@mark1russell7/otel-sink 0.1.0 → 0.1.1

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/dist/otlp.js ADDED
@@ -0,0 +1,144 @@
1
+ /**
2
+ * The rows of an OTLP/HTTP JSON export: each span, log record and metric point as one row of the store. The
3
+ * functions read only the parts of OTLP that the store keeps. They make no request and open no file.
4
+ *
5
+ * OTLP JSON gives the ids of a trace and a span in hex, and each time in nanoseconds as a string. A time of today
6
+ * is past 2^53, so each time stays a `bigint`.
7
+ */
8
+ /** The service name of a resource without `service.name`, as in the SDK of OpenTelemetry */
9
+ export const UNKNOWN_SERVICE = "unknown_service";
10
+ /** This error tells that a body is not an export of OTLP JSON. The receiver answers it with 400. */
11
+ export class OtlpShapeError extends Error {
12
+ name = "OtlpShapeError";
13
+ }
14
+ /** This function gives the value of an attribute of OTLP JSON. */
15
+ export const valueOf = (value) => {
16
+ if (value === undefined || value === null)
17
+ return null;
18
+ if (value.stringValue !== undefined)
19
+ return value.stringValue;
20
+ if (value.boolValue !== undefined)
21
+ return value.boolValue;
22
+ if (value.intValue !== undefined)
23
+ return Number(value.intValue);
24
+ if (value.doubleValue !== undefined)
25
+ return value.doubleValue;
26
+ if (value.arrayValue !== undefined)
27
+ return (value.arrayValue.values ?? []).map(valueOf);
28
+ if (value.kvlistValue !== undefined)
29
+ return attributesOf(value.kvlistValue.values);
30
+ if (value.bytesValue !== undefined)
31
+ return value.bytesValue;
32
+ return null;
33
+ };
34
+ /** This function gives the attributes of OTLP JSON as one object. */
35
+ export const attributesOf = (list = []) => Object.fromEntries(list.map(({ key, value }) => [key, valueOf(value)]));
36
+ const serviceOf = (resource) => {
37
+ const name = attributesOf(resource?.attributes)["service.name"];
38
+ return typeof name === "string" && name !== "" ? name : UNKNOWN_SERVICE;
39
+ };
40
+ const ns = (text, what) => {
41
+ if (text === undefined || text === "")
42
+ return 0n;
43
+ try {
44
+ return BigInt(text);
45
+ }
46
+ catch {
47
+ throw new OtlpShapeError(`${what} is not a time in nanoseconds: ${String(text)}`);
48
+ }
49
+ };
50
+ const HEX = /^[0-9a-f]*$/i;
51
+ const id = (text, what) => {
52
+ if (text === undefined || text === "")
53
+ return null;
54
+ if (!HEX.test(text))
55
+ throw new OtlpShapeError(`${what} is not hex: ${text}`);
56
+ return text.toLowerCase();
57
+ };
58
+ const list = (value, what) => {
59
+ if (value === undefined)
60
+ return [];
61
+ if (!Array.isArray(value))
62
+ throw new OtlpShapeError(`${what} is not a list`);
63
+ return value;
64
+ };
65
+ /** This function gives a row for each span of an export of traces. */
66
+ export const spanRows = (body) => {
67
+ const rows = [];
68
+ for (const { resource, scopeSpans } of list(body.resourceSpans, "resourceSpans")) {
69
+ const service = serviceOf(resource);
70
+ for (const { spans } of list(scopeSpans, "scopeSpans"))
71
+ for (const span of list(spans, "spans")) {
72
+ const traceId = id(span.traceId, "traceId");
73
+ const spanId = id(span.spanId, "spanId");
74
+ if (traceId === null || spanId === null)
75
+ throw new OtlpShapeError("a span has no traceId or no spanId");
76
+ rows.push({
77
+ traceId,
78
+ spanId,
79
+ parentId: id(span.parentSpanId, "parentSpanId"),
80
+ service,
81
+ name: String(span.name ?? ""),
82
+ kind: span.kind ?? null,
83
+ startNs: ns(span.startTimeUnixNano, "startTimeUnixNano"),
84
+ endNs: ns(span.endTimeUnixNano, "endTimeUnixNano"),
85
+ status: span.status?.code ?? 0,
86
+ attributes: JSON.stringify(attributesOf(span.attributes)),
87
+ });
88
+ }
89
+ }
90
+ return rows;
91
+ };
92
+ /** This function gives a row for each log record of an export of logs. A record without a time gets its observed time. */
93
+ export const logRows = (body) => {
94
+ const rows = [];
95
+ for (const { resource, scopeLogs } of list(body.resourceLogs, "resourceLogs")) {
96
+ const service = serviceOf(resource);
97
+ for (const { logRecords } of list(scopeLogs, "scopeLogs"))
98
+ for (const log of list(logRecords, "logRecords")) {
99
+ const text = valueOf(log.body);
100
+ const time = ns(log.timeUnixNano, "timeUnixNano");
101
+ rows.push({
102
+ timeNs: time === 0n ? ns(log.observedTimeUnixNano, "observedTimeUnixNano") : time,
103
+ service,
104
+ severity: log.severityNumber ?? null,
105
+ body: text === null ? null : typeof text === "string" ? text : JSON.stringify(text),
106
+ traceId: id(log.traceId, "traceId"),
107
+ spanId: id(log.spanId, "spanId"),
108
+ attributes: JSON.stringify(attributesOf(log.attributes)),
109
+ });
110
+ }
111
+ }
112
+ return rows;
113
+ };
114
+ /** This function gives a row for each point of a sum, a gauge or a histogram of an export of metrics. */
115
+ export const pointRows = (body) => {
116
+ const rows = [];
117
+ for (const { resource, scopeMetrics } of list(body.resourceMetrics, "resourceMetrics")) {
118
+ const service = serviceOf(resource);
119
+ for (const { metrics } of list(scopeMetrics, "scopeMetrics"))
120
+ for (const metric of list(metrics, "metrics")) {
121
+ const numbers = [...list(metric.sum?.dataPoints, "sum.dataPoints"), ...list(metric.gauge?.dataPoints, "gauge.dataPoints")];
122
+ for (const point of numbers)
123
+ rows.push({
124
+ timeNs: ns(point.timeUnixNano, "timeUnixNano"),
125
+ service,
126
+ metric: metric.name,
127
+ attributes: JSON.stringify(attributesOf(point.attributes)),
128
+ value: point.asDouble ?? (point.asInt === undefined ? null : Number(point.asInt)),
129
+ histogram: null,
130
+ });
131
+ for (const point of list(metric.histogram?.dataPoints, "histogram.dataPoints"))
132
+ rows.push({
133
+ timeNs: ns(point.timeUnixNano, "timeUnixNano"),
134
+ service,
135
+ metric: metric.name,
136
+ attributes: JSON.stringify(attributesOf(point.attributes)),
137
+ value: point.sum ?? null,
138
+ histogram: JSON.stringify({ count: Number(point.count ?? 0), explicitBounds: point.explicitBounds ?? [], bucketCounts: (point.bucketCounts ?? []).map(Number) }),
139
+ });
140
+ }
141
+ }
142
+ return rows;
143
+ };
144
+ //# sourceMappingURL=otlp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"otlp.js","sourceRoot":"","sources":["../src/otlp.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAuIH,4F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,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;wBACjF,SAAS,EAAE,IAAI;qBAChB,CAAC,CAAC;gBACL,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,UAAU,EAAE,sBAAsB,CAAC;oBAC5E,IAAI,CAAC,IAAI,CAAC;wBACR,MAAM,EAAE,EAAE,CAAC,KAAK,CAAC,YAAY,EAAE,cAAc,CAAC;wBAC9C,OAAO;wBACP,MAAM,EAAE,MAAM,CAAC,IAAI;wBACnB,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;wBAC1D,KAAK,EAAE,KAAK,CAAC,GAAG,IAAI,IAAI;wBACxB,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC,EAAE,KAAK,EAAE,MAAM,CAAC,KAAK,CAAC,KAAK,IAAI,CAAC,CAAC,EAAE,cAAc,EAAE,KAAK,CAAC,cAAc,IAAI,EAAE,EAAE,YAAY,EAAE,CAAC,KAAK,CAAC,YAAY,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC;qBACjK,CAAC,CAAC;YACP,CAAC;IACL,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC,CAAC"}
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The queries of the store: the slowest spans, the errors, one trace with its logs, and the counts of each service.
3
+ * Each time in a result is in milliseconds since the epoch, and each duration is in milliseconds.
4
+ */
5
+ import type { DatabaseSync } from "node:sqlite";
6
+ import type { Value } from "./otlp.ts";
7
+ /** A span in a result */
8
+ export interface SpanView {
9
+ readonly traceId: string;
10
+ readonly spanId: string;
11
+ readonly parentId: string | null;
12
+ readonly service: string;
13
+ readonly name: string;
14
+ readonly kind: number | null;
15
+ readonly startMs: number;
16
+ readonly durationMs: number;
17
+ readonly status: number;
18
+ readonly attributes: {
19
+ readonly [key: string]: Value;
20
+ };
21
+ }
22
+ /** A log record in a result */
23
+ export interface LogView {
24
+ readonly timeMs: number;
25
+ readonly service: string;
26
+ readonly severity: number | null;
27
+ readonly body: string | null;
28
+ readonly traceId: string | null;
29
+ readonly spanId: string | null;
30
+ readonly attributes: {
31
+ readonly [key: string]: Value;
32
+ };
33
+ }
34
+ /** The counts of the spans of one service */
35
+ export interface ServiceView {
36
+ readonly service: string;
37
+ readonly spans: number;
38
+ readonly failed: number;
39
+ /** The fraction of the spans with the status error */
40
+ readonly errorRate: number;
41
+ readonly slowestMs: number;
42
+ }
43
+ /** The window and the size of a query */
44
+ export interface Window {
45
+ /** The start of the window, in milliseconds since the epoch */
46
+ readonly sinceMs: number;
47
+ /** The most rows of a result, from 1 up to `MAX_LIMIT` */
48
+ readonly limit: number;
49
+ /** Only the rows of this service, when it is given */
50
+ readonly service?: string | undefined;
51
+ }
52
+ /** The most rows of one result */
53
+ export declare const MAX_LIMIT = 1000;
54
+ /** The severity number of OTLP from which a log record is an error */
55
+ export declare const ERROR_SEVERITY = 17;
56
+ /** This function gives the problems of a window. The receiver answers a window with problems with 400. */
57
+ export declare const windowProblems: (window: Window) => string[];
58
+ /** This function gives the slowest spans that start in the window, the slowest first. */
59
+ export declare const slowest: (db: DatabaseSync, window: Window) => SpanView[];
60
+ /** This function gives the spans with the status error and the error logs of the window, the newest first. */
61
+ export declare const errors: (db: DatabaseSync, window: Window) => {
62
+ readonly spans: SpanView[];
63
+ readonly logs: LogView[];
64
+ };
65
+ /** The pattern of a trace id: 32 hex digits */
66
+ export declare const TRACE_ID: RegExp;
67
+ /** This function gives the spans and the logs of one trace, in the order of their times. */
68
+ export declare const trace: (db: DatabaseSync, traceId: string) => {
69
+ readonly spans: SpanView[];
70
+ readonly logs: LogView[];
71
+ };
72
+ /** This function gives the counts of the spans of each service in the window, the most failed spans first. */
73
+ export declare const services: (db: DatabaseSync, window: Window) => ServiceView[];
74
+ //# sourceMappingURL=query.d.ts.map
@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A;CAM/G,CAAC;AAEF,8GAA8G;AAC9G,eAAO,MAAM,QAAQ,GAAI,IAAI,YAAY,EAAE,QAAQ,MAAM,KAAG,WAAW,EAWjE,CAAC"}
package/dist/query.js ADDED
@@ -0,0 +1,78 @@
1
+ import { readTransaction } from "@mark1russell7/sqlite";
2
+ /** The most rows of one result */
3
+ export const MAX_LIMIT = 1000;
4
+ /** The severity number of OTLP from which a log record is an error */
5
+ export const ERROR_SEVERITY = 17;
6
+ const SPAN_COLUMNS = `trace_id AS traceId, span_id AS spanId, parent_id AS parentId, service, name, kind,
7
+ start_ns / 1000000 AS startMs, (end_ns - start_ns) / 1e6 AS durationMs, status, attributes`;
8
+ const LOG_COLUMNS = "time_ns / 1000000 AS timeMs, service, severity, body, trace_id AS traceId, span_id AS spanId, attributes";
9
+ const spanOf = (row) => ({
10
+ traceId: String(row["traceId"]),
11
+ spanId: String(row["spanId"]),
12
+ parentId: row["parentId"] === null ? null : String(row["parentId"]),
13
+ service: String(row["service"]),
14
+ name: String(row["name"]),
15
+ kind: row["kind"] === null ? null : Number(row["kind"]),
16
+ startMs: Number(row["startMs"]),
17
+ durationMs: Number(row["durationMs"]),
18
+ status: Number(row["status"]),
19
+ attributes: JSON.parse(String(row["attributes"])),
20
+ });
21
+ const logOf = (row) => ({
22
+ timeMs: Number(row["timeMs"]),
23
+ service: String(row["service"]),
24
+ severity: row["severity"] === null ? null : Number(row["severity"]),
25
+ body: row["body"] === null ? null : String(row["body"]),
26
+ traceId: row["traceId"] === null ? null : String(row["traceId"]),
27
+ spanId: row["spanId"] === null ? null : String(row["spanId"]),
28
+ attributes: JSON.parse(String(row["attributes"])),
29
+ });
30
+ /** This function gives the problems of a window. The receiver answers a window with problems with 400. */
31
+ export const windowProblems = (window) => {
32
+ const problems = [];
33
+ if (!Number.isFinite(window.sinceMs) || window.sinceMs < 0)
34
+ problems.push("since must be a time in milliseconds from 0");
35
+ if (!Number.isSafeInteger(window.limit) || window.limit < 1 || window.limit > MAX_LIMIT)
36
+ problems.push(`limit must be a whole number from 1 to ${MAX_LIMIT}`);
37
+ return problems;
38
+ };
39
+ const sinceNs = (window) => BigInt(Math.floor(window.sinceMs)) * 1000000n;
40
+ const serviceFilter = (window, column = "service") => (window.service === undefined ? "" : ` AND ${column} = ?`);
41
+ const serviceParam = (window) => (window.service === undefined ? [] : [window.service]);
42
+ /** This function gives the slowest spans that start in the window, the slowest first. */
43
+ export const slowest = (db, window) => db
44
+ .prepare(`SELECT ${SPAN_COLUMNS} FROM spans WHERE start_ns >= ?${serviceFilter(window)} ORDER BY end_ns - start_ns DESC LIMIT ?`)
45
+ .all(sinceNs(window), ...serviceParam(window), window.limit)
46
+ .map(spanOf);
47
+ /** This function gives the spans with the status error and the error logs of the window, the newest first. */
48
+ export const errors = (db, window) => readTransaction(db, () => ({
49
+ spans: db
50
+ .prepare(`SELECT ${SPAN_COLUMNS} FROM spans WHERE status = 2 AND start_ns >= ?${serviceFilter(window)} ORDER BY start_ns DESC LIMIT ?`)
51
+ .all(sinceNs(window), ...serviceParam(window), window.limit)
52
+ .map(spanOf),
53
+ logs: db
54
+ .prepare(`SELECT ${LOG_COLUMNS} FROM logs WHERE severity >= ${ERROR_SEVERITY} AND time_ns >= ?${serviceFilter(window)} ORDER BY time_ns DESC LIMIT ?`)
55
+ .all(sinceNs(window), ...serviceParam(window), window.limit)
56
+ .map(logOf),
57
+ }));
58
+ /** The pattern of a trace id: 32 hex digits */
59
+ export const TRACE_ID = /^[0-9a-f]{32}$/;
60
+ /** This function gives the spans and the logs of one trace, in the order of their times. */
61
+ export const trace = (db, traceId) => {
62
+ const id = traceId.toLowerCase();
63
+ return readTransaction(db, () => ({
64
+ spans: db.prepare(`SELECT ${SPAN_COLUMNS} FROM spans WHERE trace_id = ? ORDER BY start_ns LIMIT ${MAX_LIMIT}`).all(id).map(spanOf),
65
+ logs: db.prepare(`SELECT ${LOG_COLUMNS} FROM logs WHERE trace_id = ? ORDER BY time_ns LIMIT ${MAX_LIMIT}`).all(id).map(logOf),
66
+ }));
67
+ };
68
+ /** This function gives the counts of the spans of each service in the window, the most failed spans first. */
69
+ export const services = (db, window) => db
70
+ .prepare(`SELECT service, COUNT(*) AS spans, SUM(status = 2) AS failed, MAX(end_ns - start_ns) / 1e6 AS slowestMs
71
+ FROM spans WHERE start_ns >= ?${serviceFilter(window)} GROUP BY service ORDER BY failed DESC, spans DESC LIMIT ?`)
72
+ .all(sinceNs(window), ...serviceParam(window), window.limit)
73
+ .map((row) => {
74
+ const spans = Number(row["spans"]);
75
+ const failed = Number(row["failed"]);
76
+ return { service: String(row["service"]), spans, failed, errorRate: spans === 0 ? 0 : failed / spans, slowestMs: Number(row["slowestMs"]) };
77
+ });
78
+ //# sourceMappingURL=query.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"query.js","sourceRoot":"","sources":["../src/query.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAgDxD,kCAAkC;AAClC,MAAM,CAAC,MAAM,SAAS,GAAG,IAAI,CAAC;AAE9B,sEAAsE;AACtE,MAAM,CAAC,MAAM,cAAc,GAAG,EAAE,CAAC;AAEjC,MAAM,YAAY,GAAG;6FACwE,CAAC;AAC9F,MAAM,WAAW,GAAG,0GAA0G,CAAC;AAI/H,MAAM,MAAM,GAAG,CAAC,GAAQ,EAAY,EAAE,CAAC,CAAC;IACtC,OAAO,EAAE,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAC/B,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IAC7B,QAAQ,EAAE,GAAG,CAAC,UAAU,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;IACnE,OAAO,EAAE,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAC/B,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,MAAM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G,CAAC,MAAM,CAAC;QAClI,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,UAAU,WAAW,wDAAwD,SAAS,EAAE,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC;KAC9H,CAAC,CAAC,CAAC;AACN,CAAC,CAAC;AAEF,8GAA8G;AAC9G,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,EAAgB,EAAE,MAAc,EAAiB,EAAE,CAC1E,EAAE;KACC,OAAO,CACN;uCACiC,aAAa,CAAC,MAAM,CAAC,4DAA4D,CACnH;KACA,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,EAAE,GAAG,YAAY,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,KAAK,CAAC;KAC3D,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE;IACX,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC;IACnC,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC;IACrC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,GAAG,KAAK,EAAE,SAAS,EAAE,MAAM,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC;AAC9I,CAAC,CAAC,CAAC"}
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The retention rules of the store, as data. Each signal has a maximum age and a maximum size. The prune deletes the
3
+ * rows past the age, then the oldest rows past the size. The sum of the sizes must be at most `HARD_LIMIT_BYTES`, so
4
+ * no set of rules lets the store fill the disk.
5
+ */
6
+ /** The three signals of the store */
7
+ export type Signal = "spans" | "logs" | "points";
8
+ /** The signals of the store, in a fixed order */
9
+ export declare const SIGNALS: readonly Signal[];
10
+ /** The rule of one signal */
11
+ export interface SignalRule {
12
+ /** The maximum age of a row, in milliseconds. The age is from the time of the row, not from its arrival. */
13
+ readonly maxAgeMs: number;
14
+ /** The maximum size of the rows of the signal, in bytes, as the store counts them */
15
+ readonly maxBytes: number;
16
+ }
17
+ /** The rules of the three signals */
18
+ export type RetentionRules = {
19
+ readonly [signal in Signal]: SignalRule;
20
+ };
21
+ /** The upper limit of the sum of the sizes of all signals: 1 GiB */
22
+ export declare const HARD_LIMIT_BYTES: number;
23
+ /** The default rules: 3 days and 256 MiB for spans and logs, 7 days and 128 MiB for metric points */
24
+ export declare const DEFAULT_RETENTION: RetentionRules;
25
+ /** This function gives the problems of a set of rules. A store refuses rules with problems. */
26
+ export declare const retentionProblems: (rules: RetentionRules) => string[];
27
+ //# sourceMappingURL=retention.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retention.d.ts","sourceRoot":"","sources":["../src/retention.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,qCAAqC;AACrC,MAAM,MAAM,MAAM,GAAG,OAAO,GAAG,MAAM,GAAG,QAAQ,CAAC;AAEjD,iDAAiD;AACjD,eAAO,MAAM,OAAO,EAAE,SAAS,MAAM,EAAgC,CAAC;AAEtE,6BAA6B;AAC7B,MAAM,WAAW,UAAU;IACzB,4GAA4G;IAC5G,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,qFAAqF;IACrF,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;CAC3B;AAED,qCAAqC;AACrC,MAAM,MAAM,cAAc,GAAG;IAAE,QAAQ,EAAE,MAAM,IAAI,MAAM,GAAG,UAAU;CAAE,CAAC;AAKzE,oEAAoE;AACpE,eAAO,MAAM,gBAAgB,EAAE,MAAmB,CAAC;AAEnD,qGAAqG;AACrG,eAAO,MAAM,iBAAiB,EAAE,cAI/B,CAAC;AAEF,+FAA+F;AAC/F,eAAO,MAAM,iBAAiB,GAAI,OAAO,cAAc,KAAG,MAAM,EAe/D,CAAC"}
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The retention rules of the store, as data. Each signal has a maximum age and a maximum size. The prune deletes the
3
+ * rows past the age, then the oldest rows past the size. The sum of the sizes must be at most `HARD_LIMIT_BYTES`, so
4
+ * no set of rules lets the store fill the disk.
5
+ */
6
+ /** The signals of the store, in a fixed order */
7
+ export const SIGNALS = ["spans", "logs", "points"];
8
+ const MiB = 1024 * 1024;
9
+ const DAY_MS = 24 * 60 * 60 * 1000;
10
+ /** The upper limit of the sum of the sizes of all signals: 1 GiB */
11
+ export const HARD_LIMIT_BYTES = 1024 * MiB;
12
+ /** The default rules: 3 days and 256 MiB for spans and logs, 7 days and 128 MiB for metric points */
13
+ export const DEFAULT_RETENTION = {
14
+ spans: { maxAgeMs: 3 * DAY_MS, maxBytes: 256 * MiB },
15
+ logs: { maxAgeMs: 3 * DAY_MS, maxBytes: 256 * MiB },
16
+ points: { maxAgeMs: 7 * DAY_MS, maxBytes: 128 * MiB },
17
+ };
18
+ /** This function gives the problems of a set of rules. A store refuses rules with problems. */
19
+ export const retentionProblems = (rules) => {
20
+ const problems = [];
21
+ let total = 0;
22
+ for (const signal of SIGNALS) {
23
+ const rule = rules[signal];
24
+ if (rule === undefined) {
25
+ problems.push(`${signal}: no rule`);
26
+ continue;
27
+ }
28
+ if (!Number.isFinite(rule.maxAgeMs) || rule.maxAgeMs <= 0)
29
+ problems.push(`${signal}: maxAgeMs must be a positive finite number`);
30
+ if (!Number.isSafeInteger(rule.maxBytes) || rule.maxBytes <= 0)
31
+ problems.push(`${signal}: maxBytes must be a positive whole number`);
32
+ else
33
+ total += rule.maxBytes;
34
+ }
35
+ if (total > HARD_LIMIT_BYTES)
36
+ problems.push(`the sum of maxBytes is ${total}, more than the hard limit ${HARD_LIMIT_BYTES}`);
37
+ return problems;
38
+ };
39
+ //# sourceMappingURL=retention.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"retention.js","sourceRoot":"","sources":["../src/retention.ts"],"names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AAC,CAAC;QACjI,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,IAAI,CAAC,QAAQ,IAAI,CAAC;YAAE,QAAQ,CAAC,IAAI,CAAC,GAAG,MAAM,4CAA4C,CAAC,CAAC;;YAChI,KAAK,IAAI,IAAI,CAAC,QAAQ,CAAC;IAC9B,CAAC;IACD,IAAI,KAAK,GAAG,gBAAgB;QAAE,QAAQ,CAAC,IAAI,CAAC,0BAA0B,KAAK,8BAA8B,gBAAgB,EAAE,CAAC,CAAC;IAC7H,OAAO,QAAQ,CAAC;AAClB,CAAC,CAAC"}
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The store of the sink: one SQLite file with a table for each signal. Each row has its size in bytes, and triggers
3
+ * keep the sum of each table in the table `sizes`. Thus the prune reads one row to know the size of a signal.
4
+ */
5
+ import { type Migration } from "@mark1russell7/sqlite";
6
+ import type { DatabaseSync } from "node:sqlite";
7
+ import type { LogRow, PointRow, SpanRow } from "./otlp.ts";
8
+ import { type RetentionRules, type Signal } from "./retention.ts";
9
+ /** The column of the time of each signal, in nanoseconds since the epoch */
10
+ export declare const TIME_COLUMN: {
11
+ readonly [signal in Signal]: string;
12
+ };
13
+ /** The steps of the schema. Do not change a step: add a new one. */
14
+ export declare const MIGRATIONS: readonly Migration[];
15
+ /** The size of a signal in the store */
16
+ export interface SignalSize {
17
+ readonly rows: number;
18
+ readonly bytes: number;
19
+ }
20
+ /** The rows that a prune deleted for one signal: past the age, and past the size */
21
+ export interface SignalPrune {
22
+ readonly aged: number;
23
+ readonly capped: number;
24
+ }
25
+ /** The result of a prune: the rows that it deleted for each signal, and if it is done */
26
+ export type Pruned = {
27
+ readonly [signal in Signal]: SignalPrune;
28
+ } & {
29
+ readonly done: boolean;
30
+ };
31
+ /** The rows of one export */
32
+ export interface Rows {
33
+ readonly spans?: readonly SpanRow[];
34
+ readonly logs?: readonly LogRow[];
35
+ readonly points?: readonly PointRow[];
36
+ }
37
+ /** The store of the sink */
38
+ export interface Store {
39
+ /** The connection, for the queries. Do not write through it: each write goes through the store. */
40
+ readonly db: DatabaseSync;
41
+ readonly rules: RetentionRules;
42
+ /** This method writes the rows in one transaction. Then it prunes each signal that is past its size. */
43
+ insert(rows: Rows): void;
44
+ /**
45
+ * This method deletes the rows past the age of each signal at `nowMs`, then the oldest rows past each size. Each
46
+ * delete is one transaction of at most `batch` rows. The prune stops after `batches` deletes (no bound by default),
47
+ * and then `done` is false. Thus a caller can let other work go between two parts of a long prune.
48
+ */
49
+ prune(nowMs: number, batches?: number): Pruned;
50
+ /** This method gives the count and the size of the rows of each signal. */
51
+ sizes(): {
52
+ readonly [signal in Signal]: SignalSize;
53
+ };
54
+ /** This method gives the size of the file in bytes, without its write-ahead log. */
55
+ fileBytes(): number;
56
+ close(): void;
57
+ }
58
+ /** The options of `openStore` */
59
+ export interface StoreOptions {
60
+ readonly rules?: RetentionRules | undefined;
61
+ /** The most rows that one delete of the prune by size removes. The default is 5000. */
62
+ readonly batch?: number | undefined;
63
+ }
64
+ /** The size that the store counts for a row: the bytes of its text, 8 bytes for each number, and 32 bytes for the row */
65
+ export declare const ROW_OVERHEAD = 32;
66
+ /**
67
+ * This function opens the store at a path, or in memory at `:memory:`. It makes the folder and the tables when they are
68
+ * not there. It throws when the rules have problems.
69
+ */
70
+ export declare const openStore: (path: string, options?: StoreOptions) => Store;
71
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAsC,KAAK,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAC3F,OAAO,KAAK,EAAE,YAAY,EAAiB,MAAM,aAAa,CAAC;AAC/D,OAAO,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAiD,KAAK,cAAc,EAAE,KAAK,MAAM,E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AAI,MAAM,GAAG,UAAU;KAAE,CAAC;IACrD,oFAAoF;IACpF,SAAS,IAAI,MAAM,CAAC;IACpB,KAAK,IAAI,IAAI,CAAC;CACf;AAED,iCAAiC;AACjC,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,KAAK,CAAC,EAAE,cAAc,GAAG,SAAS,CAAC;IAC5C,uFAAuF;IACvF,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;CACrC;AAID,yHAAyH;AACzH,eAAO,MAAM,YAAY,KAAK,CAAC;AAQ/B;;;GAGG;AACH,eAAO,MAAM,SAAS,GAAI,MAAM,MAAM,EAAE,UAAS,YAAiB,KAAG,KAkHpE,CAAC"}
package/dist/store.js ADDED
@@ -0,0 +1,151 @@
1
+ /**
2
+ * The store of the sink: one SQLite file with a table for each signal. Each row has its size in bytes, and triggers
3
+ * keep the sum of each table in the table `sizes`. Thus the prune reads one row to know the size of a signal.
4
+ */
5
+ import { migrate, openDatabase, transaction } from "@mark1russell7/sqlite";
6
+ import { DEFAULT_RETENTION, retentionProblems, SIGNALS } from "./retention.js";
7
+ /** The column of the time of each signal, in nanoseconds since the epoch */
8
+ export const TIME_COLUMN = { spans: "start_ns", logs: "time_ns", points: "time_ns" };
9
+ const sizeTriggers = (signal) => `CREATE TRIGGER ${signal}_insert AFTER INSERT ON ${signal} BEGIN UPDATE sizes SET rows = rows + 1, bytes = bytes + NEW.bytes WHERE signal = '${signal}'; END;
10
+ CREATE TRIGGER ${signal}_delete AFTER DELETE ON ${signal} BEGIN UPDATE sizes SET rows = rows - 1, bytes = bytes - OLD.bytes WHERE signal = '${signal}'; END;`;
11
+ /** The steps of the schema. Do not change a step: add a new one. */
12
+ export const MIGRATIONS = [
13
+ `CREATE TABLE spans (trace_id TEXT NOT NULL, span_id TEXT NOT NULL, parent_id TEXT, service TEXT NOT NULL, name TEXT NOT NULL,
14
+ kind INTEGER, start_ns INTEGER NOT NULL, end_ns INTEGER NOT NULL, status INTEGER NOT NULL, attributes TEXT NOT NULL, bytes INTEGER NOT NULL);
15
+ CREATE INDEX spans_start ON spans (start_ns);
16
+ CREATE INDEX spans_service_start ON spans (service, start_ns);
17
+ CREATE INDEX spans_trace ON spans (trace_id);
18
+ CREATE INDEX spans_errors ON spans (start_ns) WHERE status = 2;
19
+ CREATE TABLE logs (time_ns INTEGER NOT NULL, service TEXT NOT NULL, severity INTEGER, body TEXT, trace_id TEXT, span_id TEXT,
20
+ attributes TEXT NOT NULL, bytes INTEGER NOT NULL);
21
+ CREATE INDEX logs_time ON logs (time_ns);
22
+ CREATE INDEX logs_service_time ON logs (service, time_ns);
23
+ CREATE INDEX logs_trace ON logs (trace_id);
24
+ CREATE INDEX logs_errors ON logs (time_ns) WHERE severity >= 17;
25
+ CREATE TABLE points (time_ns INTEGER NOT NULL, service TEXT NOT NULL, metric TEXT NOT NULL, attributes TEXT NOT NULL,
26
+ value REAL, histogram TEXT, bytes INTEGER NOT NULL);
27
+ CREATE INDEX points_time ON points (time_ns);
28
+ CREATE INDEX points_metric_time ON points (metric, time_ns);
29
+ CREATE TABLE sizes (signal TEXT PRIMARY KEY, rows INTEGER NOT NULL, bytes INTEGER NOT NULL);
30
+ INSERT INTO sizes (signal, rows, bytes) VALUES ('spans', 0, 0), ('logs', 0, 0), ('points', 0, 0);
31
+ ${SIGNALS.map(sizeTriggers).join("\n")}`,
32
+ ];
33
+ const textBytes = (text) => (text === null ? 0 : Buffer.byteLength(text, "utf8"));
34
+ /** The size that the store counts for a row: the bytes of its text, 8 bytes for each number, and 32 bytes for the row */
35
+ export const ROW_OVERHEAD = 32;
36
+ const spanBytes = (row) => ROW_OVERHEAD + 8 * 4 + textBytes(row.traceId) + textBytes(row.spanId) + textBytes(row.parentId) + textBytes(row.service) + textBytes(row.name) + textBytes(row.attributes);
37
+ const logBytes = (row) => ROW_OVERHEAD + 8 * 2 + textBytes(row.service) + textBytes(row.body) + textBytes(row.traceId) + textBytes(row.spanId) + textBytes(row.attributes);
38
+ const pointBytes = (row) => ROW_OVERHEAD + 8 * 2 + textBytes(row.service) + textBytes(row.metric) + textBytes(row.attributes) + textBytes(row.histogram);
39
+ /**
40
+ * This function opens the store at a path, or in memory at `:memory:`. It makes the folder and the tables when they are
41
+ * not there. It throws when the rules have problems.
42
+ */
43
+ export const openStore = (path, options = {}) => {
44
+ const rules = options.rules ?? DEFAULT_RETENTION;
45
+ const problems = retentionProblems(rules);
46
+ if (problems.length > 0)
47
+ throw new RangeError(`the retention rules have problems: ${problems.join("; ")}`);
48
+ const batch = options.batch ?? 5000;
49
+ if (!Number.isSafeInteger(batch) || batch < 1)
50
+ throw new RangeError(`batch must be a whole number from 1: ${batch}`);
51
+ const db = openDatabase(path, { synchronous: "NORMAL", busyTimeoutMs: 5000, makeFolder: path !== ":memory:" });
52
+ try {
53
+ // Only a file with no tables takes this pragma. Thus it must come before the first step of the schema.
54
+ db.exec("PRAGMA auto_vacuum = INCREMENTAL");
55
+ migrate(db, MIGRATIONS, { name: "otel-sink" });
56
+ }
57
+ catch (error) {
58
+ db.close();
59
+ throw error;
60
+ }
61
+ const insertSpan = db.prepare("INSERT INTO spans (trace_id, span_id, parent_id, service, name, kind, start_ns, end_ns, status, attributes, bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
62
+ const insertLog = db.prepare("INSERT INTO logs (time_ns, service, severity, body, trace_id, span_id, attributes, bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
63
+ const insertPoint = db.prepare("INSERT INTO points (time_ns, service, metric, attributes, value, histogram, bytes) VALUES (?, ?, ?, ?, ?, ?, ?)");
64
+ const readSize = db.prepare("SELECT rows, bytes FROM sizes WHERE signal = ?");
65
+ const deleteAged = Object.fromEntries(SIGNALS.map((signal) => [
66
+ signal,
67
+ db.prepare(`DELETE FROM ${signal} WHERE rowid IN (SELECT rowid FROM ${signal} WHERE ${TIME_COLUMN[signal]} < ? ORDER BY ${TIME_COLUMN[signal]} LIMIT ?)`),
68
+ ]));
69
+ const deleteOldest = Object.fromEntries(SIGNALS.map((signal) => [signal, db.prepare(`DELETE FROM ${signal} WHERE rowid IN (SELECT rowid FROM ${signal} ORDER BY ${TIME_COLUMN[signal]} LIMIT ?)`)]));
70
+ const size = (signal) => {
71
+ const row = readSize.get(signal);
72
+ return { rows: Number(row?.["rows"] ?? 0), bytes: Number(row?.["bytes"] ?? 0) };
73
+ };
74
+ const unbounded = () => ({ left: Number.POSITIVE_INFINITY, complete: true });
75
+ const age = (signal, cutoff, budget) => {
76
+ let deleted = 0;
77
+ for (;;) {
78
+ if (budget.left <= 0) {
79
+ budget.complete = false;
80
+ return deleted;
81
+ }
82
+ budget.left--;
83
+ const changes = Number(transaction(db, () => deleteAged[signal].run(cutoff, batch)).changes);
84
+ deleted += changes;
85
+ if (changes < batch)
86
+ return deleted;
87
+ }
88
+ };
89
+ const cap = (signal, budget) => {
90
+ let deleted = 0;
91
+ for (;;) {
92
+ const { rows, bytes } = size(signal);
93
+ const excess = bytes - rules[signal].maxBytes;
94
+ if (excess <= 0 || rows === 0)
95
+ return deleted;
96
+ if (budget.left <= 0) {
97
+ budget.complete = false;
98
+ return deleted;
99
+ }
100
+ budget.left--;
101
+ const count = Math.min(batch, rows, Math.max(1, Math.ceil(excess / (bytes / rows))));
102
+ deleted += Number(transaction(db, () => deleteOldest[signal].run(count)).changes);
103
+ }
104
+ };
105
+ let closed = false;
106
+ return {
107
+ db,
108
+ rules,
109
+ insert(rows) {
110
+ transaction(db, () => {
111
+ for (const r of rows.spans ?? [])
112
+ insertSpan.run(r.traceId, r.spanId, r.parentId, r.service, r.name, r.kind, r.startNs, r.endNs, r.status, r.attributes, spanBytes(r));
113
+ for (const r of rows.logs ?? [])
114
+ insertLog.run(r.timeNs, r.service, r.severity, r.body, r.traceId, r.spanId, r.attributes, logBytes(r));
115
+ for (const r of rows.points ?? [])
116
+ insertPoint.run(r.timeNs, r.service, r.metric, r.attributes, r.value, r.histogram, pointBytes(r));
117
+ });
118
+ for (const signal of SIGNALS)
119
+ if ((rows[signal]?.length ?? 0) > 0)
120
+ cap(signal, unbounded());
121
+ },
122
+ prune(nowMs, batches = Number.POSITIVE_INFINITY) {
123
+ if (!(batches >= 1))
124
+ throw new RangeError(`batches must be 1 or more: ${batches}`);
125
+ const budget = { left: batches, complete: true };
126
+ const result = {};
127
+ for (const signal of SIGNALS) {
128
+ const cutoff = BigInt(Math.floor(nowMs - rules[signal].maxAgeMs)) * 1000000n;
129
+ const aged = age(signal, cutoff, budget);
130
+ result[signal] = { aged, capped: cap(signal, budget) };
131
+ }
132
+ db.exec("PRAGMA incremental_vacuum");
133
+ return { ...result, done: budget.complete };
134
+ },
135
+ sizes() {
136
+ return { spans: size("spans"), logs: size("logs"), points: size("points") };
137
+ },
138
+ fileBytes() {
139
+ const pages = Number(db.prepare("PRAGMA page_count").get()?.["page_count"] ?? 0);
140
+ const pageSize = Number(db.prepare("PRAGMA page_size").get()?.["page_size"] ?? 0);
141
+ return pages * pageSize;
142
+ },
143
+ close() {
144
+ if (closed)
145
+ return;
146
+ closed = true;
147
+ db.close();
148
+ },
149
+ };
150
+ };
151
+ //# sourceMappingURL=store.js.map