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

runtime.ts

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