watch.ts
This file
Path
apps/platform/src/watch.ts
342 lines · 9.8 KiB · TypeScript
Last changed by
Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
History of this fileTake it
The walk stopped after 200 commits: lines older than 678c8b8 point at it.
Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
lines 1–2why, one step back1// A socket's position lives in its attachment, which survives hibernation; its tag2// holds the number it opened from, for when the attachment is lost.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 3–7why, one step back3import type { ProjectApi } from "@repo/project/project";4import { keptEvents } from "@repo/project/project-store";5import { Projects } from "@repo/project/projects";6import { NoneOrMore } from "@repo/protocol/domain/common";7import { ProjectEvent } from "@repo/protocol/domain/event";Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 8why, one step back8import { keyOf } from "@repo/protocol/ids";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 9–65why, one step back9import type { ProjectName } from "@repo/protocol/ids";10import type { UnknownProject } from "@repo/protocol/refusal";11import {12 Cause,13 Context,14 Data,15 Duration,16 Effect,17 Option,18 Predicate,19 Queue,20 Ref,21 Schedule,22 Schema,23 Stream,24} from "effect";25import { Headers, HttpServerRequest } from "effect/http";26import { RpcSerialization } from "effect/rpc";2728import { decodeReply, encodeCall } from "./project-calls.ts";29import type { CallRequest, ExitEncoded } from "./project-calls.ts";30import type { ProjectShell } from "./project-shell.ts";3132const EVENT_PAGE = 100;3334const POLL = Duration.seconds(1);3536const RECONNECT = Duration.seconds(1);3738export const WATCH_TAG = "watch";3940export const WATCH_PATH = "/watch";4142const SINCE = "since:";4344export const WatchFrame = Schema.Struct({45 event: ProjectEvent,46 seq: Schema.Int,47});4849export type WatchFrame = typeof WatchFrame.Type;5051const FrameText = Schema.fromJsonString(WatchFrame);5253const encodeFrame = Schema.encodeEffect(FrameText);5455const decodeFrame = Schema.decodeEffect(FrameText);5657const SinceText = Schema.FiniteFromString.pipe(Schema.decodeTo(NoneOrMore));5859const decodeSince = Schema.decodeUnknownOption(SinceText);6061export const isFramed = (headers: Headers.Headers) =>62 Option.exists(Headers.get(headers, "content-type"), (type) =>63 type.startsWith(RpcSerialization.ndjson.contentType)64 );65Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
lines 66–67why, one step back66// Never the call's own headers: the RPC server lays them over the request's, so a67// call posted as JSON could claim to be framed.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 68–157why, one step back68export const servedFramed = Effect.map(69 Effect.serviceOption(HttpServerRequest.HttpServerRequest),70 Option.exists((request) => isFramed(request.headers))71);7273export type SocketState = Pick<74 DurableObjectState,75 "acceptWebSocket" | "getTags" | "getWebSockets"76>;7778const Position = Schema.Struct({ seq: NoneOrMore });7980const decodePosition = Schema.decodeUnknownOption(Position);8182const openedFrom = (state: SocketState, socket: WebSocket) =>83 Option.flatMap(84 Option.fromUndefinedOr(85 state.getTags(socket).find((tag) => tag.startsWith(SINCE))86 ),87 (tag) => decodeSince(tag.slice(SINCE.length))88 );8990export const watchRequest = (request: Request): Option.Option<number> => {91 const url = new URL(request.url);9293 return url.pathname === WATCH_PATH &&94 request.headers.get("upgrade")?.toLowerCase() === "websocket"95 ? decodeSince(url.searchParams.get("since") ?? "0")96 : Option.none();97};9899const send = (socket: WebSocket, frames: readonly WatchFrame[]) =>100 Effect.forEach(101 frames,102 (frame) =>103 Effect.gen(function* () {104 const text = yield* Effect.orDie(encodeFrame(frame));105106 yield* Effect.try(() => {107 socket.send(text);108 socket.serializeAttachment({ seq: frame.seq });109 });110 }),111 { discard: true }112 ).pipe(Effect.ignore);113114export const watchRoom = (state: SocketState, shell: ProjectShell) => {115 const eventsAfter = (seq: number) =>116 encodeCall("events", [seq, keptEvents]).pipe(117 Effect.flatMap((request) => shell.call(request)),118 Effect.flatMap((reply) => decodeReply("events", reply))119 );120121 const positionOf = (socket: WebSocket) =>122 Option.orElse(123 Option.map(124 decodePosition(socket.deserializeAttachment()),125 ({ seq }) => seq126 ),127 () => openedFrom(state, socket)128 );129130 const catchUp = (sockets: readonly WebSocket[]) =>131 Effect.gen(function* () {132 const standing = sockets.flatMap((socket) =>133 Option.match(positionOf(socket), {134 onNone: () => [],135 onSome: (seq) => [{ seq, socket }],136 })137 );138139 if (standing.length === 0) {140 return;141 }142143 const rows = yield* eventsAfter(144 Math.min(...standing.map(({ seq }) => seq))145 );146147 yield* Effect.forEach(148 standing,149 ({ seq, socket }) =>150 send(151 socket,152 rows.filter((row) => row.seq > seq)153 ),154 { discard: true }155 );156 });157Merge build/comments-platform into mainoscabrielbefore adoptionddf09e8
lines 158–159why, one step back158 // The commit stands whatever happens here: a failed settle is logged, and the next159 // settle sends what this one could not.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 160–220why, one step back160 const settle = Effect.suspend(() =>161 catchUp(state.getWebSockets(WATCH_TAG))162 ).pipe(163 Effect.catchCause((cause) =>164 Effect.logWarning("the project's watchers were not caught up", cause)165 )166 );167168 return {169 admit: (socket: WebSocket, since: number) =>170 Effect.suspend(() => {171 state.acceptWebSocket(socket, [WATCH_TAG, `${SINCE}${since}`]);172 socket.serializeAttachment({ seq: since });173174 return catchUp([socket]);175 }),176 alarm: () => Effect.andThen(shell.alarm(), settle),177 call: (request: typeof CallRequest.Encoded): Effect.Effect<ExitEncoded> =>178 Effect.tap(shell.call(request), () => settle),179 heard: (socket: WebSocket) => catchUp([socket]),180 };181};182183const reportOnly: ReadonlySet<number> = new Set([1005, 1006, 1015]);184185export const closeEnd = (socket: WebSocket, code: number, reason: string) =>186 Effect.try(() => {187 socket.close(reportOnly.has(code) ? 1000 : code, reason);188 }).pipe(Effect.ignore);189190interface Upgraded {191 readonly webSocket: WebSocket | null;192}193194export interface WatchNamespace {195 readonly idFromName: (name: string) => DurableObjectId;196 readonly get: (id: DurableObjectId) => {197 readonly fetch: (request: Request) => Promise<Upgraded>;198 };199}200201export const ProjectSockets = Context.Reference<Option.Option<WatchNamespace>>(202 "platform/ProjectSockets",203 { defaultValue: Option.none }204);205206class SocketRefused extends Data.TaggedError("SocketRefused")<{207 readonly cause: unknown;208}> {}209210class SocketLost extends Data.TaggedError("SocketLost")<{211 readonly reason: string;212}> {}213214const socketFrames = (215 namespace: WatchNamespace,216 project: ProjectName,217 since: number218) =>219 Stream.callback<string, SocketRefused | SocketLost>((queue) =>220 Effect.gen(function* () {Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 221why, one step back221 const stub = namespace.get(namespace.idFromName(keyOf(project)));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 222–342why, one step back222223 const answer = yield* Effect.tryPromise({224 catch: (cause) => new SocketRefused({ cause }),225 try: () =>226 stub.fetch(227 new Request(`https://project${WATCH_PATH}?since=${since}`, {228 headers: { upgrade: "websocket" },229 })230 ),231 });232233 const webSocket = yield* Effect.fromNullishOr(answer.webSocket).pipe(234 Effect.mapError(235 () => new SocketRefused({ cause: "no socket in the answer" })236 )237 );238239 webSocket.accept();240 webSocket.addEventListener("message", ({ data }) => {241 // The DO sends text frames only.242 if (Predicate.isString(data)) {243 Queue.offerUnsafe(queue, data);244 }245 });246 webSocket.addEventListener("close", () => {247 Queue.endUnsafe(queue);248 });249 webSocket.addEventListener("error", ({ message }) => {250 Queue.failCauseUnsafe(251 queue,252 Cause.fail(new SocketLost({ reason: message }))253 );254 });255256 yield* Effect.addFinalizer(() =>257 Effect.ignore(258 Effect.try(() => {259 webSocket.close(1000, "watcher gone");260 })261 )262 );263 }).pipe(264 Effect.catchTag("SocketRefused", (refused) => Queue.fail(queue, refused))265 )266 ).pipe(Stream.mapEffect((text) => Effect.orDie(decodeFrame(text))));267268const polled = (api: ProjectApi, since: number) =>269 Stream.paginate({ after: since, caughtUp: false }, ({ after, caughtUp }) =>270 Effect.gen(function* () {271 if (caughtUp) {272 yield* Effect.sleep(POLL);273 }274275 const rows = yield* api.events(after, EVENT_PAGE);276277 return [278 rows,279 Option.some({280 after: rows.at(-1)?.seq ?? after,281 caughtUp: rows.length < EVENT_PAGE,282 }),283 ] as const;284 })285 );286287const replayed = (api: ProjectApi, since: number) =>288 Stream.paginate(since, (after) =>289 Effect.map(api.events(after, EVENT_PAGE), (rows) => [290 rows,291 rows.length < EVENT_PAGE292 ? Option.none()293 : Option.fromUndefinedOr(rows.at(-1)?.seq),294 ])295 );296297const relayed = (298 namespace: WatchNamespace,299 api: ProjectApi,300 project: ProjectName,301 since: number302) =>303 Stream.unwrap(304 Effect.map(Ref.make(since), (last) => {305 const fresh = (frame: WatchFrame) =>306 Ref.modify(last, (seen) =>307 frame.seq > seen ? [true, frame.seq] : [false, seen]308 );309310 const fromLast = <A, E>(open: (from: number) => Stream.Stream<A, E>) =>311 Stream.unwrap(Effect.map(Ref.get(last), open));312313 return fromLast((from) => socketFrames(namespace, project, from)).pipe(314 Stream.filterEffect(fresh),315 Stream.catchTag("SocketLost", () => Stream.empty),316 Stream.repeat(Schedule.spaced(RECONNECT)),317 Stream.catchTag("SocketRefused", () =>318 fromLast((from) => polled(api, from))319 )320 );321 })322 );323324export const watchHandler = (325 payload: { readonly project: ProjectName; readonly since?: number },326 transport: { readonly live: boolean }327): Stream.Stream<ProjectEvent, UnknownProject, Projects> =>328 Stream.unwrap(329 Effect.gen(function* () {330 const api = yield* (yield* Projects).get(payload.project);331 const since = Math.max(0, payload.since ?? 0);332333 if (!transport.live) {334 return replayed(api, since);335 }336337 return Option.match(yield* ProjectSockets, {338 onNone: () => polled(api, since),339 onSome: (namespace) => relayed(namespace, api, payload.project, since),340 });341 })342 ).pipe(Stream.map(({ event }) => event));