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 { NodeHttpServer } from "@effect/platform-node" |
| 2 | import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient" |
| 3 | import { assert, describe, expect, it } from "@effect/vitest" |
| 4 | import { |
| 5 | Array, |
| 6 | ByteSize, |
| 7 | Cause, |
| 8 | Clock, |
| 9 | Context, |
| 10 | DateTime, |
| 11 | Deferred, |
| 12 | Effect, |
| 13 | Equal, |
| 14 | Exit, |
| 15 | Fiber, |
| 16 | FileSystem, |
| 17 | Layer, |
| 18 | Option, |
| 19 | Redacted, |
| 20 | Ref, |
| 21 | Schema, |
| 22 | SchemaGetter, |
| 23 | SchemaTransformation, |
| 24 | Stream, |
| 25 | Struct |
| 26 | } from "effect" |
| 27 | import { |
| 28 | Cookies, |
| 29 | FetchHttpClient, |
| 30 | HttpBody, |
| 31 | HttpClient, |
| 32 | HttpClientRequest, |
| 33 | type HttpClientResponse, |
| 34 | HttpRouter, |
| 35 | HttpServer, |
| 36 | HttpServerRequest, |
| 37 | HttpServerResponse, |
| 38 | Multipart |
| 39 | } from "effect/http" |
| 40 | import { |
| 41 | HttpApi, |
| 42 | HttpApiBuilder, |
| 43 | HttpApiClient, |
| 44 | HttpApiEndpoint, |
| 45 | HttpApiError, |
| 46 | HttpApiGroup, |
| 47 | HttpApiMiddleware, |
| 48 | HttpApiSchema, |
| 49 | HttpApiSecurity, |
| 50 | HttpApiTest, |
| 51 | OpenApi |
| 52 | } from "effect/http-api" |
| 53 | import type * as Socket from "effect/socket/Socket" |
| 54 | import * as Http from "node:http" |
| 55 | import type * as Net from "node:net" |
| 56 | |
| 57 | function* assertServerText(res: HttpClientResponse.HttpClientResponse, status: number, text: string) { |
| 58 | assert.strictEqual(res.status, status) |
| 59 | assert.strictEqual(yield* res.text, text) |
| 60 | } |
| 61 | |
| 62 | function* assertServerJson(res: HttpClientResponse.HttpClientResponse, status: number, json: unknown) { |
| 63 | assert.strictEqual(res.status, status) |
| 64 | assert.deepStrictEqual(yield* res.json, json) |
| 65 | } |
| 66 | |
| 67 | function* assertClientText<E, R>(res: Effect.Effect<string, E, R>, text: string) { |
| 68 | assert.strictEqual(yield* res, text) |
| 69 | } |
| 70 | |
| 71 | function* assertClientJson<E, R>(res: Effect.Effect<unknown, E, R>, json: unknown) { |
| 72 | assert.deepStrictEqual(yield* res, json) |
| 73 | } |
| 74 | |
| 75 | function* assertClientError<A, E, R>(res: Effect.Effect<A, E, R>, error: E) { |
| 76 | assert.ok(Equal.equals(yield* Effect.flip(res), error)) |
| 77 | } |
| 78 | |
| 79 | describe("HttpApi", () => { |
| 80 | it.effect("undeclared multipart stream errors respond with 413", () => { |
| 81 | const Api = HttpApi.make("api").add( |
| 82 | HttpApiGroup.make("group").add( |
| 83 | HttpApiEndpoint.post("upload", "/upload", { |
| 84 | payload: Schema.Struct({ |
| 85 | file: Multipart.SingleFileSchema |
| 86 | }).pipe(HttpApiSchema.asMultipartStream({ maxFileSize: 4 })) |
| 87 | }) |
| 88 | ) |
| 89 | ) |
| 90 | const GroupLayer = HttpApiBuilder.group( |
| 91 | Api, |
| 92 | "group", |
| 93 | (handlers) => |
| 94 | handlers.handle("upload", ({ payload }) => |
| 95 | // Handler types only allow declared errors; preserve the undeclared runtime failure. |
| 96 | payload.pipe( |
| 97 | Stream.filter(Multipart.isFile), |
| 98 | Stream.runForEach((file) => Stream.runDrain(file.content)) |
| 99 | ) as Effect.Effect<void>) |
| 100 | ) |
| 101 | const ApiLayer = HttpRouter.serve( |
| 102 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer)), |
| 103 | { disableListenLog: true, disableLogger: true } |
| 104 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 105 | |
| 106 | return Effect.gen(function*() { |
| 107 | const data = new FormData() |
| 108 | data.append("file", new Blob(["hello"], { type: "text/plain" }), "hello.txt") |
| 109 | const response = yield* HttpClientRequest.post("/upload").pipe( |
| 110 | HttpClientRequest.bodyFormData(data), |
| 111 | HttpClient.execute |
| 112 | ) |
| 113 | assert.strictEqual(response.status, 413) |
| 114 | }).pipe(Effect.provide(ApiLayer)) |
| 115 | }) |
| 116 | |
| 117 | it.effect("catch all path", () => { |
| 118 | const Api = HttpApi.make("api") |
| 119 | .add( |
| 120 | HttpApiGroup.make("group") |
| 121 | .add( |
| 122 | HttpApiEndpoint.get("catchAll", "*", { |
| 123 | success: Schema.String |
| 124 | }) |
| 125 | ) |
| 126 | ) |
| 127 | const GroupLayer = HttpApiBuilder.group( |
| 128 | Api, |
| 129 | "group", |
| 130 | (handlers) => handlers.handle("catchAll", (ctx) => Effect.succeed(ctx.request.url)) |
| 131 | ) |
| 132 | const ApiLayer = HttpRouter.serve( |
| 133 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer)), |
| 134 | { disableListenLog: true, disableLogger: true } |
| 135 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 136 | |
| 137 | return Effect.gen(function*() { |
| 138 | // server side |
| 139 | yield* assertServerText(yield* HttpClient.get(""), 200, `"/"`) |
| 140 | yield* assertServerText(yield* HttpClient.get("/"), 200, `"/"`) |
| 141 | yield* assertServerText(yield* HttpClient.get("/a/b/c"), 200, `"/a/b/c"`) |
| 142 | |
| 143 | // client side |
| 144 | const client = yield* HttpApiClient.make(Api) |
| 145 | yield* assertClientText(client.group.catchAll(), "/*") |
| 146 | }).pipe(Effect.provide(ApiLayer)) |
| 147 | }) |
| 148 | |
| 149 | describe("middleware", () => { |
| 150 | it.effect("error", () => { |
| 151 | class M extends HttpApiMiddleware.Service<M>()("Http/Logger", { |
| 152 | error: Schema.String |
| 153 | .pipe( |
| 154 | HttpApiSchema.status("MethodNotAllowed"), |
| 155 | HttpApiSchema.asText() |
| 156 | ) |
| 157 | }) {} |
| 158 | |
| 159 | const Api = HttpApi.make("api") |
| 160 | .add( |
| 161 | HttpApiGroup.make("group") |
| 162 | .add( |
| 163 | HttpApiEndpoint.get("a", "/a", { |
| 164 | success: Schema.Finite |
| 165 | }) |
| 166 | ).middleware(M) |
| 167 | ) |
| 168 | const GroupLayer = HttpApiBuilder.group( |
| 169 | Api, |
| 170 | "group", |
| 171 | (handlers) => handlers.handle("a", () => Effect.succeed(1)) |
| 172 | ) |
| 173 | const MLayer = Layer.succeed( |
| 174 | M, |
| 175 | () => Effect.fail("error") |
| 176 | ) |
| 177 | |
| 178 | const ApiLayer = HttpRouter.serve( |
| 179 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer), Layer.provide(MLayer)), |
| 180 | { disableListenLog: true, disableLogger: true } |
| 181 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 182 | |
| 183 | return Effect.gen(function*() { |
| 184 | // server side |
| 185 | yield* assertServerText(yield* HttpClient.get("/a"), 405, "error") |
| 186 | |
| 187 | // client side |
| 188 | const client = yield* HttpApiClient.make(Api) |
| 189 | yield* assertClientError(client.group.a(), "error") |
| 190 | }).pipe(Effect.provide(ApiLayer)) |
| 191 | }) |
| 192 | |
| 193 | it.effect("error array", () => { |
| 194 | class M extends HttpApiMiddleware.Service<M>()("Http/Auth", { |
| 195 | error: [HttpApiError.UnauthorizedNoContent, HttpApiError.ForbiddenNoContent] |
| 196 | }) {} |
| 197 | |
| 198 | const Api = HttpApi.make("api").add( |
| 199 | HttpApiGroup.make("group") |
| 200 | .add( |
| 201 | HttpApiEndpoint.get("unauthorized", "/unauthorized", { |
| 202 | success: Schema.String |
| 203 | }), |
| 204 | HttpApiEndpoint.get("forbidden", "/forbidden", { |
| 205 | success: Schema.String |
| 206 | }) |
| 207 | ) |
| 208 | .middleware(M) |
| 209 | ) |
| 210 | const GroupLayer = HttpApiBuilder.group( |
| 211 | Api, |
| 212 | "group", |
| 213 | (handlers) => |
| 214 | handlers |
| 215 | .handle("unauthorized", () => Effect.succeed("ok")) |
| 216 | .handle("forbidden", () => Effect.succeed("ok")) |
| 217 | ) |
| 218 | const MLayer = Layer.succeed( |
| 219 | M, |
| 220 | (_, { endpoint }) => |
| 221 | endpoint.identifier === "unauthorized" |
| 222 | ? Effect.fail(new HttpApiError.Unauthorized({})) |
| 223 | : Effect.fail(new HttpApiError.Forbidden({})) |
| 224 | ) |
| 225 | |
| 226 | const ApiLayer = HttpRouter.serve( |
| 227 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer), Layer.provide(MLayer)), |
| 228 | { disableListenLog: true, disableLogger: true } |
| 229 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 230 | |
| 231 | return Effect.gen(function*() { |
| 232 | yield* assertServerText(yield* HttpClient.get("/unauthorized"), 401, "") |
| 233 | yield* assertServerText(yield* HttpClient.get("/forbidden"), 403, "") |
| 234 | |
| 235 | const client = yield* HttpApiClient.make(Api) |
| 236 | yield* assertClientError(client.group.unauthorized(), new HttpApiError.Unauthorized({})) |
| 237 | yield* assertClientError(client.group.forbidden(), new HttpApiError.Forbidden({})) |
| 238 | }).pipe(Effect.provide(ApiLayer)) |
| 239 | }) |
| 240 | |
| 241 | it.effect("client middleware modifies request and receives metadata", () => { |
| 242 | class M extends HttpApiMiddleware.Service<M>()("Client/Metadata", { |
| 243 | requiredForClient: true |
| 244 | }) {} |
| 245 | |
| 246 | const Api = HttpApi.make("api").add( |
| 247 | HttpApiGroup.make("group") |
| 248 | .add( |
| 249 | HttpApiEndpoint.get("a", "/a", { |
| 250 | success: Schema.String |
| 251 | }) |
| 252 | ) |
| 253 | .middleware(M) |
| 254 | ) |
| 255 | const GroupLayer = HttpApiBuilder.group( |
| 256 | Api, |
| 257 | "group", |
| 258 | (handlers) => handlers.handle("a", (ctx) => Effect.succeed(ctx.request.headers["x-client"] ?? "missing")) |
| 259 | ) |
| 260 | const MLayer = Layer.succeed(M, (effect) => effect) |
| 261 | |
| 262 | const ApiLayer = HttpRouter.serve( |
| 263 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer), Layer.provide(MLayer)), |
| 264 | { disableListenLog: true, disableLogger: true } |
| 265 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 266 | |
| 267 | return Effect.gen(function*() { |
| 268 | const metadata = yield* Ref.make<{ readonly group: string; readonly endpoint: string } | undefined>(undefined) |
| 269 | |
| 270 | const MClient = HttpApiMiddleware.layerClient( |
| 271 | M, |
| 272 | Effect.fnUntraced(function*({ endpoint, group, next, request }) { |
| 273 | yield* Ref.set(metadata, { group: group.identifier, endpoint: endpoint.identifier }) |
| 274 | return yield* next(HttpClientRequest.setHeader(request, "x-client", "from-client")) |
| 275 | }) |
| 276 | ) |
| 277 | |
| 278 | const client = yield* HttpApiClient.make(Api).pipe( |
| 279 | Effect.provide(MClient) |
| 280 | ) |
| 281 | assert.strictEqual(yield* client.group.a(), "from-client") |
| 282 | assert.deepStrictEqual(yield* Ref.get(metadata), { |
| 283 | group: "group", |
| 284 | endpoint: "a" |
| 285 | }) |
| 286 | }).pipe(Effect.provide(ApiLayer)) |
| 287 | }) |
| 288 | |
| 289 | it.effect("client middleware chain order is LIFO", () => { |
| 290 | class M1 extends HttpApiMiddleware.Service<M1>()("Client/Chain1", { |
| 291 | requiredForClient: true |
| 292 | }) {} |
| 293 | |
| 294 | class M2 extends HttpApiMiddleware.Service<M2>()("Client/Chain2", { |
| 295 | requiredForClient: true |
| 296 | }) {} |
| 297 | |
| 298 | const Api = HttpApi.make("api").add( |
| 299 | HttpApiGroup.make("group") |
| 300 | .add( |
| 301 | HttpApiEndpoint.get("a", "/a", { |
| 302 | success: Schema.String |
| 303 | }) |
| 304 | .middleware(M1) |
| 305 | .middleware(M2) |
| 306 | ) |
| 307 | ) |
| 308 | const GroupLayer = HttpApiBuilder.group( |
| 309 | Api, |
| 310 | "group", |
| 311 | (handlers) => |
| 312 | handlers.handle( |
| 313 | "a", |
| 314 | (ctx) => Effect.succeed(`${ctx.request.headers["x-m1"] ?? "0"}${ctx.request.headers["x-m2"] ?? "0"}`) |
| 315 | ) |
| 316 | ) |
| 317 | const M1Layer = Layer.succeed(M1, (effect) => effect) |
| 318 | const M2Layer = Layer.succeed(M2, (effect) => effect) |
| 319 | |
| 320 | const ApiLayer = HttpRouter.serve( |
| 321 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer), Layer.provide(M1Layer), Layer.provide(M2Layer)), |
| 322 | { disableListenLog: true, disableLogger: true } |
| 323 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 324 | |
| 325 | return Effect.gen(function*() { |
| 326 | const order: Array<string> = [] |
| 327 | |
| 328 | const M1Client = HttpApiMiddleware.layerClient( |
| 329 | M1, |
| 330 | Effect.fnUntraced(function*({ next, request }) { |
| 331 | order.push("m1-before") |
| 332 | const response = yield* next(HttpClientRequest.setHeader(request, "x-m1", "1")) |
| 333 | order.push("m1-after") |
| 334 | return response |
| 335 | }) |
| 336 | ) |
| 337 | |
| 338 | const M2Client = HttpApiMiddleware.layerClient( |
| 339 | M2, |
| 340 | Effect.fnUntraced(function*({ next, request }) { |
| 341 | order.push("m2-before") |
| 342 | const response = yield* next(HttpClientRequest.setHeader(request, "x-m2", "1")) |
| 343 | order.push("m2-after") |
| 344 | return response |
| 345 | }) |
| 346 | ) |
| 347 | |
| 348 | const client = yield* HttpApiClient.make(Api).pipe( |
| 349 | Effect.provide([M1Client, M2Client]) |
| 350 | ) |
| 351 | |
| 352 | assert.strictEqual(yield* client.group.a(), "11") |
| 353 | assert.deepStrictEqual(order, ["m2-before", "m1-before", "m1-after", "m2-after"]) |
| 354 | }).pipe(Effect.provide(ApiLayer)) |
| 355 | }) |
| 356 | |
| 357 | it.effect("required client middleware can fail with typed clientError", () => { |
| 358 | class ClientFailure extends Schema.Error<ClientFailure>("ClientFailure")({ |
| 359 | _tag: Schema.tag("ClientFailure") |
| 360 | }) {} |
| 361 | |
| 362 | class M extends HttpApiMiddleware.Service<M, { |
| 363 | clientError: ClientFailure |
| 364 | }>()("Client/Failure", { |
| 365 | requiredForClient: true |
| 366 | }) {} |
| 367 | |
| 368 | const Api = HttpApi.make("api").add( |
| 369 | HttpApiGroup.make("group") |
| 370 | .add( |
| 371 | HttpApiEndpoint.get("a", "/a", { |
| 372 | success: Schema.String |
| 373 | }) |
| 374 | ) |
| 375 | .middleware(M) |
| 376 | ) |
| 377 | let handled = false |
| 378 | const GroupLayer = HttpApiBuilder.group( |
| 379 | Api, |
| 380 | "group", |
| 381 | (handlers) => |
| 382 | handlers.handle("a", () => |
| 383 | Effect.sync(() => { |
| 384 | handled = true |
| 385 | return "ok" |
| 386 | })) |
| 387 | ) |
| 388 | const MLayer = Layer.succeed(M, (effect) => effect) |
| 389 | |
| 390 | const ApiLayer = HttpRouter.serve( |
| 391 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer), Layer.provide(MLayer)), |
| 392 | { disableListenLog: true, disableLogger: true } |
| 393 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 394 | |
| 395 | return Effect.gen(function*() { |
| 396 | const MClient = HttpApiMiddleware.layerClient( |
| 397 | M, |
| 398 | () => Effect.fail(new ClientFailure({})) |
| 399 | ) |
| 400 | |
| 401 | const client = yield* HttpApiClient.make(Api).pipe( |
| 402 | Effect.provide(MClient) |
| 403 | ) |
| 404 | |
| 405 | yield* assertClientError(client.group.a(), new ClientFailure({})) |
| 406 | assert.isFalse(handled) |
| 407 | }).pipe(Effect.provide(ApiLayer)) |
| 408 | }) |
| 409 | |
| 410 | it.effect("optional client middleware is skipped when not provided", () => { |
| 411 | class M extends HttpApiMiddleware.Service<M>()("Client/Optional") {} |
| 412 | |
| 413 | const Api = HttpApi.make("api").add( |
| 414 | HttpApiGroup.make("group") |
| 415 | .add( |
| 416 | HttpApiEndpoint.get("a", "/a", { |
| 417 | success: Schema.String |
| 418 | }) |
| 419 | ) |
| 420 | .middleware(M) |
| 421 | ) |
| 422 | const GroupLayer = HttpApiBuilder.group( |
| 423 | Api, |
| 424 | "group", |
| 425 | (handlers) => handlers.handle("a", (ctx) => Effect.succeed(ctx.request.headers["x-optional"] ?? "missing")) |
| 426 | ) |
| 427 | const MLayer = Layer.succeed(M, (effect) => effect) |
| 428 | |
| 429 | const ApiLayer = HttpRouter.serve( |
| 430 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer), Layer.provide(MLayer)), |
| 431 | { disableListenLog: true, disableLogger: true } |
| 432 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 433 | |
| 434 | return Effect.gen(function*() { |
| 435 | const client = yield* HttpApiClient.make(Api) |
| 436 | assert.strictEqual(yield* client.group.a(), "missing") |
| 437 | }).pipe(Effect.provide(ApiLayer)) |
| 438 | }) |
| 439 | |
| 440 | it.effect("layerClient supports effectful construction", () => { |
| 441 | class HeaderValue extends Context.Service<HeaderValue, string>()("HeaderValue") {} |
| 442 | |
| 443 | class M extends HttpApiMiddleware.Service<M>()("Client/Effectful", { |
| 444 | requiredForClient: true |
| 445 | }) {} |
| 446 | |
| 447 | const Api = HttpApi.make("api").add( |
| 448 | HttpApiGroup.make("group") |
| 449 | .add( |
| 450 | HttpApiEndpoint.get("a", "/a", { |
| 451 | success: Schema.String |
| 452 | }) |
| 453 | ) |
| 454 | .middleware(M) |
| 455 | ) |
| 456 | const GroupLayer = HttpApiBuilder.group( |
| 457 | Api, |
| 458 | "group", |
| 459 | (handlers) => handlers.handle("a", (ctx) => Effect.succeed(ctx.request.headers["x-effect"] ?? "missing")) |
| 460 | ) |
| 461 | const MLayer = Layer.succeed(M, (effect) => effect) |
| 462 | |
| 463 | const ApiLayer = HttpRouter.serve( |
| 464 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer), Layer.provide(MLayer)), |
| 465 | { disableListenLog: true, disableLogger: true } |
| 466 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 467 | |
| 468 | return Effect.gen(function*() { |
| 469 | const MClient = HttpApiMiddleware.layerClient( |
| 470 | M, |
| 471 | Effect.gen(function*() { |
| 472 | const header = yield* HeaderValue |
| 473 | return ({ next, request }) => next(HttpClientRequest.setHeader(request, "x-effect", header)) |
| 474 | }) |
| 475 | ) |
| 476 | |
| 477 | const client = yield* HttpApiClient.make(Api).pipe( |
| 478 | Effect.provide(MClient), |
| 479 | Effect.provideService(HeaderValue, "from-effect") |
| 480 | ) |
| 481 | |
| 482 | assert.strictEqual(yield* client.group.a(), "from-effect") |
| 483 | }).pipe(Effect.provide(ApiLayer)) |
| 484 | }) |
| 485 | |
| 486 | it.effect("security middleware can be implemented with layerClient", () => { |
| 487 | class CurrentToken extends Context.Service<CurrentToken, string>()("CurrentToken") {} |
| 488 | |
| 489 | class M extends HttpApiMiddleware.Service<M, { |
| 490 | provides: CurrentToken |
| 491 | }>()("Client/Security", { |
| 492 | security: { |
| 493 | apiKey: HttpApiSecurity.apiKey({ |
| 494 | in: "header", |
| 495 | key: "authorization" |
| 496 | }) |
| 497 | } |
| 498 | }) {} |
| 499 | |
| 500 | const Api = HttpApi.make("api").add( |
| 501 | HttpApiGroup.make("group") |
| 502 | .add(HttpApiEndpoint.get("a", "/a", { |
| 503 | success: Schema.String |
| 504 | })) |
| 505 | .middleware(M) |
| 506 | ) |
| 507 | const GroupLayer = HttpApiBuilder.group( |
| 508 | Api, |
| 509 | "group", |
| 510 | (handlers) => handlers.handle("a", () => CurrentToken) |
| 511 | ) |
| 512 | const MLayer = Layer.succeed(M)({ |
| 513 | apiKey: (effect, options) => Effect.provideService(effect, CurrentToken, Redacted.value(options.credential)) |
| 514 | }) |
| 515 | |
| 516 | const ApiLayer = HttpRouter.serve( |
| 517 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer), Layer.provide(MLayer)), |
| 518 | { disableListenLog: true, disableLogger: true } |
| 519 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 520 | |
| 521 | return Effect.gen(function*() { |
| 522 | const client = yield* HttpApiClient.make(Api) |
| 523 | assert.strictEqual(yield* client.group.a(), "") |
| 524 | |
| 525 | const MClient = HttpApiMiddleware.layerClient( |
| 526 | M, |
| 527 | ({ next, request }) => next(HttpClientRequest.setHeader(request, "authorization", "token")) |
| 528 | ) |
| 529 | const authedClient = yield* HttpApiClient.make(Api).pipe(Effect.provide(MClient)) |
| 530 | |
| 531 | assert.strictEqual(yield* authedClient.group.a(), "token") |
| 532 | }).pipe(Effect.provide(ApiLayer)) |
| 533 | }) |
| 534 | |
| 535 | it.effect("basic security round trips non-ASCII credentials", () => { |
| 536 | class CurrentCredentials extends Context.Service<CurrentCredentials, string>()("CurrentCredentials") {} |
| 537 | |
| 538 | class M extends HttpApiMiddleware.Service<M, { |
| 539 | provides: CurrentCredentials |
| 540 | }>()("Client/Security/Basic", { |
| 541 | security: { |
| 542 | basic: HttpApiSecurity.basic |
| 543 | } |
| 544 | }) {} |
| 545 | |
| 546 | const Api = HttpApi.make("api").add( |
| 547 | HttpApiGroup.make("group") |
| 548 | .add(HttpApiEndpoint.get("a", "/a", { |
| 549 | success: Schema.String |
| 550 | })) |
| 551 | .middleware(M) |
| 552 | ) |
| 553 | const GroupLayer = HttpApiBuilder.group( |
| 554 | Api, |
| 555 | "group", |
| 556 | (handlers) => handlers.handle("a", () => CurrentCredentials) |
| 557 | ) |
| 558 | const MLayer = Layer.succeed(M)({ |
| 559 | basic: (effect, { credential }) => |
| 560 | Effect.provideService( |
| 561 | effect, |
| 562 | CurrentCredentials, |
| 563 | `${credential.username}:${Redacted.value(credential.password)}` |
| 564 | ) |
| 565 | }) |
| 566 | |
| 567 | const ApiLayer = HttpRouter.serve( |
| 568 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer), Layer.provide(MLayer)), |
| 569 | { disableListenLog: true, disableLogger: true } |
| 570 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 571 | |
| 572 | return Effect.gen(function*() { |
| 573 | const MClient = HttpApiMiddleware.layerClient( |
| 574 | M, |
| 575 | ({ next, request }) => next(HttpClientRequest.basicAuth(request, "usér", "pässword€")) |
| 576 | ) |
| 577 | const client = yield* HttpApiClient.make(Api).pipe(Effect.provide(MClient)) |
| 578 | |
| 579 | assert.strictEqual(yield* client.group.a(), "usér:pässword€") |
| 580 | }).pipe(Effect.provide(ApiLayer)) |
| 581 | }) |
| 582 | |
| 583 | it("security middleware cache does not reuse the first service impl", async () => { |
| 584 | class CurrentMarker extends Context.Service<CurrentMarker, string>()("CurrentMarker") {} |
| 585 | |
| 586 | class M extends HttpApiMiddleware.Service<M, { |
| 587 | provides: CurrentMarker |
| 588 | }>()("Server/Security/Repro", { |
| 589 | security: { |
| 590 | apiKey: HttpApiSecurity.apiKey({ |
| 591 | in: "header", |
| 592 | key: "authorization" |
| 593 | }) |
| 594 | } |
| 595 | }) {} |
| 596 | |
| 597 | const Api = HttpApi.make("api").add( |
| 598 | HttpApiGroup.make("group") |
| 599 | .add(HttpApiEndpoint.get("a", "/a", { |
| 600 | success: Schema.Struct({ |
| 601 | marker: Schema.String |
| 602 | }) |
| 603 | })) |
| 604 | .middleware(M) |
| 605 | ) |
| 606 | |
| 607 | const makeWebHandler = (marker: string) => { |
| 608 | const GroupLayer = HttpApiBuilder.group( |
| 609 | Api, |
| 610 | "group", |
| 611 | (handlers) => handlers.handle("a", () => Effect.map(CurrentMarker, (marker) => ({ marker }))) |
| 612 | ) |
| 613 | const MLayer = Layer.succeed(M)({ |
| 614 | apiKey: (effect) => Effect.provideService(effect, CurrentMarker, marker) |
| 615 | }) |
| 616 | |
| 617 | return HttpRouter.toWebHandler( |
| 618 | Layer.mergeAll( |
| 619 | HttpApiBuilder.layer(Api).pipe( |
| 620 | Layer.provide(GroupLayer), |
| 621 | Layer.provide(MLayer), |
| 622 | Layer.provide(HttpServer.layerServices) |
| 623 | ) |
| 624 | ), |
| 625 | { disableLogger: true } |
| 626 | ) |
| 627 | } |
| 628 | |
| 629 | const first = makeWebHandler("first") |
| 630 | const second = makeWebHandler("second") |
| 631 | |
| 632 | try { |
| 633 | const firstResponse = await first.handler( |
| 634 | new Request("http://localhost/a", { |
| 635 | headers: { |
| 636 | authorization: "token" |
| 637 | } |
| 638 | }) |
| 639 | ) |
| 640 | assert.strictEqual(firstResponse.status, 200) |
| 641 | assert.deepStrictEqual(await firstResponse.json(), { marker: "first" }) |
| 642 | |
| 643 | const secondResponse = await second.handler( |
| 644 | new Request("http://localhost/a", { |
| 645 | headers: { |
| 646 | authorization: "token" |
| 647 | } |
| 648 | }) |
| 649 | ) |
| 650 | assert.strictEqual(secondResponse.status, 200) |
| 651 | assert.deepStrictEqual(await secondResponse.json(), { marker: "second" }) |
| 652 | } finally { |
| 653 | await first.dispose() |
| 654 | await second.dispose() |
| 655 | } |
| 656 | }) |
| 657 | |
| 658 | it.effect("addHttpApi + middleware works across merged groups", () => { |
| 659 | class M1 extends HttpApiMiddleware.Service<M1>()("Http/M1") {} |
| 660 | class M2 extends HttpApiMiddleware.Service<M2>()("Http/M2") {} |
| 661 | |
| 662 | const calls: Array<string> = [] |
| 663 | |
| 664 | const V0 = HttpApi.make("v0").add( |
| 665 | HttpApiGroup.make("users").add( |
| 666 | HttpApiEndpoint.get("list", "/users", { |
| 667 | success: Schema.String |
| 668 | }) |
| 669 | ) |
| 670 | ) |
| 671 | const Api = HttpApi.make("api") |
| 672 | .add( |
| 673 | HttpApiGroup.make("health").add( |
| 674 | HttpApiEndpoint.get("health", "/health", { |
| 675 | success: Schema.String |
| 676 | }) |
| 677 | ) |
| 678 | ) |
| 679 | .addHttpApi(V0) |
| 680 | .middleware(M1) |
| 681 | .middleware(M2) |
| 682 | |
| 683 | const HealthLayer = HttpApiBuilder.group( |
| 684 | Api, |
| 685 | "health", |
| 686 | (handlers) => handlers.handle("health", () => Effect.succeed("ok")) |
| 687 | ) |
| 688 | const UsersLayer = HttpApiBuilder.group( |
| 689 | Api, |
| 690 | "users", |
| 691 | (handlers) => handlers.handle("list", () => Effect.succeed("ok")) |
| 692 | ) |
| 693 | const M1Layer = Layer.succeed( |
| 694 | M1, |
| 695 | (effect, { endpoint, group }) => |
| 696 | Effect.sync(() => calls.push(`m1:${group.identifier}.${endpoint.identifier}`)).pipe( |
| 697 | Effect.flatMap(() => effect) |
| 698 | ) |
| 699 | ) |
| 700 | const M2Layer = Layer.succeed( |
| 701 | M2, |
| 702 | (effect, { endpoint, group }) => |
| 703 | Effect.sync(() => calls.push(`m2:${group.identifier}.${endpoint.identifier}`)).pipe( |
| 704 | Effect.flatMap(() => effect) |
| 705 | ) |
| 706 | ) |
| 707 | |
| 708 | const ApiLayer = HttpRouter.serve( |
| 709 | HttpApiBuilder.layer(Api).pipe( |
| 710 | Layer.provide(HealthLayer), |
| 711 | Layer.provide(UsersLayer), |
| 712 | Layer.provide(M1Layer), |
| 713 | Layer.provide(M2Layer) |
| 714 | ), |
| 715 | { disableListenLog: true, disableLogger: true } |
| 716 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 717 | |
| 718 | return Effect.gen(function*() { |
| 719 | yield* assertServerJson(yield* HttpClient.get("/health"), 200, "ok") |
| 720 | yield* assertServerJson(yield* HttpClient.get("/users"), 200, "ok") |
| 721 | assert.deepStrictEqual(calls, [ |
| 722 | "m2:health.health", |
| 723 | "m1:health.health", |
| 724 | "m2:users.list", |
| 725 | "m1:users.list" |
| 726 | ]) |
| 727 | }).pipe(Effect.provide(ApiLayer)) |
| 728 | }) |
| 729 | |
| 730 | it.effect("missing middleware layer fails with service not found error", () => { |
| 731 | class M extends HttpApiMiddleware.Service<M>()("Server/MissingMiddleware") {} |
| 732 | |
| 733 | const Api = HttpApi.make("api").add( |
| 734 | HttpApiGroup.make("group") |
| 735 | .add( |
| 736 | HttpApiEndpoint.get("a", "/a", { |
| 737 | success: Schema.String |
| 738 | }) |
| 739 | ) |
| 740 | .middleware(M) |
| 741 | ) |
| 742 | const GroupLayer = HttpApiBuilder.group( |
| 743 | Api, |
| 744 | "group", |
| 745 | (handlers) => handlers.handle("a", () => Effect.succeed("ok")) |
| 746 | ) |
| 747 | const ApiLayer = HttpRouter.serve( |
| 748 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer)), |
| 749 | { disableListenLog: true, disableLogger: true } |
| 750 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 751 | |
| 752 | return HttpClient.get("/a").pipe( |
| 753 | Effect.provide(ApiLayer), |
| 754 | Effect.sandbox, |
| 755 | Effect.flip, |
| 756 | Effect.flatMap((cause) => |
| 757 | Effect.sync(() => { |
| 758 | const defect = Cause.squash(cause) |
| 759 | assert.instanceOf(defect, Error) |
| 760 | assert.include(defect.message, "Service not found: Server/MissingMiddleware") |
| 761 | assert.isFalse(defect.message.includes("is not a function")) |
| 762 | }) |
| 763 | ) |
| 764 | ) as Effect.Effect<void, HttpClientResponse.HttpClientResponse> |
| 765 | }) |
| 766 | }) |
| 767 | |
| 768 | it.effect("missing addHttpApi group layer has actionable error", () => { |
| 769 | const HealthApi = HttpApiGroup.make("health").add( |
| 770 | HttpApiEndpoint.get("health", "/health", { |
| 771 | success: Schema.String |
| 772 | }) |
| 773 | ) |
| 774 | const V0 = HttpApi.make("v0").add( |
| 775 | HttpApiGroup.make("users").add( |
| 776 | HttpApiEndpoint.get("list", "/users", { |
| 777 | success: Schema.String |
| 778 | }) |
| 779 | ) |
| 780 | ) |
| 781 | const Api = HttpApi.make("api") |
| 782 | .add(HealthApi) |
| 783 | .addHttpApi(V0) |
| 784 | |
| 785 | const UsersLayer = HttpApiBuilder.group( |
| 786 | Api, |
| 787 | "users", |
| 788 | (handlers) => handlers.handle("list", () => Effect.succeed("ok")) |
| 789 | ) |
| 790 | const ApiLayer = HttpRouter.serve( |
| 791 | HttpApiBuilder.layer(Api).pipe(Layer.provide(UsersLayer)), |
| 792 | { disableListenLog: true, disableLogger: true } |
| 793 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 794 | |
| 795 | return HttpClient.get("/users").pipe( |
| 796 | Effect.provide(ApiLayer), |
| 797 | Effect.sandbox, |
| 798 | Effect.flip, |
| 799 | Effect.flatMap((cause) => |
| 800 | Effect.sync(() => { |
| 801 | const defect = Cause.squash(cause) |
| 802 | assert.strictEqual(typeof defect, "string") |
| 803 | assert.include(defect, "HttpApiGroup \"health\" not found") |
| 804 | assert.include(defect, "HttpApiBuilder.group(api, \"health\", ...)") |
| 805 | assert.include(defect, "Available groups: effect/http-api/HttpApiGroup/users") |
| 806 | }) |
| 807 | ) |
| 808 | ) as Effect.Effect<void, HttpClientResponse.HttpClientResponse> |
| 809 | }) |
| 810 | |
| 811 | describe("payload option", () => { |
| 812 | describe("GET", () => { |
| 813 | it.effect("query parameters", () => { |
| 814 | const Api = HttpApi.make("api") |
| 815 | .add( |
| 816 | HttpApiGroup.make("group") |
| 817 | .add( |
| 818 | HttpApiEndpoint.get("a", "/a", { |
| 819 | payload: { |
| 820 | required: Schema.FiniteFromString, |
| 821 | optionalKey: Schema.optionalKey(Schema.FiniteFromString), |
| 822 | optional: Schema.optional(Schema.FiniteFromString) |
| 823 | }, |
| 824 | success: Schema.Any |
| 825 | }) |
| 826 | ) |
| 827 | ) |
| 828 | const GroupLayer = HttpApiBuilder.group( |
| 829 | Api, |
| 830 | "group", |
| 831 | (handlers) => handlers.handle("a", (ctx) => Effect.succeed(ctx.payload)) |
| 832 | ) |
| 833 | const ApiLayer = HttpRouter.serve( |
| 834 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer)), |
| 835 | { disableListenLog: true, disableLogger: true } |
| 836 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 837 | |
| 838 | return Effect.gen(function*() { |
| 839 | // server side |
| 840 | yield* assertServerText(yield* HttpClient.get("/a"), 400, "") |
| 841 | yield* assertServerJson(yield* HttpClient.get("/a?required=1"), 200, { required: 1 }) |
| 842 | yield* assertServerJson(yield* HttpClient.get("/a?required=1&optionalKey=1"), 200, { |
| 843 | required: 1, |
| 844 | optionalKey: 1 |
| 845 | }) |
| 846 | yield* assertServerJson(yield* HttpClient.get("/a?required=1&optional=1"), 200, { required: 1, optional: 1 }) |
| 847 | yield* assertServerJson(yield* HttpClient.get("/a?required=1"), 200, { required: 1 }) |
| 848 | // TODO: fix this test |
| 849 | yield* assertServerJson(yield* HttpClient.get("/a?required=1&optional="), 200, { required: 1, optional: 0 }) |
| 850 | |
| 851 | // client side |
| 852 | const client = yield* HttpApiClient.make(Api) |
| 853 | yield* assertClientJson(client.group.a({ payload: { required: 1 } }), { required: 1 }) |
| 854 | yield* assertClientJson(client.group.a({ payload: { required: 1, optionalKey: 1 } }), { |
| 855 | required: 1, |
| 856 | optionalKey: 1 |
| 857 | }) |
| 858 | yield* assertClientJson(client.group.a({ payload: { required: 1, optional: 1 } }), { |
| 859 | required: 1, |
| 860 | optional: 1 |
| 861 | }) |
| 862 | yield* assertClientJson(client.group.a({ payload: { required: 1, optional: undefined } }), { required: 1 }) |
| 863 | }).pipe(Effect.provide(ApiLayer)) |
| 864 | }) |
| 865 | }) |
| 866 | |
| 867 | it.effect("array of schemas with different encodings", () => { |
| 868 | const Api = HttpApi.make("api").add( |
| 869 | HttpApiGroup.make("group").add( |
| 870 | HttpApiEndpoint.post("a", "/a", { |
| 871 | payload: [ |
| 872 | Schema.Struct({ a: Schema.String }), // application/json |
| 873 | Schema.String.pipe(HttpApiSchema.asText()), // text/plain |
| 874 | Schema.Uint8Array.pipe(HttpApiSchema.asUint8Array()) // application/octet-stream |
| 875 | ], |
| 876 | success: Schema.Any |
| 877 | }) |
| 878 | ) |
| 879 | ) |
| 880 | const GroupLayer = HttpApiBuilder.group( |
| 881 | Api, |
| 882 | "group", |
| 883 | (handlers) => handlers.handle("a", (ctx) => Effect.succeed(ctx.payload)) |
| 884 | ) |
| 885 | |
| 886 | const ApiLayer = HttpRouter.serve( |
| 887 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer)), |
| 888 | { disableListenLog: true, disableLogger: true } |
| 889 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 890 | |
| 891 | return Effect.gen(function*() { |
| 892 | // server side |
| 893 | yield* assertServerText(yield* HttpClient.post("/a"), 400, "") |
| 894 | yield* assertServerJson(yield* HttpClient.post("/a", { body: HttpBody.jsonUnsafe({ a: "text" }) }), 200, { |
| 895 | a: "text" |
| 896 | }) |
| 897 | yield* assertServerJson(yield* HttpClient.post("/a", { body: HttpBody.text("text") }), 200, "text") |
| 898 | yield* assertServerJson( |
| 899 | yield* HttpClient.post("/a", { body: HttpBody.uint8Array(new Uint8Array([1, 2, 3])) }), |
| 900 | 200, |
| 901 | { 0: 1, 1: 2, 2: 3 } |
| 902 | ) |
| 903 | |
| 904 | // client side |
| 905 | const client = yield* HttpApiClient.make(Api) |
| 906 | yield* assertClientJson(client.group.a({ payload: { a: "text" } }), { a: "text" }) |
| 907 | yield* assertClientJson(client.group.a({ payload: "text" }), "text") |
| 908 | yield* assertClientJson(client.group.a({ payload: new Uint8Array([1, 2, 3]) }), { 0: 1, 1: 2, 2: 3 }) |
| 909 | }).pipe(Effect.provide(ApiLayer)) |
| 910 | }) |
| 911 | |
| 912 | describe("streaming", () => { |
| 913 | const Item = Schema.Struct({ n: Schema.Number }) |
| 914 | const Api = HttpApi.make("api").add( |
| 915 | HttpApiGroup.make("group").add( |
| 916 | HttpApiEndpoint.post("ndjson", "/ndjson", { |
| 917 | payload: HttpApiSchema.StreamNdjson({ schema: Item }), |
| 918 | success: Schema.Array(Item) |
| 919 | }), |
| 920 | HttpApiEndpoint.post("bytes", "/bytes", { |
| 921 | payload: HttpApiSchema.StreamUint8Array(), |
| 922 | success: Schema.Number |
| 923 | }), |
| 924 | HttpApiEndpoint.post("ignore", "/ignore", { |
| 925 | payload: HttpApiSchema.StreamUint8Array(), |
| 926 | success: Schema.String |
| 927 | }), |
| 928 | HttpApiEndpoint.post("flaky", "/flaky", { |
| 929 | payload: HttpApiSchema.StreamNdjson({ schema: Item }), |
| 930 | success: Schema.Array(Item), |
| 931 | error: HttpApiError.ServiceUnavailable |
| 932 | }), |
| 933 | HttpApiEndpoint.post("mixed", "/mixed", { |
| 934 | payload: [Schema.Array(Item), HttpApiSchema.StreamNdjson({ schema: Item })], |
| 935 | success: Schema.String |
| 936 | }) |
| 937 | ) |
| 938 | ) |
| 939 | const GroupLayer = HttpApiBuilder.group( |
| 940 | Api, |
| 941 | "group", |
| 942 | Effect.fnUntraced(function*(handlers) { |
| 943 | const flakyCalls = yield* Ref.make(0) |
| 944 | return handlers |
| 945 | .handle("ndjson", ({ payload }) => Stream.runCollect(payload)) |
| 946 | .handle("bytes", ({ payload }) => Stream.runFold(payload, () => 0, (total, chunk) => total + chunk.length)) |
| 947 | .handle("ignore", () => Effect.succeed("ok")) |
| 948 | .handle("flaky", ({ payload }) => |
| 949 | Effect.gen(function*() { |
| 950 | const items = yield* Stream.runCollect(payload) |
| 951 | if ((yield* Ref.getAndUpdate(flakyCalls, (n) => n + 1)) === 0) { |
| 952 | return yield* new HttpApiError.ServiceUnavailable() |
| 953 | } |
| 954 | return items |
| 955 | })) |
| 956 | .handle("mixed", ({ payload }) => |
| 957 | Stream.isStream(payload) |
| 958 | ? Effect.map(Stream.runCollect(payload), (items) => `stream:${items.length}`) |
| 959 | : Effect.succeed(`array:${payload.length}`)) |
| 960 | }) |
| 961 | ) |
| 962 | ;[ |
| 963 | { name: "node:http", layer: NodeHttpClient.layerNodeHttp }, |
| 964 | { name: "undici", layer: NodeHttpClient.layerUndici }, |
| 965 | { name: "fetch", layer: FetchHttpClient.layer } |
| 966 | ].forEach(({ layer, name }) => { |
| 967 | describe(name, () => { |
| 968 | const ApiLayer = HttpRouter.serve( |
| 969 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer)), |
| 970 | { disableListenLog: true, disableLogger: true } |
| 971 | ).pipe( |
| 972 | Layer.provideMerge(HttpServer.layerTestClient), |
| 973 | Layer.provide(layer), |
| 974 | Layer.provideMerge(NodeHttpServer.layer(Http.createServer, { port: 0 })) |
| 975 | ) |
| 976 | |
| 977 | it.effect("uploads a caller's stream", () => |
| 978 | Effect.gen(function*() { |
| 979 | const client = yield* HttpApiClient.make(Api) |
| 980 | const items = yield* client.group.ndjson({ payload: Stream.make({ n: 1 }, { n: 2 }, { n: 3 }) }) |
| 981 | assert.deepStrictEqual(items, [{ n: 1 }, { n: 2 }, { n: 3 }]) |
| 982 | const total = yield* client.group.bytes({ |
| 983 | payload: Stream.make(new Uint8Array(2), new Uint8Array(3)) |
| 984 | }) |
| 985 | assert.strictEqual(total, 5) |
| 986 | }).pipe(Effect.provide(ApiLayer))) |
| 987 | |
| 988 | it.effect("fails with an HttpClientError when the source fails before the method returns", () => |
| 989 | Effect.gen(function*() { |
| 990 | const client = yield* HttpApiClient.make(Api) |
| 991 | const error = yield* client.group.ndjson({ |
| 992 | payload: Stream.make({ n: 1 }).pipe(Stream.concat(Stream.fail("SourceError" as const))) |
| 993 | }).pipe(Effect.flip) |
| 994 | assert.strictEqual(error._tag, "HttpClientError") |
| 995 | }).pipe(Effect.provide(ApiLayer))) |
| 996 | |
| 997 | it.live("interrupts the upload once the response is decoded", () => |
| 998 | Effect.gen(function*() { |
| 999 | const client = yield* HttpApiClient.make(Api) |
| 1000 | const finalized = yield* Deferred.make<void>() |
| 1001 | const result = yield* client.group.ignore({ |
| 1002 | payload: Stream.make(new Uint8Array(1)).pipe( |
| 1003 | Stream.concat(Stream.never), |
| 1004 | Stream.ensuring(Deferred.succeed(finalized, undefined)) |
| 1005 | ) |
| 1006 | }) |
| 1007 | assert.strictEqual(result, "ok") |
| 1008 | yield* Deferred.await(finalized).pipe(Effect.timeout("1 second")) |
| 1009 | }).pipe(Effect.provide(ApiLayer))) |
| 1010 | |
| 1011 | it.effect("replays the stream on retry", () => |
| 1012 | Effect.gen(function*() { |
| 1013 | const client = yield* HttpApiClient.make(Api, { |
| 1014 | transformClient: (client) => HttpClient.retryTransient(client, { times: 1 }) |
| 1015 | }) |
| 1016 | let runs = 0 |
| 1017 | const items = yield* client.group.flaky({ |
| 1018 | payload: Stream.suspend(() => { |
| 1019 | runs++ |
| 1020 | return Stream.make({ n: 1 }, { n: 2 }) |
| 1021 | }) |
| 1022 | }) |
| 1023 | assert.deepStrictEqual(items, [{ n: 1 }, { n: 2 }]) |
| 1024 | assert.strictEqual(runs, 2) |
| 1025 | }).pipe(Effect.provide(ApiLayer))) |
| 1026 | |
| 1027 | it.effect("sends the buffered or streaming member of a mixed payload", () => |
| 1028 | Effect.gen(function*() { |
| 1029 | const client = yield* HttpApiClient.make(Api) |
| 1030 | assert.strictEqual(yield* client.group.mixed({ payload: [{ n: 1 }, { n: 2 }] }), "array:2") |
| 1031 | assert.strictEqual(yield* client.group.mixed({ payload: Stream.make({ n: 1 }, { n: 2 }) }), "stream:2") |
| 1032 | }).pipe(Effect.provide(ApiLayer))) |
| 1033 | }) |
| 1034 | }) |
| 1035 | }) |
| 1036 | }) |
| 1037 | |
| 1038 | describe("params option", () => { |
| 1039 | it.effect("should accept a record of schemas", () => { |
| 1040 | const Api = HttpApi.make("api").add( |
| 1041 | HttpApiGroup.make("group").add( |
| 1042 | HttpApiEndpoint.get("get", "/:id", { |
| 1043 | params: { |
| 1044 | id: Schema.FiniteFromString |
| 1045 | }, |
| 1046 | success: Schema.String |
| 1047 | }) |
| 1048 | ) |
| 1049 | ) |
| 1050 | const GroupLayer = HttpApiBuilder.group( |
| 1051 | Api, |
| 1052 | "group", |
| 1053 | (handlers) => handlers.handle("get", (ctx) => Effect.succeed(`User ${ctx.params.id}`)) |
| 1054 | ) |
| 1055 | |
| 1056 | const ApiLayer = HttpRouter.serve( |
| 1057 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer)), |
| 1058 | { disableListenLog: true, disableLogger: true } |
| 1059 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 1060 | |
| 1061 | return Effect.gen(function*() { |
| 1062 | // server side |
| 1063 | yield* assertServerJson(yield* HttpClient.get("/1"), 200, "User 1") |
| 1064 | |
| 1065 | // client side |
| 1066 | const client = yield* HttpApiClient.make(Api) |
| 1067 | yield* assertClientJson(client.group.get({ params: { id: 1 } }), "User 1") |
| 1068 | }).pipe(Effect.provide(ApiLayer)) |
| 1069 | }) |
| 1070 | }) |
| 1071 | |
| 1072 | describe("query option", () => { |
| 1073 | it.effect("should accept a record of schemas", () => { |
| 1074 | const Api = HttpApi.make("api").add( |
| 1075 | HttpApiGroup.make("group").add( |
| 1076 | HttpApiEndpoint.get("get", "/", { |
| 1077 | query: { |
| 1078 | id: Schema.FiniteFromString |
| 1079 | }, |
| 1080 | success: Schema.String |
| 1081 | }) |
| 1082 | ) |
| 1083 | ) |
| 1084 | const GroupLayer = HttpApiBuilder.group( |
| 1085 | Api, |
| 1086 | "group", |
| 1087 | (handlers) => handlers.handle("get", (ctx) => Effect.succeed(`User ${ctx.query.id}`)) |
| 1088 | ) |
| 1089 | |
| 1090 | const ApiLayer = HttpRouter.serve( |
| 1091 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer)), |
| 1092 | { disableListenLog: true, disableLogger: true } |
| 1093 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 1094 | |
| 1095 | return Effect.gen(function*() { |
| 1096 | // server side |
| 1097 | yield* assertServerJson(yield* HttpClient.get("/?id=1"), 200, "User 1") |
| 1098 | |
| 1099 | // client side |
| 1100 | const client = yield* HttpApiClient.make(Api) |
| 1101 | yield* assertClientJson(client.group.get({ query: { id: 1 } }), "User 1") |
| 1102 | }).pipe(Effect.provide(ApiLayer)) |
| 1103 | }) |
| 1104 | }) |
| 1105 | |
| 1106 | describe("success option", () => { |
| 1107 | it.effect("no content", () => { |
| 1108 | const Api = HttpApi.make("api") |
| 1109 | .add( |
| 1110 | HttpApiGroup.make("group") |
| 1111 | .add( |
| 1112 | HttpApiEndpoint.get("a", "/a", { |
| 1113 | success: Schema.Void |
| 1114 | }), |
| 1115 | HttpApiEndpoint.get("b", "/b", { |
| 1116 | success: HttpApiSchema.NoContent |
| 1117 | }), |
| 1118 | HttpApiEndpoint.get("c", "/c", { |
| 1119 | success: Schema.String.pipe(HttpApiSchema.asNoContent({ decode: () => "c" })) |
| 1120 | }) |
| 1121 | ) |
| 1122 | ) |
| 1123 | const GroupLayer = HttpApiBuilder.group( |
| 1124 | Api, |
| 1125 | "group", |
| 1126 | (handlers) => |
| 1127 | handlers |
| 1128 | .handle("a", () => Effect.void) |
| 1129 | .handle("b", () => Effect.succeed(HttpApiSchema.NoContent.make())) |
| 1130 | .handle("c", () => Effect.succeed("-")) |
| 1131 | ) |
| 1132 | |
| 1133 | const ApiLayer = HttpRouter.serve( |
| 1134 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer)), |
| 1135 | { disableListenLog: true, disableLogger: true } |
| 1136 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 1137 | |
| 1138 | return Effect.gen(function*() { |
| 1139 | // server side |
| 1140 | yield* assertServerText(yield* HttpClient.get("/a"), 200, "") |
| 1141 | yield* assertServerText(yield* HttpClient.get("/b"), 204, "") |
| 1142 | yield* assertServerText(yield* HttpClient.get("/c"), 200, "") |
| 1143 | |
| 1144 | // client side |
| 1145 | const client = yield* HttpApiClient.make(Api) |
| 1146 | yield* assertClientJson(client.group.a(), undefined) |
| 1147 | yield* assertClientJson(client.group.b(), undefined) |
| 1148 | yield* assertClientJson(client.group.c(), "c") |
| 1149 | }).pipe(Effect.provide(ApiLayer)) |
| 1150 | }) |
| 1151 | |
| 1152 | it.effect("upgrade", () => { |
| 1153 | class NotFound extends Schema.Error<NotFound>("NotFound")({ |
| 1154 | _tag: Schema.tag("NotFound") |
| 1155 | }, { |
| 1156 | httpApiStatus: 404 |
| 1157 | }) {} |
| 1158 | const Api = HttpApi.make("api") |
| 1159 | .add( |
| 1160 | HttpApiGroup.make("containers") |
| 1161 | .add( |
| 1162 | HttpApiEndpoint.post("attach", "/containers/:id/attach", { |
| 1163 | params: { id: Schema.String }, |
| 1164 | success: HttpApiSchema.Upgrade({ protocol: "tcp" }), |
| 1165 | error: NotFound |
| 1166 | }), |
| 1167 | HttpApiEndpoint.post("start", "/containers/:id/start", { |
| 1168 | params: { id: Schema.String }, |
| 1169 | payload: Schema.Struct({ tty: Schema.Boolean, detach: Schema.Boolean }), |
| 1170 | success: [ |
| 1171 | HttpApiSchema.Upgrade({ |
| 1172 | protocol: "tcp", |
| 1173 | headers: { "content-type": Schema.Literals(["application/raw", "application/multiplexed"]) } |
| 1174 | }), |
| 1175 | Schema.String |
| 1176 | ], |
| 1177 | error: NotFound |
| 1178 | }) |
| 1179 | ) |
| 1180 | ) |
| 1181 | const GroupLayer = HttpApiBuilder.group( |
| 1182 | Api, |
| 1183 | "containers", |
| 1184 | (handlers) => |
| 1185 | handlers |
| 1186 | .handle("attach", ({ params, upgrade }) => |
| 1187 | Effect.gen(function*() { |
| 1188 | // fails before the 101 is sent |
| 1189 | if (params.id !== "abc") return yield* new NotFound() |
| 1190 | const socket = yield* upgrade() |
| 1191 | const reader = yield* socket.reader |
| 1192 | const writer = yield* socket.writer |
| 1193 | yield* writer.write(`${params.id}:${yield* readUntilClose(reader)}`) |
| 1194 | }).pipe(Effect.catchTag("SocketError", Effect.die), Effect.scoped)) |
| 1195 | .handle("start", ({ params, payload, upgrade }) => |
| 1196 | Effect.gen(function*() { |
| 1197 | if (params.id !== "abc") return yield* new NotFound() |
| 1198 | // the server may decline the upgrade with an ordinary success |
| 1199 | if (payload.detach) return `${params.id}:detached` |
| 1200 | const socket = yield* upgrade({ |
| 1201 | headers: { "content-type": payload.tty ? "application/raw" : "application/multiplexed" } |
| 1202 | }) |
| 1203 | const reader = yield* socket.reader |
| 1204 | const writer = yield* socket.writer |
| 1205 | yield* writer.write(`${params.id}:${payload.tty}:${yield* readUntilClose(reader)}`) |
| 1206 | }).pipe(Effect.catchTag("SocketError", Effect.die), Effect.scoped)) |
| 1207 | ) |
| 1208 | const ApiLayer = HttpRouter.serve( |
| 1209 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer)), |
| 1210 | { disableListenLog: true, disableLogger: true } |
| 1211 | ).pipe( |
| 1212 | Layer.provideMerge(HttpServer.layerTestClient), |
| 1213 | Layer.provide(NodeHttpClient.layerNodeHttp), |
| 1214 | Layer.provideMerge(NodeHttpServer.layer(Http.createServer, { port: 0 })) |
| 1215 | ) |
| 1216 | |
| 1217 | return Effect.gen(function*() { |
| 1218 | // server side |
| 1219 | const refused = yield* HttpClient.post("/containers/abc/attach") |
| 1220 | assert.strictEqual(refused.status, 426) |
| 1221 | assert.strictEqual(refused.headers.upgrade, "tcp") |
| 1222 | |
| 1223 | const missingConnection = yield* HttpClient.post("/containers/abc/attach", { |
| 1224 | headers: { upgrade: "tcp" } |
| 1225 | }) |
| 1226 | assert.strictEqual(missingConnection.status, 426) |
| 1227 | assert.strictEqual(missingConnection.headers.upgrade, "tcp") |
| 1228 | |
| 1229 | // the upgrade is checked before the payload is decoded |
| 1230 | const invalidPayload = HttpBody.text("{", "application/json") |
| 1231 | const refusedStart = yield* HttpClient.post("/containers/abc/start", { body: invalidPayload }) |
| 1232 | assert.strictEqual(refusedStart.status, 426) |
| 1233 | const invalidStart = yield* HttpClient.post("/containers/abc/start", { |
| 1234 | headers: { connection: "Upgrade", upgrade: "tcp" }, |
| 1235 | body: invalidPayload |
| 1236 | }) |
| 1237 | assert.strictEqual(invalidStart.status, 400) |
| 1238 | const detachedStart = yield* HttpClient.post("/containers/abc/start", { |
| 1239 | headers: { connection: "Upgrade", upgrade: "tcp" }, |
| 1240 | body: HttpBody.text(JSON.stringify({ tty: false, detach: true }), "application/json") |
| 1241 | }) |
| 1242 | assert.strictEqual(detachedStart.status, 200) |
| 1243 | assert.strictEqual(yield* detachedStart.json, "abc:detached") |
| 1244 | |
| 1245 | // client side |
| 1246 | const client = yield* HttpApiClient.make(Api) |
| 1247 | const attached = yield* client.containers.attach({ params: { id: "abc" } }) |
| 1248 | assert.isTrue(HttpApiClient.isUpgraded(attached)) |
| 1249 | const { headers, socket } = attached |
| 1250 | assert.strictEqual(headers.upgrade, "tcp") |
| 1251 | const reader = yield* socket.reader |
| 1252 | yield* Effect.scoped(Effect.flatMap(socket.writer, (writer) => writer.write("ping"))) |
| 1253 | assert.strictEqual(yield* readUntilClose(reader), "abc:ping") |
| 1254 | |
| 1255 | const error = yield* Effect.flip(client.containers.attach({ params: { id: "missing" } })) |
| 1256 | assert.deepStrictEqual(error, new NotFound()) |
| 1257 | |
| 1258 | const started = yield* client.containers.start({ params: { id: "abc" }, payload: { tty: true, detach: false } }) |
| 1259 | if (!HttpApiClient.isUpgraded(started)) return assert.fail("expected an upgrade") |
| 1260 | assert.deepStrictEqual(started.headers, { "content-type": "application/raw" }) |
| 1261 | const startReader = yield* started.socket.reader |
| 1262 | yield* Effect.scoped(Effect.flatMap(started.socket.writer, (writer) => writer.write("ping"))) |
| 1263 | assert.strictEqual(yield* readUntilClose(startReader), "abc:true:ping") |
| 1264 | |
| 1265 | const detached = yield* client.containers.start({ |
| 1266 | params: { id: "abc" }, |
| 1267 | payload: { tty: false, detach: true } |
| 1268 | }) |
| 1269 | assert.strictEqual(detached, "abc:detached") |
| 1270 | |
| 1271 | const startError = yield* Effect.flip( |
| 1272 | client.containers.start({ params: { id: "missing" }, payload: { tty: false, detach: false } }) |
| 1273 | ) |
| 1274 | assert.deepStrictEqual(startError, new NotFound()) |
| 1275 | }).pipe(Effect.scoped, Effect.provide(ApiLayer)) |
| 1276 | }) |
| 1277 | |
| 1278 | it.live("closes an upgraded connection whose headers fail to decode", () => |
| 1279 | Effect.gen(function*() { |
| 1280 | const { baseUrl, closed } = yield* makeUpgradeServer |
| 1281 | const client = yield* HttpApiClient.make(UpgradeApi, { baseUrl }) |
| 1282 | const error = yield* Effect.flip(Effect.scoped(client.containers.start())) |
| 1283 | assert.strictEqual(error._tag, "SchemaError") |
| 1284 | yield* Deferred.await(closed).pipe(Effect.timeout("2 seconds")) |
| 1285 | }).pipe(Effect.scoped, Effect.provide(NodeHttpClient.layerNodeHttp))) |
| 1286 | |
| 1287 | it.live("closes an upgraded connection when interrupted as the upgrade is taken", () => |
| 1288 | Effect.gen(function*() { |
| 1289 | const { baseUrl, closed } = yield* makeUpgradeServer |
| 1290 | const client = yield* HttpApiClient.make(UpgradeApi, { baseUrl }) |
| 1291 | const response = yield* client.containers.start({ responseMode: "response-only" }) |
| 1292 | // interrupts the decoding fiber as soon as the upgrade succeeds |
| 1293 | const interrupted: HttpClientResponse.HttpClientResponse = Object.create(response, { |
| 1294 | upgrade: { |
| 1295 | value: Effect.tap(response.upgrade, () => |
| 1296 | Effect.withFiber((fiber) => { |
| 1297 | fiber.interruptUnsafe() |
| 1298 | return Effect.void |
| 1299 | })) |
| 1300 | } |
| 1301 | }) |
| 1302 | const decodeStart = HttpApiClient.decodeResponse(UpgradeApi, { group: "containers", endpoint: "start" }) |
| 1303 | const exit = yield* Fiber.await(yield* Effect.forkChild(decodeStart(interrupted))) |
| 1304 | assert.isTrue(Exit.hasInterrupts(exit)) |
| 1305 | yield* Deferred.await(closed).pipe(Effect.timeout("2 seconds")) |
| 1306 | }).pipe(Effect.scoped, Effect.provide(NodeHttpClient.layerNodeHttp))) |
| 1307 | |
| 1308 | it("no content via toWebHandler", async () => { |
| 1309 | const Api = HttpApi.make("api") |
| 1310 | .add( |
| 1311 | HttpApiGroup.make("group") |
| 1312 | .add(HttpApiEndpoint.delete("remove", "/items/:id", { params: { id: Schema.String } })) |
| 1313 | ) |
| 1314 | const GroupLayer = HttpApiBuilder.group( |
| 1315 | Api, |
| 1316 | "group", |
| 1317 | (handlers) => handlers.handle("remove", () => Effect.void) |
| 1318 | ) |
| 1319 | const ApiLayer = HttpApiBuilder.layer(Api).pipe( |
| 1320 | Layer.provide(GroupLayer), |
| 1321 | Layer.provide(HttpServer.layerServices) |
| 1322 | ) |
| 1323 | const { handler, dispose } = HttpRouter.toWebHandler( |
| 1324 | Layer.mergeAll(ApiLayer), |
| 1325 | { disableLogger: true } |
| 1326 | ) |
| 1327 | try { |
| 1328 | const response = await handler(new Request("http://localhost/items/123", { method: "DELETE" })) |
| 1329 | assert.strictEqual(response.status, 204) |
| 1330 | assert.strictEqual(response.body, null) |
| 1331 | } finally { |
| 1332 | await dispose() |
| 1333 | } |
| 1334 | }) |
| 1335 | |
| 1336 | describe("encodings", () => { |
| 1337 | describe("asJson", () => { |
| 1338 | it.effect("custom contentType", () => { |
| 1339 | const Api = HttpApi.make("api").add( |
| 1340 | HttpApiGroup.make("group").add( |
| 1341 | HttpApiEndpoint.get("a", "/a", { |
| 1342 | success: Schema.String.pipe(HttpApiSchema.asJson({ contentType: "application/scim+json" })) |
| 1343 | }) |
| 1344 | ) |
| 1345 | ) |
| 1346 | const GroupLayer = HttpApiBuilder.group( |
| 1347 | Api, |
| 1348 | "group", |
| 1349 | (handlers) => handlers.handle("a", () => Effect.succeed("a")) |
| 1350 | ) |
| 1351 | |
| 1352 | const ApiLayer = HttpRouter.serve( |
| 1353 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer)), |
| 1354 | { disableListenLog: true, disableLogger: true } |
| 1355 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 1356 | |
| 1357 | return Effect.gen(function*() { |
| 1358 | // server side |
| 1359 | const res = yield* HttpClient.get("/a") |
| 1360 | yield* assertServerJson(res, 200, "a") |
| 1361 | assert.strictEqual(res.headers["content-type"], "application/scim+json") |
| 1362 | |
| 1363 | // client side |
| 1364 | const client = yield* HttpApiClient.make(Api) |
| 1365 | yield* assertClientJson(client.group.a(), "a") |
| 1366 | }).pipe(Effect.provide(ApiLayer)) |
| 1367 | }) |
| 1368 | }) |
| 1369 | }) |
| 1370 | |
| 1371 | describe("StreamNdjson", () => { |
| 1372 | const Item = Schema.Struct({ text: Schema.String }) |
| 1373 | const Api = HttpApi.make("api").add( |
| 1374 | HttpApiGroup.make("group").add( |
| 1375 | HttpApiEndpoint.get("failing", "/failing", { |
| 1376 | success: HttpApiSchema.StreamNdjson({ schema: Item }) |
| 1377 | }) |
| 1378 | ) |
| 1379 | ) |
| 1380 | const makeApiLayer = (firstItemReceived: Effect.Effect<void>) => { |
| 1381 | const GroupLayer = HttpApiBuilder.group( |
| 1382 | Api, |
| 1383 | "group", |
| 1384 | (handlers) => |
| 1385 | handlers.handle("failing", () => |
| 1386 | Effect.succeed( |
| 1387 | Stream.make({ text: "a" }).pipe( |
| 1388 | Stream.concat(Stream.fromEffect(firstItemReceived.pipe(Effect.andThen(Effect.die("boom"))))) |
| 1389 | ) |
| 1390 | )) |
| 1391 | ) |
| 1392 | return HttpRouter.serve( |
| 1393 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer)), |
| 1394 | { disableListenLog: true, disableLogger: true } |
| 1395 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 1396 | } |
| 1397 | |
| 1398 | it.effect("a server failure mid-stream reaches the client as a body read error, not a clean end", () => |
| 1399 | Effect.gen(function*() { |
| 1400 | const firstItemReceived = yield* Deferred.make<void>() |
| 1401 | yield* Effect.gen(function*() { |
| 1402 | const client = yield* HttpApiClient.make(Api) |
| 1403 | const stream = yield* client.group.failing() |
| 1404 | const delivered: Array<typeof Item.Type> = [] |
| 1405 | const error = yield* stream.pipe( |
| 1406 | Stream.runForEach((item) => { |
| 1407 | delivered.push(item) |
| 1408 | return Deferred.succeed(firstItemReceived, undefined) |
| 1409 | }), |
| 1410 | Effect.flip |
| 1411 | ) |
| 1412 | assert.deepStrictEqual(delivered, [{ text: "a" }]) |
| 1413 | assert(error._tag === "HttpClientError" && error.reason._tag === "DecodeError") |
| 1414 | }).pipe(Effect.provide(makeApiLayer(Deferred.await(firstItemReceived)))) |
| 1415 | })) |
| 1416 | }) |
| 1417 | }) |
| 1418 | |
| 1419 | describe("error option", () => { |
| 1420 | it.effect("no content", () => { |
| 1421 | const Api = HttpApi.make("api") |
| 1422 | .add( |
| 1423 | HttpApiGroup.make("group") |
| 1424 | .add( |
| 1425 | HttpApiEndpoint.get("a", "/a", { |
| 1426 | error: Schema.Void.pipe(HttpApiSchema.status("Forbidden")) |
| 1427 | }), |
| 1428 | HttpApiEndpoint.get("b", "/b", { |
| 1429 | error: HttpApiSchema.NoContent, |
| 1430 | success: Schema.String |
| 1431 | }), |
| 1432 | HttpApiEndpoint.get("c", "/c", { |
| 1433 | error: Schema.String.pipe( |
| 1434 | HttpApiSchema.asNoContent({ decode: () => "c" }), |
| 1435 | HttpApiSchema.status("Forbidden") |
| 1436 | ) |
| 1437 | }), |
| 1438 | HttpApiEndpoint.get("d", "/d", { |
| 1439 | error: HttpApiSchema.Empty(400) |
| 1440 | }), |
| 1441 | HttpApiEndpoint.get("e", "/e", { |
| 1442 | error: HttpApiError.UnauthorizedNoContent |
| 1443 | }), |
| 1444 | HttpApiEndpoint.get("f", "/f", { |
| 1445 | error: HttpApiError.BadRequestNoContent |
| 1446 | }) |
| 1447 | ) |
| 1448 | ) |
| 1449 | const GroupLayer = HttpApiBuilder.group( |
| 1450 | Api, |
| 1451 | "group", |
| 1452 | (handlers) => |
| 1453 | handlers |
| 1454 | .handle("a", () => Effect.fail(undefined)) |
| 1455 | .handle("b", () => Effect.fail(HttpApiSchema.NoContent.make())) |
| 1456 | .handle("c", () => Effect.fail("")) |
| 1457 | .handle("d", () => Effect.fail(void 0)) |
| 1458 | .handle("e", () => Effect.fail(new HttpApiError.Unauthorized({}))) |
| 1459 | .handle("f", () => Effect.fail(new HttpApiError.BadRequest({}))) |
| 1460 | ) |
| 1461 | |
| 1462 | const ApiLayer = HttpRouter.serve( |
| 1463 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer)), |
| 1464 | { disableListenLog: true, disableLogger: true } |
| 1465 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 1466 | |
| 1467 | return Effect.gen(function*() { |
| 1468 | // server side |
| 1469 | yield* assertServerText(yield* HttpClient.get("/a"), 403, "") |
| 1470 | yield* assertServerText(yield* HttpClient.get("/b"), 204, "") |
| 1471 | yield* assertServerText(yield* HttpClient.get("/c"), 403, "") |
| 1472 | yield* assertServerText(yield* HttpClient.get("/d"), 400, "") |
| 1473 | yield* assertServerText(yield* HttpClient.get("/e"), 401, "") |
| 1474 | yield* assertServerText(yield* HttpClient.get("/f"), 400, "") |
| 1475 | |
| 1476 | // client side |
| 1477 | const client = yield* HttpApiClient.make(Api) |
| 1478 | yield* assertClientError(client.group.a(), undefined) |
| 1479 | yield* assertClientError(client.group.b(), undefined) |
| 1480 | yield* assertClientError(client.group.c(), "c") |
| 1481 | yield* assertClientError(client.group.d(), undefined) |
| 1482 | yield* assertClientError(client.group.e(), new HttpApiError.Unauthorized({})) |
| 1483 | yield* assertClientError(client.group.f(), new HttpApiError.BadRequest({})) |
| 1484 | }).pipe(Effect.provide(ApiLayer)) |
| 1485 | }) |
| 1486 | }) |
| 1487 | |
| 1488 | describe("original tests", () => { |
| 1489 | describe("payload", () => { |
| 1490 | it.effect("is decoded / encoded", () => |
| 1491 | Effect.gen(function*() { |
| 1492 | const expected = new User({ |
| 1493 | id: 123, |
| 1494 | name: "Joe", |
| 1495 | createdAt: DateTime.makeUnsafe(0) |
| 1496 | }) |
| 1497 | const client = yield* HttpApiClient.make(Api) |
| 1498 | const clientUsersGroup = yield* HttpApiClient.group(Api, { |
| 1499 | httpClient: yield* HttpClient.HttpClient, |
| 1500 | group: "users" |
| 1501 | }) |
| 1502 | const clientUsersEndpointCreate = yield* HttpApiClient.endpoint(Api, { |
| 1503 | httpClient: yield* HttpClient.HttpClient, |
| 1504 | group: "users", |
| 1505 | endpoint: "create" |
| 1506 | }) |
| 1507 | |
| 1508 | const apiClientUser = yield* client.users.create({ |
| 1509 | query: { id: 123 }, |
| 1510 | payload: { name: "Joe" } |
| 1511 | }) |
| 1512 | assert.deepStrictEqual( |
| 1513 | apiClientUser, |
| 1514 | expected |
| 1515 | ) |
| 1516 | const groupClientUser = yield* clientUsersGroup.create({ |
| 1517 | query: { id: 123 }, |
| 1518 | payload: { name: "Joe" } |
| 1519 | }) |
| 1520 | assert.deepStrictEqual( |
| 1521 | groupClientUser, |
| 1522 | expected |
| 1523 | ) |
| 1524 | const endpointClientUser = yield* clientUsersEndpointCreate({ |
| 1525 | query: { id: 123 }, |
| 1526 | payload: { name: "Joe" } |
| 1527 | }) |
| 1528 | assert.deepStrictEqual( |
| 1529 | endpointClientUser, |
| 1530 | expected |
| 1531 | ) |
| 1532 | }).pipe(Effect.provide(HttpLayer))) |
| 1533 | |
| 1534 | it.live("multipart", () => |
| 1535 | Effect.gen(function*() { |
| 1536 | const client = yield* HttpApiClient.make(Api) |
| 1537 | const data = new FormData() |
| 1538 | data.append("file", new Blob(["hello"], { type: "text/plain" }), "hello.txt") |
| 1539 | const result = yield* client.users.upload({ payload: data, params: {} }) |
| 1540 | assert.deepStrictEqual(result, { |
| 1541 | contentType: "text/plain", |
| 1542 | length: 5 |
| 1543 | }) |
| 1544 | }).pipe(Effect.provide(HttpLayer))) |
| 1545 | |
| 1546 | it.live("multipart stream", () => |
| 1547 | Effect.gen(function*() { |
| 1548 | const client = yield* HttpApiClient.make(Api) |
| 1549 | const data = new FormData() |
| 1550 | data.append("file", new Blob(["hello"], { type: "text/plain" }), "hello.txt") |
| 1551 | const result = yield* client.users.uploadStream({ payload: data }) |
| 1552 | assert.deepStrictEqual(result, { |
| 1553 | contentType: "text/plain", |
| 1554 | length: 5 |
| 1555 | }) |
| 1556 | }).pipe(Effect.provide(HttpLayer))) |
| 1557 | }) |
| 1558 | |
| 1559 | describe("headers", () => { |
| 1560 | it.effect("should accept a record of schemas", () => { |
| 1561 | const Api = HttpApi.make("api").add( |
| 1562 | HttpApiGroup.make("group").add( |
| 1563 | HttpApiEndpoint.get("get", "/:id", { |
| 1564 | headers: { |
| 1565 | id: Schema.FiniteFromString |
| 1566 | }, |
| 1567 | success: Schema.String |
| 1568 | }) |
| 1569 | ) |
| 1570 | ) |
| 1571 | const GroupLayer = HttpApiBuilder.group( |
| 1572 | Api, |
| 1573 | "group", |
| 1574 | (handlers) => handlers.handle("get", (ctx) => Effect.succeed(`User ${ctx.headers.id}`)) |
| 1575 | ) |
| 1576 | |
| 1577 | const ApiLayer = HttpRouter.serve( |
| 1578 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer)), |
| 1579 | { disableListenLog: true, disableLogger: true } |
| 1580 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 1581 | |
| 1582 | return Effect.gen(function*() { |
| 1583 | const client = yield* HttpApiClient.make(Api) |
| 1584 | const result = yield* client.group.get({ headers: { id: 1 } }) |
| 1585 | assert.strictEqual(result, "User 1") |
| 1586 | }).pipe(Effect.provide(ApiLayer)) |
| 1587 | }) |
| 1588 | |
| 1589 | it.effect("is decoded / encoded", () => |
| 1590 | Effect.gen(function*() { |
| 1591 | const client = yield* HttpApiClient.make(Api) |
| 1592 | const users = yield* client.users.list({ |
| 1593 | headers: { page: 1 }, |
| 1594 | query: {} |
| 1595 | }) |
| 1596 | const user = users[0] |
| 1597 | assert.deepStrictEqual( |
| 1598 | user, |
| 1599 | new User({ |
| 1600 | id: 1, |
| 1601 | name: "page 1", |
| 1602 | createdAt: DateTime.makeUnsafe(0) |
| 1603 | }) |
| 1604 | ) |
| 1605 | }).pipe(Effect.provide(HttpLayer))) |
| 1606 | }) |
| 1607 | |
| 1608 | describe("errors", () => { |
| 1609 | it.effect("empty errors have no body", () => |
| 1610 | Effect.gen(function*() { |
| 1611 | const response = yield* HttpClient.get("/groups/0") |
| 1612 | assert.strictEqual(response.status, 418) |
| 1613 | const text = yield* response.text |
| 1614 | assert.strictEqual(text, "") |
| 1615 | }).pipe(Effect.provide(HttpLayer))) |
| 1616 | |
| 1617 | it.effect("empty errors decode", () => |
| 1618 | Effect.gen(function*() { |
| 1619 | const client = yield* HttpApiClient.make(Api) |
| 1620 | const error = yield* client.groups.findById({ params: { id: 0 } }).pipe( |
| 1621 | Effect.flip |
| 1622 | ) |
| 1623 | assert.deepStrictEqual(error, new GroupError({})) |
| 1624 | }).pipe(Effect.provide(HttpLayer))) |
| 1625 | |
| 1626 | it.effect("default to 500 status code", () => |
| 1627 | Effect.gen(function*() { |
| 1628 | const response = yield* HttpClientRequest.get("/users").pipe( |
| 1629 | HttpClientRequest.setHeaders({ page: "0" }), |
| 1630 | HttpClient.execute |
| 1631 | ) |
| 1632 | assert.strictEqual(response.status, 500) |
| 1633 | const body = yield* response.json |
| 1634 | assert.deepStrictEqual(body, { |
| 1635 | _tag: "NoStatusError" |
| 1636 | }) |
| 1637 | }).pipe(Effect.provide(HttpLayer))) |
| 1638 | |
| 1639 | it.effect("class level annotations", () => |
| 1640 | Effect.gen(function*() { |
| 1641 | const response = yield* HttpClientRequest.post("/users").pipe( |
| 1642 | HttpClientRequest.setUrlParams({ id: "0" }), |
| 1643 | HttpClientRequest.bodyJsonUnsafe({ name: "boom" }), |
| 1644 | HttpClient.execute |
| 1645 | ) |
| 1646 | assert.strictEqual(response.status, 400) |
| 1647 | }).pipe(Effect.provide(HttpLayer))) |
| 1648 | |
| 1649 | it.effect("BadRequest", () => |
| 1650 | Effect.gen(function*() { |
| 1651 | const client = yield* HttpApiClient.make(Api) |
| 1652 | const error = yield* client.users.upload({ params: {}, payload: new FormData() }).pipe( |
| 1653 | Effect.flip |
| 1654 | ) |
| 1655 | assert(error._tag === "HttpClientError" && error.reason._tag === "DecodeError") |
| 1656 | assert.strictEqual(error.reason.response.status, 400) |
| 1657 | }).pipe(Effect.provide(HttpLayer))) |
| 1658 | }) |
| 1659 | |
| 1660 | it.effect("handler level context", () => |
| 1661 | Effect.gen(function*() { |
| 1662 | const client = yield* HttpApiClient.make(Api) |
| 1663 | const users = yield* client.users.list({ headers: { page: 1 }, query: {} }) |
| 1664 | const user = users[0] |
| 1665 | assert.strictEqual(user.name, "page 1") |
| 1666 | assert.deepStrictEqual(user.createdAt, DateTime.makeUnsafe(0)) |
| 1667 | }).pipe(Effect.provide(HttpLayer))) |
| 1668 | |
| 1669 | it.effect("custom client context", () => |
| 1670 | Effect.gen(function*() { |
| 1671 | let tapped = false |
| 1672 | const client = yield* HttpApiClient.makeWith(Api, { |
| 1673 | httpClient: (yield* HttpClient.HttpClient).pipe( |
| 1674 | HttpClient.tapRequest(Effect.fnUntraced(function*(_request) { |
| 1675 | tapped = true |
| 1676 | yield* CurrentUser |
| 1677 | })) |
| 1678 | ) |
| 1679 | }) |
| 1680 | const users = yield* client.users.list({ headers: { page: 1 }, query: {} }).pipe( |
| 1681 | Effect.provideService( |
| 1682 | CurrentUser, |
| 1683 | new User({ |
| 1684 | id: 1, |
| 1685 | name: "foo", |
| 1686 | createdAt: DateTime.makeUnsafe(0) |
| 1687 | }) |
| 1688 | ) |
| 1689 | ) |
| 1690 | const user = users[0] |
| 1691 | assert.strictEqual(user.name, "page 1") |
| 1692 | assert.isTrue(tapped) |
| 1693 | }).pipe(Effect.provide(HttpLayer))) |
| 1694 | |
| 1695 | describe("security", () => { |
| 1696 | it.effect("security middleware sets current user", () => |
| 1697 | Effect.gen(function*() { |
| 1698 | const server = yield* HttpServer.HttpServer |
| 1699 | const url = new URL(HttpServer.formatAddress(server.address)) |
| 1700 | url.hostname = "127.0.0.1" |
| 1701 | const ref = yield* Ref.make(Cookies.mergeIntoArray( |
| 1702 | [], |
| 1703 | url.origin, |
| 1704 | Cookies.fromSetCookie("token=foo; Path=/"), |
| 1705 | yield* Clock.currentTimeMillis |
| 1706 | )) |
| 1707 | const client = yield* HttpApiClient.makeWith(Api, { |
| 1708 | httpClient: HttpClient.withCookiesRef(yield* HttpClient.HttpClient, ref) |
| 1709 | }) |
| 1710 | const user = yield* client.users.findById({ params: { id: -1 } }) |
| 1711 | assert.strictEqual(user.name, "foo") |
| 1712 | }).pipe(Effect.provide(HttpLayer))) |
| 1713 | |
| 1714 | it.effect("apiKey header security", () => |
| 1715 | Effect.gen(function*() { |
| 1716 | const decode = HttpApiBuilder.securityDecode(securityHeader).pipe( |
| 1717 | Effect.provideService( |
| 1718 | HttpServerRequest.HttpServerRequest, |
| 1719 | HttpServerRequest.fromWeb( |
| 1720 | new Request("http://localhost:3000/", { |
| 1721 | headers: { |
| 1722 | "x-api-key": "foo" |
| 1723 | } |
| 1724 | }) |
| 1725 | ) |
| 1726 | ), |
| 1727 | Effect.provideService(HttpServerRequest.ParsedSearchParams, {}) |
| 1728 | ) |
| 1729 | const redacted = yield* decode |
| 1730 | assert.strictEqual(Redacted.value(redacted), "foo") |
| 1731 | }).pipe(Effect.provide(HttpLayer))) |
| 1732 | |
| 1733 | it.effect("apiKey query security", () => |
| 1734 | Effect.gen(function*() { |
| 1735 | const redacted = yield* HttpApiBuilder.securityDecode(securityQuery).pipe( |
| 1736 | Effect.provideService( |
| 1737 | HttpServerRequest.HttpServerRequest, |
| 1738 | HttpServerRequest.fromWeb(new Request("http://localhost:3000/")) |
| 1739 | ), |
| 1740 | Effect.provideService(HttpServerRequest.ParsedSearchParams, { |
| 1741 | api_key: "foo" |
| 1742 | }) |
| 1743 | ) |
| 1744 | assert.strictEqual(Redacted.value(redacted), "foo") |
| 1745 | }).pipe(Effect.provide(HttpLayer))) |
| 1746 | }) |
| 1747 | |
| 1748 | it.effect("client responseMode decoded-and-response", () => |
| 1749 | Effect.gen(function*() { |
| 1750 | const client = yield* HttpApiClient.make(Api) |
| 1751 | const [users, response] = yield* client.users.list({ |
| 1752 | headers: { page: 1 }, |
| 1753 | query: {}, |
| 1754 | responseMode: "decoded-and-response" |
| 1755 | }) |
| 1756 | assert.strictEqual(users[0].name, "page 1") |
| 1757 | assert.strictEqual(response.status, 200) |
| 1758 | }).pipe(Effect.provide(HttpLayer))) |
| 1759 | |
| 1760 | it.effect("client responseMode response-only skips decoding", () => { |
| 1761 | const Api = HttpApi.make("api").add( |
| 1762 | HttpApiGroup.make("group").add( |
| 1763 | HttpApiEndpoint.get("bad", "/bad", { |
| 1764 | success: Schema.Struct({ |
| 1765 | value: Schema.Finite |
| 1766 | }) |
| 1767 | }) |
| 1768 | ) |
| 1769 | ) |
| 1770 | |
| 1771 | const GroupLayer = HttpApiBuilder.group( |
| 1772 | Api, |
| 1773 | "group", |
| 1774 | (handlers) => handlers.handleRaw("bad", () => Effect.succeed(HttpServerResponse.text("not-json"))) |
| 1775 | ) |
| 1776 | |
| 1777 | const ApiLayer = HttpRouter.serve( |
| 1778 | HttpApiBuilder.layer(Api).pipe(Layer.provide(GroupLayer)), |
| 1779 | { disableListenLog: true, disableLogger: true } |
| 1780 | ).pipe(Layer.provideMerge(NodeHttpServer.layerTest)) |
| 1781 | |
| 1782 | return Effect.gen(function*() { |
| 1783 | const client = yield* HttpApiClient.make(Api) |
| 1784 | |
| 1785 | yield* Effect.flip(client.group.bad()) |
| 1786 | |
| 1787 | const response = yield* client.group.bad({ |
| 1788 | responseMode: "response-only" |
| 1789 | }) |
| 1790 | assert.strictEqual(response.status, 200) |
| 1791 | assert.strictEqual(yield* response.text, "not-json") |
| 1792 | }).pipe(Effect.provide(ApiLayer)) |
| 1793 | }) |
| 1794 | |
| 1795 | it.effect("multiple payload types", () => |
| 1796 | Effect.gen(function*() { |
| 1797 | const client = yield* HttpApiClient.make(Api) |
| 1798 | let [group, response] = yield* client.groups.create({ |
| 1799 | payload: { name: "Some group" }, |
| 1800 | responseMode: "decoded-and-response" |
| 1801 | }) |
| 1802 | assert.deepStrictEqual(group, new Group({ id: 1, name: "Some group" })) |
| 1803 | assert.strictEqual(response.status, 200) |
| 1804 | |
| 1805 | const data = new FormData() |
| 1806 | data.set("name", "Some group") |
| 1807 | ;[group, response] = yield* client.groups.create({ |
| 1808 | payload: data, |
| 1809 | responseMode: "decoded-and-response" |
| 1810 | }) |
| 1811 | assert.deepStrictEqual(group, new Group({ id: 1, name: "Some group" })) |
| 1812 | assert.strictEqual(response.status, 200) |
| 1813 | |
| 1814 | group = yield* client.groups.create({ |
| 1815 | payload: { foo: "Some group" } |
| 1816 | }) |
| 1817 | assert.deepStrictEqual(group, new Group({ id: 1, name: "Some group" })) |
| 1818 | }).pipe(Effect.provide(HttpLayer))) |
| 1819 | |
| 1820 | it.effect(".handle can return HttpServerResponse", () => |
| 1821 | Effect.gen(function*() { |
| 1822 | const client = yield* HttpApiClient.make(Api) |
| 1823 | const response = yield* client.groups.handle({ |
| 1824 | params: { id: 1 }, |
| 1825 | payload: { name: "Some group" } |
| 1826 | }) |
| 1827 | assert.deepStrictEqual(response, { |
| 1828 | id: 1, |
| 1829 | name: "Some group" |
| 1830 | }) |
| 1831 | }).pipe(Effect.provide(HttpLayer))) |
| 1832 | |
| 1833 | it.effect(".handleRaw can manually process body", () => |
| 1834 | Effect.gen(function*() { |
| 1835 | const client = yield* HttpApiClient.make(Api) |
| 1836 | const response = yield* client.groups.handleRaw({ |
| 1837 | params: { id: 1 }, |
| 1838 | payload: { name: "Some group" } |
| 1839 | }) |
| 1840 | assert.deepStrictEqual(response, { |
| 1841 | id: 1, |
| 1842 | name: "Some group" |
| 1843 | }) |
| 1844 | }).pipe(Effect.provide(HttpLayer))) |
| 1845 | |
| 1846 | describe("OpenAPI spec", () => { |
| 1847 | it("fixture", () => { |
| 1848 | const spec = OpenApi.fromApi(Api) |
| 1849 | expect(spec).toMatchSnapshot() |
| 1850 | }) |
| 1851 | }) |
| 1852 | |
| 1853 | it.effect("error from plain text", () => { |
| 1854 | class RateLimitError extends Schema.Error<RateLimitError>("RateLimitError")({ |
| 1855 | _tag: Schema.tag("RateLimitError"), |
| 1856 | message: Schema.String |
| 1857 | }) {} |
| 1858 | |
| 1859 | const RateLimitErrorSchema = Schema.String.pipe( |
| 1860 | Schema.decodeTo( |
| 1861 | RateLimitError, |
| 1862 | SchemaTransformation.transform({ |
| 1863 | encode: ({ message }) => message, |
| 1864 | decode: (message) => new RateLimitError({ message }) |
| 1865 | }) |
| 1866 | ), |
| 1867 | HttpApiSchema.status("TooManyRequests"), |
| 1868 | HttpApiSchema.asText() |
| 1869 | ) |
| 1870 | |
| 1871 | const Api = HttpApi.make("api").add( |
| 1872 | HttpApiGroup.make("group").add( |
| 1873 | HttpApiEndpoint.get("error", "/error", { |
| 1874 | error: RateLimitErrorSchema |
| 1875 | }) |
| 1876 | ) |
| 1877 | ) |
| 1878 | const ApiLayer = HttpApiBuilder.layer(Api).pipe( |
| 1879 | Layer.provide( |
| 1880 | HttpApiBuilder.group( |
| 1881 | Api, |
| 1882 | "group", |
| 1883 | (handlers) => handlers.handle("error", () => new RateLimitError({ message: "Rate limit exceeded" })) |
| 1884 | ) |
| 1885 | ), |
| 1886 | HttpRouter.serve, |
| 1887 | Layer.provideMerge(NodeHttpServer.layerTest) |
| 1888 | ) |
| 1889 | return Effect.gen(function*() { |
| 1890 | const client = yield* HttpApiClient.make(Api) |
| 1891 | const response = yield* client.group.error().pipe(Effect.flip) |
| 1892 | assert.deepStrictEqual(response, new RateLimitError({ message: "Rate limit exceeded" })) |
| 1893 | }).pipe(Effect.provide(ApiLayer)) |
| 1894 | }) |
| 1895 | }) |
| 1896 | |
| 1897 | describe("HttpApiTest", () => { |
| 1898 | it.effect("works", () => |
| 1899 | Effect.gen(function*() { |
| 1900 | const client = yield* HttpApiTest.groups(Api, ["groups"]) |
| 1901 | const result = yield* client.groups.findById({ params: { id: 0 } }) |
| 1902 | assert.deepStrictEqual(result, new Group({ id: 1, name: "foo" })) |
| 1903 | }).pipe( |
| 1904 | Effect.provide([ |
| 1905 | NodeHttpServer.layerHttpServices, |
| 1906 | AuthorizationLayer, |
| 1907 | HttpApiBuilder.group(Api, "groups", (handlers) => |
| 1908 | handlers |
| 1909 | .handle("findById", () => Effect.succeed(new Group({ id: 1, name: "foo" }))) |
| 1910 | .handle( |
| 1911 | "handle", |
| 1912 | () => Effect.die("unimplemented") |
| 1913 | ) |
| 1914 | .handle("create", () => Effect.die("unimplemented")) |
| 1915 | .handle("handleRaw", () => Effect.die("unimplemented"))) |
| 1916 | ]) |
| 1917 | )) |
| 1918 | }) |
| 1919 | }) |
| 1920 | |
| 1921 | const UpgradeApi = HttpApi.make("api").add( |
| 1922 | HttpApiGroup.make("containers").add( |
| 1923 | HttpApiEndpoint.post("start", "/start", { |
| 1924 | success: HttpApiSchema.Upgrade({ |
| 1925 | protocol: "tcp", |
| 1926 | headers: { "content-type": Schema.Literal("application/raw") } |
| 1927 | }) |
| 1928 | }) |
| 1929 | ) |
| 1930 | ) |
| 1931 | |
| 1932 | // Answers upgrade requests with a 101 whose Content-Type does not match |
| 1933 | // UpgradeApi, and completes `closed` once the client closes the connection. |
| 1934 | const makeUpgradeServer = Effect.gen(function*() { |
| 1935 | const closed = yield* Deferred.make<void>() |
| 1936 | const sockets = new Set<Net.Socket>() |
| 1937 | const server = yield* Effect.acquireRelease( |
| 1938 | Effect.callback<Http.Server>((resume) => { |
| 1939 | const server = Http.createServer() |
| 1940 | server.on("upgrade", (_request: Http.IncomingMessage, socket: Net.Socket) => { |
| 1941 | sockets.add(socket) |
| 1942 | const done = () => Deferred.doneUnsafe(closed, Effect.void) |
| 1943 | socket.once("end", done) |
| 1944 | socket.once("close", done) |
| 1945 | socket.write( |
| 1946 | "HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: tcp\r\n" + |
| 1947 | "Content-Type: text/plain\r\n\r\n" |
| 1948 | ) |
| 1949 | // the server side must read for the client's close to arrive |
| 1950 | socket.resume() |
| 1951 | }) |
| 1952 | server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server))) |
| 1953 | }), |
| 1954 | (server) => |
| 1955 | Effect.callback<void>((resume) => { |
| 1956 | for (const socket of sockets) socket.destroy() |
| 1957 | server.close(() => resume(Effect.void)) |
| 1958 | }) |
| 1959 | ) |
| 1960 | return { baseUrl: `http://127.0.0.1:${(server.address() as Net.AddressInfo).port}`, closed } |
| 1961 | }) |
| 1962 | |
| 1963 | const readUntilClose = Effect.fnUntraced(function*(reader: Socket.Reader) { |
| 1964 | const decoder = new TextDecoder() |
| 1965 | let text = "" |
| 1966 | while (true) { |
| 1967 | const chunks = yield* reader.pull.pipe( |
| 1968 | Effect.catchReason("SocketError", "SocketCloseError", () => Effect.succeed(undefined)) |
| 1969 | ) |
| 1970 | if (chunks === undefined) return text |
| 1971 | for (const chunk of chunks) text += typeof chunk === "string" ? chunk : decoder.decode(chunk) |
| 1972 | } |
| 1973 | }) |
| 1974 | |
| 1975 | class UserError extends Schema.Error<UserError>("UserError")({ |
| 1976 | _tag: Schema.tag("UserError") |
| 1977 | }, { |
| 1978 | httpApiStatus: 400 |
| 1979 | }) {} |
| 1980 | class GroupError extends Schema.Error<GroupError>("GroupError")({ |
| 1981 | _tag: Schema.tag("GroupError") |
| 1982 | }, { |
| 1983 | httpApiStatus: 418 |
| 1984 | }) {} |
| 1985 | class NoStatusError extends Schema.Error<NoStatusError>("NoStatusError")({ |
| 1986 | _tag: Schema.tag("NoStatusError") |
| 1987 | }) {} |
| 1988 | |
| 1989 | class User extends Schema.Class<User>("User")({ |
| 1990 | id: Schema.Int, |
| 1991 | uuid: Schema.optional(Schema.String), |
| 1992 | name: Schema.String, |
| 1993 | createdAt: Schema.DateTimeUtcFromString |
| 1994 | }, { |
| 1995 | description: "Some description for User" |
| 1996 | }) {} |
| 1997 | |
| 1998 | class Group extends Schema.Class<Group>("Group")({ |
| 1999 | id: Schema.Int, |
| 2000 | name: Schema.String |
| 2001 | }) {} |
| 2002 | |
| 2003 | const securityHeader = HttpApiSecurity.apiKey({ |
| 2004 | in: "header", |
| 2005 | key: "x-api-key" |
| 2006 | }) |
| 2007 | |
| 2008 | const securityQuery = HttpApiSecurity.apiKey({ |
| 2009 | in: "query", |
| 2010 | key: "api_key" |
| 2011 | }) |
| 2012 | |
| 2013 | class CurrentUser extends Context.Service<CurrentUser, User>()("CurrentUser") {} |
| 2014 | |
| 2015 | class Authorization extends HttpApiMiddleware.Service<Authorization, { |
| 2016 | provides: CurrentUser |
| 2017 | }>()("Authorization", { |
| 2018 | security: { |
| 2019 | cookie: HttpApiSecurity.apiKey({ |
| 2020 | in: "cookie", |
| 2021 | key: "token" |
| 2022 | }) |
| 2023 | } |
| 2024 | }) {} |
| 2025 | |
| 2026 | class GroupsApi extends HttpApiGroup.make("groups").add( |
| 2027 | HttpApiEndpoint.get("findById", "/:id", { |
| 2028 | params: { |
| 2029 | id: Schema.FiniteFromString |
| 2030 | }, |
| 2031 | success: Group, |
| 2032 | error: GroupError.pipe(HttpApiSchema.asNoContent({ |
| 2033 | decode: () => new GroupError({}) |
| 2034 | })) |
| 2035 | }), |
| 2036 | HttpApiEndpoint.post("create", "/", { |
| 2037 | payload: [ |
| 2038 | Schema.Struct(Struct.pick(Group.fields, ["name"])), |
| 2039 | Schema.Struct({ foo: Schema.String }).pipe( |
| 2040 | HttpApiSchema.asFormUrlEncoded() |
| 2041 | ), |
| 2042 | Schema.Struct(Struct.pick(Group.fields, ["name"])).pipe( |
| 2043 | HttpApiSchema.asMultipart() |
| 2044 | ) |
| 2045 | ], |
| 2046 | success: Group |
| 2047 | }), |
| 2048 | HttpApiEndpoint.post("handle", "/handle/:id", { |
| 2049 | params: { |
| 2050 | id: Schema.FiniteFromString |
| 2051 | }, |
| 2052 | payload: Schema.Struct({ |
| 2053 | name: Schema.String |
| 2054 | }), |
| 2055 | success: Schema.Struct({ |
| 2056 | id: Schema.Finite, |
| 2057 | name: Schema.String |
| 2058 | }) |
| 2059 | }), |
| 2060 | HttpApiEndpoint.post("handleRaw", "/handleraw/:id", { |
| 2061 | params: { |
| 2062 | id: Schema.FiniteFromString |
| 2063 | }, |
| 2064 | payload: Schema.Struct({ |
| 2065 | name: Schema.String |
| 2066 | }), |
| 2067 | success: Schema.Struct({ |
| 2068 | id: Schema.Finite, |
| 2069 | name: Schema.String |
| 2070 | }) |
| 2071 | }) |
| 2072 | ).prefix("/groups") {} |
| 2073 | |
| 2074 | class UsersApi extends HttpApiGroup.make("users") |
| 2075 | .add( |
| 2076 | HttpApiEndpoint.get("findById", "/:id", { |
| 2077 | params: { |
| 2078 | id: Schema.Finite |
| 2079 | }, |
| 2080 | success: User, |
| 2081 | error: UserError |
| 2082 | }), |
| 2083 | HttpApiEndpoint.post("create", "/", { |
| 2084 | payload: Schema.Struct(Struct.omit(User.fields, ["id", "createdAt"])), |
| 2085 | query: { |
| 2086 | id: Schema.Finite |
| 2087 | }, |
| 2088 | success: User, |
| 2089 | error: [UserError, UserError] |
| 2090 | }), |
| 2091 | HttpApiEndpoint.get("list", "/", { |
| 2092 | headers: { |
| 2093 | page: Schema.Finite.pipe( |
| 2094 | Schema.optionalKey, |
| 2095 | Schema.decode({ |
| 2096 | decode: SchemaGetter.withDefault(Effect.succeed(1)), |
| 2097 | encode: SchemaGetter.passthrough() |
| 2098 | }) |
| 2099 | ) |
| 2100 | }, |
| 2101 | query: { |
| 2102 | query: Schema.optional(Schema.String).annotate({ description: "search query" }) |
| 2103 | }, |
| 2104 | success: Schema.Array(User), |
| 2105 | error: NoStatusError |
| 2106 | }) |
| 2107 | .annotate(OpenApi.Deprecated, true) |
| 2108 | .annotate(OpenApi.Summary, "test summary") |
| 2109 | .annotateMerge(OpenApi.annotations({ identifier: "listUsers" })), |
| 2110 | HttpApiEndpoint.post("upload", "/upload/:0?", { |
| 2111 | params: { |
| 2112 | 0: Schema.optional(Schema.String) |
| 2113 | }, |
| 2114 | payload: Schema.Struct({ |
| 2115 | file: Multipart.SingleFileSchema |
| 2116 | }).pipe(HttpApiSchema.asMultipart()), |
| 2117 | success: Schema.Struct({ |
| 2118 | contentType: Schema.String, |
| 2119 | length: Schema.Int |
| 2120 | }) |
| 2121 | }), |
| 2122 | HttpApiEndpoint.post("uploadStream", `/uploadstream`, { |
| 2123 | payload: Schema.Struct({ |
| 2124 | file: Multipart.SingleFileSchema |
| 2125 | }).pipe(HttpApiSchema.asMultipartStream()), |
| 2126 | success: Schema.Struct({ |
| 2127 | contentType: Schema.String, |
| 2128 | length: Schema.Int |
| 2129 | }) |
| 2130 | }) |
| 2131 | ) |
| 2132 | .middleware(Authorization) |
| 2133 | .annotateMerge(OpenApi.annotations({ title: "Users API" })) |
| 2134 | {} |
| 2135 | |
| 2136 | class TopLevelApi extends HttpApiGroup.make("root", { topLevel: true }) |
| 2137 | .add( |
| 2138 | HttpApiEndpoint.get("healthz", `/healthz`, { |
| 2139 | success: HttpApiSchema.NoContent.annotate({ description: "Empty" }) |
| 2140 | }) |
| 2141 | ) |
| 2142 | {} |
| 2143 | |
| 2144 | class AnotherApi extends HttpApi.make("another").add(GroupsApi) {} |
| 2145 | |
| 2146 | class Api extends HttpApi.make("api") |
| 2147 | .addHttpApi(AnotherApi) |
| 2148 | .add(UsersApi.prefix("/users")) |
| 2149 | .add(TopLevelApi) |
| 2150 | .annotateMerge(OpenApi.annotations({ |
| 2151 | title: "API", |
| 2152 | summary: "test api summary", |
| 2153 | transform: (openApiSpec) => ({ |
| 2154 | ...openApiSpec, |
| 2155 | tags: [...openApiSpec.tags ?? [], { |
| 2156 | name: "Tag from OpenApi.Transform annotation" |
| 2157 | }] |
| 2158 | }) |
| 2159 | })) |
| 2160 | .annotate( |
| 2161 | HttpApi.AdditionalSchemas, |
| 2162 | [ |
| 2163 | Schema.Struct({ |
| 2164 | contentType: Schema.String, |
| 2165 | length: Schema.Int |
| 2166 | }).annotate({ |
| 2167 | identifier: "ComponentsSchema" |
| 2168 | }) |
| 2169 | ] |
| 2170 | ) |
| 2171 | {} |
| 2172 | |
| 2173 | // impl |
| 2174 | |
| 2175 | class UserRepo extends Context.Service<UserRepo, { |
| 2176 | readonly findById: (id: number) => Effect.Effect<User> |
| 2177 | }>()("UserRepo") { |
| 2178 | static layer = Layer.succeed(this)({ |
| 2179 | findById: (id) => Effect.map(DateTime.now, (now) => ({ id, name: "foo", createdAt: now })) |
| 2180 | }) |
| 2181 | } |
| 2182 | |
| 2183 | const AuthorizationLayer = Layer.succeed( |
| 2184 | Authorization |
| 2185 | )({ |
| 2186 | cookie: (effect, opts) => |
| 2187 | Effect.provideService( |
| 2188 | effect, |
| 2189 | CurrentUser, |
| 2190 | new User({ |
| 2191 | id: 1, |
| 2192 | name: Redacted.value(opts.credential), |
| 2193 | createdAt: DateTime.nowUnsafe() |
| 2194 | }) |
| 2195 | ) |
| 2196 | }) |
| 2197 | |
| 2198 | const HttpUsersLayer = HttpApiBuilder.group( |
| 2199 | Api, |
| 2200 | "users", |
| 2201 | Effect.fnUntraced(function*(handlers) { |
| 2202 | const fs = yield* FileSystem.FileSystem |
| 2203 | const repo = yield* UserRepo |
| 2204 | return handlers |
| 2205 | .handle("findById", (_) => _.params.id === -1 ? CurrentUser : repo.findById(_.params.id)) |
| 2206 | .handle("create", (_) => |
| 2207 | _.payload.name === "boom" |
| 2208 | ? Effect.fail(new UserError({})) |
| 2209 | : Effect.map(DateTime.now, (now) => |
| 2210 | new User({ |
| 2211 | id: _.query.id, |
| 2212 | name: _.payload.name, |
| 2213 | createdAt: now |
| 2214 | }))) |
| 2215 | .handle("list", (_) => |
| 2216 | _.headers.page === 0 |
| 2217 | ? Effect.fail(new NoStatusError({})) |
| 2218 | // test handler level context |
| 2219 | : Effect.map(DateTime.nowInCurrentZone, (now) => [ |
| 2220 | new User({ |
| 2221 | id: 1, |
| 2222 | name: `page ${_.headers.page}`, |
| 2223 | createdAt: DateTime.toUtc(now) |
| 2224 | }) |
| 2225 | ])) |
| 2226 | .handle("upload", (_) => |
| 2227 | Effect.gen(function*() { |
| 2228 | const stat = yield* fs.stat(_.payload.file.path).pipe(Effect.orDie) |
| 2229 | return { |
| 2230 | contentType: _.payload.file.contentType, |
| 2231 | length: Option.getOrThrow(ByteSize.toNumber(stat.size)) |
| 2232 | } |
| 2233 | })) |
| 2234 | .handle("uploadStream", (_) => |
| 2235 | Effect.gen(function*() { |
| 2236 | const { content, file } = yield* _.payload.pipe( |
| 2237 | Stream.filter(Multipart.isFile), |
| 2238 | Stream.mapEffect((file) => |
| 2239 | file.contentEffect.pipe( |
| 2240 | Effect.map((content) => ({ file, content })) |
| 2241 | ) |
| 2242 | ), |
| 2243 | Stream.runCollect, |
| 2244 | Effect.flatMap((_) => Effect.fromOption(Array.head(_))), |
| 2245 | Effect.orDie |
| 2246 | ) |
| 2247 | return { |
| 2248 | contentType: file.contentType, |
| 2249 | length: content.length |
| 2250 | } |
| 2251 | })) |
| 2252 | }) |
| 2253 | ).pipe( |
| 2254 | Layer.provide([ |
| 2255 | UserRepo.layer, |
| 2256 | AuthorizationLayer |
| 2257 | ]) |
| 2258 | ) |
| 2259 | |
| 2260 | const HttpGroupsLayer = HttpApiBuilder.group( |
| 2261 | Api, |
| 2262 | "groups", |
| 2263 | (handlers) => |
| 2264 | handlers |
| 2265 | .handle("findById", ({ params }) => |
| 2266 | params.id === 0 |
| 2267 | ? Effect.fail(new GroupError({})) |
| 2268 | : Effect.succeed(new Group({ id: 1, name: "foo" }))) |
| 2269 | .handle("create", ({ payload }) => |
| 2270 | Effect.succeed( |
| 2271 | new Group({ |
| 2272 | id: 1, |
| 2273 | name: "foo" in payload ? payload.foo : payload.name |
| 2274 | }) |
| 2275 | )) |
| 2276 | .handle( |
| 2277 | "handle", |
| 2278 | Effect.fnUntraced(function*({ params, payload }) { |
| 2279 | return HttpServerResponse.jsonUnsafe({ |
| 2280 | id: params.id, |
| 2281 | name: payload.name |
| 2282 | }) |
| 2283 | }) |
| 2284 | ) |
| 2285 | .handleRaw( |
| 2286 | "handleRaw", |
| 2287 | Effect.fnUntraced(function*({ params, request }) { |
| 2288 | const body = (yield* Effect.orDie(request.json)) as { name: string } |
| 2289 | return HttpServerResponse.jsonUnsafe({ |
| 2290 | id: params.id, |
| 2291 | name: body.name |
| 2292 | }) |
| 2293 | }) |
| 2294 | ) |
| 2295 | ) |
| 2296 | |
| 2297 | const TopLevelLayer = HttpApiBuilder.group( |
| 2298 | Api, |
| 2299 | "root", |
| 2300 | (handlers) => handlers.handle("healthz", (_) => Effect.void) |
| 2301 | ) |
| 2302 | |
| 2303 | const HttpApiLayer = Layer.provide(HttpApiBuilder.layer(Api), [ |
| 2304 | HttpGroupsLayer, |
| 2305 | HttpUsersLayer, |
| 2306 | TopLevelLayer |
| 2307 | ]) |
| 2308 | |
| 2309 | const HttpLayer = HttpRouter.serve(HttpApiLayer, { |
| 2310 | disableListenLog: true, |
| 2311 | disableLogger: true |
| 2312 | }).pipe( |
| 2313 | Layer.provideMerge(NodeHttpServer.layerTest), |
| 2314 | Layer.provide(DateTime.layerCurrentZoneOffset(0)) |
| 2315 | ) |