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
486export function createEnvironmentQueryAtomFamily<R, ER, Input, A, E>(
487 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
488 options: EnvironmentQueryAtomOptions<
489 Input,
490 A,
491 E,
492 EnvironmentSupervisor | EnvironmentRegistry | AtomRegistry.AtomRegistry | R
493 >,
494): (target: {
495 readonly environmentId: EnvironmentIdType;
496 readonly input: Input;
497}) => Atom.Atom<AsyncResult.AsyncResult<A, E | ER | Error>> {
498 const connectionAtom = Atom.family((environmentId: EnvironmentIdType) =>
499 runtime.atom(
500 followStreamInEnvironment(
501 environmentId,
502 Stream.unwrap(
503 EnvironmentSupervisor.pipe(
504 Effect.map((supervisor) =>
505 SubscriptionRef.changes(supervisor.state).pipe(
506 Stream.zipLatest(SubscriptionRef.changes(supervisor.session)),
507 ),
508 ),
509 ),
510 ),
511 ),
512 { initialValue: null },
513 ),
514 );
515 const family = Atom.family((key: string) => {
516 const target = parseEnvironmentRpcKey<Input>(key);
517 const idleTtlMs = options.idleTtlMs ?? 5 * 60_000;
518 const queryAtom = runtime
519 .atom<
520 A,
521 E | ConnectionAttemptError | EnvironmentNotRegisteredError | EnvironmentRpcUnavailableError
522 >((get) => {
523 const connection = Option.getOrNull(
524 AsyncResult.value(get(connectionAtom(target.environmentId))),
525 );
526 if (connection === null) {
527 return Effect.never;
528 }
529 const [connectionState, session] = connection;
530 switch (connectionState.phase) {
531 case "connected":
532 return Option.isSome(session)
533 ? runInEnvironment(target.environmentId, options.execute(target.input))
534 : Effect.never;
535 case "connecting":
536 case "backoff":
537 return Effect.never;
538 case "available":
539 case "offline":
540 case "blocked":
541 if (connectionState.lastFailure !== null) {
542 return Effect.fail(connectionState.lastFailure);
543 }
544 return Effect.fail(
545 new EnvironmentRpcUnavailableError({
546 environmentId: target.environmentId,
547 message: `Environment ${target.environmentId} is ${
548 connectionState.phase === "available" ? "not connected" : connectionState.phase
549 }.`,
550 }),
551 );
552 }
553 })
554 .pipe(
555 Atom.swr({
556 staleTime: options.staleTimeMs ?? 30_000,
557 revalidateOnMount: true,
558 }),
559 Atom.setIdleTTL(idleTtlMs),
560 );
561 const intervalQuery =
562 options.refreshIntervalMs === undefined
563 ? queryAtom
564 : queryAtom.pipe(Atom.withRefresh(options.refreshIntervalMs));
565 const refreshTrigger = options.refreshTrigger?.(target);
566 return (
567 refreshTrigger === undefined
568 ? intervalQuery
569 : intervalQuery.pipe(Atom.makeRefreshOnSignal(refreshTrigger))
570 ).pipe(Atom.setIdleTTL(idleTtlMs), Atom.withLabel(`${options.label}:${key}`));
571 });
572 return (target) => family(environmentRpcKey(target));
573}
574
575export function createEnvironmentSubscriptionAtomFamily<R, ER, Input, A, E>(
576 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
577 options: EnvironmentSubscriptionAtomOptions<Input, A, E, EnvironmentSupervisor | R>,
578) {
579 const family = Atom.family((key: string) => {
580 const target = parseEnvironmentRpcKey<Input>(key);
581 return runtime
582 .atom(followStreamInEnvironment(target.environmentId, options.subscribe(target.input)))
583 .pipe(
584 Atom.setIdleTTL(options.idleTtlMs ?? 5 * 60_000),
585 Atom.withLabel(
586 options.sensitiveInput
587 ? `${options.label}:${target.environmentId}`
588 : `${options.label}:${key}`,
589 ),
590 );
591 });
592 return (target: { readonly environmentId: EnvironmentIdType; readonly input: Input }) =>
593 family(environmentRpcKey(target));
594}
595
596export function createEnvironmentCommand<R, ER, Input, A, E>(
597 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
598 options: EnvironmentCommandAtomOptions<
599 Input,
600 A,
601 E,
602 EnvironmentSupervisor | EnvironmentRegistry | R
603 >,
604) {
605 return createRuntimeCommand(runtime, {
606 label: options.label,
607 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
608 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
609 execute: (target, registry) =>
610 runInEnvironment(
611 target.environmentId,
612 options.execute(target.input, registry, target.environmentId),
613 ),
614 });
615}
616
617export function createEnvironmentRpcQueryAtomFamily<R, ER, TTag extends EnvironmentUnaryRpcTag>(
618 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
619 options: {
620 readonly label: string;
621 readonly tag: TTag;
622 readonly execute?: (
623 input: EnvironmentRpcInput<TTag>,
624 ) => Effect.Effect<
625 EnvironmentRpcSuccess<TTag>,
626 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
627 EnvironmentSupervisor | EnvironmentRegistry
628 >;
629 readonly staleTimeMs?: number;
630 readonly idleTtlMs?: number;
631 readonly refreshIntervalMs?: number;
632 readonly refreshTrigger?: (target: {
633 readonly environmentId: EnvironmentIdType;
634 readonly input: EnvironmentRpcInput<TTag>;
635 }) => Atom.Atom<unknown> | undefined;
636 },
637) {
638 return createEnvironmentQueryAtomFamily(runtime, {
639 label: options.label,
640 ...(options.staleTimeMs === undefined ? {} : { staleTimeMs: options.staleTimeMs }),
641 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
642 ...(options.refreshIntervalMs === undefined
643 ? {}
644 : { refreshIntervalMs: options.refreshIntervalMs }),
645 ...(options.refreshTrigger === undefined ? {} : { refreshTrigger: options.refreshTrigger }),
646 execute: (input: EnvironmentRpcInput<TTag>) =>
647 options.execute?.(input) ?? request(options.tag, input),
648 });
649}
650
651export function createEnvironmentRpcSubscriptionAtomFamily<
652 R,
653 ER,
654 TTag extends EnvironmentSubscriptionRpcTag,
655 B = EnvironmentRpcStreamValue<TTag>,
656>(
657 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
658 options: {
659 readonly label: string;
660 readonly tag: TTag;
661 readonly idleTtlMs?: number;
662 readonly transform?: (
663 stream: Stream.Stream<
664 EnvironmentRpcStreamValue<TTag>,
665 EnvironmentRpcStreamFailure<TTag>,
666 EnvironmentSupervisor | R
667 >,
668 ) => Stream.Stream<B, EnvironmentRpcStreamFailure<TTag>, EnvironmentSupervisor | R>;
669 },
670) {
671 return createEnvironmentSubscriptionAtomFamily(runtime, {
672 label: options.label,
673 ...(options.idleTtlMs === undefined ? {} : { idleTtlMs: options.idleTtlMs }),
674 subscribe: (input: EnvironmentRpcInput<TTag>) => {
675 const stream = subscribe(options.tag, input);
676 return options.transform === undefined
677 ? (stream as Stream.Stream<B, EnvironmentRpcStreamFailure<TTag>, EnvironmentSupervisor | R>)
678 : options.transform(stream);
679 },
680 });
681}
682
683export function createEnvironmentRpcCommand<R, ER, TTag extends EnvironmentUnaryRpcTag>(
684 runtime: Atom.AtomRuntime<EnvironmentRegistry | R, ER>,
685 options: {
686 readonly label: string;
687 readonly tag: TTag;
688 readonly execute?: (
689 input: EnvironmentRpcInput<TTag>,
690 ) => Effect.Effect<
691 EnvironmentRpcSuccess<TTag>,
692 EnvironmentRpcFailure<TTag> | EnvironmentRpcUnavailableError,
693 EnvironmentSupervisor | EnvironmentRegistry
694 >;
695 readonly scheduler?: AtomCommandScheduler;
696 readonly concurrency?: AtomCommandConcurrency<{
697 readonly environmentId: EnvironmentIdType;
698 readonly input: EnvironmentRpcInput<TTag>;
699 }>;
700 readonly onSuccess?: (
701 target: {
702 readonly environmentId: EnvironmentIdType;
703 readonly input: EnvironmentRpcInput<TTag>;
704 },
705 registry: AtomRegistry.AtomRegistry,
706 ) => Effect.Effect<void, never, R>;
707 readonly onSettled?: (
708 target: {
709 readonly environmentId: EnvironmentIdType;
710 readonly input: EnvironmentRpcInput<TTag>;
711 },
712 registry: AtomRegistry.AtomRegistry,
713 ) => Effect.Effect<void, never, R>;
714 },
715) {
716 return createEnvironmentCommand(runtime, {
717 label: options.label,
718 ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }),
719 ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }),
720 execute: (input: EnvironmentRpcInput<TTag>, registry, environmentId) => {
721 const target = {
722 environmentId,
723 input,
724 };
725 return (options.execute?.(input) ?? request(options.tag, input)).pipe(
726 Effect.tap(() => options.onSuccess?.(target, registry) ?? Effect.void),
727 Effect.ensuring(options.onSettled?.(target, registry) ?? Effect.void),
728 );
729 },
730 });
731}