From 5decbba57cb19ba4176f24e7e8867656dea71f0a Mon Sep 17 00:00:00 2001 From: codex Date: Tue, 11 Aug 2026 18:16:58 -0400 Subject: [PATCH 1/2] feat(encounters): ephemeral Co-DM presence on the encounter SSE stream (#2209) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add the data-foundation slice of Co-DM presence (#816 slice 1): an ephemeral, authenticated, in-memory registry of which members are on an encounter's live surface, broadcast as an `encounter.presence` snapshot on the existing campaign-event SSE stream. UI rendering is a subsequent slice. Schema (@campfire/schema) - EncounterPresenceActivity ('viewing' | 'editing'), EncounterPresenceEntry, EncounterPresenceSnapshot, EncounterPresenceDeclare request body. - New CampaignEvent variant `encounter.presence` carrying a full snapshot (campaignId, encounterId, members[]) so a reconnecting/late-joining client reconciles by replacing its local set — there is no persisted history to refetch. Server - EncounterPresenceService: in-memory registry keyed by (encounterId, userId), kept alive by declare/heartbeat, lazily reaped on TTL expiry (no background timer — the server module has none). Emits a snapshot on join / activity change / leave / heartbeat-expire. - REST surface on EncountersController: GET/POST/DELETE /encounters/:id/presence. POST declares+heartbeats (silent on a same-activity heartbeat) and returns the snapshot; DELETE leaves; GET reads. - Secrecy: a hidden encounter's presence is routed DM-only via an audience predicate at emit time (hidden re-read fresh, mirroring emitEncounterEvent), so a non-DM never receives the frame and the encounter's existence never leaks. Presence is transport-level state (like an SSE keepalive): not persisted, not audited. Restart drops everyone; reconnect re-declares. - campaign-event-projection classifies `encounter.presence` as broadcast-safe (role-dependent secrecy is enforced upstream at emit, not by projection). Tests - encounter-presence.e2e-spec.ts: join/leave/expire lifecycle, heartbeat-no-op, activity change, reconnect restore, hidden-encounter role filtering (404 + DM- only delivery), campaign isolation, multi-participant snapshots, strict-body validation. 18 cases. - campaign-event-projection.spec.ts: sample for the new frame. Closes #2209. --- .../encounters/encounter-presence.service.ts | 206 ++++++++ .../encounters/encounters.controller.ts | 72 ++- .../src/modules/encounters/encounters.dto.ts | 6 +- .../modules/encounters/encounters.module.ts | 3 +- .../events/campaign-event-projection.ts | 9 + .../test/encounter-presence.e2e-spec.ts | 441 ++++++++++++++++++ .../unit/campaign-event-projection.spec.ts | 1 + packages/schema/src/index.ts | 74 +++ 8 files changed, 809 insertions(+), 3 deletions(-) create mode 100644 apps/server/src/modules/encounters/encounter-presence.service.ts create mode 100644 apps/server/test/encounter-presence.e2e-spec.ts diff --git a/apps/server/src/modules/encounters/encounter-presence.service.ts b/apps/server/src/modules/encounters/encounter-presence.service.ts new file mode 100644 index 000000000..96a01a0f5 --- /dev/null +++ b/apps/server/src/modules/encounters/encounter-presence.service.ts @@ -0,0 +1,206 @@ +import { Inject, Injectable } from '@nestjs/common'; +import { eq } from 'drizzle-orm'; +import type { EncounterPresenceActivity, EncounterPresenceSnapshot } from '@campfire/schema'; +import { DB, type DrizzleDb } from '../../db/db.module'; +import { encounters } from '../../db/schema'; +import { CampaignEventsService } from '../events/campaign-events.service'; + +/** One presence record in the in-memory registry (issue #2209). */ +interface PresenceRecord { + userId: string; + campaignId: number; + activity: EncounterPresenceActivity; + /** Wall-clock ms of the last declare/heartbeat. Reaped by `sweep()` once older than TTL. */ + lastSeenMs: number; +} + +/** + * How long a presence entry survives without a heartbeat before it is expired. + * + * The client heartbeats (POST /encounters/:id/presence) on a cadence well inside this + * window, so a live participant refreshes continually; a participant whose tab closed, + * crashed, or lost the network stops heartbeating and is reaped after TTL. There is NO + * background timer (the server module has none anywhere — see the absence of setInterval + * in src/): expiry is lazy, reaped on the next registry access, which is also when the + * leave frame is emitted. That is correct because a leave frame only matters to an + * observer, and an observer's next read/heartbeat is exactly when the registry is touched. + * + * Exported mutable so the e2e suite can shrink it to exercise expiry without waiting. + */ +export let ENCOUNTER_PRESENCE_TTL_MS = 45_000; + +/** Test-only: shrink the presence TTL to exercise expiry deterministically. */ +export function setEncounterPresenceTtlForTests(ms: number): void { + ENCOUNTER_PRESENCE_TTL_MS = ms; +} + +/** + * Ephemeral, in-memory Co-DM presence registry for encounters (issue #2209, #816 slice 1). + * + * Tracks which authenticated users have declared themselves on an encounter's live surface + * (a coarse `viewing` | `editing` activity) and broadcasts the resulting snapshot as an + * `encounter.presence` campaign event on the existing SSE stream whenever the set changes + * (join / activity change / explicit leave / heartbeat-expire). + * + * DESIGN NOTES + * + * - In-memory only. Presence is transport-level state (like an SSE keepalive), not a + * domain write: it is not persisted and not audited. Restart drops everyone, and a + * reconnecting client re-declares (AC: "reconnect restores presence"). + * - Snapshot, not delta. Each frame carries the full current set for the encounter, so a + * late-joining or reconnecting client reconciles by replacing its local state — there is + * no persisted history to refetch and no missed-event log to replay. + * - Lazy expiry. `sweep()` runs at the top of every public method. It reaps entries whose + * last heartbeat is older than TTL and emits a leave snapshot for each affected + * encounter. This keeps the registry tidy and the snapshots honest without a timer, and + * it is what makes "heartbeat-expire" observable on the wire. + * - Secrecy at emit time. A hidden encounter's presence must not reach a non-DM (it would + * leak the encounter's existence). The emit helper re-reads the encounter's `hidden` + * column fresh and routes the frame through `emitForAudience` with a DM-only predicate + * when hidden — the same concurrent-hide defence `EncountersService.emitEncounterEvent` + * uses for the encounter.* ticks. + */ +@Injectable() +export class EncounterPresenceService { + /** encounterId -> (userId -> record). A user may be present on several encounters. */ + private readonly registry = new Map>(); + + constructor( + @Inject(DB) private readonly db: DrizzleDb, + private readonly events: CampaignEventsService, + ) {} + + /** + * Declare (or refresh) presence for `(userId, encounterId)`. Emits a snapshot when the + * caller is newly present OR their activity changed; a pure heartbeat (same activity) + * only refreshes `lastSeenMs` and emits nothing. Always returns the current snapshot. + */ + declare(input: { + encounterId: number; + campaignId: number; + userId: string; + activity: EncounterPresenceActivity; + }): EncounterPresenceSnapshot { + this.sweep(); + const { encounterId, campaignId, userId, activity } = input; + const now = Date.now(); + const bucket = this.registry.get(encounterId); + const existing = bucket?.get(userId); + // A real change the table needs to hear about: a brand-new participant, or an activity + // transition (viewing -> editing). A same-activity heartbeat is silent on the wire. + const changed = !existing || existing.activity !== activity; + const record: PresenceRecord = { userId, campaignId, activity, lastSeenMs: now }; + if (bucket) { + bucket.set(userId, record); + } else { + this.registry.set(encounterId, new Map([[userId, record]])); + } + if (changed) this.emitSnapshot(encounterId, campaignId); + // readSnapshot (not snapshot): the sweep at the top already reaped stale entries. + return this.readSnapshot(encounterId); + } + + /** + * Remove `(userId, encounterId)` from the registry. Emits a snapshot when the caller was + * actually present (a leave for someone never present is a no-op on the wire). Returns + * the resulting snapshot regardless, so a client tearing down its tab gets a confirming + * body without a second round-trip. + */ + leave(input: { encounterId: number; userId: string }): EncounterPresenceSnapshot { + this.sweep(); + const { encounterId, userId } = input; + const bucket = this.registry.get(encounterId); + const record = bucket?.get(userId); + if (record) { + bucket!.delete(userId); + if (bucket!.size === 0) this.registry.delete(encounterId); + this.emitSnapshot(encounterId, record.campaignId); + } + // readSnapshot (not snapshot): the sweep at the top already reaped stale entries. + return this.readSnapshot(encounterId); + } + + /** + * Read the current presence set for an encounter (also the shape returned by declare/ + * leave). Sweeps first so a caller never observes an already-expired participant. + */ + snapshot(encounterId: number): EncounterPresenceSnapshot { + this.sweep(); + return this.readSnapshot(encounterId); + } + + /** + * Force a sweep now. Public for the e2e suite, which shrinks the TTL and calls this to + * assert expiry deterministically rather than racing the lazy-reap window. + */ + expireNow(): void { + this.sweep(); + } + + // ---- internals ---- + + /** Reap entries older than TTL and emit a leave snapshot for each affected encounter. */ + private sweep(): void { + const cutoff = Date.now() - ENCOUNTER_PRESENCE_TTL_MS; + const expired: Array<{ encounterId: number; campaignId: number }> = []; + for (const [encounterId, bucket] of this.registry) { + let touched = false; + let campaignId: number | undefined; + for (const [userId, record] of bucket) { + if (record.lastSeenMs < cutoff) { + bucket.delete(userId); + touched = true; + campaignId = record.campaignId; + } + } + if (touched && campaignId !== undefined) { + if (bucket.size === 0) this.registry.delete(encounterId); + expired.push({ encounterId, campaignId }); + } + } + // Emit after the mutation so each snapshot reflects the reaped set. Order is stable + // enough (Map insertion order by encounterId) and each frame is self-describing. + for (const { encounterId, campaignId } of expired) { + this.emitSnapshot(encounterId, campaignId); + } + } + + private readSnapshot(encounterId: number): EncounterPresenceSnapshot { + const bucket = this.registry.get(encounterId); + const members = bucket + ? Array.from(bucket.values()) + .map((r) => ({ userId: r.userId, activity: r.activity })) + .sort((a, b) => (a.userId < b.userId ? -1 : a.userId > b.userId ? 1 : 0)) + : []; + return { encounterId, members }; + } + + /** + * Emit the current snapshot for an encounter, role-routing at emit time. A hidden + * encounter's presence is DM-only (a non-DM must not learn it exists); a visible + * encounter's presence reaches every campaign member via the normal SSE fan-out. + * `hidden` is re-read fresh to defend against a concurrent hide, mirroring + * `EncountersService.emitEncounterEvent`. + */ + private emitSnapshot(encounterId: number, campaignId: number): void { + const snapshot = this.readSnapshot(encounterId); + const hidden = this.currentHidden(encounterId); + // No audience predicate => the frame fans out to every campaign member. A hidden + // encounter constrains that to DMs only. + const audience = hidden ? (viewer: { role: string }) => viewer.role === 'dm' : undefined; + this.events.emitForAudience( + { type: 'encounter.presence', campaignId, encounterId, members: snapshot.members }, + audience, + ); + } + + /** Fresh single-row read of an encounter's `hidden` flag. A missing row reads hidden. */ + private currentHidden(encounterId: number): boolean { + const row = this.db + .select({ hidden: encounters.hidden }) + .from(encounters) + .where(eq(encounters.id, encounterId)) + .get(); + return row ? Boolean(row.hidden) : true; + } +} diff --git a/apps/server/src/modules/encounters/encounters.controller.ts b/apps/server/src/modules/encounters/encounters.controller.ts index 4feb05110..8e3180401 100644 --- a/apps/server/src/modules/encounters/encounters.controller.ts +++ b/apps/server/src/modules/encounters/encounters.controller.ts @@ -7,9 +7,10 @@ import { CampaignAccessService } from '../membership/campaign-access.service'; import { contentDispositionHeader } from '../attachments/filename'; import { DERIVATIVE_VARIANT_NAMES, isDerivativeVariantName } from '../attachments/image-derivatives'; import { EncountersService } from './encounters.service'; -import { EncounterCreateDto, EncounterGenerateDto, EncounterPreviewDto, EncounterCommitDto, EncounterUpdateDto, EncounterEscalationUpdateDto, EncounterReopenDto, CombatantCreateDto, CombatantUpdateDto, CombatantRemoveRequestDto, CombatantRemoveUndoDto, CombatantResourceAdjustDto, CreatureCheckRollDto, DeathSaveRollDto, CombatantRollInitiativeDto, CombatantReorderDto, CombatantTurnStatePatchDto, EncounterEndTurnDto, EncounterNextTurnDto, RollRequestDto, ActionRollRequestDto, ManualRollRequestDto, MapObjectCreateDto, MapObjectUpdateDto, MapPingDto, AoeTemplateDeclareDto, AoeTemplateUpdateDto, ActionResolveRequestDto, ActionApplyRequestDto, ActionUndoTokenDto, TokenBatchPreviewDto, TokenBatchApplyDto, TokenBatchUndoDto, SavedTokenFormationDto, QuickRollRequestDto, EncounterAftermathApplyXpInputDto, EncounterAftermathLootTransferInputDto, EncounterAftermathQuestUpdateInputDto, EncounterAftermathBeatUpdateInputDto, EncounterAftermathTimelineEventInputDto } from './encounters.dto'; +import { EncounterCreateDto, EncounterGenerateDto, EncounterPreviewDto, EncounterCommitDto, EncounterUpdateDto, EncounterEscalationUpdateDto, EncounterReopenDto, CombatantCreateDto, CombatantUpdateDto, CombatantRemoveRequestDto, CombatantRemoveUndoDto, CombatantResourceAdjustDto, CreatureCheckRollDto, DeathSaveRollDto, CombatantRollInitiativeDto, CombatantReorderDto, CombatantTurnStatePatchDto, EncounterEndTurnDto, EncounterNextTurnDto, RollRequestDto, ActionRollRequestDto, ManualRollRequestDto, MapObjectCreateDto, MapObjectUpdateDto, MapPingDto, AoeTemplateDeclareDto, AoeTemplateUpdateDto, ActionResolveRequestDto, ActionApplyRequestDto, ActionUndoTokenDto, TokenBatchPreviewDto, TokenBatchApplyDto, TokenBatchUndoDto, SavedTokenFormationDto, QuickRollRequestDto, EncounterAftermathApplyXpInputDto, EncounterAftermathLootTransferInputDto, EncounterAftermathQuestUpdateInputDto, EncounterAftermathBeatUpdateInputDto, EncounterAftermathTimelineEventInputDto, EncounterPresenceDeclareDto } from './encounters.dto'; import { EncounterMapService } from './encounter-map.service'; import { ActionResolverService } from './action-resolver.service'; +import { EncounterPresenceService } from './encounter-presence.service'; import type { Request, Response } from 'express'; import { parseFogState } from '../../common/fog'; import { isVisibleTo } from '../../common/redact'; @@ -250,6 +251,7 @@ export class EncountersController { private readonly access: CampaignAccessService, private readonly encounterMaps: EncounterMapService, private readonly actions: ActionResolverService, + private readonly presence: EncounterPresenceService, ) {} @Get(':id') @@ -677,6 +679,74 @@ export class EncountersController { return result; } + @Get(':id/presence') + @ApiOperation({ + summary: 'List who is currently present on this encounter', + description: + 'Requires campaign membership. Returns the ephemeral Co-DM presence snapshot (issue #2209, #816 slice 1): ' + + 'which authenticated members have declared themselves on this encounter\u2019s live surface, with a coarse ' + + 'viewing/editing activity. Hidden encounters 404 for non-DMs, identical to GET /encounters/:id. ' + + 'Presence is in-memory only; a server restart clears it and clients re-declare on reconnect.', + }) + @ApiResponse({ status: 200, description: 'EncounterPresenceSnapshot.' }) + @ApiResponse({ status: 403, description: 'Not a member of this campaign.' }) + @ApiResponse({ status: 404, description: 'Encounter not found, or hidden from this viewer.' }) + async getPresence(@Param('id', ParseIntPipe) id: number, @CurrentUser() user: RequestUser) { + const row = await this.encounters.getRowOrThrow(id); + const role = await this.access.requireMember(user, row.campaignId); + if (!isVisibleTo({ hidden: row.hidden }, role)) { + throw new NotFoundException(); + } + return this.presence.snapshot(id); + } + + @Post(':id/presence') + @ApiOperation({ + summary: 'Declare / refresh presence on this encounter', + description: + 'Requires campaign membership. Declares the caller present on this encounter\u2019s live surface with a coarse ' + + 'activity (viewing | editing) and refreshes the heartbeat (issue #2209, #816 slice 1). A first declare or an ' + + 'activity change broadcasts an encounter.presence snapshot on the campaign SSE stream; a same-activity ' + + 'heartbeat only refreshes the lease. Hidden encounters 404 for non-DMs. The response is the resulting snapshot.', + }) + @ApiResponse({ status: 201, description: 'EncounterPresenceSnapshot after the declare.' }) + @ApiResponse({ status: 403, description: 'Not a member of this campaign.' }) + @ApiResponse({ status: 404, description: 'Encounter not found, or hidden from this viewer.' }) + async declarePresence( + @Param('id', ParseIntPipe) id: number, + @Body() body: EncounterPresenceDeclareDto, + @CurrentUser() user: RequestUser, + ) { + const row = await this.encounters.getRowOrThrow(id); + const role = await this.access.requireMember(user, row.campaignId); + if (!isVisibleTo({ hidden: row.hidden }, role)) { + throw new NotFoundException(); + } + return this.presence.declare({ + encounterId: id, + campaignId: row.campaignId, + userId: user.id, + activity: body.activity, + }); + } + + @Delete(':id/presence') + @HttpCode(200) + @ApiOperation({ + summary: 'Leave this encounter\u2019s live surface', + description: + 'Requires campaign membership. Removes the caller from this encounter\u2019s presence set and broadcasts the ' + + 'updated snapshot on the campaign SSE stream (issue #2209, #816 slice 1). Membership only \u2014 no hidden ' + + 'gate, because a member only ever removes itself from an encounter it could declare on.', + }) + @ApiResponse({ status: 200, description: 'EncounterPresenceSnapshot after the leave.' }) + @ApiResponse({ status: 403, description: 'Not a member of this campaign.' }) + async leavePresence(@Param('id', ParseIntPipe) id: number, @CurrentUser() user: RequestUser) { + const row = await this.encounters.getRowOrThrow(id); + await this.access.requireMember(user, row.campaignId); + return this.presence.leave({ encounterId: id, userId: user.id }); + } + @Delete(':id') @ApiOperation({ summary: 'Delete (trash) an encounter', description: 'dm role required. Soft-delete (issue #701) — combatants, logs, map, and links survive for restore.' }) @ApiResponse({ status: 200, description: 'Trashed.' }) diff --git a/apps/server/src/modules/encounters/encounters.dto.ts b/apps/server/src/modules/encounters/encounters.dto.ts index 61a6cd4cc..750e5ecec 100644 --- a/apps/server/src/modules/encounters/encounters.dto.ts +++ b/apps/server/src/modules/encounters/encounters.dto.ts @@ -1,5 +1,5 @@ import { createZodDto } from 'nestjs-zod'; -import { EncounterCreate, EncounterGenerate, EncounterPreviewRequest, EncounterCommit, EncounterUpdate, EncounterEscalationUpdate, EncounterReopen, CombatantCreate, CombatantUpdate, CombatantRemoveRequest, CombatantRemoveUndo, CombatantResourceAdjust, CombatantStatblock, CreatureCheckRollRequest, DeathSaveRollRequest, CombatantRollInitiativeRequest, CombatantReorderRequest, CombatantTurnStatePatch, EncounterEndTurn, EncounterNextTurn, RollRequest, ActionRollRequest, ManualRollRequest, MapObjectCreate, MapObjectUpdate, MapPing, ExpectedUpdatedAt, ActionResolveRequest, ActionApplyRequest, ActionUndoToken, TokenBatchPreviewRequest, TokenBatchApply, TokenBatchUndo, SavedTokenFormation, QuickRollRequest, EncounterAftermathApplyXpInput, EncounterAftermathLootTransferInput, EncounterAftermathQuestUpdateInput, EncounterAftermathBeatUpdateInput, EncounterAftermathTimelineEventInput, AoeTemplateDeclare, AoeTemplateUpdate } from '@campfire/schema'; +import { EncounterCreate, EncounterGenerate, EncounterPreviewRequest, EncounterCommit, EncounterUpdate, EncounterEscalationUpdate, EncounterReopen, CombatantCreate, CombatantUpdate, CombatantRemoveRequest, CombatantRemoveUndo, CombatantResourceAdjust, CombatantStatblock, CreatureCheckRollRequest, DeathSaveRollRequest, CombatantRollInitiativeRequest, CombatantReorderRequest, CombatantTurnStatePatch, EncounterEndTurn, EncounterNextTurn, RollRequest, ActionRollRequest, ManualRollRequest, MapObjectCreate, MapObjectUpdate, MapPing, ExpectedUpdatedAt, ActionResolveRequest, ActionApplyRequest, ActionUndoToken, TokenBatchPreviewRequest, TokenBatchApply, TokenBatchUndo, SavedTokenFormation, QuickRollRequest, EncounterAftermathApplyXpInput, EncounterAftermathLootTransferInput, EncounterAftermathQuestUpdateInput, EncounterAftermathBeatUpdateInput, EncounterAftermathTimelineEventInput, AoeTemplateDeclare, AoeTemplateUpdate, EncounterPresenceDeclare } from '@campfire/schema'; export class EncounterCreateDto extends createZodDto(EncounterCreate.strict()) {} export class QuickRollRequestDto extends createZodDto(QuickRollRequest.strict()) {} @@ -113,3 +113,7 @@ export class EncounterAftermathLootTransferInputDto extends createZodDto(Encount export class EncounterAftermathQuestUpdateInputDto extends createZodDto(EncounterAftermathQuestUpdateInput.strict()) {} export class EncounterAftermathBeatUpdateInputDto extends createZodDto(EncounterAftermathBeatUpdateInput.strict().default({})) {} export class EncounterAftermathTimelineEventInputDto extends createZodDto(EncounterAftermathTimelineEventInput.strict()) {} + +// Issue #2209 (#816 slice 1): ephemeral Co-DM presence declare/heartbeat body. +// EncounterPresenceDeclare is already .strict(), so an unknown key 400s. +export class EncounterPresenceDeclareDto extends createZodDto(EncounterPresenceDeclare) {} diff --git a/apps/server/src/modules/encounters/encounters.module.ts b/apps/server/src/modules/encounters/encounters.module.ts index b1939c3a0..9372c938f 100644 --- a/apps/server/src/modules/encounters/encounters.module.ts +++ b/apps/server/src/modules/encounters/encounters.module.ts @@ -17,6 +17,7 @@ import { CampaignsModule } from '../campaigns/campaigns.module'; import { EncountersService } from './encounters.service'; import { EncounterMapService } from './encounter-map.service'; import { ActionResolverService } from './action-resolver.service'; +import { EncounterPresenceService } from './encounter-presence.service'; import { CampaignEncountersController, CampaignRollController, EncountersController } from './encounters.controller'; @Module({ @@ -39,7 +40,7 @@ import { CampaignEncountersController, CampaignRollController, EncountersControl forwardRef(() => CampaignsModule), ], controllers: [CampaignEncountersController, CampaignRollController, EncountersController], - providers: [EncountersService, EncounterMapService, ActionResolverService], + providers: [EncountersService, EncounterMapService, ActionResolverService, EncounterPresenceService], // EncounterMapService is exported so the public cast capability (issue #547) can // serve the SAME fog-rendered, viewer-role map bytes without going through the // membership-authenticated /encounters/:id/map route. diff --git a/apps/server/src/modules/events/campaign-event-projection.ts b/apps/server/src/modules/events/campaign-event-projection.ts index 4eaa1a4b8..28a8f671a 100644 --- a/apps/server/src/modules/events/campaign-event-projection.ts +++ b/apps/server/src/modules/events/campaign-event-projection.ts @@ -34,6 +34,15 @@ export const CAMPAIGN_BROADCAST_SAFE_FRAMES: Record