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