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