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