Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

runtime.ts

1,195 lines43.6 KB

1import { msg } from "gt-i18n";
2import { translatableMessage } from "../errors/translatable.ts";
3import type { QueryPersistence } from "./queryPersistence.ts";
4import { createCommandPermissions } from "./commandPermissions.ts";
5import { followStreamInEnvironment } from "./environmentStreams.ts";
6import { reuseUnchanged } from "./serverConfigProjection.ts";
7export { runStreamInEnvironment, followStreamInEnvironment } from "./environmentStreams.ts";
8import {
9 type ClientGuardedRpcTag,
10 EnvironmentId,
11 type EnvironmentId as EnvironmentIdType,
12} from "@t3tools/contracts";
13import * as Cause from "effect/Cause";
14import * as Deferred from "effect/Deferred";
15import * as Effect from "effect/Effect";
16import type * as Exit from "effect/Exit";
17import * as Fiber from "effect/Fiber";
18import * as Option from "effect/Option";
19import * as Schema from "effect/Schema";
20import * as Semaphore from "effect/Semaphore";
21import * as Stream from "effect/Stream";
22import * as SubscriptionRef from "effect/SubscriptionRef";
23import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
24​
25import type { ConnectionAttemptError, SupervisorConnectionState } from "../connection/model.ts";
26import * as EnvironmentRegistry from "../connection/registry.ts";
27import {
28 type EnvironmentRpcInput,
29 type EnvironmentRpcSuccess,
30 type EnvironmentRpcFailure,
31 type EnvironmentRpcStreamFailure,
32 type EnvironmentRpcStreamValue,
33 type EnvironmentSubscriptionRpcTag,
34 type EnvironmentUnaryRpcTag,
35 EnvironmentRpcUnavailableError,
36 isLostTransportCause,
37 request,
38 requestGuarded,
39 RpcPermissionGuard,
40 subscribe,
41} from "../rpc/client.ts";
42import * as EnvironmentSupervisor from "../connection/supervisor.ts";
43import type * as RpcSession from "../rpc/session.ts";
44​
45const isEnvironmentRpcUnavailable = Schema.is(EnvironmentRpcUnavailableError);
46​
47/**
48 * Holds back the unavailable failure of a query whose session went away. The
49 * query atom reruns when it sees that session change, so settling first would
50 * show a failure for a query that is about to retry. While `session` is still
51 * current no rerun is coming, and the failure stands.
52 */
53const pendingOnceSessionReplaced =
54 (session: RpcSession.RpcSession) =>
55 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
56 effect.pipe(
57 // The query's error type is generic, so its tags are unknown to `catchTags`.
58 Effect.catchIf(isEnvironmentRpcUnavailable, (error) =>
59 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
60 Effect.flatMap((supervisor) => SubscriptionRef.get(supervisor.session)),
61 Effect.flatMap((current) =>
62 Option.isSome(current) && current.value === session ? Effect.fail(error) : Effect.never,
63 ),
64 ),
65 ),
66 );
67​
68interface EnvironmentAtomOptions<Input, A, E, R> {
69 readonly label: string;
70 readonly execute: (input: Input) => Effect.Effect<A, E, R>;
71 readonly scheduler?: AtomCommandScheduler;
72 readonly concurrency?: AtomCommandConcurrency<{
73 readonly environmentId: EnvironmentIdType;
74 readonly input: Input;
75 }>;
77​
78interface EnvironmentCommandAtomOptions<Input, A, E, R> extends Omit<
79 EnvironmentAtomOptions<Input, A, E, R>,
80 "execute"
81> {
82 readonly execute: (
83 input: Input,
84 registry: AtomRegistry.AtomRegistry,
85 environmentId: EnvironmentIdType,
86 ) => Effect.Effect<A, E, R>;
88​
89interface EnvironmentQueryAtomOptions<Input, A, E, R> extends Omit<
90 EnvironmentAtomOptions<Input, A, E, R>,
91 "execute"
92> {
93 /**
94 * `emit` shows a provisional value while the query keeps waiting. The settled
95 * result replaces it, so catch failures that should keep it on screen.
96 */
97 readonly execute: (
98 input: Input,
99 emit: (value: A) => Effect.Effect<void>,
100 previous: Option.Option<A>,
101 ) => Effect.Effect<A, E, R>;
102 readonly persistence?: QueryPersistence<A>;
103 readonly staleTimeMs?: number;
104 readonly idleTtlMs?: number;
105 readonly refreshIntervalMs?: number;
106 /** Each change of the returned signal refreshes the query; `query` is the data it refreshes. */
107 readonly refreshTrigger?: (
108 target: {
109 readonly environmentId: EnvironmentIdType;
110 readonly input: Input;
111 },
112 query: Atom.Atom<AsyncResult.AsyncResult<A, unknown>>,
113 ) => Atom.Atom<unknown> | undefined;
114 readonly isFinal?: (value: A) => boolean;
115 /**
116 * Runs where each server answer lands, before readers see it, so derived records (summaries,
117 * snapshots, watches) come from the producer instead of from components watching the data.
118 * Cached and emitted provisional values are not answers.
119 */
120 readonly onAnswer?: QueryAnswerHandler<Input, A>;
122​
123export type QueryAnswerHandler<Input, A> = (
124 target: { readonly environmentId: EnvironmentIdType; readonly input: Input },
125 value: A,
126 registry: AtomRegistry.AtomRegistry,
127) => Effect.Effect<void>;
128​
129interface EnvironmentSubscriptionAtomOptions<Input, A, E, R> {
130 readonly sensitiveInput?: boolean;
131 readonly label: string;
132 readonly subscribe: (input: Input) => Stream.Stream<A, E, R>;
133 readonly completeWhen?: (value: A) => boolean;
134 readonly idleTtlMs?: number;
135 /** Keeps a completed value this long after its last reader leaves, so reopening skips a resubscribe. */
136 readonly completedTtlMs?: number;
138​
139export type SettledAsyncResult<A, E> = AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>;
140​
141export type AtomCommandResult<A, E> = SettledAsyncResult<A, E>;
142​
143export type AtomCommandSuccess<R> = R extends AtomCommandResult<infer A, infer _E> ? A : never;
144​
145export type AtomCommandFailure<R> = R extends AtomCommandResult<infer _A, infer E> ? E : never;
146​
147export interface AtomCommandOptions {
148 readonly label?: string;
149 readonly reportFailure?: boolean;
150 readonly reportDefect?: boolean;
151 /** Aborting interrupts the run. */
152 readonly signal?: AbortSignal | undefined;
154​
155export interface AtomCommandReporter {
156 readonly warn: (message: string, cause: Cause.Cause<unknown>) => void;
157 readonly error: (message: string, cause: Cause.Cause<unknown>) => void;
159​
160export interface AtomCommand<W, A, E> {
161 readonly label: string;
162 /**
163 * Runs on the calling fiber, so interrupting the caller stops the command. Code outside
164 * Effect starts it with `runAtomCommand`.
165 */
166 readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Effect.Effect<A, E>;
168​
169export type AtomCommandConcurrency<W> =
170 | { readonly mode: "parallel" }
171 | {
172 readonly mode: "serial" | "singleFlight" | "latest";
173 readonly key: (input: W) => string;
174 };
175​
176/** One run that several callers wait on. It is interrupted once the last of them stops waiting. */
177interface SharedRun {
178 readonly result: Deferred.Deferred<unknown, unknown>;
179 waiters: number;
180 fiber: Fiber.Fiber<unknown, unknown> | undefined;
182​
183interface AtomCommandLatestLane {
184 pending: (SharedRun & { start: Effect.Effect<void> }) | undefined;
186​
187interface AtomCommandSchedulerState {
188 readonly serial: Map<string, { readonly semaphore: Semaphore.Semaphore; users: number }>;
189 readonly singleFlight: Map<string, SharedRun>;
190 readonly latest: Map<string, AtomCommandLatestLane>;
192​
193export interface AtomCommandScheduler {
194 readonly schedule: <W, A, E, R>(
195 registry: AtomRegistry.AtomRegistry,
196 concurrency: AtomCommandConcurrency<W>,
197 input: W,
198 effect: Effect.Effect<A, E, R>,
199 ) => Effect.Effect<A, E, R>;
201​
202const startSharedRun = <A, E>(run: SharedRun, effect: Effect.Effect<A, E>) =>
203 effect.pipe(
204 Effect.interruptible,
205 Effect.onExit((exit) => Deferred.done(run.result, exit)),
206 Effect.ignoreCause,
207 Effect.forkDetach({ startImmediately: true }),
208 Effect.map((fiber) => {
209 run.fiber = fiber;
210 }),
211 );
212​
213const awaitSharedRun = <A, E>(
214 run: SharedRun,
215 restore: <X, XE, XR>(effect: Effect.Effect<X, XE, XR>) => Effect.Effect<X, XE, XR>,
216 abandon: Effect.Effect<void>,
217): Effect.Effect<A, E> => {
218 run.waiters++;
219 return restore(Deferred.await(run.result as Deferred.Deferred<A, E>)).pipe(
220 Effect.onInterrupt(() => (--run.waiters === 0 ? abandon : Effect.void)),
221 );
222};
223​
224const interruptSharedRun = (run: SharedRun) =>
225 run.fiber === undefined ? Effect.void : Fiber.interrupt(run.fiber);
226​
227export function createAtomCommandScheduler(): AtomCommandScheduler {
228 const registryStates = new WeakMap<AtomRegistry.AtomRegistry, AtomCommandSchedulerState>();
229 const stateFor = (registry: AtomRegistry.AtomRegistry) => {
230 let state = registryStates.get(registry);
231 if (state === undefined) {
232 state = { serial: new Map(), singleFlight: new Map(), latest: new Map() };
233 registryStates.set(registry, state);
234 }
235 return state;
236 };
237​
238 const serial = <A, E, R>(
239 lanes: AtomCommandSchedulerState["serial"],
240 key: string,
241 effect: Effect.Effect<A, E, R>,
242 ) =>
243 Effect.acquireUseRelease(
244 Effect.sync(() => {
245 const lane = lanes.get(key) ?? { semaphore: Semaphore.makeUnsafe(1), users: 0 };
246 lanes.set(key, lane);
247 lane.users++;
248 return lane;
249 }),
250 (lane) => lane.semaphore.withPermit(effect),
251 (lane) =>
252 Effect.sync(() => {
253 if (--lane.users === 0) lanes.delete(key);
254 }),
255 );
256​
257 const singleFlight = <A, E, R>(
258 flights: AtomCommandSchedulerState["singleFlight"],
259 key: string,
260 effect: Effect.Effect<A, E, R>,
261 ) =>
262 Effect.uninterruptibleMask((restore) =>
263 Effect.gen(function* () {
264 let flight = flights.get(key);
265 if (flight === undefined) {
266 const started: SharedRun = {
267 result: Deferred.makeUnsafe(),
268 waiters: 0,
269 fiber: undefined,
270 };
271 flight = started;
272 flights.set(key, started);
273 const context = yield* Effect.context<R>();
274 yield* startSharedRun(
275 started,
276 effect.pipe(
277 Effect.provide(context),
278 Effect.ensuring(
279 Effect.sync(() => {
280 if (flights.get(key) === started) flights.delete(key);
281 }),
282 ),
283 ),
284 );
285 }
286 const joined = flight;
287 return yield* awaitSharedRun<A, E>(
288 joined,
289 restore,
290 Effect.suspend(() => {
291 // Left the map first, so a caller arriving during the interrupt starts a fresh run.
292 if (flights.get(key) === joined) flights.delete(key);
293 return interruptSharedRun(joined);
294 }),
295 );
296 }),
297 );
298​
299 const latest = <A, E, R>(
300 lanes: AtomCommandSchedulerState["latest"],
301 key: string,
302 effect: Effect.Effect<A, E, R>,
303 ) =>
304 Effect.uninterruptibleMask((restore) =>
305 Effect.gen(function* () {
306 const context = yield* Effect.context<R>();
307 const existing = lanes.get(key);
308 const lane = existing ?? { pending: undefined };
309 lanes.set(key, lane);
310 // Callers that queue behind a run share the next one, which runs the newest of them.
311 const batch = lane.pending ?? {
312 result: Deferred.makeUnsafe(),
313 waiters: 0,
314 fiber: undefined,
315 start: Effect.void,
316 };
317 batch.start = startSharedRun(batch, Effect.provide(effect, context));
318 lane.pending = batch;
319​
320 if (existing === undefined) {
321 const drain: Effect.Effect<void> = Effect.suspend(() => {
322 const next = lane.pending;
323 if (next === undefined) {
324 lanes.delete(key);
325 return Effect.void;
326 }
327 lane.pending = undefined;
328 return next.start.pipe(
329 Effect.andThen(Deferred.await(next.result)),
330 Effect.exit,
331 Effect.andThen(drain),
332 );
333 });
334 yield* drain.pipe(Effect.forkDetach({ startImmediately: true }));
335 }
336 return yield* awaitSharedRun<A, E>(
337 batch,
338 restore,
339 Effect.suspend(() => {
340 if (lane.pending === batch) lane.pending = undefined;
341 return interruptSharedRun(batch);
342 }),
343 );
344 }),
345 );
346​
347 return {
348 schedule: (registry, concurrency, input, effect) =>
349 concurrency.mode === "parallel"
350 ? effect
351 : Effect.suspend(() => {
352 const key = concurrency.key(input);
353 const state = stateFor(registry);
354 switch (concurrency.mode) {
355 case "serial":
356 return serial(state.serial, key, effect);
357 case "singleFlight":
358 return singleFlight(state.singleFlight, key, effect);
359 case "latest":
360 return latest(state.latest, key, effect);
361 }
362 }),
363 };
365​
366const settleAtEdge = <A, E>(
367 effect: Effect.Effect<A, E>,
368 options: AtomCommandOptions,
369 reporter: AtomCommandReporter,
370): Promise<AtomCommandResult<A, E>> =>
371 Effect.runPromiseExit(effect, { signal: options.signal }).then((exit) => {
372 const result = AsyncResult.fromExit(exit);
373 reportAtomCommandResult(result, options, reporter);
374 return result;
375 });
376​
377/** Starts a command from outside Effect. Effect callers yield `command.run` instead. */
378export function runAtomCommand<W, A, E>(
379 registry: AtomRegistry.AtomRegistry,
380 command: AtomCommand<W, A, E>,
381 input: W,
382 options: AtomCommandOptions = {},
383 reporter: AtomCommandReporter = console,
384): Promise<AtomCommandResult<A, E>> {
385 return settleAtEdge(
386 Effect.suspend(() => command.run(registry, input)),
387 { ...options, label: options.label ?? command.label },
388 reporter,
389 );
391​
392export function mapAtomCommandResult<A, E, B>(
393 result: AtomCommandResult<A, E>,
394 map: (value: A) => B,
395): AtomCommandResult<B, E> {
396 return result._tag === "Success"
397 ? AsyncResult.success(map(result.value))
398 : AsyncResult.failure(result.cause);
400​
401export function isAtomCommandInterrupted(result: AtomCommandResult<unknown, unknown>): boolean {
402 return result._tag === "Failure" && Cause.hasInterruptsOnly(result.cause);
404​
405/** The command may have been applied even though its reply was lost with the socket. */
406export function isAtomCommandOutcomeUnknown(result: AtomCommandResult<unknown, unknown>): boolean {
407 return result._tag === "Failure" && isLostTransportCause(result.cause);
409​
410export function squashAtomCommandFailure(result: {
411 readonly cause: Cause.Cause<unknown>;
412}): unknown {
413 const squashed = Cause.squash(result.cause);
414 // A server `Effect.die("text")` decodes over RPC as a bare string; callers read `Error`s.
415 return typeof squashed === "string" ? new Error(squashed) : squashed;
417​
418export async function settleAsyncResult<A, E>(
419 execute: () => Promise<Exit.Exit<A, E>>,
420): Promise<SettledAsyncResult<A, E>> {
421 try {
422 return AsyncResult.fromExit(await execute());
423 } catch (defect) {
424 return AsyncResult.failure(Cause.die(defect));
425 }
427​
428export interface AtomQueryOptions extends AtomCommandOptions {
429 /**
430 * Force a fresh execution instead of accepting a value the atom already
431 * holds (e.g. an SWR-cached result within its stale window). Used by
432 * verification flows where a cached failure must not satisfy a retry.
433 */
434 readonly refresh?: boolean;
436​
437/**
438 * A query atom's settled value. The atom stays mounted while the caller waits, and
439 * interrupting the caller releases it.
440 */
441export const awaitAtomResult = <A, E>(
442 registry: AtomRegistry.AtomRegistry,
443 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
444 options: Pick<AtomQueryOptions, "refresh"> = {},
445): Effect.Effect<A, E> =>
446 Effect.scoped(
447 Effect.gen(function* () {
448 yield* AtomRegistry.mount(registry, atom);
449 if (options.refresh) {
450 yield* Effect.sync(() => {
451 const current = registry.get(atom);
452 if (current._tag !== "Initial" && !current.waiting) {
453 registry.refresh(atom);
454 }
455 });
456 }
457 return yield* AtomRegistry.getResult(registry, atom, {
458 suspendOnWaiting: true,
459 });
460 }),
461 );
462​
463/** Reads a query atom from outside Effect. Effect callers yield `awaitAtomResult` instead. */
464export function executeAtomQuery<A, E>(
465 registry: AtomRegistry.AtomRegistry,
466 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
467 options: AtomQueryOptions = {},
468 reporter: AtomCommandReporter = console,
469): Promise<AtomCommandResult<A, E>> {
470 return settleAtEdge(awaitAtomResult(registry, atom, options), options, reporter);
472​
473/** Runs an effect on the calling fiber with the services of an atom runtime. */
474export const provideAtomRuntime =
475 <R, ER>(registry: AtomRegistry.AtomRegistry, runtime: Atom.AtomRuntime<R, ER>) =>
476 <A, E>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E | ER> =>
477 Effect.scoped(
478 AtomRegistry.mount(registry, runtime).pipe(
479 Effect.andThen(AtomRegistry.getResult(registry, runtime)),
480 Effect.flatMap((context) => Effect.provide(effect, context)),
481 ),
482 );
483​
484export function createRuntimeCommand<R, ER, W, A, E>(
485 runtime: Atom.AtomRuntime<R, ER>,
486 options: {
487 readonly label: string;
488 readonly execute: (input: W, registry: AtomRegistry.AtomRegistry) => Effect.Effect<A, E, R>;
489 readonly scheduler?: AtomCommandScheduler;
490 readonly concurrency?: AtomCommandConcurrency<W>;
491 },
492): AtomCommand<W, A, E | ER> {
493 const scheduler = options.scheduler ?? createAtomCommandScheduler();
494 const concurrency = options.concurrency ?? { mode: "parallel" as const };
495 return {
496 label: options.label,
497 run: (registry, input) =>
498 scheduler.schedule(
499 registry,
500 concurrency,
501 input,
502 Effect.suspend(() => options.execute(input, registry)).pipe(
503 provideAtomRuntime(registry, runtime),
504 ),
505 ),
506 };
508​
509export function reportAtomCommandResult(
510 result: AtomCommandResult<unknown, unknown>,
511 options: AtomCommandOptions = {},
512 reporter: AtomCommandReporter = console,
513): void {
514 if (AsyncResult.isSuccess(result) || Cause.hasInterruptsOnly(result.cause)) {
515 return;
516 }
517​
518 const label = options.label ?? "atom command";
519 if (Cause.hasDies(result.cause)) {
520 if (options.reportDefect ?? true) {
521 reporter.error(`[atom-command] ${label} defected`, result.cause);
522 }
523 } else if (options.reportFailure ?? true) {
524 reporter.warn(`[atom-command] ${label} failed`, result.cause);
525 }
527​
528export async function settlePromise<A>(
529 execute: () => Promise<A>,
530): Promise<AtomCommandResult<A, never>> {
531 try {
532 return AsyncResult.success(await execute());
533 } catch (defect) {
534 return AsyncResult.failure(Cause.die(defect));
535 }
537​
538/** Where a query's answer is persisted, so an action's reply can be saved where a read would be. */
539export const queryPersistenceKey = (label: string, input: unknown): string =>
540 JSON.stringify([label, input]);
541​
542function environmentRpcKey<Input>(target: {
543 readonly environmentId: EnvironmentIdType;
544 readonly input: Input;
545}): string {
546 return JSON.stringify([target.environmentId, target.input]);
548​
549function parseEnvironmentRpcKey<Input>(key: string): {
550 readonly environmentId: EnvironmentIdType;
551 readonly input: Input;
552} {
553 const decoded = JSON.parse(key) as [EnvironmentIdType, Input];
554 return {
555 environmentId: EnvironmentId.make(decoded[0]),
556 input: decoded[1],
557 };
559​
560function runInEnvironment<A, E, R>(
561 environmentId: EnvironmentIdType,
562 effect: Effect.Effect<A, E, R>,
563): Effect.Effect<
564 A,
565 E | EnvironmentRegistry.EnvironmentNotRegisteredError,
566 EnvironmentRegistry.EnvironmentRegistry | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
567> {
568 return EnvironmentRegistry.EnvironmentRegistry.pipe(
569 Effect.flatMap((registry) => registry.run(environmentId, effect)),
570 );
572​
573/**
574 * `Atom.makeRefreshOnSignal` subscribes to the signal, so a query that outlives its view on an
575 * idle TTL still re-runs on every change. Reading the signal as a dependency instead lets the
576 * registry re-run a mounted query right away and only mark an idle one stale, which then
577 * refreshes on its next read.
578 */
579const refreshOnSignalWhileRead =
580 <V>(signal: Atom.Atom<unknown>, isFinal: (value: V) => boolean) =>
581 <A extends V>(self: Atom.Atom<A>): Atom.Atom<A> => {
582 // The signal value each registry's data was read under. Held outside the node because the
583 // registry can sweep this node while `self` keeps the data, and the rebuilt node must still
584 // see a change it missed.
585 const readUnder = new WeakMap<AtomRegistry.AtomRegistry, unknown>();
586 return Atom.transform(
587 self,
588 (get) => {
589 const current = get(signal);
590 get.subscribe(self, (value) => get.setSelf(value));
591 const changed =
592 readUnder.has(get.registry) && !Object.is(readUnder.get(get.registry), current);
593 readUnder.set(get.registry, current);
594 if (changed && !isFinal(get.once(self))) get.refresh(self);
595 return get.once(self);
596 },
597 { initialValueTarget: self },
598 );
599 };
600​
601const refreshEveryUntilFinal =
602 <V>(intervalMs: number, isFinal: (value: V) => boolean) =>
603 <A extends V>(self: Atom.Atom<A>): Atom.Atom<A> =>
604 Atom.transform(
605 self,
606 (get) => {
607 const value = get(self);
608 if (!isFinal(value)) {
609 // @effect-diagnostics-next-line globalTimers:off - Mirrors `Atom.withRefresh`, outside an Effect runtime.
610 const handle = setTimeout(() => get.refresh(self), intervalMs);
611 get.addFinalizer(() => clearTimeout(handle));
612 }
613 return value;
614 },
615 { initialValueTarget: self },
616 );
617​
618const isStale = (result: AsyncResult.AsyncResult<unknown, unknown>, staleTimeMs: number) => {
619 if (result.waiting) return false;
620 const success =
621 result._tag === "Failure" ? Option.getOrUndefined(result.previousSuccess) : result;
622 if (success?._tag !== "Success") return result._tag === "Failure";
623 // @effect-diagnostics-next-line globalDate:off - `AsyncResult` timestamps come from `Date.now`.
624 return Date.now() - success.timestamp >= staleTimeMs;
625};
626​
627/**
628 * Stale-while-revalidate on every mount. `Atom.swr` checks only when its node builds, which an idle
629 * TTL skips on a remount; this layer has no TTL (a transform drops it) while `self` keeps the cache.
630 * It reads `self` as a dependency, not a subscription, so `self` goes idle with its last reader.
631 */
632export const revalidateOnMount =
633 (staleTimeMs: number) =>
634 <A, E>(
635 self: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
636 ): Atom.Atom<AsyncResult.AsyncResult<A, E>> =>
637 Atom.transform(
638 self,
639 (get) => {
640 const current = get(self);
641 if (Option.isNone(get.self()) && isStale(current, staleTimeMs)) {
642 let active = true;
643 get.addFinalizer(() => {
644 active = false;
645 });
646 // Deferred out of the build, which runs while React renders. A plain read drops this
647 // node before the task runs, so only a mount refetches.
648 get.registry.schedulerAsync.makeDispatcher().scheduleTask(() => {
649 if (active && isStale(get.once(self), staleTimeMs)) get.refresh(self);
650 }, 0);
651 }
652 return current;
653 },
654 { initialValueTarget: self },
655 );
656​
657/**
658 * A query result's data alone. A refetch always publishes a new result (a new
659 * timestamp, `waiting` on and off), while equal data keeps its identity, so a
660 * reader of only this skips the refetches that changed nothing.
661 */
662export const selectEnvironmentQueryData = <A, E>(result: AsyncResult.AsyncResult<A, E>): A | null =>
663 AsyncResult.getOrElse(result, () => null);
664​
665type EnvironmentConnection = readonly [
666 SupervisorConnectionState,
667 Option.Option<RpcSession.RpcSession>,
668];
669​
670const connectionAtomsByRuntime = new WeakMap<
671 object,
672 (
673 environmentId: EnvironmentIdType,
674 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentConnection | null>>
675>();
676​
677/**
678 * One connection atom per environment for every query on a runtime, so a reader of the session
679 * generation and a query it re-runs see the same connection change at once.
680 */
681function environmentConnectionAtoms<R, ER>(
682 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
683) {
684 const existing = connectionAtomsByRuntime.get(runtime);
685 if (existing !== undefined) return existing;
686 const family = Atom.family((environmentId: EnvironmentIdType) =>
687 runtime.atom(
688 followStreamInEnvironment(
689 environmentId,
690 Stream.unwrap(
691 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
692 Effect.map((supervisor) =>
693 SubscriptionRef.changes(supervisor.state).pipe(
694 Stream.zipLatest(SubscriptionRef.changes(supervisor.session)),
695 ),
696 ),
697 ),
698 ),
699 ),
700 { initialValue: null },
701 ),
702 ) as (
703 environmentId: EnvironmentIdType,
704 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentConnection | null>>;
705 connectionAtomsByRuntime.set(runtime, family);
706 return family;
708​
709export function environmentConnectionAtom<R, ER>(
710 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
711 environmentId: EnvironmentIdType,
712) {
713 return environmentConnectionAtoms(runtime)(environmentId);
715​
716const sessionGenerationAtomsByRuntime = new WeakMap<
717 object,
718 (environmentId: EnvironmentIdType) => Atom.Atom<number>
719>();
720​
721/**
722 * Counts established sessions; it changes only when a new one comes up, so failed one-shot reads
723 * can watch it to run again. Keyed on the session object because the supervisor's `generation`
724 * restarts when the registry installs a new supervisor (re-pairing, route edits).
725 */
726export function environmentSessionGenerationAtom<R, ER>(
727 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
728 environmentId: EnvironmentIdType,
729): Atom.Atom<number> {
730 let family = sessionGenerationAtomsByRuntime.get(runtime);
731 if (family === undefined) {
732 const connectionAtom = environmentConnectionAtoms(runtime);
733 const sessionsSeen = Atom.family((id: EnvironmentIdType) =>
734 Atom.make(
735 (get): { readonly session: RpcSession.RpcSession | null; readonly count: number } => {
736 const previous = Option.getOrElse(
737 get.self<{ readonly session: RpcSession.RpcSession | null; readonly count: number }>(),
738 () => ({ session: null, count: 0 }),
739 );
740 const connection = AsyncResult.getOrElse(get(connectionAtom(id)), () => null);
741 if (connection === null || connection[0].phase !== "connected") return previous;
742 const session = Option.getOrNull(connection[1]);
743 return session === null || session === previous.session
744 ? previous
745 : { session, count: previous.count + 1 };
746 },
747 ),
748 );
749 family = Atom.family((id: EnvironmentIdType) =>
750 Atom.make((get) => get(sessionsSeen(id)).count).pipe(
751 Atom.withLabel(`environment-session-generation:${id}`),
752 ),
753 );
754 sessionGenerationAtomsByRuntime.set(runtime, family);
755 }
756 return family(environmentId);
758​
759export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
760 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
761 options: EnvironmentQueryAtomOptions<
762 Input,
763 A,
764 E,
765 | EnvironmentSupervisor.EnvironmentSupervisor
766 | EnvironmentRegistry.EnvironmentRegistry
767 | AtomRegistry.AtomRegistry
768 | R
769 >,
770): (
771 target: { readonly environmentId: EnvironmentIdType; readonly input: Input },
772 mountScope?: string,
773) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
774 const connectionAtom = environmentConnectionAtoms(runtime);
775 // `Atom.family` holds members weakly and the mounted layer has no TTL, so each member lives
776 // as long as its cache: keyed weakly, this lets both go once the cache's TTL ends.
777 const cacheFamily = Atom.family((key: string) => {
778 const target = parseEnvironmentRpcKey<Input>(key);
779 const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
780 const queryAtom = runtime
781 .atom<
782 A,
783 | E
784 | ConnectionAttemptError
785 | EnvironmentRegistry.EnvironmentNotRegisteredError
786 | EnvironmentRpcUnavailableError
787 >((get) => {
788 const connection = AsyncResult.getOrElse(
789 get(connectionAtom(target.environmentId)),
790 () => null,
791 );
792 // A refetch that returns equal content keeps the previous value's
793 // references, so readers of the data skip re-rendering on idle polls.
794 const share = (value: A): A =>
795 reuseUnchanged(
796 Option.getOrUndefined(
797 Option.flatMap(get.self<AsyncResult.AsyncResult<A, unknown>>(), AsyncResult.value),
798 ),
799 value,
800 );
801 const emit = (value: A) =>
802 Effect.sync(() => get.setSelf(AsyncResult.success(share(value), { waiting: true }))).pipe(
803 // A value set while the atom builds wins over the build's own
804 // result, so a query that then settled synchronously would stay
805 // waiting forever. Suspend on a promise (`yieldNow` is drained
806 // inside the build) so the settled result arrives asynchronously.
807 Effect.andThen(Effect.promise(() => Promise.resolve())),
808 );
809 const execute = (): Effect.Effect<
810 A,
811 | E
812 | ConnectionAttemptError
813 | EnvironmentRegistry.EnvironmentNotRegisteredError
814 | EnvironmentRpcUnavailableError,
815 | EnvironmentRegistry.EnvironmentRegistry
816 | AtomRegistry.AtomRegistry
817 | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
818 > => {
819 if (connection === null) return Effect.never;
820 const [connectionState, session] = connection;
821 switch (connectionState.phase) {
822 case "connected":
823 return Option.isSome(session)
824 ? runInEnvironment(
825 target.environmentId,
826 options
827 .execute(
828 target.input,
829 emit,
830 Option.flatMap(
831 get.self<AsyncResult.AsyncResult<A, unknown>>(),
832 AsyncResult.value,
833 ),
834 )
835 .pipe(pendingOnceSessionReplaced(session.value)),
836 )
837 : Effect.never;
838 case "connecting":
839 case "backoff":
840 // A retry can take minutes. A query with an answer keeps showing it while it
841 // waits; one with nothing to show reports the failure the retry is recovering
842 // from, so its reader stops loading, and re-runs when the connection settles.
843 return connectionState.lastFailure !== null &&
844 Option.isNone(
845 Option.flatMap(
846 get.self<AsyncResult.AsyncResult<A, unknown>>(),
847 AsyncResult.value,
848 ),
849 )
850 ? Effect.fail(connectionState.lastFailure)
851 : Effect.never;
852 case "available":
853 case "offline":
854 case "blocked":
855 if (connectionState.lastFailure !== null) {
856 return Effect.fail(connectionState.lastFailure);
857 }
858 return Effect.fail(
859 new EnvironmentRpcUnavailableError({
860 environmentId: target.environmentId,
861 ...translatableMessage(
862 connectionState.phase === "offline"
863 ? msg`Environment ${{ environmentId: target.environmentId }} is offline.`
864 : connectionState.phase === "blocked"
865 ? msg`Environment ${{ environmentId: target.environmentId }} is blocked.`
866 : msg`Environment ${{ environmentId: target.environmentId }} is not connected.`,
867 ),
868 }),
869 );
870 }
871 };
872 const onAnswer = options.onAnswer;
873 const answer = () =>
874 onAnswer === undefined
875 ? execute().pipe(Effect.map(share))
876 : execute().pipe(
877 Effect.map(share),
878 Effect.tap((value) => onAnswer(target, value, get.registry)),
879 );
880 if (!options.persistence) return answer();
881 const persistence = options.persistence;
882 const cacheKey = queryPersistenceKey(options.label, target.input);
883 const previous = Option.flatMap(
884 get.self<AsyncResult.AsyncResult<A, unknown>>(),
885 AsyncResult.value,
886 );
887 return Effect.gen(function* () {
888 const cached = Option.isSome(previous)
889 ? previous
890 : yield* persistence.load(target.environmentId, cacheKey);
891 if (
892 Option.isSome(cached) &&
893 (connection === null || connection[0].phase !== "connected")
894 ) {
895 return cached.value;
896 }
897 if (Option.isNone(previous) && Option.isSome(cached)) yield* emit(cached.value);
898 // Readers must not wait on the disk: web saves one IndexedDB row per listed PR's stats.
899 // The save ends with the query, so a removed environment's cache stays cleared.
900 return yield* answer().pipe(
901 Effect.tap((value) =>
902 persistence.save(target.environmentId, cacheKey, value).pipe(Effect.forkScoped),
903 ),
904 );
905 });
906 })
907 .pipe(Atom.setIdleTTL(idleTtlMs));
908 const isFinal = (result: AsyncResult.AsyncResult<A, unknown>) =>
909 options.isFinal !== undefined && Option.exists(AsyncResult.value(result), options.isFinal);
910 const intervalQuery =
911 options.refreshIntervalMs === undefined
912 ? queryAtom
913 : queryAtom.pipe(refreshEveryUntilFinal(options.refreshIntervalMs, isFinal));
914 const refreshTrigger = options.refreshTrigger?.(target, intervalQuery);
915 return (
916 refreshTrigger === undefined
917 ? intervalQuery
918 : intervalQuery.pipe(refreshOnSignalWhileRead(refreshTrigger, isFinal))
919 ).pipe(Atom.setIdleTTL(idleTtlMs));
920 });
921 type QueryAtom = ReturnType<typeof cacheFamily>;
922 const membersByCache = new WeakMap<QueryAtom, Map<string | undefined, QueryAtom>>();
923 return (target, mountScope) => {
924 const key = environmentRpcKey(target);
925 const cache = cacheFamily(key);
926 let members = membersByCache.get(cache);
927 if (members === undefined) {
928 members = new Map();
929 membersByCache.set(cache, members);
930 }
931 const existing = members.get(mountScope);
932 if (existing !== undefined) return existing;
933 const member = cache.pipe(
934 revalidateOnMount(options.staleTimeMs ?? 30_000),
935 Atom.withLabel(`${options.label}:${key}${mountScope === undefined ? "" : `:${mountScope}`}`),
936 );
937 members.set(mountScope, member);
938 return member;
939 };
941​
942export function createEnvironmentSubscriptionAtomFamily<R, ER, Input, A, E>(
943 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
944 options: EnvironmentSubscriptionAtomOptions<
945 Input,
946 A,
947 E,
948 EnvironmentSupervisor.EnvironmentSupervisor | AtomRegistry.AtomRegistry | R
949 >,
950) {
951 const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
952 const label = (key: string) =>
953 options.sensitiveInput
954 ? `${options.label}:${parseEnvironmentRpcKey<Input>(key).environmentId}`
955 : `${options.label}:${key}`;
956 const live = Atom.family((key: string) => {
957 const target = parseEnvironmentRpcKey<Input>(key);
958 return runtime
959 .atom(
960 Stream.suspend(() =>
961 followStreamInEnvironment(target.environmentId, options.subscribe(target.input)),
962 ).pipe(options.completeWhen ? Stream.takeUntil(options.completeWhen) : (stream) => stream),
963 )
964 .pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(label(key)));
965 });
966 const { completeWhen, completedTtlMs } = options;
967 if (completeWhen === undefined || completedTtlMs === undefined) {
968 return (target: { readonly environmentId: EnvironmentIdType; readonly input: Input }) =>
969 live(environmentRpcKey(target));
970 }
971 const completed = Atom.family((key: string) =>
972 Atom.make(Option.none<A>()).pipe(
973 Atom.setIdleTTL(completedTtlMs),
974 Atom.withLabel(`${label(key)}:completed`),
975 ),
976 );
977 // Reading `completed` first drops the live subscription once its value is final.
978 const family = Atom.family((key: string) =>
979 Atom.make((get) => {
980 const done = get(completed(key));
981 if (Option.isSome(done)) return AsyncResult.success(done.value);
982 const result = get(live(key));
983 if (AsyncResult.isSuccess(result) && !result.waiting && completeWhen(result.value)) {
984 get.set(completed(key), Option.some(result.value));
985 }
986 return result;
987 }).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(label(key))),
988 );
989 return (target: { readonly environmentId: EnvironmentIdType; readonly input: Input }) =>
990 family(environmentRpcKey(target));
992​
993export function createEnvironmentCommand<R, ER, Input, A, E>(
994 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
995 options: EnvironmentCommandAtomOptions<
996 Input,
997 A,
998 E,
999 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry | R
1000 >,
1001) {
1002 return createRuntimeCommand(runtime, {
1003 label: options.label,
1004 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
1005 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
1006 execute: (target, registry) =>
1007 runInEnvironment(
1008 target.environmentId,
1009 options.execute(target.input, registry, target.environmentId),
1010 ),
1011 });
1013​
1014export function createEnvironmentRpcQueryAtomFamily<
1015 R,
1016 ER,
1017 TTag extends Exclude<EnvironmentUnaryRpcTag, ClientGuardedRpcTag>,
1019 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
1020 options: {
1021 readonly label: string;
1022 readonly tag: TTag;
1023 readonly execute?: (
1024 input: EnvironmentRpcInput<TTag>,
1025 emit: (value: EnvironmentRpcSuccess<TTag>) => Effect.Effect<void>,
1026 previous: Option.Option<EnvironmentRpcSuccess<TTag>>,
1027 ) => Effect.Effect<
1028 EnvironmentRpcSuccess<TTag>,
1029 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
1030 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry
1031 >;
1032 readonly persistence?: QueryPersistence<EnvironmentRpcSuccess<TTag>>;
1033 readonly staleTimeMs?: number;
1034 readonly idleTtlMs?: number;
1035 readonly refreshIntervalMs?: number;
1036 readonly refreshTrigger?: (target: {
1037 readonly environmentId: EnvironmentIdType;
1038 readonly input: EnvironmentRpcInput<TTag>;
1039 }) => Atom.Atom<unknown> | undefined;
1040 readonly isFinal?: (value: EnvironmentRpcSuccess<TTag>) => boolean;
1041 readonly onAnswer?: QueryAnswerHandler<EnvironmentRpcInput<TTag>, EnvironmentRpcSuccess<TTag>>;
1042 },
1043) {
1044 return createEnvironmentQueryAtomFamily(runtime, {
1045 label: options.label,
1046 ...(options.persistence === undefined ? {} : { persistence: options.persistence }),
1047 ...(options.staleTimeMs === undefined ? {} : { staleTimeMs: options.staleTimeMs }),
1048 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
1049 ...(options.refreshIntervalMs === undefined
1050 ? {}
1051 : { refreshIntervalMs: options.refreshIntervalMs }),
1052 ...(options.refreshTrigger === undefined ? {} : { refreshTrigger: options.refreshTrigger }),
1053 ...(options.isFinal === undefined ? {} : { isFinal: options.isFinal }),
1054 ...(options.onAnswer === undefined ? {} : { onAnswer: options.onAnswer }),
1055 execute: (
1056 input: EnvironmentRpcInput<TTag>,
1057 emit: (value: EnvironmentRpcSuccess<TTag>) => Effect.Effect<void>,
1058 previous: Option.Option<EnvironmentRpcSuccess<TTag>>,
1059 ) => options.execute?.(input, emit, previous) ?? request(options.tag, input),
1060 });
1062​
1063export function createEnvironmentRpcSubscriptionAtomFamily<
1064 R,
1065 ER,
1066 TTag extends EnvironmentSubscriptionRpcTag,
1067 B = EnvironmentRpcStreamValue<TTag>,
1069 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
1070 options: {
1071 readonly label: string;
1072 readonly tag: TTag;
1073 readonly idleTtlMs?: number;
1074 readonly completeWhen?: (value: B) => boolean;
1075 readonly completedTtlMs?: number;
1076 readonly transform?: (
1077 stream: Stream.Stream<
1078 EnvironmentRpcStreamValue<TTag>,
1079 EnvironmentRpcStreamFailure<TTag>,
1080 EnvironmentSupervisor.EnvironmentSupervisor | R
1081 >,
1082 ) => Stream.Stream<
1083 B,
1084 EnvironmentRpcStreamFailure<TTag>,
1085 EnvironmentSupervisor.EnvironmentSupervisor | R
1086 >;
1087 },
1088) {
1089 return createEnvironmentSubscriptionAtomFamily(runtime, {
1090 label: options.label,
1091 ...(options.completeWhen === undefined ? {} : { completeWhen: options.completeWhen }),
1092 ...(options.completedTtlMs === undefined ? {} : { completedTtlMs: options.completedTtlMs }),
1093 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
1094 subscribe: (input: EnvironmentRpcInput<TTag>) => {
1095 const stream = subscribe(options.tag, input);
1096 return options.transform === undefined
1097 ? (stream as Stream.Stream<
1098 B,
1099 EnvironmentRpcStreamFailure<TTag>,
1100 EnvironmentSupervisor.EnvironmentSupervisor | R
1101 >)
1102 : options.transform(stream);
1103 },
1104 });
1106​
1107export function createEnvironmentRpcCommand<
1108 R,
1109 ER,
1110 TTag extends EnvironmentUnaryRpcTag,
1111 Input extends EnvironmentRpcInput<TTag> = EnvironmentRpcInput<TTag>,
1112 Started = undefined,
1114 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
1115 options: {
1116 readonly label: string;
1117 readonly tag: TTag;
1118 /** Runs once authorized, as the request starts; what it returns reaches `onSuccess`. */
1119 readonly onStart?: (
1120 target: {
1121 readonly environmentId: EnvironmentIdType;
1122 readonly input: NoInfer<Input>;
1123 },
1124 registry: AtomRegistry.AtomRegistry,
1125 ) => Started;
1126 readonly execute?: (
1127 input: Input,
1128 registry: AtomRegistry.AtomRegistry,
1129 environmentId: EnvironmentIdType,
1130 ) => Effect.Effect<
1131 EnvironmentRpcSuccess<TTag>,
1132 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
1133 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry
1134 >;
1135 readonly scheduler?: AtomCommandScheduler;
1136 readonly concurrency?: AtomCommandConcurrency<{
1137 readonly environmentId: EnvironmentIdType;
1138 readonly input: NoInfer<Input>;
1139 }>;
1140 readonly onSuccess?: (
1141 target: {
1142 readonly environmentId: EnvironmentIdType;
1143 readonly input: NoInfer<Input>;
1144 },
1145 registry: AtomRegistry.AtomRegistry,
1146 result: EnvironmentRpcSuccess<TTag>,
1147 started: Started | undefined,
1148 ) => Effect.Effect<void, never, R>;
1149 readonly onSettled?: (
1150 target: {
1151 readonly environmentId: EnvironmentIdType;
1152 readonly input: NoInfer<Input>;
1153 },
1154 registry: AtomRegistry.AtomRegistry,
1155 exit: Exit.Exit<EnvironmentRpcSuccess<TTag>, unknown>,
1156 ) => Effect.Effect<void, never, R>;
1157 },
1158) {
1159 const permissions = createCommandPermissions(runtime, options.tag);
1160 const command = createEnvironmentCommand(runtime, {
1161 label: options.label,
1162 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
1163 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
1164 execute: (input: Input, registry, environmentId) => {
1165 const target = {
1166 environmentId,
1167 input,
1168 };
1169 let started: Started | undefined;
1170 // Routing requires consent on the origin as well as the actual destination.
1171 // The transport check below deliberately checks the destination again.
1172 return permissions.authorize(registry, environmentId, input).pipe(
1173 Effect.andThen(() => {
1174 started = options.onStart?.(target, registry);
1175 return (
1176 options.execute?.(input, registry, environmentId) ?? requestGuarded(options.tag, input)
1177 );
1178 }),
1179 Effect.provideService(RpcPermissionGuard, {
1180 authorize: (id, method, payload) =>
1181 createCommandPermissions(runtime, method).authorize(registry, id, payload),
1182 }),
1183 Effect.tap(
1184 (result) => options.onSuccess?.(target, registry, result, started) ?? Effect.void,
1185 ),
1186 Effect.onExit((exit) => options.onSettled?.(target, registry, exit) ?? Effect.void),
1187 );
1188 },
1189 });
1190 return {
1191 ...command,
1192 requiredScopes: permissions.requiredScopes,
1193 permissionAtom: permissions.permissionAtom,
1194 };