Skip to content

Commit 34a3001

Browse files
fix(gmail): prevent duplicate watch renewals during stalls
1 parent df72216 commit 34a3001

4 files changed

Lines changed: 156 additions & 16 deletions

File tree

‎src/hooks/gmail-ops.test.ts‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ vi.mock("../infra/executable-path.js", () => ({
5555

5656
const { runGmailService } = await import("./gmail-ops.js");
5757

58-
function createGmailConfig(account = "[email protected]") {
58+
function createGmailConfig(account = "[email protected]", renewEveryMinutes?: number) {
5959
return {
6060
hooks: {
6161
enabled: true,
@@ -65,6 +65,7 @@ function createGmailConfig(account = "[email protected]") {
6565
topic: "projects/demo/topics/gmail",
6666
pushToken: "push-token",
6767
tailscale: { mode: "off" as const },
68+
renewEveryMinutes,
6869
},
6970
},
7071
};
@@ -115,4 +116,43 @@ describe("runGmailService", () => {
115116
shutdown?.();
116117
}
117118
});
119+
120+
it("keeps a stalled foreground renewal single-flight", async () => {
121+
vi.useFakeTimers();
122+
let resolveRenewal!: (value: { code: number; stdout: string; stderr: string }) => void;
123+
const renewal = new Promise<{ code: number; stdout: string; stderr: string }>((resolve) => {
124+
resolveRenewal = resolve;
125+
});
126+
mocks.getRuntimeConfig.mockReturnValue(createGmailConfig("[email protected]", 1));
127+
mocks.runCommandWithTimeout
128+
.mockResolvedValueOnce({ code: 0, stdout: "", stderr: "" })
129+
.mockImplementation(async () => await renewal);
130+
131+
const child = new EventEmitter();
132+
const kill = vi.fn(() => {
133+
child.emit("exit", null, "SIGTERM");
134+
return true;
135+
});
136+
mocks.spawn.mockReturnValue(Object.assign(child, { kill, killed: false }));
137+
138+
const existingSigintListeners = new Set(process.rawListeners("SIGINT"));
139+
let shutdown: (() => void) | undefined;
140+
try {
141+
await runGmailService({});
142+
shutdown = process
143+
.rawListeners("SIGINT")
144+
.find((listener) => !existingSigintListeners.has(listener)) as (() => void) | undefined;
145+
146+
await vi.advanceTimersByTimeAsync(60_000);
147+
expect(mocks.runCommandWithTimeout).toHaveBeenCalledTimes(2);
148+
await vi.advanceTimersByTimeAsync(60_000);
149+
const callsWhileStalled = mocks.runCommandWithTimeout.mock.calls.length;
150+
resolveRenewal({ code: 0, stdout: "", stderr: "" });
151+
await Promise.resolve();
152+
153+
expect(callsWhileStalled).toBe(2);
154+
} finally {
155+
shutdown?.();
156+
}
157+
});
118158
});

‎src/hooks/gmail-ops.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -321,10 +321,21 @@ export async function runGmailService(opts: GmailRunOptions) {
321321
let child = spawnGogServe(runtimeConfig);
322322

323323
const renewMs = runtimeConfig.renewEveryMinutes * 60_000;
324+
let renewalInFlight: Promise<void> | null = null;
324325
const renewTimer = setInterval(() => {
325-
void startGmailWatch(runtimeConfig).catch((err: unknown) => {
326-
defaultRuntime.error(`gmail watch renew failed: ${String(err)}`);
327-
});
326+
if (shuttingDown || renewalInFlight) {
327+
return;
328+
}
329+
const renewal = startGmailWatch(runtimeConfig)
330+
.catch((err: unknown) => {
331+
defaultRuntime.error(`gmail watch renew failed: ${String(err)}`);
332+
})
333+
.finally(() => {
334+
if (renewalInFlight === renewal) {
335+
renewalInFlight = null;
336+
}
337+
});
338+
renewalInFlight = renewal;
328339
}, renewMs);
329340

330341
const detachSignals = () => {

‎src/hooks/gmail-watcher.test.ts‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ vi.mock("../process/exec.js", () => ({
3232

3333
const { startGmailWatcher, stopGmailWatcher } = await import("./gmail-watcher.js");
3434

35-
function createGmailConfig(account = "[email protected]") {
35+
function createGmailConfig(account = "[email protected]", renewEveryMinutes?: number) {
3636
return {
3737
hooks: {
3838
enabled: true,
@@ -41,6 +41,7 @@ function createGmailConfig(account = "[email protected]") {
4141
account,
4242
topic: "projects/demo/topics/gmail",
4343
pushToken: "push-token",
44+
renewEveryMinutes,
4445
},
4546
},
4647
} as never;
@@ -282,6 +283,65 @@ describe("startGmailWatcher", () => {
282283
}
283284
});
284285

286+
it("keeps a stalled periodic renewal single-flight", async () => {
287+
vi.useFakeTimers();
288+
try {
289+
const renewal = deferredCommandResult();
290+
mocks.runCommandWithTimeout
291+
.mockResolvedValueOnce({ code: 0, stdout: "", stderr: "" })
292+
.mockImplementation(async () => await renewal.promise);
293+
294+
await startGmailWatcher(createGmailConfig("[email protected]", 1));
295+
await vi.advanceTimersByTimeAsync(60_000);
296+
expect(mocks.runCommandWithTimeout).toHaveBeenCalledTimes(2);
297+
298+
await vi.advanceTimersByTimeAsync(60_000);
299+
const callsWhileStalled = mocks.runCommandWithTimeout.mock.calls.length;
300+
renewal.resolve({ code: 0, stdout: "", stderr: "" });
301+
await Promise.resolve();
302+
303+
expect(callsWhileStalled).toBe(2);
304+
} finally {
305+
vi.useRealTimers();
306+
}
307+
});
308+
309+
it("does not let a stalled renewal survive stop and suppress a replacement watcher", async () => {
310+
vi.useFakeTimers();
311+
try {
312+
let stalledSignal: AbortSignal | undefined;
313+
mocks.runCommandWithTimeout
314+
.mockResolvedValueOnce({ code: 0, stdout: "", stderr: "" })
315+
.mockImplementationOnce(
316+
async (_args, options: { signal?: AbortSignal }) =>
317+
await new Promise<{ code: number; stdout: string; stderr: string }>((resolve) => {
318+
stalledSignal = options.signal;
319+
options.signal?.addEventListener(
320+
"abort",
321+
() => resolve({ code: 1, stdout: "", stderr: "aborted" }),
322+
{ once: true },
323+
);
324+
}),
325+
)
326+
.mockResolvedValue({ code: 0, stdout: "", stderr: "" });
327+
328+
await startGmailWatcher(createGmailConfig("[email protected]", 1));
329+
await vi.advanceTimersByTimeAsync(60_000);
330+
expect(stalledSignal?.aborted).toBe(false);
331+
332+
await stopGmailWatcher();
333+
expect(stalledSignal?.aborted).toBe(true);
334+
335+
await startGmailWatcher(createGmailConfig("[email protected]", 1));
336+
await vi.advanceTimersByTimeAsync(60_000);
337+
338+
expect(mocks.runCommandWithTimeout).toHaveBeenCalledTimes(4);
339+
expect(mocks.runCommandWithTimeout.mock.calls[3]?.[0]).toContain("[email protected]");
340+
} finally {
341+
vi.useRealTimers();
342+
}
343+
});
344+
285345
it("escalates to SIGKILL and resolves on final timeout when process ignores signals", async () => {
286346
vi.useFakeTimers();
287347
try {

‎src/hooks/gmail-watcher.ts‎

Lines changed: 40 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@ const log = createSubsystemLogger("gmail-watcher");
2626

2727
let watcherProcess: ChildProcess | null = null;
2828
let renewInterval: ReturnType<typeof setInterval> | null = null;
29+
let renewalInFlight: Promise<boolean> | null = null;
30+
let renewalAbortController: AbortController | null = null;
2931
let shuttingDown = false;
3032
let currentConfig: GmailHookRuntimeConfig | null = null;
3133
let respawnTimeout: ReturnType<typeof setTimeout> | null = null;
@@ -177,6 +179,29 @@ function settleProcess(proc: ChildProcess): Promise<void> {
177179
});
178180
}
179181

182+
async function stopPeriodicRenewal(): Promise<void> {
183+
if (renewInterval) {
184+
clearInterval(renewInterval);
185+
renewInterval = null;
186+
}
187+
188+
const renewal = renewalInFlight;
189+
const controller = renewalAbortController;
190+
if (!renewal) {
191+
renewalAbortController = null;
192+
return;
193+
}
194+
195+
controller?.abort();
196+
await renewal;
197+
if (renewalInFlight === renewal) {
198+
renewalInFlight = null;
199+
}
200+
if (renewalAbortController === controller) {
201+
renewalAbortController = null;
202+
}
203+
}
204+
180205
type GmailWatcherStartResult = {
181206
started: boolean;
182207
reason?: string;
@@ -291,16 +316,13 @@ export async function startGmailWatcher(
291316
// does not orphan the old serve process or leave a dangling timer.
292317
// This must run before Tailscale/watch-start to prevent the old
293318
// process from exiting and queuing a respawn during async work.
294-
if (watcherProcess || renewInterval || respawnTimeout) {
319+
if (watcherProcess || renewInterval || renewalInFlight || respawnTimeout) {
295320
shuttingDown = true;
296321
if (respawnTimeout) {
297322
clearTimeout(respawnTimeout);
298323
respawnTimeout = null;
299324
}
300-
if (renewInterval) {
301-
clearInterval(renewInterval);
302-
renewInterval = null;
303-
}
325+
await stopPeriodicRenewal();
304326
if (watcherProcess) {
305327
const oldProcess = watcherProcess;
306328
watcherProcess = null;
@@ -363,10 +385,20 @@ export async function startGmailWatcher(
363385
watcherProcess = spawnGogServe(runtimeConfig);
364386
const renewMs = runtimeConfig.renewEveryMinutes * 60_000;
365387
renewInterval = setInterval(() => {
366-
if (shuttingDown) {
388+
if (shuttingDown || renewalInFlight) {
367389
return;
368390
}
369-
void startGmailWatch(runtimeConfig);
391+
const controller = new AbortController();
392+
renewalAbortController = controller;
393+
const renewal = startGmailWatch(runtimeConfig, { signal: controller.signal }).finally(() => {
394+
if (renewalInFlight === renewal) {
395+
renewalInFlight = null;
396+
}
397+
if (renewalAbortController === controller) {
398+
renewalAbortController = null;
399+
}
400+
});
401+
renewalInFlight = renewal;
370402
}, renewMs);
371403

372404
log.info(
@@ -386,10 +418,7 @@ export async function stopGmailWatcher(): Promise<void> {
386418
clearTimeout(respawnTimeout);
387419
respawnTimeout = null;
388420
}
389-
if (renewInterval) {
390-
clearInterval(renewInterval);
391-
renewInterval = null;
392-
}
421+
await stopPeriodicRenewal();
393422

394423
if (watcherProcess) {
395424
log.info("stopping gmail watcher");

0 commit comments

Comments
 (0)