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