diff --git a/CLAUDE.md b/CLAUDE.md index db87a1f..9e3c05a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -119,6 +119,26 @@ Bitbucket, and GitLab; in production, ensure SSH authentication credentials are SvelteKit's CSRF Origin check depends on this value instead of deriving it from the incoming Host header, preventing bypasses when running behind a proxy that rewrites Host headers. +## Domain events + +Services announce what happened on an in-process event bus in `#lib/server/events`; the design is +in `docs/adr/0001-event-bus-and-alerts.md`. + +- Names: `..`, snake_case, past participle + (`code_report.analysis.completed`, `vault.secret.created`, `access.granted`). Declare each type + and its payload in `DomainEventMap` (`src/lib/server/events/types.ts`). +- Publish only **after** the GitDB write succeeded, with the right `scope` + (`organizationId` / `projectId`). `publish()` returns immediately; handlers run asynchronously, + in order per subscriber, and a failing handler is only logged. +- Delivery is at-most-once and per process; events are not persisted. +- The actor comes from the request context (`userId` / `apiKeyId` set in `hooks.server.ts`), + falling back to `system`. +- Inject `EventBus` through the service constructor from the module's `index.ts`; only composition + roots import the `eventBus` singleton. In unit tests use `RecordingEventBus` from + `#lib/server/events/testing`. +- Payloads **never** contain secrets (vault values, invitation/reset tokens or URLs, hashes, API + keys), and alert recipients are always filtered with `cancanService`. + ## Authorization Permission grants are always scope-prefixed and match the catalog in `src/lib/config/permissions.ts` diff --git a/docs/adr/0001-event-bus-and-alerts.md b/docs/adr/0001-event-bus-and-alerts.md new file mode 100644 index 0000000..e828be7 --- /dev/null +++ b/docs/adr/0001-event-bus-and-alerts.md @@ -0,0 +1,122 @@ +# ADR 0001: Local domain event bus and configurable alerts + +- Status: Proposed +- Date: 2026-11-20 +- Issues: #76 (epic), #77 (this ADR and the `EventBus` class) + +## Context + +Notifications are direct calls from services to concrete notifiers (`InvitationNotifier`, +`PasswordResetNotifier`). To let organization and project admins create **configurable alerts** +("when `code_report.analysis.completed` happens for service `api-gateway` with critical +vulnerabilities, email these users or roles"), services need to announce what happened without +knowing who listens. + +Constraints: GitDB is the only persistence layer, the app runs as a single SvelteKit process per +replica, and we do not want to operate a broker (Redis, Kafka, a queue) for this. + +## Decision + +Services publish **typed domain events** on an **in-process event bus** +(`#lib/server/events`). An alert engine (#79) subscribes to every event, matches the alerts +configured for the event's scope and notifies recipients by email. + +``` +Service ──publish(type, payload)──▶ EventBus (in-process) ──▶ AlertEngine ('*') ──▶ notify(Mail) +``` + +### 1. Event names + +`..` in **snake_case**, the action as a **past participle**. The +resource may be omitted when the module is the resource. + +- `code_report.analysis.completed`, `code_report.analysis.failed`, `code_report.policy.violated` +- `vault.secret.created`, `vault.env.imported` +- `project.created`, `access.granted`, `api_key.revoked` + +Each type and its payload is declared in `DomainEventMap` (`src/lib/server/events/types.ts`), so +`publish()` and `subscribe()` are type-checked end to end. + +### 2. Delivery semantics + +- Publish **after** the GitDB write has succeeded (after the repository `await`). A failed write + publishes nothing. +- **Asynchronous** dispatch: `publish()` builds the envelope and returns it immediately; handlers + run on later microtasks and add no latency to the request. +- **At-most-once**: events in flight when the process dies are lost. This is acceptable for + alerts and must not be relied on for anything that needs a guarantee. +- **Per process**: an event published in one replica does not reach the others. Multi-replica + delivery is out of scope for v1. +- **Ordering**: each subscriber receives events in publish order (a per-subscriber queue). A slow + subscriber does not delay other subscribers. +- **Isolation**: every handler runs in its own `try/catch`. A failure is logged through + `createLogger('events')` with the event `type` and `id`, and never reaches the publisher, other + handlers, or later events. +- `drain()` waits for pending handlers (tests, graceful shutdown). + +### 3. Persistence + +- **Alerts** are configuration and are stored in **GitDB** (auditable, consistent with the rest of + the platform). +- **Events are not persisted.** +- **Alert executions** (firing history) are **not** stored in GitDB in v1, to avoid one commit per + email sent: only logs, plus optionally an in-memory buffer of the last N firings per alert. + +### 4. Actor + +`#lib/server/request-context` (`AsyncLocalStorage`) carries the request actor. Besides the commit +identity (`name`, `email`) it now carries `userId` for sessions and `apiKeyId` / +`apiKeyProjectId` for API keys, set by `hooks.server.ts`. The bus resolves the event actor from it +without changing service signatures: + +| Request context | `event.actor` | +| ------------------------------- | ------------------------------------------ | +| `apiKeyId` set | `{ kind: 'api_key', apiKeyId, projectId }` | +| `userId` set | `{ kind: 'user', userId }` | +| none (startup, background work) | `{ kind: 'system' }` | + +Publishers may pass an explicit `actor` to override it. Only `name` and `email` reach GitDB. + +### 5. Security rules (mandatory for the whole epic) + +- Payloads **never** contain secrets: no vault values, invitation or password reset tokens or + URLs, password or token hashes, or API keys (a `keyPrefix` is fine). +- No recipient receives information about a resource they cannot read: recipients are **always** + filtered with `cancanService` against the event's read permission and scope. + +## Implementation + +``` +src/lib/server/events/ + types.ts DomainEventMap, DomainEvent, EventActor, EventScope + event-bus.ts EventBus interface + InProcessEventBus + testing.ts RecordingEventBus for service unit tests + index.ts HMR-safe `eventBus` singleton + exports + event-bus.test.ts +``` + +- The singleton lives on `globalThis` (`Symbol.for('gitops.events.bus')`) so Vite HMR does not + create a second bus with duplicated subscribers in development. +- Services receive an `EventBus` through their **constructor** from their module's `index.ts` + (composition root); only composition roots import the `eventBus` singleton. Unit tests inject a + `RecordingEventBus` and assert on `events` / `ofType()`. +- No new dependencies. + +## Consequences + +- Services stay decoupled from alerts; adding a new consumer means subscribing, not editing + services. +- Delivery is best effort. If we later need cross-replica delivery or guarantees, the + `EventBus` interface allows swapping the implementation (e.g. an outbox in GitDB or a broker) + without touching publishers. +- Every new event must respect the payload rules above and is covered by a no-leak test (#78). + +## Alternatives considered + +- **External broker (Redis pub/sub, Kafka, a queue)**: delivery across replicas and durability, + at the cost of a new piece of infrastructure to run for a feature that tolerates losses. Rejected + for v1. +- **Node `EventEmitter`**: synchronous dispatch, a throwing listener breaks the publisher, and no + typing per event. Rejected in favour of a small dedicated class. +- **Persisting events in GitDB**: one commit per event is too much write volume and noise in the + audit history. diff --git a/src/hooks.server.ts b/src/hooks.server.ts index bd988fc..d7e9f2f 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -118,7 +118,12 @@ const authGuard: Handle = async ({ event, resolve }) => { event.locals.apiKey = apiKey; return runWithActor( - { name: `apikey:${apiKey.name}`, email: `apikey+${apiKey.id}@gitops.local` }, + { + name: `apikey:${apiKey.name}`, + email: `apikey+${apiKey.id}@gitops.local`, + apiKeyId: apiKey.id, + apiKeyProjectId: apiKey.projectId, + }, () => resolve(event), ); } @@ -167,6 +172,7 @@ const authGuard: Handle = async ({ event, resolve }) => { const actor = { name: currentUser.username, email: currentUser.email || `${currentUser.username}@gitops.local`, + userId: currentUser.id, }; return runWithActor(actor, () => resolve(event)); }; diff --git a/src/lib/server/events/event-bus.test.ts b/src/lib/server/events/event-bus.test.ts new file mode 100644 index 0000000..ce94013 --- /dev/null +++ b/src/lib/server/events/event-bus.test.ts @@ -0,0 +1,285 @@ +import { describe, expect, it, vi } from 'vitest'; +import { runWithActor } from '#lib/server/request-context'; +import { InProcessEventBus, actorFromRequest } from './event-bus'; +import { RecordingEventBus } from './testing'; + +type TestEvents = { + 'test.item.created': { itemId: string }; + 'test.item.deleted': { itemId: string; reason: string }; +}; + +function createBus() { + const logger = { error: vi.fn() }; + const bus = new InProcessEventBus({ logger }); + return { bus, logger }; +} + +describe('InProcessEventBus', () => { + it('builds the envelope and returns it from publish', () => { + const bus = new InProcessEventBus({ + logger: { error: vi.fn() }, + now: () => new Date('2026-11-20T10:00:00.000Z'), + generateId: () => 'event-1', + }); + + const event = bus.publish( + 'test.item.created', + { itemId: 'a' }, + { scope: { organizationId: 'org-1', projectId: 'project-1' } }, + ); + + expect(event).toEqual({ + id: 'event-1', + type: 'test.item.created', + occurredAt: '2026-11-20T10:00:00.000Z', + actor: { kind: 'system' }, + scope: { organizationId: 'org-1', projectId: 'project-1' }, + payload: { itemId: 'a' }, + }); + }); + + it('delivers each event only to the subscribers of its type', async () => { + const { bus } = createBus(); + const created = vi.fn(); + const deleted = vi.fn(); + bus.subscribe('test.item.created', created); + bus.subscribe('test.item.deleted', deleted); + + bus.publish('test.item.created', { itemId: 'a' }); + await bus.drain(); + + expect(created).toHaveBeenCalledTimes(1); + expect(created.mock.calls[0][0].payload).toEqual({ itemId: 'a' }); + expect(deleted).not.toHaveBeenCalled(); + }); + + it("delivers every event to '*' subscribers", async () => { + const { bus } = createBus(); + const all = vi.fn(); + bus.subscribe('*', all); + + bus.publish('test.item.created', { itemId: 'a' }); + bus.publish('test.item.deleted', { itemId: 'a', reason: 'gone' }); + await bus.drain(); + + expect(all.mock.calls.map(([event]) => event.type)).toEqual([ + 'test.item.created', + 'test.item.deleted', + ]); + }); + + it('stops delivering after unsubscribe', async () => { + const { bus } = createBus(); + const handler = vi.fn(); + const unsubscribe = bus.subscribe('test.item.created', handler); + + bus.publish('test.item.created', { itemId: 'a' }); + await bus.drain(); + unsubscribe(); + bus.publish('test.item.created', { itemId: 'b' }); + await bus.drain(); + + expect(handler).toHaveBeenCalledTimes(1); + }); + + it('does not deliver events already queued when the subscriber unsubscribes', async () => { + const { bus } = createBus(); + const handler = vi.fn(); + const unsubscribe = bus.subscribe('test.item.created', handler); + + bus.publish('test.item.created', { itemId: 'a' }); + unsubscribe(); + await bus.drain(); + + expect(handler).not.toHaveBeenCalled(); + }); + + it('isolates a failing handler and logs it with the event type and id', async () => { + const { bus, logger } = createBus(); + const healthy = vi.fn(); + bus.subscribe('test.item.created', () => { + throw new Error('sync boom'); + }); + bus.subscribe('test.item.created', async () => { + throw new Error('async boom'); + }); + bus.subscribe('test.item.created', healthy); + + const event = bus.publish('test.item.created', { itemId: 'a' }); + await bus.drain(); + + expect(healthy).toHaveBeenCalledTimes(1); + expect(logger.error).toHaveBeenCalledTimes(2); + expect(logger.error).toHaveBeenCalledWith( + expect.objectContaining({ eventType: 'test.item.created', eventId: event.id }), + expect.any(String), + ); + }); + + it('keeps delivering later events to a subscriber whose handler failed', async () => { + const { bus } = createBus(); + const seen: string[] = []; + bus.subscribe('test.item.created', (event) => { + if (event.payload.itemId === 'a') throw new Error('boom'); + seen.push(event.payload.itemId); + }); + + bus.publish('test.item.created', { itemId: 'a' }); + bus.publish('test.item.created', { itemId: 'b' }); + await bus.drain(); + + expect(seen).toEqual(['b']); + }); + + it('does not wait for handlers in publish', async () => { + const { bus } = createBus(); + let release!: () => void; + const handler = vi.fn(() => new Promise((resolve) => (release = resolve))); + bus.subscribe('test.item.created', handler); + + bus.publish('test.item.created', { itemId: 'a' }); + + // handlers are scheduled, not called inline + expect(handler).not.toHaveBeenCalled(); + + await Promise.resolve(); + await Promise.resolve(); + expect(handler).toHaveBeenCalledTimes(1); + release(); + await bus.drain(); + }); + + it('preserves publish order per subscriber even with async handlers', async () => { + const { bus } = createBus(); + const seen: string[] = []; + bus.subscribe('test.item.created', async (event) => { + // the first event takes longer: it must still be handled first + await new Promise((resolve) => setTimeout(resolve, event.payload.itemId === 'a' ? 20 : 0)); + seen.push(event.payload.itemId); + }); + + bus.publish('test.item.created', { itemId: 'a' }); + bus.publish('test.item.created', { itemId: 'b' }); + bus.publish('test.item.created', { itemId: 'c' }); + await bus.drain(); + + expect(seen).toEqual(['a', 'b', 'c']); + }); + + it('does not let a slow subscriber delay the others', async () => { + const { bus } = createBus(); + let release!: () => void; + bus.subscribe('test.item.created', () => new Promise((resolve) => (release = resolve))); + const fast = vi.fn(); + bus.subscribe('test.item.created', fast); + + bus.publish('test.item.created', { itemId: 'a' }); + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(fast).toHaveBeenCalledTimes(1); + release(); + await bus.drain(); + }); + + it('drain waits for pending handlers, including events they publish', async () => { + const { bus } = createBus(); + const finished: string[] = []; + bus.subscribe('test.item.created', async (event) => { + await new Promise((resolve) => setTimeout(resolve, 10)); + finished.push('created'); + bus.publish('test.item.deleted', { itemId: event.payload.itemId, reason: 'cascade' }); + }); + bus.subscribe('test.item.deleted', async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + finished.push('deleted'); + }); + + bus.publish('test.item.created', { itemId: 'a' }); + await bus.drain(); + + expect(finished).toEqual(['created', 'deleted']); + }); + + it('drain resolves immediately with nothing pending', async () => { + const { bus } = createBus(); + await expect(bus.drain()).resolves.toBeUndefined(); + }); + + describe('actor', () => { + it('resolves a user actor from the request context', () => { + const { bus } = createBus(); + + const event = runWithActor({ name: 'ana', email: 'ana@example.com', userId: 'user-1' }, () => + bus.publish('test.item.created', { itemId: 'a' }), + ); + + expect(event.actor).toEqual({ kind: 'user', userId: 'user-1' }); + }); + + it('resolves an API key actor from the request context', () => { + const { bus } = createBus(); + + const event = runWithActor( + { + name: 'apikey:ci', + email: 'apikey+key-1@gitops.local', + apiKeyId: 'key-1', + apiKeyProjectId: 'project-1', + }, + () => bus.publish('test.item.created', { itemId: 'a' }), + ); + + expect(event.actor).toEqual({ kind: 'api_key', apiKeyId: 'key-1', projectId: 'project-1' }); + }); + + it('falls back to the system actor outside a request', () => { + const { bus } = createBus(); + + expect(bus.publish('test.item.created', { itemId: 'a' }).actor).toEqual({ kind: 'system' }); + }); + + it('lets the publisher override the actor', () => { + const { bus } = createBus(); + + const event = runWithActor({ name: 'ana', email: 'ana@example.com', userId: 'user-1' }, () => + bus.publish('test.item.created', { itemId: 'a' }, { actor: { kind: 'system' } }), + ); + + expect(event.actor).toEqual({ kind: 'system' }); + }); + + it('maps request actors without ids to the system actor', () => { + expect(actorFromRequest({ name: 'legacy', email: 'legacy@example.com' })).toEqual({ + kind: 'system', + }); + expect(actorFromRequest(null)).toEqual({ kind: 'system' }); + }); + }); +}); + +describe('RecordingEventBus', () => { + it('records published events in order and still notifies subscribers', async () => { + const bus = new RecordingEventBus(); + const handler = vi.fn(); + bus.subscribe('test.item.deleted', handler); + + bus.publish('test.item.created', { itemId: 'a' }); + bus.publish('test.item.deleted', { itemId: 'a', reason: 'gone' }); + await bus.drain(); + + expect(bus.types()).toEqual(['test.item.created', 'test.item.deleted']); + expect(bus.ofType('test.item.deleted').map((event) => event.payload)).toEqual([ + { itemId: 'a', reason: 'gone' }, + ]); + expect(handler).toHaveBeenCalledTimes(1); + }); + + it('clears recorded events', () => { + const bus = new RecordingEventBus(); + bus.publish('test.item.created', { itemId: 'a' }); + + bus.clear(); + + expect(bus.events).toEqual([]); + }); +}); diff --git a/src/lib/server/events/event-bus.ts b/src/lib/server/events/event-bus.ts new file mode 100644 index 0000000..34d855b --- /dev/null +++ b/src/lib/server/events/event-bus.ts @@ -0,0 +1,153 @@ +import type { Logger } from 'pino'; +import { createLogger } from '#lib/server/logger'; +import { getCurrentActor, type RequestActor } from '#lib/server/request-context'; +import type { + AnyEventEnvelope, + DomainEventMap, + EventActor, + EventEnvelope, + EventHandler, + EventTypeOf, + PublishOptions, + Unsubscribe, +} from './types'; + +export interface EventBus { + /** + * Publishes `type` and returns its envelope immediately; handlers run asynchronously. + * Call it only after the GitDB write it describes has succeeded. + */ + publish>( + type: K, + payload: M[K], + opts?: PublishOptions, + ): EventEnvelope; + + /** Subscribes to one event type, or to every type with `'*'`. Returns the unsubscribe function. */ + subscribe>( + type: K, + handler: EventHandler>, + ): Unsubscribe; + subscribe(type: '*', handler: EventHandler>): Unsubscribe; + + /** Resolves once every handler scheduled so far (and any they schedule) has finished. */ + drain(): Promise; +} + +type Subscription = { + type: EventTypeOf | '*'; + handler: EventHandler>; + active: boolean; + /** Per-subscriber queue: keeps delivery in publish order even for async handlers. */ + tail: Promise; +}; + +export type InProcessEventBusOptions = { + logger?: Pick; + resolveActor?: () => RequestActor | null; + now?: () => Date; + generateId?: () => string; +}; + +/** Maps the request context onto an event actor; no context means a system event. */ +export function actorFromRequest(actor: RequestActor | null): EventActor { + if (actor?.apiKeyId) { + return { kind: 'api_key', apiKeyId: actor.apiKeyId, projectId: actor.apiKeyProjectId ?? null }; + } + if (actor?.userId) return { kind: 'user', userId: actor.userId }; + return { kind: 'system' }; +} + +/** + * In-process, at-most-once event bus. Events are not persisted and never leave the process. + * + * - `publish()` never waits for handlers and never throws because of them. + * - Each subscriber receives events in publish order; a slow subscriber does not delay others. + * - A failing handler is logged with the event `type` and `id` and does not affect other handlers + * or later events. + */ +export class InProcessEventBus implements EventBus { + private readonly subscriptions = new Set>(); + private readonly log: Pick; + private readonly resolveActor: () => RequestActor | null; + private readonly now: () => Date; + private readonly generateId: () => string; + + constructor(options: InProcessEventBusOptions = {}) { + this.log = options.logger ?? createLogger('events'); + this.resolveActor = options.resolveActor ?? getCurrentActor; + this.now = options.now ?? (() => new Date()); + this.generateId = options.generateId ?? (() => crypto.randomUUID()); + } + + publish>( + type: K, + payload: M[K], + opts: PublishOptions = {}, + ): EventEnvelope { + const event: EventEnvelope = { + id: this.generateId(), + type, + occurredAt: this.now().toISOString(), + actor: opts.actor ?? actorFromRequest(this.resolveActor()), + scope: { ...opts.scope }, + payload, + }; + + this.dispatch(event as unknown as AnyEventEnvelope); + return event; + } + + subscribe>( + type: K, + handler: EventHandler>, + ): Unsubscribe; + subscribe(type: '*', handler: EventHandler>): Unsubscribe; + subscribe( + type: EventTypeOf | '*', + handler: EventHandler> | EventHandler, + ): Unsubscribe { + const subscription: Subscription = { + type, + handler: handler as EventHandler>, + active: true, + tail: Promise.resolve(), + }; + this.subscriptions.add(subscription); + + return () => { + subscription.active = false; + this.subscriptions.delete(subscription); + }; + } + + async drain(): Promise { + // handlers may publish more events while we wait: loop until every queue is settled + for (;;) { + const tails = [...this.subscriptions].map((s) => s.tail); + await Promise.all(tails); + const settled = [...this.subscriptions].every((s, i) => s.tail === tails[i]); + if (settled && tails.length === this.subscriptions.size) return; + } + } + + private dispatch(event: AnyEventEnvelope): void { + for (const subscription of this.subscriptions) { + if (subscription.type !== '*' && subscription.type !== event.type) continue; + // `.then` defers to a microtask, so publish() returns before any handler runs + subscription.tail = subscription.tail.then(() => this.run(subscription, event)); + } + } + + private async run(subscription: Subscription, event: AnyEventEnvelope): Promise { + if (!subscription.active) return; + try { + await subscription.handler(event); + } catch (error) { + this.log.error( + { err: error, eventType: event.type, eventId: event.id, subscribedTo: subscription.type }, + `[events] handler failed for ${event.type} (${event.id})`, + ); + } + } +} diff --git a/src/lib/server/events/index.ts b/src/lib/server/events/index.ts new file mode 100644 index 0000000..7aff03b --- /dev/null +++ b/src/lib/server/events/index.ts @@ -0,0 +1,19 @@ +import { InProcessEventBus, type EventBus } from './event-bus'; + +export { InProcessEventBus, actorFromRequest } from './event-bus'; +export type { EventBus, InProcessEventBusOptions } from './event-bus'; +export type * from './types'; + +const GLOBAL_KEY = Symbol.for('gitops.events.bus'); + +type GlobalWithBus = typeof globalThis & { [GLOBAL_KEY]?: EventBus }; + +/** + * Process-wide event bus. Stored on `globalThis` so Vite HMR re-evaluating this module in + * development keeps the same instance instead of piling up duplicate subscribers. + * + * Services receive it through their constructor from their module's `index.ts`; only composition + * roots import this singleton. + */ +export const eventBus: EventBus = ((globalThis as GlobalWithBus)[GLOBAL_KEY] ??= + new InProcessEventBus()); diff --git a/src/lib/server/events/testing.ts b/src/lib/server/events/testing.ts new file mode 100644 index 0000000..32239f5 --- /dev/null +++ b/src/lib/server/events/testing.ts @@ -0,0 +1,51 @@ +import { InProcessEventBus, type InProcessEventBusOptions } from './event-bus'; +import type { + AnyEventEnvelope, + DomainEventMap, + EventEnvelope, + EventTypeOf, + PublishOptions, +} from './types'; + +/** + * Event bus for unit tests: records every published event so services can be asserted on what + * they emit. Subscribers still work, so it can also wire a subscriber under test. + * + * ```ts + * const events = new RecordingEventBus(); + * const service = new VaultService(repository, events); + * await service.createSecret(input); + * expect(events.ofType('vault.secret.created')).toHaveLength(1); + * ``` + */ +export class RecordingEventBus extends InProcessEventBus { + readonly events: AnyEventEnvelope[] = []; + + constructor(options: InProcessEventBusOptions = {}) { + super({ logger: { error: () => {} }, ...options }); + } + + override publish>( + type: K, + payload: M[K], + opts?: PublishOptions, + ): EventEnvelope { + const event = super.publish(type, payload, opts); + this.events.push(event as unknown as AnyEventEnvelope); + return event; + } + + /** Recorded events of one type, in publish order. */ + ofType>(type: K): EventEnvelope[] { + return this.events.filter((event) => event.type === type) as unknown as EventEnvelope[]; + } + + /** Event types recorded so far, in publish order. */ + types(): EventTypeOf[] { + return this.events.map((event) => event.type); + } + + clear(): void { + this.events.length = 0; + } +} diff --git a/src/lib/server/events/types.ts b/src/lib/server/events/types.ts new file mode 100644 index 0000000..f1168bd --- /dev/null +++ b/src/lib/server/events/types.ts @@ -0,0 +1,64 @@ +/** + * Domain event types. See `docs/adr/0001-event-bus-and-alerts.md` for the design and rules. + * + * Event names follow `..` in snake_case, with the action as a past + * participle (`code_report.analysis.completed`, `vault.secret.created`, `access.granted`). + */ + +/** Who caused the event. Resolved from the request context when the publisher does not pass one. */ +export type EventActor = + | { kind: 'user'; userId: string } + | { kind: 'api_key'; apiKeyId: string; projectId: string | null } + | { kind: 'system' }; + +/** Where the event happened; the alert engine matches alerts by this scope. */ +export type EventScope = { + organizationId?: string | null; + projectId?: string | null; +}; + +/** + * Event type → payload. Each module adds its events here (declaration merging is not used: add + * the entries directly so the whole catalog stays in one place). + * + * Payloads must never contain secrets: no vault values, invitation or reset tokens, hashes or + * API keys. + */ +// eslint-disable-next-line @typescript-eslint/no-empty-object-type -- filled in by #78 +export interface DomainEventMap {} + +/** Event names of an event map. */ +export type EventTypeOf = Extract; + +/** Envelope published on the bus for event `K` of map `M`. */ +export type EventEnvelope> = { + /** `crypto.randomUUID()` */ + id: string; + type: K; + /** ISO 8601 */ + occurredAt: string; + actor: EventActor; + scope: EventScope; + payload: M[K]; +}; + +/** Discriminated union of every envelope of map `M` (what a `'*'` subscriber receives). */ +export type AnyEventEnvelope = { + [K in EventTypeOf]: EventEnvelope; +}[EventTypeOf]; + +export type EventType = EventTypeOf; + +export type DomainEvent = EventEnvelope; + +export type AnyDomainEvent = AnyEventEnvelope; + +export type PublishOptions = { + scope?: EventScope; + /** Overrides the actor resolved from the request context (e.g. background jobs). */ + actor?: EventActor; +}; + +export type EventHandler = (event: E) => void | Promise; + +export type Unsubscribe = () => void; diff --git a/src/lib/server/gitdb/index.ts b/src/lib/server/gitdb/index.ts index c39c023..d9f1249 100644 --- a/src/lib/server/gitdb/index.ts +++ b/src/lib/server/gitdb/index.ts @@ -97,5 +97,6 @@ export function getGitDb(): CachedGitDb { } const actor = getCurrentActor(); - return actor ? instance.as(actor) : instance; + // only the commit identity reaches GitDB; ids in the request context are for domain events + return actor ? instance.as({ name: actor.name, email: actor.email }) : instance; } diff --git a/src/lib/server/request-context.ts b/src/lib/server/request-context.ts index 3938892..9100927 100644 --- a/src/lib/server/request-context.ts +++ b/src/lib/server/request-context.ts @@ -1,13 +1,24 @@ import { AsyncLocalStorage } from 'node:async_hooks'; export type RequestActor = { + /** Commit author name written by GitDB. */ name: string; + /** Commit author email written by GitDB. */ email: string; + /** Set when the request is authenticated with a session. */ + userId?: string; + /** Set when the request is authenticated with an `Authorization: Bearer gvs_...` API key. */ + apiKeyId?: string; + /** Project the API key is confined to (`null` for keys that are not project-scoped). */ + apiKeyProjectId?: string | null; }; const storage = new AsyncLocalStorage(); -/** Runs `fn` with `actor` available to any `getGitDb()` call made during its execution. */ +/** + * Runs `fn` with `actor` available to anything that reads the request context during its + * execution: `getGitDb()` (commit author) and the domain event bus (event actor). + */ export function runWithActor(actor: RequestActor, fn: () => T): T { return storage.run(actor, fn); }