Initial Commit

This commit is contained in:
2026-05-27 23:29:53 +01:00
commit fbc70f96e6
10000 changed files with 1102152 additions and 0 deletions

View File

@@ -0,0 +1,217 @@
# OpenSpec Change: enterprise-network-observability
- **Change ID**: enterprise-network-observability
- **Package**: `@suaveplan/network-observability`
- **Category**: universal/network
- **Target path**: `universal/network/network-observability`
- **Status**: SUPERSEDED-BY-GENESIS-WAVE
- **Date**: 2026-04-24
---
## Summary
Deliver `@suaveplan/network-observability` on the genesis branch from scratch at enterprise quality. The package provides network metrics collection and distributed tracing instrumentation: RTT measurements, bandwidth estimation, connection health scoring, packet loss tracking, span propagation across network hops, and structured event emission for network anomalies. Genesis adds structured errors via `@suaveplan/error`, Zod schemas for all metric types, deep OTel integration (this package is specifically about observability), `AbortSignal` on collection tasks, injectable `Clock` for measurement timestamps, and event-bus emission for threshold breaches.
---
## Current-state audit (genesis)
The package does not exist on genesis yet — this is a fresh build.
---
## Available workspace deps on genesis
| Package | Role |
|---|---|
| `@suaveplan/error` (`workspace:^`) | Base class for `NetworkObservabilityError`; stable error codes |
| `@suaveplan/types` (`workspace:^`) | `LoggerLike`, `Clock`, `EventBusLike` |
| `@suaveplan/events` (`workspace:^`) | Event bus for threshold breach notifications |
| `@suaveplan/logger` (`workspace:^`) | Structured logging |
| `@suaveplan/timing` (`workspace:^`) | Stopwatch and throttle for measurement intervals |
| `zod` (`catalog:forms`) | Zod schemas for all public metric types |
| `@opentelemetry/api` (`catalog:observability`) | Deep OTel integration — this package enriches OTel spans |
| `tslib` (`catalog:build`) | Runtime helpers |
Dev deps: `vitest`, `@vitest/coverage-istanbul`, `fast-check` (all `catalog:testing`).
---
## Public API surface
### Core
```ts
function createNetworkMonitor(options?: NetworkMonitorOptions): NetworkMonitor
interface NetworkMonitor {
start(signal?: AbortSignal): Promise<void>
stop(): void
snapshot(): NetworkSnapshot
history(limit?: number): ReadonlyArray<NetworkSnapshot>
on(event: NetworkEvent, handler: (data: NetworkSnapshot) => void): () => void
}
```
### Metric types
```ts
interface NetworkSnapshot {
readonly timestamp: number
readonly rtt: RttMetrics
readonly bandwidth: BandwidthMetrics
readonly packetLoss: PacketLossMetrics
readonly health: NetworkHealthScore
}
interface RttMetrics {
readonly current: number
readonly min: number
readonly max: number
readonly avg: number
readonly p50: number
readonly p95: number
readonly p99: number
readonly samples: number
}
interface BandwidthMetrics {
readonly downloadBps: number
readonly uploadBps?: number
readonly estimatedAt: number
}
interface PacketLossMetrics {
readonly rate: number // 0–1
readonly total: number
readonly lost: number
}
interface NetworkHealthScore {
readonly score: number // 0–100
readonly grade: 'excellent' | 'good' | 'fair' | 'poor' | 'critical'
readonly factors: ReadonlyArray<HealthFactor>
}
interface HealthFactor {
readonly name: string
readonly weight: number
readonly score: number
readonly impact: 'positive' | 'negative' | 'neutral'
}
```
### Span propagation
```ts
function injectTraceContext(headers: Record<string, string>): Record<string, string>
function extractTraceContext(headers: Record<string, string>): SpanContext | null
function withNetworkSpan<T>(name: string, fn: () => Promise<T>, attributes?: NetworkSpanAttributes): Promise<T>
interface NetworkSpanAttributes {
url?: string
method?: string
statusCode?: number
requestSize?: number
responseSize?: number
}
```
### Options
```ts
interface NetworkMonitorOptions {
measureIntervalMs?: number
historySize?: number
rttTargetUrl?: string
thresholds?: NetworkThresholds
logger?: LoggerLike
clock?: Clock
eventBus?: EventBusLike
}
interface NetworkThresholds {
maxRttMs?: number
minBandwidthBps?: number
maxPacketLossRate?: number
minHealthScore?: number
}
type NetworkEvent = 'snapshot' | 'threshold-breach' | 'recovery'
```
### Error codes
```ts
type NetworkObservabilityErrorCode =
| 'NET_OBS_MEASUREMENT_FAILED'
| 'NET_OBS_MONITOR_ALREADY_RUNNING'
| 'NET_OBS_ABORT'
function registerNetworkObservabilityErrorCodes(): void
```
---
## Genesis additions
1. **Structured `NetworkObservabilityError`** with stable `NET_OBS.*` codes
2. **Zod schemas** for all metric types and options
3. **Health scoring algorithm** — weighted composite of RTT, packet loss, bandwidth; grades A–F
4. **W3C Trace Context propagation** helpers (`injectTraceContext`, `extractTraceContext`)
5. **Threshold alerting** — emits event-bus events when thresholds are breached or recovered
6. **Injectable `Clock`** for deterministic timestamp tests
7. **OTel deep integration** — this package is the entry point for network-layer OTel spans
---
## File layout
```text
universal/network/network-observability/
package.json
tsconfig.json
vitest.config.ts
src/
index.ts
error-codes.ts
constants/
index.ts
types/
common.ts
common.md
core/
monitor/
monitor.ts
monitor.md
monitor.types.ts
monitor.test.ts
index.ts
health/
health.ts
health.md
health.test.ts
index.ts
tracing/
propagation.ts
propagation.md
propagation.test.ts
index.ts
metrics/
rtt.ts
rtt.md
rtt.test.ts
bandwidth.ts
bandwidth.md
bandwidth.test.ts
tests/
integration.test.ts
property.test.ts
```
---
## Impact
**Workspace dep prerequisites**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/events`, `@suaveplan/logger`, `@suaveplan/timing` must be published.

View File

@@ -0,0 +1,92 @@
# Tasks: enterprise-network-observability
**Change ID**: enterprise-network-observability
**Package**: `@suaveplan/network-observability`
**Target path**: `universal/network/network-observability`
**Prerequisite packages on Verdaccio**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/events`, `@suaveplan/logger`, `@suaveplan/timing`
---
## 1. Scaffold
- [x] Create `universal/network/network-observability/` with `src/`, `tests/`, and all feature subdirectories.
- [x] Write `package.json` at version `0.1.0`: `"sideEffects": false`, exports map, deps per `proposal.md`.
- [x] Write `tsconfig.json`, `vitest.config.ts`, scripts.
---
## 2. Types and error codes
- [x] Define all public types in `src/types/common.ts`: `NetworkSnapshot`, `RttMetrics`, `BandwidthMetrics`, `PacketLossMetrics`, `NetworkHealthScore`, `HealthFactor`, `NetworkMonitorOptions`, `NetworkThresholds`, `NetworkEvent`, `NetworkSpanAttributes`.
- [x] Write `src/types/common.md` (≥200 words, simple + advanced examples).
- [x] Define error codes in `src/error-codes.ts`.
- [x] Write Zod schemas in `src/types/schemas.ts` + `src/types/schemas.md`.
---
## 3. RTT metrics (`src/metrics/rtt.ts`)
- [x] Implement `measureRtt(url: string, samples?: number, signal?: AbortSignal): Promise<RttMetrics>`:
- Fire `samples` (default 5) HTTP HEAD or WebSocket ping probes in sequence.
- Compute min/max/avg/p50/p95/p99 over results.
- [x] Write `rtt.test.ts` + `rtt.md`.
---
## 4. Bandwidth metrics (`src/metrics/bandwidth.ts`)
- [x] Implement `measureBandwidth(url: string, signal?: AbortSignal): Promise<BandwidthMetrics>`:
- Download a known-size payload; compute bytes / elapsed time.
- [x] Write `bandwidth.test.ts` + `bandwidth.md`.
---
## 5. Health scoring (`src/core/health/`)
- [x] Implement `computeHealthScore(snapshot: Partial<NetworkSnapshot>, thresholds?: NetworkThresholds): NetworkHealthScore`:
- RTT factor (40%): 100 if < 50ms, linear decay to 0 at 500ms.
- Packet loss factor (35%): 100 if 0%, linear decay to 0 at 10%.
- Bandwidth factor (25%): 100 if > 10Mbps, linear decay to 0 at 0.
- Weighted sum = score; grade from score: 80+ excellent, 60+ good, 40+ fair, 20+ poor, <20 critical.
- [x] Write `health.test.ts` (≤500 lines): known inputs produce expected scores and grades.
- [x] Write `health.md` (≥200 words).
---
## 6. Trace context propagation (`src/tracing/`)
- [x] Implement `injectTraceContext(headers)` — calls `context.with(...)` + OTel `TextMapPropagator.inject`.
- [x] Implement `extractTraceContext(headers)` — calls OTel `TextMapPropagator.extract`.
- [x] Implement `withNetworkSpan(name, fn, attributes?)` — wraps `fn` in a span with network attributes.
- [x] Write `propagation.test.ts` + `propagation.md`.
---
## 7. Network monitor (`src/core/monitor/`)
- [x] Implement `createNetworkMonitor(options?)`:
- On `start()`, begin measurement loop using `@suaveplan/timing` interval timer.
- Each iteration: call RTT probe, compute health score, push to history ring buffer.
- Emit `snapshot` event on each measurement.
- Check against thresholds; emit `threshold-breach` on violation, `recovery` on recovery.
- OTel: gauge `net.rtt_ms`, gauge `net.health_score`, gauge `net.packet_loss`.
- [x] Implement `monitor.snapshot()`, `monitor.history(limit?)`, `monitor.on(event, handler)`.
- [x] Write `monitor.test.ts` (≤500 lines): start/stop, snapshot, threshold breach + recovery event.
- [x] Write `monitor.md` (≥200 words).
---
## 8. Property-based tests (`tests/property.test.ts`)
- [x] Health score monotonicity: increasing RTT (all else equal) never increases the score.
- [x] Grade ordering: `score >= 80 ⇒ excellent`, grade boundaries consistent.
---
## 9. Docs and verify
- [x] All per-file `.md` files per layout in `proposal.md`.
- [x] `universal/network/network-observability/README.md`.
- [x] `bunx turbo lint typecheck test test:coverage --filter=@suaveplan/network-observability` — all green, 100% coverage.
- [x] `bun scripts/publish.ts --package @suaveplan/network-observability`.
- [x] Update `CLAUDE.md`. Archive change folder.