diff --git a/packages/devframe/src/adapters/initiate.ts b/packages/devframe/src/adapters/initiate.ts index 7e0579cb..f93902de 100644 --- a/packages/devframe/src/adapters/initiate.ts +++ b/packages/devframe/src/adapters/initiate.ts @@ -304,6 +304,7 @@ export function initDevframe( host: hostImpl, importMetaUrl: def.importMetaUrl, }) + api.ownTracing(context.tracing) const setupInfo: DevframeSetupInfo = { flags: options.flags ?? {} } // Wire services are constructed and made ready BEFORE setup, so // `setup(ctx)` can consume them synchronously (`ctx.services.get`). diff --git a/packages/devframe/src/node/__tests__/host-tracing.test.ts b/packages/devframe/src/node/__tests__/host-tracing.test.ts index ad3fd020..cf9a2a02 100644 --- a/packages/devframe/src/node/__tests__/host-tracing.test.ts +++ b/packages/devframe/src/node/__tests__/host-tracing.test.ts @@ -263,6 +263,25 @@ describe('devframeTracingHost', () => { expect(ctx.tracing.list().some(info => info.name === name)).toBe(false) }) + it('lets a source reattach during unsubscribe and ignores its old detach handle', async () => { + const ctx = await createCtx() + const unsubscribe = vi.fn<() => void>() + const source = { + list: () => [], + records: () => [], + subscribe: vi.fn(() => unsubscribe), + } + const detach = ctx.tracing.attach(source) + unsubscribe.mockImplementationOnce(() => { + detach() + ctx.tracing.attach(source) + }) + detach() + detach() + expect(unsubscribe).toHaveBeenCalledTimes(1) + expect(source.subscribe).toHaveBeenCalledTimes(2) + }) + it('keeps control in a source that has no record() / stop()', async () => { const ctx = await createCtx() const name = uniqueName() diff --git a/packages/devframe/src/node/host-tracing.ts b/packages/devframe/src/node/host-tracing.ts index a9c1f3da..9fccebf4 100644 --- a/packages/devframe/src/node/host-tracing.ts +++ b/packages/devframe/src/node/host-tracing.ts @@ -31,7 +31,10 @@ const BUILTIN_CHANNELS: Record = { */ export class DevframeTracingHostImpl implements DevframeTracingHost { private readonly local: TracingRecorder - private readonly sources: DevframeTracingSource[] = [] + private readonly sources = new Map void>() + private readonly failedDetaches = new Set<() => void>() + private readonly unsubscribeLocal: () => void + private disposed = false /** Channel name → the source that owns it. Attached sources win over the local one. */ private owners = new Map() private readonly sinks = new Map>() @@ -55,11 +58,30 @@ export class DevframeTracingHostImpl implements DevframeTracingHost { ) for (const [name, description] of Object.entries(BUILTIN_CHANNELS)) this.local.add(name, 'builtin', description) - this.local.subscribe(event => this.onSourceEvent(this.local, event)) + this.unsubscribeLocal = this.local.subscribe(event => this.onSourceEvent(this.local, event)) this.refresh() this.registerRpc() } + async dispose(): Promise { + this.disposed = true + clearTimeout(this.countTimer) + this.unsubscribeLocal() + this.listeners.clear() + this.owners.clear() + for (const { name } of this.local.list()) + this.local.stop(name) + for (const sink of this.sinks.values()) + sink.close() + this.sinks.clear() + // Each source owns its recorder. Unsubscribe without stopping it. + const detaches = [ + ...this.sources.values(), + ...this.failedDetaches, + ] + await Promise.all(detaches.map(async detach => detach())) + } + _applyOptions(options: DevframeTracingOptions | undefined): void { this.local.applyOptions(options) } @@ -77,7 +99,8 @@ export class DevframeTracingHostImpl implements DevframeTracingHost { * the call does nothing, and devframe never records its channel itself. */ record(name: string): void { - this.ownerOf(name).record?.(name) + if (!this.disposed) + this.ownerOf(name).record?.(name) } stop(name: string): void { @@ -93,6 +116,8 @@ export class DevframeTracingHostImpl implements DevframeTracingHost { } onRecord(name: string, fn: (record: DevframeTraceRecord) => void): () => void { + if (this.disposed) + return () => {} if (!this.owners.has(name)) this.local.add(name, 'adhoc') let set = this.listeners.get(name) @@ -105,22 +130,33 @@ export class DevframeTracingHostImpl implements DevframeTracingHost { } attach(source: DevframeTracingSource): () => void { - if (this.sources.includes(source)) + if (this.disposed || this.sources.has(source)) return () => {} - this.sources.push(source) - const unsubscribe = source.subscribe(event => this.onSourceEvent(source, event)) - this.refresh() - return () => { - const index = this.sources.indexOf(source) - if (index === -1) + let unsubscribe: (() => void) | undefined + const detach = () => { + if (this.sources.get(source) === detach) + this.sources.delete(source) + else if (!this.failedDetaches.delete(detach)) return - this.sources.splice(index, 1) - unsubscribe() - this.refresh() + try { + unsubscribe?.() + } + catch (error) { + this.failedDetaches.add(detach) + throw error + } + if (!this.disposed) + this.refresh() } + this.sources.set(source, detach) + unsubscribe = source.subscribe(event => this.onSourceEvent(source, event)) + this.refresh() + return detach } private onSourceEvent(source: DevframeTracingSource, event: DevframeTracingSourceEvent): void { + if (this.disposed) + return if (event.type === 'channels') { this.refresh() return @@ -156,7 +192,10 @@ export class DevframeTracingHostImpl implements DevframeTracingHost { private collect(): { owners: Map, infos: Map } { const owners = new Map() const infos = new Map() - for (const source of [this.local, ...this.sources]) { + for (const source of [ + this.local, + ...this.sources.keys(), + ]) { for (const info of source.list()) { owners.set(info.name, source) infos.set(info.name, info) @@ -196,6 +235,8 @@ export class DevframeTracingHostImpl implements DevframeTracingHost { private async publish(infos: Map): Promise { const state = await this.state + if (this.disposed) + return const next: Record = {} for (const [name, info] of infos) next[name] = { ...info, streamId: this.sinks.get(name)?.id } diff --git a/packages/devframe/src/node/instance-shell.ts b/packages/devframe/src/node/instance-shell.ts index 434ea339..8a7ab9ca 100644 --- a/packages/devframe/src/node/instance-shell.ts +++ b/packages/devframe/src/node/instance-shell.ts @@ -6,7 +6,7 @@ import type { H3, H3Event } from 'h3' import type { Buffer } from 'node:buffer' import type { IncomingMessage, Server as NodeHttpServer, ServerResponse } from 'node:http' import type { Duplex } from 'node:stream' -import type { ConnectionMeta, DevframeNodeContext, DevframeNodeRpcSession, DevframeNodeRpcSessionMeta, DevframeRpcClientFunctions, DevframeRpcServerFunctions } from '../types' +import type { ConnectionMeta, DevframeNodeContext, DevframeNodeRpcSession, DevframeNodeRpcSessionMeta, DevframeRpcClientFunctions, DevframeRpcServerFunctions, DevframeTracingHost } from '../types' import type { DevframeSseOptions, DevframeWsOptions } from '../types/devframe' import type { DevframeAuthHandler } from './auth' import type { RpcFunctionsHostImpl } from './host-functions' @@ -21,6 +21,7 @@ import { defineHandler, fromNodeHandler, H3 as H3App, toNodeHandler } from 'h3' import { DEVFRAME_SSE_ROUTE, DEVFRAME_WS_ROUTE } from '../constants' import { createInteractiveAuth } from '../recipes/interactive-auth' import { diagnostics } from './diagnostics' +import { DevframeTracingHostImpl } from './host-tracing' import { getInternalContext } from './hub-internals/context' import { listenWithLoopbackTwin } from './listen' import { detectServerRuntime } from './runtime' @@ -369,6 +370,8 @@ export interface InstanceShellApi { app: H3 /** The public origin, once known (pinned, or derived from the first request). */ origin: () => string | undefined + /** Release tracing for a context the instance created, even if setup fails. */ + ownTracing: (tracing: DevframeTracingHost) => void /** The connection meta, once the transport has resolved. */ connectionMeta: () => ConnectionMeta | undefined } @@ -695,12 +698,17 @@ export function createInstanceShell( let started: StartedServer | undefined let transport: WsRpcTransport | undefined let dispose: (() => Promise) | undefined + let ownedTracing: DevframeTracingHostImpl | undefined let ctx: TContext const api: InstanceShellApi = { base, app, origin: currentOrigin, + ownTracing(tracing) { + if (tracing instanceof DevframeTracingHostImpl) + ownedTracing = tracing + }, connectionMeta: () => meta, } @@ -931,7 +939,10 @@ export function createInstanceShell( maybeRegister() } - const initPromise = init() + const initPromise = init().catch(async (error) => { + await ownedTracing?.dispose().catch(() => {}) + throw error + }) // Surface init failures through `ready`/`handler`, never as an unhandled // rejection from the eager kick-off. initPromise.catch(() => {}) @@ -1090,12 +1101,17 @@ export function createInstanceShell( attach, async close() { await initPromise.catch(() => {}) - await registerPromise?.catch(() => {}) - registration?.unregister() - await dispose?.() - await ssePromise?.then(live => live.close()).catch(() => {}) - await started?.close() - await transportPromise?.then(live => live.close()).catch(() => {}) + try { + await ownedTracing?.dispose() + } + finally { + await registerPromise?.catch(() => {}) + registration?.unregister() + await dispose?.() + await ssePromise?.then(live => live.close()).catch(() => {}) + await started?.close() + await transportPromise?.then(live => live.close()).catch(() => {}) + } }, internals: { get started() { diff --git a/packages/hub/src/node/__tests__/tracing-lifecycle.test.ts b/packages/hub/src/node/__tests__/tracing-lifecycle.test.ts new file mode 100644 index 00000000..3cc7ce60 --- /dev/null +++ b/packages/hub/src/node/__tests__/tracing-lifecycle.test.ts @@ -0,0 +1,121 @@ +import type { DevframeNodeContext } from 'devframe/types' +import { tracingChannel } from 'node:diagnostics_channel' +import { initHub } from '@devframes/hub/initiate' +import { DEVFRAME_EVENTS } from 'devframe/constants' +import { initDevframe } from 'devframe/initiate' +import { createTracingRecorder } from 'devframe/node' +import { describe, expect, it, vi } from 'vitest' + +const options = { base: '/tracing/', mcp: false, register: false } as const +type Setup = (ctx: DevframeNodeContext) => void +const instances = [ + { + kind: 'devframe', + start: (setup: Setup) => initDevframe({ + id: 'tracing', + name: 'Tracing', + packageName: 'test-tracing', + version: '0.0.0', + homepage: '', + description: '', + setup, + }, options), + }, + { + kind: 'hub', + start: (setup: Setup) => initHub({ ...options, configure: setup }), + }, +] + +describe.each(instances)('$kind tracing', ({ kind, start }) => { + it('closes its streams and subscriptions while an attached tool keeps recording', async () => { + const name = `test:owned-tracing:${kind}` + const app = start(ctx => ctx.scope('child').tracing.record(name)) + const ctx = await app.context + const tool = createTracingRecorder() + const channel = tool.register(name) + tool.record(name) + const detach = ctx.tracing.attach(tool) + const onRecord = vi.fn() + ctx.tracing.onRecord(name, onRecord) + const streamId = ctx.tracing.list().find(info => info.name === name)!.streamId + const broadcast = vi.spyOn(ctx.rpc, 'broadcast') + + vi.useFakeTimers() + try { + channel.traceSync(() => 1) + expect(vi.getTimerCount()).toBe(1) + onRecord.mockClear() + + await app.close() + expect(vi.getTimerCount()).toBe(0) + expect(broadcast).toHaveBeenCalledWith(expect.objectContaining({ + method: DEVFRAME_EVENTS.broadcast.streamingEnd, + args: [DEVFRAME_EVENTS.stream.tracing, streamId, undefined], + })) + channel.traceSync(() => 2) + expect(tool.records(name).map(record => record.result)).toEqual([1, 2]) + expect(ctx.tracing.records(name).map(record => record.result)).toEqual([1]) + expect(onRecord).not.toHaveBeenCalled() + } + finally { + vi.useRealTimers() + detach() + tool.stop(name) + await app.close() + } + expect(channel.hasSubscribers).toBe(false) + }) + + it('releases tracing before setup rejection and preserves the setup error', async () => { + const name = `test:failed-tracing:${kind}` + const channel = tracingChannel(name) + const setupError = new Error('setup failed') + const unsubscribe = vi.fn().mockImplementationOnce(() => { + throw new Error('detach failed') + }) + const app = start((ctx) => { + ctx.tracing.record(name) + ctx.tracing.attach({ + list: () => [], + records: () => [], + subscribe: () => unsubscribe, + }) + throw setupError + }) + await expect(app.ready).rejects.toBe(setupError) + expect(channel.hasSubscribers).toBe(false) + expect(unsubscribe).toHaveBeenCalledTimes(1) + await app.close() + expect(unsubscribe).toHaveBeenCalledTimes(2) + }) +}) + +it('keeps tracing on a caller-supplied hub context through close and failed setup', async () => { + const owner = initHub(options) + const context = await owner.context + const name = 'test:borrowed-tracing' + const channel = context.tracing.register(name) + context.tracing.record(name) + try { + const borrower = initHub({ ...options, context }) + await borrower.ready + await borrower.close() + + const setupError = new Error('borrower setup failed') + const failed = initHub({ + ...options, + context, + configure: () => { throw setupError }, + }) + await expect(failed.ready).rejects.toBe(setupError) + await failed.close() + + channel.traceSync(() => 3) + expect(context.tracing.records(name).map(record => record.result)).toEqual([3]) + } + finally { + await owner.close() + } + expect(channel.hasSubscribers).toBe(false) +}) diff --git a/packages/hub/src/node/initiate.ts b/packages/hub/src/node/initiate.ts index 46180849..52bfbe08 100644 --- a/packages/hub/src/node/initiate.ts +++ b/packages/hub/src/node/initiate.ts @@ -381,7 +381,7 @@ async function resolveHubContext( app.use(joinURL(frameBase, DEVFRAME_CONNECTION_META_FILENAME), () => api.connectionMeta()) }, } - return createHubContext({ + const context = await createHubContext({ cwd, workspaceRoot: cwd, mode: 'dev', @@ -390,6 +390,8 @@ async function resolveHubContext( ? { builtinRpcDeclarations: options.rpcDeclarations } : {}), }) + api.ownTracing(context.tracing) + return context } /** diff --git a/tests/__snapshots__/tsnapi/devframe/internal.snapshot.d.ts b/tests/__snapshots__/tsnapi/devframe/internal.snapshot.d.ts index 43bcc2b6..a113e695 100644 --- a/tests/__snapshots__/tsnapi/devframe/internal.snapshot.d.ts +++ b/tests/__snapshots__/tsnapi/devframe/internal.snapshot.d.ts @@ -91,6 +91,7 @@ export interface InstanceShellApi { base: string; app: H3; origin: () => string | undefined; + ownTracing: (_: DevframeTracingHost) => void; connectionMeta: () => ConnectionMeta | undefined; } export interface InstanceShellInit {