@mark1russell7/otel-sink 0.0.0-stage → 0.1.0
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/CHANGELOG.md +12 -0
- package/LICENSE +21 -0
- package/README.md +66 -2
- package/package.json +86 -3
- package/src/api.ts +195 -0
- package/src/index.ts +117 -0
- package/src/main.ts +35 -0
- package/src/otlp.ts +273 -0
- package/src/query.ts +145 -0
- package/src/retention.ts +53 -0
- package/src/store.ts +218 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- The first release. `@mark1russell7/otel-sink` is an OTLP/HTTP receiver for one computer with no collector. It keeps spans, logs and metric points in one SQLite file.
|
|
8
|
+
- The receiver: `POST /v1/traces`, `/v1/logs` and `/v1/metrics` take OTLP JSON, with gzip or without it. A protobuf body gets 415, a body larger than 8 MiB gets 413, and a body that is not OTLP gets 400.
|
|
9
|
+
- The retention rules (`RetentionRules`): a maximum age and a maximum size for each signal, and a hard limit of 1 GiB on the sum. The store caps a signal at each write, and a worker prunes in bounded parts.
|
|
10
|
+
- The queries: `GET /api/slowest`, `/api/errors`, `/api/trace`, `/api/services` and `/api/stats`.
|
|
11
|
+
- The command `otel-sink`, with the environment variables `PORT`, `PROBE_PORT`, `SERVICE_PROFILE` and `SINK_DB`. It refuses to start when its own OTLP endpoint is its receiver.
|
|
12
|
+
- The plain functions `openStore`, `spanRows`, `logRows`, `pointRows`, `slowest`, `errors`, `trace` and `services`, and `declare(options)` for the service.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mark Russell
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,67 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mark1russell7/otel-sink
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A small OTLP/HTTP receiver for one computer. It keeps spans, logs and metric points in one SQLite file, with retention rules. It answers questions about them over HTTP: the slowest spans, the errors, one trace with its logs, and the counts of each service.
|
|
4
|
+
|
|
5
|
+
The sink is for a development computer or a small host with no collector. It is not a replacement for a collector and a store, for example Tempo, Loki or Prometheus.
|
|
6
|
+
|
|
7
|
+
## Start it
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install --global @mark1russell7/otel-sink
|
|
11
|
+
SINK_DB=~/otel-sink.db PORT=4318 otel-sink
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
The environment gives these values. The value in parentheses is the value without the variable.
|
|
15
|
+
|
|
16
|
+
- `PORT` (4318): the port of the receiver and of the queries.
|
|
17
|
+
- `PROBE_PORT` (9090): the port of `/startup`, `/readiness`, `/liveness` and `/report`.
|
|
18
|
+
- `SERVICE_PROFILE` (`local`): the profile of the shutdown, `local` or `pod`.
|
|
19
|
+
- `SINK_DB` (`otel-sink.db` in the home folder): the SQLite file. The sink makes its folder when the folder is not there.
|
|
20
|
+
- `OTEL_EXPORTER_OTLP_ENDPOINT`: the endpoint of the telemetry of the sink itself. The sink refuses to start when it is its own receiver, because each export then makes a new export.
|
|
21
|
+
|
|
22
|
+
Point a sender at the sink:
|
|
23
|
+
|
|
24
|
+
```sh
|
|
25
|
+
OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318
|
|
26
|
+
OTEL_EXPORTER_OTLP_PROTOCOL=http/json
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## The receiver
|
|
30
|
+
|
|
31
|
+
- `POST /v1/traces`, `POST /v1/logs` and `POST /v1/metrics` take a body of OTLP JSON, with gzip or without it.
|
|
32
|
+
- **Only JSON.** The default protocol of the OTLP exporters is `http/protobuf`. The sink answers it with 415, and the body of the answer names the setting `OTEL_EXPORTER_OTLP_PROTOCOL=http/json`.
|
|
33
|
+
- **The limits.** A body larger than 8 MiB gets 413. A body that is not OTLP JSON gets 400. The sink reads and drops the rest of a refused body, thus the sender reads the answer and gets no reset.
|
|
34
|
+
- **The metrics.** The sink keeps the points of sums, gauges and histograms. It keeps the count, the sum and the buckets of each histogram point.
|
|
35
|
+
|
|
36
|
+
## The queries
|
|
37
|
+
|
|
38
|
+
Each query takes `since` (a time in milliseconds since the epoch, the last hour by default), `limit` (from 1 to 1000, 50 by default) and `service`. Each time in a result is in milliseconds since the epoch. A bad parameter gets 400 with a list of the problems.
|
|
39
|
+
|
|
40
|
+
| Route | Result |
|
|
41
|
+
| --- | --- |
|
|
42
|
+
| `GET /api/slowest` | The slowest spans of the window, the slowest first |
|
|
43
|
+
| `GET /api/errors` | The spans with the status error and the logs from the severity ERROR (17), the newest first |
|
|
44
|
+
| `GET /api/trace?id=<trace id>` | The spans and the logs of one trace, in the order of their times |
|
|
45
|
+
| `GET /api/services` | For each service: the count of spans, the count of failed spans, the error rate and the slowest span |
|
|
46
|
+
| `GET /api/stats` | The rows and the bytes of each signal, the size of the file, and the retention rules |
|
|
47
|
+
|
|
48
|
+
## Retention
|
|
49
|
+
|
|
50
|
+
The retention rules are data (`RetentionRules`). Each signal has a maximum age and a maximum size.
|
|
51
|
+
|
|
52
|
+
- **The defaults.** Spans and logs: 3 days and 256 MiB each. Metric points: 7 days and 128 MiB.
|
|
53
|
+
- **The hard limit.** The sum of the sizes must be 1 GiB or less. `openStore` refuses rules with problems, and `retentionProblems` gives those problems.
|
|
54
|
+
- **The size of a row.** The store counts the bytes of the text of each row, 8 bytes for each number and 32 bytes for the row. Triggers keep the sum of each signal in the table `sizes`.
|
|
55
|
+
- **The cap at each write.** After each export, the store deletes the oldest rows of a signal that is past its size. Thus a signal goes past its size by one export at most.
|
|
56
|
+
- **The prune.** A worker deletes the rows past their age each minute, and the oldest rows past each size. Each delete is one transaction of at most 5000 rows. Each part of a prune does at most 20 deletes, then the intake continues.
|
|
57
|
+
- **The file.** The file uses `auto_vacuum = INCREMENTAL`, and each prune gives the free pages back to the disk.
|
|
58
|
+
|
|
59
|
+
## As a library
|
|
60
|
+
|
|
61
|
+
`openStore`, the decoders (`spanRows`, `logRows`, `pointRows`) and the queries (`slowest`, `errors`, `trace`, `services`) are plain functions. `declare(options)` gives the service with its receiver, its queries and its retention worker, and it starts nothing.
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { declare, PROFILES } from "@mark1russell7/otel-sink";
|
|
65
|
+
|
|
66
|
+
const life = await declare({ port: 4318, probePort: 9090, profile: PROFILES["local"]!, path: "sink.db" }).run();
|
|
67
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,89 @@
|
|
|
1
1
|
{
|
|
2
|
+
"$schema": "https://json.schemastore.org/package",
|
|
2
3
|
"name": "@mark1russell7/otel-sink",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
4
|
+
"version": "0.1.0",
|
|
5
|
+
"description": "An OTLP/HTTP JSON receiver for one computer: spans, logs and metric points in one SQLite file, with retention rules and queries over HTTP.",
|
|
6
|
+
"keywords": [
|
|
7
|
+
"opentelemetry",
|
|
8
|
+
"otlp",
|
|
9
|
+
"sqlite",
|
|
10
|
+
"traces",
|
|
11
|
+
"logs",
|
|
12
|
+
"metrics",
|
|
13
|
+
"retention"
|
|
14
|
+
],
|
|
15
|
+
"type": "module",
|
|
16
|
+
"main": "./dist/index.js",
|
|
17
|
+
"types": "./dist/index.d.ts",
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"default": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./package.json": "./package.json"
|
|
24
|
+
},
|
|
25
|
+
"bin": {
|
|
26
|
+
"otel-sink": "./dist/main.js"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"dist",
|
|
30
|
+
"!dist/**/.tsbuildinfo",
|
|
31
|
+
"src",
|
|
32
|
+
"!src/**/*.test.ts",
|
|
33
|
+
"!src/**/*.test-util.ts",
|
|
34
|
+
"README.md",
|
|
35
|
+
"CHANGELOG.md",
|
|
36
|
+
"LICENSE"
|
|
37
|
+
],
|
|
38
|
+
"sideEffects": false,
|
|
39
|
+
"publishConfig": {
|
|
40
|
+
"access": "public"
|
|
41
|
+
},
|
|
42
|
+
"repository": {
|
|
43
|
+
"type": "git",
|
|
44
|
+
"url": "git+https://github.com/mark1russell7/otel-ts.git",
|
|
45
|
+
"directory": "packages/otel-sink"
|
|
46
|
+
},
|
|
47
|
+
"license": "MIT",
|
|
48
|
+
"author": "Mark Russell (https://github.com/mark1russell7)",
|
|
49
|
+
"homepage": "https://github.com/mark1russell7/otel-ts/tree/main/packages/otel-sink#readme",
|
|
50
|
+
"bugs": {
|
|
51
|
+
"url": "https://github.com/mark1russell7/otel-ts/issues"
|
|
52
|
+
},
|
|
53
|
+
"engines": {
|
|
54
|
+
"node": ">=22.15.0"
|
|
55
|
+
},
|
|
56
|
+
"dependencies": {
|
|
57
|
+
"@mark1russell7/otel-ts": "^0.11.2",
|
|
58
|
+
"@mark1russell7/service": "^0.13.0",
|
|
59
|
+
"@mark1russell7/sqlite": "^0.7.1",
|
|
60
|
+
"@opentelemetry/api": "^1.10.0",
|
|
61
|
+
"@opentelemetry/context-async-hooks": "^3.1.1",
|
|
62
|
+
"@opentelemetry/core": "^3.1.1",
|
|
63
|
+
"@opentelemetry/exporter-logs-otlp-http": "^0.301.2",
|
|
64
|
+
"@opentelemetry/exporter-logs-otlp-proto": "^0.301.2",
|
|
65
|
+
"@opentelemetry/exporter-metrics-otlp-http": "^0.301.2",
|
|
66
|
+
"@opentelemetry/exporter-metrics-otlp-proto": "^0.301.2",
|
|
67
|
+
"@opentelemetry/exporter-trace-otlp-http": "^0.301.2",
|
|
68
|
+
"@opentelemetry/exporter-trace-otlp-proto": "^0.301.2",
|
|
69
|
+
"@opentelemetry/resources": "^3.1.1",
|
|
70
|
+
"@opentelemetry/sdk-logs": "^3.1.1",
|
|
71
|
+
"@opentelemetry/sdk-metrics": "^3.1.1",
|
|
72
|
+
"@opentelemetry/sdk-trace": "^3.1.1",
|
|
73
|
+
"@opentelemetry/semantic-conventions": "^1.40.0"
|
|
74
|
+
},
|
|
75
|
+
"devDependencies": {
|
|
76
|
+
"@mark1russell7/cue": "^2.0.0",
|
|
77
|
+
"@types/node": "^26.6.5",
|
|
78
|
+
"@vitest/coverage-v8": "^4.1.12",
|
|
79
|
+
"typescript": "^5.9.0",
|
|
80
|
+
"vitest": "^4.1.12"
|
|
81
|
+
},
|
|
82
|
+
"scripts": {
|
|
83
|
+
"build": "tsc -p tsconfig.json",
|
|
84
|
+
"test": "vitest run",
|
|
85
|
+
"test:watch": "vitest",
|
|
86
|
+
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.test.json",
|
|
87
|
+
"start": "node src/main.ts"
|
|
88
|
+
}
|
|
6
89
|
}
|
package/src/api.ts
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
|
|
2
|
+
import { gunzip } from "node:zlib";
|
|
3
|
+
import { promisify } from "node:util";
|
|
4
|
+
import type { ServiceBuilder } from "@mark1russell7/service";
|
|
5
|
+
import { handle, httpTransport, pathOf, type RequestHandler } from "@mark1russell7/service/http";
|
|
6
|
+
import { logRows, OtlpShapeError, pointRows, spanRows, type LogsExport, type MetricsExport, type TracesExport } from "./otlp.ts";
|
|
7
|
+
import { errors, services, slowest, trace, TRACE_ID, windowProblems, type Window } from "./query.ts";
|
|
8
|
+
import type { Rows, Store } from "./store.ts";
|
|
9
|
+
|
|
10
|
+
const unzip = promisify(gunzip);
|
|
11
|
+
|
|
12
|
+
/** These are the options of the API of the service. */
|
|
13
|
+
export interface ApiOptions {
|
|
14
|
+
/** This number is the port of the API. */
|
|
15
|
+
readonly port: number;
|
|
16
|
+
/** This function gives the store. It throws before the store opens. */
|
|
17
|
+
readonly store: () => Store;
|
|
18
|
+
/** This function gives the time in milliseconds since the epoch. The default is `Date.now`. */
|
|
19
|
+
readonly now?: (() => number) | undefined;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** The most bytes of the body of one export, after gzip: 8 MiB */
|
|
23
|
+
export const MAX_BODY_BYTES: number = 8 * 1024 * 1024;
|
|
24
|
+
|
|
25
|
+
/** The paths of the OTLP/HTTP receiver, and the rows of each body */
|
|
26
|
+
const RECEIVERS: Readonly<Record<string, (body: unknown) => Rows>> = {
|
|
27
|
+
"/v1/traces": (body) => ({ spans: spanRows(body as TracesExport) }),
|
|
28
|
+
"/v1/logs": (body) => ({ logs: logRows(body as LogsExport) }),
|
|
29
|
+
"/v1/metrics": (body) => ({ points: pointRows(body as MetricsExport) }),
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** The window of a query without `since`: the last hour */
|
|
33
|
+
export const DEFAULT_WINDOW_MS: number = 60 * 60 * 1000;
|
|
34
|
+
/** The most rows of a query without `limit` */
|
|
35
|
+
export const DEFAULT_LIMIT = 50;
|
|
36
|
+
|
|
37
|
+
/** The routes of the queries. Each one is idempotent. */
|
|
38
|
+
export const QUERY_ROUTES = ["GET /api/slowest", "GET /api/errors", "GET /api/services", "GET /api/trace", "GET /api/stats"] as const;
|
|
39
|
+
|
|
40
|
+
const s = (value: number) => ({ value, unit: "s" });
|
|
41
|
+
|
|
42
|
+
const reply = (res: ServerResponse, status: number, body: unknown): true => {
|
|
43
|
+
const text = JSON.stringify(body);
|
|
44
|
+
res.writeHead(status, { "content-type": "application/json", "content-length": Buffer.byteLength(text) });
|
|
45
|
+
res.end(text);
|
|
46
|
+
return true;
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
class TooLargeError extends Error {}
|
|
50
|
+
|
|
51
|
+
/** The most bytes that the receiver reads and drops after a refusal. Past it, the receiver closes the connection. */
|
|
52
|
+
export const MAX_DISCARD_BYTES: number = 8 * MAX_BODY_BYTES;
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* This function reads the rest of a body and drops it, up to `MAX_DISCARD_BYTES`. Thus the client reads the refusal
|
|
56
|
+
* before the connection closes, and it does not get a reset. Past that size, it destroys the connection.
|
|
57
|
+
*/
|
|
58
|
+
const discard = (req: IncomingMessage, already = 0): Promise<void> =>
|
|
59
|
+
new Promise((resolve) => {
|
|
60
|
+
if (req.readableEnded) return resolve();
|
|
61
|
+
let size = already;
|
|
62
|
+
req.removeAllListeners("data");
|
|
63
|
+
req.on("data", (part: Buffer) => {
|
|
64
|
+
size += part.length;
|
|
65
|
+
if (size > MAX_DISCARD_BYTES) {
|
|
66
|
+
req.destroy();
|
|
67
|
+
resolve();
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
req.once("end", () => resolve());
|
|
71
|
+
req.once("close", () => resolve());
|
|
72
|
+
req.once("error", () => resolve());
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
/** This function reads a body up to `MAX_BODY_BYTES`. Past that size, it drops the rest and rejects with a `TooLargeError`. */
|
|
76
|
+
const readBody = (req: IncomingMessage): Promise<Buffer> =>
|
|
77
|
+
new Promise((resolve, reject) => {
|
|
78
|
+
const declared = Number(req.headers["content-length"] ?? 0);
|
|
79
|
+
if (declared > MAX_DISCARD_BYTES) {
|
|
80
|
+
req.destroy();
|
|
81
|
+
return reject(new TooLargeError());
|
|
82
|
+
}
|
|
83
|
+
if (declared > MAX_BODY_BYTES) return void discard(req).then(() => reject(new TooLargeError()));
|
|
84
|
+
const parts: Buffer[] = [];
|
|
85
|
+
let size = 0;
|
|
86
|
+
const onData = (part: Buffer): void => {
|
|
87
|
+
size += part.length;
|
|
88
|
+
if (size <= MAX_BODY_BYTES) return void parts.push(part);
|
|
89
|
+
req.off("end", onEnd);
|
|
90
|
+
void discard(req, size).then(() => reject(new TooLargeError()));
|
|
91
|
+
};
|
|
92
|
+
const onEnd = (): void => resolve(Buffer.concat(parts));
|
|
93
|
+
req.on("data", onData);
|
|
94
|
+
req.once("end", onEnd);
|
|
95
|
+
req.once("error", reject);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* This function gives the handler of the OTLP/HTTP receiver: `POST /v1/traces`, `/v1/logs` and `/v1/metrics` with a
|
|
100
|
+
* body of OTLP JSON, with gzip or without it. It answers 415 to another type, 413 to a large body and 400 to a body
|
|
101
|
+
* that is not OTLP JSON. The handler writes its own status, so it is a mount of the transport, not a route of `handle`.
|
|
102
|
+
*/
|
|
103
|
+
export const receiver = (store: () => Store): RequestHandler => {
|
|
104
|
+
const handler = async (req: IncomingMessage, res: ServerResponse): Promise<boolean> => {
|
|
105
|
+
const toRows = req.method === "POST" ? RECEIVERS[pathOf(req.url)] : undefined;
|
|
106
|
+
if (toRows === undefined) return false;
|
|
107
|
+
const type = String(req.headers["content-type"] ?? "").split(";")[0]?.trim().toLowerCase();
|
|
108
|
+
if (type !== "application/json") {
|
|
109
|
+
await discard(req);
|
|
110
|
+
return reply(res, 415, { error: "the sink takes only OTLP JSON. Set OTEL_EXPORTER_OTLP_PROTOCOL=http/json in the sender." });
|
|
111
|
+
}
|
|
112
|
+
const encoding = String(req.headers["content-encoding"] ?? "identity").toLowerCase();
|
|
113
|
+
if (encoding !== "identity" && encoding !== "gzip") {
|
|
114
|
+
await discard(req);
|
|
115
|
+
return reply(res, 415, { error: `the sink takes no content encoding ${encoding}: only gzip or none` });
|
|
116
|
+
}
|
|
117
|
+
let rows: Rows;
|
|
118
|
+
try {
|
|
119
|
+
const raw = await readBody(req);
|
|
120
|
+
const text = encoding === "gzip" ? await unzip(raw, { maxOutputLength: MAX_BODY_BYTES }) : raw;
|
|
121
|
+
rows = toRows(JSON.parse(text.toString("utf8")) as unknown);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (error instanceof TooLargeError || (error as { code?: unknown }).code === "ERR_BUFFER_TOO_LARGE")
|
|
124
|
+
return reply(res, 413, { error: `the body is larger than ${MAX_BODY_BYTES} bytes` });
|
|
125
|
+
if (error instanceof SyntaxError || error instanceof OtlpShapeError || (error as { code?: unknown }).code === "Z_DATA_ERROR")
|
|
126
|
+
return reply(res, 400, { error: error instanceof Error ? error.message : String(error) });
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
store().insert(rows);
|
|
130
|
+
// The success of OTLP/HTTP JSON: an empty response message, thus no partial success
|
|
131
|
+
return reply(res, 200, {});
|
|
132
|
+
};
|
|
133
|
+
return handler;
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
/** This function gives the window of a query from the query string of its target. */
|
|
137
|
+
export const windowOf = (url: string | undefined, nowMs: number): Window => {
|
|
138
|
+
const query = new URL(url ?? "/", "http://sink").searchParams;
|
|
139
|
+
const since = query.get("since");
|
|
140
|
+
const limit = query.get("limit");
|
|
141
|
+
const service = query.get("service");
|
|
142
|
+
return {
|
|
143
|
+
sinceMs: since === null ? nowMs - DEFAULT_WINDOW_MS : Number(since),
|
|
144
|
+
limit: limit === null ? DEFAULT_LIMIT : Number(limit),
|
|
145
|
+
...(service === null || service === "" ? {} : { service }),
|
|
146
|
+
};
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
const traceIdOf = (url: string | undefined): string => new URL(url ?? "/", "http://sink").searchParams.get("id")?.toLowerCase() ?? "";
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* This function gives the handler that answers 400 to a query with bad parameters. It gives false for each other
|
|
153
|
+
* request, so the next handler gets it.
|
|
154
|
+
*/
|
|
155
|
+
const queryCheck = (now: () => number): RequestHandler => {
|
|
156
|
+
const handler = (req: IncomingMessage, res: ServerResponse): boolean => {
|
|
157
|
+
if (req.method !== "GET") return false;
|
|
158
|
+
const path = pathOf(req.url);
|
|
159
|
+
if (!QUERY_ROUTES.includes(`GET ${path}` as (typeof QUERY_ROUTES)[number])) return false;
|
|
160
|
+
const problems = path === "/api/trace" ? (TRACE_ID.test(traceIdOf(req.url)) ? [] : ["id must be a trace id of 32 hex digits"]) : windowProblems(windowOf(req.url, now()));
|
|
161
|
+
return problems.length === 0 ? false : reply(res, 400, { problems });
|
|
162
|
+
};
|
|
163
|
+
return handler;
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* This function gives the API to the service of the entry: an HTTP server with the OTLP/HTTP receiver and the
|
|
168
|
+
* queries. The API is a component. It does not start the server, and it does not use `run()`.
|
|
169
|
+
*/
|
|
170
|
+
export const attachApi = (svc: ServiceBuilder, options: ApiOptions): ServiceBuilder => {
|
|
171
|
+
const now = options.now ?? Date.now;
|
|
172
|
+
const store = options.store;
|
|
173
|
+
// The transport has no defaults: the idle close, the sweep of idle connections and the Retry-After of each 503.
|
|
174
|
+
const http = httpTransport(
|
|
175
|
+
createServer(),
|
|
176
|
+
{ server_idle_close: s(65), server_idle_sweep_interval: s(1), server_retry_after: s(1) },
|
|
177
|
+
{ listen: { port: options.port } },
|
|
178
|
+
);
|
|
179
|
+
http.mount(receiver(store));
|
|
180
|
+
http.mount(queryCheck(now));
|
|
181
|
+
// Each query goes through the service. Thus the drain waits for it, and the shutdown can cut it.
|
|
182
|
+
http.mount(handle("api", "GET /api/slowest", (req) => slowest(store().db, windowOf(req.url, now()))));
|
|
183
|
+
http.mount(handle("api", "GET /api/errors", (req) => errors(store().db, windowOf(req.url, now()))));
|
|
184
|
+
http.mount(handle("api", "GET /api/services", (req) => services(store().db, windowOf(req.url, now()))));
|
|
185
|
+
http.mount(handle("api", "GET /api/trace", (req) => trace(store().db, traceIdOf(req.url))));
|
|
186
|
+
http.mount(
|
|
187
|
+
handle("api", "GET /api/stats", () => {
|
|
188
|
+
const opened = store();
|
|
189
|
+
return { sizes: opened.sizes(), fileBytes: opened.fileBytes(), rules: opened.rules };
|
|
190
|
+
}),
|
|
191
|
+
);
|
|
192
|
+
const api = svc.controller("api").requires("store");
|
|
193
|
+
for (const route of QUERY_ROUTES) api.route(route, { idempotent: true });
|
|
194
|
+
return svc.server("http", http.knobs, http);
|
|
195
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { kubernetes, localDev, service, workerLoop } from "@mark1russell7/service";
|
|
2
|
+
import type { Profile, ServiceBuilder } from "@mark1russell7/service";
|
|
3
|
+
import { probeServer } from "@mark1russell7/service/http";
|
|
4
|
+
import { attachApi } from "./api.ts";
|
|
5
|
+
import type { RetentionRules } from "./retention.ts";
|
|
6
|
+
import { openStore, type Store } from "./store.ts";
|
|
7
|
+
|
|
8
|
+
export { attachApi, receiver, windowOf, MAX_BODY_BYTES, QUERY_ROUTES, type ApiOptions } from "./api.ts";
|
|
9
|
+
export * from "./otlp.ts";
|
|
10
|
+
export * from "./query.ts";
|
|
11
|
+
export * from "./retention.ts";
|
|
12
|
+
export * from "./store.ts";
|
|
13
|
+
|
|
14
|
+
const s = (value: number) => ({ value, unit: "s" });
|
|
15
|
+
const count = (value: number) => ({ value, unit: "count" });
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* These are the profiles of the shutdown, by name. `local` is for the computer of a developer.
|
|
19
|
+
* `pod` is for a pod of Kubernetes with a grace of 30 s and no preStop hook. Make `grace` equal to
|
|
20
|
+
* the `terminationGracePeriodSeconds` of the pod.
|
|
21
|
+
*/
|
|
22
|
+
export const PROFILES: Readonly<Record<string, Profile>> = {
|
|
23
|
+
local: localDev,
|
|
24
|
+
pod: kubernetes({ grace: s(30), preStop: s(0) }),
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* This function tells if an OTLP endpoint is the receiver of this sink. A sink that exports its own spans to itself
|
|
29
|
+
* makes new spans at each export, without an end.
|
|
30
|
+
*/
|
|
31
|
+
export const isOwnEndpoint = (endpoint: string | undefined, port: number): boolean => {
|
|
32
|
+
if (endpoint === undefined || endpoint === "") return false;
|
|
33
|
+
let url: URL;
|
|
34
|
+
try {
|
|
35
|
+
url = new URL(endpoint);
|
|
36
|
+
} catch {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
const local = ["localhost", "127.0.0.1", "[::1]", "0.0.0.0"].includes(url.hostname);
|
|
40
|
+
const target = url.port === "" ? (url.protocol === "https:" ? 443 : 80) : Number(url.port);
|
|
41
|
+
return local && target === port;
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
/** The most deletes of one iteration of the retention worker. Each delete is one transaction of at most 5000 rows. */
|
|
45
|
+
export const PRUNE_BATCHES = 20;
|
|
46
|
+
|
|
47
|
+
/** These are the options of the service. */
|
|
48
|
+
export interface Options {
|
|
49
|
+
/** This number is the port of the API. */
|
|
50
|
+
readonly port: number;
|
|
51
|
+
/** This number is the port of the probes: `/startup`, `/readiness`, `/liveness` and `/report`. */
|
|
52
|
+
readonly probePort: number;
|
|
53
|
+
/** This profile gives the phases of the shutdown and the effect of a second signal. */
|
|
54
|
+
readonly profile: Profile;
|
|
55
|
+
/** This path is the SQLite file of the store, or `:memory:`. */
|
|
56
|
+
readonly path: string;
|
|
57
|
+
/** These rules give the age and the size of each signal. The default is `DEFAULT_RETENTION`. */
|
|
58
|
+
readonly rules?: RetentionRules | undefined;
|
|
59
|
+
/** This time is the sleep of the retention worker between two prunes, in seconds. The default is 60. */
|
|
60
|
+
readonly pruneEverySeconds?: number | undefined;
|
|
61
|
+
/** This function gives the time in milliseconds since the epoch. The default is `Date.now`. */
|
|
62
|
+
readonly now?: (() => number) | undefined;
|
|
63
|
+
/** This function gets each failure of a prune. The default does nothing: the next prune tries again after its backoff. */
|
|
64
|
+
readonly onPruneError?: ((error: unknown, failures: number) => void) | undefined;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* This function declares the one service of the process. It starts nothing. `describe()` gives the
|
|
69
|
+
* declaration as data, and `lint()` examines it. Only the entry (`main.ts`) uses `run()`.
|
|
70
|
+
* The store is a dependency: it opens before the servers start, and it closes after they stop.
|
|
71
|
+
*/
|
|
72
|
+
export const declare = (options: Options): ServiceBuilder => {
|
|
73
|
+
const now = options.now ?? Date.now;
|
|
74
|
+
let opened: Store | undefined;
|
|
75
|
+
const store = (): Store => {
|
|
76
|
+
if (opened === undefined) throw new Error("the store is not open");
|
|
77
|
+
return opened;
|
|
78
|
+
};
|
|
79
|
+
// The prune of the store, on a loop. A throw is a failure, and the loop waits its backoff. Each iteration does at most
|
|
80
|
+
// PRUNE_BATCHES deletes, and gives "more" when the prune is not done. Thus the intake goes on between two parts, and
|
|
81
|
+
// each part ends in its bound, before the cap of the drain of each profile.
|
|
82
|
+
const retention = workerLoop(
|
|
83
|
+
{
|
|
84
|
+
worker_sleep: s(options.pruneEverySeconds ?? 60),
|
|
85
|
+
unit_processing_time: s(3),
|
|
86
|
+
retry_base: s(5),
|
|
87
|
+
retry_cap: s(300),
|
|
88
|
+
close_bound: s(0.5),
|
|
89
|
+
concurrency: count(1),
|
|
90
|
+
},
|
|
91
|
+
{ iteration: () => (store().prune(now(), PRUNE_BATCHES).done ? undefined : "more"), onError: options.onPruneError },
|
|
92
|
+
);
|
|
93
|
+
const svc = service("otel-sink").dependency(
|
|
94
|
+
"store",
|
|
95
|
+
{ system: null, knobs: {}, operations: {} },
|
|
96
|
+
{
|
|
97
|
+
connect: () => {
|
|
98
|
+
opened = openStore(options.path, { rules: options.rules });
|
|
99
|
+
},
|
|
100
|
+
close: () => {
|
|
101
|
+
opened?.close();
|
|
102
|
+
opened = undefined;
|
|
103
|
+
},
|
|
104
|
+
},
|
|
105
|
+
);
|
|
106
|
+
return (
|
|
107
|
+
attachApi(svc, { port: options.port, store, now })
|
|
108
|
+
.worker("retention", retention.knobs, retention)
|
|
109
|
+
// The probes have a port of their own. Thus they answer through the whole shutdown.
|
|
110
|
+
.healthServer(probeServer({ port: options.probePort, server_retry_after: s(1) }))
|
|
111
|
+
// The policies apply to the checks of the service. Add a check with `check(check, run)`.
|
|
112
|
+
.readiness({ type: "debounce", interval: s(5), failAfter: 3, recoverAfter: 1 })
|
|
113
|
+
.liveness({ type: "window", failAfter: s(45) })
|
|
114
|
+
.startup(s(30))
|
|
115
|
+
.profile(options.profile)
|
|
116
|
+
);
|
|
117
|
+
};
|
package/src/main.ts
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* This file is the entry of the process, and the only file that uses `run()`. The lifecycle owns the
|
|
4
|
+
* signals of the process. After SIGTERM or Ctrl-C, the service stops in its phases, and the process
|
|
5
|
+
* exits with 0 or 1.
|
|
6
|
+
*
|
|
7
|
+
* The environment gives `PORT` (4318), `PROBE_PORT` (9090), `SERVICE_PROFILE` (`local`) and `SINK_DB`
|
|
8
|
+
* (`otel-sink.db` in the home folder). The value in parentheses is the value without the variable.
|
|
9
|
+
*
|
|
10
|
+
* The run starts the context of otel-ts, so each log and each span of a request has its context. With a value in
|
|
11
|
+
* `OTEL_EXPORTER_OTLP_ENDPOINT`, the run also exports the spans.
|
|
12
|
+
*/
|
|
13
|
+
import { homedir } from "node:os";
|
|
14
|
+
import { join } from "node:path";
|
|
15
|
+
import { PROFILES, declare, isOwnEndpoint } from "./index.ts";
|
|
16
|
+
|
|
17
|
+
/** This function gives a port from the environment, or the fallback when the variable is not set. */
|
|
18
|
+
const port = (name: string, fallback: number): number => {
|
|
19
|
+
const text = process.env[name];
|
|
20
|
+
const value = text === undefined ? fallback : Number(text);
|
|
21
|
+
if (!Number.isInteger(value) || value < 0 || value > 65535) throw new Error(`${name} is not a port: ${text}`);
|
|
22
|
+
return value;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const name = process.env["SERVICE_PROFILE"] ?? "local";
|
|
26
|
+
const profile = PROFILES[name];
|
|
27
|
+
if (profile === undefined) throw new Error(`SERVICE_PROFILE is "${name}". The profiles are: ${Object.keys(PROFILES).join(", ")}.`);
|
|
28
|
+
|
|
29
|
+
const path = process.env["SINK_DB"] ?? join(homedir(), "otel-sink.db");
|
|
30
|
+
|
|
31
|
+
const api = port("PORT", 4318);
|
|
32
|
+
for (const name of ["OTEL_EXPORTER_OTLP_ENDPOINT", "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", "OTEL_EXPORTER_OTLP_LOGS_ENDPOINT", "OTEL_EXPORTER_OTLP_METRICS_ENDPOINT"])
|
|
33
|
+
if (isOwnEndpoint(process.env[name], api)) throw new Error(`${name} is the receiver of this sink. The sink must not export its own telemetry to itself.`);
|
|
34
|
+
|
|
35
|
+
await declare({ port: api, probePort: port("PROBE_PORT", 9090), profile, path }).run();
|
package/src/otlp.ts
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
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
|
+
|
|
9
|
+
/** A value of an attribute, in the JSON of OTLP */
|
|
10
|
+
export interface AnyValue {
|
|
11
|
+
readonly stringValue?: string;
|
|
12
|
+
readonly boolValue?: boolean;
|
|
13
|
+
readonly intValue?: string | number;
|
|
14
|
+
readonly doubleValue?: number;
|
|
15
|
+
readonly arrayValue?: { readonly values?: readonly AnyValue[] };
|
|
16
|
+
readonly kvlistValue?: { readonly values?: readonly KeyValue[] };
|
|
17
|
+
readonly bytesValue?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** An attribute, in the JSON of OTLP */
|
|
21
|
+
export interface KeyValue {
|
|
22
|
+
readonly key: string;
|
|
23
|
+
readonly value?: AnyValue;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** A resource, in the JSON of OTLP */
|
|
27
|
+
export interface OtlpResource {
|
|
28
|
+
readonly attributes?: readonly KeyValue[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A time in nanoseconds since the epoch, as OTLP JSON gives it */
|
|
32
|
+
export type Nanos = string | number | undefined;
|
|
33
|
+
|
|
34
|
+
/** A span, in the JSON of OTLP */
|
|
35
|
+
export interface OtlpSpan {
|
|
36
|
+
readonly traceId: string;
|
|
37
|
+
readonly spanId: string;
|
|
38
|
+
readonly parentSpanId?: string;
|
|
39
|
+
readonly name: string;
|
|
40
|
+
readonly kind?: number;
|
|
41
|
+
readonly startTimeUnixNano?: Nanos;
|
|
42
|
+
readonly endTimeUnixNano?: Nanos;
|
|
43
|
+
readonly attributes?: readonly KeyValue[];
|
|
44
|
+
readonly status?: { readonly code?: number; readonly message?: string };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** A log record, in the JSON of OTLP */
|
|
48
|
+
export interface OtlpLogRecord {
|
|
49
|
+
readonly timeUnixNano?: Nanos;
|
|
50
|
+
readonly observedTimeUnixNano?: Nanos;
|
|
51
|
+
readonly severityNumber?: number;
|
|
52
|
+
readonly body?: AnyValue;
|
|
53
|
+
readonly traceId?: string;
|
|
54
|
+
readonly spanId?: string;
|
|
55
|
+
readonly attributes?: readonly KeyValue[];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** A point of a sum or a gauge, in the JSON of OTLP */
|
|
59
|
+
export interface OtlpNumberPoint {
|
|
60
|
+
readonly timeUnixNano?: Nanos;
|
|
61
|
+
readonly attributes?: readonly KeyValue[];
|
|
62
|
+
readonly asDouble?: number;
|
|
63
|
+
readonly asInt?: string | number;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** A point of a histogram, in the JSON of OTLP */
|
|
67
|
+
export interface OtlpHistogramPoint {
|
|
68
|
+
readonly timeUnixNano?: Nanos;
|
|
69
|
+
readonly attributes?: readonly KeyValue[];
|
|
70
|
+
readonly count?: string | number;
|
|
71
|
+
readonly sum?: number;
|
|
72
|
+
readonly explicitBounds?: readonly number[];
|
|
73
|
+
readonly bucketCounts?: readonly (string | number)[];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A metric, in the JSON of OTLP. The store keeps sums, gauges and histograms. */
|
|
77
|
+
export interface OtlpMetric {
|
|
78
|
+
readonly name: string;
|
|
79
|
+
readonly sum?: { readonly dataPoints?: readonly OtlpNumberPoint[] };
|
|
80
|
+
readonly gauge?: { readonly dataPoints?: readonly OtlpNumberPoint[] };
|
|
81
|
+
readonly histogram?: { readonly dataPoints?: readonly OtlpHistogramPoint[] };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The body of an export of traces, in the JSON of OTLP */
|
|
85
|
+
export interface TracesExport {
|
|
86
|
+
readonly resourceSpans?: readonly { readonly resource?: OtlpResource; readonly scopeSpans?: readonly { readonly spans?: readonly OtlpSpan[] }[] }[];
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** The body of an export of logs, in the JSON of OTLP */
|
|
90
|
+
export interface LogsExport {
|
|
91
|
+
readonly resourceLogs?: readonly { readonly resource?: OtlpResource; readonly scopeLogs?: readonly { readonly logRecords?: readonly OtlpLogRecord[] }[] }[];
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The body of an export of metrics, in the JSON of OTLP */
|
|
95
|
+
export interface MetricsExport {
|
|
96
|
+
readonly resourceMetrics?: readonly { readonly resource?: OtlpResource; readonly scopeMetrics?: readonly { readonly metrics?: readonly OtlpMetric[] }[] }[];
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The value of an attribute in the store */
|
|
100
|
+
export type Value = string | number | boolean | null | readonly Value[] | { readonly [key: string]: Value };
|
|
101
|
+
|
|
102
|
+
/** A span as a row of the store */
|
|
103
|
+
export interface SpanRow {
|
|
104
|
+
readonly traceId: string;
|
|
105
|
+
readonly spanId: string;
|
|
106
|
+
readonly parentId: string | null;
|
|
107
|
+
readonly service: string;
|
|
108
|
+
readonly name: string;
|
|
109
|
+
/** The kind of OTLP: 1 internal, 2 server, 3 client, 4 producer, 5 consumer, or null when it is not given */
|
|
110
|
+
readonly kind: number | null;
|
|
111
|
+
readonly startNs: bigint;
|
|
112
|
+
readonly endNs: bigint;
|
|
113
|
+
/** The status code of OTLP: 0 unset, 1 ok, 2 error */
|
|
114
|
+
readonly status: number;
|
|
115
|
+
/** The attributes, as JSON text */
|
|
116
|
+
readonly attributes: string;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** A log record as a row of the store */
|
|
120
|
+
export interface LogRow {
|
|
121
|
+
readonly timeNs: bigint;
|
|
122
|
+
readonly service: string;
|
|
123
|
+
readonly severity: number | null;
|
|
124
|
+
readonly body: string | null;
|
|
125
|
+
readonly traceId: string | null;
|
|
126
|
+
readonly spanId: string | null;
|
|
127
|
+
readonly attributes: string;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** A metric point as a row of the store */
|
|
131
|
+
export interface PointRow {
|
|
132
|
+
readonly timeNs: bigint;
|
|
133
|
+
readonly service: string;
|
|
134
|
+
readonly metric: string;
|
|
135
|
+
readonly attributes: string;
|
|
136
|
+
/** The value of a sum or a gauge, or the sum of a histogram */
|
|
137
|
+
readonly value: number | null;
|
|
138
|
+
/** The count and the buckets of a histogram, as JSON text, or null for a sum or a gauge */
|
|
139
|
+
readonly histogram: string | null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** The service name of a resource without `service.name`, as in the SDK of OpenTelemetry */
|
|
143
|
+
export const UNKNOWN_SERVICE = "unknown_service";
|
|
144
|
+
|
|
145
|
+
/** This error tells that a body is not an export of OTLP JSON. The receiver answers it with 400. */
|
|
146
|
+
export class OtlpShapeError extends Error {
|
|
147
|
+
override readonly name = "OtlpShapeError";
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** This function gives the value of an attribute of OTLP JSON. */
|
|
151
|
+
export const valueOf = (value: AnyValue | undefined): Value => {
|
|
152
|
+
if (value === undefined || value === null) return null;
|
|
153
|
+
if (value.stringValue !== undefined) return value.stringValue;
|
|
154
|
+
if (value.boolValue !== undefined) return value.boolValue;
|
|
155
|
+
if (value.intValue !== undefined) return Number(value.intValue);
|
|
156
|
+
if (value.doubleValue !== undefined) return value.doubleValue;
|
|
157
|
+
if (value.arrayValue !== undefined) return (value.arrayValue.values ?? []).map(valueOf);
|
|
158
|
+
if (value.kvlistValue !== undefined) return attributesOf(value.kvlistValue.values);
|
|
159
|
+
if (value.bytesValue !== undefined) return value.bytesValue;
|
|
160
|
+
return null;
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
/** This function gives the attributes of OTLP JSON as one object. */
|
|
164
|
+
export const attributesOf = (list: readonly KeyValue[] = []): { readonly [key: string]: Value } =>
|
|
165
|
+
Object.fromEntries(list.map(({ key, value }) => [key, valueOf(value)]));
|
|
166
|
+
|
|
167
|
+
const serviceOf = (resource: OtlpResource | undefined): string => {
|
|
168
|
+
const name = attributesOf(resource?.attributes)["service.name"];
|
|
169
|
+
return typeof name === "string" && name !== "" ? name : UNKNOWN_SERVICE;
|
|
170
|
+
};
|
|
171
|
+
|
|
172
|
+
const ns = (text: Nanos, what: string): bigint => {
|
|
173
|
+
if (text === undefined || text === "") return 0n;
|
|
174
|
+
try {
|
|
175
|
+
return BigInt(text);
|
|
176
|
+
} catch {
|
|
177
|
+
throw new OtlpShapeError(`${what} is not a time in nanoseconds: ${String(text)}`);
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
const HEX = /^[0-9a-f]*$/i;
|
|
182
|
+
const id = (text: string | undefined, what: string): string | null => {
|
|
183
|
+
if (text === undefined || text === "") return null;
|
|
184
|
+
if (!HEX.test(text)) throw new OtlpShapeError(`${what} is not hex: ${text}`);
|
|
185
|
+
return text.toLowerCase();
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
const list = <T>(value: readonly T[] | undefined, what: string): readonly T[] => {
|
|
189
|
+
if (value === undefined) return [];
|
|
190
|
+
if (!Array.isArray(value)) throw new OtlpShapeError(`${what} is not a list`);
|
|
191
|
+
return value;
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
/** This function gives a row for each span of an export of traces. */
|
|
195
|
+
export const spanRows = (body: TracesExport): SpanRow[] => {
|
|
196
|
+
const rows: SpanRow[] = [];
|
|
197
|
+
for (const { resource, scopeSpans } of list(body.resourceSpans, "resourceSpans")) {
|
|
198
|
+
const service = serviceOf(resource);
|
|
199
|
+
for (const { spans } of list(scopeSpans, "scopeSpans"))
|
|
200
|
+
for (const span of list(spans, "spans")) {
|
|
201
|
+
const traceId = id(span.traceId, "traceId");
|
|
202
|
+
const spanId = id(span.spanId, "spanId");
|
|
203
|
+
if (traceId === null || spanId === null) throw new OtlpShapeError("a span has no traceId or no spanId");
|
|
204
|
+
rows.push({
|
|
205
|
+
traceId,
|
|
206
|
+
spanId,
|
|
207
|
+
parentId: id(span.parentSpanId, "parentSpanId"),
|
|
208
|
+
service,
|
|
209
|
+
name: String(span.name ?? ""),
|
|
210
|
+
kind: span.kind ?? null,
|
|
211
|
+
startNs: ns(span.startTimeUnixNano, "startTimeUnixNano"),
|
|
212
|
+
endNs: ns(span.endTimeUnixNano, "endTimeUnixNano"),
|
|
213
|
+
status: span.status?.code ?? 0,
|
|
214
|
+
attributes: JSON.stringify(attributesOf(span.attributes)),
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return rows;
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
/** This function gives a row for each log record of an export of logs. A record without a time gets its observed time. */
|
|
222
|
+
export const logRows = (body: LogsExport): LogRow[] => {
|
|
223
|
+
const rows: LogRow[] = [];
|
|
224
|
+
for (const { resource, scopeLogs } of list(body.resourceLogs, "resourceLogs")) {
|
|
225
|
+
const service = serviceOf(resource);
|
|
226
|
+
for (const { logRecords } of list(scopeLogs, "scopeLogs"))
|
|
227
|
+
for (const log of list(logRecords, "logRecords")) {
|
|
228
|
+
const text = valueOf(log.body);
|
|
229
|
+
const time = ns(log.timeUnixNano, "timeUnixNano");
|
|
230
|
+
rows.push({
|
|
231
|
+
timeNs: time === 0n ? ns(log.observedTimeUnixNano, "observedTimeUnixNano") : time,
|
|
232
|
+
service,
|
|
233
|
+
severity: log.severityNumber ?? null,
|
|
234
|
+
body: text === null ? null : typeof text === "string" ? text : JSON.stringify(text),
|
|
235
|
+
traceId: id(log.traceId, "traceId"),
|
|
236
|
+
spanId: id(log.spanId, "spanId"),
|
|
237
|
+
attributes: JSON.stringify(attributesOf(log.attributes)),
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
return rows;
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
/** This function gives a row for each point of a sum, a gauge or a histogram of an export of metrics. */
|
|
245
|
+
export const pointRows = (body: MetricsExport): PointRow[] => {
|
|
246
|
+
const rows: PointRow[] = [];
|
|
247
|
+
for (const { resource, scopeMetrics } of list(body.resourceMetrics, "resourceMetrics")) {
|
|
248
|
+
const service = serviceOf(resource);
|
|
249
|
+
for (const { metrics } of list(scopeMetrics, "scopeMetrics"))
|
|
250
|
+
for (const metric of list(metrics, "metrics")) {
|
|
251
|
+
const numbers = [...list(metric.sum?.dataPoints, "sum.dataPoints"), ...list(metric.gauge?.dataPoints, "gauge.dataPoints")];
|
|
252
|
+
for (const point of numbers)
|
|
253
|
+
rows.push({
|
|
254
|
+
timeNs: ns(point.timeUnixNano, "timeUnixNano"),
|
|
255
|
+
service,
|
|
256
|
+
metric: metric.name,
|
|
257
|
+
attributes: JSON.stringify(attributesOf(point.attributes)),
|
|
258
|
+
value: point.asDouble ?? (point.asInt === undefined ? null : Number(point.asInt)),
|
|
259
|
+
histogram: null,
|
|
260
|
+
});
|
|
261
|
+
for (const point of list(metric.histogram?.dataPoints, "histogram.dataPoints"))
|
|
262
|
+
rows.push({
|
|
263
|
+
timeNs: ns(point.timeUnixNano, "timeUnixNano"),
|
|
264
|
+
service,
|
|
265
|
+
metric: metric.name,
|
|
266
|
+
attributes: JSON.stringify(attributesOf(point.attributes)),
|
|
267
|
+
value: point.sum ?? null,
|
|
268
|
+
histogram: JSON.stringify({ count: Number(point.count ?? 0), explicitBounds: point.explicitBounds ?? [], bucketCounts: (point.bucketCounts ?? []).map(Number) }),
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return rows;
|
|
273
|
+
};
|
package/src/query.ts
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
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 { readTransaction } from "@mark1russell7/sqlite";
|
|
7
|
+
import type { Value } from "./otlp.ts";
|
|
8
|
+
|
|
9
|
+
/** A span in a result */
|
|
10
|
+
export interface SpanView {
|
|
11
|
+
readonly traceId: string;
|
|
12
|
+
readonly spanId: string;
|
|
13
|
+
readonly parentId: string | null;
|
|
14
|
+
readonly service: string;
|
|
15
|
+
readonly name: string;
|
|
16
|
+
readonly kind: number | null;
|
|
17
|
+
readonly startMs: number;
|
|
18
|
+
readonly durationMs: number;
|
|
19
|
+
readonly status: number;
|
|
20
|
+
readonly attributes: { readonly [key: string]: Value };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A log record in a result */
|
|
24
|
+
export interface LogView {
|
|
25
|
+
readonly timeMs: number;
|
|
26
|
+
readonly service: string;
|
|
27
|
+
readonly severity: number | null;
|
|
28
|
+
readonly body: string | null;
|
|
29
|
+
readonly traceId: string | null;
|
|
30
|
+
readonly spanId: string | null;
|
|
31
|
+
readonly attributes: { 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
|
+
|
|
44
|
+
/** The window and the size of a query */
|
|
45
|
+
export interface Window {
|
|
46
|
+
/** The start of the window, in milliseconds since the epoch */
|
|
47
|
+
readonly sinceMs: number;
|
|
48
|
+
/** The most rows of a result, from 1 up to `MAX_LIMIT` */
|
|
49
|
+
readonly limit: number;
|
|
50
|
+
/** Only the rows of this service, when it is given */
|
|
51
|
+
readonly service?: string | undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The most rows of one result */
|
|
55
|
+
export const MAX_LIMIT = 1000;
|
|
56
|
+
|
|
57
|
+
/** The severity number of OTLP from which a log record is an error */
|
|
58
|
+
export const ERROR_SEVERITY = 17;
|
|
59
|
+
|
|
60
|
+
const SPAN_COLUMNS = `trace_id AS traceId, span_id AS spanId, parent_id AS parentId, service, name, kind,
|
|
61
|
+
start_ns / 1000000 AS startMs, (end_ns - start_ns) / 1e6 AS durationMs, status, attributes`;
|
|
62
|
+
const LOG_COLUMNS = "time_ns / 1000000 AS timeMs, service, severity, body, trace_id AS traceId, span_id AS spanId, attributes";
|
|
63
|
+
|
|
64
|
+
type Row = Record<string, unknown>;
|
|
65
|
+
|
|
66
|
+
const spanOf = (row: Row): SpanView => ({
|
|
67
|
+
traceId: String(row["traceId"]),
|
|
68
|
+
spanId: String(row["spanId"]),
|
|
69
|
+
parentId: row["parentId"] === null ? null : String(row["parentId"]),
|
|
70
|
+
service: String(row["service"]),
|
|
71
|
+
name: String(row["name"]),
|
|
72
|
+
kind: row["kind"] === null ? null : Number(row["kind"]),
|
|
73
|
+
startMs: Number(row["startMs"]),
|
|
74
|
+
durationMs: Number(row["durationMs"]),
|
|
75
|
+
status: Number(row["status"]),
|
|
76
|
+
attributes: JSON.parse(String(row["attributes"])) as SpanView["attributes"],
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
const logOf = (row: Row): LogView => ({
|
|
80
|
+
timeMs: Number(row["timeMs"]),
|
|
81
|
+
service: String(row["service"]),
|
|
82
|
+
severity: row["severity"] === null ? null : Number(row["severity"]),
|
|
83
|
+
body: row["body"] === null ? null : String(row["body"]),
|
|
84
|
+
traceId: row["traceId"] === null ? null : String(row["traceId"]),
|
|
85
|
+
spanId: row["spanId"] === null ? null : String(row["spanId"]),
|
|
86
|
+
attributes: JSON.parse(String(row["attributes"])) as LogView["attributes"],
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
/** This function gives the problems of a window. The receiver answers a window with problems with 400. */
|
|
90
|
+
export const windowProblems = (window: Window): string[] => {
|
|
91
|
+
const problems: string[] = [];
|
|
92
|
+
if (!Number.isFinite(window.sinceMs) || window.sinceMs < 0) problems.push("since must be a time in milliseconds from 0");
|
|
93
|
+
if (!Number.isSafeInteger(window.limit) || window.limit < 1 || window.limit > MAX_LIMIT) problems.push(`limit must be a whole number from 1 to ${MAX_LIMIT}`);
|
|
94
|
+
return problems;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const sinceNs = (window: Window): bigint => BigInt(Math.floor(window.sinceMs)) * 1_000_000n;
|
|
98
|
+
const serviceFilter = (window: Window, column = "service"): string => (window.service === undefined ? "" : ` AND ${column} = ?`);
|
|
99
|
+
const serviceParam = (window: Window): string[] => (window.service === undefined ? [] : [window.service]);
|
|
100
|
+
|
|
101
|
+
/** This function gives the slowest spans that start in the window, the slowest first. */
|
|
102
|
+
export const slowest = (db: DatabaseSync, window: Window): SpanView[] =>
|
|
103
|
+
db
|
|
104
|
+
.prepare(`SELECT ${SPAN_COLUMNS} FROM spans WHERE start_ns >= ?${serviceFilter(window)} ORDER BY end_ns - start_ns DESC LIMIT ?`)
|
|
105
|
+
.all(sinceNs(window), ...serviceParam(window), window.limit)
|
|
106
|
+
.map(spanOf);
|
|
107
|
+
|
|
108
|
+
/** This function gives the spans with the status error and the error logs of the window, the newest first. */
|
|
109
|
+
export const errors = (db: DatabaseSync, window: Window): { readonly spans: SpanView[]; readonly logs: LogView[] } =>
|
|
110
|
+
readTransaction(db, () => ({
|
|
111
|
+
spans: db
|
|
112
|
+
.prepare(`SELECT ${SPAN_COLUMNS} FROM spans WHERE status = 2 AND start_ns >= ?${serviceFilter(window)} ORDER BY start_ns DESC LIMIT ?`)
|
|
113
|
+
.all(sinceNs(window), ...serviceParam(window), window.limit)
|
|
114
|
+
.map(spanOf),
|
|
115
|
+
logs: db
|
|
116
|
+
.prepare(`SELECT ${LOG_COLUMNS} FROM logs WHERE severity >= ${ERROR_SEVERITY} AND time_ns >= ?${serviceFilter(window)} ORDER BY time_ns DESC LIMIT ?`)
|
|
117
|
+
.all(sinceNs(window), ...serviceParam(window), window.limit)
|
|
118
|
+
.map(logOf),
|
|
119
|
+
}));
|
|
120
|
+
|
|
121
|
+
/** The pattern of a trace id: 32 hex digits */
|
|
122
|
+
export const TRACE_ID: RegExp = /^[0-9a-f]{32}$/;
|
|
123
|
+
|
|
124
|
+
/** This function gives the spans and the logs of one trace, in the order of their times. */
|
|
125
|
+
export const trace = (db: DatabaseSync, traceId: string): { readonly spans: SpanView[]; readonly logs: LogView[] } => {
|
|
126
|
+
const id = traceId.toLowerCase();
|
|
127
|
+
return readTransaction(db, () => ({
|
|
128
|
+
spans: db.prepare(`SELECT ${SPAN_COLUMNS} FROM spans WHERE trace_id = ? ORDER BY start_ns LIMIT ${MAX_LIMIT}`).all(id).map(spanOf),
|
|
129
|
+
logs: db.prepare(`SELECT ${LOG_COLUMNS} FROM logs WHERE trace_id = ? ORDER BY time_ns LIMIT ${MAX_LIMIT}`).all(id).map(logOf),
|
|
130
|
+
}));
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
/** This function gives the counts of the spans of each service in the window, the most failed spans first. */
|
|
134
|
+
export const services = (db: DatabaseSync, window: Window): ServiceView[] =>
|
|
135
|
+
db
|
|
136
|
+
.prepare(
|
|
137
|
+
`SELECT service, COUNT(*) AS spans, SUM(status = 2) AS failed, MAX(end_ns - start_ns) / 1e6 AS slowestMs
|
|
138
|
+
FROM spans WHERE start_ns >= ?${serviceFilter(window)} GROUP BY service ORDER BY failed DESC, spans DESC LIMIT ?`,
|
|
139
|
+
)
|
|
140
|
+
.all(sinceNs(window), ...serviceParam(window), window.limit)
|
|
141
|
+
.map((row) => {
|
|
142
|
+
const spans = Number(row["spans"]);
|
|
143
|
+
const failed = Number(row["failed"]);
|
|
144
|
+
return { service: String(row["service"]), spans, failed, errorRate: spans === 0 ? 0 : failed / spans, slowestMs: Number(row["slowestMs"]) };
|
|
145
|
+
});
|
package/src/retention.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
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
|
+
|
|
7
|
+
/** The three signals of the store */
|
|
8
|
+
export type Signal = "spans" | "logs" | "points";
|
|
9
|
+
|
|
10
|
+
/** The signals of the store, in a fixed order */
|
|
11
|
+
export const SIGNALS: readonly Signal[] = ["spans", "logs", "points"];
|
|
12
|
+
|
|
13
|
+
/** The rule of one signal */
|
|
14
|
+
export interface SignalRule {
|
|
15
|
+
/** The maximum age of a row, in milliseconds. The age is from the time of the row, not from its arrival. */
|
|
16
|
+
readonly maxAgeMs: number;
|
|
17
|
+
/** The maximum size of the rows of the signal, in bytes, as the store counts them */
|
|
18
|
+
readonly maxBytes: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The rules of the three signals */
|
|
22
|
+
export type RetentionRules = { readonly [signal in Signal]: SignalRule };
|
|
23
|
+
|
|
24
|
+
const MiB = 1024 * 1024;
|
|
25
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
26
|
+
|
|
27
|
+
/** The upper limit of the sum of the sizes of all signals: 1 GiB */
|
|
28
|
+
export const HARD_LIMIT_BYTES: number = 1024 * MiB;
|
|
29
|
+
|
|
30
|
+
/** The default rules: 3 days and 256 MiB for spans and logs, 7 days and 128 MiB for metric points */
|
|
31
|
+
export const DEFAULT_RETENTION: RetentionRules = {
|
|
32
|
+
spans: { maxAgeMs: 3 * DAY_MS, maxBytes: 256 * MiB },
|
|
33
|
+
logs: { maxAgeMs: 3 * DAY_MS, maxBytes: 256 * MiB },
|
|
34
|
+
points: { maxAgeMs: 7 * DAY_MS, maxBytes: 128 * MiB },
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/** This function gives the problems of a set of rules. A store refuses rules with problems. */
|
|
38
|
+
export const retentionProblems = (rules: RetentionRules): string[] => {
|
|
39
|
+
const problems: string[] = [];
|
|
40
|
+
let total = 0;
|
|
41
|
+
for (const signal of SIGNALS) {
|
|
42
|
+
const rule = rules[signal] as SignalRule | undefined;
|
|
43
|
+
if (rule === undefined) {
|
|
44
|
+
problems.push(`${signal}: no rule`);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (!Number.isFinite(rule.maxAgeMs) || rule.maxAgeMs <= 0) problems.push(`${signal}: maxAgeMs must be a positive finite number`);
|
|
48
|
+
if (!Number.isSafeInteger(rule.maxBytes) || rule.maxBytes <= 0) problems.push(`${signal}: maxBytes must be a positive whole number`);
|
|
49
|
+
else total += rule.maxBytes;
|
|
50
|
+
}
|
|
51
|
+
if (total > HARD_LIMIT_BYTES) problems.push(`the sum of maxBytes is ${total}, more than the hard limit ${HARD_LIMIT_BYTES}`);
|
|
52
|
+
return problems;
|
|
53
|
+
};
|
package/src/store.ts
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
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, type Migration } from "@mark1russell7/sqlite";
|
|
6
|
+
import type { DatabaseSync, StatementSync } from "node:sqlite";
|
|
7
|
+
import type { LogRow, PointRow, SpanRow } from "./otlp.ts";
|
|
8
|
+
import { DEFAULT_RETENTION, retentionProblems, SIGNALS, type RetentionRules, type Signal } from "./retention.ts";
|
|
9
|
+
|
|
10
|
+
/** The column of the time of each signal, in nanoseconds since the epoch */
|
|
11
|
+
export const TIME_COLUMN: { readonly [signal in Signal]: string } = { spans: "start_ns", logs: "time_ns", points: "time_ns" };
|
|
12
|
+
|
|
13
|
+
const sizeTriggers = (signal: Signal): string =>
|
|
14
|
+
`CREATE TRIGGER ${signal}_insert AFTER INSERT ON ${signal} BEGIN UPDATE sizes SET rows = rows + 1, bytes = bytes + NEW.bytes WHERE signal = '${signal}'; END;
|
|
15
|
+
CREATE TRIGGER ${signal}_delete AFTER DELETE ON ${signal} BEGIN UPDATE sizes SET rows = rows - 1, bytes = bytes - OLD.bytes WHERE signal = '${signal}'; END;`;
|
|
16
|
+
|
|
17
|
+
/** The steps of the schema. Do not change a step: add a new one. */
|
|
18
|
+
export const MIGRATIONS: readonly Migration[] = [
|
|
19
|
+
`CREATE TABLE spans (trace_id TEXT NOT NULL, span_id TEXT NOT NULL, parent_id TEXT, service TEXT NOT NULL, name TEXT NOT NULL,
|
|
20
|
+
kind INTEGER, start_ns INTEGER NOT NULL, end_ns INTEGER NOT NULL, status INTEGER NOT NULL, attributes TEXT NOT NULL, bytes INTEGER NOT NULL);
|
|
21
|
+
CREATE INDEX spans_start ON spans (start_ns);
|
|
22
|
+
CREATE INDEX spans_service_start ON spans (service, start_ns);
|
|
23
|
+
CREATE INDEX spans_trace ON spans (trace_id);
|
|
24
|
+
CREATE INDEX spans_errors ON spans (start_ns) WHERE status = 2;
|
|
25
|
+
CREATE TABLE logs (time_ns INTEGER NOT NULL, service TEXT NOT NULL, severity INTEGER, body TEXT, trace_id TEXT, span_id TEXT,
|
|
26
|
+
attributes TEXT NOT NULL, bytes INTEGER NOT NULL);
|
|
27
|
+
CREATE INDEX logs_time ON logs (time_ns);
|
|
28
|
+
CREATE INDEX logs_service_time ON logs (service, time_ns);
|
|
29
|
+
CREATE INDEX logs_trace ON logs (trace_id);
|
|
30
|
+
CREATE INDEX logs_errors ON logs (time_ns) WHERE severity >= 17;
|
|
31
|
+
CREATE TABLE points (time_ns INTEGER NOT NULL, service TEXT NOT NULL, metric TEXT NOT NULL, attributes TEXT NOT NULL,
|
|
32
|
+
value REAL, histogram TEXT, bytes INTEGER NOT NULL);
|
|
33
|
+
CREATE INDEX points_time ON points (time_ns);
|
|
34
|
+
CREATE INDEX points_metric_time ON points (metric, time_ns);
|
|
35
|
+
CREATE TABLE sizes (signal TEXT PRIMARY KEY, rows INTEGER NOT NULL, bytes INTEGER NOT NULL);
|
|
36
|
+
INSERT INTO sizes (signal, rows, bytes) VALUES ('spans', 0, 0), ('logs', 0, 0), ('points', 0, 0);
|
|
37
|
+
${SIGNALS.map(sizeTriggers).join("\n")}`,
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
/** The size of a signal in the store */
|
|
41
|
+
export interface SignalSize {
|
|
42
|
+
readonly rows: number;
|
|
43
|
+
readonly bytes: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The rows that a prune deleted for one signal: past the age, and past the size */
|
|
47
|
+
export interface SignalPrune {
|
|
48
|
+
readonly aged: number;
|
|
49
|
+
readonly capped: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The result of a prune: the rows that it deleted for each signal, and if it is done */
|
|
53
|
+
export type Pruned = { readonly [signal in Signal]: SignalPrune } & { readonly done: boolean };
|
|
54
|
+
|
|
55
|
+
/** The rows of one export */
|
|
56
|
+
export interface Rows {
|
|
57
|
+
readonly spans?: readonly SpanRow[];
|
|
58
|
+
readonly logs?: readonly LogRow[];
|
|
59
|
+
readonly points?: readonly PointRow[];
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The store of the sink */
|
|
63
|
+
export interface Store {
|
|
64
|
+
/** The connection, for the queries. Do not write through it: each write goes through the store. */
|
|
65
|
+
readonly db: DatabaseSync;
|
|
66
|
+
readonly rules: RetentionRules;
|
|
67
|
+
/** This method writes the rows in one transaction. Then it prunes each signal that is past its size. */
|
|
68
|
+
insert(rows: Rows): void;
|
|
69
|
+
/**
|
|
70
|
+
* This method deletes the rows past the age of each signal at `nowMs`, then the oldest rows past each size. Each
|
|
71
|
+
* delete is one transaction of at most `batch` rows. The prune stops after `batches` deletes (no bound by default),
|
|
72
|
+
* and then `done` is false. Thus a caller can let other work go between two parts of a long prune.
|
|
73
|
+
*/
|
|
74
|
+
prune(nowMs: number, batches?: number): Pruned;
|
|
75
|
+
/** This method gives the count and the size of the rows of each signal. */
|
|
76
|
+
sizes(): { readonly [signal in Signal]: SignalSize };
|
|
77
|
+
/** This method gives the size of the file in bytes, without its write-ahead log. */
|
|
78
|
+
fileBytes(): number;
|
|
79
|
+
close(): void;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** The options of `openStore` */
|
|
83
|
+
export interface StoreOptions {
|
|
84
|
+
readonly rules?: RetentionRules | undefined;
|
|
85
|
+
/** The most rows that one delete of the prune by size removes. The default is 5000. */
|
|
86
|
+
readonly batch?: number | undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const textBytes = (text: string | null): number => (text === null ? 0 : Buffer.byteLength(text, "utf8"));
|
|
90
|
+
|
|
91
|
+
/** 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 */
|
|
92
|
+
export const ROW_OVERHEAD = 32;
|
|
93
|
+
const spanBytes = (row: SpanRow): number =>
|
|
94
|
+
ROW_OVERHEAD + 8 * 4 + textBytes(row.traceId) + textBytes(row.spanId) + textBytes(row.parentId) + textBytes(row.service) + textBytes(row.name) + textBytes(row.attributes);
|
|
95
|
+
const logBytes = (row: LogRow): number =>
|
|
96
|
+
ROW_OVERHEAD + 8 * 2 + textBytes(row.service) + textBytes(row.body) + textBytes(row.traceId) + textBytes(row.spanId) + textBytes(row.attributes);
|
|
97
|
+
const pointBytes = (row: PointRow): number =>
|
|
98
|
+
ROW_OVERHEAD + 8 * 2 + textBytes(row.service) + textBytes(row.metric) + textBytes(row.attributes) + textBytes(row.histogram);
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* This function opens the store at a path, or in memory at `:memory:`. It makes the folder and the tables when they are
|
|
102
|
+
* not there. It throws when the rules have problems.
|
|
103
|
+
*/
|
|
104
|
+
export const openStore = (path: string, options: StoreOptions = {}): Store => {
|
|
105
|
+
const rules = options.rules ?? DEFAULT_RETENTION;
|
|
106
|
+
const problems = retentionProblems(rules);
|
|
107
|
+
if (problems.length > 0) throw new RangeError(`the retention rules have problems: ${problems.join("; ")}`);
|
|
108
|
+
const batch = options.batch ?? 5000;
|
|
109
|
+
if (!Number.isSafeInteger(batch) || batch < 1) throw new RangeError(`batch must be a whole number from 1: ${batch}`);
|
|
110
|
+
|
|
111
|
+
const db = openDatabase(path, { synchronous: "NORMAL", busyTimeoutMs: 5000, makeFolder: path !== ":memory:" });
|
|
112
|
+
try {
|
|
113
|
+
// Only a file with no tables takes this pragma. Thus it must come before the first step of the schema.
|
|
114
|
+
db.exec("PRAGMA auto_vacuum = INCREMENTAL");
|
|
115
|
+
migrate(db, MIGRATIONS, { name: "otel-sink" });
|
|
116
|
+
} catch (error) {
|
|
117
|
+
db.close();
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const insertSpan = db.prepare(
|
|
122
|
+
"INSERT INTO spans (trace_id, span_id, parent_id, service, name, kind, start_ns, end_ns, status, attributes, bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
123
|
+
);
|
|
124
|
+
const insertLog = db.prepare("INSERT INTO logs (time_ns, service, severity, body, trace_id, span_id, attributes, bytes) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
|
|
125
|
+
const insertPoint = db.prepare("INSERT INTO points (time_ns, service, metric, attributes, value, histogram, bytes) VALUES (?, ?, ?, ?, ?, ?, ?)");
|
|
126
|
+
const readSize = db.prepare("SELECT rows, bytes FROM sizes WHERE signal = ?");
|
|
127
|
+
const deleteAged = Object.fromEntries(
|
|
128
|
+
SIGNALS.map((signal) => [
|
|
129
|
+
signal,
|
|
130
|
+
db.prepare(`DELETE FROM ${signal} WHERE rowid IN (SELECT rowid FROM ${signal} WHERE ${TIME_COLUMN[signal]} < ? ORDER BY ${TIME_COLUMN[signal]} LIMIT ?)`),
|
|
131
|
+
]),
|
|
132
|
+
) as Record<Signal, StatementSync>;
|
|
133
|
+
const deleteOldest = Object.fromEntries(
|
|
134
|
+
SIGNALS.map((signal) => [signal, db.prepare(`DELETE FROM ${signal} WHERE rowid IN (SELECT rowid FROM ${signal} ORDER BY ${TIME_COLUMN[signal]} LIMIT ?)`)]),
|
|
135
|
+
) as Record<Signal, StatementSync>;
|
|
136
|
+
|
|
137
|
+
const size = (signal: Signal): SignalSize => {
|
|
138
|
+
const row = readSize.get(signal);
|
|
139
|
+
return { rows: Number(row?.["rows"] ?? 0), bytes: Number(row?.["bytes"] ?? 0) };
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
/** A budget of deletes. Each delete takes one unit of it. `complete` is false when a prune stopped with work left. */
|
|
143
|
+
interface Budget {
|
|
144
|
+
left: number;
|
|
145
|
+
complete: boolean;
|
|
146
|
+
}
|
|
147
|
+
const unbounded = (): Budget => ({ left: Number.POSITIVE_INFINITY, complete: true });
|
|
148
|
+
|
|
149
|
+
const age = (signal: Signal, cutoff: bigint, budget: Budget): number => {
|
|
150
|
+
let deleted = 0;
|
|
151
|
+
for (;;) {
|
|
152
|
+
if (budget.left <= 0) {
|
|
153
|
+
budget.complete = false;
|
|
154
|
+
return deleted;
|
|
155
|
+
}
|
|
156
|
+
budget.left--;
|
|
157
|
+
const changes = Number(transaction(db, () => deleteAged[signal].run(cutoff, batch)).changes);
|
|
158
|
+
deleted += changes;
|
|
159
|
+
if (changes < batch) return deleted;
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
const cap = (signal: Signal, budget: Budget): number => {
|
|
164
|
+
let deleted = 0;
|
|
165
|
+
for (;;) {
|
|
166
|
+
const { rows, bytes } = size(signal);
|
|
167
|
+
const excess = bytes - rules[signal].maxBytes;
|
|
168
|
+
if (excess <= 0 || rows === 0) return deleted;
|
|
169
|
+
if (budget.left <= 0) {
|
|
170
|
+
budget.complete = false;
|
|
171
|
+
return deleted;
|
|
172
|
+
}
|
|
173
|
+
budget.left--;
|
|
174
|
+
const count = Math.min(batch, rows, Math.max(1, Math.ceil(excess / (bytes / rows))));
|
|
175
|
+
deleted += Number(transaction(db, () => deleteOldest[signal].run(count)).changes);
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
let closed = false;
|
|
180
|
+
return {
|
|
181
|
+
db,
|
|
182
|
+
rules,
|
|
183
|
+
insert(rows) {
|
|
184
|
+
transaction(db, () => {
|
|
185
|
+
for (const r of rows.spans ?? [])
|
|
186
|
+
insertSpan.run(r.traceId, r.spanId, r.parentId, r.service, r.name, r.kind, r.startNs, r.endNs, r.status, r.attributes, spanBytes(r));
|
|
187
|
+
for (const r of rows.logs ?? []) insertLog.run(r.timeNs, r.service, r.severity, r.body, r.traceId, r.spanId, r.attributes, logBytes(r));
|
|
188
|
+
for (const r of rows.points ?? []) insertPoint.run(r.timeNs, r.service, r.metric, r.attributes, r.value, r.histogram, pointBytes(r));
|
|
189
|
+
});
|
|
190
|
+
for (const signal of SIGNALS) if ((rows[signal]?.length ?? 0) > 0) cap(signal, unbounded());
|
|
191
|
+
},
|
|
192
|
+
prune(nowMs, batches = Number.POSITIVE_INFINITY) {
|
|
193
|
+
if (!(batches >= 1)) throw new RangeError(`batches must be 1 or more: ${batches}`);
|
|
194
|
+
const budget: Budget = { left: batches, complete: true };
|
|
195
|
+
const result = {} as Record<Signal, SignalPrune>;
|
|
196
|
+
for (const signal of SIGNALS) {
|
|
197
|
+
const cutoff = BigInt(Math.floor(nowMs - rules[signal].maxAgeMs)) * 1_000_000n;
|
|
198
|
+
const aged = age(signal, cutoff, budget);
|
|
199
|
+
result[signal] = { aged, capped: cap(signal, budget) };
|
|
200
|
+
}
|
|
201
|
+
db.exec("PRAGMA incremental_vacuum");
|
|
202
|
+
return { ...result, done: budget.complete };
|
|
203
|
+
},
|
|
204
|
+
sizes() {
|
|
205
|
+
return { spans: size("spans"), logs: size("logs"), points: size("points") };
|
|
206
|
+
},
|
|
207
|
+
fileBytes() {
|
|
208
|
+
const pages = Number(db.prepare("PRAGMA page_count").get()?.["page_count"] ?? 0);
|
|
209
|
+
const pageSize = Number(db.prepare("PRAGMA page_size").get()?.["page_size"] ?? 0);
|
|
210
|
+
return pages * pageSize;
|
|
211
|
+
},
|
|
212
|
+
close() {
|
|
213
|
+
if (closed) return;
|
|
214
|
+
closed = true;
|
|
215
|
+
db.close();
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
};
|