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

runtime.ts

1,195 lines43.5 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 request,
37 requestGuarded,
38 RpcPermissionGuard,
39 subscribe,
40} from "../rpc/client.ts";
41import * as EnvironmentSupervisor from "../connection/supervisor.ts";
42import type * as RpcSession from "../rpc/session.ts";
43​
44const isEnvironmentRpcUnavailable = Schema.is(EnvironmentRpcUnavailableError);
45​
46/**
47 * Holds back the unavailable failure of a query whose session went away. The
48 * query atom reruns when it sees that session change, so settling first would
49 * show a failure for a query that is about to retry. While `session` is still
50 * current no rerun is coming, and the failure stands.
51 */
52const pendingOnceSessionReplaced =
53 (session: RpcSession.RpcSession) =>
54 <A, E, R>(effect: Effect.Effect<A, E, R>) =>
55 effect.pipe(
56 // The query's error type is generic, so its tags are unknown to `catchTags`.
57 Effect.catchIf(isEnvironmentRpcUnavailable, (error) =>
58 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
59 Effect.flatMap((supervisor) => SubscriptionRef.get(supervisor.session)),
60 Effect.flatMap((current) =>
61 Option.isSome(current) && current.value === session ? Effect.fail(error) : Effect.never,
62 ),
63 ),
64 ),
65 );
66​
67interface EnvironmentAtomOptions<Input, A, E, R> {
68 readonly label: string;
69 readonly execute: (input: Input) => Effect.Effect<A, E, R>;
70 readonly scheduler?: AtomCommandScheduler;
71 readonly concurrency?: AtomCommandConcurrency<{
72 readonly environmentId: EnvironmentIdType;
73 readonly input: Input;
74 }>;
76​
77interface EnvironmentCommandAtomOptions<Input, A, E, R> extends Omit<
78 EnvironmentAtomOptions<Input, A, E, R>,
79 "execute"
80> {
81 readonly execute: (
82 input: Input,
83 registry: AtomRegistry.AtomRegistry,
84 environmentId: EnvironmentIdType,
85 ) => Effect.Effect<A, E, R>;
87​
88interface EnvironmentQueryAtomOptions<Input, A, E, R> extends Omit<
89 EnvironmentAtomOptions<Input, A, E, R>,
90 "execute"
91> {
92 /**
93 * `emit` shows a provisional value while the query keeps waiting. The settled
94 * result replaces it, so catch failures that should keep it on screen.
95 */
96 readonly execute: (
97 input: Input,
98 emit: (value: A) => Effect.Effect<void>,
99 previous: Option.Option<A>,
100 ) => Effect.Effect<A, E, R>;
101 readonly persistence?: QueryPersistence<A>;
102 readonly staleTimeMs?: number;
103 readonly idleTtlMs?: number;
104 readonly refreshIntervalMs?: number;
105 /** Each change of the returned signal refreshes the query; `query` is the data it refreshes. */
106 readonly refreshTrigger?: (
107 target: {
108 readonly environmentId: EnvironmentIdType;
109 readonly input: Input;
110 },
111 query: Atom.Atom<AsyncResult.AsyncResult<A, unknown>>,
112 ) => Atom.Atom<unknown> | undefined;
113 readonly isFinal?: (value: A) => boolean;
114 /**
115 * Runs where each server answer lands, before readers see it, so derived records (summaries,
116 * snapshots, watches) come from the producer instead of from components watching the data.
117 * Cached and emitted provisional values are not answers.
118 */
119 readonly onAnswer?: QueryAnswerHandler<Input, A>;
121​
122export type QueryAnswerHandler<Input, A> = (
123 target: { readonly environmentId: EnvironmentIdType; readonly input: Input },
124 value: A,
125 registry: AtomRegistry.AtomRegistry,
126) => Effect.Effect<void>;
127​
128interface EnvironmentSubscriptionAtomOptions<Input, A, E, R> {
129 readonly sensitiveInput?: boolean;
130 readonly label: string;
131 readonly subscribe: (input: Input) => Stream.Stream<A, E, R>;
132 readonly completeWhen?: (value: A) => boolean;
133 readonly idleTtlMs?: number;
134 /** Keeps a completed value this long after its last reader leaves, so reopening skips a resubscribe. */
135 readonly completedTtlMs?: number;
137​
138export type SettledAsyncResult<A, E> = AsyncResult.Success<A, E> | AsyncResult.Failure<A, E>;
139​
140export type AtomCommandResult<A, E> = SettledAsyncResult<A, E>;
141​
142export type AtomCommandSuccess<R> = R extends AtomCommandResult<infer A, infer _E> ? A : never;
143​
144export type AtomCommandFailure<R> = R extends AtomCommandResult<infer _A, infer E> ? E : never;
145​
146export interface AtomCommandOptions {
147 readonly label?: string;
148 readonly reportFailure?: boolean;
149 readonly reportDefect?: boolean;
150 /** Aborting interrupts the run. */
151 readonly signal?: AbortSignal | undefined;
153​
154export interface AtomCommandReporter {
155 readonly warn: (message: string, cause: Cause.Cause<unknown>) => void;
156 readonly error: (message: string, cause: Cause.Cause<unknown>) => void;
158​
159export interface AtomCommand<W, A, E> {
160 readonly label: string;
161 /**
162 * Runs on the calling fiber, so interrupting the caller stops the command. Code outside
163 * Effect starts it with `runAtomCommand`.
164 */
165 readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Effect.Effect<A, E>;
167​
168export type AtomCommandConcurrency<W> =
169 | { readonly mode: "parallel" }
170 | {
171 readonly mode: "serial" | "singleFlight" | "latest";
172 readonly key: (input: W) => string;
173 };
174​
175/** One run that several callers wait on. It is interrupted once the last of them stops waiting. */
176interface SharedRun {
177 readonly result: Deferred.Deferred<unknown, unknown>;
178 waiters: number;
179 fiber: Fiber.Fiber<unknown, unknown> | undefined;
181​
182interface AtomCommandLatestLane {
183 pending: (SharedRun & { start: Effect.Effect<void> }) | undefined;
185​
186interface AtomCommandSchedulerState {
187 readonly serial: Map<string, { readonly semaphore: Semaphore.Semaphore; users: number }>;
188 readonly singleFlight: Map<string, SharedRun>;
189 readonly latest: Map<string, AtomCommandLatestLane>;
191​
192export interface AtomCommandScheduler {
193 readonly schedule: <W, A, E, R>(
194 registry: AtomRegistry.AtomRegistry,
195 concurrency: AtomCommandConcurrency<W>,
196 input: W,
197 effect: Effect.Effect<A, E, R>,
198 ) => Effect.Effect<A, E, R>;
200​
201const startSharedRun = <A, E>(run: SharedRun, effect: Effect.Effect<A, E>) =>
202 effect.pipe(
203 Effect.interruptible,
204 Effect.onExit((exit) => Deferred.done(run.result, exit)),
205 Effect.ignoreCause,
206 Effect.forkDetach({ startImmediately: true }),
207 Effect.map((fiber) => {
208 run.fiber = fiber;
209 }),
210 );
211​
212const awaitSharedRun = <A, E>(
213 run: SharedRun,
214 restore: <X, XE, XR>(effect: Effect.Effect<X, XE, XR>) => Effect.Effect<X, XE, XR>,
215 abandon: Effect.Effect<void>,
216): Effect.Effect<A, E> => {
217 run.waiters++;
218 return restore(Deferred.await(run.result as Deferred.Deferred<A, E>)).pipe(
219 Effect.onInterrupt(() => (--run.waiters === 0 ? abandon : Effect.void)),
220 );
221};
222​
223const interruptSharedRun = (run: SharedRun) =>
224 run.fiber === undefined ? Effect.void : Fiber.interrupt(run.fiber);
225​
226export function createAtomCommandScheduler(): AtomCommandScheduler {
227 const registryStates = new WeakMap<AtomRegistry.AtomRegistry, AtomCommandSchedulerState>();
228 const stateFor = (registry: AtomRegistry.AtomRegistry) => {
229 let state = registryStates.get(registry);
230 if (state === undefined) {
231 state = { serial: new Map(), singleFlight: new Map(), latest: new Map() };
232 registryStates.set(registry, state);
233 }
234 return state;
235 };
236​
237 const serial = <A, E, R>(
238 lanes: AtomCommandSchedulerState["serial"],
239 key: string,
240 effect: Effect.Effect<A, E, R>,
241 ) =>
242 Effect.acquireUseRelease(
243 Effect.sync(() => {
244 const lane = lanes.get(key) ?? { semaphore: Semaphore.makeUnsafe(1), users: 0 };
245 lanes.set(key, lane);
246 lane.users++;
247 return lane;
248 }),
249 (lane) => lane.semaphore.withPermit(effect),
250 (lane) =>
251 Effect.sync(() => {
252 if (--lane.users === 0) lanes.delete(key);
253 }),
254 );
255​
256 const singleFlight = <A, E, R>(
257 flights: AtomCommandSchedulerState["singleFlight"],
258 key: string,
259 effect: Effect.Effect<A, E, R>,
260 ) =>
261 Effect.uninterruptibleMask((restore) =>
262 Effect.gen(function* () {
263 let flight = flights.get(key);
264 if (flight === undefined) {
265 const started: SharedRun = {
266 result: Deferred.makeUnsafe(),
267 waiters: 0,
268 fiber: undefined,
269 };
270 flight = started;
271 flights.set(key, started);
272 const context = yield* Effect.context<R>();
273 yield* startSharedRun(
274 started,
275 effect.pipe(
276 Effect.provide(context),
277 Effect.ensuring(
278 Effect.sync(() => {
279 if (flights.get(key) === started) flights.delete(key);
280 }),
281 ),
282 ),
283 );
284 }
285 const joined = flight;
286 return yield* awaitSharedRun<A, E>(
287 joined,
288 restore,
289 Effect.suspend(() => {
290 // Left the map first, so a caller arriving during the interrupt starts a fresh run.
291 if (flights.get(key) === joined) flights.delete(key);
292 return interruptSharedRun(joined);
293 }),
294 );
295 }),
296 );
297​
298 const latest = <A, E, R>(
299 lanes: AtomCommandSchedulerState["latest"],
300 key: string,
301 effect: Effect.Effect<A, E, R>,
302 ) =>
303 Effect.uninterruptibleMask((restore) =>
304 Effect.gen(function* () {
305 const context = yield* Effect.context<R>();
306 const existing = lanes.get(key);
307 const lane = existing ?? { pending: undefined };
308 lanes.set(key, lane);
309 // Callers that queue behind a run share the next one, which runs the newest of them.
310 const batch = lane.pending ?? {
311 result: Deferred.makeUnsafe(),
312 waiters: 0,
313 fiber: undefined,
314 start: Effect.void,
315 };
316 batch.start = startSharedRun(batch, Effect.provide(effect, context));
317 lane.pending = batch;
318​
319 if (existing === undefined) {
320 const drain: Effect.Effect<void> = Effect.suspend(() => {
321 const next = lane.pending;
322 if (next === undefined) {
323 lanes.delete(key);
324 return Effect.void;
325 }
326 lane.pending = undefined;
327 return next.start.pipe(
328 Effect.andThen(Deferred.await(next.result)),
329 Effect.exit,
330 Effect.andThen(drain),
331 );
332 });
333 yield* drain.pipe(Effect.forkDetach({ startImmediately: true }));
334 }
335 return yield* awaitSharedRun<A, E>(
336 batch,
337 restore,
338 Effect.suspend(() => {
339 if (lane.pending === batch) lane.pending = undefined;
340 return interruptSharedRun(batch);
341 }),
342 );
343 }),
344 );
345​
346 return {
347 schedule: (registry, concurrency, input, effect) =>
348 concurrency.mode === "parallel"
349 ? effect
350 : Effect.suspend(() => {
351 const key = concurrency.key(input);
352 const state = stateFor(registry);
353 switch (concurrency.mode) {
354 case "serial":
355 return serial(state.serial, key, effect);
356 case "singleFlight":
357 return singleFlight(state.singleFlight, key, effect);
358 case "latest":
359 return latest(state.latest, key, effect);
360 }
361 }),
362 };
364​
365const settleAtEdge = <A, E>(
366 effect: Effect.Effect<A, E>,
367 options: AtomCommandOptions,
368 reporter: AtomCommandReporter,
369): Promise<AtomCommandResult<A, E>> =>
370 Effect.runPromiseExit(effect, { signal: options.signal }).then((exit) => {
371 const result = AsyncResult.fromExit(exit);
372 reportAtomCommandResult(result, options, reporter);
373 return result;
374 });
375​
376/** Starts a command from outside Effect. Effect callers yield `command.run` instead. */
377export function runAtomCommand<W, A, E>(
378 registry: AtomRegistry.AtomRegistry,
379 command: AtomCommand<W, A, E>,
380 input: W,
381 options: AtomCommandOptions = {},
382 reporter: AtomCommandReporter = console,
383): Promise<AtomCommandResult<A, E>> {
384 return settleAtEdge(
385 Effect.suspend(() => command.run(registry, input)),
386 { ...options, label: options.label ?? command.label },
387 reporter,
388 );
390​
391export function mapAtomCommandResult<A, E, B>(
392 result: AtomCommandResult<A, E>,
393 map: (value: A) => B,
394): AtomCommandResult<B, E> {
395 return result._tag === "Success"
396 ? AsyncResult.success(map(result.value))
397 : AsyncResult.failure(result.cause);
399​
400export function isAtomCommandInterrupted(result: AtomCommandResult<unknown, unknown>): boolean {
401 return result._tag === "Failure" && Cause.hasInterruptsOnly(result.cause);
403​
404export function squashAtomCommandFailure(result: {
405 readonly cause: Cause.Cause<unknown>;
406}): unknown {
407 const squashed = Cause.squash(result.cause);
408 // A server `Effect.die("text")` decodes over RPC as a bare string; callers read `Error`s.
409 return typeof squashed === "string" ? new Error(squashed) : squashed;
411​
412export async function settleAsyncResult<A, E>(
413 execute: () => Promise<Exit.Exit<A, E>>,
414): Promise<SettledAsyncResult<A, E>> {
415 try {
416 return AsyncResult.fromExit(await execute());
417 } catch (defect) {
418 return AsyncResult.failure(Cause.die(defect));
419 }
421​
422export interface AtomQueryOptions extends AtomCommandOptions {
423 /**
424 * Force a fresh execution instead of accepting a value the atom already
425 * holds (e.g. an SWR-cached result within its stale window). Used by
426 * verification flows where a cached failure must not satisfy a retry.
427 */
428 readonly refresh?: boolean;
430​
431/**
432 * A query atom's settled value. The atom stays mounted while the caller waits, and
433 * interrupting the caller releases it.
434 */
435export const awaitAtomResult = <A, E>(
436 registry: AtomRegistry.AtomRegistry,
437 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
438 options: Pick<AtomQueryOptions, "refresh"> = {},
439): Effect.Effect<A, E> =>
440 Effect.scoped(
441 Effect.gen(function* () {
442 yield* AtomRegistry.mount(registry, atom);
443 if (options.refresh) {
444 yield* Effect.sync(() => {
445 const current = registry.get(atom);
446 if (current._tag !== "Initial" && !current.waiting) {
447 registry.refresh(atom);
448 }
449 });
450 }
451 return yield* AtomRegistry.getResult(registry, atom, {
452 suspendOnWaiting: true,
453 });
454 }),
455 );
456​
457/** Reads a query atom from outside Effect. Effect callers yield `awaitAtomResult` instead. */
458export function executeAtomQuery<A, E>(
459 registry: AtomRegistry.AtomRegistry,
460 atom: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
461 options: AtomQueryOptions = {},
462 reporter: AtomCommandReporter = console,
463): Promise<AtomCommandResult<A, E>> {
464 return settleAtEdge(awaitAtomResult(registry, atom, options), options, reporter);
466​
467/** Runs an effect on the calling fiber with the services of an atom runtime. */
468export const provideAtomRuntime =
469 <R, ER>(registry: AtomRegistry.AtomRegistry, runtime: Atom.AtomRuntime<R, ER>) =>
470 <A, E>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E | ER> =>
471 Effect.scoped(
472 AtomRegistry.mount(registry, runtime).pipe(
473 Effect.andThen(AtomRegistry.getResult(registry, runtime)),
474 Effect.flatMap((context) => Effect.provide(effect, context)),
475 ),
476 );
477​
478export function createRuntimeCommand<R, ER, W, A, E>(
479 runtime: Atom.AtomRuntime<R, ER>,
480 options: {
481 readonly label: string;
482 readonly execute: (input: W, registry: AtomRegistry.AtomRegistry) => Effect.Effect<A, E, R>;
483 readonly scheduler?: AtomCommandScheduler;
484 readonly concurrency?: AtomCommandConcurrency<W>;
485 },
486): AtomCommand<W, A, E | ER> {
487 const scheduler = options.scheduler ?? createAtomCommandScheduler();
488 const concurrency = options.concurrency ?? { mode: "parallel" as const };
489 return {
490 label: options.label,
491 run: (registry, input) =>
492 scheduler.schedule(
493 registry,
494 concurrency,
495 input,
496 Effect.suspend(() => options.execute(input, registry)).pipe(
497 provideAtomRuntime(registry, runtime),
498 ),
499 ),
500 };
502​
503export function reportAtomCommandResult(
504 result: AtomCommandResult<unknown, unknown>,
505 options: AtomCommandOptions = {},
506 reporter: AtomCommandReporter = console,
507): void {
508 if (AsyncResult.isSuccess(result) || Cause.hasInterruptsOnly(result.cause)) {
509 return;
510 }
511​
512 const label = options.label ?? "atom command";
513 if (Cause.hasDies(result.cause)) {
514 if (options.reportDefect ?? true) {
515 reporter.error(`[atom-command] ${label} defected`, result.cause);
516 }
517 } else if (options.reportFailure ?? true) {
518 reporter.warn(`[atom-command] ${label} failed`, result.cause);
519 }
521​
522export async function settlePromise<A>(
523 execute: () => Promise<A>,
524): Promise<AtomCommandResult<A, never>> {
525 try {
526 return AsyncResult.success(await execute());
527 } catch (defect) {
528 return AsyncResult.failure(Cause.die(defect));
529 }
531​
532/** Where a query's answer is persisted, so an action's reply can be saved where a read would be. */
533export const queryPersistenceKey = (label: string, input: unknown): string =>
534 JSON.stringify([label, input]);
535​
536function environmentRpcKey<Input>(target: {
537 readonly environmentId: EnvironmentIdType;
538 readonly input: Input;
539}): string {
540 return JSON.stringify([target.environmentId, target.input]);
542​
543function parseEnvironmentRpcKey<Input>(key: string): {
544 readonly environmentId: EnvironmentIdType;
545 readonly input: Input;
546} {
547 const decoded = JSON.parse(key) as [EnvironmentIdType, Input];
548 return {
549 environmentId: EnvironmentId.make(decoded[0]),
550 input: decoded[1],
551 };
553​
554function runInEnvironment<A, E, R>(
555 environmentId: EnvironmentIdType,
556 effect: Effect.Effect<A, E, R>,
557): Effect.Effect<
558 A,
559 E | EnvironmentRegistry.EnvironmentNotRegisteredError,
560 EnvironmentRegistry.EnvironmentRegistry | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
561> {
562 return EnvironmentRegistry.EnvironmentRegistry.pipe(
563 Effect.flatMap((registry) => registry.run(environmentId, effect)),
564 );
566​
567/**
568 * `Atom.makeRefreshOnSignal` subscribes to the signal, so a query that outlives its view on an
569 * idle TTL still re-runs on every change. Reading the signal as a dependency instead lets the
570 * registry re-run a mounted query right away and only mark an idle one stale, which then
571 * refreshes on its next read.
572 */
573const refreshOnSignalWhileRead =
574 <V>(signal: Atom.Atom<unknown>, isFinal: (value: V) => boolean) =>
575 <A extends V>(self: Atom.Atom<A>): Atom.Atom<A> => {
576 // The signal value each registry's data was read under. Held outside the node because the
577 // registry can sweep this node while `self` keeps the data, and the rebuilt node must still
578 // see a change it missed.
579 const readUnder = new WeakMap<AtomRegistry.AtomRegistry, unknown>();
580 return Atom.transform(
581 self,
582 (get) => {
583 const current = get(signal);
584 get.subscribe(self, (value) => get.setSelf(value));
585 const changed =
586 readUnder.has(get.registry) && !Object.is(readUnder.get(get.registry), current);
587 readUnder.set(get.registry, current);
588 if (changed && !isFinal(get.once(self))) get.refresh(self);
589 return get.once(self);
590 },
591 { initialValueTarget: self },
592 );
593 };
594​
595const refreshEveryUntilFinal =
596 <V>(intervalMs: number, isFinal: (value: V) => boolean) =>
597 <A extends V>(self: Atom.Atom<A>): Atom.Atom<A> =>
598 Atom.transform(
599 self,
600 (get) => {
601 const value = get(self);
602 if (!isFinal(value)) {
603 // @effect-diagnostics-next-line globalTimers:off - Mirrors `Atom.withRefresh`, outside an Effect runtime.
604 const handle = setTimeout(() => get.refresh(self), intervalMs);
605 get.addFinalizer(() => clearTimeout(handle));
606 }
607 return value;
608 },
609 { initialValueTarget: self },
610 );
611​
612const isStale = (result: AsyncResult.AsyncResult<unknown, unknown>, staleTimeMs: number) => {
613 if (result.waiting) return false;
614 const success =
615 result._tag === "Failure" ? Option.getOrUndefined(result.previousSuccess) : result;
616 if (success?._tag !== "Success") return result._tag === "Failure";
617 // @effect-diagnostics-next-line globalDate:off - `AsyncResult` timestamps come from `Date.now`.
618 return Date.now() - success.timestamp >= staleTimeMs;
619};
620​
621/**
622 * Stale-while-revalidate on every mount. `Atom.swr` checks only when its node builds, which an idle
623 * TTL skips on a remount; this layer has no TTL (a transform drops it) while `self` keeps the cache.
624 * It reads `self` as a dependency, not a subscription, so `self` goes idle with its last reader.
625 */
626export const revalidateOnMount =
627 (staleTimeMs: number) =>
628 <A, E>(
629 self: Atom.Atom<AsyncResult.AsyncResult<A, E>>,
630 ): Atom.Atom<AsyncResult.AsyncResult<A, E>> =>
631 Atom.transform(
632 self,
633 (get) => {
634 const current = get(self);
635 if (Option.isNone(get.self()) && isStale(current, staleTimeMs)) {
636 let active = true;
637 get.addFinalizer(() => {
638 active = false;
639 });
640 // Deferred out of the build, which runs while React renders. A plain read drops this
641 // node before the task runs, so only a mount refetches.
642 get.registry.schedulerAsync.makeDispatcher().scheduleTask(() => {
643 if (active && isStale(get.once(self), staleTimeMs)) get.refresh(self);
644 }, 0);
645 }
646 return current;
647 },
648 { initialValueTarget: self },
649 );
650​
651/**
652 * A query result's data alone. A refetch always publishes a new result (a new
653 * timestamp, `waiting` on and off), while equal data keeps its identity, so a
654 * reader of only this skips the refetches that changed nothing.
655 */
656export const selectEnvironmentQueryData = <A, E>(result: AsyncResult.AsyncResult<A, E>): A | null =>
657 AsyncResult.getOrElse(result, () => null);
658​
659type EnvironmentConnection = readonly [
660 SupervisorConnectionState,
661 Option.Option<RpcSession.RpcSession>,
662];
663​
664const connectionAtomsByRuntime = new WeakMap<
665 object,
666 (
667 environmentId: EnvironmentIdType,
668 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentConnection | null>>
669>();
670​
671/**
672 * One connection atom per environment for every query on a runtime, so a reader of the session
673 * generation and a query it re-runs see the same connection change at once.
674 */
675function environmentConnectionAtoms<R, ER>(
676 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
677) {
678 const existing = connectionAtomsByRuntime.get(runtime);
679 if (existing !== undefined) return existing;
680 const family = Atom.family((environmentId: EnvironmentIdType) =>
681 runtime.atom(
682 followStreamInEnvironment(
683 environmentId,
684 Stream.unwrap(
685 EnvironmentSupervisor.EnvironmentSupervisor.pipe(
686 Effect.map((supervisor) =>
687 SubscriptionRef.changes(supervisor.state).pipe(
688 Stream.zipLatest(SubscriptionRef.changes(supervisor.session)),
689 ),
690 ),
691 ),
692 ),
693 ),
694 { initialValue: null },
695 ),
696 ) as (
697 environmentId: EnvironmentIdType,
698 ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentConnection | null>>;
699 connectionAtomsByRuntime.set(runtime, family);
700 return family;
702​
703export function environmentConnectionAtom<R, ER>(
704 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
705 environmentId: EnvironmentIdType,
706) {
707 return environmentConnectionAtoms(runtime)(environmentId);
709​
710const sessionGenerationAtomsByRuntime = new WeakMap<
711 object,
712 (environmentId: EnvironmentIdType) => Atom.Atom<number>
713>();
714​
715/**
716 * Counts established sessions; it changes only when a new one comes up, so failed one-shot reads
717 * can watch it to run again. Keyed on the session object because the supervisor's `generation`
718 * restarts when the registry installs a new supervisor (re-pairing, route edits).
719 */
720export function environmentSessionGenerationAtom<R, ER>(
721 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
722 environmentId: EnvironmentIdType,
723): Atom.Atom<number> {
724 let family = sessionGenerationAtomsByRuntime.get(runtime);
725 if (family === undefined) {
726 const connectionAtom = environmentConnectionAtoms(runtime);
727 const sessionsSeen = Atom.family((id: EnvironmentIdType) =>
728 Atom.make(
729 (get): { readonly session: RpcSession.RpcSession | null; readonly count: number } => {
730 const previous = Option.getOrElse(
731 get.self<{ readonly session: RpcSession.RpcSession | null; readonly count: number }>(),
732 () => ({ session: null, count: 0 }),
733 );
734 const connection = AsyncResult.getOrElse(get(connectionAtom(id)), () => null);
735 if (connection === null || connection[0].phase !== "connected") return previous;
736 const session = Option.getOrNull(connection[1]);
737 return session === null || session === previous.session
738 ? previous
739 : { session, count: previous.count + 1 };
740 },
741 ),
742 );
743 family = Atom.family((id: EnvironmentIdType) =>
744 Atom.make((get) => get(sessionsSeen(id)).count).pipe(
745 Atom.withLabel(`environment-session-generation:${id}`),
746 ),
747 );
748 sessionGenerationAtomsByRuntime.set(runtime, family);
749 }
750 return family(environmentId);
752​
753export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
754 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
755 options: EnvironmentQueryAtomOptions<
756 Input,
757 A,
758 E,
759 | EnvironmentSupervisor.EnvironmentSupervisor
760 | EnvironmentRegistry.EnvironmentRegistry
761 | AtomRegistry.AtomRegistry
762 | R
763 >,
764): (
765 target: { readonly environmentId: EnvironmentIdType; readonly input: Input },
766 mountScope?: string,
767) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
768 const connectionAtom = environmentConnectionAtoms(runtime);
769 // `Atom.family` holds members weakly and the mounted layer has no TTL, so each member lives
770 // as long as its cache: keyed weakly, this lets both go once the cache's TTL ends.
771 const cacheFamily = Atom.family((key: string) => {
772 const target = parseEnvironmentRpcKey<Input>(key);
773 const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
774 const queryAtom = runtime
775 .atom<
776 A,
777 | E
778 | ConnectionAttemptError
779 | EnvironmentRegistry.EnvironmentNotRegisteredError
780 | EnvironmentRpcUnavailableError
781 >((get) => {
782 const connection = AsyncResult.getOrElse(
783 get(connectionAtom(target.environmentId)),
784 () => null,
785 );
786 // A refetch that returns equal content keeps the previous value's
787 // references, so readers of the data skip re-rendering on idle polls.
788 const share = (value: A): A =>
789 reuseUnchanged(
790 Option.getOrUndefined(
791 Option.flatMap(get.self<AsyncResult.AsyncResult<A, unknown>>(), AsyncResult.value),
792 ),
793 value,
794 );
795 const emit = (value: A) =>
796 Effect.sync(() => get.setSelf(AsyncResult.success(share(value), { waiting: true }))).pipe(
797 // A value set while the atom builds wins over the build's own
798 // result, so a query that then settled synchronously would stay
799 // waiting forever. Suspend on a promise (`yieldNow` is drained
800 // inside the build) so the settled result arrives asynchronously.
801 Effect.andThen(Effect.promise(() => Promise.resolve())),
802 );
803 const execute = (): Effect.Effect<
804 A,
805 | E
806 | ConnectionAttemptError
807 | EnvironmentRegistry.EnvironmentNotRegisteredError
808 | EnvironmentRpcUnavailableError,
809 | EnvironmentRegistry.EnvironmentRegistry
810 | AtomRegistry.AtomRegistry
811 | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
812 > => {
813 if (connection === null) return Effect.never;
814 const [connectionState, session] = connection;
815 switch (connectionState.phase) {
816 case "connected":
817 return Option.isSome(session)
818 ? runInEnvironment(
819 target.environmentId,
820 options
821 .execute(
822 target.input,
823 emit,
824 Option.flatMap(
825 get.self<AsyncResult.AsyncResult<A, unknown>>(),
826 AsyncResult.value,
827 ),
828 )
829 .pipe(pendingOnceSessionReplaced(session.value)),
830 )
831 : Effect.never;
832 case "connecting":
833 case "backoff":
834 // A retry can take minutes. A query with an answer keeps showing it while it
835 // waits; one with nothing to show reports the failure the retry is recovering
836 // from, so its reader stops loading, and re-runs when the connection settles.
837 return connectionState.lastFailure !== null &&
838 Option.isNone(
839 Option.flatMap(
840 get.self<AsyncResult.AsyncResult<A, unknown>>(),
841 AsyncResult.value,
842 ),
843 )
844 ? Effect.fail(connectionState.lastFailure)
845 : Effect.never;
846 case "available":
847 case "offline":
848 case "blocked":
849 if (connectionState.lastFailure !== null) {
850 return Effect.fail(connectionState.lastFailure);
851 }
852 return Effect.fail(
853 new EnvironmentRpcUnavailableError({
854 environmentId: target.environmentId,
855 ...translatableMessage(
856 connectionState.phase === "offline"
857 ? msg("Environment {environmentId} is offline.", {
858 environmentId: target.environmentId,
859 })
860 : connectionState.phase === "blocked"
861 ? msg("Environment {environmentId} is blocked.", {
862 environmentId: target.environmentId,
863 })
864 : msg("Environment {environmentId} is not connected.", {
865 environmentId: target.environmentId,
866 }),
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 | 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 };