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

runtime.ts

1,045 lines37.1 KB

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