The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import * as Domain from "@alchemy.run/domain"; |
| 2 | import * as DomainHttp from "@alchemy.run/domain/Http"; |
| 3 | import { InMemory } from "@alchemy.run/domain/InMemory"; |
| 4 | import { describe, expect, it } from "@alchemy.run/test"; |
| 5 | import * as BunHttpServer from "@effect/platform-bun/BunHttpServer"; |
| 6 | import * as Cause from "effect/Cause"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Sse from "effect/encoding/Sse"; |
| 9 | import * as Exit from "effect/Exit"; |
| 10 | import * as Fiber from "effect/Fiber"; |
| 11 | import * as HttpApi from "effect/http-api/HttpApi"; |
| 12 | import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; |
| 13 | import type * as HttpApiGroup from "effect/http-api/HttpApiGroup"; |
| 14 | import * as HttpApiSchema from "effect/http-api/HttpApiSchema"; |
| 15 | import * as OpenApi from "effect/http-api/OpenApi"; |
| 16 | import * as Headers from "effect/http/Headers"; |
| 17 | import * as HttpClient from "effect/http/HttpClient"; |
| 18 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 19 | import * as HttpRouter from "effect/http/HttpRouter"; |
| 20 | import * as Layer from "effect/Layer"; |
| 21 | import * as Option from "effect/Option"; |
| 22 | import * as RpcMiddleware from "effect/rpc/RpcMiddleware"; |
| 23 | import * as Schema from "effect/Schema"; |
| 24 | import * as Stream from "effect/Stream"; |
| 25 | |
| 26 | // ---------------------------------------------------------------- a wallet domain |
| 27 | |
| 28 | const WalletId = Schema.String.pipe(Schema.brand("WalletId")); |
| 29 | |
| 30 | /** Who is calling. The session middleware provides it from an `x-owner` header. */ |
| 31 | class Owner extends Domain.RequestContext<Owner>()("Test/Owner", Schema.String) {} |
| 32 | class Unauthenticated extends Domain.Rejection("Unauthenticated") {} |
| 33 | class Session extends RpcMiddleware.Service<Session, { provides: Owner }>()("Test/Session", { |
| 34 | // A middleware error answers with the status it is annotated with. |
| 35 | error: Unauthenticated.pipe(HttpApiSchema.status(401)), |
| 36 | }) {} |
| 37 | const SessionLive = Layer.succeed(Session, (effect, { headers }) => |
| 38 | Option.match(Headers.get(headers, "x-owner"), { |
| 39 | onNone: () => Effect.fail(new Unauthenticated()), |
| 40 | onSome: (owner) => Effect.provideService(effect, Owner, owner), |
| 41 | }), |
| 42 | ); |
| 43 | |
| 44 | class Deposited extends Domain.Event("Deposited", { |
| 45 | owner: Schema.String, |
| 46 | amount: Schema.Int, |
| 47 | at: Schema.DateTimeUtc, |
| 48 | }) {} |
| 49 | class OverLimit extends Domain.Rejection("OverLimit", { limit: Schema.Int }) {} |
| 50 | /** Its status is Effect's own `httpApiStatus` annotation, which every HttpApi reads. */ |
| 51 | class NotOwner extends Domain.Rejection("NotOwner", {}, { httpApiStatus: 403 }) {} |
| 52 | |
| 53 | class Deposit extends Domain.Command("Deposit", { |
| 54 | target: WalletId, |
| 55 | middleware: [Session], |
| 56 | // `at` is a transform (an ISO string on the wire, a DateTime in `decide`). |
| 57 | input: { amount: Schema.Int, at: Schema.DateTimeUtc }, |
| 58 | events: [Deposited], |
| 59 | rejects: [OverLimit], |
| 60 | reply: { balance: Schema.Int, at: Schema.NullOr(Schema.DateTimeUtc) }, |
| 61 | }) {} |
| 62 | |
| 63 | const WalletState = Schema.Struct({ |
| 64 | owner: Schema.NullOr(Schema.String), |
| 65 | balance: Schema.Int, |
| 66 | at: Schema.NullOr(Schema.DateTimeUtc), |
| 67 | }); |
| 68 | |
| 69 | class Wallet extends Domain.Aggregate("Wallet", { |
| 70 | id: WalletId, |
| 71 | state: WalletState, |
| 72 | initial: { owner: null, balance: 0, at: null }, |
| 73 | commands: [Deposit], |
| 74 | decide: { |
| 75 | Deposit: Effect.fn(function* (_, cmd) { |
| 76 | if (cmd.amount > 100) return yield* new OverLimit({ limit: 100 }); |
| 77 | return [new Deposited({ owner: yield* Owner, amount: cmd.amount, at: cmd.at })]; |
| 78 | }), |
| 79 | }, |
| 80 | evolve: { |
| 81 | Deposited: (s, e) => ({ owner: e.owner, balance: s.balance + e.amount, at: e.at }), |
| 82 | }, |
| 83 | reply: { Deposit: (s) => ({ balance: s.balance, at: s.at }) }, |
| 84 | read: { middleware: [Session] }, |
| 85 | }) {} |
| 86 | |
| 87 | /** Only the wallet's owner reads its balance. */ |
| 88 | class Balance extends Domain.View("Balance", { |
| 89 | from: [Wallet], |
| 90 | key: Wallet, |
| 91 | middleware: [Session], |
| 92 | rejects: [NotOwner], |
| 93 | state: Schema.Struct({ owner: Schema.String, balance: Schema.Int }), |
| 94 | initial: { owner: "", balance: 0 }, |
| 95 | evolve: { Deposited: (s, e) => ({ owner: e.owner, balance: s.balance + e.amount }) }, |
| 96 | validate: Effect.fn(function* (_request, s) { |
| 97 | if (s !== null && s.owner !== (yield* Owner)) return yield* new NotOwner(); |
| 98 | }), |
| 99 | }) {} |
| 100 | |
| 101 | // ---------------------------------------------------------------- the HTTP surface |
| 102 | |
| 103 | /** |
| 104 | * A session with a client half: a typed client attaches the caller as |
| 105 | * `x-owner`. The server holds one for its own calls, as "server". |
| 106 | */ |
| 107 | class SignedSession extends RpcMiddleware.Service<SignedSession, { provides: Owner }>()( |
| 108 | "Test/SignedSession", |
| 109 | { error: Unauthenticated.pipe(HttpApiSchema.status(401)), requiredForClient: true }, |
| 110 | ) {} |
| 111 | const SignedSessionLive = Layer.succeed(SignedSession, (effect, { headers }) => |
| 112 | Option.match(Headers.get(headers, "x-owner"), { |
| 113 | onNone: () => Effect.fail(new Unauthenticated()), |
| 114 | onSome: (owner) => Effect.provideService(effect, Owner, owner), |
| 115 | }), |
| 116 | ); |
| 117 | const ServerCredential = RpcMiddleware.layerClient(SignedSession, ({ request, next }) => |
| 118 | next({ ...request, headers: Headers.set(request.headers, "x-owner", "server") }), |
| 119 | ); |
| 120 | |
| 121 | class Signed extends Domain.Event("Signed", { owner: Schema.String }) {} |
| 122 | class Sign extends Domain.Command("Sign", { |
| 123 | target: Schema.String, |
| 124 | middleware: [SignedSession], |
| 125 | events: [Signed], |
| 126 | reply: { owner: Schema.NullOr(Schema.String) }, |
| 127 | }) {} |
| 128 | class Ledger extends Domain.Aggregate("Ledger", { |
| 129 | id: Schema.String, |
| 130 | state: Schema.Struct({ owner: Schema.NullOr(Schema.String) }), |
| 131 | initial: { owner: null }, |
| 132 | commands: [Sign], |
| 133 | decide: { |
| 134 | Sign: Effect.fn(function* () { |
| 135 | return [new Signed({ owner: yield* Owner })]; |
| 136 | }), |
| 137 | }, |
| 138 | evolve: { Signed: (_, e) => ({ owner: e.owner }) }, |
| 139 | reply: { Sign: (s) => ({ owner: s.owner }) }, |
| 140 | }) {} |
| 141 | class Wallets extends Domain.Model("HttpWallets", { |
| 142 | aggregates: [Wallet, Ledger], |
| 143 | views: [Balance], |
| 144 | }) {} |
| 145 | class WalletApi extends Domain.Api("WalletApi", { |
| 146 | model: Wallets, |
| 147 | commands: ["Deposit"], |
| 148 | aggregates: ["Wallet"], |
| 149 | }) {} |
| 150 | class LedgerApi extends Domain.Api("LedgerApi", { |
| 151 | model: Wallets, |
| 152 | commands: ["Sign"], |
| 153 | views: [], |
| 154 | }) {} |
| 155 | |
| 156 | /** Every call the Api serves. */ |
| 157 | const WalletHttp = DomainHttp.toHttpApi(WalletApi); |
| 158 | |
| 159 | /** An Api for HTTP clients that may only deposit: publishing less is a smaller Api. */ |
| 160 | class DepositOnlyApi extends Domain.Api("DepositOnlyApi", { |
| 161 | model: Wallets, |
| 162 | commands: ["Deposit"], |
| 163 | views: [], |
| 164 | aggregates: [], |
| 165 | }) {} |
| 166 | |
| 167 | /** The hosted model, its middleware, and an in-process Bun server with a client for it. */ |
| 168 | const Hosted = Layer.mergeAll( |
| 169 | SessionLive, |
| 170 | SignedSessionLive, |
| 171 | ServerCredential, |
| 172 | Wallets.layer(Layer.empty), |
| 173 | ).pipe(Layer.provide(InMemory), Layer.provideMerge(BunHttpServer.layerTest)); |
| 174 | |
| 175 | const serve = <Id extends string, Groups extends HttpApiGroup.Constraint>( |
| 176 | api: HttpApi.HttpApi<Id, Groups>, |
| 177 | handlers: Layer.Layer<HttpApiGroup.ToService<Id, Groups>, never, Layer.Success<typeof Hosted>>, |
| 178 | ) => |
| 179 | HttpRouter.serve(HttpApiBuilder.layer(api), { disableListenLog: true, disableLogger: true }).pipe( |
| 180 | Layer.provide(handlers), |
| 181 | Layer.provideMerge(Hosted), |
| 182 | ); |
| 183 | |
| 184 | /** The surface's own HttpApi, served. */ |
| 185 | const Served = serve(WalletHttp.api, WalletHttp.layer); |
| 186 | |
| 187 | /** An app's own HttpApi that serves the group under `/v1`. */ |
| 188 | const AppApi = HttpApi.make("App").add(WalletHttp.group.prefix("/v1")); |
| 189 | |
| 190 | interface SendOptions { |
| 191 | readonly owner?: string; |
| 192 | readonly body?: unknown; |
| 193 | readonly headers?: Record<string, string>; |
| 194 | } |
| 195 | |
| 196 | const execute = (method: "GET" | "POST", path: string, options: SendOptions) => |
| 197 | Effect.gen(function* () { |
| 198 | const client = yield* HttpClient.HttpClient; |
| 199 | let request = HttpClientRequest.make(method)(path).pipe( |
| 200 | HttpClientRequest.setHeaders(options.headers ?? {}), |
| 201 | ); |
| 202 | if (options.owner) request = HttpClientRequest.setHeader(request, "x-owner", options.owner); |
| 203 | if (options.body !== undefined) |
| 204 | request = HttpClientRequest.bodyJsonUnsafe(request, options.body); |
| 205 | return yield* client.execute(request); |
| 206 | }); |
| 207 | |
| 208 | const send = (method: "GET" | "POST", path: string, options: SendOptions = {}) => |
| 209 | Effect.gen(function* () { |
| 210 | const response = yield* execute(method, path, options); |
| 211 | const text = yield* response.text; |
| 212 | return { status: response.status, body: text === "" ? undefined : JSON.parse(text) }; |
| 213 | }); |
| 214 | |
| 215 | /** |
| 216 | * Open a live read. The status arrives once the read has its first value, so |
| 217 | * the read is subscribed when this returns; `take(n)` collects the next `n` |
| 218 | * SSE events, each with its parsed `data`. |
| 219 | */ |
| 220 | const listen = (path: string, options: SendOptions = {}) => |
| 221 | Effect.gen(function* () { |
| 222 | const response = yield* execute("GET", path, options); |
| 223 | const contentType = response.headers["content-type"]; |
| 224 | const take = (n: number) => |
| 225 | response.stream.pipe( |
| 226 | Stream.decodeText, |
| 227 | Stream.pipeThroughChannel(Sse.decode()), |
| 228 | Stream.take(n), |
| 229 | Stream.map((event) => ({ event: event.event, data: JSON.parse(event.data) })), |
| 230 | Stream.runCollect, |
| 231 | Effect.timeout("5 seconds"), |
| 232 | ); |
| 233 | return { status: response.status, contentType, take }; |
| 234 | }); |
| 235 | |
| 236 | const at = "2026-10-25T12:00:00.000Z"; |
| 237 | |
| 238 | // ---------------------------------------------------------------- tests |
| 239 | |
| 240 | describe("Domain toHttpApi", { tags: ["unit", "local"] }, () => { |
| 241 | it.live("a command endpoint runs the command and answers with its receipt", () => |
| 242 | Effect.gen(function* () { |
| 243 | const { status, body } = yield* send("POST", "/Deposit", { |
| 244 | owner: "sam", |
| 245 | body: { target: "w-1", input: { amount: 40, at } }, |
| 246 | }); |
| 247 | expect(status).toBe(200); |
| 248 | // The transform is decoded once on the way in and encoded once on the way out. |
| 249 | expect(body).toEqual({ reply: { balance: 40, at }, stream: expect.any(String), version: 1 }); |
| 250 | }).pipe(Effect.provide(Served)), |
| 251 | ); |
| 252 | |
| 253 | it.live("a rejection answers with its status and its typed body", () => |
| 254 | Effect.gen(function* () { |
| 255 | const over = yield* send("POST", "/Deposit", { |
| 256 | owner: "sam", |
| 257 | body: { target: "w-1", input: { amount: 500, at } }, |
| 258 | }); |
| 259 | // A declared rejection with no status of its own is a 422. |
| 260 | expect(over).toEqual({ status: 422, body: { _tag: "OverLimit", limit: 100 } }); |
| 261 | |
| 262 | // The middleware runs as for any client, and its error keeps its annotated status. |
| 263 | const anonymous = yield* send("POST", "/Deposit", { |
| 264 | body: { target: "w-1", input: { amount: 1, at } }, |
| 265 | }); |
| 266 | expect(anonymous).toEqual({ status: 401, body: { _tag: "Unauthenticated" } }); |
| 267 | |
| 268 | // Input the command's schema refuses never reaches the model. |
| 269 | const malformed = yield* send("POST", "/Deposit", { |
| 270 | owner: "sam", |
| 271 | body: { target: "w-1", input: { amount: "lots", at } }, |
| 272 | }); |
| 273 | expect(malformed.status).toBe(400); |
| 274 | }).pipe(Effect.provide(Served)), |
| 275 | ); |
| 276 | |
| 277 | it.live("a read endpoint answers with the key's state, read after a write", () => |
| 278 | Effect.gen(function* () { |
| 279 | const { body: receipt } = yield* send("POST", "/Deposit", { |
| 280 | owner: "kim", |
| 281 | body: { target: "w-2", input: { amount: 25, at } }, |
| 282 | }); |
| 283 | const read = yield* send( |
| 284 | "GET", |
| 285 | `/Balance/w-2?stream=${encodeURIComponent(receipt.stream)}&version=${receipt.version}`, |
| 286 | { owner: "kim" }, |
| 287 | ); |
| 288 | expect(read).toEqual({ status: 200, body: { owner: "kim", balance: 25 } }); |
| 289 | |
| 290 | // The view's `validate` runs, and its rejection takes the status `toHttpApi` gave it. |
| 291 | const someoneElse = yield* send("GET", "/Balance/w-2", { owner: "sam" }); |
| 292 | expect(someoneElse).toEqual({ status: 403, body: { _tag: "NotOwner" } }); |
| 293 | |
| 294 | // A key with nothing in it reads as `null`, like the Api's own `get`. |
| 295 | const empty = yield* send("GET", "/Balance/w-9", { owner: "kim" }); |
| 296 | expect(empty).toEqual({ status: 200, body: null }); |
| 297 | |
| 298 | // `stream` without `version` is not a position to wait for. |
| 299 | const half = yield* send("GET", "/Balance/w-2?stream=x", { owner: "kim" }); |
| 300 | expect(half.status).toBe(400); |
| 301 | }).pipe(Effect.provide(Served)), |
| 302 | ); |
| 303 | |
| 304 | it.live("a snapshot endpoint answers with the state and its cursor", () => |
| 305 | Effect.gen(function* () { |
| 306 | yield* send("POST", "/Deposit", { |
| 307 | owner: "kim", |
| 308 | body: { target: "w-4", input: { amount: 7, at } }, |
| 309 | }); |
| 310 | const snapshot = yield* send("GET", "/Balance/w-4/snapshot", { owner: "kim" }); |
| 311 | expect(snapshot).toEqual({ |
| 312 | status: 200, |
| 313 | body: { state: { owner: "kim", balance: 7 }, cursor: expect.any(Number) }, |
| 314 | }); |
| 315 | // Its own path: `get` still answers with the bare state. |
| 316 | expect((yield* send("GET", "/Balance/w-4", { owner: "kim" })).body).toEqual({ |
| 317 | owner: "kim", |
| 318 | balance: 7, |
| 319 | }); |
| 320 | }).pipe(Effect.provide(Served)), |
| 321 | ); |
| 322 | |
| 323 | it.live("a watch endpoint streams the state, then every change, as Server-Sent Events", () => |
| 324 | Effect.gen(function* () { |
| 325 | yield* send("POST", "/Deposit", { |
| 326 | owner: "kim", |
| 327 | body: { target: "w-5", input: { amount: 10, at } }, |
| 328 | }); |
| 329 | const watch = yield* listen("/Balance/w-5/watch", { owner: "kim" }); |
| 330 | expect(watch.status).toBe(200); |
| 331 | expect(watch.contentType).toContain("text/event-stream"); |
| 332 | const events = yield* Effect.forkChild(watch.take(2)); |
| 333 | yield* send("POST", "/Deposit", { |
| 334 | owner: "kim", |
| 335 | body: { target: "w-5", input: { amount: 5, at } }, |
| 336 | }); |
| 337 | expect(yield* Fiber.join(events)).toEqual([ |
| 338 | { |
| 339 | event: "message", |
| 340 | data: { state: { owner: "kim", balance: 10 }, cursor: expect.any(Number) }, |
| 341 | }, |
| 342 | { |
| 343 | event: "message", |
| 344 | data: { state: { owner: "kim", balance: 15 }, cursor: expect.any(Number) }, |
| 345 | }, |
| 346 | ]); |
| 347 | }).pipe(Effect.provide(Served)), |
| 348 | ); |
| 349 | |
| 350 | it.live("a live read's middleware and validate answer with their status before it streams", () => |
| 351 | Effect.gen(function* () { |
| 352 | yield* send("POST", "/Deposit", { |
| 353 | owner: "kim", |
| 354 | body: { target: "w-6", input: { amount: 1, at } }, |
| 355 | }); |
| 356 | // The session middleware refuses a caller with no owner. |
| 357 | expect(yield* send("GET", "/Balance/w-6/watch")).toEqual({ |
| 358 | status: 401, |
| 359 | body: { _tag: "Unauthenticated" }, |
| 360 | }); |
| 361 | // The view's `validate` refuses someone else's wallet. |
| 362 | expect(yield* send("GET", "/Balance/w-6/watch", { owner: "sam" })).toEqual({ |
| 363 | status: 403, |
| 364 | body: { _tag: "NotOwner" }, |
| 365 | }); |
| 366 | // An aggregate's `read` middleware guards its events too. |
| 367 | expect((yield* send("GET", "/Wallet/w-6/events")).status).toBe(401); |
| 368 | }).pipe(Effect.provide(Served)), |
| 369 | ); |
| 370 | |
| 371 | it.live("a change validate refuses ends the stream with a typed failure event", () => |
| 372 | Effect.gen(function* () { |
| 373 | yield* send("POST", "/Deposit", { |
| 374 | owner: "kim", |
| 375 | body: { target: "w-7", input: { amount: 1, at } }, |
| 376 | }); |
| 377 | const watch = yield* listen("/Balance/w-7/watch", { owner: "kim" }); |
| 378 | const events = yield* Effect.forkChild(watch.take(3)); |
| 379 | // Sam's deposit makes Sam the owner, so Kim may no longer read the wallet. |
| 380 | yield* send("POST", "/Deposit", { |
| 381 | owner: "sam", |
| 382 | body: { target: "w-7", input: { amount: 1, at } }, |
| 383 | }); |
| 384 | const [first, failure, ...rest] = yield* Fiber.join(events); |
| 385 | expect(first!.data.state).toEqual({ owner: "kim", balance: 1 }); |
| 386 | expect(failure!.event).toBe("effect/http-api/stream/failure"); |
| 387 | // A typed failure, not a defect: the Cause of the rejection `validate` returned. |
| 388 | expect(failure!.data).toEqual([{ _tag: "Fail", error: { _tag: "NotOwner" } }]); |
| 389 | // The failure ends the stream. |
| 390 | expect(rest).toEqual([]); |
| 391 | }).pipe(Effect.provide(Served)), |
| 392 | ); |
| 393 | |
| 394 | it.live("an events endpoint streams history, a CaughtUp frame, then live events", () => |
| 395 | Effect.gen(function* () { |
| 396 | yield* send("POST", "/Deposit", { |
| 397 | owner: "kim", |
| 398 | body: { target: "w-8", input: { amount: 2, at } }, |
| 399 | }); |
| 400 | yield* send("POST", "/Deposit", { |
| 401 | owner: "kim", |
| 402 | body: { target: "w-8", input: { amount: 3, at } }, |
| 403 | }); |
| 404 | const all = yield* listen("/Wallet/w-8/events", { owner: "kim" }); |
| 405 | const history = yield* Effect.forkChild(all.take(4)); |
| 406 | yield* send("POST", "/Deposit", { |
| 407 | owner: "kim", |
| 408 | body: { target: "w-8", input: { amount: 4, at } }, |
| 409 | }); |
| 410 | const frames = (yield* Fiber.join(history)).map(({ data }) => |
| 411 | data._tag === "CaughtUp" ? "caught up" : data.event.amount, |
| 412 | ); |
| 413 | expect(frames).toEqual([2, 3, "caught up", 4]); |
| 414 | |
| 415 | // `after` resumes from a cursor: only what came after it, then the frame. |
| 416 | const [, second] = (yield* Fiber.join(history)).map(({ data }) => data); |
| 417 | const resumed = yield* listen(`/Wallet/w-8/events?after=${second.envelope.seq}`, { |
| 418 | owner: "kim", |
| 419 | }); |
| 420 | const tail = (yield* resumed.take(2)).map(({ data }) => |
| 421 | data._tag === "CaughtUp" ? "caught up" : data.event.amount, |
| 422 | ); |
| 423 | expect(tail).toEqual([4, "caught up"]); |
| 424 | }).pipe(Effect.provide(Served)), |
| 425 | ); |
| 426 | |
| 427 | it.live("a middleware's client half never replaces the HTTP caller's headers", () => |
| 428 | Effect.gen(function* () { |
| 429 | // The server holds a credential for its own calls; an HTTP caller signs as itself. |
| 430 | expect( |
| 431 | yield* send("POST", "/Sign", { owner: "alice", body: { target: "l-1", input: {} } }), |
| 432 | ).toEqual({ |
| 433 | status: 200, |
| 434 | body: { reply: { owner: "alice" }, stream: "Ledger/l-1", version: 1 }, |
| 435 | }); |
| 436 | // A caller without one is refused, not signed in as the server. |
| 437 | expect(yield* send("POST", "/Sign", { body: { target: "l-2", input: {} } })).toEqual({ |
| 438 | status: 401, |
| 439 | body: { _tag: "Unauthenticated" }, |
| 440 | }); |
| 441 | }).pipe( |
| 442 | Effect.provide( |
| 443 | (() => { |
| 444 | const LedgerHttp = DomainHttp.toHttpApi(LedgerApi); |
| 445 | return serve(LedgerHttp.api, LedgerHttp.layer); |
| 446 | })(), |
| 447 | ), |
| 448 | ), |
| 449 | ); |
| 450 | |
| 451 | it.live("serves the group inside your own HttpApi, under its prefix", () => |
| 452 | Effect.gen(function* () { |
| 453 | const deposit = yield* send("POST", "/v1/Deposit", { |
| 454 | owner: "sam", |
| 455 | body: { target: "w-3", input: { amount: 5, at } }, |
| 456 | }); |
| 457 | expect(deposit.status).toBe(200); |
| 458 | expect((yield* send("POST", "/Deposit", { owner: "sam", body: {} })).status).toBe(404); |
| 459 | }).pipe(Effect.provide(serve(AppApi, WalletHttp.layerFor(AppApi)))), |
| 460 | ); |
| 461 | |
| 462 | it.live("a smaller Api publishes only its own calls", () => |
| 463 | Effect.gen(function* () { |
| 464 | const deposit = yield* send("POST", "/Deposit", { |
| 465 | owner: "sam", |
| 466 | body: { target: "w-10", input: { amount: 2, at } }, |
| 467 | }); |
| 468 | expect(deposit.status).toBe(200); |
| 469 | expect((yield* send("GET", "/Wallet/w-10", { owner: "sam" })).status).toBe(404); |
| 470 | expect((yield* send("GET", "/Balance/w-10/watch", { owner: "sam" })).status).toBe(404); |
| 471 | }).pipe( |
| 472 | Effect.provide( |
| 473 | (() => { |
| 474 | const DepositOnlyHttp = DomainHttp.toHttpApi(DepositOnlyApi); |
| 475 | return serve(DepositOnlyHttp.api, DepositOnlyHttp.layer); |
| 476 | })(), |
| 477 | ), |
| 478 | ), |
| 479 | ); |
| 480 | |
| 481 | it("the OpenAPI document lists each endpoint with its schemas", () => { |
| 482 | const spec = OpenApi.fromApi(WalletHttp.api); |
| 483 | expect(Object.keys(spec.paths).sort()).toEqual([ |
| 484 | "/Balance/{key}", |
| 485 | "/Balance/{key}/events", |
| 486 | "/Balance/{key}/list", |
| 487 | "/Balance/{key}/snapshot", |
| 488 | "/Balance/{key}/watch", |
| 489 | "/Deposit", |
| 490 | "/Wallet/{key}", |
| 491 | "/Wallet/{key}/events", |
| 492 | "/Wallet/{key}/watch", |
| 493 | ]); |
| 494 | |
| 495 | const deposit = spec.paths["/Deposit"]!.post!; |
| 496 | expect(deposit.operationId).toBe("WalletApi.Deposit"); |
| 497 | const body = JSON.stringify(deposit.requestBody); |
| 498 | for (const field of ["target", "amount", "at", "commandId"]) expect(body).toContain(field); |
| 499 | expect(Object.keys(deposit.responses).sort()).toEqual(["200", "401", "422"]); |
| 500 | expect(JSON.stringify(deposit.responses["422"])).toContain("OverLimit"); |
| 501 | |
| 502 | const balance = spec.paths["/Balance/{key}"]!.get!; |
| 503 | expect(balance.parameters.map((p) => [p.name, p.in]).sort()).toEqual([ |
| 504 | ["key", "path"], |
| 505 | ["stream", "query"], |
| 506 | ["version", "query"], |
| 507 | ]); |
| 508 | // Waiting for a write can time out: `ConsistencyTimeout` is a 422. |
| 509 | expect(Object.keys(balance.responses).sort()).toEqual(["200", "401", "403", "422"]); |
| 510 | expect(JSON.stringify(balance.responses["422"])).toContain("ConsistencyTimeout"); |
| 511 | // A live read is an event stream, with its failures before it starts. |
| 512 | const watch = spec.paths["/Balance/{key}/watch"]!.get!; |
| 513 | expect(Object.keys(watch.responses["200"]!.content ?? {})).toEqual(["text/event-stream"]); |
| 514 | expect(Object.keys(watch.responses).sort()).toEqual(["200", "401", "403"]); |
| 515 | const events = spec.paths["/Wallet/{key}/events"]!.get!; |
| 516 | expect(events.parameters.map((p) => [p.name, p.in]).sort()).toEqual([ |
| 517 | ["after", "query"], |
| 518 | ["key", "path"], |
| 519 | ]); |
| 520 | |
| 521 | // The schemas the document refers to, as components. |
| 522 | const components = JSON.stringify(spec.components.schemas); |
| 523 | for (const tag of ["OverLimit", "Unauthenticated", "NotOwner"]) { |
| 524 | expect(components).toContain(tag); |
| 525 | } |
| 526 | }); |
| 527 | |
| 528 | it("publishes every call the Api serves: commands, views, streams, then aggregates", () => { |
| 529 | expect( |
| 530 | Object.values(WalletHttp.group.endpoints).map((e) => [e.identifier, e.method, e.path]), |
| 531 | ).toEqual([ |
| 532 | ["Deposit", "POST", "/Deposit"], |
| 533 | ["Balance.get", "GET", "/Balance/:key"], |
| 534 | ["Balance.watch", "GET", "/Balance/:key/watch"], |
| 535 | ["Balance.events", "GET", "/Balance/:key/events"], |
| 536 | ["Balance.list", "GET", "/Balance/:key/list"], |
| 537 | ["Balance.snapshot", "GET", "/Balance/:key/snapshot"], |
| 538 | ["Wallet.get", "GET", "/Wallet/:key"], |
| 539 | ["Wallet.watch", "GET", "/Wallet/:key/watch"], |
| 540 | ["Wallet.events", "GET", "/Wallet/:key/events"], |
| 541 | ]); |
| 542 | }); |
| 543 | |
| 544 | it.live("layerFor an HttpApi without the group fails the Layer with a DefinitionError", () => |
| 545 | Effect.gen(function* () { |
| 546 | /** The defect building the surface's Layer dies with. */ |
| 547 | const defectOf = (surface: { readonly layer: Layer.Layer<any, never, any> }) => |
| 548 | Layer.build(surface.layer).pipe( |
| 549 | Effect.provide(Hosted), |
| 550 | Effect.scoped, |
| 551 | Effect.exit, |
| 552 | Effect.map((exit) => (Exit.isFailure(exit) ? Cause.squash(exit.cause) : undefined)), |
| 553 | ); |
| 554 | |
| 555 | // `layerFor` an HttpApi that does not hold the group. |
| 556 | const elsewhere = yield* defectOf({ layer: WalletHttp.layerFor(HttpApi.make("Elsewhere")) }); |
| 557 | expect(elsewhere).toMatchObject({ |
| 558 | _tag: "DefinitionError", |
| 559 | message: "Elsewhere does not hold the WalletApi group: add it first", |
| 560 | }); |
| 561 | }), |
| 562 | ); |
| 563 | }); |