The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Context from "effect/Context"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as Layer from "effect/Layer"; |
| 4 | import type * as Schedule from "effect/Schedule"; |
| 5 | import type * as Aggregate from "./Aggregate.ts"; |
| 6 | import type * as Event from "./Event.ts"; |
| 7 | import type * as Key from "./Key.ts"; |
| 8 | import type * as View from "./View.ts"; |
| 9 | |
| 10 | /** One source, or several. */ |
| 11 | export type From = View.Source | ReadonlyArray<View.Source>; |
| 12 | /** The sources of a `from`. */ |
| 13 | export type SourcesOf<F> = F extends ReadonlyArray<infer S> ? S : F; |
| 14 | |
| 15 | /** |
| 16 | * What a policy receives for each event it subscribes to. |
| 17 | */ |
| 18 | export interface Trigger<F, E, Key extends Key.Any = View.SourceKey<SourcesOf<F>>> { |
| 19 | /** The key the event was routed to: the source instance, unless the policy declares `key`. */ |
| 20 | readonly key: Key.RefOf<Key>; |
| 21 | /** The route named in `keyOf` that brought it here, if any. */ |
| 22 | readonly route: string | undefined; |
| 23 | /** The aggregate or view instance the event came from (a view key's value for a Schema-keyed view). */ |
| 24 | readonly source: Key.RefOf<View.SourceKey<SourcesOf<F>>>; |
| 25 | /** The event. */ |
| 26 | readonly event: E; |
| 27 | /** The event's envelope. */ |
| 28 | readonly envelope: Aggregate.Envelope<Key.IdOf<View.SourceKey<SourcesOf<F>>>>; |
| 29 | /** For a view source: the view's state after the event. */ |
| 30 | readonly state: View.SourceState<SourcesOf<F>>; |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * How a policy's Layer tunes it. These are variants: they change how it runs, |
| 35 | * never what it means. |
| 36 | */ |
| 37 | export interface Options { |
| 38 | /** Retry a failed run on this schedule before leaving it to the platform's redelivery. */ |
| 39 | readonly retry?: Schedule.Schedule<unknown, unknown>; |
| 40 | } |
| 41 | |
| 42 | /** |
| 43 | * A policy's handler. It runs after the triggering event commits, at least |
| 44 | * once, in order per source instance. Every failure must be handled: send a |
| 45 | * command or ignore it. It requires nothing: resolve aggregate clients, Ports |
| 46 | * and views while building it, in `toLayer`. |
| 47 | */ |
| 48 | export type Handler<T> = (trigger: T) => Effect.Effect<void>; |
| 49 | |
| 50 | /** |
| 51 | * Structural constraint satisfied by every policy class. |
| 52 | */ |
| 53 | export interface Any extends Context.Key<unknown, unknown> { |
| 54 | readonly kind: "Policy"; |
| 55 | readonly policyName: string; |
| 56 | readonly definition: { |
| 57 | readonly from: From; |
| 58 | readonly key?: Key.Any; |
| 59 | readonly keyOf?: { readonly [key: string]: unknown }; |
| 60 | readonly on: ReadonlyArray<Event.Any>; |
| 61 | }; |
| 62 | } |
| 63 | |
| 64 | /** The declared `key` (an optional field), or the source's key when there is none. */ |
| 65 | type KeyOfDefinition<D> = D extends { readonly key?: infer K } |
| 66 | ? Exclude<K, undefined> extends infer Declared extends Key.Any |
| 67 | ? [Declared] extends [never] |
| 68 | ? SourceKeyOfDefinition<D> |
| 69 | : Declared |
| 70 | : SourceKeyOfDefinition<D> |
| 71 | : SourceKeyOfDefinition<D>; |
| 72 | type SourceKeyOfDefinition<D> = D extends { readonly from: infer F } |
| 73 | ? View.SourceKey<SourcesOf<F>> |
| 74 | : never; |
| 75 | |
| 76 | /** The trigger type of a policy class. */ |
| 77 | export type TriggerOf<P extends Any> = Trigger< |
| 78 | P["definition"]["from"], |
| 79 | Aggregate.InstanceOf<P["definition"]["on"][number]>, |
| 80 | KeyOfDefinition<P["definition"]> |
| 81 | >; |
| 82 | |
| 83 | type AsList<F> = F extends ReadonlyArray<View.Source> ? F : readonly [F]; |
| 84 | |
| 85 | /** |
| 86 | * The pure definition of a policy: its invariants. |
| 87 | */ |
| 88 | export interface Definition< |
| 89 | F extends From, |
| 90 | On extends ReadonlyArray<Event.Any>, |
| 91 | Key extends Key.Any | undefined, |
| 92 | > { |
| 93 | /** The aggregate or view, or several, whose events it reacts to. */ |
| 94 | readonly from: F; |
| 95 | /** |
| 96 | * What partitions it: an aggregate, whose refs are its keys, or a string |
| 97 | * Schema, whose values are. Triggers for one key run in order, one at a |
| 98 | * time. Defaults to the source instance. |
| 99 | */ |
| 100 | readonly key?: Key; |
| 101 | /** Which key each trigger goes to, by event tag or source name (like a view's `keyOf`). */ |
| 102 | readonly keyOf?: Key extends Key.Any |
| 103 | ? { |
| 104 | readonly [K in View.HandlerKey<AsList<F>>]?: View.Routed< |
| 105 | View.KeyFn<Key, View.InputFor<AsList<F>, K>> |
| 106 | >; |
| 107 | } |
| 108 | : never; |
| 109 | /** The events it reacts to. */ |
| 110 | readonly on: On; |
| 111 | } |
| 112 | |
| 113 | /** The requirement identifier of a policy class. */ |
| 114 | export type Identifier<P extends Any> = P extends Context.Key<infer I, unknown> ? I : never; |
| 115 | |
| 116 | /** |
| 117 | * Type-level identity of a policy in an Effect's requirements. |
| 118 | */ |
| 119 | export interface PolicyKey<Name extends string> { |
| 120 | readonly "~alchemy/Domain/Policy": Name; |
| 121 | } |
| 122 | |
| 123 | /** |
| 124 | * "Whenever this happens, do that": one of the business's standing rules. On |
| 125 | * an event from an aggregate or a view, it decides what to do next and acts by |
| 126 | * sending commands and calling external systems. Policies run shortly after the |
| 127 | * event, never in the same step, so use them only for eventually consistent |
| 128 | * work. Delivery is at least once; the commands a policy sends get ids |
| 129 | * derived from the event, so a second run sends the same commands. |
| 130 | * |
| 131 | * ### Reacting to an aggregate |
| 132 | * **Example:** Open an account for every new customer |
| 133 | * ```typescript |
| 134 | * import * as Domain from "@alchemy.run/domain"; |
| 135 | * import * as Effect from "effect/Effect"; |
| 136 | * import { Account, AccountId, OpenAccount } from "./Account.ts"; |
| 137 | * import { Customer, CustomerRegistered } from "./Customer.ts"; |
| 138 | * |
| 139 | * export class MainAccountProvisioning extends Domain.Policy("MainAccountProvisioning", { |
| 140 | * from: Customer, |
| 141 | * on: [CustomerRegistered], |
| 142 | * }) {} |
| 143 | * |
| 144 | * export const MainAccountProvisioningLive = MainAccountProvisioning.toLayer( |
| 145 | * Effect.gen(function* () { |
| 146 | * const accounts = yield* Account; |
| 147 | * return Effect.fn(function* ({ source }) { |
| 148 | * yield* accounts |
| 149 | * .send(AccountId.make(`${source.id}-main`), new OpenAccount({ owner: source.id })) |
| 150 | * .pipe(Effect.catchTag("AlreadyOpen", () => Effect.void)); |
| 151 | * }); |
| 152 | * }), |
| 153 | * ); |
| 154 | * ``` |
| 155 | * |
| 156 | * ### Calling an external system |
| 157 | * **Example:** Score risky withdrawals |
| 158 | * ```typescript |
| 159 | * import * as Domain from "@alchemy.run/domain"; |
| 160 | * import * as Effect from "effect/Effect"; |
| 161 | * import { Account, MoneyWithdrawn } from "./Account.ts"; |
| 162 | * import { FraudCheck } from "./FraudCheck.ts"; |
| 163 | * |
| 164 | * export class FraudReview extends Domain.Policy("FraudReview", { |
| 165 | * from: Account, |
| 166 | * on: [MoneyWithdrawn], |
| 167 | * }) {} |
| 168 | * |
| 169 | * export const FraudReviewLive = FraudReview.toLayer( |
| 170 | * Effect.gen(function* () { |
| 171 | * const fraud = yield* FraudCheck; |
| 172 | * return Effect.fn(function* ({ source, event }) { |
| 173 | * const { risk } = yield* fraud.score({ accountId: source.id, amount: event.amount }); |
| 174 | * yield* Effect.log(`risk ${risk} for ${source.id}`); |
| 175 | * }); |
| 176 | * }), |
| 177 | * ); |
| 178 | * ``` |
| 179 | * |
| 180 | * @primitive |
| 181 | */ |
| 182 | export const make = < |
| 183 | const Name extends string, |
| 184 | const F extends From, |
| 185 | const On extends ReadonlyArray<Event.Any>, |
| 186 | Key extends Key.Any | undefined = undefined, |
| 187 | >( |
| 188 | name: Name, |
| 189 | definition: Definition<F, On, Key>, |
| 190 | ): PolicyClass<Name, F, On, Key extends Key.Any ? Key : View.SourceKey<SourcesOf<F>>> => { |
| 191 | const Tag = Context.Service<PolicyKey<Name>, Handler<unknown>>()(`alchemy/Domain/Policy/${name}`); |
| 192 | return class extends Tag { |
| 193 | static readonly kind = "Policy" as const; |
| 194 | static readonly policyName: Name = name; |
| 195 | static readonly definition = definition; |
| 196 | static toLayer<Self extends Any, E, R>( |
| 197 | this: Self, |
| 198 | build: Effect.Effect<Handler<TriggerOf<Self>>, E, R>, |
| 199 | options: Options = {}, |
| 200 | ): Layer.Layer<Identifier<Self>, E, R> { |
| 201 | const retry = options.retry; |
| 202 | return Layer.effect( |
| 203 | this as unknown as Context.Key<Identifier<Self>, Handler<TriggerOf<Self>>>, |
| 204 | retry |
| 205 | ? Effect.map( |
| 206 | build, |
| 207 | (handle): Handler<TriggerOf<Self>> => |
| 208 | (trigger) => |
| 209 | handle(trigger).pipe( |
| 210 | Effect.catchDefect((defect) => Effect.fail(defect)), |
| 211 | Effect.retry(retry), |
| 212 | Effect.orDie, |
| 213 | ), |
| 214 | ) |
| 215 | : build, |
| 216 | ); |
| 217 | } |
| 218 | } as unknown as PolicyClass< |
| 219 | Name, |
| 220 | F, |
| 221 | On, |
| 222 | Key extends Key.Any ? Key : View.SourceKey<SourcesOf<F>> |
| 223 | >; |
| 224 | }; |
| 225 | |
| 226 | /** |
| 227 | * The class type returned by {@link make}. |
| 228 | */ |
| 229 | export interface PolicyClass< |
| 230 | Name extends string, |
| 231 | F extends From, |
| 232 | On extends ReadonlyArray<Event.Any>, |
| 233 | Key extends Key.Any, |
| 234 | > extends Context.ServiceClass< |
| 235 | PolicyKey<Name>, |
| 236 | string, |
| 237 | Handler<Trigger<F, Aggregate.InstanceOf<On[number]>, Key>> |
| 238 | > { |
| 239 | readonly kind: "Policy"; |
| 240 | readonly policyName: Name; |
| 241 | readonly definition: { |
| 242 | readonly from: F; |
| 243 | readonly key?: Key; |
| 244 | readonly keyOf?: { readonly [key: string]: unknown }; |
| 245 | readonly on: On; |
| 246 | }; |
| 247 | /** |
| 248 | * Implement the policy. The construction Effect runs once, resolving every |
| 249 | * service the handler uses (aggregate clients, views, Ports); the handler |
| 250 | * itself requires nothing. `options` tune how it runs, such as retries. |
| 251 | */ |
| 252 | toLayer<Self extends Any, E, R>( |
| 253 | this: Self, |
| 254 | build: Effect.Effect<Handler<TriggerOf<Self>>, E, R>, |
| 255 | options?: Options, |
| 256 | ): Layer.Layer<Identifier<Self>, E, R>; |
| 257 | } |