The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Effect from "effect/Effect"; |
| 2 | import * as Exit from "effect/Exit"; |
| 3 | import * as HttpApi from "effect/http-api/HttpApi"; |
| 4 | import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; |
| 5 | import * as HttpApiEndpoint from "effect/http-api/HttpApiEndpoint"; |
| 6 | import * as HttpApiGroup from "effect/http-api/HttpApiGroup"; |
| 7 | import * as HttpApiSchema from "effect/http-api/HttpApiSchema"; |
| 8 | import type { HttpServerRequest } from "effect/http/HttpServerRequest"; |
| 9 | import * as Layer from "effect/Layer"; |
| 10 | import type * as Rpc from "effect/rpc/Rpc"; |
| 11 | import type * as RpcGroup from "effect/rpc/RpcGroup"; |
| 12 | import type * as RpcMiddleware from "effect/rpc/RpcMiddleware"; |
| 13 | import * as RpcSchema from "effect/rpc/RpcSchema"; |
| 14 | import * as Schema from "effect/Schema"; |
| 15 | import * as SchemaAST from "effect/SchemaAST"; |
| 16 | import * as Scope from "effect/Scope"; |
| 17 | import * as Sink from "effect/Sink"; |
| 18 | import * as Stream from "effect/Stream"; |
| 19 | import type { Servable } from "./Api.ts"; |
| 20 | import { DefinitionError, MissingGroup } from "./DefinitionError.ts"; |
| 21 | import { type Operation, operationsOf, outsideClient } from "./ReadRpcs.ts"; |
| 22 | |
| 23 | /** |
| 24 | * What {@link toHttpApi} reads from an Api class: what it serves, its RPCs, |
| 25 | * and its in-process client (`clientInProcess`), which runs every call |
| 26 | * through the Api's own handlers and middleware. |
| 27 | */ |
| 28 | export interface Publishable { |
| 29 | readonly apiName: string; |
| 30 | readonly serves: ReadonlyArray<Servable>; |
| 31 | readonly group: RpcGroup.RpcGroup<Rpc.Any>; |
| 32 | readonly clientInProcess: Effect.Effect<unknown, never, any>; |
| 33 | } |
| 34 | |
| 35 | /** |
| 36 | * What serving the HTTP API needs: the hosted model and the Layers of the |
| 37 | * middleware what the Api serves declares, as for the Api itself. Not the |
| 38 | * client half of any middleware: the HTTP caller sends its own headers. |
| 39 | */ |
| 40 | export type Requirements<A extends Publishable> = Exclude< |
| 41 | Effect.Services<A["clientInProcess"]>, |
| 42 | Scope.Scope | RpcMiddleware.ForClient<any> |
| 43 | >; |
| 44 | |
| 45 | /** The group, an HttpApi holding only it, and the Layers that serve it. */ |
| 46 | export interface HttpApiSurface<Name extends string, R> { |
| 47 | /** One endpoint per published call. Add it to your own `HttpApi` to serve it with other groups. */ |
| 48 | readonly group: HttpApiGroup.HttpApiGroup<Name, HttpApiEndpoint.Top>; |
| 49 | /** An `HttpApi` with only {@link group}, for `HttpApiBuilder.layer` and `OpenApi.fromApi`. */ |
| 50 | readonly api: HttpApi.HttpApi<Name, HttpApiGroup.HttpApiGroup<Name, HttpApiEndpoint.Top>>; |
| 51 | /** The handlers of {@link group} in {@link api}. */ |
| 52 | readonly layer: Layer.Layer<HttpApiGroup.Service<Name, Name>, never, R>; |
| 53 | /** |
| 54 | * The handlers of {@link group} in your own `HttpApi`, which may add a |
| 55 | * prefix, middleware or other groups. |
| 56 | */ |
| 57 | readonly layerFor: <ApiId extends string, Groups extends HttpApiGroup.Constraint>( |
| 58 | api: HttpApi.HttpApi<ApiId, Groups>, |
| 59 | ) => Layer.Layer<HttpApiGroup.Service<ApiId, Name>, never, R>; |
| 60 | } |
| 61 | |
| 62 | /** The status of a typed failure that does not declare one. */ |
| 63 | const DEFAULT_STATUS = 422; |
| 64 | |
| 65 | /** The query of a `get`, `peek` or `snapshot`: wait for a write, given as its receipt's `stream` and `version`. */ |
| 66 | const AtLeastQuery = Schema.Struct({ |
| 67 | stream: Schema.optional(Schema.String), |
| 68 | version: Schema.optional(Schema.Number), |
| 69 | }).check( |
| 70 | Schema.makeFilter((query) => |
| 71 | (query.stream === undefined) === (query.version === undefined) |
| 72 | ? undefined |
| 73 | : "stream and version go together", |
| 74 | ), |
| 75 | ); |
| 76 | |
| 77 | /** The members of a schema of failures, without `Never`. */ |
| 78 | const membersOf = (schema: Schema.Top): ReadonlyArray<Schema.Top> => { |
| 79 | const union = schema as Schema.Top & { readonly members?: ReadonlyArray<Schema.Top> }; |
| 80 | if (SchemaAST.isUnion(schema.ast) && union.members) return union.members.flatMap(membersOf); |
| 81 | return SchemaAST.isNever(schema.ast) ? [] : [schema]; |
| 82 | }; |
| 83 | |
| 84 | /** |
| 85 | * The status `HttpApiSchema.status` gave a schema. It is an annotation on the |
| 86 | * schema, or on its key context when the schema is a field. |
| 87 | */ |
| 88 | const resolveStatus = (ast: SchemaAST.AST): number | undefined => |
| 89 | SchemaAST.resolveAt<number>("httpApiStatus")(ast) ?? |
| 90 | (ast.context?.annotations?.httpApiStatus as number | undefined); |
| 91 | |
| 92 | /** |
| 93 | * Every typed failure of a call: its declared rejections (a streaming call |
| 94 | * declares them on its stream), then its middleware's errors. |
| 95 | */ |
| 96 | const failuresOf = (rpc: Rpc.AnyWithProps): ReadonlyArray<Schema.Top> => { |
| 97 | const seen = new Set<Schema.Top>(); |
| 98 | const streamed = RpcSchema.isStreamSchema(rpc.successSchema) ? [rpc.successSchema.error] : []; |
| 99 | for (const schema of [ |
| 100 | rpc.errorSchema, |
| 101 | ...streamed, |
| 102 | ...[...rpc.middlewares].map((m) => m.error), |
| 103 | ]) { |
| 104 | for (const member of membersOf(schema)) seen.add(member); |
| 105 | } |
| 106 | return [...seen]; |
| 107 | }; |
| 108 | |
| 109 | /** One published call, with what its handler needs. */ |
| 110 | interface Published { |
| 111 | readonly operation: Operation; |
| 112 | /** True for the typed failures the endpoint declares; anything else is a defect. */ |
| 113 | readonly isDeclared: (error: unknown) => boolean; |
| 114 | } |
| 115 | |
| 116 | /** The request a handler receives, loosely: the endpoint's decoded parts. */ |
| 117 | interface DecodedRequest { |
| 118 | readonly params?: { readonly key: string }; |
| 119 | readonly query?: Record<string, unknown>; |
| 120 | readonly payload?: Record<string, unknown>; |
| 121 | readonly request: HttpServerRequest; |
| 122 | } |
| 123 | |
| 124 | type Client = Record<string, unknown>; |
| 125 | |
| 126 | /** Call the Api's own client as the published call: the HTTP request's parts become its payload. */ |
| 127 | const call = (client: Client, operation: Operation, request: DecodedRequest) => { |
| 128 | // The request's headers go to the call, so its middleware reads cookies and tokens as usual. |
| 129 | const headers = request.request.headers; |
| 130 | if (operation.operation === "send") { |
| 131 | const send = client[operation.name] as ( |
| 132 | target: unknown, |
| 133 | input: unknown, |
| 134 | options: object, |
| 135 | ) => Effect.Effect<unknown, unknown>; |
| 136 | const { target, input, commandId } = request.payload as { |
| 137 | readonly target: unknown; |
| 138 | readonly input: unknown; |
| 139 | readonly commandId?: string; |
| 140 | }; |
| 141 | return send(target, input, { headers, ...(commandId === undefined ? {} : { commandId }) }); |
| 142 | } |
| 143 | const reads = client[operation.name] as Record< |
| 144 | string, |
| 145 | ( |
| 146 | key: string, |
| 147 | options: object, |
| 148 | ) => Effect.Effect<unknown, unknown> | Stream.Stream<unknown, unknown> |
| 149 | >; |
| 150 | const { stream, version, ...rest } = request.query ?? {}; |
| 151 | const atLeast = |
| 152 | stream === undefined |
| 153 | ? {} |
| 154 | : { atLeast: { stream: stream as string, version: version as number } }; |
| 155 | return reads[operation.operation]!(request.params!.key, { headers, ...atLeast, ...rest }); |
| 156 | }; |
| 157 | |
| 158 | /** |
| 159 | * A live read as an SSE body. The first value is read before the response |
| 160 | * starts, so a failure of the read's middleware or `validate` answers with |
| 161 | * its HTTP status, like any other call. A failure after that ends the stream |
| 162 | * with a typed failure event. The in-process client lives until the stream |
| 163 | * ends. |
| 164 | */ |
| 165 | const live = Effect.fn(function* ( |
| 166 | client: Effect.Effect<Client, never, Scope.Scope>, |
| 167 | operation: Operation, |
| 168 | request: DecodedRequest, |
| 169 | ) { |
| 170 | const scope = yield* Scope.make(); |
| 171 | const peeled = yield* Effect.gen(function* () { |
| 172 | const reads = call(yield* client, operation, request) as Stream.Stream<unknown, unknown>; |
| 173 | return yield* Stream.peel(reads, Sink.take(1)); |
| 174 | }).pipe( |
| 175 | Scope.provide(scope), |
| 176 | Effect.onError((cause) => Scope.close(scope, Exit.failCause(cause))), |
| 177 | ); |
| 178 | const [first, rest] = peeled; |
| 179 | return Stream.fromIterable(first).pipe( |
| 180 | Stream.concat(rest), |
| 181 | Stream.onExit((exit) => Scope.close(scope, exit)), |
| 182 | ); |
| 183 | }); |
| 184 | |
| 185 | /** A call that answers once, through a client that lives for the request. */ |
| 186 | const once = Effect.fn(function* ( |
| 187 | client: Effect.Effect<Client, never, Scope.Scope>, |
| 188 | operation: Operation, |
| 189 | request: DecodedRequest, |
| 190 | ) { |
| 191 | return yield* call(yield* client, operation, request) as Effect.Effect<unknown, unknown>; |
| 192 | }); |
| 193 | |
| 194 | /** |
| 195 | * The SSE body of a live read: each value the RPC streams is one event's |
| 196 | * `data`, and a failure after the first value is the typed failure event. |
| 197 | */ |
| 198 | const sseOf = (rpc: Rpc.AnyWithProps, errors: ReadonlyArray<Schema.Top>) => { |
| 199 | const streamed = rpc.successSchema as RpcSchema.Stream<Schema.Top, Schema.Top>; |
| 200 | return HttpApiSchema.StreamSse({ |
| 201 | data: streamed.success, |
| 202 | error: errors.length === 0 ? Schema.Never : Schema.Union(errors), |
| 203 | }); |
| 204 | }; |
| 205 | |
| 206 | /** The endpoint of one call. The schemas are the RPC's own, so the HTTP wire is the RPC wire. */ |
| 207 | const endpointOf = ( |
| 208 | operation: Operation, |
| 209 | rpc: Rpc.AnyWithProps, |
| 210 | errors: ReadonlyArray<Schema.Top>, |
| 211 | ): HttpApiEndpoint.Top => { |
| 212 | const fields = (rpc.payloadSchema as unknown as Schema.Struct<Schema.Struct.Fields>).fields; |
| 213 | const error = errors.length === 0 ? undefined : errors; |
| 214 | const endpoint = |
| 215 | operation.operation === "send" |
| 216 | ? HttpApiEndpoint.post(operation.rpc._tag, `/${operation.name}`, { |
| 217 | payload: rpc.payloadSchema, |
| 218 | success: rpc.successSchema, |
| 219 | error, |
| 220 | }) |
| 221 | : operation.stream |
| 222 | ? HttpApiEndpoint.get( |
| 223 | operation.rpc._tag, |
| 224 | `/${operation.name}/:key/${operation.operation}`, |
| 225 | { |
| 226 | params: { key: fields.key! }, |
| 227 | // `events` resumes after a cursor; `watch` takes nothing but the key. |
| 228 | ...(fields.after ? { query: { after: fields.after } } : {}), |
| 229 | success: sseOf(rpc, errors), |
| 230 | error, |
| 231 | }, |
| 232 | ) |
| 233 | : operation.operation === "list" |
| 234 | ? HttpApiEndpoint.get(operation.rpc._tag, `/${operation.name}/:key/list`, { |
| 235 | params: { key: fields.key! }, |
| 236 | query: { |
| 237 | order: fields.order!, |
| 238 | take: fields.take!, |
| 239 | after: fields.after!, |
| 240 | }, |
| 241 | success: rpc.successSchema, |
| 242 | error, |
| 243 | }) |
| 244 | : HttpApiEndpoint.get( |
| 245 | operation.rpc._tag, |
| 246 | operation.operation === "snapshot" |
| 247 | ? `/${operation.name}/:key/snapshot` |
| 248 | : `/${operation.name}/:key`, |
| 249 | { |
| 250 | params: { key: fields.key! }, |
| 251 | // A view's reads and a stream's `peek` can wait for a write; an aggregate reads its state. |
| 252 | ...(fields.atLeast ? { query: AtLeastQuery } : {}), |
| 253 | success: rpc.successSchema, |
| 254 | error, |
| 255 | }, |
| 256 | ); |
| 257 | return endpoint as unknown as HttpApiEndpoint.Top; |
| 258 | }; |
| 259 | |
| 260 | /** |
| 261 | * Publish an Api's calls as a plain HTTP JSON API, with an OpenAPI document, |
| 262 | * from the same Api. Each published call is one endpoint: |
| 263 | * |
| 264 | * | Call | Method and path | Input | |
| 265 | * | ----------------------- | ---------------------------- | --------------------------------------- | |
| 266 | * | a command | `POST /<Command>` | JSON body: `target`, `commandId`, input | |
| 267 | * | `get`, `peek` | `GET /<Name>/{key}` | `?stream=&version=` waits for a write | |
| 268 | * | `snapshot` | `GET /<Name>/{key}/snapshot`| `?stream=&version=` waits for a write | |
| 269 | * | `list` | `GET /<Name>/{key}/list` | `?order=&take=&after=` | |
| 270 | * | `watch` | `GET /<Name>/{key}/watch` | Server-Sent Events | |
| 271 | * | `events` | `GET /<Name>/{key}/events` | Server-Sent Events, `?after=` a cursor | |
| 272 | * |
| 273 | * A command answers with its receipt; a read with what the Api's own client |
| 274 | * gets (`null` for an empty key). A typed failure answers with its `_tag` |
| 275 | * and data, at the status its schema's `httpApiStatus` annotation gives it |
| 276 | * (`Domain.Rejection("NotOwner", {}, { httpApiStatus: 403 })`), and 422 if it |
| 277 | * has none: a rejection is a refused request, not a server fault. Input its |
| 278 | * schema refuses is a 400. |
| 279 | * |
| 280 | * A live read (`watch`, `events`) answers with a Server-Sent Events stream: |
| 281 | * each value is one event's JSON `data`. A failure before the first value, |
| 282 | * such as its middleware refusing the caller, answers with its status like |
| 283 | * any other call. A failure after it, such as `validate` refusing a change, |
| 284 | * ends the stream with an `effect/http-api/stream/failure` event whose |
| 285 | * `data` is the typed failure. |
| 286 | * |
| 287 | * Every call goes through the Api's own handlers in process, with the HTTP |
| 288 | * request's headers, so its middleware, its checks and its rejections run as |
| 289 | * for any client, and its input is decoded once. A read's `where` filter is |
| 290 | * not published. |
| 291 | * |
| 292 | * Every call the Api serves is published. To publish less, give HTTP |
| 293 | * clients their own, smaller Api. |
| 294 | * |
| 295 | * **Example:** Serve an Api, with its OpenAPI document |
| 296 | * ```typescript |
| 297 | * import * as DomainHttp from "@alchemy.run/domain/Http"; |
| 298 | * import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder"; |
| 299 | * import * as OpenApi from "effect/http-api/OpenApi"; |
| 300 | * |
| 301 | * const BankHttp = DomainHttp.toHttpApi(CustomerApi); |
| 302 | * const BankHttpLive = HttpApiBuilder.layer(BankHttp.api, { openapiPath: "/openapi.json" }).pipe( |
| 303 | * Layer.provide(BankHttp.layer), |
| 304 | * Layer.provide(BankLive), |
| 305 | * ); |
| 306 | * const spec = OpenApi.fromApi(BankHttp.api); |
| 307 | * ``` |
| 308 | * |
| 309 | * **Example:** Watch a view from a browser |
| 310 | * ```typescript |
| 311 | * // in the browser: one event per change, each `{ state, cursor }` |
| 312 | * const source = new EventSource(`/AccountSummary/${accountId}/watch`); |
| 313 | * source.onmessage = (event) => render(JSON.parse(event.data).state); |
| 314 | * ``` |
| 315 | */ |
| 316 | export const toHttpApi = <A extends Publishable>( |
| 317 | api: A, |
| 318 | ): HttpApiSurface<A["apiName"], Requirements<A>> => { |
| 319 | const name = api.apiName; |
| 320 | const calls = operationsOf(api.serves); |
| 321 | // A failure without a status of its own is a refused request, not a server fault. |
| 322 | const withStatus = (failure: Schema.Top): Schema.Top => |
| 323 | resolveStatus(failure.ast) === undefined |
| 324 | ? HttpApiSchema.status(DEFAULT_STATUS)(failure) |
| 325 | : failure; |
| 326 | |
| 327 | const published: Array<Published> = []; |
| 328 | let group = HttpApiGroup.make(name) as unknown as HttpApiGroup.HttpApiGroup< |
| 329 | string, |
| 330 | HttpApiEndpoint.Top |
| 331 | >; |
| 332 | for (const operation of calls) { |
| 333 | const { rpc } = operation; |
| 334 | const errors = failuresOf(rpc).map(withStatus); |
| 335 | const endpoint = endpointOf(operation, rpc, errors); |
| 336 | const declared = errors.length === 0 ? undefined : Schema.is(Schema.Union(errors)); |
| 337 | published.push({ operation, isDeclared: (error) => declared?.(error) ?? false }); |
| 338 | group = group.add(endpoint) as typeof group; |
| 339 | } |
| 340 | |
| 341 | const layerFor = (httpApi: HttpApi.HttpApi<string, HttpApiGroup.Constraint>) => { |
| 342 | if (!(name in httpApi.groups)) { |
| 343 | return new DefinitionError({ |
| 344 | reason: new MissingGroup({ httpApi: httpApi.identifier, group: name }), |
| 345 | }).pipe(Effect.die, Layer.effectDiscard); |
| 346 | } |
| 347 | return HttpApiBuilder.group(httpApi as never, name as never, (handlers: any) => { |
| 348 | // The Api's in-process client: its handlers and middleware, nothing |
| 349 | // serialized. One per request, as `yield* Api` builds one server per request. |
| 350 | // Without the client half of any middleware (see `outsideClient`). |
| 351 | const client = outsideClient(api) as Effect.Effect<Client, never, Scope.Scope>; |
| 352 | for (const { operation, isDeclared } of published) { |
| 353 | // Only the endpoint's declared failures are public; anything else is a defect. |
| 354 | const declaredOnly = <A, R>(effect: Effect.Effect<A, unknown, R>) => |
| 355 | Effect.catchIf(effect, (error) => !isDeclared(error), Effect.die); |
| 356 | handlers = handlers.handle(operation.rpc._tag, (request: DecodedRequest) => |
| 357 | operation.stream |
| 358 | ? live(client, operation, request).pipe( |
| 359 | declaredOnly, |
| 360 | Effect.map(Stream.catchIf((error) => !isDeclared(error), Stream.die)), |
| 361 | ) |
| 362 | : once(client, operation, request).pipe(declaredOnly, Effect.scoped), |
| 363 | ); |
| 364 | } |
| 365 | return handlers; |
| 366 | }); |
| 367 | }; |
| 368 | |
| 369 | const httpApi = HttpApi.make(name).add(group as never); |
| 370 | return { |
| 371 | group, |
| 372 | api: httpApi, |
| 373 | layer: layerFor(httpApi as never), |
| 374 | layerFor, |
| 375 | } as unknown as HttpApiSurface<A["apiName"], Requirements<A>>; |
| 376 | }; |