diff --git a/CHANGELOG.md b/CHANGELOG.md index fbb481e..28d688f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,16 @@ npm treats versions as semver and semver forbids leading zeros. ## [Unreleased] +### Added + +- **Mesh: peer and RPC latency on `mesh:*` events** (#97). A new `mesh:rpc` event fires for each + teacup→teapot call that answered, with `name` (token or route), `url` (the teapot), + `durationMs` and the request's `requestId`/`traceId`. `mesh:rpc:error` carries the same fields + plus `status`, and now also fires for a 504 timeout and for a call cut off by the link dropping + (503). `mesh:connect`/`mesh:disconnect` on the teacup carry `url`. On the teapot, + `mesh:rpc:error` gains `status`, `durationMs` and the request ids; it names no peer until + per-teacup identity (M8). Existing `EventPayload` fields only. Mesh is `@experimental`. + ### Changed - **Mesh: a token whose teapot is absent at boot is served degraded instead of failing the boot** diff --git a/api/index.api.md b/api/index.api.md index 07414df..62ac8d8 100644 --- a/api/index.api.md +++ b/api/index.api.md @@ -518,7 +518,7 @@ export function isValidationError(error: unknown): error is ValidationError; export const JsonTransformer: TransformerFn; // @public -export type LifecycleEvent = 'boot:provider:start' | 'boot:provider:ok' | 'boot:provider:fail' | 'request:step:enter' | 'request:step:leave' | 'request:step:error' | 'stream:open' | 'stream:close' | 'stream:error' | 'mesh:connect' | 'mesh:disconnect' | 'mesh:rpc:error' | 'mesh:boot:retry' | 'mesh:routes' | 'mesh:degraded' | 'mesh:restored' | 'plugin:mounted' | 'request:start' | 'request:end' | 'request:failed' | 'route:matched' | 'route:unmatched'; +export type LifecycleEvent = 'boot:provider:start' | 'boot:provider:ok' | 'boot:provider:fail' | 'request:step:enter' | 'request:step:leave' | 'request:step:error' | 'stream:open' | 'stream:close' | 'stream:error' | 'mesh:connect' | 'mesh:disconnect' | 'mesh:rpc:error' | 'mesh:rpc' | 'mesh:boot:retry' | 'mesh:routes' | 'mesh:degraded' | 'mesh:restored' | 'plugin:mounted' | 'request:start' | 'request:end' | 'request:failed' | 'route:matched' | 'route:unmatched'; // @public export interface Link { diff --git a/src/bus.ts b/src/bus.ts index c4dce3c..b70c621 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -41,6 +41,11 @@ export type LifecycleEvent = | 'mesh:connect' | 'mesh:disconnect' | 'mesh:rpc:error' + // One teacup→teapot RPC that answered (#97): `name` the token or route pattern, `url` the + // teapot, `durationMs` the round trip, plus the request's `requestId`/`traceId`. Its failures + // (an error answer, a 504 timeout, a 503 when the link drops mid-call) are `mesh:rpc:error` + // with the same fields and `status`. + | 'mesh:rpc' // A boot-time connect attempt that failed and will be retried until `bootTimeoutMs` passes. // Separate from `mesh:disconnect`, which is a link that was up and went away — this one never // came up, and a deploy watching for trouble wants to tell those apart. @@ -133,7 +138,10 @@ export interface EventPayload { * framework does not know what was sent, and will not guess. */ status?: number; - /** `mesh:routes`: the teapot whose routes changed. */ + /** + * The teapot a teacup-side mesh event concerns: `mesh:connect`, `mesh:disconnect`, `mesh:rpc`, + * `mesh:rpc:error` and `mesh:routes`. Bounded by `MeshConfig.teapots`, so it is safe as a label. + */ url?: string; /** `mesh:routes`: routes added to the remote table, as `'METHOD /pattern'`. */ added?: string[]; diff --git a/src/mesh/link.ts b/src/mesh/link.ts index e524130..4bfdfc6 100644 --- a/src/mesh/link.ts +++ b/src/mesh/link.ts @@ -1,4 +1,4 @@ -import type { Bus } from '../bus'; +import type { Bus, EventPayload } from '../bus'; import type { Logger } from '../logger'; import { HttpError } from '../signals'; import { connectSocket, type SocketCtor } from '../http/ws-adapter'; @@ -69,6 +69,8 @@ type PendingEntry = { resolve: (v: unknown) => void; reject: (e: unknown) => void; timer: ReturnType; + /** The call's `mesh:rpc` payload as of now: name, teapot url, elapsed ms and the request's ids (#97). */ + event: () => EventPayload; }; /** Mutable per-link state: which socket is current, and whether the application hung up for good. */ @@ -95,9 +97,16 @@ const DEFAULT_MAX_DELAY_MS = 30_000; * 503, not a bare Error: a dead upstream is not "this service broke", and the status is what * tells a caller it may retry and an operator where to look. A bare Error renders as a 500. */ -function rejectAllPending(pending: Map, reason: string, headers?: Record): void { +function rejectAllPending( + pending: Map, + reason: string, + headers?: Record, + bus?: Bus, +): void { for (const [, entry] of pending) { clearTimeout(entry.timer); + // A call cut off mid-request by the session ending is an RPC failure like any other (#97). + bus?.emit('mesh:rpc:error', { ...entry.event(), status: 503, error: new Error(reason) }); entry.reject(new HttpError(503, reason, undefined, headers)); } @@ -114,6 +123,7 @@ function sendRpc( ctx: RequestEnvelope, timeoutMs: number, downHeaders?: Record, + obs?: { bus?: Bus; url: string }, ): Promise { // Answer now rather than in timeoutMs. A closed socket cannot deliver the frame, so waiting // would make every request to a downed teapot hang for the full timeout (30s by default) @@ -123,15 +133,26 @@ function sendRpc( return Promise.reject(new HttpError(503, `mesh link is down: cannot resolve '${name}'`, undefined, downHeaders)); } + const started = performance.now(); + const event = (): EventPayload => ({ + name, + url: obs?.url, + durationMs: performance.now() - started, + requestId: ctx.correlation?.requestId, + traceId: ctx.correlation?.traceId, + }); + return new Promise((resolveCall, rejectCall) => { // 504: the link is alive but the teapot did not answer in time — a gateway timeout, // which is a different operational story from a link that is down. const timer = setTimeout(() => { pending.delete(id); - rejectCall(new HttpError(504, `mesh rpc timeout: ${name}`)); + const error = new HttpError(504, `mesh rpc timeout: ${name}`); + obs?.bus?.emit('mesh:rpc:error', { ...event(), status: 504, error }); + rejectCall(error); }, timeoutMs); - pending.set(id, { name, resolve: resolveCall, reject: rejectCall, timer }); + pending.set(id, { name, resolve: resolveCall, reject: rejectCall, timer, event }); // Not before the socket has room (#41); the timeout already runs, so a teapot that stops // reading still answers 504. Settled while waiting (timeout, close): nothing left to send. void sendWhenDrained(socket, () => @@ -152,12 +173,13 @@ function settleRpcResponse( clearTimeout(entry.timer); if (frame.ok) { + bus?.emit('mesh:rpc', entry.event()); entry.resolve(frame.result); } else { // `entry.name`, not `frame.id`: the id is a per-link counter, so this event used to report // "0" or "1" where every other emitter reports what failed — including the teapot's own // emit for the same call, which made the two sides of one failure impossible to line up. - bus?.emit('mesh:rpc:error', { name: entry.name, error: frame.error }); + bus?.emit('mesh:rpc:error', { ...entry.event(), status: frame.error.status ?? 500, error: frame.error }); entry.reject(new HttpError(frame.error.status ?? 500, frame.error.message)); } } @@ -517,7 +539,10 @@ export function connectLink(args: { // manifest's steps, because the graph is fixed at boot, and takes the returning one's routes. manifest: { steps: [], routes: [] }, rpc: (kind, name, ctx) => - sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs, downHeaders()), + sendRpc(state.socket, pending, String(counter++), kind, name, ctx, timeoutMs, downHeaders(), { + bus: args.bus, + url: args.url, + }), close: () => { // Terminal, by contract. `closeLinks` runs on shutdown, and a link that reconnected after // the application hung up would leave a process that cannot exit. @@ -558,10 +583,10 @@ export function connectLink(args: { /** End the current session: nothing can be delivered on it, so fail what was waiting. */ const endSession = (attempt: number): void => { state.socket = undefined; - args.bus?.emit('mesh:disconnect', { name: args.url }); + args.bus?.emit('mesh:disconnect', { name: args.url, url: args.url }); // Scheduled before the rejection, so the 503s carry the real wait in `retry-after`. scheduleRetry(attempt); - rejectAllPending(pending, `mesh link to ${args.url} is down`, downHeaders()); + rejectAllPending(pending, `mesh link to ${args.url} is down`, downHeaders(), args.bus); // With reconnection off, a link that was up and dropped is gone for good (D15). `adopted` // keeps a first connect that never succeeded out of this: that link never escaped. if (!bounds) dropWithoutReconnect(adopted, giveUp); @@ -580,7 +605,7 @@ export function connectLink(args: { state.socket = session.socket; const returning = adopted; adopted = true; - args.bus?.emit('mesh:connect', { name: args.url }); + args.bus?.emit('mesh:connect', { name: args.url, url: args.url }); reconnected(returning, link, session.manifest, args.onReconnect); return true; diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index 291675a..a276dad 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -203,6 +203,7 @@ async function handleRpc( exportedRoutes: Set, ): Promise { const { id, name } = frame; + const started = performance.now(); try { const result = await resolveRpc(frame, deps, exportedScopes, exportedRoutes); @@ -230,7 +231,16 @@ async function handleRpc( // `errorToResponse` masks it. The full error stays on this side, in the event below. const message = isHttpError(err) || status < 500 ? (err as Error).message : 'Internal Server Error'; - deps.bus?.emit('mesh:rpc:error', { name, error: err }); + // No peer identity on this side until per-teacup identity lands (M8); the request's ids join it + // to the teacup's own `mesh:rpc:error` for the same call (#97). + deps.bus?.emit('mesh:rpc:error', { + name, + error: err, + status, + durationMs: performance.now() - started, + requestId: frame.ctx?.correlation?.requestId, + traceId: frame.ctx?.correlation?.traceId, + }); await reply(socket, { type: 'rpc-res', id, ok: false, error: { message, status } }); } } diff --git a/test/mesh/events.test.ts b/test/mesh/events.test.ts new file mode 100644 index 0000000..21eef0e --- /dev/null +++ b/test/mesh/events.test.ts @@ -0,0 +1,117 @@ +import { describe, it, expect } from 'vitest'; +import { createApp, Step, Route, Get, Module, needs, type EventPayload } from '../../src/index'; + +// #97: which teapot a mesh event concerns, and how long each RPC took, on existing payload fields. + +@Step({ provides: 'auth', needs: [], export: true }) +class Auth { + run() { + return { auth: { ok: true } }; + } +} +@Step({ provides: 'broken', needs: [], export: true }) +class Broken { + run(): never { + throw new Error('db down'); + } +} +@Step({ provides: 'slow', needs: [], export: true }) +class Slow { + async run() { + await new Promise((r) => setTimeout(r, 300)); + return { slow: true }; + } +} +@Module({ mountpoint: '/api', steps: [Auth, Broken, Slow] }) +class TeapotModule {} + +@Route('/t') +class Ctl { + @Get('/auth') + auth(@needs('auth') auth: any) { + return { auth }; + } + @Get('/broken') + broken(@needs('broken') broken: any) { + return { broken }; + } + @Get('/slow') + slow(@needs('slow') slow: any) { + return { slow }; + } +} +@Module({ mountpoint: '/api', controllers: [Ctl] }) +class TeacupModule {} + +const quiet = { debug() {}, info() {}, warn() {}, error() {} }; + +async function pair() { + const teapot = createApp({ modules: [TeapotModule], experimental: true, logger: quiet, mesh: { secret: 's' } }); + const server = await teapot.listen(0); + const url = `ws://127.0.0.1:${(server.address() as { port: number }).port}/__mesh__/control`; + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + logger: quiet, + mesh: { teapots: [{ url, secret: 's' }], timeoutMs: 100 }, + }); + const seen: Record = { teacup: [], teapot: [] }; + for (const kind of ['mesh:connect', 'mesh:rpc', 'mesh:rpc:error'] as const) { + teacup.bus.on(kind, (e) => seen.teacup!.push({ ...e, scope: kind })); + teapot.bus.on(kind, (e) => seen.teapot!.push({ ...e, scope: kind })); + } + const close = async () => { + await teacup.close(); + await teapot.close(); + server.close(); + }; + return { teacup, url, seen, close }; +} + +const get = (path: string) => new Request(`http://x/api/t${path}`, { headers: { 'x-request-id': 'req-97' } }); + +describe('mesh events carry the peer and the RPC latency (#97)', () => { + it('mesh:connect names the teapot, and mesh:rpc carries url, durationMs and the request ids', async () => { + const { teacup, url, seen, close } = await pair(); + try { + expect((await teacup.fetch(get('/auth'))).status).toBe(200); + + expect(seen.teacup!.find((e) => e.scope === 'mesh:connect')).toMatchObject({ name: url, url }); + const rpc = seen.teacup!.find((e) => e.scope === 'mesh:rpc'); + expect(rpc).toMatchObject({ name: 'auth', url, requestId: 'req-97' }); + expect(rpc!.durationMs).toBeGreaterThanOrEqual(0); + } finally { + await close(); + } + }); + + it('an error answer is mesh:rpc:error with status and latency on both sides, joined by requestId', async () => { + const { teacup, url, seen, close } = await pair(); + try { + expect((await teacup.fetch(get('/broken'))).status).toBe(500); + + const cup = seen.teacup!.find((e) => e.scope === 'mesh:rpc:error'); + expect(cup).toMatchObject({ name: 'broken', url, status: 500, requestId: 'req-97' }); + expect(cup!.durationMs).toBeGreaterThanOrEqual(0); + const pot = seen.teapot!.find((e) => e.scope === 'mesh:rpc:error'); + expect(pot).toMatchObject({ name: 'broken', status: 500, requestId: 'req-97' }); + expect(pot!.durationMs).toBeGreaterThanOrEqual(0); + expect(seen.teacup!.some((e) => e.scope === 'mesh:rpc')).toBe(false); + } finally { + await close(); + } + }); + + it('a timeout is mesh:rpc:error with status 504 and the time it waited', async () => { + const { teacup, url, seen, close } = await pair(); + try { + expect((await teacup.fetch(get('/slow'))).status).toBe(504); + + const err = seen.teacup!.find((e) => e.scope === 'mesh:rpc:error'); + expect(err).toMatchObject({ name: 'slow', url, status: 504, requestId: 'req-97' }); + expect(err!.durationMs).toBeGreaterThanOrEqual(90); + } finally { + await close(); + } + }); +});