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