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 DateTime from "effect/DateTime"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Metric from "effect/Metric"; |
| 5 | import * as Option from "effect/Option"; |
| 6 | import * as Redacted from "effect/Redacted"; |
| 7 | import * as Schema from "effect/Schema"; |
| 8 | import * as Tracer from "effect/Tracer"; |
| 9 | |
| 10 | /** |
| 11 | * Span attributes a declaration adds for its values: a command's input, an |
| 12 | * event, a rejection. Nothing from a payload is recorded unless you return |
| 13 | * it here, and a `Redacted` value you return is recorded as `<redacted>`. |
| 14 | */ |
| 15 | export type Attributes<V> = (value: V) => Readonly<Record<string, unknown>>; |
| 16 | |
| 17 | /** |
| 18 | * How a hosted model records telemetry. Tuning, not meaning, so it lives on |
| 19 | * the Layer: `Bank.layer(handlers, { telemetry: { views: false } })`. |
| 20 | */ |
| 21 | export interface Options { |
| 22 | /** |
| 23 | * Trace every view applying an event. Views apply every event they fold, |
| 24 | * so this is the busiest span. |
| 25 | * @default true |
| 26 | */ |
| 27 | readonly views?: boolean; |
| 28 | } |
| 29 | |
| 30 | /** @internal */ |
| 31 | export interface Resolved { |
| 32 | readonly views: boolean; |
| 33 | } |
| 34 | |
| 35 | /** @internal */ |
| 36 | export const resolve = (options: Options | undefined): Resolved => ({ |
| 37 | views: options?.views ?? true, |
| 38 | }); |
| 39 | |
| 40 | /** A span's identity, stored with what it caused so later work can continue or link to it. @internal */ |
| 41 | export const TraceJson = Schema.Struct({ |
| 42 | traceId: Schema.String, |
| 43 | spanId: Schema.String, |
| 44 | sampled: Schema.Boolean, |
| 45 | }); |
| 46 | export type TraceJson = typeof TraceJson.Type; |
| 47 | |
| 48 | /** The current span, as JSON, if any. @internal */ |
| 49 | export const currentTrace: Effect.Effect<TraceJson | undefined> = Effect.currentParentSpan.pipe( |
| 50 | Effect.map((span): TraceJson => ({ |
| 51 | traceId: span.traceId, |
| 52 | spanId: span.spanId, |
| 53 | sampled: span.sampled, |
| 54 | })), |
| 55 | Effect.orElseSucceed(() => undefined), |
| 56 | ); |
| 57 | |
| 58 | /** A stored trace, as a parent or link target. @internal */ |
| 59 | export const spanOf = (trace: TraceJson): Tracer.ExternalSpan => |
| 60 | Tracer.externalSpan({ traceId: trace.traceId, spanId: trace.spanId, sampled: trace.sampled }); |
| 61 | |
| 62 | /** |
| 63 | * The flow work belongs to: the id of the first command in a chain of |
| 64 | * commands, events and reactions. Policies and sagas provide it, so every |
| 65 | * command they send carries it on. |
| 66 | * |
| 67 | * @internal |
| 68 | */ |
| 69 | export class Correlation extends Context.Service<Correlation, { readonly id: string }>()( |
| 70 | "alchemy/Domain/Correlation", |
| 71 | ) {} |
| 72 | |
| 73 | /** The correlation id for a new command: the one it was caused by, else its own id. @internal */ |
| 74 | export const correlationFor = (commandId: string): Effect.Effect<string> => |
| 75 | Effect.map(Effect.serviceOption(Correlation), (c) => (Option.isSome(c) ? c.value.id : commandId)); |
| 76 | |
| 77 | const MAX_STRING = 256; |
| 78 | const MAX_ITEMS = 20; |
| 79 | const MAX_DEPTH = 4; |
| 80 | |
| 81 | /** Flatten a decoded value into span attributes. `Redacted` values never appear. */ |
| 82 | const flatten = (out: Record<string, unknown>, key: string, value: unknown, depth: number) => { |
| 83 | if (value === undefined) return; |
| 84 | if (Redacted.isRedacted(value)) { |
| 85 | out[key] = "<redacted>"; |
| 86 | } else if (value === null || typeof value === "boolean" || typeof value === "number") { |
| 87 | out[key] = value; |
| 88 | } else if (typeof value === "string") { |
| 89 | out[key] = value.length > MAX_STRING ? `${value.slice(0, MAX_STRING)}…` : value; |
| 90 | } else if (typeof value === "bigint") { |
| 91 | out[key] = value.toString(); |
| 92 | } else if (DateTime.isDateTime(value)) { |
| 93 | out[key] = DateTime.formatIso(value); |
| 94 | } else if (value instanceof Date) { |
| 95 | out[key] = value.toISOString(); |
| 96 | } else if (value instanceof Uint8Array) { |
| 97 | out[key] = `<${value.byteLength} bytes>`; |
| 98 | } else if (depth >= MAX_DEPTH) { |
| 99 | out[key] = "<nested>"; |
| 100 | } else if (Array.isArray(value)) { |
| 101 | out[`${key}.length`] = value.length; |
| 102 | value.slice(0, MAX_ITEMS).forEach((item, i) => flatten(out, `${key}.${i}`, item, depth + 1)); |
| 103 | } else if (typeof value === "object") { |
| 104 | for (const [field, inner] of Object.entries(value)) { |
| 105 | if (field === "_tag") continue; |
| 106 | flatten(out, `${key}.${field}`, inner, depth + 1); |
| 107 | } |
| 108 | } |
| 109 | }; |
| 110 | |
| 111 | /** |
| 112 | * The attributes a declaration adds for one of its values, if it declares |
| 113 | * `attributes`. Values are flattened, capped, and `Redacted` values hidden. |
| 114 | * |
| 115 | * @internal |
| 116 | */ |
| 117 | export const attributesOf = (cls: unknown, value: unknown): Record<string, unknown> => { |
| 118 | const attributes = (cls as { readonly attributes?: Attributes<any> } | undefined)?.attributes; |
| 119 | if (attributes === undefined) return {}; |
| 120 | const out: Record<string, unknown> = {}; |
| 121 | for (const [key, inner] of Object.entries(attributes(value))) flatten(out, key, inner, 0); |
| 122 | return out; |
| 123 | }; |
| 124 | |
| 125 | // ---------------------------------------------------------------- metrics |
| 126 | |
| 127 | const ms = Metric.exponentialBoundaries({ start: 1, factor: 2, count: 22 }); |
| 128 | |
| 129 | /** Commands handled, by `domain.aggregate`, `domain.command` and `domain.outcome`. */ |
| 130 | export const commands = Metric.counter("domain.commands", { |
| 131 | description: "Commands handled by aggregates", |
| 132 | incremental: true, |
| 133 | }); |
| 134 | /** How long an aggregate took to decide and commit a command, in milliseconds. */ |
| 135 | export const commandDuration = Metric.histogram("domain.command.duration", { |
| 136 | description: "Milliseconds to decide and commit a command", |
| 137 | boundaries: ms, |
| 138 | }); |
| 139 | /** Events committed, by `domain.aggregate` and `domain.event`. */ |
| 140 | export const events = Metric.counter("domain.events", { |
| 141 | description: "Events committed by aggregates", |
| 142 | incremental: true, |
| 143 | }); |
| 144 | /** Milliseconds from an event's commit to a reaction handling it, by `domain.consumer`. */ |
| 145 | export const lag = Metric.histogram("domain.lag", { |
| 146 | description: "Milliseconds from commit to handling, per consumer", |
| 147 | boundaries: ms, |
| 148 | }); |
| 149 | /** Reaction runs, by `domain.kind`, `domain.consumer` and `domain.outcome`. */ |
| 150 | export const runs = Metric.counter("domain.runs", { |
| 151 | description: "Policy, view, projection and saga runs", |
| 152 | incremental: true, |
| 153 | }); |
| 154 | /** Inputs per projection batch. */ |
| 155 | export const batchSize = Metric.histogram("domain.projection.batch_size", { |
| 156 | description: "Inputs per projection batch", |
| 157 | boundaries: Metric.exponentialBoundaries({ start: 1, factor: 2, count: 12 }), |
| 158 | }); |
| 159 | /** External system calls, by `domain.system`, `domain.operation` and `domain.outcome`. */ |
| 160 | export const externalCalls = Metric.counter("domain.external.calls", { |
| 161 | description: "Calls to external systems", |
| 162 | incremental: true, |
| 163 | }); |
| 164 | |
| 165 | /** @internal */ |
| 166 | export const record = <M extends Metric.Metric<number, any>>( |
| 167 | metric: M, |
| 168 | attributes: Record<string, string>, |
| 169 | value = 1, |
| 170 | ) => Metric.update(Metric.withAttributes(metric, attributes), value); |
| 171 | |
| 172 | /** The outcome of an exit, for metrics and spans: ok, the failure's tag, or defect. @internal */ |
| 173 | export const outcomeOf = (failure: unknown): string => |
| 174 | failure === undefined |
| 175 | ? "ok" |
| 176 | : typeof failure === "object" && failure !== null && "_tag" in failure |
| 177 | ? String((failure as { readonly _tag: unknown })._tag) |
| 178 | : "defect"; |