Skip to content

Commit 2a69cc7

Browse files
KrisBraunclaude
andcommitted
connector-outlook-calendar: defer onChannelEnabled into queued task
Address two issues from review of 830c90f: 1. Lock acquisition moved out of the HTTP-response path. Previously onChannelEnabled acquired the sync lock synchronously, so if the queued syncOutlookBatch was dropped the lock was held by nothing for up to 2h. Mirror google-calendar's initCalendar pattern: thin onChannelEnabled queues initCalendar; initCalendar acquires the lock, sets up the watch, initializes sync state, and queues the first batch — all inside the task runtime. 2. Recovery clear narrowed to what google does synchronously (clear + release stale lock) and the rest moved into initCalendar so it can't race a still-running prior batch. Also: name two magic constants (RENEWAL_LEAD_MS, SUBSCRIPTION_DURATION_DAYS), extract tryGetApi helper to dedupe the four call sites of "get token or warn and bail", sharpen one stale comment. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 830c90f commit 2a69cc7

1 file changed

Lines changed: 100 additions & 58 deletions

File tree

‎connectors/outlook-calendar/src/outlook-calendar.ts‎

Lines changed: 100 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,15 @@ export class OutlookCalendar extends Connector<OutlookCalendar> {
152152
// no stuck-sync recovery is needed.
153153
private static readonly SYNC_LOCK_TTL_MS = 2 * 60 * 60 * 1000;
154154

155+
// Renew subscription this far before expiry. MS Graph caps calendar
156+
// subscriptions at ~3 days; without renewal every connection's webhook
157+
// silently dies after 72 hours.
158+
private static readonly RENEWAL_LEAD_MS = 24 * 60 * 60 * 1000;
159+
160+
// Maximum subscription lifetime allowed by MS Graph for calendar
161+
// resources. Used when creating/renewing subscriptions.
162+
private static readonly SUBSCRIPTION_DURATION_DAYS = 3;
163+
155164
/**
156165
* Returns available Outlook calendars as channel resources.
157166
*/
@@ -176,14 +185,18 @@ export class OutlookCalendar extends Connector<OutlookCalendar> {
176185
* previously-broken connection. Drop the persisted delta token and
177186
* sync lock so the next pass re-walks history and picks up events
178187
* that changed during the auth gap.
188+
*
189+
* Keep this method thin: it must return quickly so the HTTP response
190+
* boundary doesn't hold the sync lock. All real init work (lock,
191+
* webhook setup, sync state, first batch) is deferred to initCalendar
192+
* which runs inside a queued task.
179193
*/
180194
async onChannelEnabled(channel: Channel, context?: SyncContext): Promise<void> {
181195
if (context?.recovering) {
182196
// Wipe persisted sync state (including the Graph delta token in
183-
// `state.state`) so the next pass re-walks history. The lock is
184-
// owned by the framework now and self-expires; we explicitly
185-
// release here so a stale lock from the pre-recovery sync doesn't
186-
// block this pass.
197+
// `state.state`) so the next pass re-walks history. Clearing is
198+
// idempotent and cheap. Release any TTL-stuck lock from the
199+
// pre-recovery outage so initCalendar can acquire fresh.
187200
await this.clear(`outlook_sync_state_${channel.id}`);
188201
await this.tools.store.releaseLock(`sync_${channel.id}`);
189202
} else if (context?.syncHistoryMin) {
@@ -200,40 +213,60 @@ export class OutlookCalendar extends Connector<OutlookCalendar> {
200213

201214
await this.set(`sync_enabled_${channel.id}`, true);
202215

216+
// Queue all initialization as a task to avoid blocking the HTTP
217+
// response. initCalendar acquires the sync lock, sets up the webhook,
218+
// initializes sync state, and starts the first batch.
219+
const initCallback = await this.callback(this.initCalendar, channel.id);
220+
await this.runTask(initCallback);
221+
}
222+
223+
/**
224+
* Initializes an Outlook calendar channel: acquires the sync lock, sets
225+
* up the webhook subscription, initializes sync state, and queues the
226+
* first sync batch. Runs as a queued task so the lock acquisition
227+
* doesn't straddle the HTTP-response boundary (where a dropped task
228+
* could leave the lock held until the TTL expires).
229+
*/
230+
async initCalendar(calendarId: string): Promise<void> {
231+
// Auth-token presence check up front: getApi() throws if the token
232+
// was cleared, and as a queued task that throw becomes a retry loop.
233+
// Skip cleanly instead.
234+
const api = await this.tryGetApi(calendarId, "initCalendar");
235+
if (!api) {
236+
return;
237+
}
238+
203239
// Acquire sync lock. Self-expires after SYNC_LOCK_TTL_MS so a crashed
204240
// worker can't wedge sync forever. Bails if another sync is in flight.
205241
const acquired = await this.tools.store.acquireLock(
206-
`sync_${channel.id}`,
242+
`sync_${calendarId}`,
207243
OutlookCalendar.SYNC_LOCK_TTL_MS
208244
);
209245
if (!acquired) {
210246
return;
211247
}
212248

249+
// Setup webhook for this calendar
250+
await this.setupOutlookWatch(calendarId);
251+
213252
// Determine default sync range (2 years into the past)
214253
const now = new Date();
215254
const min = new Date(now.getFullYear() - 2, 0, 1);
216255

217-
await this.set(`outlook_sync_state_${channel.id}`, {
218-
calendarId: channel.id,
256+
await this.set(`outlook_sync_state_${calendarId}`, {
257+
calendarId,
219258
min,
220259
sequence: 1,
221260
} as SyncState);
222261

262+
// Start first sync batch
223263
const syncCallback = await this.callback(
224264
this.syncOutlookBatch,
225-
channel.id,
265+
calendarId,
226266
true, // initialSync
227267
1 // batchNumber
228268
);
229269
await this.runTask(syncCallback);
230-
231-
// Queue webhook setup as a separate task to avoid blocking the HTTP response
232-
const webhookCallback = await this.callback(
233-
this.setupOutlookWatch,
234-
channel.id
235-
);
236-
await this.runTask(webhookCallback);
237270
}
238271

239272
/**
@@ -253,6 +286,27 @@ export class OutlookCalendar extends Connector<OutlookCalendar> {
253286
return new GraphApi(token.token);
254287
}
255288

289+
/**
290+
* Non-throwing variant of getApi(): logs a warning and returns null
291+
* when the auth token is missing. Used by queued tasks so a cleared
292+
* token doesn't turn into an infinite retry loop. Callers remain
293+
* responsible for releasing any held lock and clearing sync state on
294+
* null (cleanup varies per call site).
295+
*/
296+
private async tryGetApi(
297+
calendarId: string,
298+
label: string
299+
): Promise<GraphApi | null> {
300+
const token = await this.tools.integrations.get(calendarId);
301+
if (!token) {
302+
console.warn(
303+
`Auth token missing for calendar ${calendarId} during ${label}, skipping`
304+
);
305+
return null;
306+
}
307+
return new GraphApi(token.token);
308+
}
309+
256310
private async getUserEmail(calendarId: string): Promise<string> {
257311
const api = await this.getApi(calendarId);
258312
const data = (await api.call(
@@ -383,12 +437,14 @@ export class OutlookCalendar extends Connector<OutlookCalendar> {
383437
return;
384438
}
385439

386-
// Calculate renewal time: 24 hours before expiry
440+
// Calculate renewal time: RENEWAL_LEAD_MS before expiry
387441
const expiry =
388442
watchData.expiry instanceof Date
389443
? watchData.expiry
390444
: new Date(watchData.expiry);
391-
const renewalTime = new Date(expiry.getTime() - 24 * 60 * 60 * 1000);
445+
const renewalTime = new Date(
446+
expiry.getTime() - OutlookCalendar.RENEWAL_LEAD_MS
447+
);
392448

393449
// Don't schedule if already past renewal time (edge case)
394450
if (renewalTime <= new Date()) {
@@ -432,22 +488,18 @@ export class OutlookCalendar extends Connector<OutlookCalendar> {
432488
return;
433489
}
434490

435-
// Guard auth token before calling getApi() — same retry-loop concern
436-
// as syncOutlookBatch/initCalendar.
437-
const token = await this.tools.integrations.get(calendarId);
438-
if (!token) {
439-
console.warn(
440-
`Auth token missing for calendar ${calendarId} during renewal, skipping`
441-
);
491+
const api = await this.tryGetApi(calendarId, "renewOutlookWatch");
492+
if (!api) {
442493
return;
443494
}
444-
const api = new GraphApi(token.token);
445495

446496
// PATCH the subscription to extend the expiry. Keeps the
447497
// subscription id stable, so we don't have to re-create the watch
448498
// state or invalidate any client validation that already happened.
449499
const newExpiry = new Date();
450-
newExpiry.setDate(newExpiry.getDate() + 3);
500+
newExpiry.setDate(
501+
newExpiry.getDate() + OutlookCalendar.SUBSCRIPTION_DURATION_DAYS
502+
);
451503

452504
try {
453505
await api.renewSubscription(oldWatchData.subscriptionId, newExpiry);
@@ -486,18 +538,13 @@ export class OutlookCalendar extends Connector<OutlookCalendar> {
486538
}
487539

488540
async setupOutlookWatch(calendarId: string): Promise<void> {
489-
// Auth-token presence check up front: getApi() throws "No Microsoft
490-
// authentication token available" if the token was cleared. As a
491-
// queued task, that throw makes the runtime retry forever and floods
492-
// error tracking. Skip cleanly instead.
493-
const token = await this.tools.integrations.get(calendarId);
494-
if (!token) {
495-
console.warn(
496-
`Auth token missing for calendar ${calendarId} during setupOutlookWatch, skipping`
497-
);
541+
// Auth-token presence check up front: getApi() throws if the token
542+
// was cleared, and as a queued task that throw becomes a retry loop.
543+
// Skip cleanly instead.
544+
const api = await this.tryGetApi(calendarId, "setupOutlookWatch");
545+
if (!api) {
498546
return;
499547
}
500-
const api = new GraphApi(token.token);
501548

502549
// Microsoft Graph validates subscription endpoints by POSTing with a
503550
// `validationToken` query parameter and expects the token echoed back
@@ -515,9 +562,12 @@ export class OutlookCalendar extends Connector<OutlookCalendar> {
515562
return;
516563
}
517564

518-
// Microsoft Graph subscriptions expire, so we set expiry for 3 days from now
565+
// Microsoft Graph subscriptions expire — set expiry to the maximum
566+
// allowed lifetime for calendar resources.
519567
const expirationDate = new Date();
520-
expirationDate.setDate(expirationDate.getDate() + 3);
568+
expirationDate.setDate(
569+
expirationDate.getDate() + OutlookCalendar.SUBSCRIPTION_DURATION_DAYS
570+
);
521571

522572
try {
523573
const subscription = await api.createSubscription(
@@ -550,16 +600,14 @@ export class OutlookCalendar extends Connector<OutlookCalendar> {
550600
batchNumber: number = 1
551601
): Promise<void> {
552602
try {
553-
// Auth-token presence check must run before ensureUserIdentity (which
554-
// calls getApi() and throws if the token was cleared). As a queued
555-
// task, that throw makes the runtime retry forever and floods error
556-
// tracking. Release any held lock and clear sync state so the next
557-
// re-auth can start fresh.
558-
const token = await this.tools.integrations.get(calendarId);
559-
if (!token) {
560-
console.warn(
561-
`Auth token missing for calendar ${calendarId} at batch ${batchNumber}, skipping`
562-
);
603+
// Auth-token presence check up front: getApi() throws if the token
604+
// was cleared, and as a queued task that throw becomes a retry loop.
605+
// Skip cleanly instead.
606+
const api = await this.tryGetApi(
607+
calendarId,
608+
`syncOutlookBatch (batch ${batchNumber})`
609+
);
610+
if (!api) {
563611
await this.clear(`outlook_sync_state_${calendarId}`);
564612
await this.tools.store.releaseLock(`sync_${calendarId}`);
565613
return;
@@ -580,8 +628,6 @@ export class OutlookCalendar extends Connector<OutlookCalendar> {
580628
sequence: 1,
581629
};
582630

583-
const api = new GraphApi(token.token);
584-
585631
// Process ONE batch (single API page) instead of while loop
586632
const result = await syncOutlookCalendar(api, calendarId, syncState);
587633

@@ -1007,9 +1053,8 @@ export class OutlookCalendar extends Connector<OutlookCalendar> {
10071053
watchData.expiry instanceof Date
10081054
? watchData.expiry
10091055
: new Date(watchData.expiry);
1010-
const hoursUntilExpiry =
1011-
(expiry.getTime() - Date.now()) / (1000 * 60 * 60);
1012-
if (hoursUntilExpiry < 24) {
1056+
const msUntilExpiry = expiry.getTime() - Date.now();
1057+
if (msUntilExpiry < OutlookCalendar.RENEWAL_LEAD_MS) {
10131058
this.renewOutlookWatch(calendarId).catch((error) => {
10141059
console.error(
10151060
`Failed to reactively renew Outlook subscription for ${calendarId}:`,
@@ -1041,11 +1086,8 @@ export class OutlookCalendar extends Connector<OutlookCalendar> {
10411086

10421087
// Auth-token presence check up front — same retry-loop concern as
10431088
// syncOutlookBatch. Release the lock if we bail.
1044-
const token = await this.tools.integrations.get(calendarId);
1045-
if (!token) {
1046-
console.warn(
1047-
`Auth token missing for calendar ${calendarId} during startIncrementalSync, skipping`
1048-
);
1089+
const api = await this.tryGetApi(calendarId, "startIncrementalSync");
1090+
if (!api) {
10491091
await this.tools.store.releaseLock(`sync_${calendarId}`);
10501092
return;
10511093
}

0 commit comments

Comments
 (0)