httpapi-promptasync-context.test.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. // Regression coverage for issue #26526's claim that promptAsync's
  2. // Effect.forkIn loses the request's InstanceRef/WorkspaceRef. It does not —
  3. // forkIn preserves Context.Reference values via standard fiber inheritance.
  4. //
  5. // The companion claim that the streaming prompt handler "captures and
  6. // provides" those services is true and load-bearing: Stream.fromEffect's
  7. // body runs detached from the request fiber's context, so the explicit
  8. // Effect.provideService calls there are required, not defensive duplication.
  9. import { NodeHttpServer, NodeServices } from "@effect/platform-node"
  10. import { describe, expect } from "bun:test"
  11. import { Deferred, Effect, Layer, Schema, Scope } from "effect"
  12. import * as Stream from "effect/Stream"
  13. import { HttpClient, HttpRouter, HttpServerResponse } from "effect/unstable/http"
  14. import * as Socket from "effect/unstable/socket/Socket"
  15. import { HttpApi, HttpApiBuilder, HttpApiEndpoint, HttpApiGroup, HttpApiSchema } from "effect/unstable/httpapi"
  16. import { mkdir } from "node:fs/promises"
  17. import { registerAdapter } from "../../src/control-plane/adapters"
  18. import type { WorkspaceAdapter } from "../../src/control-plane/types"
  19. import { Workspace } from "../../src/control-plane/workspace"
  20. import { InstanceRef, WorkspaceRef } from "../../src/effect/instance-ref"
  21. import { Project } from "../../src/project/project"
  22. import { Session } from "../../src/session/session"
  23. import {
  24. InstanceContextMiddleware,
  25. instanceContextLayer,
  26. } from "../../src/server/routes/instance/httpapi/middleware/instance-context"
  27. import {
  28. WorkspaceRoutingMiddleware,
  29. WorkspaceRoutingQuery,
  30. workspaceRoutingLayer,
  31. } from "../../src/server/routes/instance/httpapi/middleware/workspace-routing"
  32. import { resetDatabase } from "../fixture/db"
  33. import { disposeAllInstances, tmpdirScoped } from "../fixture/fixture"
  34. import { workspaceLayerWithRuntimeFlags } from "../fixture/workspace"
  35. import { testEffect } from "../lib/effect"
  36. const testStateLayer = Layer.effectDiscard(
  37. Effect.gen(function* () {
  38. yield* Effect.promise(() => resetDatabase())
  39. yield* Effect.addFinalizer(() =>
  40. Effect.promise(async () => {
  41. await disposeAllInstances()
  42. await resetDatabase()
  43. }),
  44. )
  45. }),
  46. )
  47. const workspaceLayer = workspaceLayerWithRuntimeFlags({ experimentalWorkspaces: true })
  48. const it = testEffect(Layer.mergeAll(testStateLayer, NodeHttpServer.layerTest, NodeServices.layer, workspaceLayer))
  49. const instanceContextTestLayer = Layer.mergeAll(
  50. instanceContextLayer,
  51. workspaceRoutingLayer.pipe(Layer.provide(Socket.layerWebSocketConstructorGlobal)),
  52. )
  53. const localAdapter = (directory: string): WorkspaceAdapter => ({
  54. name: "Local Test",
  55. description: "Create a local test workspace",
  56. configure: (info) => ({ ...info, name: "local-test", directory }),
  57. create: async () => {
  58. await mkdir(directory, { recursive: true })
  59. },
  60. async remove() {},
  61. target: () => ({ type: "local" as const, directory }),
  62. })
  63. const setupWorkspace = (kind: string) =>
  64. Effect.gen(function* () {
  65. const dir = yield* tmpdirScoped({ git: true })
  66. yield* Project.use.fromDirectory(dir)
  67. const projectID = yield* Project.Service.use((svc) => svc.fromDirectory(dir).pipe(Effect.map((p) => p.project.id)))
  68. registerAdapter(projectID, kind, localAdapter(dir))
  69. const workspace = yield* Workspace.Service.use((svc) =>
  70. svc.create({ type: kind, branch: null, extra: null, projectID }),
  71. )
  72. return { dir, workspace }
  73. })
  74. type Capture = { directory?: string; workspaceID?: string }
  75. const captureInstance = Effect.gen(function* () {
  76. const instance = yield* InstanceRef
  77. const workspaceID = yield* WorkspaceRef
  78. return { directory: instance?.directory, workspaceID } satisfies Capture
  79. })
  80. const ProbeApi = HttpApi.make("handler-context-probe").add(
  81. HttpApiGroup.make("probe")
  82. .add(
  83. HttpApiEndpoint.post("fork", "/fork-probe", { query: WorkspaceRoutingQuery, success: Schema.Boolean }),
  84. HttpApiEndpoint.post("streamWithout", "/stream-probe-without", {
  85. query: WorkspaceRoutingQuery,
  86. success: Schema.String.pipe(HttpApiSchema.asText({ contentType: "application/json" })),
  87. }),
  88. HttpApiEndpoint.post("streamWith", "/stream-probe-with", {
  89. query: WorkspaceRoutingQuery,
  90. success: Schema.String.pipe(HttpApiSchema.asText({ contentType: "application/json" })),
  91. }),
  92. )
  93. .middleware(InstanceContextMiddleware)
  94. .middleware(WorkspaceRoutingMiddleware),
  95. )
  96. const serveProbes = (input: {
  97. fork?: Effect.Effect<boolean, never, Scope.Scope>
  98. streamWithout?: Effect.Effect<HttpServerResponse.HttpServerResponse>
  99. streamWith?: Effect.Effect<HttpServerResponse.HttpServerResponse>
  100. }) =>
  101. HttpApiBuilder.layer(ProbeApi).pipe(
  102. Layer.provide(
  103. HttpApiBuilder.group(ProbeApi, "probe", (handlers) =>
  104. handlers
  105. .handle("fork", () => input.fork ?? Effect.succeed(false))
  106. .handleRaw(
  107. "streamWithout",
  108. () => input.streamWithout ?? Effect.succeed(HttpServerResponse.empty({ status: 404 })),
  109. )
  110. .handleRaw("streamWith", () => input.streamWith ?? Effect.succeed(HttpServerResponse.empty({ status: 404 }))),
  111. ),
  112. ),
  113. Layer.provide(instanceContextTestLayer),
  114. Layer.provide(Layer.mock(Session.Service)({})),
  115. HttpRouter.serve,
  116. Layer.build,
  117. )
  118. describe("HttpApi handler context inheritance", () => {
  119. // Mirrors handlers/session.ts:281 promptAsync. The forked fiber inherits
  120. // the request's Context — including InstanceRef and WorkspaceRef provided
  121. // by InstanceContextMiddleware — without any explicit re-provide.
  122. it.live("Effect.forkIn preserves InstanceRef/WorkspaceRef across the fork", () =>
  123. Effect.gen(function* () {
  124. const { dir, workspace } = yield* setupWorkspace("local-fork")
  125. const capture = yield* Deferred.make<Capture>()
  126. yield* serveProbes({
  127. fork: Effect.gen(function* () {
  128. const scope = yield* Scope.Scope
  129. yield* Effect.gen(function* () {
  130. yield* Deferred.succeed(capture, yield* captureInstance)
  131. }).pipe(Effect.forkIn(scope, { startImmediately: true }))
  132. return true
  133. }),
  134. })
  135. const response = yield* HttpClient.post(
  136. `/fork-probe?directory=${encodeURIComponent(dir)}&workspace=${encodeURIComponent(workspace.id)}`,
  137. )
  138. expect(response.status).toBe(200)
  139. const observed = yield* Deferred.await(capture).pipe(Effect.timeout("2 seconds"))
  140. expect(observed.directory).toBe(dir)
  141. expect(observed.workspaceID).toBe(workspace.id)
  142. }),
  143. )
  144. // Mirrors handlers/session.ts:255 prompt — the streaming handler reads
  145. // InstanceRef/WorkspaceRef in the request fiber and re-provides them to
  146. // the Stream.fromEffect body. This test locks in why the explicit
  147. // provides are required: without them the stream body sees undefined.
  148. it.live("Stream.fromEffect body needs explicit provides — inheritance does not carry through", () =>
  149. Effect.gen(function* () {
  150. const { dir, workspace } = yield* setupWorkspace("local-stream")
  151. const withoutCapture = yield* Deferred.make<Capture>()
  152. const withCapture = yield* Deferred.make<Capture>()
  153. yield* serveProbes({
  154. streamWithout: Effect.gen(function* () {
  155. return HttpServerResponse.stream(
  156. Stream.fromEffect(
  157. Effect.gen(function* () {
  158. yield* Deferred.succeed(withoutCapture, yield* captureInstance)
  159. return ""
  160. }),
  161. ).pipe(Stream.encodeText),
  162. { contentType: "application/json" },
  163. )
  164. }),
  165. streamWith: Effect.gen(function* () {
  166. const instance = yield* InstanceRef
  167. const workspaceID = yield* WorkspaceRef
  168. return HttpServerResponse.stream(
  169. Stream.fromEffect(
  170. Effect.gen(function* () {
  171. yield* Deferred.succeed(withCapture, yield* captureInstance)
  172. return ""
  173. }).pipe(Effect.provideService(InstanceRef, instance), Effect.provideService(WorkspaceRef, workspaceID)),
  174. ).pipe(Stream.encodeText),
  175. { contentType: "application/json" },
  176. )
  177. }),
  178. })
  179. const queryString = `directory=${encodeURIComponent(dir)}&workspace=${encodeURIComponent(workspace.id)}`
  180. const responseWithout = yield* HttpClient.post(`/stream-probe-without?${queryString}`)
  181. yield* responseWithout.text
  182. const responseWith = yield* HttpClient.post(`/stream-probe-with?${queryString}`)
  183. yield* responseWith.text
  184. const without = yield* Deferred.await(withoutCapture).pipe(Effect.timeout("2 seconds"))
  185. expect(without.directory).toBeUndefined()
  186. expect(without.workspaceID).toBeUndefined()
  187. const withProvide = yield* Deferred.await(withCapture).pipe(Effect.timeout("2 seconds"))
  188. expect(withProvide.directory).toBe(dir)
  189. expect(withProvide.workspaceID).toBe(workspace.id)
  190. }),
  191. )
  192. })