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