@spellkave/agent-observability 0.0.0-bootstrap → 0.0.0-stage
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/package.json +4 -33
- package/LICENSE +0 -89
- package/src/correlation.ts +0 -84
- package/src/emit.ts +0 -231
- package/src/events.ts +0 -399
- package/src/index.ts +0 -13
- package/src/metrics.ts +0 -677
- package/src/node-memory.ts +0 -73
- package/src/node-metrics.ts +0 -36
- package/src/node-resource.ts +0 -92
- package/src/node-traces.ts +0 -27
- package/src/node.ts +0 -379
- package/src/otel.ts +0 -594
- package/src/reader.ts +0 -122
- package/src/traces.ts +0 -261
- package/src/world-table-event.ts +0 -52
package/src/metrics.ts
DELETED
|
@@ -1,677 +0,0 @@
|
|
|
1
|
-
// Dependency-free OTLP/HTTP metrics for WORLD ACTORS. Hosts own this exporter;
|
|
2
|
-
// browser-safe gameplay libraries receive only the structural port below.
|
|
3
|
-
import { CYCLE_WAKE_OUTCOMES, type CycleWakeOutcome } from "./events.ts";
|
|
4
|
-
import type { OtlpTransportSnapshot } from "./otel.ts";
|
|
5
|
-
|
|
6
|
-
export const OTEL_METRICS_SERVICE_NAME = "spellkave-world-actors";
|
|
7
|
-
|
|
8
|
-
export type WorldActorRequestStatus = "ok" | "error";
|
|
9
|
-
|
|
10
|
-
export interface HostMemorySample {
|
|
11
|
-
processRssBytes: number;
|
|
12
|
-
heapUsedBytes: number;
|
|
13
|
-
heapTotalBytes: number;
|
|
14
|
-
externalBytes: number;
|
|
15
|
-
arrayBuffersBytes: number;
|
|
16
|
-
cgroupCurrentBytes?: number;
|
|
17
|
-
cgroupPeakBytes?: number;
|
|
18
|
-
cgroupLimitBytes?: number;
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export interface WorkerMemorySample {
|
|
22
|
-
actorEntityKey: string;
|
|
23
|
-
heapUsedBytes: number;
|
|
24
|
-
heapTotalBytes?: number;
|
|
25
|
-
externalBytes?: number;
|
|
26
|
-
arrayBuffersBytes?: number;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
const HOST_MEMORY_METRICS = {
|
|
30
|
-
processRssBytes: "process_rss_bytes",
|
|
31
|
-
heapUsedBytes: "main_heap_used_bytes",
|
|
32
|
-
heapTotalBytes: "main_heap_total_bytes",
|
|
33
|
-
externalBytes: "main_external_bytes",
|
|
34
|
-
arrayBuffersBytes: "main_array_buffers_bytes",
|
|
35
|
-
cgroupCurrentBytes: "cgroup_current_bytes",
|
|
36
|
-
cgroupPeakBytes: "cgroup_peak_bytes",
|
|
37
|
-
cgroupLimitBytes: "cgroup_limit_bytes",
|
|
38
|
-
} as const;
|
|
39
|
-
|
|
40
|
-
export interface WorldActorMetrics {
|
|
41
|
-
recordRequest(input: {
|
|
42
|
-
toolName: string;
|
|
43
|
-
durationMs: number;
|
|
44
|
-
status: WorldActorRequestStatus;
|
|
45
|
-
}): void;
|
|
46
|
-
recordCycleFailure(input: {
|
|
47
|
-
step: string;
|
|
48
|
-
failureClass: string;
|
|
49
|
-
errorCode?: string;
|
|
50
|
-
retryCount: number;
|
|
51
|
-
/** Seat that failed. Admitted via SAFE_METRIC_ATTRIBUTE_KEYS. */
|
|
52
|
-
actorEntityKey?: string;
|
|
53
|
-
}): void;
|
|
54
|
-
/** One scheduled self-driven seat run and its fate (the `cycle_wake`
|
|
55
|
-
* event's bounded `outcome`). Counts, no actor attribute: the question it
|
|
56
|
-
* answers is host-wide ("how many wakes per tick ran vs. skipped"). */
|
|
57
|
-
recordCycleWake?(input: { outcome: CycleWakeOutcome }): void;
|
|
58
|
-
/** Aggregate cycle-duration sample (work-only; excludes concurrency-slot
|
|
59
|
-
* wait). Implementations MUST NOT export a per-cycle series — accumulate
|
|
60
|
-
* and ship on {@link flush}. */
|
|
61
|
-
recordCycleDuration?(input: { actorEntityKey: string; durationMs: number }): void;
|
|
62
|
-
/** Time spent waiting for `acquireCycleSlot`. Same actor-attribute
|
|
63
|
-
* discipline as {@link recordCycleDuration}. */
|
|
64
|
-
recordCycleQueueWait?(input: { actorEntityKey: string; durationMs: number }): void;
|
|
65
|
-
/** Host-wide in-flight cycle count. Accumulates max-in-window (not last
|
|
66
|
-
* sample) and ships as a gauge on flush. Optional queueDepth is the limiter
|
|
67
|
-
* waiter count — also max-in-window, host-wide, no actor attribute. */
|
|
68
|
-
recordOpenCycles?(input: { openCycles: number; queueDepth?: number }): void;
|
|
69
|
-
/** Unconditional metrics-exporter liveness. Call on a host heartbeat (npc-host
|
|
70
|
-
* sweep or session-daemon interval); shipped as a delta counter on flush even
|
|
71
|
-
* when nothing else happened. */
|
|
72
|
-
recordExporterHeartbeat?(): void;
|
|
73
|
-
/** Latest V8 isolate heap per seat worker. Shipped as a gauge on flush. */
|
|
74
|
-
recordWorkerHeap?(input: WorkerMemorySample): void;
|
|
75
|
-
/** Host-wide snapshot, without actor labels. Missing fields stay absent. */
|
|
76
|
-
recordHostMemory?(input: HostMemorySample): void;
|
|
77
|
-
/** A seat worker was respawned: a fresh V8 isolate and a full seat-graph
|
|
78
|
-
* compile. THE signal for the CPU-throttle storm of sk-jay0.6.15.12 —
|
|
79
|
-
* before this counter existed the only trace was a `console.error` line,
|
|
80
|
-
* which is why that bug sat open for two weeks and had to be measured by
|
|
81
|
-
* grepping pod logs. Watch the TREND: a rate that does not decay after
|
|
82
|
-
* boot is the storm. */
|
|
83
|
-
recordSeatRespawn?(input: { reason: SeatRecoveryReason }): void;
|
|
84
|
-
/** A seat reopened its own session instead of being respawned
|
|
85
|
-
* (sk-jay0.6.15.56.10). `success` rising while `seat_respawns_total` stays
|
|
86
|
-
* flat is the fix working. */
|
|
87
|
-
recordSeatReconnect?(input: { outcome: "success" | "failure" }): void;
|
|
88
|
-
/** A seat's cycle-slot request waited longer than the warning threshold
|
|
89
|
-
* without a grant (sk-jay0.6.15.56.16.12.4). Watch the TREND: a counter
|
|
90
|
-
* that keeps rising after boot means the host cycle gate is starved. */
|
|
91
|
-
recordCycleSlotWaitExceeded?(input: { actorEntityKey: string }): void;
|
|
92
|
-
flush(): Promise<void>;
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
export interface OtlpHttpMetricsOptions {
|
|
96
|
-
/** Pull the local log transport state on flush, without logging recursively. */
|
|
97
|
-
logTransportSnapshot?: () => OtlpTransportSnapshot;
|
|
98
|
-
endpoint: string;
|
|
99
|
-
serviceName?: string;
|
|
100
|
-
headers?: Record<string, string>;
|
|
101
|
-
resourceAttributes?: Record<string, unknown>;
|
|
102
|
-
fetchFn?: typeof fetch;
|
|
103
|
-
now?: () => number;
|
|
104
|
-
onError?: (error: unknown) => void;
|
|
105
|
-
maxPendingExports?: number;
|
|
106
|
-
/** Abort each export request after this deadline; default 10 seconds, the
|
|
107
|
-
* same bound the OTLP log sink uses. Without it a request that never
|
|
108
|
-
* settles holds its admission slot for the life of the process, and once
|
|
109
|
-
* `maxPendingExports` of them hang every later export is dropped as
|
|
110
|
-
* "queue is saturated" (sk-jay0.6.15.56.21). */
|
|
111
|
-
requestTimeoutMs?: number;
|
|
112
|
-
/** Exact registry-owned values permitted to create metric series. */
|
|
113
|
-
allowedToolNames?: readonly string[];
|
|
114
|
-
allowedCycleSteps?: readonly string[];
|
|
115
|
-
allowedErrorCodes?: readonly string[];
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
type Scalar = string | number | boolean;
|
|
119
|
-
|
|
120
|
-
const SAFE_RESOURCE_ATTRIBUTE_KEYS = new Set([
|
|
121
|
-
"service.name",
|
|
122
|
-
"service.namespace",
|
|
123
|
-
// Deployed revision (`SPELLKAVE_IMAGE_TAG`, sk-0m4.120.13) — a tag, never a path.
|
|
124
|
-
"service.version",
|
|
125
|
-
"service.instance.id",
|
|
126
|
-
// sk-jay0.6.38.13: old semconv key — the collector hygiene key AND the live
|
|
127
|
-
// column (see `world_actor_traces`/`world_actor_run_events` for the
|
|
128
|
-
// per-signal column names this maps to).
|
|
129
|
-
"deployment.environment",
|
|
130
|
-
"deployment.environment.name",
|
|
131
|
-
"spellkave.world_slug",
|
|
132
|
-
]);
|
|
133
|
-
|
|
134
|
-
const SAFE_METRIC_ATTRIBUTE_KEYS = new Set([
|
|
135
|
-
"spellkave.world_slug",
|
|
136
|
-
"spellkave.tool_name",
|
|
137
|
-
"spellkave.status",
|
|
138
|
-
"spellkave.step",
|
|
139
|
-
"spellkave.failure_class",
|
|
140
|
-
"spellkave.error_code",
|
|
141
|
-
"spellkave.actor_entity_key",
|
|
142
|
-
"spellkave.recovery_reason",
|
|
143
|
-
]);
|
|
144
|
-
|
|
145
|
-
const DURATION_BUCKETS_MS = [10, 25, 50, 100, 250, 500, 1_000, 2_500, 5_000];
|
|
146
|
-
const FAILURE_CLASSES = new Set([
|
|
147
|
-
"authoring_rejected",
|
|
148
|
-
"apply_rejected",
|
|
149
|
-
"SeatContractError",
|
|
150
|
-
"Error",
|
|
151
|
-
"TypeError",
|
|
152
|
-
"unknown",
|
|
153
|
-
]);
|
|
154
|
-
|
|
155
|
-
function failureClassDimension(value: string): string {
|
|
156
|
-
return FAILURE_CLASSES.has(value) ? value : "other";
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/** Why a seat worker was respawned. CLOSED SET — the raw reason strings carry
|
|
160
|
-
* durations ("no update for 12345ms exceeds 5000"), so shipping them as an
|
|
161
|
-
* attribute would be unbounded cardinality. */
|
|
162
|
-
const SEAT_RECOVERY_REASONS = new Set(["transport_down", "open_cycle", "stale", "other"]);
|
|
163
|
-
|
|
164
|
-
export type SeatRecoveryReason = "transport_down" | "open_cycle" | "stale" | "other";
|
|
165
|
-
|
|
166
|
-
function seatRecoveryReasonDimension(value: string): string {
|
|
167
|
-
return SEAT_RECOVERY_REASONS.has(value) ? value : "other";
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
function scalar(value: unknown): Scalar | undefined {
|
|
171
|
-
if (typeof value === "string") return value.slice(0, 128);
|
|
172
|
-
if (typeof value === "boolean") return value;
|
|
173
|
-
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
174
|
-
return undefined;
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
function otlpAttributes(
|
|
178
|
-
values: Readonly<Record<string, unknown>>,
|
|
179
|
-
allowed: ReadonlySet<string>,
|
|
180
|
-
): Array<Record<string, unknown>> {
|
|
181
|
-
const out: Array<Record<string, unknown>> = [];
|
|
182
|
-
for (const [key, raw] of Object.entries(values)) {
|
|
183
|
-
if (!allowed.has(key)) continue;
|
|
184
|
-
const value = scalar(raw);
|
|
185
|
-
if (value === undefined) continue;
|
|
186
|
-
if (typeof value === "boolean") out.push({ key, value: { boolValue: value } });
|
|
187
|
-
else if (typeof value === "number") {
|
|
188
|
-
out.push({
|
|
189
|
-
key,
|
|
190
|
-
value: Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value },
|
|
191
|
-
});
|
|
192
|
-
} else out.push({ key, value: { stringValue: value } });
|
|
193
|
-
}
|
|
194
|
-
return out;
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
function unixNano(now: () => number): string {
|
|
198
|
-
return String(Math.round(now() * 1_000_000));
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
function metricsUrl(endpoint: string): string {
|
|
202
|
-
const base = endpoint.trim().replace(/\/+$/, "");
|
|
203
|
-
return base.endsWith("/v1/metrics") ? base : `${base}/v1/metrics`;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
function countBuckets(value: number): string[] {
|
|
207
|
-
const counts = DURATION_BUCKETS_MS.map(() => 0);
|
|
208
|
-
let placed = false;
|
|
209
|
-
for (let index = 0; index < DURATION_BUCKETS_MS.length; index += 1) {
|
|
210
|
-
if (!placed && value <= (DURATION_BUCKETS_MS[index] ?? Number.POSITIVE_INFINITY)) {
|
|
211
|
-
counts[index] = 1;
|
|
212
|
-
placed = true;
|
|
213
|
-
}
|
|
214
|
-
}
|
|
215
|
-
return [...counts, placed ? 0 : 1].map(String);
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
interface HistogramAcc {
|
|
219
|
-
count: number;
|
|
220
|
-
sum: number;
|
|
221
|
-
min: number;
|
|
222
|
-
max: number;
|
|
223
|
-
buckets: number[];
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
function addHistogramSample(
|
|
227
|
-
map: Map<string, HistogramAcc>,
|
|
228
|
-
actorEntityKey: string,
|
|
229
|
-
durationMs: number,
|
|
230
|
-
): void {
|
|
231
|
-
const key = actorEntityKey.slice(0, 128);
|
|
232
|
-
const safeDuration = Number.isFinite(durationMs) ? Math.max(0, durationMs) : 0;
|
|
233
|
-
const existing = map.get(key);
|
|
234
|
-
if (existing === undefined) {
|
|
235
|
-
const buckets = DURATION_BUCKETS_MS.map(() => 0);
|
|
236
|
-
let placed = false;
|
|
237
|
-
for (let index = 0; index < DURATION_BUCKETS_MS.length; index += 1) {
|
|
238
|
-
if (!placed && safeDuration <= (DURATION_BUCKETS_MS[index] ?? Number.POSITIVE_INFINITY)) {
|
|
239
|
-
buckets[index] = 1;
|
|
240
|
-
placed = true;
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
map.set(key, {
|
|
244
|
-
count: 1,
|
|
245
|
-
sum: safeDuration,
|
|
246
|
-
min: safeDuration,
|
|
247
|
-
max: safeDuration,
|
|
248
|
-
buckets: [...buckets, placed ? 0 : 1],
|
|
249
|
-
});
|
|
250
|
-
return;
|
|
251
|
-
}
|
|
252
|
-
existing.count += 1;
|
|
253
|
-
existing.sum += safeDuration;
|
|
254
|
-
existing.min = Math.min(existing.min, safeDuration);
|
|
255
|
-
existing.max = Math.max(existing.max, safeDuration);
|
|
256
|
-
let placed = false;
|
|
257
|
-
for (let index = 0; index < DURATION_BUCKETS_MS.length; index += 1) {
|
|
258
|
-
if (!placed && safeDuration <= (DURATION_BUCKETS_MS[index] ?? Number.POSITIVE_INFINITY)) {
|
|
259
|
-
existing.buckets[index] = (existing.buckets[index] ?? 0) + 1;
|
|
260
|
-
placed = true;
|
|
261
|
-
}
|
|
262
|
-
}
|
|
263
|
-
if (!placed) {
|
|
264
|
-
const overflow = existing.buckets.length - 1;
|
|
265
|
-
existing.buckets[overflow] = (existing.buckets[overflow] ?? 0) + 1;
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
|
|
269
|
-
export function createOtlpHttpMetrics(options: OtlpHttpMetricsOptions): WorldActorMetrics {
|
|
270
|
-
const now = options.now ?? Date.now;
|
|
271
|
-
const doFetch = options.fetchFn ?? globalThis.fetch.bind(globalThis);
|
|
272
|
-
const pending = new Set<Promise<void>>();
|
|
273
|
-
const configuredMaxPending = options.maxPendingExports ?? 64;
|
|
274
|
-
const maxPendingExports = Number.isFinite(configuredMaxPending)
|
|
275
|
-
? Math.max(1, Math.trunc(configuredMaxPending))
|
|
276
|
-
: 64;
|
|
277
|
-
let saturationReported = false;
|
|
278
|
-
const configuredTimeout = options.requestTimeoutMs ?? 10_000;
|
|
279
|
-
const requestTimeoutMs = Number.isFinite(configuredTimeout)
|
|
280
|
-
? Math.max(1, Math.trunc(configuredTimeout))
|
|
281
|
-
: 10_000;
|
|
282
|
-
const resourceAttributes = otlpAttributes(
|
|
283
|
-
{
|
|
284
|
-
"service.name": options.serviceName ?? OTEL_METRICS_SERVICE_NAME,
|
|
285
|
-
"service.namespace": "spellkave",
|
|
286
|
-
...options.resourceAttributes,
|
|
287
|
-
},
|
|
288
|
-
SAFE_RESOURCE_ATTRIBUTE_KEYS,
|
|
289
|
-
);
|
|
290
|
-
const stableMetricAttributes = {
|
|
291
|
-
"spellkave.world_slug": options.resourceAttributes?.["spellkave.world_slug"],
|
|
292
|
-
};
|
|
293
|
-
const allowedToolNames = new Set(options.allowedToolNames ?? []);
|
|
294
|
-
const allowedCycleSteps = new Set(options.allowedCycleSteps ?? []);
|
|
295
|
-
const allowedErrorCodes = new Set(options.allowedErrorCodes ?? []);
|
|
296
|
-
const cycleDurationBySeat = new Map<string, HistogramAcc>();
|
|
297
|
-
const cycleQueueWaitBySeat = new Map<string, HistogramAcc>();
|
|
298
|
-
const workerHeapBySeat = new Map<string, { sample: WorkerMemorySample; atMs: number }>();
|
|
299
|
-
let hostMemory: HostMemorySample | undefined;
|
|
300
|
-
let openCycles = 0;
|
|
301
|
-
let openCyclesMax = 0;
|
|
302
|
-
let openCyclesRecorded = false;
|
|
303
|
-
let queueDepth = 0;
|
|
304
|
-
let queueDepthMax = 0;
|
|
305
|
-
let queueDepthRecorded = false;
|
|
306
|
-
let exporterHeartbeats = 0;
|
|
307
|
-
const reportError = (error: unknown): void => {
|
|
308
|
-
try {
|
|
309
|
-
options.onError?.(error);
|
|
310
|
-
} catch {
|
|
311
|
-
// An observability callback is observability too; keep it non-fatal.
|
|
312
|
-
}
|
|
313
|
-
};
|
|
314
|
-
|
|
315
|
-
function ship(metrics: ReadonlyArray<Record<string, unknown>>): void {
|
|
316
|
-
if (pending.size >= maxPendingExports) {
|
|
317
|
-
if (!saturationReported) {
|
|
318
|
-
saturationReported = true;
|
|
319
|
-
reportError(new Error("OTLP metrics export queue is saturated"));
|
|
320
|
-
}
|
|
321
|
-
return;
|
|
322
|
-
}
|
|
323
|
-
let request: Promise<Response>;
|
|
324
|
-
const controller = new AbortController();
|
|
325
|
-
const timer = setTimeout(() => controller.abort(), requestTimeoutMs);
|
|
326
|
-
timer.unref?.();
|
|
327
|
-
try {
|
|
328
|
-
const headers = new Headers(options.headers);
|
|
329
|
-
headers.set("content-type", "application/json");
|
|
330
|
-
request = doFetch(metricsUrl(options.endpoint), {
|
|
331
|
-
method: "POST",
|
|
332
|
-
headers,
|
|
333
|
-
signal: controller.signal,
|
|
334
|
-
body: JSON.stringify({
|
|
335
|
-
resourceMetrics: [
|
|
336
|
-
{
|
|
337
|
-
resource: { attributes: resourceAttributes },
|
|
338
|
-
scopeMetrics: [
|
|
339
|
-
{
|
|
340
|
-
scope: { name: "@spellkave/agent-observability" },
|
|
341
|
-
metrics,
|
|
342
|
-
},
|
|
343
|
-
],
|
|
344
|
-
},
|
|
345
|
-
],
|
|
346
|
-
}),
|
|
347
|
-
});
|
|
348
|
-
} catch (error) {
|
|
349
|
-
clearTimeout(timer);
|
|
350
|
-
reportError(error);
|
|
351
|
-
return;
|
|
352
|
-
}
|
|
353
|
-
let tracked: Promise<void>;
|
|
354
|
-
tracked = request
|
|
355
|
-
.then((response) => {
|
|
356
|
-
if (!response.ok) {
|
|
357
|
-
throw new Error(`OTLP metrics export failed: ${response.status} ${response.statusText}`);
|
|
358
|
-
}
|
|
359
|
-
})
|
|
360
|
-
.catch((error) => reportError(error))
|
|
361
|
-
.finally(() => {
|
|
362
|
-
clearTimeout(timer);
|
|
363
|
-
pending.delete(tracked);
|
|
364
|
-
if (pending.size < maxPendingExports) saturationReported = false;
|
|
365
|
-
});
|
|
366
|
-
pending.add(tracked);
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
function sumMetric(
|
|
370
|
-
name: string,
|
|
371
|
-
attributes: Readonly<Record<string, unknown>>,
|
|
372
|
-
value = 1,
|
|
373
|
-
): Record<string, unknown> {
|
|
374
|
-
return {
|
|
375
|
-
name,
|
|
376
|
-
unit: "{event}",
|
|
377
|
-
sum: {
|
|
378
|
-
aggregationTemporality: 1,
|
|
379
|
-
isMonotonic: true,
|
|
380
|
-
dataPoints: [
|
|
381
|
-
{
|
|
382
|
-
attributes: otlpAttributes(attributes, SAFE_METRIC_ATTRIBUTE_KEYS),
|
|
383
|
-
timeUnixNano: unixNano(now),
|
|
384
|
-
asInt: String(Math.max(0, Math.trunc(value))),
|
|
385
|
-
},
|
|
386
|
-
],
|
|
387
|
-
},
|
|
388
|
-
};
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
return {
|
|
392
|
-
recordRequest({ toolName, durationMs, status }) {
|
|
393
|
-
const safeDuration = Number.isFinite(durationMs) ? Math.max(0, durationMs) : 0;
|
|
394
|
-
const attributes = {
|
|
395
|
-
...stableMetricAttributes,
|
|
396
|
-
"spellkave.tool_name": allowedToolNames.has(toolName) ? toolName : "other",
|
|
397
|
-
"spellkave.status": status === "ok" ? "ok" : "error",
|
|
398
|
-
};
|
|
399
|
-
ship([
|
|
400
|
-
sumMetric("spellkave.world_actor.requests_total", attributes),
|
|
401
|
-
{
|
|
402
|
-
name: "spellkave.world_actor.request_duration",
|
|
403
|
-
unit: "ms",
|
|
404
|
-
histogram: {
|
|
405
|
-
aggregationTemporality: 1,
|
|
406
|
-
dataPoints: [
|
|
407
|
-
{
|
|
408
|
-
attributes: otlpAttributes(attributes, SAFE_METRIC_ATTRIBUTE_KEYS),
|
|
409
|
-
timeUnixNano: unixNano(now),
|
|
410
|
-
count: "1",
|
|
411
|
-
sum: safeDuration,
|
|
412
|
-
explicitBounds: DURATION_BUCKETS_MS,
|
|
413
|
-
bucketCounts: countBuckets(safeDuration),
|
|
414
|
-
min: safeDuration,
|
|
415
|
-
max: safeDuration,
|
|
416
|
-
},
|
|
417
|
-
],
|
|
418
|
-
},
|
|
419
|
-
},
|
|
420
|
-
]);
|
|
421
|
-
},
|
|
422
|
-
recordSeatRespawn({ reason }) {
|
|
423
|
-
ship([
|
|
424
|
-
sumMetric("spellkave.world_actor.seat_respawns_total", {
|
|
425
|
-
...stableMetricAttributes,
|
|
426
|
-
"spellkave.recovery_reason": seatRecoveryReasonDimension(reason),
|
|
427
|
-
}),
|
|
428
|
-
]);
|
|
429
|
-
},
|
|
430
|
-
recordSeatReconnect({ outcome }) {
|
|
431
|
-
ship([
|
|
432
|
-
sumMetric("spellkave.world_actor.seat_reconnects_total", {
|
|
433
|
-
...stableMetricAttributes,
|
|
434
|
-
"spellkave.status": outcome === "success" ? "success" : "failure",
|
|
435
|
-
}),
|
|
436
|
-
]);
|
|
437
|
-
},
|
|
438
|
-
recordCycleSlotWaitExceeded(_input: { actorEntityKey: string }) {
|
|
439
|
-
ship([
|
|
440
|
-
sumMetric("spellkave.world_actor.cycle_slot_wait_exceeded_total", stableMetricAttributes),
|
|
441
|
-
]);
|
|
442
|
-
},
|
|
443
|
-
recordCycleFailure({ step, failureClass, errorCode, retryCount, actorEntityKey }) {
|
|
444
|
-
const safeErrorCode =
|
|
445
|
-
errorCode !== undefined && allowedErrorCodes.has(errorCode) ? errorCode : undefined;
|
|
446
|
-
const attributes = {
|
|
447
|
-
...stableMetricAttributes,
|
|
448
|
-
"spellkave.step": allowedCycleSteps.has(step) ? step : "other",
|
|
449
|
-
"spellkave.failure_class": failureClassDimension(failureClass),
|
|
450
|
-
...(safeErrorCode === undefined ? {} : { "spellkave.error_code": safeErrorCode }),
|
|
451
|
-
...(actorEntityKey === undefined || actorEntityKey === ""
|
|
452
|
-
? {}
|
|
453
|
-
: { "spellkave.actor_entity_key": actorEntityKey.slice(0, 128) }),
|
|
454
|
-
};
|
|
455
|
-
ship([
|
|
456
|
-
sumMetric("spellkave.world_actor.cycle_failures_total", attributes),
|
|
457
|
-
...(retryCount > 0
|
|
458
|
-
? [sumMetric("spellkave.world_actor.cycle_retries_total", attributes)]
|
|
459
|
-
: []),
|
|
460
|
-
]);
|
|
461
|
-
},
|
|
462
|
-
recordCycleWake({ outcome }) {
|
|
463
|
-
ship([
|
|
464
|
-
sumMetric("spellkave.world_actor.cycle_wakes_total", {
|
|
465
|
-
...stableMetricAttributes,
|
|
466
|
-
"spellkave.wake_outcome": CYCLE_WAKE_OUTCOMES.includes(outcome) ? outcome : "other",
|
|
467
|
-
}),
|
|
468
|
-
]);
|
|
469
|
-
},
|
|
470
|
-
recordCycleDuration({ actorEntityKey, durationMs }) {
|
|
471
|
-
addHistogramSample(cycleDurationBySeat, actorEntityKey, durationMs);
|
|
472
|
-
},
|
|
473
|
-
recordCycleQueueWait({ actorEntityKey, durationMs }) {
|
|
474
|
-
addHistogramSample(cycleQueueWaitBySeat, actorEntityKey, durationMs);
|
|
475
|
-
},
|
|
476
|
-
recordOpenCycles({ openCycles: next, queueDepth: nextQueue }) {
|
|
477
|
-
openCycles = Number.isFinite(next) ? Math.max(0, Math.trunc(next)) : 0;
|
|
478
|
-
openCyclesMax = Math.max(openCyclesMax, openCycles);
|
|
479
|
-
openCyclesRecorded = true;
|
|
480
|
-
if (nextQueue === undefined) return;
|
|
481
|
-
queueDepth = Number.isFinite(nextQueue) ? Math.max(0, Math.trunc(nextQueue)) : 0;
|
|
482
|
-
queueDepthMax = Math.max(queueDepthMax, queueDepth);
|
|
483
|
-
queueDepthRecorded = true;
|
|
484
|
-
},
|
|
485
|
-
recordExporterHeartbeat() {
|
|
486
|
-
exporterHeartbeats += 1;
|
|
487
|
-
},
|
|
488
|
-
recordWorkerHeap(sample) {
|
|
489
|
-
workerHeapBySeat.set(sample.actorEntityKey.slice(0, 128), {
|
|
490
|
-
sample: { ...sample },
|
|
491
|
-
atMs: now(),
|
|
492
|
-
});
|
|
493
|
-
},
|
|
494
|
-
recordHostMemory(sample) {
|
|
495
|
-
hostMemory = { ...sample };
|
|
496
|
-
},
|
|
497
|
-
async flush() {
|
|
498
|
-
const cycleMetrics: Record<string, unknown>[] = [];
|
|
499
|
-
try {
|
|
500
|
-
const snapshot = options.logTransportSnapshot?.();
|
|
501
|
-
if (snapshot !== undefined) {
|
|
502
|
-
for (const key of ["pending", "dropped", "timedOut", "failed"] as const) {
|
|
503
|
-
const value = snapshot[key];
|
|
504
|
-
if (!Number.isSafeInteger(value) || value < 0) continue;
|
|
505
|
-
const suffix = key === "timedOut" ? "timed_out" : key;
|
|
506
|
-
cycleMetrics.push({
|
|
507
|
-
name: `spellkave.world_actor.log_export_${suffix}`,
|
|
508
|
-
unit: "{request}",
|
|
509
|
-
gauge: {
|
|
510
|
-
dataPoints: [
|
|
511
|
-
{
|
|
512
|
-
attributes: otlpAttributes(stableMetricAttributes, SAFE_METRIC_ATTRIBUTE_KEYS),
|
|
513
|
-
timeUnixNano: unixNano(now),
|
|
514
|
-
asInt: String(value),
|
|
515
|
-
},
|
|
516
|
-
],
|
|
517
|
-
},
|
|
518
|
-
});
|
|
519
|
-
}
|
|
520
|
-
}
|
|
521
|
-
} catch (error) {
|
|
522
|
-
reportError(error);
|
|
523
|
-
}
|
|
524
|
-
if (hostMemory !== undefined) {
|
|
525
|
-
for (const [key, name] of Object.entries(HOST_MEMORY_METRICS)) {
|
|
526
|
-
const value = hostMemory[key as keyof HostMemorySample];
|
|
527
|
-
if (value === undefined || !Number.isSafeInteger(value) || value < 0) continue;
|
|
528
|
-
cycleMetrics.push({
|
|
529
|
-
name: `spellkave.world_actor.${name}`,
|
|
530
|
-
unit: "By",
|
|
531
|
-
gauge: {
|
|
532
|
-
dataPoints: [
|
|
533
|
-
{
|
|
534
|
-
attributes: otlpAttributes(stableMetricAttributes, SAFE_METRIC_ATTRIBUTE_KEYS),
|
|
535
|
-
timeUnixNano: unixNano(now),
|
|
536
|
-
asInt: String(value),
|
|
537
|
-
},
|
|
538
|
-
],
|
|
539
|
-
},
|
|
540
|
-
});
|
|
541
|
-
}
|
|
542
|
-
hostMemory = undefined;
|
|
543
|
-
}
|
|
544
|
-
if (exporterHeartbeats > 0) {
|
|
545
|
-
cycleMetrics.push(
|
|
546
|
-
sumMetric(
|
|
547
|
-
"spellkave.world_actor.exporter_heartbeats_total",
|
|
548
|
-
stableMetricAttributes,
|
|
549
|
-
exporterHeartbeats,
|
|
550
|
-
),
|
|
551
|
-
);
|
|
552
|
-
exporterHeartbeats = 0;
|
|
553
|
-
}
|
|
554
|
-
for (const [actorEntityKey, acc] of cycleDurationBySeat) {
|
|
555
|
-
cycleMetrics.push({
|
|
556
|
-
name: "spellkave.world_actor.cycle_duration",
|
|
557
|
-
unit: "ms",
|
|
558
|
-
histogram: {
|
|
559
|
-
aggregationTemporality: 1,
|
|
560
|
-
dataPoints: [
|
|
561
|
-
{
|
|
562
|
-
attributes: otlpAttributes(
|
|
563
|
-
{
|
|
564
|
-
...stableMetricAttributes,
|
|
565
|
-
"spellkave.actor_entity_key": actorEntityKey,
|
|
566
|
-
},
|
|
567
|
-
SAFE_METRIC_ATTRIBUTE_KEYS,
|
|
568
|
-
),
|
|
569
|
-
timeUnixNano: unixNano(now),
|
|
570
|
-
count: String(acc.count),
|
|
571
|
-
sum: acc.sum,
|
|
572
|
-
explicitBounds: DURATION_BUCKETS_MS,
|
|
573
|
-
bucketCounts: acc.buckets.map(String),
|
|
574
|
-
min: acc.min,
|
|
575
|
-
max: acc.max,
|
|
576
|
-
},
|
|
577
|
-
],
|
|
578
|
-
},
|
|
579
|
-
});
|
|
580
|
-
}
|
|
581
|
-
cycleDurationBySeat.clear();
|
|
582
|
-
for (const [actorEntityKey, acc] of cycleQueueWaitBySeat) {
|
|
583
|
-
cycleMetrics.push({
|
|
584
|
-
name: "spellkave.world_actor.cycle_queue_wait",
|
|
585
|
-
unit: "ms",
|
|
586
|
-
histogram: {
|
|
587
|
-
aggregationTemporality: 1,
|
|
588
|
-
dataPoints: [
|
|
589
|
-
{
|
|
590
|
-
attributes: otlpAttributes(
|
|
591
|
-
{
|
|
592
|
-
...stableMetricAttributes,
|
|
593
|
-
"spellkave.actor_entity_key": actorEntityKey,
|
|
594
|
-
},
|
|
595
|
-
SAFE_METRIC_ATTRIBUTE_KEYS,
|
|
596
|
-
),
|
|
597
|
-
timeUnixNano: unixNano(now),
|
|
598
|
-
count: String(acc.count),
|
|
599
|
-
sum: acc.sum,
|
|
600
|
-
explicitBounds: DURATION_BUCKETS_MS,
|
|
601
|
-
bucketCounts: acc.buckets.map(String),
|
|
602
|
-
min: acc.min,
|
|
603
|
-
max: acc.max,
|
|
604
|
-
},
|
|
605
|
-
],
|
|
606
|
-
},
|
|
607
|
-
});
|
|
608
|
-
}
|
|
609
|
-
cycleQueueWaitBySeat.clear();
|
|
610
|
-
if (openCyclesRecorded) {
|
|
611
|
-
cycleMetrics.push({
|
|
612
|
-
name: "spellkave.world_actor.open_cycles",
|
|
613
|
-
unit: "{cycle}",
|
|
614
|
-
gauge: {
|
|
615
|
-
dataPoints: [
|
|
616
|
-
{
|
|
617
|
-
attributes: otlpAttributes(stableMetricAttributes, SAFE_METRIC_ATTRIBUTE_KEYS),
|
|
618
|
-
timeUnixNano: unixNano(now),
|
|
619
|
-
asInt: String(openCyclesMax),
|
|
620
|
-
},
|
|
621
|
-
],
|
|
622
|
-
},
|
|
623
|
-
});
|
|
624
|
-
openCyclesMax = openCycles;
|
|
625
|
-
}
|
|
626
|
-
if (queueDepthRecorded) {
|
|
627
|
-
cycleMetrics.push({
|
|
628
|
-
name: "spellkave.world_actor.cycle_queue_depth",
|
|
629
|
-
unit: "{waiter}",
|
|
630
|
-
gauge: {
|
|
631
|
-
dataPoints: [
|
|
632
|
-
{
|
|
633
|
-
attributes: otlpAttributes(stableMetricAttributes, SAFE_METRIC_ATTRIBUTE_KEYS),
|
|
634
|
-
timeUnixNano: unixNano(now),
|
|
635
|
-
asInt: String(queueDepthMax),
|
|
636
|
-
},
|
|
637
|
-
],
|
|
638
|
-
},
|
|
639
|
-
});
|
|
640
|
-
queueDepthMax = queueDepth;
|
|
641
|
-
}
|
|
642
|
-
for (const [actorEntityKey, { sample, atMs }] of workerHeapBySeat) {
|
|
643
|
-
const fields = [
|
|
644
|
-
["worker_heap_bytes", sample.heapUsedBytes, "By"],
|
|
645
|
-
["worker_heap_total_bytes", sample.heapTotalBytes, "By"],
|
|
646
|
-
["worker_external_bytes", sample.externalBytes, "By"],
|
|
647
|
-
["worker_array_buffers_bytes", sample.arrayBuffersBytes, "By"],
|
|
648
|
-
["worker_memory_sample_age_ms", Math.max(0, now() - atMs), "ms"],
|
|
649
|
-
] as const;
|
|
650
|
-
for (const [name, value, unit] of fields) {
|
|
651
|
-
if (value === undefined || !Number.isSafeInteger(value) || value < 0) continue;
|
|
652
|
-
cycleMetrics.push({
|
|
653
|
-
name: `spellkave.world_actor.${name}`,
|
|
654
|
-
unit,
|
|
655
|
-
gauge: {
|
|
656
|
-
dataPoints: [
|
|
657
|
-
{
|
|
658
|
-
attributes: otlpAttributes(
|
|
659
|
-
{
|
|
660
|
-
...stableMetricAttributes,
|
|
661
|
-
"spellkave.actor_entity_key": actorEntityKey,
|
|
662
|
-
},
|
|
663
|
-
SAFE_METRIC_ATTRIBUTE_KEYS,
|
|
664
|
-
),
|
|
665
|
-
timeUnixNano: unixNano(now),
|
|
666
|
-
asInt: String(value),
|
|
667
|
-
},
|
|
668
|
-
],
|
|
669
|
-
},
|
|
670
|
-
});
|
|
671
|
-
}
|
|
672
|
-
}
|
|
673
|
-
if (cycleMetrics.length > 0) ship(cycleMetrics);
|
|
674
|
-
await Promise.allSettled([...pending]);
|
|
675
|
-
},
|
|
676
|
-
};
|
|
677
|
-
}
|