@lp-labs/sync-observability 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Libin Prasanth
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,97 @@
1
- # Temporary Holding Version
1
+ # @lp-labs/sync-observability
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Bounded numeric synchronization metrics and payload-free diagnostics.
4
+
5
+ Original independent MIT TypeScript implementation with **zero runtime/peer dependencies**. ESM and CommonJS with separate declarations, Node 18+ (browser use when adapters/APIs are available). Development dependencies are not consumer runtime dependencies.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @lp-labs/sync-observability
11
+ ```
12
+
13
+ ## Complete example
14
+
15
+ ```js
16
+ import assert from 'node:assert/strict';
17
+ import { createSyncObservability, SyncObservabilityError } from '@lp-labs/sync-observability';
18
+ const monitor = createSyncObservability({ maxEvents: 2, staleAfterMs: 10 });
19
+ monitor.record({ kind: 'queue', at: 1, queueSize: 2 });
20
+ monitor.record({ kind: 'completed', at: 2 });
21
+ assert.equal(monitor.metrics(2).health, 'healthy');
22
+ assert.equal(monitor.metrics(13).health, 'stale');
23
+ assert.equal(monitor.exportDiagnostics(2).metrics.completed, 1);
24
+ ```
25
+
26
+ CommonJS exposes the same API: `const api = require('@lp-labs/sync-observability')`.
27
+
28
+ ## Scope, customization and performance
29
+
30
+ Allowlisted kinds and numeric signals only: unknown fields reject rather than silently redact. No identifiers, payloads or labels stored. Ring history default 200 events; lifetime counters retain totals. Explicit now recommended for deterministic tests. Events must be nondecreasing; future observations relative to now are rejected. Queue threshold defaults 10,000. Health precedence stale/backlogged/conflicted/healthy; failures are separate counters, not an automatic outage classification.
31
+
32
+ Configure explicit limits, clocks, policies and adapters through the API below. Error classes and standard TypeError/RangeError reject malformed input; adapter/handler errors propagate. Await asynchronous methods and handle rejection in your application; no success-shaped fallback on failed work. Inputs must be trusted ordinary data, not hostile proxies; adapters must meet documented atomicity, isolation and ownership contracts. This package never publishes data, loads external code or starts background services at import time.
33
+
34
+ ## API reference
35
+
36
+ The complete exported TypeScript contract (including option defaults discussed above, method return shapes, and error codes) is included below. TypeScript users import interfaces using `import type`; JavaScript users pass matching ordinary objects. Signature optionals indicate intentionally optional fields, not silent recovery.
37
+
38
+ ```ts
39
+ export type ObservationKind =
40
+ 'started' | 'completed' | 'failed' | 'conflict' | 'queue' | 'checkpoint';
41
+ export type SyncHealth = 'healthy' | 'stale' | 'backlogged' | 'conflicted' | 'unknown';
42
+ export interface SyncObservation {
43
+ kind: ObservationKind;
44
+ at: number;
45
+ lagMs?: number;
46
+ queueSize?: number;
47
+ }
48
+ export interface SanitizedObservation {
49
+ kind: ObservationKind;
50
+ at: number;
51
+ lagMs: number;
52
+ queueSize: number;
53
+ }
54
+ export interface SyncMetrics {
55
+ health: SyncHealth;
56
+ observedAt: number;
57
+ lastActivityAt: number | null;
58
+ lagMs: number;
59
+ queueSize: number;
60
+ conflicts: number;
61
+ failures: number;
62
+ completed: number;
63
+ }
64
+ export interface DiagnosticExport {
65
+ format: 'lp-sync-diagnostics';
66
+ version: 1;
67
+ metrics: SyncMetrics;
68
+ observations: SanitizedObservation[];
69
+ truncated: boolean;
70
+ }
71
+ export interface SyncObservabilityOptions {
72
+ maxEvents?: number;
73
+ maxQueueSize?: number;
74
+ staleAfterMs?: number;
75
+ }
76
+ export declare class SyncObservabilityError extends Error {
77
+ readonly code: 'invalid' | 'capacity';
78
+ constructor(code: 'invalid' | 'capacity', message: string);
79
+ }
80
+ export interface SyncObservability {
81
+ record(observation: SyncObservation): void;
82
+ metrics(now?: number): SyncMetrics;
83
+ exportDiagnostics(now?: number): DiagnosticExport;
84
+ }
85
+ /** Keeps only allow-listed numeric sync signals; labels, payloads, and identifiers are never stored. */
86
+ export declare function createSyncObservability(
87
+ options?: SyncObservabilityOptions,
88
+ ): SyncObservability;
89
+ ```
90
+
91
+ ## Support
92
+
93
+ If this library is useful to you, consider supporting its maintenance with a [donation via PayPal](https://www.paypal.me/LibinPrasanth).
94
+
95
+ ## Author
96
+
97
+ Created by [Libin Prasanth](https://www.linkedin.com/in/libinprasanth/). Connect on LinkedIn for updates and discussion.
@@ -0,0 +1,47 @@
1
+ export type ObservationKind = 'started' | 'completed' | 'failed' | 'conflict' | 'queue' | 'checkpoint';
2
+ export type SyncHealth = 'healthy' | 'stale' | 'backlogged' | 'conflicted' | 'unknown';
3
+ export interface SyncObservation {
4
+ kind: ObservationKind;
5
+ at: number;
6
+ lagMs?: number;
7
+ queueSize?: number;
8
+ }
9
+ export interface SanitizedObservation {
10
+ kind: ObservationKind;
11
+ at: number;
12
+ lagMs: number;
13
+ queueSize: number;
14
+ }
15
+ export interface SyncMetrics {
16
+ health: SyncHealth;
17
+ observedAt: number;
18
+ lastActivityAt: number | null;
19
+ lagMs: number;
20
+ queueSize: number;
21
+ conflicts: number;
22
+ failures: number;
23
+ completed: number;
24
+ }
25
+ export interface DiagnosticExport {
26
+ format: 'lp-sync-diagnostics';
27
+ version: 1;
28
+ metrics: SyncMetrics;
29
+ observations: SanitizedObservation[];
30
+ truncated: boolean;
31
+ }
32
+ export interface SyncObservabilityOptions {
33
+ maxEvents?: number;
34
+ maxQueueSize?: number;
35
+ staleAfterMs?: number;
36
+ }
37
+ export declare class SyncObservabilityError extends Error {
38
+ readonly code: 'invalid' | 'capacity';
39
+ constructor(code: 'invalid' | 'capacity', message: string);
40
+ }
41
+ export interface SyncObservability {
42
+ record(observation: SyncObservation): void;
43
+ metrics(now?: number): SyncMetrics;
44
+ exportDiagnostics(now?: number): DiagnosticExport;
45
+ }
46
+ /** Keeps only allow-listed numeric sync signals; labels, payloads, and identifiers are never stored. */
47
+ export declare function createSyncObservability(options?: SyncObservabilityOptions): SyncObservability;
@@ -0,0 +1,114 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.SyncObservabilityError = void 0;
4
+ exports.createSyncObservability = createSyncObservability;
5
+ class SyncObservabilityError extends Error {
6
+ code;
7
+ constructor(code, message) {
8
+ super(message);
9
+ this.code = code;
10
+ this.name = 'SyncObservabilityError';
11
+ }
12
+ }
13
+ exports.SyncObservabilityError = SyncObservabilityError;
14
+ const KINDS = [
15
+ 'started',
16
+ 'completed',
17
+ 'failed',
18
+ 'conflict',
19
+ 'queue',
20
+ 'checkpoint',
21
+ ];
22
+ function boundedInteger(value, min, max, label) {
23
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max) {
24
+ throw new SyncObservabilityError('invalid', `${label} must be a safe integer from ${min} to ${max}.`);
25
+ }
26
+ return value;
27
+ }
28
+ function optionsRecord(value) {
29
+ if (typeof value !== 'object' ||
30
+ value === null ||
31
+ Array.isArray(value) ||
32
+ Object.getPrototypeOf(value) !== Object.prototype ||
33
+ Object.getOwnPropertySymbols(value).length !== 0) {
34
+ throw new SyncObservabilityError('invalid', 'Options and observations must be plain objects.');
35
+ }
36
+ return value;
37
+ }
38
+ /** Keeps only allow-listed numeric sync signals; labels, payloads, and identifiers are never stored. */
39
+ function createSyncObservability(options = {}) {
40
+ const rawOptions = optionsRecord(options);
41
+ if (Object.keys(rawOptions).some((key) => !['maxEvents', 'maxQueueSize', 'staleAfterMs'].includes(key))) {
42
+ throw new SyncObservabilityError('invalid', 'Options contain an unknown field.');
43
+ }
44
+ const maxEvents = boundedInteger(options.maxEvents ?? 200, 1, 10_000, 'maxEvents');
45
+ const maxQueueSize = boundedInteger(options.maxQueueSize ?? 10_000, 1, 1_000_000, 'maxQueueSize');
46
+ const staleAfterMs = boundedInteger(options.staleAfterMs ?? 60_000, 0, 86_400_000, 'staleAfterMs');
47
+ let observations = [];
48
+ let lagMs = 0;
49
+ let queueSize = 0;
50
+ let conflicts = 0;
51
+ let failures = 0;
52
+ let completed = 0;
53
+ let droppedEvents = false;
54
+ const metrics = (now = Date.now()) => {
55
+ const observedAt = boundedInteger(now, 0, Number.MAX_SAFE_INTEGER, 'now');
56
+ const lastActivityAt = observations.at(-1)?.at ?? null;
57
+ if (lastActivityAt !== null && observedAt < lastActivityAt)
58
+ throw new SyncObservabilityError('invalid', 'now predates the last observation.');
59
+ let health = 'unknown';
60
+ if (lastActivityAt !== null) {
61
+ health =
62
+ observedAt - lastActivityAt > staleAfterMs
63
+ ? 'stale'
64
+ : queueSize >= maxQueueSize
65
+ ? 'backlogged'
66
+ : conflicts > 0
67
+ ? 'conflicted'
68
+ : 'healthy';
69
+ }
70
+ return { health, observedAt, lastActivityAt, lagMs, queueSize, conflicts, failures, completed };
71
+ };
72
+ return {
73
+ record(input) {
74
+ const raw = optionsRecord(input);
75
+ if (Object.keys(raw).some((key) => !['kind', 'at', 'lagMs', 'queueSize'].includes(key))) {
76
+ throw new SyncObservabilityError('invalid', 'Observation contains an unknown field.');
77
+ }
78
+ if (typeof input.kind !== 'string' || !KINDS.includes(input.kind)) {
79
+ throw new SyncObservabilityError('invalid', 'Observation kind is not supported.');
80
+ }
81
+ const at = boundedInteger(input.at, 0, Number.MAX_SAFE_INTEGER, 'at');
82
+ const nextLag = boundedInteger(input.lagMs ?? 0, 0, Number.MAX_SAFE_INTEGER, 'lagMs');
83
+ const nextQueue = boundedInteger(input.queueSize ?? 0, 0, maxQueueSize, 'queueSize');
84
+ const previous = observations.at(-1);
85
+ if (previous && at < previous.at) {
86
+ throw new SyncObservabilityError('invalid', 'Observation timestamps must be nondecreasing.');
87
+ }
88
+ const safe = { kind: input.kind, at, lagMs: nextLag, queueSize: nextQueue };
89
+ observations.push(safe);
90
+ if (observations.length > maxEvents) {
91
+ observations = observations.slice(-maxEvents);
92
+ droppedEvents = true;
93
+ }
94
+ lagMs = nextLag;
95
+ queueSize = nextQueue;
96
+ if (input.kind === 'conflict')
97
+ conflicts++;
98
+ if (input.kind === 'failed')
99
+ failures++;
100
+ if (input.kind === 'completed')
101
+ completed++;
102
+ },
103
+ metrics,
104
+ exportDiagnostics(now = Date.now()) {
105
+ return {
106
+ format: 'lp-sync-diagnostics',
107
+ version: 1,
108
+ metrics: metrics(now),
109
+ observations: observations.map((entry) => ({ ...entry })),
110
+ truncated: droppedEvents,
111
+ };
112
+ },
113
+ };
114
+ }
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}
@@ -0,0 +1,47 @@
1
+ export type ObservationKind = 'started' | 'completed' | 'failed' | 'conflict' | 'queue' | 'checkpoint';
2
+ export type SyncHealth = 'healthy' | 'stale' | 'backlogged' | 'conflicted' | 'unknown';
3
+ export interface SyncObservation {
4
+ kind: ObservationKind;
5
+ at: number;
6
+ lagMs?: number;
7
+ queueSize?: number;
8
+ }
9
+ export interface SanitizedObservation {
10
+ kind: ObservationKind;
11
+ at: number;
12
+ lagMs: number;
13
+ queueSize: number;
14
+ }
15
+ export interface SyncMetrics {
16
+ health: SyncHealth;
17
+ observedAt: number;
18
+ lastActivityAt: number | null;
19
+ lagMs: number;
20
+ queueSize: number;
21
+ conflicts: number;
22
+ failures: number;
23
+ completed: number;
24
+ }
25
+ export interface DiagnosticExport {
26
+ format: 'lp-sync-diagnostics';
27
+ version: 1;
28
+ metrics: SyncMetrics;
29
+ observations: SanitizedObservation[];
30
+ truncated: boolean;
31
+ }
32
+ export interface SyncObservabilityOptions {
33
+ maxEvents?: number;
34
+ maxQueueSize?: number;
35
+ staleAfterMs?: number;
36
+ }
37
+ export declare class SyncObservabilityError extends Error {
38
+ readonly code: 'invalid' | 'capacity';
39
+ constructor(code: 'invalid' | 'capacity', message: string);
40
+ }
41
+ export interface SyncObservability {
42
+ record(observation: SyncObservation): void;
43
+ metrics(now?: number): SyncMetrics;
44
+ exportDiagnostics(now?: number): DiagnosticExport;
45
+ }
46
+ /** Keeps only allow-listed numeric sync signals; labels, payloads, and identifiers are never stored. */
47
+ export declare function createSyncObservability(options?: SyncObservabilityOptions): SyncObservability;
@@ -0,0 +1,109 @@
1
+ export class SyncObservabilityError extends Error {
2
+ code;
3
+ constructor(code, message) {
4
+ super(message);
5
+ this.code = code;
6
+ this.name = 'SyncObservabilityError';
7
+ }
8
+ }
9
+ const KINDS = [
10
+ 'started',
11
+ 'completed',
12
+ 'failed',
13
+ 'conflict',
14
+ 'queue',
15
+ 'checkpoint',
16
+ ];
17
+ function boundedInteger(value, min, max, label) {
18
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max) {
19
+ throw new SyncObservabilityError('invalid', `${label} must be a safe integer from ${min} to ${max}.`);
20
+ }
21
+ return value;
22
+ }
23
+ function optionsRecord(value) {
24
+ if (typeof value !== 'object' ||
25
+ value === null ||
26
+ Array.isArray(value) ||
27
+ Object.getPrototypeOf(value) !== Object.prototype ||
28
+ Object.getOwnPropertySymbols(value).length !== 0) {
29
+ throw new SyncObservabilityError('invalid', 'Options and observations must be plain objects.');
30
+ }
31
+ return value;
32
+ }
33
+ /** Keeps only allow-listed numeric sync signals; labels, payloads, and identifiers are never stored. */
34
+ export function createSyncObservability(options = {}) {
35
+ const rawOptions = optionsRecord(options);
36
+ if (Object.keys(rawOptions).some((key) => !['maxEvents', 'maxQueueSize', 'staleAfterMs'].includes(key))) {
37
+ throw new SyncObservabilityError('invalid', 'Options contain an unknown field.');
38
+ }
39
+ const maxEvents = boundedInteger(options.maxEvents ?? 200, 1, 10_000, 'maxEvents');
40
+ const maxQueueSize = boundedInteger(options.maxQueueSize ?? 10_000, 1, 1_000_000, 'maxQueueSize');
41
+ const staleAfterMs = boundedInteger(options.staleAfterMs ?? 60_000, 0, 86_400_000, 'staleAfterMs');
42
+ let observations = [];
43
+ let lagMs = 0;
44
+ let queueSize = 0;
45
+ let conflicts = 0;
46
+ let failures = 0;
47
+ let completed = 0;
48
+ let droppedEvents = false;
49
+ const metrics = (now = Date.now()) => {
50
+ const observedAt = boundedInteger(now, 0, Number.MAX_SAFE_INTEGER, 'now');
51
+ const lastActivityAt = observations.at(-1)?.at ?? null;
52
+ if (lastActivityAt !== null && observedAt < lastActivityAt)
53
+ throw new SyncObservabilityError('invalid', 'now predates the last observation.');
54
+ let health = 'unknown';
55
+ if (lastActivityAt !== null) {
56
+ health =
57
+ observedAt - lastActivityAt > staleAfterMs
58
+ ? 'stale'
59
+ : queueSize >= maxQueueSize
60
+ ? 'backlogged'
61
+ : conflicts > 0
62
+ ? 'conflicted'
63
+ : 'healthy';
64
+ }
65
+ return { health, observedAt, lastActivityAt, lagMs, queueSize, conflicts, failures, completed };
66
+ };
67
+ return {
68
+ record(input) {
69
+ const raw = optionsRecord(input);
70
+ if (Object.keys(raw).some((key) => !['kind', 'at', 'lagMs', 'queueSize'].includes(key))) {
71
+ throw new SyncObservabilityError('invalid', 'Observation contains an unknown field.');
72
+ }
73
+ if (typeof input.kind !== 'string' || !KINDS.includes(input.kind)) {
74
+ throw new SyncObservabilityError('invalid', 'Observation kind is not supported.');
75
+ }
76
+ const at = boundedInteger(input.at, 0, Number.MAX_SAFE_INTEGER, 'at');
77
+ const nextLag = boundedInteger(input.lagMs ?? 0, 0, Number.MAX_SAFE_INTEGER, 'lagMs');
78
+ const nextQueue = boundedInteger(input.queueSize ?? 0, 0, maxQueueSize, 'queueSize');
79
+ const previous = observations.at(-1);
80
+ if (previous && at < previous.at) {
81
+ throw new SyncObservabilityError('invalid', 'Observation timestamps must be nondecreasing.');
82
+ }
83
+ const safe = { kind: input.kind, at, lagMs: nextLag, queueSize: nextQueue };
84
+ observations.push(safe);
85
+ if (observations.length > maxEvents) {
86
+ observations = observations.slice(-maxEvents);
87
+ droppedEvents = true;
88
+ }
89
+ lagMs = nextLag;
90
+ queueSize = nextQueue;
91
+ if (input.kind === 'conflict')
92
+ conflicts++;
93
+ if (input.kind === 'failed')
94
+ failures++;
95
+ if (input.kind === 'completed')
96
+ completed++;
97
+ },
98
+ metrics,
99
+ exportDiagnostics(now = Date.now()) {
100
+ return {
101
+ format: 'lp-sync-diagnostics',
102
+ version: 1,
103
+ metrics: metrics(now),
104
+ observations: observations.map((entry) => ({ ...entry })),
105
+ truncated: droppedEvents,
106
+ };
107
+ },
108
+ };
109
+ }
package/package.json CHANGED
@@ -1,6 +1,63 @@
1
1
  {
2
2
  "name": "@lp-labs/sync-observability",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Bounded numeric synchronization metrics and payload-free diagnostics.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/cjs/index.js",
8
+ "module": "./dist/esm/index.js",
9
+ "types": "./dist/esm/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "import": {
13
+ "types": "./dist/esm/index.d.ts",
14
+ "default": "./dist/esm/index.js"
15
+ },
16
+ "require": {
17
+ "types": "./dist/cjs/index.d.ts",
18
+ "default": "./dist/cjs/index.js"
19
+ }
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "sideEffects": false,
29
+ "engines": {
30
+ "node": ">=18"
31
+ },
32
+ "scripts": {
33
+ "build": "node scripts/build.mjs",
34
+ "typecheck": "npm run build && node scripts/check-types.mjs",
35
+ "test": "npm run build && node --test tests/*.test.mjs",
36
+ "format": "prettier --write src scripts tests *.json README.md",
37
+ "format:check": "prettier --check src scripts tests *.json README.md",
38
+ "prepack": "npm run build"
39
+ },
40
+ "devDependencies": {
41
+ "typescript": "^5.9.3",
42
+ "prettier": "^3.6.2"
43
+ },
44
+ "prettier": {
45
+ "singleQuote": true,
46
+ "semi": true,
47
+ "trailingComma": "all",
48
+ "printWidth": 100,
49
+ "endOfLine": "lf"
50
+ },
51
+ "publishConfig": {
52
+ "access": "public",
53
+ "registry": "https://registry.npmjs.org/"
54
+ },
55
+ "author": {
56
+ "name": "Libin Prasanth",
57
+ "url": "https://www.linkedin.com/in/libinprasanth/"
58
+ },
59
+ "funding": {
60
+ "type": "paypal",
61
+ "url": "https://www.paypal.me/LibinPrasanth"
62
+ }
63
+ }