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