cursedbelt-server 1.0.1 → 1.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/dist/server/guard/index.d.ts +1 -0
- package/dist/server/guard/index.js +1 -0
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.js +5 -0
- package/dist/server/jobs/index.d.ts +1 -0
- package/dist/server/jobs/index.js +1 -0
- package/dist/server/metrics/telemetrySink.d.ts +119 -0
- package/dist/server/metrics/telemetrySink.js +76 -0
- package/dist/server/middleware/index.d.ts +1 -0
- package/dist/server/middleware/index.js +3 -0
- package/dist/server/middleware/requestLogger.d.ts +30 -11
- package/dist/server/middleware/requestLogger.js +15 -6
- package/package.json +4 -2
- package/src/server/guard/index.ts +1 -0
- package/src/server/index.ts +14 -0
- package/src/server/jobs/index.ts +1 -0
- package/src/server/metrics/telemetrySink.spec.ts +288 -0
- package/src/server/metrics/telemetrySink.ts +181 -0
- package/src/server/middleware/index.ts +9 -0
- package/src/server/middleware/requestLogger.ts +43 -17
- package/src/server/storage/fileUploadClient-chunked.integration.spec.ts +183 -0
- package/src/server/storage/fileUploadClient.integration.spec.ts +139 -0
- package/src/shippedFilesAreTracked.spec.ts +69 -0
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// The GuardEngine server wiring (02 §4): the argon2id binding adapter that arms
|
|
2
2
|
// cwip's KDF seam, and the Ed25519 session signer that mints and revokes.
|
|
3
3
|
export * from './argon2Binding';
|
|
4
|
+
export * from './passwordVerifier';
|
|
4
5
|
export * from './verifier';
|
|
5
6
|
export * from './revocationStore';
|
|
6
7
|
export * from './sessionSigner';
|
package/dist/server/index.d.ts
CHANGED
|
@@ -10,6 +10,7 @@ export { type CreateJobRunnerOptions, createFireQueue, createJobRunner, createPo
|
|
|
10
10
|
export { buildProbeArgs, buildThumbnailArgs, buildTrimArgs, extractThumbnail, ffmpegTimeToSeconds, isFfmpegAvailable, isFfprobeAvailable, type ProbeResult, parseFfmpegProgress, parseFfprobe, probeMedia, renderImage, trimVideo, type VideoCodecPlan, videoCodecPlan, } from './media-bun';
|
|
11
11
|
export { createMetricsBuffer, type MetricRow, type MetricsBuffer, type MetricsBufferOptions, } from './metrics/metricsBuffer';
|
|
12
12
|
export { normalizeRoute } from './metrics/normalizeRoute';
|
|
13
|
+
export { type AnalyticsEngineDataset, createTelemetrySink, TELEMETRY_POINT_VERSION, type TelemetryEvent, type TelemetrySink, type TelemetrySinkOptions, toDataPoint, } from './metrics/telemetrySink';
|
|
13
14
|
export { correlationId } from './middleware/correlationId';
|
|
14
15
|
export { type CorsOpts, corsAllowlist, corsOptsFromEnv } from './middleware/corsAllowlist';
|
|
15
16
|
export { errorEnvelope } from './middleware/errorEnvelope';
|
|
@@ -23,3 +24,4 @@ export type { Migration } from './migration/types';
|
|
|
23
24
|
export { AUDIT_LOG_MIGRATIONS, auditStateAt, auditStateAtVersion, auditStep, createSqliteAuditSink, } from './audit';
|
|
24
25
|
export { applyFtsSchema, type BackupInfo, buildFtsSchema, clampLimit, clampOffset, collectSqliteStats, createFts5Search, createSqliteBackupService, createSqliteHealthChecks, createSqliteViewerMiddleware, type DbStats, exportSqliteSnapshot, exportSqliteTable, type Fts5Search, type FtsHighlightOpts, type FtsResult, type FtsSearchOpts, type FtsSnippetOpts, type FtsTableSpec, type ImportMode, type ImportResult, importRowsIntoSqliteTable, isKnownTable, isReadOnlySql, listSqliteTables, NotReadOnlyError, quoteIdent, type RestoreResult, readSqliteTable, restoreSqliteSnapshot, runReadonlySqlite, type SnapshotExport, type SqliteBackupOpts, type SqliteBackupS3Opts, type SqliteBackupService, type SqliteHealthCheck, type SqliteHealthOpts, type SqliteHealthResult, type SqliteHealthStatus, type SqliteTableInfo, type SqliteTablePage, sanitizeFtsQuery, snapshotSqlite, type TableExport, type TableExportFormat, type TableStat, UnknownTableError, } from './sqlite';
|
|
25
26
|
export { computePresence, createEventBus, createWsHub, type EventBus, type EventBusData, joinRoom, leaveRoom, type PresenceEntry, type PresenceState, ROOM_META_KEY, roomOf, type WsChannel, type WsClient, type WsData, type WsHandshake, type WsHub, type WsHubOpts, type WsMessage, } from './ws';
|
|
27
|
+
export { resolveAppDataHome } from './paths/appDataHome';
|
package/dist/server/index.js
CHANGED
|
@@ -27,6 +27,7 @@ export { buildProbeArgs, buildThumbnailArgs, buildTrimArgs, extractThumbnail, ff
|
|
|
27
27
|
// ── Metrics ───────────────────────────────────────────────────────────────────
|
|
28
28
|
export { createMetricsBuffer, } from './metrics/metricsBuffer';
|
|
29
29
|
export { normalizeRoute } from './metrics/normalizeRoute';
|
|
30
|
+
export { createTelemetrySink, TELEMETRY_POINT_VERSION, toDataPoint, } from './metrics/telemetrySink';
|
|
30
31
|
// ── Middleware ────────────────────────────────────────────────────────────────
|
|
31
32
|
export { correlationId } from './middleware/correlationId';
|
|
32
33
|
export { corsAllowlist, corsOptsFromEnv } from './middleware/corsAllowlist';
|
|
@@ -51,3 +52,7 @@ export { applyFtsSchema, buildFtsSchema, clampLimit, clampOffset, collectSqliteS
|
|
|
51
52
|
// ── WebSocket hub (task 28): Bun-native upgrade, channel registry, heartbeat, ──
|
|
52
53
|
// presence-as-a-view, room helpers, and the push-only event-bus subset (ru).
|
|
53
54
|
export { computePresence, createEventBus, createWsHub, joinRoom, leaveRoom, ROOM_META_KEY, roomOf, } from './ws';
|
|
55
|
+
// The app-data root resolver. Exported at the root (2026-09-15, task 148) because
|
|
56
|
+
// `cursedbelt-cc`'s localHost needs it and it answers a question about the HOST, not
|
|
57
|
+
// about any one subsystem — so no subpath barrel is its natural home.
|
|
58
|
+
export { resolveAppDataHome } from './paths/appDataHome';
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { createFireQueue } from './fireQueue';
|
|
2
2
|
export { defaultJobLogger } from './logger';
|
|
3
|
+
export { createPlainjobConnection } from './plainjobAdapter';
|
|
3
4
|
export { createPollingJob } from './polling';
|
|
4
5
|
export { createJobRunner } from './runner';
|
|
5
6
|
export { JobTimeoutError } from './timeout';
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
// *definitions* stay business and consume these primitives.
|
|
5
5
|
export { createFireQueue } from './fireQueue';
|
|
6
6
|
export { defaultJobLogger } from './logger';
|
|
7
|
+
export { createPlainjobConnection } from './plainjobAdapter';
|
|
7
8
|
export { createPollingJob } from './polling';
|
|
8
9
|
export { createJobRunner } from './runner';
|
|
9
10
|
export { JobTimeoutError } from './timeout';
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import type { Database } from 'bun:sqlite';
|
|
2
|
+
import { type MetricRow } from './metricsBuffer';
|
|
3
|
+
/**
|
|
4
|
+
* ONE seam for "this app served a request", with two backends and no third.
|
|
5
|
+
*
|
|
6
|
+
* ── Why this exists ─────────────────────────────────────────────────────────
|
|
7
|
+
* `request_metrics` is a row per request. On D1 that is the one line in
|
|
8
|
+
* Cloudflare's pricing with a dollar-scale overage — **$1.00 per million rows
|
|
9
|
+
* written** — and a row per request is precisely the shape that buys it. Workers
|
|
10
|
+
* Analytics Engine is purpose-built for the same job: `writeDataPoint()` per
|
|
11
|
+
* event, SQL to query, unlimited cardinality, **10M data points and 1M read
|
|
12
|
+
* queries included per month**, and **zero** database writes.
|
|
13
|
+
*
|
|
14
|
+
* 🔴 **Adopt it for the ALLOWANCE, not because it is unbilled today.**
|
|
15
|
+
* Cloudflare's own wording is that you "will not be billed for your use of
|
|
16
|
+
* Workers Analytics Engine" today and that the published prices are "shared in
|
|
17
|
+
* advance… once Cloudflare starts billing for usage in the coming months". The
|
|
18
|
+
* free-today part is temporary; the allowance is not. At this fleet's measured
|
|
19
|
+
* ~1M requests/month the bill is $0 either way, so building against the
|
|
20
|
+
* allowance makes the billing switch a non-event.
|
|
21
|
+
*
|
|
22
|
+
* ── Why not `prom-client` / a `/metrics` scrape ──────────────────────────────
|
|
23
|
+
* A scrape genuinely does turn many writes into one, and on a long-lived Bun
|
|
24
|
+
* process it would work. A Worker is **a stateless V8 isolate with no
|
|
25
|
+
* long-lived process**: isolates are created and destroyed between requests and
|
|
26
|
+
* run concurrently in many datacentres, so a `/metrics` scrape reaches ONE
|
|
27
|
+
* arbitrary isolate holding a random fraction of the counters. The in-process
|
|
28
|
+
* registry has nowhere to live. (A Durable Object does have a durable identity
|
|
29
|
+
* *and* memory, and is the real `prom-client` analogue — but it is a whole
|
|
30
|
+
* stateful object to operate for counters Analytics Engine already aggregates.
|
|
31
|
+
* Prometheus itself also needs an always-on host to scrape FROM, and that host
|
|
32
|
+
* is the Mac this fleet is trying to switch off.)
|
|
33
|
+
*
|
|
34
|
+
* ── The contract ────────────────────────────────────────────────────────────
|
|
35
|
+
* · `analytics` bound → one `writeDataPoint` per event, **zero** SQLite/D1 rows.
|
|
36
|
+
* · no `analytics` → the existing {@link MetricsBuffer}, byte-for-byte
|
|
37
|
+
* unchanged, so the gate and a Mac-hosted app keep working.
|
|
38
|
+
* Both are proven by `telemetrySink.spec.ts`, which is the point of the seam:
|
|
39
|
+
* the choice is made ONCE here rather than per app.
|
|
40
|
+
*/
|
|
41
|
+
/**
|
|
42
|
+
* The Workers Analytics Engine binding, typed locally so this package needs no
|
|
43
|
+
* dependency on `@cloudflare/workers-types` (it is a Bun/Hono package, and a
|
|
44
|
+
* Worker supplies the real binding at runtime).
|
|
45
|
+
*
|
|
46
|
+
* Platform limits, which {@link toDataPoint} respects:
|
|
47
|
+
* **1** index of ≤96 bytes, ≤**20** blobs totalling ≤5120 bytes, ≤**20** doubles.
|
|
48
|
+
*/
|
|
49
|
+
export interface AnalyticsEngineDataset {
|
|
50
|
+
writeDataPoint(point: {
|
|
51
|
+
indexes?: (ArrayBuffer | string | null)[];
|
|
52
|
+
blobs?: (ArrayBuffer | string | null)[];
|
|
53
|
+
doubles?: number[];
|
|
54
|
+
}): void;
|
|
55
|
+
}
|
|
56
|
+
/** One request's telemetry. Identical to {@link MetricRow} — the seam does not re-shape it. */
|
|
57
|
+
export type TelemetryEvent = MetricRow;
|
|
58
|
+
/**
|
|
59
|
+
* A superset-compatible shape: a {@link MetricsBuffer} IS a `TelemetrySink`, so
|
|
60
|
+
* an app that already owns a buffer can keep passing it.
|
|
61
|
+
*/
|
|
62
|
+
export interface TelemetrySink {
|
|
63
|
+
/** Enqueue one request's telemetry. Never blocks the response. */
|
|
64
|
+
record(event: TelemetryEvent): void;
|
|
65
|
+
/** Force whatever is pending out now (shutdown + tests). No-op on Analytics Engine. */
|
|
66
|
+
flush(): void;
|
|
67
|
+
/** Stop any timer and drain. No-op on Analytics Engine. */
|
|
68
|
+
stop(): void;
|
|
69
|
+
/** Events pending locally. Always 0 on Analytics Engine — it has no buffer to hold. */
|
|
70
|
+
readonly size: number;
|
|
71
|
+
}
|
|
72
|
+
export interface TelemetrySinkOptions {
|
|
73
|
+
/**
|
|
74
|
+
* The Analytics Engine binding, when the platform supplies one. Present ⇒ it
|
|
75
|
+
* WINS, and `db` is never written. `null`/`undefined` ⇒ the SQLite path.
|
|
76
|
+
*/
|
|
77
|
+
analytics?: AnalyticsEngineDataset | null;
|
|
78
|
+
/** The `request_metrics` database. Required unless `analytics` is bound. */
|
|
79
|
+
db?: Database | null;
|
|
80
|
+
/** Flush cadence for the SQLite path, in ms. Default: 1500. Ignored by Analytics Engine. */
|
|
81
|
+
flushIntervalMs?: number;
|
|
82
|
+
/** Eager-flush threshold for the SQLite path. Default: 5000. Ignored by Analytics Engine. */
|
|
83
|
+
maxSize?: number;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* 🔴 **The data-point layout is a WIRE FORMAT.** Analytics Engine columns are
|
|
87
|
+
* positional (`blob1`, `double1`, …), so every saved SQL query breaks if a
|
|
88
|
+
* position moves. Append only; never reorder, never repurpose.
|
|
89
|
+
*
|
|
90
|
+
* ```
|
|
91
|
+
* index1 = route, truncated to 96 bytes — the sampling key, so sampling is per route
|
|
92
|
+
* blob1 = method blob2 = route (untruncated) blob3 = userId ('' when anonymous)
|
|
93
|
+
* double1 = status double2 = durationMs double3 = bytesOut
|
|
94
|
+
* ```
|
|
95
|
+
*
|
|
96
|
+
* `ts` is deliberately absent: Analytics Engine stamps its own `timestamp`
|
|
97
|
+
* column, so sending ours would store the same instant twice.
|
|
98
|
+
*
|
|
99
|
+
* `-1` is the "unknown" marker for all three doubles, because a positional
|
|
100
|
+
* doubles array cannot hold a null and `0` is a real value for every one of them
|
|
101
|
+
* (a 0-byte 204, notably). Read it as `NULL`, not as a measurement.
|
|
102
|
+
*/
|
|
103
|
+
export declare const TELEMETRY_POINT_VERSION = 1;
|
|
104
|
+
/** The documented layout above, as data. Exported so the spec asserts the wire format itself. */
|
|
105
|
+
export declare function toDataPoint(event: TelemetryEvent): {
|
|
106
|
+
indexes: string[];
|
|
107
|
+
blobs: string[];
|
|
108
|
+
doubles: number[];
|
|
109
|
+
};
|
|
110
|
+
/**
|
|
111
|
+
* Build the sink for whatever platform this process is on.
|
|
112
|
+
*
|
|
113
|
+
* Throws when NEITHER backend is available, on purpose. "An app with no
|
|
114
|
+
* `request_metrics` is not quiet; it is unmeasured" — and a sink that silently
|
|
115
|
+
* drops every event is exactly the failure this seam exists to end. A misbound
|
|
116
|
+
* Worker should fail at construction, in the deploy, rather than serve traffic
|
|
117
|
+
* that nothing can see.
|
|
118
|
+
*/
|
|
119
|
+
export declare function createTelemetrySink(opts: TelemetrySinkOptions): TelemetrySink;
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { createMetricsBuffer } from './metricsBuffer';
|
|
2
|
+
/**
|
|
3
|
+
* 🔴 **The data-point layout is a WIRE FORMAT.** Analytics Engine columns are
|
|
4
|
+
* positional (`blob1`, `double1`, …), so every saved SQL query breaks if a
|
|
5
|
+
* position moves. Append only; never reorder, never repurpose.
|
|
6
|
+
*
|
|
7
|
+
* ```
|
|
8
|
+
* index1 = route, truncated to 96 bytes — the sampling key, so sampling is per route
|
|
9
|
+
* blob1 = method blob2 = route (untruncated) blob3 = userId ('' when anonymous)
|
|
10
|
+
* double1 = status double2 = durationMs double3 = bytesOut
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* `ts` is deliberately absent: Analytics Engine stamps its own `timestamp`
|
|
14
|
+
* column, so sending ours would store the same instant twice.
|
|
15
|
+
*
|
|
16
|
+
* `-1` is the "unknown" marker for all three doubles, because a positional
|
|
17
|
+
* doubles array cannot hold a null and `0` is a real value for every one of them
|
|
18
|
+
* (a 0-byte 204, notably). Read it as `NULL`, not as a measurement.
|
|
19
|
+
*/
|
|
20
|
+
export const TELEMETRY_POINT_VERSION = 1;
|
|
21
|
+
const INDEX_MAX_BYTES = 96;
|
|
22
|
+
/**
|
|
23
|
+
* Truncate to at most `maxBytes` UTF-8 bytes without splitting a code point —
|
|
24
|
+
* `String.slice` counts UTF-16 units, so a route with one multi-byte character
|
|
25
|
+
* can be ≤96 chars and still exceed the 96-BYTE index limit.
|
|
26
|
+
*/
|
|
27
|
+
function truncateUtf8(value, maxBytes) {
|
|
28
|
+
const encoded = new TextEncoder().encode(value);
|
|
29
|
+
if (encoded.length <= maxBytes)
|
|
30
|
+
return value;
|
|
31
|
+
return new TextDecoder('utf-8', { fatal: false }).decode(encoded.subarray(0, maxBytes)).replace(
|
|
32
|
+
// A cut through a multi-byte sequence decodes to U+FFFD; drop that trailing artefact.
|
|
33
|
+
/�+$/, '');
|
|
34
|
+
}
|
|
35
|
+
const num = (value) => typeof value === 'number' && Number.isFinite(value) ? value : -1;
|
|
36
|
+
/** The documented layout above, as data. Exported so the spec asserts the wire format itself. */
|
|
37
|
+
export function toDataPoint(event) {
|
|
38
|
+
const route = event.route ?? '';
|
|
39
|
+
return {
|
|
40
|
+
indexes: [truncateUtf8(route, INDEX_MAX_BYTES)],
|
|
41
|
+
blobs: [event.method ?? '', route, event.userId ?? ''],
|
|
42
|
+
doubles: [num(event.status), num(event.durationMs), num(event.bytesOut)],
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Build the sink for whatever platform this process is on.
|
|
47
|
+
*
|
|
48
|
+
* Throws when NEITHER backend is available, on purpose. "An app with no
|
|
49
|
+
* `request_metrics` is not quiet; it is unmeasured" — and a sink that silently
|
|
50
|
+
* drops every event is exactly the failure this seam exists to end. A misbound
|
|
51
|
+
* Worker should fail at construction, in the deploy, rather than serve traffic
|
|
52
|
+
* that nothing can see.
|
|
53
|
+
*/
|
|
54
|
+
export function createTelemetrySink(opts) {
|
|
55
|
+
const { analytics, db, flushIntervalMs, maxSize } = opts;
|
|
56
|
+
if (analytics) {
|
|
57
|
+
// Analytics Engine writes are fire-and-forget and already off the response
|
|
58
|
+
// path — there is nothing to buffer, so flush/stop are honestly no-ops.
|
|
59
|
+
return {
|
|
60
|
+
record(event) {
|
|
61
|
+
analytics.writeDataPoint(toDataPoint(event));
|
|
62
|
+
},
|
|
63
|
+
flush() { },
|
|
64
|
+
stop() { },
|
|
65
|
+
get size() {
|
|
66
|
+
return 0;
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
if (!db) {
|
|
71
|
+
throw new Error('createTelemetrySink: neither an Analytics Engine binding (`analytics`) nor a `db` was ' +
|
|
72
|
+
'provided. Telemetry would be silently dropped; bind one of the two.');
|
|
73
|
+
}
|
|
74
|
+
// The unchanged SQLite path — same module, same batching, same rows.
|
|
75
|
+
return createMetricsBuffer({ db, flushIntervalMs, maxSize });
|
|
76
|
+
}
|
|
@@ -4,6 +4,7 @@ export { errorEnvelope } from './errorEnvelope';
|
|
|
4
4
|
export { crossOriginRefusal } from './localOrigin';
|
|
5
5
|
export { clientIp, createRateLimiter, type RateLimitOpts } from './rateLimit';
|
|
6
6
|
export { type RequestLoggerOpts, requestLogger } from './requestLogger';
|
|
7
|
+
export { type AnalyticsEngineDataset, createTelemetrySink, type TelemetryEvent, type TelemetrySink, type TelemetrySinkOptions, } from '../metrics/telemetrySink';
|
|
7
8
|
export { type CspDirectives, type SecurityHeadersOpts, securityHeaders, } from './securityHeaders';
|
|
8
9
|
export { toValidationIssues, VALIDATION_ERROR_CODE, type ValidationIssue, validationEnvelope, } from '../errors';
|
|
9
10
|
export { type ZValidatorTarget, zValidator } from './zValidator';
|
|
@@ -5,6 +5,9 @@ export { errorEnvelope } from './errorEnvelope';
|
|
|
5
5
|
export { crossOriginRefusal } from './localOrigin';
|
|
6
6
|
export { clientIp, createRateLimiter } from './rateLimit';
|
|
7
7
|
export { requestLogger } from './requestLogger';
|
|
8
|
+
// The telemetry seam `requestLogger` writes through — re-exported here so a caller
|
|
9
|
+
// that reaches `./middleware` for the logger can bind Analytics Engine in the same import.
|
|
10
|
+
export { createTelemetrySink, } from '../metrics/telemetrySink';
|
|
8
11
|
export { securityHeaders, } from './securityHeaders';
|
|
9
12
|
export { toValidationIssues, VALIDATION_ERROR_CODE, validationEnvelope, } from '../errors';
|
|
10
13
|
export { zValidator } from './zValidator';
|
|
@@ -1,29 +1,48 @@
|
|
|
1
1
|
import type { Database } from 'bun:sqlite';
|
|
2
2
|
import type { MiddlewareHandler } from 'hono';
|
|
3
3
|
import type { CursedbeltEnv } from '../context';
|
|
4
|
-
import {
|
|
4
|
+
import type { MetricsBuffer } from '../metrics/metricsBuffer';
|
|
5
|
+
import { type AnalyticsEngineDataset, type TelemetrySink } from '../metrics/telemetrySink';
|
|
5
6
|
/**
|
|
6
|
-
* Structured request/response logging. After each request it records one
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
7
|
+
* Structured request/response logging. After each request it records one
|
|
8
|
+
* telemetry event through the {@link TelemetrySink} (off the hot path) and, for
|
|
9
|
+
* errors (status ≥ 400) or slow requests, one `event_logs` row tagged with the
|
|
10
|
+
* correlation id. Attributes rows to `c.get('userId')` when the app's auth
|
|
10
11
|
* middleware has set it.
|
|
11
12
|
*
|
|
13
|
+
* 🔴 **Where the telemetry LANDS is the sink's decision, not this file's.** With
|
|
14
|
+
* an Analytics Engine binding it is one `writeDataPoint` and **zero** database
|
|
15
|
+
* rows; without one it is the same batched `request_metrics` insert it has always
|
|
16
|
+
* been. See `../metrics/telemetrySink.ts` for why that is the only choice offered.
|
|
17
|
+
*
|
|
12
18
|
* It records metrics even when a downstream handler THROWS: the error is caught,
|
|
13
|
-
* the would-be status derived, the
|
|
19
|
+
* the would-be status derived, the event recorded, then the error re-thrown so the
|
|
14
20
|
* error-envelope `onError` still produces the response.
|
|
15
21
|
*/
|
|
16
22
|
export interface RequestLoggerOpts {
|
|
17
23
|
/**
|
|
18
|
-
* The
|
|
19
|
-
*
|
|
20
|
-
|
|
21
|
-
|
|
24
|
+
* The Analytics Engine binding, when the platform supplies one. Present ⇒ the
|
|
25
|
+
* telemetry goes there and NOTHING is written to `request_metrics`.
|
|
26
|
+
*/
|
|
27
|
+
analytics?: AnalyticsEngineDataset | null;
|
|
28
|
+
/**
|
|
29
|
+
* The sink to write through. Provide one (and own its lifecycle via
|
|
30
|
+
* `sink.stop()`) to share it / flush deterministically; omit to build one from
|
|
31
|
+
* `db` + `analytics`. A {@link MetricsBuffer} is a valid sink.
|
|
22
32
|
*/
|
|
33
|
+
sink?: TelemetrySink;
|
|
34
|
+
/** @deprecated Use {@link RequestLoggerOpts.sink} — a `MetricsBuffer` is one. Kept for callers that predate the sink. */
|
|
23
35
|
buffer?: MetricsBuffer;
|
|
24
36
|
/** Duration (ms) at/above which a 2xx request also logs an `event_logs` row. Default: 2000. */
|
|
25
37
|
slowMs?: number;
|
|
26
38
|
/** Also write `event_logs` rows for status ≥ 400. Default: true. */
|
|
27
39
|
logErrors?: boolean;
|
|
28
40
|
}
|
|
29
|
-
|
|
41
|
+
/**
|
|
42
|
+
* @param db The `request_metrics` / `event_logs` database. Pass `null` on a
|
|
43
|
+
* platform that has no `bun:sqlite` — a Worker with `analytics` bound — in
|
|
44
|
+
* which case `event_logs` is not written either, because there is nowhere to
|
|
45
|
+
* put it. `analytics` or `sink` is then mandatory; `createTelemetrySink`
|
|
46
|
+
* throws rather than drop telemetry silently.
|
|
47
|
+
*/
|
|
48
|
+
export declare function requestLogger(db: Database | null, opts?: RequestLoggerOpts): MiddlewareHandler<CursedbeltEnv>;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { HTTPException } from 'hono/http-exception';
|
|
2
2
|
import { isApiError } from '../errors';
|
|
3
|
-
import { createMetricsBuffer } from '../metrics/metricsBuffer';
|
|
4
3
|
import { normalizeRoute } from '../metrics/normalizeRoute';
|
|
4
|
+
import { createTelemetrySink, } from '../metrics/telemetrySink';
|
|
5
5
|
function statusOfThrown(err) {
|
|
6
6
|
if (isApiError(err))
|
|
7
7
|
return err.status;
|
|
@@ -9,13 +9,22 @@ function statusOfThrown(err) {
|
|
|
9
9
|
return err.status;
|
|
10
10
|
return 500;
|
|
11
11
|
}
|
|
12
|
+
/**
|
|
13
|
+
* @param db The `request_metrics` / `event_logs` database. Pass `null` on a
|
|
14
|
+
* platform that has no `bun:sqlite` — a Worker with `analytics` bound — in
|
|
15
|
+
* which case `event_logs` is not written either, because there is nowhere to
|
|
16
|
+
* put it. `analytics` or `sink` is then mandatory; `createTelemetrySink`
|
|
17
|
+
* throws rather than drop telemetry silently.
|
|
18
|
+
*/
|
|
12
19
|
export function requestLogger(db, opts = {}) {
|
|
13
|
-
const
|
|
20
|
+
const sink = opts.sink ?? opts.buffer ?? createTelemetrySink({ db, analytics: opts.analytics ?? null });
|
|
14
21
|
const slowMs = opts.slowMs ?? 2000;
|
|
15
22
|
const logErrors = opts.logErrors ?? true;
|
|
16
|
-
const insertEvent = db
|
|
23
|
+
const insertEvent = db
|
|
24
|
+
? db.prepare(`INSERT INTO event_logs
|
|
17
25
|
(id, correlation_id, event_name, type, message, details, duration_ms, user_id, created_at)
|
|
18
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
26
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`)
|
|
27
|
+
: null;
|
|
19
28
|
return async (c, next) => {
|
|
20
29
|
const start = performance.now();
|
|
21
30
|
let thrown;
|
|
@@ -33,10 +42,10 @@ export function requestLogger(db, opts = {}) {
|
|
|
33
42
|
const lenHeader = didThrow ? null : c.res.headers.get('content-length');
|
|
34
43
|
const bytesOut = lenHeader ? Number(lenHeader) : null;
|
|
35
44
|
const userId = c.get('userId') ?? null;
|
|
36
|
-
|
|
45
|
+
sink.record({ ts: Date.now(), method, route, status, durationMs, bytesOut, userId });
|
|
37
46
|
const isError = status >= 400;
|
|
38
47
|
const isSlow = durationMs >= slowMs;
|
|
39
|
-
if ((logErrors && isError) || isSlow) {
|
|
48
|
+
if (insertEvent && ((logErrors && isError) || isSlow)) {
|
|
40
49
|
const type = status >= 500 ? 'error' : isError ? 'warn' : 'info';
|
|
41
50
|
insertEvent.run(crypto.randomUUID(), c.get('correlationId') ?? null, isError ? 'http_error' : 'http_slow', type, `${method} ${route} → ${status}`, JSON.stringify({ method, route, status, durationMs: Math.round(durationMs), bytesOut }), Math.round(durationMs), userId, new Date().toISOString());
|
|
42
51
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cursedbelt-server",
|
|
3
|
-
"version": "1.0
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"license": "ISC",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "The app-facing Bun/Hono server tier of the cursedbelt split \u2014 storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
|
|
@@ -22,7 +22,8 @@
|
|
|
22
22
|
"build": "bun run clean && tsc -p tsconfig.build.json",
|
|
23
23
|
"paths": "bun ../../tools/check-paths.ts .",
|
|
24
24
|
"verify": "bun run paths && bun run typecheck && bun run build && bun run test",
|
|
25
|
-
"prepublishOnly": "bun run verify"
|
|
25
|
+
"prepublishOnly": "bun run verify",
|
|
26
|
+
"test:pg": "bun run scripts/testPg.ts"
|
|
26
27
|
},
|
|
27
28
|
"files": [
|
|
28
29
|
"dist",
|
|
@@ -221,6 +222,7 @@
|
|
|
221
222
|
"@node-rs/argon2": "^2.0.2",
|
|
222
223
|
"@types/bun": "^1.3.14",
|
|
223
224
|
"@types/node": "^24",
|
|
225
|
+
"cursedbelt": "^3.0.0",
|
|
224
226
|
"hono": "4.12.28",
|
|
225
227
|
"kysely": "^0.28.17",
|
|
226
228
|
"kysely-bun-sqlite": "^0.4.0",
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// The GuardEngine server wiring (02 §4): the argon2id binding adapter that arms
|
|
2
2
|
// cwip's KDF seam, and the Ed25519 session signer that mints and revokes.
|
|
3
3
|
export * from './argon2Binding';
|
|
4
|
+
export * from './passwordVerifier';
|
|
4
5
|
export * from './verifier';
|
|
5
6
|
export * from './revocationStore';
|
|
6
7
|
export * from './sessionSigner';
|
package/src/server/index.ts
CHANGED
|
@@ -144,6 +144,15 @@ export {
|
|
|
144
144
|
type MetricsBufferOptions,
|
|
145
145
|
} from './metrics/metricsBuffer';
|
|
146
146
|
export { normalizeRoute } from './metrics/normalizeRoute';
|
|
147
|
+
export {
|
|
148
|
+
type AnalyticsEngineDataset,
|
|
149
|
+
createTelemetrySink,
|
|
150
|
+
TELEMETRY_POINT_VERSION,
|
|
151
|
+
type TelemetryEvent,
|
|
152
|
+
type TelemetrySink,
|
|
153
|
+
type TelemetrySinkOptions,
|
|
154
|
+
toDataPoint,
|
|
155
|
+
} from './metrics/telemetrySink';
|
|
147
156
|
// ── Middleware ────────────────────────────────────────────────────────────────
|
|
148
157
|
export { correlationId } from './middleware/correlationId';
|
|
149
158
|
export { type CorsOpts, corsAllowlist, corsOptsFromEnv } from './middleware/corsAllowlist';
|
|
@@ -246,3 +255,8 @@ export {
|
|
|
246
255
|
type WsHubOpts,
|
|
247
256
|
type WsMessage,
|
|
248
257
|
} from './ws';
|
|
258
|
+
|
|
259
|
+
// The app-data root resolver. Exported at the root (2026-09-15, task 148) because
|
|
260
|
+
// `cursedbelt-cc`'s localHost needs it and it answers a question about the HOST, not
|
|
261
|
+
// about any one subsystem — so no subpath barrel is its natural home.
|
|
262
|
+
export { resolveAppDataHome } from './paths/appDataHome';
|
package/src/server/jobs/index.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
export { createFireQueue } from './fireQueue';
|
|
7
7
|
export { defaultJobLogger } from './logger';
|
|
8
|
+
export { createPlainjobConnection } from './plainjobAdapter';
|
|
8
9
|
export { createPollingJob } from './polling';
|
|
9
10
|
export { createJobRunner } from './runner';
|
|
10
11
|
export { JobTimeoutError } from './timeout';
|