Skip to content
Myr

rpc-route.test.ts

This file

Path

apps/web/test/rpc-route.test.ts

206 lines · 5.9 KiB · TypeScript

Last changed by

Merge build/comments-web-rest into mainoscabrielbefore adoption0eb1248

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 1–206why, one step back
1import { describe, expect, it } from "@effect/vitest";
2import { Client } from "@repo/protocol/contracts";3import { ProjectName } from "@repo/protocol/ids";4import { untouchable } from "@repo/testkit/untouchable";5import { Effect, Exit, Schema } from "effect";67import { backend } from "../src/server/backend.ts";8import { serverClientOver } from "../src/server/client.ts";9import { rpcHandler } from "../src/server/rpc.ts";10import type { Backend } from "../src/server/rpc.ts";1112const PLATFORM_URL = "https://platform-test.example.workers.dev";1314const WEB_URL = "https://web-test.example.workers.dev";1516const LIST_ASKS =17 '[{"_tag":"Request","id":"0","tag":"listAsks","payload":{"project":"datekit"},"headers":[]}]';1819const seenOf = (request: Request) =>20 Effect.map(21 Effect.promise(() => request.text()),22 (body) => ({23 authorization: request.headers.get("authorization"),24 body,25 contentType: request.headers.get("content-type"),26 cookie: request.headers.get("cookie"),27 method: request.method,28 url: request.url,29 })30 );3132const recorder = (answer: () => Response) => {33 const handed: Request[] = [];3435 const fetch = (request: Request) => {36 handed.push(request);3738 return Promise.resolve(answer());39 };4041 return { fetch, seen: Effect.suspend(() => Effect.forEach(handed, seenOf)) };42};4344const envWith = (fetch: (request: Request) => Promise<Response>): Env => ({45 PLATFORM: untouchable<Fetcher>("PLATFORM", {46 fetch: (input, init) => fetch(new Request(input, init)),47 }),48 PUBLIC_PLATFORM_URL: PLATFORM_URL,49});5051const unused = envWith(() => Promise.resolve(new Response("unused")));5253const listAsksPost = (headers: Readonly<Record<string, string>> = {}) =>54 new Request(`${WEB_URL}/rpc`, {55 body: LIST_ASKS,56 headers: { "content-type": "application/json", ...headers },57 method: "POST",58 });5960describe("the /rpc route's handler", () => {61 it.effect("hands the request to the backend it was given, with the env", () =>62 Effect.gen(function* () {63 const envs: Env[] = [];64 const stub = recorder(() => new Response("answered"));6566 const given: Backend = (request, env) => {67 envs.push(env);6869 return stub.fetch(request);70 };7172 const response = yield* Effect.promise(() =>73 rpcHandler(given, unused)({ request: listAsksPost() })74 );7576 expect(envs).toStrictEqual([unused]);77 expect(yield* stub.seen).toStrictEqual([78 {79 authorization: null,80 body: LIST_ASKS,81 contentType: "application/json",82 cookie: null,83 method: "POST",84 url: `${WEB_URL}/rpc`,85 },86 ]);87 expect(yield* Effect.promise(() => response.text())).toBe("answered");88 })89 );90});9192describe("the production backend", () => {93 it.effect(94 "forwards to PLATFORM at the platform's URL, keeping method, headers and body, but not the browser's cookies",95 () =>96 Effect.gen(function* () {97 const platform = recorder(() => new Response("from the platform"));9899 const response = yield* Effect.promise(() =>100 backend(101 listAsksPost({ cookie: "theme=dark" }),102 envWith(platform.fetch)103 )104 );105106 expect(yield* platform.seen).toStrictEqual([107 {108 authorization: null,109 body: LIST_ASKS,110 contentType: "application/json",111 cookie: null,112 method: "POST",113 url: `${PLATFORM_URL}/rpc`,114 },115 ]);116 expect(yield* Effect.promise(() => response.text())).toBe(117 "from the platform"118 );119 })120 );121122 it.effect("keeps the path and the query on the platform's origin", () =>123 Effect.gen(function* () {124 const platform = recorder(() => new Response("ok"));125126 yield* Effect.promise(() =>127 backend(128 new Request(`${WEB_URL}/releases/x?y=1`),129 envWith(platform.fetch)130 )131 );132133 const seen = yield* platform.seen;134135 expect(seen.map(({ method, url }) => [method, url])).toStrictEqual([136 ["GET", `${PLATFORM_URL}/releases/x?y=1`],137 ]);138 })139 );140});141142describe("a server route's client", () => {143 it.effect(144 "posts each call to /rpc through the backend, in process, with the caller's cookie",145 () =>146 Effect.gen(function* () {147 const stub = recorder(148 () => new Response("not an rpc answer", { status: 500 })149 );150151 const given: Backend = (request) => stub.fetch(request);152153 const exit = yield* Effect.service(Client).pipe(154 Effect.flatMap((client) =>155 client.listAsks({156 project: Schema.decodeSync(ProjectName)("datekit"),157 })158 ),159 Effect.provide(160 serverClientOver(given)(161 unused,162 listAsksPost({ cookie: "session=abc" })163 )164 ),165 Effect.exit166 );167168 const seen = yield* stub.seen;169170 expect(Exit.isFailure(exit)).toBeTruthy();171 expect(172 seen.map(({ body, contentType, cookie, method, url }) => ({173 body: body.includes('"tag":"listAsks"'),174 contentType,175 cookie,176 method,177 // Effect's HTTP protocol posts to its URL with a trailing slash.178 path: new URL(url).pathname.replace(/\/$/u, ""),179 }))180 ).toStrictEqual([181 {182 body: true,183 contentType: "application/json",184 cookie: "session=abc",185 method: "POST",186 path: "/rpc",187 },188 ]);189 expect(new URL(seen[0]?.url ?? "").origin).toBe(WEB_URL);190 })191 );192});193194describe("the /rpc route", () => {195 it.effect("answers POST with the backend's handler, and nothing else", () =>196 Effect.gen(function* () {197 const { Route } = yield* Effect.promise(198 () => import("../src/routes/rpc.ts")199 );200201 expect(Object.keys(Route.options.server?.handlers ?? {})).toStrictEqual([202 "POST",203 ]);204 })205 );206});