fake-api.ts 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. // Test-local programmable IApiClient fake (NOT the fixture: fixture is a demo
  2. // data source on a real clock; behavior tests need per-case responses and
  3. // deferred-controlled timing). Streams are hand pumps: pushMux/pushHost.
  4. import type {
  5. HostFrame, IApiClient, MuxFrame, RpcRequest, RpcResponse, SessionId,
  6. } from '../src/client/api.ts'
  7. import { RpcId } from '../src/client/api.ts'
  8. export interface Deferred<T> {
  9. promise: Promise<T>
  10. resolve(value: T): void
  11. reject(error: unknown): void
  12. }
  13. /** Test-held settlement: the case decides when an RPC lands (history-pending injections etc.). */
  14. export function deferred<T>(): Deferred<T> {
  15. let resolve!: (value: T) => void
  16. let reject!: (error: unknown) => void
  17. const promise = new Promise<T>((res, rej) => {
  18. resolve = res
  19. reject = rej
  20. })
  21. return { promise, resolve, reject }
  22. }
  23. let nextRpc = 0
  24. export function ok<T>(value: T): RpcResponse<T> {
  25. return { rpcId: RpcId(`fake-${nextRpc++}`), result: { ok: true, value } }
  26. }
  27. type StreamItem<F> = { kind: 'frame'; envelope: RpcRequest<F> } | { kind: 'end' } | { kind: 'fail'; error: unknown }
  28. interface StreamConn<F> {
  29. feed(item: StreamItem<F>): void
  30. }
  31. export class FakeApiClient implements IApiClient {
  32. /** Chronological call record: [method, payload]. */
  33. readonly calls: { method: string; payload: unknown }[] = []
  34. // Programmable slots (defaults answer OK-empty); reassign per case.
  35. onList: (payload: unknown) => Promise<RpcResponse<{ items: never[] }>> = () => Promise.resolve(ok({ items: [] }))
  36. onCreate: (payload: unknown) => Promise<RpcResponse<{ sessionId: SessionId }>> = () => Promise.resolve(ok({ sessionId: 'fk-new' as SessionId }))
  37. onHistory: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number })
  38. => Promise<RpcResponse<{ events: never[]; hasMore: boolean }>> =
  39. () => Promise.resolve(ok({ events: [], hasMore: false }))
  40. onPrompt: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  41. onCancel: (payload: unknown) => Promise<RpcResponse<{ accepted: true }>> = () => Promise.resolve(ok({ accepted: true as const }))
  42. onDescribe: (payload: unknown) => Promise<RpcResponse<{ version: string; cwd: string; attachedSessions: number }>> =
  43. () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0 }))
  44. private readonly muxConns: StreamConn<MuxFrame>[] = []
  45. private readonly hostConns: StreamConn<HostFrame>[] = []
  46. // Parameter annotations below are local structural types on purpose: the CI
  47. // lint lane runs without built artifacts, where IApiClient's wire types
  48. // (apiproxy subpath) resolve to any and inferred params trip no-unsafe-argument.
  49. readonly sessions: IApiClient['sessions'] = {
  50. list: (payload: unknown) => this.record('session.list', payload, this.onList(payload)),
  51. create: (payload: unknown) => this.record('session.create', payload, this.onCreate(payload)),
  52. history: (payload: { sessionId: SessionId; beforeSeq?: number; maxMessages?: number }) =>
  53. this.record('session.history', payload, this.onHistory(payload)),
  54. prompt: (payload: unknown) => this.record('session.prompt', payload, this.onPrompt(payload)),
  55. cancel: (payload: unknown) => this.record('session.cancel', payload, this.onCancel(payload)),
  56. }
  57. readonly host: IApiClient['host'] = {
  58. describe: payload => this.record('host.describe', payload, this.onDescribe(payload)),
  59. }
  60. /** When true, streams never fire onOpen (misbehaving-carrier material for the handshake timeout guard). */
  61. suppressStreamOpen = false
  62. /** When true, onOpen callbacks are parked instead of fired; releaseStreamOpens() fires them.
  63. * Lets a case hold the readiness handshake open (describe done, streams not yet "established"). */
  64. holdStreamOpen = false
  65. private heldOpens: (() => void)[] = []
  66. releaseStreamOpens(): void {
  67. const held = this.heldOpens
  68. this.heldOpens = []
  69. for (const fire of held) fire()
  70. }
  71. readonly events: IApiClient['events'] = {
  72. mux: (_payload: unknown, signal: AbortSignal, onOpen?: () => void) =>
  73. this.openStream(this.muxConns, signal, onOpen),
  74. host: (_payload: unknown, signal: AbortSignal, onOpen?: () => void) =>
  75. this.openStream(this.hostConns, signal, onOpen),
  76. }
  77. respond(): Promise<{ accepted: false; reason: 'not-pending' }> {
  78. return Promise.resolve({ accepted: false, reason: 'not-pending' })
  79. }
  80. /** Push one mux frame to every open mux stream (rpcId minted unless pinned by the case). */
  81. pushMux(frame: MuxFrame, rpcId?: string): void {
  82. for (const conn of [...this.muxConns]) conn.feed({ kind: 'frame', envelope: { rpcId: RpcId(rpcId ?? `push-${nextRpc++}`), payload: frame } })
  83. }
  84. pushHost(frame: HostFrame, rpcId?: string): void {
  85. for (const conn of [...this.hostConns]) conn.feed({ kind: 'frame', envelope: { rpcId: RpcId(rpcId ?? `push-${nextRpc++}`), payload: frame } })
  86. }
  87. /** End (clean close) or fail (throw) every open stream — reconnect-path material. */
  88. endStreams(): void {
  89. for (const conn of [...this.muxConns, ...this.hostConns]) conn.feed({ kind: 'end' })
  90. }
  91. failStreams(error: unknown): void {
  92. for (const conn of [...this.muxConns, ...this.hostConns]) conn.feed({ kind: 'fail', error })
  93. }
  94. get openMuxCount(): number {
  95. return this.muxConns.length
  96. }
  97. callsOf(method: string): unknown[] {
  98. return this.calls.filter(c => c.method === method).map(c => c.payload)
  99. }
  100. private record<T>(method: string, payload: unknown, response: Promise<T>): Promise<T> {
  101. this.calls.push({ method, payload })
  102. return response
  103. }
  104. private async *openStream<F>(registry: StreamConn<F>[], signal: AbortSignal, onOpen?: () => void): AsyncGenerator<RpcRequest<F>> {
  105. const inbox: StreamItem<F>[] = []
  106. let wake: (() => void) | null = null
  107. const conn: StreamConn<F> = {
  108. feed: (item) => {
  109. inbox.push(item)
  110. wake?.()
  111. },
  112. }
  113. registry.push(conn)
  114. if (this.holdStreamOpen && onOpen !== undefined) this.heldOpens.push(onOpen)
  115. else if (!this.suppressStreamOpen) onOpen?.()
  116. try {
  117. while (!signal.aborted) {
  118. while (inbox.length > 0) {
  119. const item = inbox.shift() as StreamItem<F>
  120. if (item.kind === 'end') return
  121. if (item.kind === 'fail') throw item.error
  122. yield item.envelope
  123. }
  124. await new Promise<void>((resolve) => {
  125. wake = resolve
  126. signal.addEventListener('abort', () => { resolve() }, { once: true })
  127. })
  128. wake = null
  129. }
  130. } finally {
  131. registry.splice(registry.indexOf(conn), 1)
  132. }
  133. }
  134. }