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