Initial Commit
This commit is contained in:
253
openspec/changes/enterprise-service-discovery/proposal.md
Normal file
253
openspec/changes/enterprise-service-discovery/proposal.md
Normal file
@@ -0,0 +1,253 @@
|
||||
# OpenSpec Change: enterprise-service-discovery
|
||||
|
||||
- **Change ID**: enterprise-service-discovery
|
||||
- **Package**: `@suaveplan/service-discovery`
|
||||
- **Category**: universal
|
||||
- **Target path**: `universal/network/service-discovery`
|
||||
- **Status**: PROPOSED
|
||||
- **Date**: 2026-04-24
|
||||
- **Reference spec**: `/mnt/s/web/suaveplan/enterprise/service-discovery.md`
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
Deliver `@suaveplan/service-discovery` on the genesis branch from scratch at enterprise quality. The package provides a service registry and discovery system: `ServiceRegistry` (register/deregister/lookup services by name and tags), health-check scheduler (HTTP and TCP probes, injectable), TTL-based expiry, `ServiceResolver` with round-robin and weighted load balancing, in-memory and pluggable backends, and event-bus change notifications. Pure TypeScript, no platform hard deps.
|
||||
|
||||
---
|
||||
|
||||
## Current-state audit (genesis)
|
||||
|
||||
The package does not exist on genesis yet — this is a fresh build. No prior source, no test results, no coverage data. The main-branch package had 97.76% coverage.
|
||||
|
||||
---
|
||||
|
||||
## Available workspace deps on genesis
|
||||
|
||||
| Package | Role |
|
||||
|---|---|
|
||||
| `@suaveplan/error` (`workspace:^`) | Base class for `ServiceDiscoveryError`; `SERVICE_DISCOVERY.*` codes |
|
||||
| `@suaveplan/types` (`workspace:^`) | `LoggerLike`, `Clock`, `StorageLike` |
|
||||
| `@suaveplan/events` (`workspace:^`) | Event bus for registry-change notifications |
|
||||
| `@suaveplan/network` (`workspace:^`) | `HttpClient` for HTTP health probes |
|
||||
| `@suaveplan/retry` (`workspace:^`) | Retry on health-check probes |
|
||||
| `zod` (`catalog:forms`) | Zod schemas for all public option types |
|
||||
| `@opentelemetry/api` (`catalog:observability`) | Spans + counters |
|
||||
|
||||
Dev deps: `vitest`, `@vitest/coverage-istanbul`, `fast-check`, `mitata` (all `catalog:testing`).
|
||||
|
||||
---
|
||||
|
||||
## Public API
|
||||
|
||||
### Core types
|
||||
|
||||
```ts
|
||||
class ServiceDiscoveryError extends SuaveplanError
|
||||
|
||||
type ServiceStatus = 'healthy' | 'unhealthy' | 'unknown'
|
||||
type HealthCheckType = 'http' | 'tcp' | 'custom'
|
||||
type LoadBalancingStrategy = 'round-robin' | 'weighted' | 'random' | 'first-healthy'
|
||||
|
||||
interface ServiceEndpoint {
|
||||
host: string
|
||||
port: number
|
||||
protocol?: string // default: 'http'
|
||||
path?: string // default: '/'
|
||||
}
|
||||
|
||||
interface HealthCheck {
|
||||
type: HealthCheckType
|
||||
intervalMs?: number // default: 30000
|
||||
timeoutMs?: number // default: 5000
|
||||
failureThreshold?: number // default: 3; mark unhealthy after N consecutive failures
|
||||
successThreshold?: number // default: 1; mark healthy after N consecutive successes
|
||||
customCheck?: (endpoint: ServiceEndpoint) => Promise<boolean>
|
||||
}
|
||||
|
||||
interface ServiceRegistration {
|
||||
id: string // unique per instance
|
||||
name: string // service name (logical)
|
||||
version?: string
|
||||
endpoint: ServiceEndpoint
|
||||
tags?: string[]
|
||||
metadata?: Record<string, string>
|
||||
ttlMs?: number // auto-expire if not refreshed; 0 = no expiry
|
||||
healthCheck?: HealthCheck
|
||||
weight?: number // for weighted load balancing; default: 1
|
||||
}
|
||||
|
||||
interface ServiceInstance extends ServiceRegistration {
|
||||
status: ServiceStatus
|
||||
registeredAt: number // unix epoch ms
|
||||
lastSeenAt: number
|
||||
lastCheckedAt?: number
|
||||
failureCount: number
|
||||
successCount: number
|
||||
}
|
||||
|
||||
interface RegistryBackend {
|
||||
register(instance: ServiceRegistration): Promise<void>
|
||||
deregister(id: string): Promise<void>
|
||||
get(id: string): Promise<ServiceInstance | undefined>
|
||||
list(name?: string, tags?: string[]): Promise<ServiceInstance[]>
|
||||
refresh(id: string): Promise<void> // reset TTL
|
||||
updateStatus(id: string, status: ServiceStatus): Promise<void>
|
||||
}
|
||||
|
||||
interface ServiceRegistryOptions {
|
||||
backend?: RegistryBackend // default: MemoryRegistryBackend
|
||||
events?: EventBusLike // for change notifications
|
||||
clock?: Clock
|
||||
logger?: LoggerLike
|
||||
}
|
||||
|
||||
class ServiceRegistry {
|
||||
constructor(options?: ServiceRegistryOptions)
|
||||
register(registration: ServiceRegistration): Promise<void>
|
||||
deregister(id: string): Promise<void>
|
||||
refresh(id: string): Promise<void>
|
||||
get(id: string): Promise<ServiceInstance | undefined>
|
||||
list(name?: string, tags?: string[]): Promise<ServiceInstance[]>
|
||||
listHealthy(name: string, tags?: string[]): Promise<ServiceInstance[]>
|
||||
startHealthChecks(client?: HttpClient): void
|
||||
stopHealthChecks(): void
|
||||
}
|
||||
|
||||
interface ServiceResolverOptions {
|
||||
registry: ServiceRegistry
|
||||
strategy?: LoadBalancingStrategy // default: 'round-robin'
|
||||
clock?: Clock
|
||||
logger?: LoggerLike
|
||||
}
|
||||
|
||||
class ServiceResolver {
|
||||
constructor(options: ServiceResolverOptions)
|
||||
resolve(name: string, tags?: string[]): Promise<ServiceInstance>
|
||||
resolveAll(name: string, tags?: string[]): Promise<ServiceInstance[]>
|
||||
}
|
||||
|
||||
function createServiceRegistry(options?: ServiceRegistryOptions): ServiceRegistry
|
||||
function createServiceResolver(options: ServiceResolverOptions): ServiceResolver
|
||||
|
||||
// In-memory backend (default)
|
||||
class MemoryRegistryBackend implements RegistryBackend { ... }
|
||||
```
|
||||
|
||||
### Error codes
|
||||
|
||||
```ts
|
||||
type ServiceDiscoveryErrorCode =
|
||||
| 'SERVICE_DISCOVERY_NOT_FOUND'
|
||||
| 'SERVICE_DISCOVERY_ALREADY_REGISTERED'
|
||||
| 'SERVICE_DISCOVERY_HEALTH_CHECK_FAILED'
|
||||
| 'SERVICE_DISCOVERY_NO_HEALTHY_INSTANCES'
|
||||
| 'SERVICE_DISCOVERY_TTL_EXPIRED'
|
||||
| 'SERVICE_DISCOVERY_INVALID_REGISTRATION'
|
||||
|
||||
const SERVICE_DISCOVERY_ERROR_METADATA: Readonly<Record<ServiceDiscoveryErrorCode, CodeMetadata>>
|
||||
function registerServiceDiscoveryErrorCodes(): void
|
||||
```
|
||||
|
||||
### Zod schemas
|
||||
|
||||
```ts
|
||||
ServiceEndpointSchema
|
||||
HealthCheckSchema
|
||||
ServiceRegistrationSchema
|
||||
ServiceInstanceSchema
|
||||
ServiceRegistryOptionsSchema
|
||||
ServiceResolverOptionsSchema
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## New additions for genesis
|
||||
|
||||
1. **Pluggable `RegistryBackend`** — `MemoryRegistryBackend` ships by default; callers can swap to Redis, SurrealDB, or any other store implementing the interface.
|
||||
2. **Health-check scheduler** — HTTP probes use `@suaveplan/network` `HttpClient`; TCP probes use injected `net.connect`-compatible function. All timers use injectable `Clock`.
|
||||
3. **TTL expiry** — background sweeper removes expired registrations; sweep interval = min(TTL) / 2.
|
||||
4. **Event notifications** — `'service:registered'`, `'service:deregistered'`, `'service:status-changed'` events emitted on `EventBusLike`.
|
||||
5. **Load balancing** — four strategies: round-robin (stateful cursor), weighted (WRR), random (injected RNG), first-healthy (deterministic).
|
||||
6. **`AbortSignal` propagation** — `resolve` accepts optional signal; throws `ServiceDiscoveryError(SERVICE_DISCOVERY_NO_HEALTHY_INSTANCES)` on abort.
|
||||
7. **OTel instrumentation** — counter `service_discovery.register_total`, counter `service_discovery.resolve_total`, histogram `service_discovery.resolve_duration_ms`, counter `service_discovery.health_check_total` (attr `service_discovery.result`).
|
||||
8. **Property-based tests** — round-robin resolves to all registered healthy instances in N calls (no skips), weighted strategy probability distribution converges, register+deregister+list invariants.
|
||||
9. **Benchmark suite** — `register` 100 services, `resolve` hot path (round-robin, 1000 instances), health check scheduler overhead.
|
||||
|
||||
---
|
||||
|
||||
## File layout
|
||||
|
||||
```text
|
||||
universal/network/service-discovery/
|
||||
package.json
|
||||
tsconfig.json
|
||||
vitest.config.ts
|
||||
src/
|
||||
index.ts
|
||||
error-codes.ts
|
||||
constants/
|
||||
index.ts
|
||||
types/
|
||||
common.ts
|
||||
common.md
|
||||
core/
|
||||
service-registry/
|
||||
service-registry.ts
|
||||
service-registry.md
|
||||
service-registry.types.ts
|
||||
service-registry.test.ts
|
||||
index.ts
|
||||
service-resolver/
|
||||
service-resolver.ts
|
||||
service-resolver.md
|
||||
service-resolver.types.ts
|
||||
service-resolver.test.ts
|
||||
index.ts
|
||||
backends/
|
||||
memory-backend/
|
||||
memory-backend.ts
|
||||
memory-backend.md
|
||||
memory-backend.test.ts
|
||||
index.ts
|
||||
health/
|
||||
http-probe/
|
||||
http-probe.ts
|
||||
http-probe.md
|
||||
http-probe.test.ts
|
||||
index.ts
|
||||
tcp-probe/
|
||||
tcp-probe.ts
|
||||
tcp-probe.md
|
||||
tcp-probe.test.ts
|
||||
index.ts
|
||||
health-scheduler/
|
||||
health-scheduler.ts
|
||||
health-scheduler.md
|
||||
health-scheduler.test.ts
|
||||
index.ts
|
||||
balancing/
|
||||
round-robin/
|
||||
round-robin.ts
|
||||
round-robin.md
|
||||
round-robin.test.ts
|
||||
index.ts
|
||||
weighted/
|
||||
weighted.ts
|
||||
weighted.md
|
||||
weighted.test.ts
|
||||
index.ts
|
||||
__benchmarks__/
|
||||
service-discovery.bench.ts
|
||||
tests/
|
||||
integration.test.ts
|
||||
property.test.ts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Impact
|
||||
|
||||
**Downstream**: any microservice or multi-peer architecture on genesis; `@suaveplan/api-gateway` consumers.
|
||||
**Breaking changes**: none — fresh build.
|
||||
**Prerequisites**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/events`, `@suaveplan/network`, `@suaveplan/retry` published to Verdaccio.
|
||||
109
openspec/changes/enterprise-service-discovery/tasks.md
Normal file
109
openspec/changes/enterprise-service-discovery/tasks.md
Normal file
@@ -0,0 +1,109 @@
|
||||
# Tasks: enterprise-service-discovery
|
||||
|
||||
**Change ID**: enterprise-service-discovery
|
||||
**Package**: `@suaveplan/service-discovery`
|
||||
**Target path**: `universal/network/service-discovery`
|
||||
**Prerequisite packages on Verdaccio**: `@suaveplan/error`, `@suaveplan/types`, `@suaveplan/events`, `@suaveplan/network`, `@suaveplan/retry`
|
||||
|
||||
---
|
||||
|
||||
## 0. Pre-flight (non-negotiable)
|
||||
|
||||
- [ ] 0.1 Confirm clean working tree (`git status` reports nothing) and no in-flight worktrees with uncommitted work (`git worktree list` then `git status` in each)
|
||||
- [ ] 0.2 If any worktrees exist under `.claude/worktrees/`, account for each one: still-active agent, work-pending-merge, or stale-and-prune. Stale worktrees MUST be removed (`git worktree remove`) before opening a new one — code that has been lost twice on main is the failure mode this guards against.
|
||||
- [ ] 0.3 Confirm the package set in `MANIFEST.md` matches `find packages -maxdepth 3 -name package.json` count. Drift here means a prior change archived without regenerating the manifest.
|
||||
|
||||
## 1. Scaffold
|
||||
|
||||
- [ ] Create directory `universal/network/service-discovery/` with `src/`, `tests/`, `src/__benchmarks__/`, and all feature subdirectories per the layout in `proposal.md`.
|
||||
- [ ] Write `package.json` at version `0.1.0` with `"type": "module"`, `"sideEffects": false`, full `exports` map, deps: `@suaveplan/error workspace:^`, `@suaveplan/types workspace:^`, `@suaveplan/events workspace:^`, `@suaveplan/network workspace:^`, `@suaveplan/retry workspace:^`, `zod catalog:forms`, `@opentelemetry/api catalog:observability`.
|
||||
- [ ] Write `tsconfig.json` extending `@suaveplan/typescript-config/library.json`.
|
||||
- [ ] Write `vitest.config.ts` using `createTestConfig()` from `@suaveplan/testing/config`.
|
||||
- [ ] Add `lint`, `typecheck`, `test`, `test:coverage`, `build`, `docs:check` scripts.
|
||||
|
||||
---
|
||||
|
||||
## 2. Types + errors
|
||||
|
||||
- [ ] Write `src/types/common.ts` — all interfaces and type aliases from proposal.
|
||||
- [ ] Write `src/types/common.md`.
|
||||
- [ ] Write `src/error-codes.ts` — `ServiceDiscoveryErrorCode`, `SERVICE_DISCOVERY_ERROR_METADATA`, `registerServiceDiscoveryErrorCodes()`.
|
||||
- [ ] Write Zod schemas: `ServiceEndpointSchema`, `HealthCheckSchema`, `ServiceRegistrationSchema`, `ServiceInstanceSchema`, `ServiceRegistryOptionsSchema`, `ServiceResolverOptionsSchema`.
|
||||
|
||||
---
|
||||
|
||||
## 3. MemoryRegistryBackend
|
||||
|
||||
- [ ] Implement `MemoryRegistryBackend implements RegistryBackend` — `Map<string, ServiceInstance>` store, `register`/`deregister`/`get`/`list`/`refresh`/`updateStatus`. `list` supports optional `name` and `tags` filters (tag filter = intersection).
|
||||
- [ ] Write `memory-backend.test.ts` (≤500 lines): register, deregister, list with filters, refresh resets TTL, updateStatus.
|
||||
- [ ] Write `memory-backend.md`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Health checks
|
||||
|
||||
### HTTP probe
|
||||
|
||||
- [ ] Implement `runHttpProbe(endpoint, check, httpClient): Promise<boolean>` — GET `<protocol>://<host>:<port><path>`, return `true` if status 2xx, false otherwise; timeout from `check.timeoutMs`.
|
||||
- [ ] Write `http-probe.test.ts` (uses stub `HttpClient`) and `http-probe.md`.
|
||||
|
||||
### TCP probe
|
||||
|
||||
- [ ] Implement `runTcpProbe(endpoint, check, connectFn): Promise<boolean>` — injectable `connectFn(host, port): Promise<void>` (abstracts `net.connect`); returns `true` on success within timeout.
|
||||
- [ ] Write `tcp-probe.test.ts` and `tcp-probe.md`.
|
||||
|
||||
### Health scheduler
|
||||
|
||||
- [ ] Implement `HealthScheduler` — for each registered instance with a `healthCheck`, runs probes on `intervalMs` using injectable `Clock`; updates `ServiceInstance.status` via backend; tracks consecutive failure/success counts; emits events on status change.
|
||||
- [ ] Write `health-scheduler.test.ts` (≤500 lines): probe triggers, failure threshold, success threshold, stop clears timers.
|
||||
- [ ] Write `health-scheduler.md`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Load balancing strategies
|
||||
|
||||
- [ ] Implement `roundRobin(instances): ServiceInstance` — stateful cursor (closure-based, not class-level to keep it pure).
|
||||
- [ ] Implement `weighted(instances): ServiceInstance` — weighted random selection (cumulative weight table + RNG via injectable function).
|
||||
- [ ] Write `round-robin.test.ts`, `round-robin.md`, `weighted.test.ts`, `weighted.md`.
|
||||
|
||||
---
|
||||
|
||||
## 6. ServiceRegistry
|
||||
|
||||
- [ ] Implement `ServiceRegistry` — delegates to `backend`; TTL sweeper (setInterval on `Clock`); emits `service:registered`, `service:deregistered`, `service:status-changed` on `events` bus; `startHealthChecks`/`stopHealthChecks`.
|
||||
- [ ] Wire OTel: counter `service_discovery.register_total`, counter `service_discovery.health_check_total`.
|
||||
- [ ] Write `service-registry.test.ts` (≤500 lines): register, deregister, listHealthy, TTL expiry, event emission.
|
||||
- [ ] Write `service-registry.md`.
|
||||
|
||||
---
|
||||
|
||||
## 7. ServiceResolver
|
||||
|
||||
- [ ] Implement `ServiceResolver` — `resolve` calls `registry.listHealthy`, applies load balancing strategy, throws `SERVICE_DISCOVERY_NO_HEALTHY_INSTANCES` if empty; `resolveAll` returns full healthy list.
|
||||
- [ ] Wire OTel: counter `service_discovery.resolve_total`, histogram `service_discovery.resolve_duration_ms`.
|
||||
- [ ] Write `service-resolver.test.ts` (≤500 lines): resolve with round-robin, weighted, random, first-healthy; empty list throws; abort signal.
|
||||
- [ ] Write `service-resolver.md`.
|
||||
|
||||
---
|
||||
|
||||
## 8. Benchmarks
|
||||
|
||||
- [ ] Write `src/__benchmarks__/service-discovery.bench.ts` — `register` 100 services, `resolve` hot path round-robin 1000 instances, health check scheduler overhead.
|
||||
|
||||
---
|
||||
|
||||
## 9. Tests
|
||||
|
||||
- [ ] Write `tests/integration.test.ts` — full lifecycle: register → health check → resolve → deregister.
|
||||
- [ ] Write `tests/property.test.ts` (fast-check) — round-robin covers all instances in N calls, weighted distribution converges, register+list invariants.
|
||||
|
||||
---
|
||||
|
||||
## 10. Docs + verify + publish
|
||||
|
||||
- [ ] All co-located `.md` files (≥200 words each).
|
||||
- [ ] Write `README.md` at package root.
|
||||
- [ ] `bunx turbo lint typecheck test --filter=@suaveplan/service-discovery` — green.
|
||||
- [ ] `bunx turbo test:coverage --filter=@suaveplan/service-discovery` — 100%.
|
||||
- [ ] `bun scripts/publish.ts --package @suaveplan/service-discovery`.
|
||||
- [ ] Archive to `openspec/archive/2026-04-24-enterprise-service-discovery/`.
|
||||
Reference in New Issue
Block a user