Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,14 @@ npm treats versions as semver and semver forbids leading zeros.

## [Unreleased]

### Changed

- **Mesh: teapots connect in parallel at boot** (#95). Each absent teapot used to cost its own
`bootTimeoutMs` before the next one was tried, so three absent teapots held the boot for three
budgets; now they cost one. Remote steps and routes still register in config order, so the graph
does not depend on which teapot answers first. A refusal (wrong secret) still fails the boot at
once, without waiting for an absent teapot's budget. Mesh is `@experimental`; no API change.

## [26.11.0-rc.2] - 2026-11-23

### Added
Expand Down
30 changes: 26 additions & 4 deletions src/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@

export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';

type Runner = (ctx: any) => any;

Check warning on line 80 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type

Check warning on line 80 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type

/** Something shutdown closes: a mesh link, or the retry loop of a teapot that missed boot. */
type Closable = Pick<Link, 'close'>;
Expand Down Expand Up @@ -670,7 +670,7 @@
'is the object itself, and the mesh transports data, not objects. ' +
'Export a @Step instead, which runs on the teapot per request and returns its result.',
);
const instance: any = new ProviderClass();

Check warning on line 673 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
registry.providerInstances.set(meta.provides, instance);
registry.setRunner(
meta.provides,
Expand All @@ -685,7 +685,7 @@
const meta = getStepMeta(StepClass)!;
registry.stepNodes.push({ name: meta.provides, needs: meta.needs, provides: [meta.provides], origin });
if (meta.export) registry.exportedSteps.push(meta.provides);
const instance: any = new StepClass();

Check warning on line 688 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
registry.setRunner(
meta.provides,
keyedRunner('step', meta.provides, [meta.provides], (ctx) => instance.run(ctx)),
Expand All @@ -703,7 +703,7 @@
): void {
for (const ControllerClass of controllers) {
for (const route of getRoutes(ControllerClass)) {
const instance: any = new ControllerClass();

Check warning on line 706 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
const argSpecs = getArgs(ControllerClass, route.handlerName);
const pattern = joinPath(mountpoint, route.path);
const declaration = `${ControllerClass.name}.${route.handlerName}`;
Expand All @@ -725,7 +725,7 @@
steps: [],
handlerName: route.handlerName,
needs: getHandlerNeeds(argSpecs),
run: async (context: any) => instance[route.handlerName](...(await resolveArgs(argSpecs, context))),

Check warning on line 728 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
transformer,
duplicates: route.duplicates,
maxBodyBytes: route.maxBodyBytes,
Expand Down Expand Up @@ -1528,10 +1528,33 @@
);
const ctx: MembershipContext = { mesh, bus, logger, table };

// All teapots connect at once, so N absent ones cost one boot budget rather than N (#95). A refusal
// still fails the boot immediately; the attempts still running are closed as they land, since
// nothing else will ever hold their links.
const holders = teapots.map((): { link?: Link } => ({}));
const attempts = teapots.map((teapot, i) =>
connectUntilDeadline(mesh, bus, logger, teapot.url, () => connectTeapot(ctx, teapot, holders[i]!)),
);
let links: (Link | undefined)[];

try {
links = await Promise.all(attempts);
} catch (err) {
for (const attempt of attempts)
attempt.then(
(link) => link?.close(),
() => {},
);
throw err;
}

// Registration walks the config order, not arrival order, so the graph is the same on every boot.
meshLinks.push(...links.filter((link): link is Link => link !== undefined));

try {
for (const teapot of teapots) {
const holder: { link?: Link } = {};
const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () => connectTeapot(ctx, teapot, holder));
for (const [i, teapot] of teapots.entries()) {
const link = links[i];
const holder = holders[i]!;

if (!link) {
absent.push(teapot.url);
Expand All @@ -1541,7 +1564,6 @@
}

holder.link = link;
meshLinks.push(link);
const { steps, routes } = buildRemote(link);
const origin = `mesh:${teapot.url}`;

Expand Down Expand Up @@ -1762,7 +1784,7 @@

const resolveScope = async (name: string, env: RequestEnvelope): Promise<unknown> => {
// context is intentionally `any`: providers and steps merge arbitrary keys into it
const seed: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers };

Check warning on line 1787 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
// The teapot gates names before this runs, so an exported token always has a slice.
const { providers, steps } = slices.get(name)!;

Expand All @@ -1785,7 +1807,7 @@
const plan = routePlans.find((candidate) => candidate.pattern === name && candidate.method === env.method);

if (!plan) {
const error: any = new Error(`no route ${name}`);

Check warning on line 1810 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
error.status = 404;
throw error;
}
Expand All @@ -1810,7 +1832,7 @@
});

if ('stream' in result) {
const error: any = new Error('cannot proxy a streaming route');

Check warning on line 1835 in src/app/index.ts

View workflow job for this annotation

GitHub Actions / build

Unexpected any. Specify a different type
error.status = 500;
throw error;
}
Expand Down
26 changes: 26 additions & 0 deletions test/bun/mesh-reconnect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,3 +187,29 @@ test('mesh on Bun: a reconnecting teapot keeps its routes with 503 + retry-after
await teacup.close();
}
});

// #95: absent teapots connect in parallel, so three of them cost one boot budget, not three.
@Module({ mountpoint: '/api', controllers: [] })
class EmptyModule {}

test('mesh on Bun: three absent teapots boot in about one bootTimeoutMs', async () => {
const teacup = createApp({
modules: [EmptyModule],
experimental: true,
logger: { debug() {}, info() {}, warn() {}, error() {} },
mesh: {
teapots: [9, 10, 11].map((port) => ({ url: `ws://127.0.0.1:${port}/x`, secret: SECRET })),
secret: SECRET,
bootTimeoutMs: 600,
},
});

try {
const started = Date.now();
await teacup.ready();
const elapsed = Date.now() - started;
expect(elapsed).toBeLessThan(1500);
} finally {
await teacup.close();
}
}, 15_000);
26 changes: 26 additions & 0 deletions test/deno/mesh-reconnect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,29 @@ Deno.test('mesh on Deno: a reconnecting teapot keeps its routes with 503 + retry
await teacup.close();
}
});

// #95: absent teapots connect in parallel, so three of them cost one boot budget, not three.
@Module({ mountpoint: '/api', controllers: [] })
class EmptyModule {}

Deno.test('mesh on Deno: three absent teapots boot in about one bootTimeoutMs', async () => {
const teacup = createApp({
modules: [EmptyModule],
experimental: true,
logger: { debug() {}, info() {}, warn() {}, error() {} },
mesh: {
teapots: [9, 10, 11].map((port) => ({ url: `ws://127.0.0.1:${port}/x`, secret: SECRET })),
secret: SECRET,
bootTimeoutMs: 600,
},
});

try {
const started = Date.now();
await teacup.ready();
const elapsed = Date.now() - started;
assertEquals(elapsed < 1500, true, `took ${elapsed}ms`);
} finally {
await teacup.close();
}
});
53 changes: 53 additions & 0 deletions test/mesh/boot-retry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,4 +310,57 @@ describe('mesh boot retry', () => {
await teacup.close();
}
}, 15_000);

it('connects absent teapots in parallel, so three of them cost one boot budget (#95)', async () => {
// Sequential connects spent bootTimeoutMs per absent teapot: 3 × 600ms here, ~1.8s.
const teacup = createApp({
modules: [LocalOnlyModule],
experimental: true,
logger: collect().logger,
mesh: {
teapots: [9, 10, 11].map((port) => ({ url: `ws://127.0.0.1:${port}/x`, secret: 's' })),
secret: 's',
bootTimeoutMs: 600,
},
});

try {
const started = Date.now();
await teacup.ready();
expect(Date.now() - started).toBeLessThan(1500);
} finally {
await teacup.close();
}
}, 15_000);

it('still fails fast on a refusal while another teapot is absent', async () => {
// In parallel the refusal no longer waits for the absent teapot's budget to run out first.
const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'good' } });
const server = await teapot.listen(0);
const port = (server.address() as { port: number }).port;

const teacup = createApp({
modules: [TeacupModule],
experimental: true,
logger: collect().logger,
mesh: {
teapots: [
{ url: 'ws://127.0.0.1:9/x', secret: 's' },
{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'WRONG' },
],
timeoutMs: 500,
bootTimeoutMs: 30_000,
},
});

try {
const started = Date.now();
await expect(teacup.ready()).rejects.toThrow(/mesh/);
expect(Date.now() - started).toBeLessThan(3000);
} finally {
await teacup.close();
await teapot.close();
server.close();
}
}, 40_000);
});
Loading