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): (
717 target: { readonly environmentId: EnvironmentIdType; readonly input: Input },
718 mountScope?: string,
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 cacheFamily = Atom.family((key: string) => {
724 const target = parseEnvironmentRpcKey<Input>(key);
725 const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
726 const queryAtom = runtime
727 .atom<
728 A,
729 | E
730 | ConnectionAttemptError
731 | EnvironmentRegistry.EnvironmentNotRegisteredError
732 | EnvironmentRpcUnavailableError
733 >((get) => {
734 const connection = AsyncResult.getOrElse(
735 get(connectionAtom(target.environmentId)),
736 () => null,
737 );
738 // A refetch that returns equal content keeps the previous value's
739 // references, so readers of the data skip re-rendering on idle polls.
740 const share = (value: A): A =>
741 reuseUnchanged(
742 Option.getOrUndefined(
743 Option.flatMap(get.self<AsyncResult.AsyncResult<A, unknown>>(), AsyncResult.value),
744 ),
745 value,
746 );
747 const emit = (value: A) =>
748 Effect.sync(() => get.setSelf(AsyncResult.success(share(value), { waiting: true }))).pipe(
749 // A value set while the atom builds wins over the build's own
750 // result, so a query that then settled synchronously would stay
751 // waiting forever. Suspend on a promise (`yieldNow` is drained
752 // inside the build) so the settled result arrives asynchronously.
753 Effect.andThen(Effect.promise(() => Promise.resolve())),
754 );
755 const execute = (): Effect.Effect<
756 A,
757 | E
758 | ConnectionAttemptError
759 | EnvironmentRegistry.EnvironmentNotRegisteredError
760 | EnvironmentRpcUnavailableError,
761 | EnvironmentRegistry.EnvironmentRegistry
762 | AtomRegistry.AtomRegistry
763 | Exclude<R, EnvironmentSupervisor.EnvironmentSupervisor>
764 > => {
765 if (connection === null) return Effect.never;
766 const [connectionState, session] = connection;
767 switch (connectionState.phase) {
768 case "connected":
769 return Option.isSome(session)
770 ? runInEnvironment(
771 target.environmentId,
772 options
773 .execute(
774 target.input,
775 emit,
776 Option.flatMap(
777 get.self<AsyncResult.AsyncResult<A, unknown>>(),
778 AsyncResult.value,
779 ),
780 )
781 .pipe(pendingOnceSessionReplaced(session.value)),
782 )
783 : Effect.never;
784 case "connecting":
785 case "backoff":
786 // A retry can take minutes. A query with an answer keeps showing it while it
787 // waits; one with nothing to show reports the failure the retry is recovering
788 // from, so its reader stops loading, and re-runs when the connection settles.
789 return connectionState.lastFailure !== null &&
790 Option.isNone(
791 Option.flatMap(
792 get.self<AsyncResult.AsyncResult<A, unknown>>(),
793 AsyncResult.value,
794 ),
795 )
796 ? Effect.fail(connectionState.lastFailure)
797 : Effect.never;
798 case "available":
799 case "offline":
800 case "blocked":
801 if (connectionState.lastFailure !== null) {
802 return Effect.fail(connectionState.lastFailure);
803 }
804 return Effect.fail(
805 new EnvironmentRpcUnavailableError({
806 environmentId: target.environmentId,
807 ...translatableMessage(
808 connectionState.phase === "offline"
809 ? msg("Environment {environmentId} is offline.", {
810 environmentId: target.environmentId,
811 })
812 : connectionState.phase === "blocked"
813 ? msg("Environment {environmentId} is blocked.", {
814 environmentId: target.environmentId,
815 })
816 : msg("Environment {environmentId} is not connected.", {
817 environmentId: target.environmentId,
818 }),
819 ),
820 }),
821 );
822 }
823 };
824 const onAnswer = options.onAnswer;
825 const answer = () =>
826 onAnswer === undefined
827 ? execute().pipe(Effect.map(share))
828 : execute().pipe(
829 Effect.map(share),
830 Effect.tap((value) => onAnswer(target, value, get.registry)),
831 );
832 if (!options.persistence) return answer();
833 const persistence = options.persistence;
834 const cacheKey = queryPersistenceKey(options.label, target.input);
835 const previous = Option.flatMap(
836 get.self<AsyncResult.AsyncResult<A, unknown>>(),
837 AsyncResult.value,
838 );
839 return Effect.gen(function* () {
840 const cached = Option.isSome(previous)
841 ? previous
842 : yield* persistence.load(target.environmentId, cacheKey);
843 if (
844 Option.isSome(cached) &&
845 (connection === null || connection[0].phase !== "connected")
846 ) {
847 return cached.value;
848 }
849 if (Option.isNone(previous) && Option.isSome(cached)) yield* emit(cached.value);
850 // Readers must not wait on the disk: web saves one IndexedDB row per listed PR's stats.
851 // The save ends with the query, so a removed environment's cache stays cleared.
852 return yield* answer().pipe(
853 Effect.tap((value) =>
854 persistence.save(target.environmentId, cacheKey, value).pipe(Effect.forkScoped),
855 ),
856 );
857 });
858 })
859 .pipe(Atom.setIdleTTL(idleTtlMs));
860 const isFinal = (result: AsyncResult.AsyncResult<A, unknown>) =>
861 options.isFinal !== undefined && Option.exists(AsyncResult.value(result), options.isFinal);
862 const intervalQuery =
863 options.refreshIntervalMs === undefined
864 ? queryAtom
865 : queryAtom.pipe(refreshEveryUntilFinal(options.refreshIntervalMs, isFinal));
866 const refreshTrigger = options.refreshTrigger?.(target);
867 return (
868 refreshTrigger === undefined
869 ? intervalQuery
870 : intervalQuery.pipe(refreshOnSignalWhileRead(refreshTrigger, isFinal))
871 ).pipe(Atom.setIdleTTL(idleTtlMs));
872 });
873 type QueryAtom = ReturnType<typeof cacheFamily>;
874 const membersByCache = new WeakMap<QueryAtom, Map<string | undefined, QueryAtom>>();
875 return (target, mountScope) => {
876 const key = environmentRpcKey(target);
877 const cache = cacheFamily(key);
878 let members = membersByCache.get(cache);
879 if (members === undefined) {
880 members = new Map();
881 membersByCache.set(cache, members);
882 }
883 const existing = members.get(mountScope);
884 if (existing !== undefined) return existing;
885 const member = cache.pipe(
886 revalidateOnMount(options.staleTimeMs ?? 30_000),
887 Atom.withLabel(`${options.label}:${key}${mountScope === undefined ? "" : `:${mountScope}`}`),
888 );
889 members.set(mountScope, member);
890 return member;
891 };
892}
893
894export function createEnvironmentSubscriptionAtomFamily<R, ER, Input, A, E>(
895 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
896 options: EnvironmentSubscriptionAtomOptions<
897 Input,
898 A,
899 E,
900 EnvironmentSupervisor.EnvironmentSupervisor | R
901 >,
902) {
903 const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
904 const label = (key: string) =>
905 options.sensitiveInput
906 ? `${options.label}:${parseEnvironmentRpcKey<Input>(key).environmentId}`
907 : `${options.label}:${key}`;
908 const live = Atom.family((key: string) => {
909 const target = parseEnvironmentRpcKey<Input>(key);
910 return runtime
911 .atom(
912 Stream.suspend(() =>
913 followStreamInEnvironment(target.environmentId, options.subscribe(target.input)),
914 ).pipe(options.completeWhen ? Stream.takeUntil(options.completeWhen) : (stream) => stream),
915 )
916 .pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(label(key)));
917 });
918 const { completeWhen, completedTtlMs } = options;
919 if (completeWhen === undefined || completedTtlMs === undefined) {
920 return (target: { readonly environmentId: EnvironmentIdType; readonly input: Input }) =>
921 live(environmentRpcKey(target));
922 }
923 const completed = Atom.family((key: string) =>
924 Atom.make(Option.none<A>()).pipe(
925 Atom.setIdleTTL(completedTtlMs),
926 Atom.withLabel(`${label(key)}:completed`),
927 ),
928 );
929 // Reading `completed` first drops the live subscription once its value is final.
930 const family = Atom.family((key: string) =>
931 Atom.make((get) => {
932 const done = get(completed(key));
933 if (Option.isSome(done)) return AsyncResult.success(done.value);
934 const result = get(live(key));
935 if (AsyncResult.isSuccess(result) && !result.waiting && completeWhen(result.value)) {
936 get.set(completed(key), Option.some(result.value));
937 }
938 return result;
939 }).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(label(key))),
940 );
941 return (target: { readonly environmentId: EnvironmentIdType; readonly input: Input }) =>
942 family(environmentRpcKey(target));
943}
944
945export function createEnvironmentCommand<R, ER, Input, A, E>(
946 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
947 options: EnvironmentCommandAtomOptions<
948 Input,
949 A,
950 E,
951 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry | R
952 >,
953) {
954 return createRuntimeCommand(runtime, {
955 label: options.label,
956 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
957 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
958 execute: (target, registry) =>
959 runInEnvironment(
960 target.environmentId,
961 options.execute(target.input, registry, target.environmentId),
962 ),
963 });
964}
965
966export function createEnvironmentRpcQueryAtomFamily<
967 R,
968 ER,
969 TTag extends Exclude<EnvironmentUnaryRpcTag, ClientGuardedRpcTag>,
970>(
971 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
972 options: {
973 readonly label: string;
974 readonly tag: TTag;
975 readonly execute?: (
976 input: EnvironmentRpcInput<TTag>,
977 emit: (value: EnvironmentRpcSuccess<TTag>) => Effect.Effect<void>,
978 previous: Option.Option<EnvironmentRpcSuccess<TTag>>,
979 ) => Effect.Effect<
980 EnvironmentRpcSuccess<TTag>,
981 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
982 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry
983 >;
984 readonly persistence?: QueryPersistence<EnvironmentRpcSuccess<TTag>>;
985 readonly staleTimeMs?: number;
986 readonly idleTtlMs?: number;
987 readonly refreshIntervalMs?: number;
988 readonly refreshTrigger?: (target: {
989 readonly environmentId: EnvironmentIdType;
990 readonly input: EnvironmentRpcInput<TTag>;
991 }) => Atom.Atom<unknown> | undefined;
992 readonly isFinal?: (value: EnvironmentRpcSuccess<TTag>) => boolean;
993 readonly onAnswer?: QueryAnswerHandler<EnvironmentRpcInput<TTag>, EnvironmentRpcSuccess<TTag>>;
994 },
995) {
996 return createEnvironmentQueryAtomFamily(runtime, {
997 label: options.label,
998 ...(options.persistence === undefined ? {} : { persistence: options.persistence }),
999 ...(options.staleTimeMs === undefined ? {} : { staleTimeMs: options.staleTimeMs }),
1000 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
1001 ...(options.refreshIntervalMs === undefined
1002 ? {}
1003 : { refreshIntervalMs: options.refreshIntervalMs }),
1004 ...(options.refreshTrigger === undefined ? {} : { refreshTrigger: options.refreshTrigger }),
1005 ...(options.isFinal === undefined ? {} : { isFinal: options.isFinal }),
1006 ...(options.onAnswer === undefined ? {} : { onAnswer: options.onAnswer }),
1007 execute: (
1008 input: EnvironmentRpcInput<TTag>,
1009 emit: (value: EnvironmentRpcSuccess<TTag>) => Effect.Effect<void>,
1010 previous: Option.Option<EnvironmentRpcSuccess<TTag>>,
1011 ) => options.execute?.(input, emit, previous) ?? request(options.tag, input),
1012 });
1013}
1014
1015export function createEnvironmentRpcSubscriptionAtomFamily<
1016 R,
1017 ER,
1018 TTag extends EnvironmentSubscriptionRpcTag,
1019 B = EnvironmentRpcStreamValue<TTag>,
1020>(
1021 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
1022 options: {
1023 readonly label: string;
1024 readonly tag: TTag;
1025 readonly idleTtlMs?: number;
1026 readonly completeWhen?: (value: B) => boolean;
1027 readonly completedTtlMs?: number;
1028 readonly transform?: (
1029 stream: Stream.Stream<
1030 EnvironmentRpcStreamValue<TTag>,
1031 EnvironmentRpcStreamFailure<TTag>,
1032 EnvironmentSupervisor.EnvironmentSupervisor | R
1033 >,
1034 ) => Stream.Stream<
1035 B,
1036 EnvironmentRpcStreamFailure<TTag>,
1037 EnvironmentSupervisor.EnvironmentSupervisor | R
1038 >;
1039 },
1040) {
1041 return createEnvironmentSubscriptionAtomFamily(runtime, {
1042 label: options.label,
1043 ...(options.completeWhen === undefined ? {} : { completeWhen: options.completeWhen }),
1044 ...(options.completedTtlMs === undefined ? {} : { completedTtlMs: options.completedTtlMs }),
1045 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
1046 subscribe: (input: EnvironmentRpcInput<TTag>) => {
1047 const stream = subscribe(options.tag, input);
1048 return options.transform === undefined
1049 ? (stream as Stream.Stream<
1050 B,
1051 EnvironmentRpcStreamFailure<TTag>,
1052 EnvironmentSupervisor.EnvironmentSupervisor | R
1053 >)
1054 : options.transform(stream);
1055 },
1056 });
1057}
1058
1059export function createEnvironmentRpcCommand<
1060 R,
1061 ER,
1062 TTag extends EnvironmentUnaryRpcTag,
1063 Input extends EnvironmentRpcInput<TTag> = EnvironmentRpcInput<TTag>,
1064 Started = undefined,
1065>(
1066 runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,
1067 options: {
1068 readonly label: string;
1069 readonly tag: TTag;
1070 /** Runs once authorized, as the request starts; what it returns reaches `onSuccess`. */
1071 readonly onStart?: (
1072 target: {
1073 readonly environmentId: EnvironmentIdType;
1074 readonly input: NoInfer<Input>;
1075 },
1076 registry: AtomRegistry.AtomRegistry,
1077 ) => Started;
1078 readonly execute?: (
1079 input: Input,
1080 registry: AtomRegistry.AtomRegistry,
1081 environmentId: EnvironmentIdType,
1082 ) => Effect.Effect<
1083 EnvironmentRpcSuccess<TTag>,
1084 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
1085 EnvironmentSupervisor.EnvironmentSupervisor | EnvironmentRegistry.EnvironmentRegistry
1086 >;
1087 readonly scheduler?: AtomCommandScheduler;
1088 readonly concurrency?: AtomCommandConcurrency<{
1089 readonly environmentId: EnvironmentIdType;
1090 readonly input: NoInfer<Input>;
1091 }>;
1092 readonly onSuccess?: (
1093 target: {
1094 readonly environmentId: EnvironmentIdType;
1095 readonly input: NoInfer<Input>;
1096 },
1097 registry: AtomRegistry.AtomRegistry,
1098 result: EnvironmentRpcSuccess<TTag>,
1099 started: Started | undefined,
1100 ) => Effect.Effect<void, never, R>;
1101 readonly onSettled?: (
1102 target: {
1103 readonly environmentId: EnvironmentIdType;
1104 readonly input: NoInfer<Input>;
1105 },
1106 registry: AtomRegistry.AtomRegistry,
1107 ) => Effect.Effect<void, never, R>;
1108 },
1109) {
1110 const permissions = createCommandPermissions(runtime, options.tag);
1111 const command = createEnvironmentCommand(runtime, {
1112 label: options.label,
1113 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
1114 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
1115 execute: (input: Input, registry, environmentId) => {
1116 const target = {
1117 environmentId,
1118 input,
1119 };
1120 let started: Started | undefined;
1121 // Routing requires consent on the origin as well as the actual destination.
1122 // The transport check below deliberately checks the destination again.
1123 return permissions.authorize(registry, environmentId, input).pipe(
1124 Effect.andThen(() => {
1125 started = options.onStart?.(target, registry);
1126 return (
1127 options.execute?.(input, registry, environmentId) ?? requestGuarded(options.tag, input)
1128 );
1129 }),
1130 Effect.provideService(RpcPermissionGuard, {
1131 authorize: (id, method, payload) =>
1132 createCommandPermissions(runtime, method).authorize(registry, id, payload),
1133 }),
1134 Effect.tap(
1135 (result) => options.onSuccess?.(target, registry, result, started) ?? Effect.void,
1136 ),
1137 Effect.ensuring(options.onSettled?.(target, registry) ?? Effect.void),
1138 );
1139 },
1140 });
1141 return {
1142 ...command,
1143 requiredScopes: permissions.requiredScopes,
1144 permissionAtom: permissions.permissionAtom,
1145 };
1146}