Skip to content
Draft
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
1 change: 1 addition & 0 deletions packages/devframe/src/adapters/initiate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down
19 changes: 19 additions & 0 deletions packages/devframe/src/node/__tests__/host-tracing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
69 changes: 55 additions & 14 deletions packages/devframe/src/node/host-tracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,10 @@ const BUILTIN_CHANNELS: Record<string, string> = {
*/
export class DevframeTracingHostImpl implements DevframeTracingHost {
private readonly local: TracingRecorder
private readonly sources: DevframeTracingSource[] = []
private readonly sources = new Map<DevframeTracingSource, () => 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<string, DevframeTracingSource>()
private readonly sinks = new Map<string, StreamSink<DevframeTraceRecord>>()
Expand All @@ -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<void> {
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)
}
Expand All @@ -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 {
Expand All @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -156,7 +192,10 @@ export class DevframeTracingHostImpl implements DevframeTracingHost {
private collect(): { owners: Map<string, DevframeTracingSource>, infos: Map<string, DevframeTracingChannelInfo> } {
const owners = new Map<string, DevframeTracingSource>()
const infos = new Map<string, DevframeTracingChannelInfo>()
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)
Expand Down Expand Up @@ -196,6 +235,8 @@ export class DevframeTracingHostImpl implements DevframeTracingHost {

private async publish(infos: Map<string, DevframeTracingChannelInfo>): Promise<void> {
const state = await this.state
if (this.disposed)
return
const next: Record<string, DevframeTracingChannelInfo> = {}
for (const [name, info] of infos)
next[name] = { ...info, streamId: this.sinks.get(name)?.id }
Expand Down
32 changes: 24 additions & 8 deletions packages/devframe/src/node/instance-shell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand All @@ -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'
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -695,12 +698,17 @@ export function createInstanceShell<TContext extends DevframeNodeContext>(
let started: StartedServer | undefined
let transport: WsRpcTransport | undefined
let dispose: (() => Promise<void>) | 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,
}

Expand Down Expand Up @@ -931,7 +939,10 @@ export function createInstanceShell<TContext extends DevframeNodeContext>(
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(() => {})
Expand Down Expand Up @@ -1090,12 +1101,17 @@ export function createInstanceShell<TContext extends DevframeNodeContext>(
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() {
Expand Down
121 changes: 121 additions & 0 deletions packages/hub/src/node/__tests__/tracing-lifecycle.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
4 changes: 3 additions & 1 deletion packages/hub/src/node/initiate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand All @@ -390,6 +390,8 @@ async function resolveHubContext(
? { builtinRpcDeclarations: options.rpcDeclarations }
: {}),
})
api.ownTracing(context.tracing)
return context
}

/**
Expand Down
1 change: 1 addition & 0 deletions tests/__snapshots__/tsnapi/devframe/internal.snapshot.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ export interface InstanceShellApi {
base: string;
app: H3;
origin: () => string | undefined;
ownTracing: (_: DevframeTracingHost) => void;
connectionMeta: () => ConnectionMeta | undefined;
}
export interface InstanceShellInit<TContext extends DevframeNodeContext> {
Expand Down
Loading