Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
214 changes: 214 additions & 0 deletions apps/server/src/modules/encounters/encounter-presence.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,214 @@
import { Inject, Injectable } from '@nestjs/common';
import { eq } from 'drizzle-orm';
import type { EncounterPresenceActivity, EncounterPresenceEntry, 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<number, Map<string, PresenceRecord>>();

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);
let campaignId = record?.campaignId ?? 0;
if (record) {
campaignId = record.campaignId;
bucket!.delete(userId);
if (bucket!.size === 0) this.registry.delete(encounterId);
this.emitSnapshot(encounterId, campaignId);
}
// readSnapshot with the campaignId captured before the bucket was emptied.
return { campaignId, encounterId, members: this.readMembers(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 first = bucket?.values().next().value as PresenceRecord | undefined;
const campaignId = first?.campaignId ?? 0;
Comment thread
AwsomeFox marked this conversation as resolved.
Resolved
return { campaignId, encounterId, members: this.readMembers(encounterId) };
}

private readMembers(encounterId: number): EncounterPresenceEntry[] {
const bucket = this.registry.get(encounterId);
return 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))
: [];
}

/**
* 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;
Comment thread
AwsomeFox marked this conversation as resolved.
Resolved
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;
}
}
76 changes: 75 additions & 1 deletion apps/server/src/modules/encounters/encounters.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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')
Expand Down Expand Up @@ -677,6 +679,78 @@ 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();
}
Comment thread
AwsomeFox marked this conversation as resolved.
Resolved
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). Hidden encounters 404 for ' +
'non-DMs, same gate as declare, so a non-DM cannot probe an encounter id via a leave request.',
})
@ApiResponse({ status: 200, description: 'EncounterPresenceSnapshot after the leave.' })
@ApiResponse({ status: 403, description: 'Not a member of this campaign.' })
@ApiResponse({ status: 404, description: 'Encounter not found, or hidden from this viewer.' })
async leavePresence(@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.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.' })
Expand Down
6 changes: 5 additions & 1 deletion apps/server/src/modules/encounters/encounters.dto.ts
Original file line number Diff line number Diff line change
@@ -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()) {}
Expand Down Expand Up @@ -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) {}
Loading
Loading