2 Commits
Author SHA1 Message Date
chrnx 08d3dd061b Merge pull request 'fix(container): cache the in-flight promise of an app-scoped binding (GitHub #46)' (#169) from fix/provider-inflight-cache into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 25s
CI / build (push) Successful in 29s
CI / runtimes (edge) (push) Successful in 19s
Promote → GitHub / push-github (push) Successful in 7s
CI / runtimes (deno) (push) Successful in 33s
2026-10-24 23:42:18 +00:00
chrnx 510e9c4863 fix(container): cache the in-flight promise of an app-scoped binding (GitHub #46)
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 29s
CI / runtimes (bun) (pull_request) Successful in 20s
CI / runtimes (deno) (pull_request) Successful in 33s
CI / runtimes (edge) (pull_request) Successful in 19s
Container.resolve marked an app-scoped binding resolved only after its
factory settled. Two resolutions that started before then both found
nothing cached and both ran the factory, so one token could open two
pools.

The binding now caches the promise as soon as the factory starts, and
every resolution returns that promise. Retry semantics are unchanged:
before, a rejected factory set nothing and the next resolution ran it
again. Now a rejection clears the cached promise, so the next
resolution still retries, and only the callers already waiting on the
failed attempt share its rejection. The factory runs inside an async
wrapper so a synchronous throw takes the same path.

createApp was not exposed to this in practice. bootProvider runs each
provider's runner once, inside the memoized boot, and registers the
finished value as a constant factory, and Container is not exported.
The fix makes the container's own guarantee hold instead of relying on
that.

Refs: GitHub #46
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-24 18:31:40 -05:00
3 changed files with 67 additions and 10 deletions

No files matched your search

+7
View File
@@ -301,6 +301,13 @@ npm treats versions as semver and semver forbids leading zeros.
by `Base` too. Each decorator now writes a copy onto the class it decorates. The subclass still by `Base` too. Each decorator now writes a copy onto the class it decorates. The subclass still
starts from what it inherits. starts from what it inherits.
- **An app-scoped binding runs its factory once, however many resolve it at once** (GitHub #46).
The internal container cached the value only after the factory settled, so two resolutions that
started before then each ran it. It now caches the pending promise. A rejection is still not
cached: the next resolution retries, as before, and the callers already waiting share that one
rejection. `createApp` was not affected in practice, because it runs each provider once during
the memoized boot and registers the finished value, but the container no longer depends on that.
- **`listen()` rejects when the port is taken** (#138). A bind failure such as `EADDRINUSE` or - **`listen()` rejects when the port is taken** (#138). A bind failure such as `EADDRINUSE` or
`EACCES` arrives as the server's `error` event, which `listen()` did not handle: the promise `EACCES` arrives as the server's `error` event, which `listen()` did not handle: the promise
never settled, and the error surfaced as an unhandled one. It now rejects with that error. The never settled, and the error surfaced as an unhandled one. It now rejects with that error. The
+14 -10
View File
@@ -6,8 +6,8 @@ export type Factory = (ctx: Record<string, unknown>) => unknown | Promise<unknow
interface Binding { interface Binding {
scope: Scope; scope: Scope;
factory: Factory; factory: Factory;
cached?: unknown; /** The app-scoped value, cached as a promise from the moment the factory starts. */
resolved?: boolean; cached?: Promise<unknown>;
} }
/** Minimal token-keyed dependency container with app-scoped memoization and async, mesh-ready resolution. */ /** Minimal token-keyed dependency container with app-scoped memoization and async, mesh-ready resolution. */
@@ -30,14 +30,18 @@ export class Container {
async resolve(token: string, ctx: Record<string, unknown> = {}): Promise<unknown> { async resolve(token: string, ctx: Record<string, unknown> = {}): Promise<unknown> {
const binding = this.bindings.get(token); const binding = this.bindings.get(token);
if (!binding) throw new Error(`unknown token: ${token}`); if (!binding) throw new Error(`unknown token: ${token}`);
if (binding.scope === 'app' && binding.resolved) return binding.cached; if (binding.scope === 'request') return binding.factory(ctx);
const value = await binding.factory(ctx); if (binding.cached) return binding.cached;
if (binding.scope === 'app') { // The pending promise is cached, not the settled value (GitHub #46): a resolve that starts
binding.cached = value; // while the factory is still running must wait for it, or it runs the factory a second time.
binding.resolved = true; // A rejection is not kept — it clears the cache, so the next resolve retries, as it did when
} // only successes were cached. The async wrapper turns a synchronous throw into that rejection.
const pending = (async () => binding.factory(ctx))();
return value; binding.cached = pending;
pending.catch(() => {
if (binding.cached === pending) binding.cached = undefined;
});
return pending;
} }
} }
+46
View File
@@ -17,6 +17,52 @@ test('resolve is async even for sync factories', async () => {
await expect(c.resolve('cfg')).resolves.toEqual({ port: 3000 }); await expect(c.resolve('cfg')).resolves.toEqual({ port: 3000 });
}); });
// GitHub #46: only the settled value was cached, so a second resolve that started before the first
// factory settled ran the factory again — two pools for one app-scoped token.
test('concurrent resolutions of an app-scoped token share one factory call', async () => {
const c = new Container();
const pending: (() => void)[] = [];
const factory = vi.fn(() => new Promise((resolve) => pending.push(() => resolve({ pool: {} }))));
c.register('db', 'app', factory);
const both = Promise.all([c.resolve('db'), c.resolve('db')]);
await Promise.resolve();
for (const release of pending) release();
const [a, b] = await both;
expect(factory).toHaveBeenCalledTimes(1);
expect(a).toBe(b);
});
// A rejection is not cached: the next resolve retries, as it did before #46. Callers that were
// already waiting on the failing attempt share its rejection rather than starting their own.
test('a rejected app-scoped factory is shared while in flight, then retried', async () => {
const c = new Container();
let calls = 0;
const factory = vi.fn(async () => {
calls += 1;
if (calls === 1) throw new Error('refused');
return { pool: calls };
});
c.register('db', 'app', factory);
const results = await Promise.allSettled([c.resolve('db'), c.resolve('db')]);
expect(results.map((r) => r.status)).toEqual(['rejected', 'rejected']);
expect(factory).toHaveBeenCalledTimes(1);
await expect(c.resolve('db')).resolves.toEqual({ pool: 2 });
await expect(c.resolve('db')).resolves.toEqual({ pool: 2 });
expect(factory).toHaveBeenCalledTimes(2);
});
test('a factory that throws synchronously rejects, and is retried', async () => {
const c = new Container();
let calls = 0;
c.register('db', 'app', () => {
calls += 1;
if (calls === 1) throw new Error('sync');
return 'ok';
});
await expect(c.resolve('db')).rejects.toThrow('sync');
await expect(c.resolve('db')).resolves.toBe('ok');
});
test('resolve throws a clear error for an unknown token', async () => { test('resolve throws a clear error for an unknown token', async () => {
const c = new Container(); const c = new Container();
await expect(c.resolve('missing')).rejects.toThrow(/unknown token: missing/); await expect(c.resolve('missing')).rejects.toThrow(/unknown token: missing/);