From 54589ae1c29b67f38b92f9abff012f8887f4a886 Mon Sep 17 00:00:00 2001 From: U-ITACHII Date: Tue, 24 Nov 2026 00:27:39 +0530 Subject: [PATCH] fix(localworker): swap Miniflare instance before disposing previous one and dedupe concurrent cold starts (#4689) * fix(localworker): swap Miniflare instance before disposing previous one and dedupe concurrent cold starts * test(localworker): restore the service's tests and cover the swap on the real runtime Brings back the existing LocalWorkerService tests and adds cases for a request during a redeploy, concurrent first requests, and a retry after a failed first deploy. The first-request deploy moves into its own method, and both dispose paths share one helper. --------- Co-authored-by: U-ITACHII <356922991+U-ITACHII@users.noreply.github.com> Co-authored-by: Daniel Salazar --- .../localworker/LocalWorkerService.test.ts | 76 ++++++++++++++++++- .../localworker/LocalWorkerService.ts | 73 ++++++++++++------ 2 files changed, 123 insertions(+), 26 deletions(-) diff --git a/src/backend/services/localworker/LocalWorkerService.test.ts b/src/backend/services/localworker/LocalWorkerService.test.ts index 0f220c93c..355295726 100644 --- a/src/backend/services/localworker/LocalWorkerService.test.ts +++ b/src/backend/services/localworker/LocalWorkerService.test.ts @@ -20,7 +20,7 @@ import { createServer } from 'node:http'; import type { AddressInfo } from 'node:net'; import { Readable } from 'node:stream'; -import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { WORKER_SUBDOMAIN_PREFIX, type SubdomainRow, @@ -254,6 +254,57 @@ describe('LocalWorkerService.cfCallLocal', () => { expect(await res.text()).toBe('up'); await localWorkers.cfDeleteLocal(name); }); + + it('serves concurrent first requests from a single deploy', async () => { + const name = `lws-cold-${Date.now()}`; + const src = await writeSource( + `${name}.js`, + "router.get('/', () => new Response('up'));", + ); + await seedWorkerRow(name, { root_dir_id: src.id }); + const deploy = vi.spyOn(localWorkers, 'cfDeployLocal'); + try { + const responses = await Promise.all( + Array.from({ length: 8 }, () => + localWorkers.cfCallLocal( + name, + new Request('http://x.localhost/'), + ), + ), + ); + const bodies = await Promise.all(responses.map((r) => r.text())); + expect(bodies).toEqual(Array(8).fill('up')); + expect(deploy).toHaveBeenCalledTimes(1); + } finally { + deploy.mockRestore(); + await localWorkers.cfDeleteLocal(name); + } + }, 60_000); + + it('retries the deploy on the request after a failed first one', async () => { + const name = `lws-retry-${Date.now()}`; + const src = await writeSource( + `${name}.js`, + "router.get('/', () => new Response('up'));", + ); + const row = await seedWorkerRow(name, { root_dir_id: src.id }); + const call = () => + localWorkers.cfCallLocal(name, new Request('http://x.localhost/')); + + // With no source file the deploy throws for every waiting request. + await server.stores.subdomain.update(row.uuid as string, { + root_dir_id: null, + }); + const failed = await Promise.allSettled([call(), call()]); + expect(failed.map((r) => r.status)).toEqual(['rejected', 'rejected']); + + await server.stores.subdomain.update(row.uuid as string, { + root_dir_id: src.id, + }); + const res = await call(); + expect(await res.text()).toBe('up'); + await localWorkers.cfDeleteLocal(name); + }, 60_000); }); describe('LocalWorkerService.cfDeleteLocal', () => { @@ -298,6 +349,29 @@ describe('LocalWorkerService.cfDeployLocal', () => { expect(after.status).toBe(404); }, 60_000); + it('serves a request that arrives while a redeploy is in progress', async () => { + const name = `lws-swap-${Date.now()}`; + const respond = (text: string) => + `addEventListener('fetch', (e) => e.respondWith(new Response('${text}')));`; + const call = () => + localWorkers.cfCallLocal(name, new Request('http://x.localhost/')); + try { + await localWorkers.cfDeployLocal(name, 'auth', respond('v1')); + expect(await (await call()).text()).toBe('v1'); + + const redeploy = localWorkers.cfDeployLocal( + name, + 'auth', + respond('v2'), + ); + const during = await call(); + expect(await during.text()).toBe('v2'); + expect((await redeploy).success).toBe(true); + } finally { + await localWorkers.cfDeleteLocal(name); + } + }, 60_000); + it('reaches this machine, but not link-local or LAN addresses by default', async () => { const local = createServer((_req, res) => res.end('reached')); await new Promise((r) => local.listen(0, '127.0.0.1', r)); diff --git a/src/backend/services/localworker/LocalWorkerService.ts b/src/backend/services/localworker/LocalWorkerService.ts index 25fe1239f..859f39af8 100644 --- a/src/backend/services/localworker/LocalWorkerService.ts +++ b/src/backend/services/localworker/LocalWorkerService.ts @@ -25,6 +25,8 @@ const IDLE_SWEEP_INTERVAL_MS = 60 * 1000; // sweep cadence const activeWorkers = new Map(); // Registry key -> last dispatch/deploy time (ms). Drives the idle sweep. const lastAccess = new Map(); +// Worker name -> its first-request deploy, while that deploy is running. +const inflightColdStarts = new Map>(); let idleSweepTimer: ReturnType | null = null; /** @@ -86,7 +88,7 @@ export class LocalWorkerService extends PuterService { code: string, extraBindings: Record, ) { - await this.#disposeWorker(key); + const previous = activeWorkers.get(key); try { const mf = new Miniflare({ modules: false, @@ -114,8 +116,11 @@ export class LocalWorkerService extends PuterService { }, script: code, } as WorkerOptions); + // Registered before the old instance goes, so a request never + // finds the key empty mid-redeploy. activeWorkers.set(key, mf); this.#touch(key); + await this.#disposeInstance(previous); return { success: true, errors: [], @@ -138,26 +143,24 @@ export class LocalWorkerService extends PuterService { async cfCallLocal(workerName: string, request: Request) { let mf = activeWorkers.get(workerName); if (!mf) { - // cfDeployLocal here - const existingSub: SubdomainRow | null = - await this.stores.subdomain.getBySubdomain( - 'workers.puter.' + workerName, - ); - - if (!existingSub) { + // Concurrent first requests share one deploy: a second one would + // dispose the instance the first is being served by. + let pending = inflightColdStarts.get(workerName); + if (!pending) { + pending = this.#coldStart(workerName); + inflightColdStarts.set(workerName, pending); + } + try { + await pending; + } finally { + if (inflightColdStarts.get(workerName) === pending) { + inflightColdStarts.delete(workerName); + } + } + mf = activeWorkers.get(workerName); + if (!mf) { return new Response('subdomain not found', { status: 404 }); } - // A suspended owner's worker answers as one that doesn't exist. - const owner = await this.stores.user.getById(existingSub.user_id); - if (owner?.suspended) { - return new Response('subdomain not found', { status: 404 }); - } - const [_, authorization, code] = await this.reconstructDeployArgs( - workerName, - existingSub, - ); - await this.cfDeployLocal(workerName, authorization, code); - mf = activeWorkers.get(workerName)!; } // Mark activity so the idle sweep keeps this worker resident. this.#touch(workerName); @@ -172,6 +175,23 @@ export class LocalWorkerService extends PuterService { ...(hasBody ? { duplex: 'half' } : {}), } as unknown as MiniflareRequestInit); } + /** Deploys a worker from its subdomain row, if it has one to serve. */ + async #coldStart(workerName: string): Promise { + const existingSub: SubdomainRow | null = + await this.stores.subdomain.getBySubdomain( + 'workers.puter.' + workerName, + ); + if (!existingSub) return; + // A suspended owner's worker answers as one that doesn't exist. + const owner = await this.stores.user.getById(existingSub.user_id); + if (owner?.suspended) return; + const [_, authorization, code] = await this.reconstructDeployArgs( + workerName, + existingSub, + ); + await this.cfDeployLocal(workerName, authorization, code); + } + /** * Dispatch into a resident worker without the subdomain-row lookup * `cfCallLocal` falls back to — `null` means "not deployed here", which is @@ -218,12 +238,15 @@ export class LocalWorkerService extends PuterService { const mf = activeWorkers.get(workerName); activeWorkers.delete(workerName); lastAccess.delete(workerName); - if (mf) { - try { - await mf.dispose(); // releases the instance's port - } catch { - /* best-effort teardown */ - } + await this.#disposeInstance(mf); + } + + async #disposeInstance(mf: Miniflare | undefined): Promise { + if (!mf) return; + try { + await mf.dispose(); // releases the instance's port + } catch { + /* best-effort teardown */ } }