|
| 1 | +import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 2 | +import { assert, describe, it } from "@effect/vitest"; |
| 3 | +import { |
| 4 | + AuthOrchestrationReadScope, |
| 5 | + AuthRelayReadScope, |
| 6 | + type AuthEnvironmentScope, |
| 7 | + ProviderDriverKind, |
| 8 | + ProviderInstanceId, |
| 9 | + ProviderSessionId, |
| 10 | + ThreadId, |
| 11 | + WS_METHODS, |
| 12 | + WsRpcGroup, |
| 13 | +} from "@t3tools/contracts"; |
| 14 | +import * as Deferred from "effect/Deferred"; |
| 15 | +import * as Effect from "effect/Effect"; |
| 16 | +import * as Layer from "effect/Layer"; |
| 17 | +import * as Queue from "effect/Queue"; |
| 18 | +import * as TestClock from "effect/testing/TestClock"; |
| 19 | +import { RpcMessage, RpcSerialization, RpcServer } from "effect/rpc"; |
| 20 | + |
| 21 | +import * as RpcAuthorization from "../auth/RpcAuthorization.ts"; |
| 22 | +import { RPC_REQUIRED_SCOPES } from "../auth/RpcAuthorization.ts"; |
| 23 | +import * as ProviderEventLoggers from "../provider/ProviderEventLoggers.ts"; |
| 24 | +import * as ProviderOrchestrationAdapterInfrastructure from "../provider/ProviderOrchestrationAdapterInfrastructure.ts"; |
| 25 | +import * as ContributionStatusStore from "./ContributionStatusStore.ts"; |
| 26 | + |
| 27 | +const TAG = WS_METHODS.subscribeContributionStatus; |
| 28 | +const THREAD = ThreadId.make("thread-1"); |
| 29 | +const SOURCE = { |
| 30 | + kind: "provider-session", |
| 31 | + providerSessionId: ProviderSessionId.make("session-1"), |
| 32 | + providerInstanceId: ProviderInstanceId.make("pi"), |
| 33 | + driver: ProviderDriverKind.make("pi"), |
| 34 | +} as const; |
| 35 | +const encodedEntry = (texts: ReadonlyArray<string>) => ({ |
| 36 | + threadId: THREAD, |
| 37 | + source: SOURCE, |
| 38 | + items: texts.map((text, index) => ({ key: `k${index}`, text })), |
| 39 | +}); |
| 40 | + |
| 41 | +// The server group narrowed to this RPC; it keeps the group's scope middleware. |
| 42 | +const group = WsRpcGroup.omit( |
| 43 | + ...[...WsRpcGroup.requests.keys()].filter( |
| 44 | + (tag): tag is Exclude<keyof typeof RPC_REQUIRED_SCOPES, typeof TAG> => tag !== TAG, |
| 45 | + ), |
| 46 | +); |
| 47 | + |
| 48 | +/** |
| 49 | + * Serves `subscribeContributionStatus` as ws.ts does (the store's subscription |
| 50 | + * stream behind the connection's scope middleware) over an in-memory RPC protocol. |
| 51 | + */ |
| 52 | +const serveStatus = Effect.fn("serveStatus")(function* ( |
| 53 | + store: ContributionStatusStore.ContributionStatusStoreShape, |
| 54 | + scopes: ReadonlyArray<AuthEnvironmentScope>, |
| 55 | +) { |
| 56 | + const responses = yield* Queue.unbounded<RpcMessage.FromServerEncoded>(); |
| 57 | + const receive = yield* Deferred.make<Parameters<RpcServer.Protocol["Service"]["run"]>[0]>(); |
| 58 | + const protocol = yield* RpcServer.Protocol.make((write) => |
| 59 | + Effect.gen(function* () { |
| 60 | + yield* Deferred.succeed(receive, write); |
| 61 | + const serialization = yield* RpcSerialization.RpcSerialization; |
| 62 | + return { |
| 63 | + disconnects: yield* Queue.unbounded<number>(), |
| 64 | + send: (_clientId, response) => Queue.offer(responses, response), |
| 65 | + end: () => Effect.void, |
| 66 | + clientIds: Effect.succeed(new Set([0])), |
| 67 | + initialMessage: Effect.succeedNone, |
| 68 | + supportsAck: false, |
| 69 | + supportsTransferables: false, |
| 70 | + supportsSpanPropagation: false, |
| 71 | + supportsNotifications: true, |
| 72 | + codecFor: serialization.codecFor, |
| 73 | + }; |
| 74 | + }), |
| 75 | + ); |
| 76 | + yield* RpcServer.make(group).pipe( |
| 77 | + Effect.provide( |
| 78 | + Layer.merge( |
| 79 | + group.toLayerHandler(TAG, () => ContributionStatusStore.subscriptionStream(store)), |
| 80 | + RpcAuthorization.layer(scopes), |
| 81 | + ), |
| 82 | + ), |
| 83 | + Effect.provideService(RpcServer.Protocol, protocol), |
| 84 | + Effect.forkScoped, |
| 85 | + ); |
| 86 | + const write = yield* Deferred.await(receive); |
| 87 | + return { |
| 88 | + subscribe: (id: string) => |
| 89 | + write(0, { _tag: "Request", id, tag: TAG, payload: {}, headers: [] }), |
| 90 | + interrupt: (id: string) => write(0, { _tag: "Interrupt", requestId: id }), |
| 91 | + /** The next frame the client receives; the store publishes one per visible change. */ |
| 92 | + next: Queue.take(responses), |
| 93 | + /** Lets server fibers run so a frame that would be sent is in the queue. */ |
| 94 | + pending: TestClock.adjust(0).pipe(Effect.andThen(Queue.size(responses))), |
| 95 | + }; |
| 96 | +}); |
| 97 | + |
| 98 | +const chunk = ( |
| 99 | + requestId: string, |
| 100 | + entries: ReadonlyArray<ReturnType<typeof encodedEntry>>, |
| 101 | +): RpcMessage.FromServerEncoded => ({ _tag: "Chunk", requestId, values: [{ entries }] }); |
| 102 | + |
| 103 | +describe("subscribeContributionStatus", () => { |
| 104 | + it.effect("streams the current snapshot, replacements, and a fresh snapshot on resubscribe", () => |
| 105 | + Effect.gen(function* () { |
| 106 | + const store = yield* ContributionStatusStore.make(); |
| 107 | + const handle = yield* store.openSource(SOURCE); |
| 108 | + yield* handle.bindThread(THREAD); |
| 109 | + yield* handle.set({ key: "k0", text: "plan" }); |
| 110 | + const client = yield* serveStatus(store, [AuthOrchestrationReadScope]); |
| 111 | + |
| 112 | + yield* client.subscribe("1"); |
| 113 | + assert.deepStrictEqual(yield* client.next, chunk("1", [encodedEntry(["plan"])])); |
| 114 | + |
| 115 | + yield* handle.set({ key: "k0", text: "build" }); |
| 116 | + assert.deepStrictEqual(yield* client.next, chunk("1", [encodedEntry(["build"])])); |
| 117 | + yield* handle.clear("k0"); |
| 118 | + assert.deepStrictEqual(yield* client.next, chunk("1", [])); |
| 119 | + |
| 120 | + // A reconnect is a new subscription whose first frame is the current state. |
| 121 | + yield* handle.set({ key: "k0", text: "review" }); |
| 122 | + assert.deepStrictEqual(yield* client.next, chunk("1", [encodedEntry(["review"])])); |
| 123 | + yield* client.subscribe("2"); |
| 124 | + assert.deepStrictEqual(yield* client.next, chunk("2", [encodedEntry(["review"])])); |
| 125 | + |
| 126 | + // An interrupted subscription stops receiving frames; the other keeps going. |
| 127 | + yield* client.interrupt("1"); |
| 128 | + assert.strictEqual((yield* client.next)._tag, "Exit"); |
| 129 | + yield* handle.set({ key: "k0", text: "done" }); |
| 130 | + assert.deepStrictEqual(yield* client.next, chunk("2", [encodedEntry(["done"])])); |
| 131 | + assert.strictEqual(yield* client.pending, 0); |
| 132 | + }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped), |
| 133 | + ); |
| 134 | + |
| 135 | + it.effect("refuses a client without the orchestration read scope", () => |
| 136 | + Effect.gen(function* () { |
| 137 | + const store = yield* ContributionStatusStore.make(); |
| 138 | + const handle = yield* store.openSource(SOURCE); |
| 139 | + yield* handle.bindThread(THREAD); |
| 140 | + yield* handle.set({ key: "k0", text: "plan" }); |
| 141 | + const client = yield* serveStatus(store, [AuthRelayReadScope]); |
| 142 | + |
| 143 | + yield* client.subscribe("1"); |
| 144 | + assert.deepStrictEqual(yield* client.next, { |
| 145 | + _tag: "Exit", |
| 146 | + requestId: "1", |
| 147 | + exit: { |
| 148 | + _tag: "Failure", |
| 149 | + cause: [ |
| 150 | + { |
| 151 | + _tag: "Fail", |
| 152 | + error: { |
| 153 | + _tag: "EnvironmentAuthorizationError", |
| 154 | + message: `The authenticated token is missing required scope: ${AuthOrchestrationReadScope}.`, |
| 155 | + requiredScope: AuthOrchestrationReadScope, |
| 156 | + }, |
| 157 | + }, |
| 158 | + ], |
| 159 | + }, |
| 160 | + }); |
| 161 | + }).pipe(Effect.provide(RpcSerialization.layerJson), Effect.scoped), |
| 162 | + ); |
| 163 | + |
| 164 | + it.effect("shares one store between provider adapters and the WebSocket stream", () => |
| 165 | + Effect.gen(function* () { |
| 166 | + // Mirrors server.ts: adapters get the store through the provider |
| 167 | + // infrastructure inside an unwrapped instance-registry layer, while the |
| 168 | + // WebSocket layer reads it from the runtime's own reference. |
| 169 | + const producer = Layer.unwrap( |
| 170 | + Effect.succeed( |
| 171 | + Layer.effectDiscard( |
| 172 | + Effect.gen(function* () { |
| 173 | + const store = yield* ContributionStatusStore.ContributionStatusStore; |
| 174 | + const handle = yield* store.openSource(SOURCE); |
| 175 | + yield* handle.bindThread(THREAD); |
| 176 | + yield* handle.set({ key: "k0", text: "from adapter" }); |
| 177 | + }), |
| 178 | + ).pipe(Layer.provide(ProviderOrchestrationAdapterInfrastructure.layer)), |
| 179 | + ), |
| 180 | + ); |
| 181 | + // As in server.ts, the registry layer sits below the store reference, so |
| 182 | + // the producer only sees the store its own infrastructure provides. |
| 183 | + const runtime = ContributionStatusStore.layer.pipe( |
| 184 | + Layer.provideMerge(producer), |
| 185 | + Layer.provide( |
| 186 | + Layer.merge( |
| 187 | + NodeServices.layer, |
| 188 | + Layer.succeed( |
| 189 | + ProviderEventLoggers.ProviderEventLoggers, |
| 190 | + ProviderEventLoggers.NoOpProviderEventLoggers, |
| 191 | + ), |
| 192 | + ), |
| 193 | + ), |
| 194 | + ); |
| 195 | + |
| 196 | + const snapshot = yield* Effect.gen(function* () { |
| 197 | + const store = yield* ContributionStatusStore.ContributionStatusStore; |
| 198 | + return yield* store.snapshot; |
| 199 | + }).pipe(Effect.provide(runtime)); |
| 200 | + assert.deepStrictEqual(snapshot.entries, [ |
| 201 | + { threadId: THREAD, source: SOURCE, items: [{ key: "k0", text: "from adapter" }] }, |
| 202 | + ]); |
| 203 | + }), |
| 204 | + ); |
| 205 | +}); |
0 commit comments