diff --git a/projects/start-sdk/changelog/patch-fixed-filehelper-watch-backoff.md b/projects/start-sdk/changelog/patch-fixed-filehelper-watch-backoff.md new file mode 100644 index 0000000000..01534abac1 --- /dev/null +++ b/projects/start-sdk/changelog/patch-fixed-filehelper-watch-backoff.md @@ -0,0 +1,5 @@ +--- +release-notes: false +--- + +- Back off `FileHelper` file-watch retries when watching fails repeatedly. diff --git a/projects/start-sdk/lib/mainFn/Daemon.ts b/projects/start-sdk/lib/mainFn/Daemon.ts index 202dc95d2e..303e794d18 100644 --- a/projects/start-sdk/lib/mainFn/Daemon.ts +++ b/projects/start-sdk/lib/mainFn/Daemon.ts @@ -2,6 +2,7 @@ import * as T from '@start9labs/start-core/types' import { asError } from '@start9labs/start-core/util/asError' import { logErrorOnce } from '@start9labs/start-core/util/logErrorOnce' import { Drop } from '../util' +import { delay } from '../util/delay' import { SubContainer } from '../util/SubContainer' import { CommandController } from './CommandController' import { DaemonCommandType } from './Daemons' @@ -14,12 +15,13 @@ const MAX_TIMEOUT_MS = 30000 * A managed long-running process wrapper around {@link CommandController}. * * When started, the daemon automatically restarts its underlying command on - * failure with exponential backoff (up to 30 seconds). While the daemon is - * running, it holds a use-token (`subcontainer.hold()`) on its SubContainer - * so the container is not destroyed out from under it. There are two ways to - * bring it down: {@link stop} releases the hold but leaves the SubContainer - * intact so a later {@link start} can resume in it (a restartable pause); - * {@link term} additionally destroys the SubContainer (genuine teardown). + * failure, waiting one second longer after each failure (up to 30 seconds). + * While the daemon is running, it holds a use-token (`subcontainer.hold()`) + * on its SubContainer so the container is not destroyed out from under it. + * There are two ways to bring it down: {@link stop} releases the hold but + * leaves the SubContainer intact so a later {@link start} can resume in it + * (a restartable pause); {@link term} additionally destroys the SubContainer + * (genuine teardown). * * @typeParam Manifest - The service manifest type * @typeParam C - The subcontainer type, or `null` for JS-only daemons @@ -178,15 +180,7 @@ export class Daemon< if (!signal.aborted) logErrorOnce(e) } if (signal.aborted) break - await new Promise(resolve => { - const wake = () => { - clearTimeout(timer) - signal.removeEventListener('abort', wake) - resolve() - } - const timer = setTimeout(wake, timeoutCounter) - signal.addEventListener('abort', wake) - }) + await delay(timeoutCounter, { signal }) timeoutCounter += TIMEOUT_INCREMENT_MS timeoutCounter = Math.min(MAX_TIMEOUT_MS, timeoutCounter) } diff --git a/projects/start-sdk/lib/test/Daemons.test.ts b/projects/start-sdk/lib/test/Daemons.test.ts index c66d21bb29..5090ddad9e 100644 --- a/projects/start-sdk/lib/test/Daemons.test.ts +++ b/projects/start-sdk/lib/test/Daemons.test.ts @@ -38,6 +38,7 @@ const bareEager = (destroyFs: () => Promise) => destroyRequested: false, holdCount: 0, teardown: null, + releaseContextCleanup: () => {}, fileMounts: new FileMounts(), leaderExited: true, guid: 'guid', diff --git a/projects/start-sdk/lib/test/delay.test.ts b/projects/start-sdk/lib/test/delay.test.ts new file mode 100644 index 0000000000..0a9b8a8d51 --- /dev/null +++ b/projects/start-sdk/lib/test/delay.test.ts @@ -0,0 +1,70 @@ +import { delay, ExponentialBackoff } from '../util/delay' + +const MAX_TIMEOUT_MS = 2 ** 31 - 1 + +describe('delay', () => { + beforeEach(() => jest.useFakeTimers()) + afterEach(() => jest.useRealTimers()) + + const settledBy = async (pending: Promise, ms: number) => { + let settled = false + pending.then(() => (settled = true)) + await jest.advanceTimersByTimeAsync(ms) + return settled + } + + it('resolves at once when already aborted', async () => { + const ctrl = new AbortController() + ctrl.abort() + const pending = delay(Infinity, { signal: ctrl.signal }) + expect(await settledBy(pending, 0)).toBe(true) + expect(jest.getTimerCount()).toBe(0) + }) + + it('resolves on abort and clears its timer', async () => { + const ctrl = new AbortController() + const pending = delay(MAX_TIMEOUT_MS + 1_000, { signal: ctrl.signal }) + expect(await settledBy(pending, MAX_TIMEOUT_MS)).toBe(false) + ctrl.abort() + expect(await settledBy(pending, 0)).toBe(true) + expect(jest.getTimerCount()).toBe(0) + }) + + it('resolves an infinite delay on abort', async () => { + const ctrl = new AbortController() + const pending = delay(Infinity, { signal: ctrl.signal }) + expect(await settledBy(pending, MAX_TIMEOUT_MS)).toBe(false) + ctrl.abort() + expect(await settledBy(pending, 0)).toBe(true) + }) +}) + +describe('delay timer ref', () => { + afterEach(() => jest.restoreAllMocks()) + + it('holds the event loop unless ref is false', async () => { + const timers = jest.spyOn(globalThis, 'setTimeout') + const ctrl = new AbortController() + const pending = [ + delay(60_000, { signal: ctrl.signal }), + delay(60_000, { signal: ctrl.signal, ref: false }), + ] + const refs = timers.mock.results.map(r => + (r.value as NodeJS.Timeout).hasRef(), + ) + ctrl.abort() + await Promise.all(pending) + expect(refs).toEqual([true, false]) + }) +}) + +describe('ExponentialBackoff', () => { + it('doubles up to the cap and restarts after reset', () => { + const backoff = new ExponentialBackoff(100, 500) + expect([1, 2, 3, 4, 5].map(() => backoff.next())).toEqual([ + 100, 200, 400, 500, 500, + ]) + backoff.reset() + expect(backoff.next()).toBe(100) + }) +}) diff --git a/projects/start-sdk/lib/test/fileHelper.watch.test.ts b/projects/start-sdk/lib/test/fileHelper.watch.test.ts index 00801cdf3b..53348b8c54 100644 --- a/projects/start-sdk/lib/test/fileHelper.watch.test.ts +++ b/projects/start-sdk/lib/test/fileHelper.watch.test.ts @@ -4,9 +4,13 @@ import { tmpdir } from 'node:os' import { dirname, join } from 'node:path' import { Effects } from '@start9labs/start-core/Effects' import { AbortedError } from '@start9labs/start-core/util/AbortedError' +import * as z from '@start9labs/start-core/z' import { FileHelper } from '../util/fileHelper' -const effects = { isInContext: true } as Effects +const effects = { + isInContext: true, + onLeaveContext: (_fn: () => void | null | undefined) => {}, +} as Effects const realWatch = fs.watch const observeWatch = () => { @@ -174,3 +178,417 @@ describe('FileHelper.watch', () => { } }) }) + +describe('FileHelper watch retry backoff', () => { + const BACKOFF_SCHEDULE = [ + 100, 200, 400, 800, 1600, 3200, 6400, 12800, 25600, 30000, 30000, + ] + + const makeEmfile = (target: unknown) => + Object.assign(new Error(`EMFILE: too many open files, watch '${target}'`), { + code: 'EMFILE', + }) + + const makeFailingWatchIterator = ( + target: unknown, + signal?: AbortSignal, + ): AsyncIterableIterator> => ({ + [Symbol.asyncIterator]() { + return this + }, + next() { + if (signal?.aborted) { + const err = new Error('The operation was aborted') + err.name = 'AbortError' + return Promise.reject(err) + } + return Promise.reject(makeEmfile(target)) + }, + return() { + return Promise.resolve({ value: undefined, done: true }) + }, + }) + + const mockFailingWatch = ( + override?: ( + call: number, + target: unknown, + signal?: AbortSignal, + ) => AsyncIterableIterator> | undefined, + ) => { + let calls = 0 + return jest.spyOn(fs, 'watch').mockImplementation(((target, options) => { + calls += 1 + const signal = (options as WatchOptions | undefined)?.signal + return ( + override?.(calls, target, signal) ?? + makeFailingWatchIterator(target, signal) + ) + }) as typeof fs.watch) + } + + const createErrorTracker = () => { + const waiters = new Map void>() + const spy = jest.spyOn(console, 'error').mockImplementation(() => { + const count = spy.mock.calls.length + const resolve = waiters.get(count) + if (resolve) { + waiters.delete(count) + resolve() + } + }) + const waitForErrors = (count: number) => + spy.mock.calls.length >= count + ? Promise.resolve() + : new Promise(resolve => waiters.set(count, resolve)) + return { spy, waitForErrors } + } + + const flushImmediate = () => + new Promise(resolve => setImmediate(resolve)) + + afterEach(() => { + jest.useRealTimers() + jest.restoreAllMocks() + }) + + test.each([ + { name: 'existing file', exists: true }, + { name: 'missing file (onCreated)', exists: false }, + ])( + 'backs off exponentially up to 30s on persistent EMFILE ($name)', + async ({ exists }) => { + const dir = await fs.mkdtemp(join(tmpdir(), 'file-backoff-')) + const path = join(dir, 'config.txt') + if (exists) await fs.writeFile(path, 'initial') + + jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] }) + const { spy: errorSpy, waitForErrors } = createErrorTracker() + const watchSpy = mockFailingWatch() + + const abort = new AbortController() + const wait = FileHelper.string(path) + .read() + .waitFor(effects, value => value === 'updated', abort.signal) + + try { + await waitForErrors(1) + await flushImmediate() + expect(watchSpy).toHaveBeenCalledTimes(1) + expect(errorSpy).toHaveBeenCalledTimes(1) + expect(jest.getTimerCount()).toBe(1) + + for (let i = 0; i < BACKOFF_SCHEDULE.length; i++) { + const delay = BACKOFF_SCHEDULE[i] + const expectedBefore = i + 1 + await jest.advanceTimersByTimeAsync(delay - 1) + await flushImmediate() + expect(jest.getTimerCount()).toBe(1) + expect(watchSpy).toHaveBeenCalledTimes(expectedBefore) + expect(errorSpy).toHaveBeenCalledTimes(expectedBefore) + + await jest.advanceTimersByTimeAsync(1) + expect(jest.getTimerCount()).toBe(0) + await waitForErrors(expectedBefore + 1) + await flushImmediate() + expect(watchSpy).toHaveBeenCalledTimes(expectedBefore + 1) + expect(errorSpy).toHaveBeenCalledTimes(expectedBefore + 1) + expect(jest.getTimerCount()).toBe(1) + } + } finally { + abort.abort() + await wait.catch(() => {}) + await fs.rm(dir, { recursive: true, force: true }) + } + }, + ) + + test.each([ + { name: 'existing file change', exists: true }, + { name: 'missing file (onCreated)', exists: false }, + ])('resets backoff to 100ms after recovery ($name)', async ({ exists }) => { + const dir = await fs.mkdtemp(join(tmpdir(), 'file-backoff-reset-')) + const path = join(dir, 'config.txt') + if (exists) await fs.writeFile(path, 'v1') + + jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] }) + const { spy: errorSpy, waitForErrors } = createErrorTracker() + + let deliverEvent!: () => void + let watchReady!: () => void + const thirdWatchReady = new Promise(resolve => (watchReady = resolve)) + + const watchSpy = mockFailingWatch(call => { + if (call !== 3) return undefined + return { + [Symbol.asyncIterator]() { + return this + }, + next() { + watchReady() + return new Promise>>( + resolve => { + deliverEvent = () => + resolve({ + value: { + eventType: exists ? 'change' : 'rename', + filename: 'config.txt', + }, + done: false, + }) + }, + ) + }, + return() { + return Promise.resolve({ value: undefined, done: true }) + }, + } + }) + + const abort = new AbortController() + const gen = FileHelper.string(path).read().watch(effects, abort.signal) + let pendingNext: Promise | undefined + + try { + expect((await gen.next()).value).toBe(exists ? 'v1' : null) + const nextRead = gen.next() + pendingNext = nextRead + + await waitForErrors(1) + await flushImmediate() + expect(jest.getTimerCount()).toBe(1) + await jest.advanceTimersByTimeAsync(100) + await waitForErrors(2) + await flushImmediate() + expect(jest.getTimerCount()).toBe(1) + + await jest.advanceTimersByTimeAsync(200) + await thirdWatchReady + await flushImmediate() + await fs.writeFile(path, 'v2') + deliverEvent() + + expect((await nextRead).value).toBe('v2') + const afterReset = gen.next() + pendingNext = afterReset + + await waitForErrors(3) + await flushImmediate() + expect(watchSpy).toHaveBeenCalledTimes(4) + expect(jest.getTimerCount()).toBe(1) + + await jest.advanceTimersByTimeAsync(99) + await flushImmediate() + expect(jest.getTimerCount()).toBe(1) + expect(watchSpy).toHaveBeenCalledTimes(4) + + await jest.advanceTimersByTimeAsync(1) + expect(jest.getTimerCount()).toBe(0) + await waitForErrors(4) + await flushImmediate() + expect(watchSpy).toHaveBeenCalledTimes(5) + expect(errorSpy).toHaveBeenCalledTimes(4) + + abort.abort() + await expect(afterReset).rejects.toThrow(AbortedError) + } finally { + abort.abort() + await pendingNext?.catch(() => {}) + await gen.return(undefined as never).catch(() => {}) + await fs.rm(dir, { recursive: true, force: true }) + } + }) + + test('aborts waitFor and watch immediately during backoff sleep without logging AbortError', async () => { + const dir = await fs.mkdtemp(join(tmpdir(), 'file-backoff-abort-')) + const path = join(dir, 'config.txt') + await fs.writeFile(path, 'initial') + + jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] }) + const { spy: errorSpy, waitForErrors } = createErrorTracker() + mockFailingWatch() + + const waitAbort = new AbortController() + const watchAbort = new AbortController() + const wait = FileHelper.string(path) + .read() + .waitFor(effects, value => value === 'updated', waitAbort.signal) + const gen = FileHelper.string(path).read().watch(effects, watchAbort.signal) + let watchNext: Promise | undefined + + try { + expect((await gen.next()).value).toBe('initial') + watchNext = gen.next() + + await waitForErrors(2) + await flushImmediate() + expect(jest.getTimerCount()).toBe(2) + + waitAbort.abort() + watchAbort.abort() + + await expect(wait).rejects.toThrow(AbortedError) + await expect(watchNext).rejects.toThrow(AbortedError) + expect(jest.getTimerCount()).toBe(0) + expect(errorSpy).toHaveBeenCalledTimes(2) + } finally { + waitAbort.abort() + watchAbort.abort() + await wait.catch(() => {}) + await watchNext?.catch(() => {}) + await gen.return(undefined as never).catch(() => {}) + await fs.rm(dir, { recursive: true, force: true }) + } + }) + + test('backoff sleep does not keep the process alive', async () => { + const dir = await fs.mkdtemp(join(tmpdir(), 'file-backoff-ref-')) + const path = join(dir, 'config.txt') + await fs.writeFile(path, 'initial') + + const { waitForErrors } = createErrorTracker() + mockFailingWatch() + const timers = jest.spyOn(globalThis, 'setTimeout') + + const abort = new AbortController() + const wait = FileHelper.string(path) + .read() + .waitFor(effects, value => value === 'updated', abort.signal) + + try { + await waitForErrors(1) + await flushImmediate() + const retryTimers = timers.mock.calls.flatMap(([, ms], i) => + ms === BACKOFF_SCHEDULE[0] ? [timers.mock.results[i].value] : [], + ) + expect(retryTimers.map(timer => timer.hasRef())).toEqual([false]) + } finally { + abort.abort() + await wait.catch(() => {}) + await fs.rm(dir, { recursive: true, force: true }) + } + }) + + test('terminates immediately on effects.onLeaveContext during backoff sleep without accumulating listeners', async () => { + const dir = await fs.mkdtemp(join(tmpdir(), 'file-backoff-leave-')) + const path = join(dir, 'config.txt') + await fs.writeFile(path, 'initial') + + jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] }) + const { spy: errorSpy, waitForErrors } = createErrorTracker() + mockFailingWatch() + + const leaveCallbacks: (() => void | null | undefined)[] = [] + const ctxEffects = { + isInContext: true, + onLeaveContext: (fn: () => void | null | undefined) => { + leaveCallbacks.push(fn) + }, + } as Effects + + const gen = FileHelper.string(path).read().watch(ctxEffects) + let watchNext: Promise | undefined + + try { + expect((await gen.next()).value).toBe('initial') + watchNext = gen.next() + + await waitForErrors(1) + await flushImmediate() + expect(jest.getTimerCount()).toBe(1) + await jest.advanceTimersByTimeAsync(100) + await waitForErrors(2) + await flushImmediate() + + expect(leaveCallbacks).toHaveLength(1) + expect(jest.getTimerCount()).toBe(1) + + ctxEffects.isInContext = false + for (const fn of leaveCallbacks) fn() + + await expect(watchNext).rejects.toThrow(AbortedError) + expect(jest.getTimerCount()).toBe(0) + expect(errorSpy).toHaveBeenCalledTimes(2) + } finally { + ctxEffects.isInContext = false + for (const fn of leaveCallbacks) fn() + await watchNext?.catch(() => {}) + await gen.return(undefined as never).catch(() => {}) + await fs.rm(dir, { recursive: true, force: true }) + } + }) + + test('bounds context-leave registrations across completed readers', async () => { + const dir = await fs.mkdtemp(join(tmpdir(), 'file-watch-context-')) + const path = join(dir, 'config.txt') + await fs.writeFile(path, 'initial') + + const leaveCallbacks: (() => void | null | undefined)[] = [] + const ctxEffects = { + isInContext: true, + onLeaveContext: (fn: () => void | null | undefined) => { + leaveCallbacks.push(fn) + }, + } as Effects + const file = FileHelper.string(path) + let gen: AsyncGenerator | undefined + let watchNext: Promise | undefined + + try { + for (let i = 0; i < 10; i++) { + await expect(file.read().waitFor(ctxEffects, () => true)).resolves.toBe( + 'initial', + ) + gen = file.read().watch(ctxEffects) + expect((await gen.next()).value).toBe('initial') + await gen.return(undefined) + } + expect(leaveCallbacks).toHaveLength(1) + + gen = file.read().watch(ctxEffects) + expect((await gen.next()).value).toBe('initial') + watchNext = gen.next() + ctxEffects.isInContext = false + for (const fn of leaveCallbacks) fn() + await expect(watchNext).rejects.toThrow(AbortedError) + expect(leaveCallbacks).toHaveLength(1) + } finally { + ctxEffects.isInContext = false + for (const fn of leaveCallbacks) fn() + await watchNext?.catch(() => {}) + await gen?.return(undefined).catch(() => {}) + await fs.rm(dir, { recursive: true, force: true }) + } + }) + + test('propagates doRead errors without retrying with backoff', async () => { + const dir = await fs.mkdtemp(join(tmpdir(), 'file-backoff-read-err-')) + const invalidJsonPath = join(dir, 'bad.json') + const badSchemaPath = join(dir, 'schema.json') + await fs.writeFile(invalidJsonPath, '{invalid json') + await fs.writeFile(badSchemaPath, JSON.stringify({ count: 'not-a-number' })) + + const schema = z.object({ count: z.number() }) + const errorSpy = jest.spyOn(console, 'error').mockImplementation(() => {}) + const watchSpy = jest.spyOn(fs, 'watch') + + try { + await expect( + FileHelper.json(invalidJsonPath, schema) + .read() + .waitFor(effects, () => true), + ).rejects.toThrow(SyntaxError) + + await expect( + FileHelper.json(badSchemaPath, schema) + .read() + .waitFor(effects, () => true), + ).rejects.toThrow() + + expect(watchSpy).toHaveBeenCalledTimes(2) + expect(errorSpy).not.toHaveBeenCalled() + } finally { + await fs.rm(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/projects/start-sdk/lib/test/onLeaveUntil.test.ts b/projects/start-sdk/lib/test/onLeaveUntil.test.ts new file mode 100644 index 0000000000..25022e7312 --- /dev/null +++ b/projects/start-sdk/lib/test/onLeaveUntil.test.ts @@ -0,0 +1,24 @@ +import { Effects } from '@start9labs/start-core/Effects' +import { onLeaveUntil } from '../util/onLeaveUntil' + +describe('onLeaveUntil', () => { + it('arms one hook per context and runs only unreleased callbacks', () => { + const hooks: (() => void | null | undefined)[] = [] + const effects = { + isInContext: true, + onLeaveContext: (fn: () => void | null | undefined) => { + hooks.push(fn) + }, + } as Effects + const released = jest.fn() + const kept = jest.fn() + + onLeaveUntil(effects, released)() + onLeaveUntil(effects, kept) + expect(hooks).toHaveLength(1) + + for (const hook of hooks) hook() + expect(released).not.toHaveBeenCalled() + expect(kept).toHaveBeenCalledTimes(1) + }) +}) diff --git a/projects/start-sdk/lib/trigger/cooldownTrigger.ts b/projects/start-sdk/lib/trigger/cooldownTrigger.ts index 55ab48a498..a0baefae73 100644 --- a/projects/start-sdk/lib/trigger/cooldownTrigger.ts +++ b/projects/start-sdk/lib/trigger/cooldownTrigger.ts @@ -1,5 +1,5 @@ import { Trigger } from '.' -import { delay } from './delay' +import { delay } from '../util/delay' /** * A trigger that polls at a fixed interval. diff --git a/projects/start-sdk/lib/trigger/defaultTrigger.ts b/projects/start-sdk/lib/trigger/defaultTrigger.ts index 898d07781b..78872cc4ed 100644 --- a/projects/start-sdk/lib/trigger/defaultTrigger.ts +++ b/projects/start-sdk/lib/trigger/defaultTrigger.ts @@ -1,6 +1,6 @@ import { HealthStatus } from '@start9labs/start-core/types' import { Trigger } from '.' -import { delay } from './delay' +import { delay, ExponentialBackoff } from '../util/delay' const SETTLED_MS = 30_000 const PENDING: { [K in HealthStatus]?: number } = { @@ -18,18 +18,18 @@ const PENDING: { [K in HealthStatus]?: number } = { */ export const defaultTrigger: Trigger = async function* (getInput) { let succeeded = false - let loadingMs = 1_000 + const loading = new ExponentialBackoff(1_000, SETTLED_MS) while (true) { const input = getInput() succeeded ||= input.lastResult === 'success' const backoff = !succeeded && (input.lastResult === 'loading' || input.lastWaiting) + if (!backoff) loading.reset() const ms = backoff - ? loadingMs + ? loading.next() : input.lastWaiting ? SETTLED_MS : (PENDING[input.lastResult ?? 'starting'] ?? SETTLED_MS) - loadingMs = backoff ? Math.min(loadingMs * 2, SETTLED_MS) : 1_000 await delay(ms) yield } diff --git a/projects/start-sdk/lib/trigger/delay.ts b/projects/start-sdk/lib/trigger/delay.ts deleted file mode 100644 index b036af6104..0000000000 --- a/projects/start-sdk/lib/trigger/delay.ts +++ /dev/null @@ -1,9 +0,0 @@ -const MAX_TIMEOUT_MS = 2 ** 31 - 1 - -/** Resolves after `ms`, however long; never resolves for `Infinity`. */ -export async function delay(ms: number): Promise { - if (ms === Infinity) return new Promise(() => {}) - for (; ms > MAX_TIMEOUT_MS; ms -= MAX_TIMEOUT_MS) - await new Promise(resolve => setTimeout(resolve, MAX_TIMEOUT_MS)) - await new Promise(resolve => setTimeout(resolve, ms)) -} diff --git a/projects/start-sdk/lib/trigger/statusTrigger.ts b/projects/start-sdk/lib/trigger/statusTrigger.ts index fcc370dc97..e3bdba9686 100644 --- a/projects/start-sdk/lib/trigger/statusTrigger.ts +++ b/projects/start-sdk/lib/trigger/statusTrigger.ts @@ -1,6 +1,6 @@ import { HealthStatus } from '@start9labs/start-core/types' import { Trigger } from '.' -import { delay } from './delay' +import { delay } from '../util/delay' type StatusIntervals = { [K in HealthStatus]?: number } diff --git a/projects/start-sdk/lib/util/SubContainer.ts b/projects/start-sdk/lib/util/SubContainer.ts index 86d8883ba4..633f80b342 100644 --- a/projects/start-sdk/lib/util/SubContainer.ts +++ b/projects/start-sdk/lib/util/SubContainer.ts @@ -10,6 +10,7 @@ import { logErrorOnce } from '@start9labs/start-core/util/logErrorOnce' import { Mounts } from '../mainFn/Mounts' import { FileMounts } from './fileMounts' import { jsonEnv } from './jsonEnv' +import { onLeaveUntil } from './onLeaveUntil' import { PathQueue } from './PathQueue' export const execFile = promisify(cp.execFile) @@ -376,51 +377,6 @@ export const SubContainer = { }, } -/** - * Live eager subcontainers grouped by the effects context that created them. - * Any still alive when that context leaves (e.g. a subcontainer created in - * `main` but never explicitly destroyed) is torn down via the armed - * `onLeaveContext` hook instead of lingering until GC runs its `Drop` - * finalizer. - * - * One hook is armed per distinct effects object — on the first subcontainer - * created under it — and each subcontainer removes itself on destroy, so - * repeated short-lived containers (`withTemp`, per-poll health checks) don't - * accumulate registrations. Destroying via `destroy()` keeps the hold model - * intact: a container still held by a running daemon defers teardown until - * the daemon's own context-leave releases it. - */ -const contextLiveSubcontainers = new WeakMap< - T.Effects, - Set> ->() - -function registerForContextCleanup( - effects: T.Effects, - sub: SubContainerEager, -): void { - let live = contextLiveSubcontainers.get(effects) - if (!live) { - live = new Set() - contextLiveSubcontainers.set(effects, live) - effects.onLeaveContext(() => { - const remaining = contextLiveSubcontainers.get(effects) - if (!remaining) return - for (const c of [...remaining]) { - c.destroy().catch(e => console.error(e)) - } - }) - } - live.add(sub) -} - -function unregisterFromContextCleanup( - effects: T.Effects, - sub: SubContainerEager, -): void { - contextLiveSubcontainers.get(effects)?.delete(sub) -} - /** * Want to limit what we can do in a container, so we want to launch a container with a specific image and the mounts. * @@ -440,6 +396,12 @@ export class SubContainerEager< private destroyRequested = false private holdCount = 0 private teardown: Promise | null = null + /** + * Withdraws this container from its creating context's teardown. Until + * withdrawn, leaving that context calls {@link destroy}, which waits for + * outstanding holds. + */ + private releaseContextCleanup = () => {} private readonly fileMounts = new FileMounts() private sharedMounts = false private sharedVolumeDependency = false @@ -529,7 +491,9 @@ export class SubContainerEager< guid, identity, ) - registerForContextCleanup(effects, res) + res.releaseContextCleanup = onLeaveUntil(effects, () => { + res.destroy().catch(e => console.error(e)) + }) try { onCreate?.(res) @@ -737,19 +701,18 @@ export class SubContainerEager< } /** - * Detach from the creating context's `onLeaveContext` cleanup — drops this - * subcontainer from its context's live set so a context-leave no longer - * destroys it. The caller becomes responsible for calling {@link destroy}. - * Idempotent. + * Detach from the creating context's `onLeaveContext` cleanup, so a + * context-leave no longer destroys this subcontainer. The caller becomes + * responsible for calling {@link destroy}. Idempotent. */ detach(): void { - unregisterFromContextCleanup(this.effects, this) + this.releaseContextCleanup() } private _destroyImmediate(): Promise { return (this.teardown ??= (async () => { this.destroyed = true - unregisterFromContextCleanup(this.effects, this) + this.releaseContextCleanup() const guid = this.guid await this.fileMounts.close() await this.killLeader() diff --git a/projects/start-sdk/lib/util/delay.ts b/projects/start-sdk/lib/util/delay.ts new file mode 100644 index 0000000000..db5a9cbd61 --- /dev/null +++ b/projects/start-sdk/lib/util/delay.ts @@ -0,0 +1,59 @@ +const MAX_TIMEOUT_MS = 2 ** 31 - 1 + +export type DelayOptions = { + signal?: AbortSignal + ref?: boolean +} + +/** + * Resolves after `ms`, however long, or as soon as the signal aborts. + * Never resolves for `Infinity` without a signal. + */ +export function delay( + ms: number, + { signal, ref = true }: DelayOptions = {}, +): Promise { + if (signal?.aborted) return Promise.resolve() + return new Promise(resolve => { + let timer: ReturnType | undefined + const wake = () => { + clearTimeout(timer) + signal?.removeEventListener('abort', wake) + resolve() + } + const wait = (remaining: number) => { + if (remaining === Infinity) return + const step = Math.min(remaining, MAX_TIMEOUT_MS) + timer = setTimeout( + () => (remaining > step ? wait(remaining - step) : wake()), + step, + ) + if (!ref) timer.unref() + } + signal?.addEventListener('abort', wake) + wait(ms) + }) +} + +/** Delays that double from the initial delay up to the cap. */ +export class ExponentialBackoff { + private nextMs: number + + constructor( + private readonly initialMs: number, + private readonly maxMs: number, + ) { + this.nextMs = initialMs + } + + /** Returns the current delay and doubles the one after it. */ + next(): number { + const ms = this.nextMs + this.nextMs = Math.min(ms * 2, this.maxMs) + return ms + } + + reset() { + this.nextMs = this.initialMs + } +} diff --git a/projects/start-sdk/lib/util/fileHelper.ts b/projects/start-sdk/lib/util/fileHelper.ts index 06c0f9ef6b..00f3042739 100644 --- a/projects/start-sdk/lib/util/fileHelper.ts +++ b/projects/start-sdk/lib/util/fileHelper.ts @@ -22,6 +22,8 @@ import { withUpdateDeadline, } from './fileAccess' import { hasFileMounts, refreshFileMounts } from './fileMounts' +import { delay, ExponentialBackoff } from './delay' +import { onLeaveUntil } from './onLeaveUntil' async function readRaw(path: string): Promise { return fs.readFile(path, 'utf-8').catch(error => { @@ -36,6 +38,9 @@ const exists = (path: string) => () => false, ) +const WATCH_RETRY_INITIAL_MS = 100 +const WATCH_RETRY_MAX_MS = 30_000 + /** Starts watching at once; `fs.watch` defers until its first read. */ function watchPath(path: string, abort: AbortSignal) { const ctrl = new AbortController() @@ -342,23 +347,50 @@ class FileHelperImpl implements FileHelper { protected async *produceRaw( abort: AbortSignal, ): AsyncGenerator { - while (this.effects.isInContext && !abort.aborted) { - if (await exists(filePath)) { - const watch = watchPath(filePath, abort) - try { - yield await doRead() - await watch.first.catch(e => { - if (!abort.aborted) console.error(asError(e)) - }) - } finally { - watch.stop() + if (!this.effects.isInContext || abort.aborted) return + const signalCtrl = new AbortController() + let releaseLeave = () => {} + const onAbort = () => { + releaseLeave() + signalCtrl.abort() + } + abort.addEventListener('abort', onAbort, { once: true }) + releaseLeave = onLeaveUntil(this.effects, onAbort) + const signal = signalCtrl.signal + const retry = new ExponentialBackoff( + WATCH_RETRY_INITIAL_MS, + WATCH_RETRY_MAX_MS, + ) + try { + while (this.effects.isInContext && !signal.aborted) { + let failed = false + const onWatchError = (e: unknown) => { + if (signal.aborted) return + failed = true + console.error(asError(e)) + } + const present = await exists(filePath) + if (signal.aborted) break + if (present) { + const watch = watchPath(filePath, signal) + try { + yield await doRead() + await watch.first.catch(onWatchError) + } finally { + watch.stop() + } + } else { + yield null + await onCreated(filePath, signal).catch(onWatchError) } - } else { - yield null - await onCreated(filePath, abort).catch(e => { - if (!abort.aborted) console.error(asError(e)) - }) + // A waiting reader never holds the event loop. + if (failed) await delay(retry.next(), { signal, ref: false }) + else retry.reset() } + } finally { + releaseLeave() + abort.removeEventListener('abort', onAbort) + signalCtrl.abort() } } diff --git a/projects/start-sdk/lib/util/onLeaveUntil.ts b/projects/start-sdk/lib/util/onLeaveUntil.ts new file mode 100644 index 0000000000..afda01021c --- /dev/null +++ b/projects/start-sdk/lib/util/onLeaveUntil.ts @@ -0,0 +1,23 @@ +import * as T from '@start9labs/start-core/types' + +const leaveCallbacks = new WeakMap void>>() + +/** + * Runs the callback when the context leaves, unless released first. + * The caller must release it on completion. + */ +export function onLeaveUntil(effects: T.Effects, fn: () => void): () => void { + const existing = leaveCallbacks.get(effects) + const callbacks = existing ?? new Set<() => void>() + if (!existing) { + leaveCallbacks.set(effects, callbacks) + effects.onLeaveContext(() => { + for (const callback of callbacks) callback() + callbacks.clear() + }) + } + callbacks.add(fn) + return () => { + callbacks.delete(fn) + } +}