@openpeepshq/core 0.29.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/analytics/compile.js +15 -7
  2. package/dist/analytics/jamMetrics.d.ts +47 -0
  3. package/dist/analytics/jamMetrics.js +93 -0
  4. package/dist/analytics/pdfReport.js +40 -1
  5. package/dist/analytics/read.js +68 -5
  6. package/dist/analytics/report.d.ts +75 -0
  7. package/dist/analytics/report.js +1 -0
  8. package/dist/db/pg/map/registry.js +11 -1
  9. package/dist/db/pg/schema/analytics.d.ts +68 -0
  10. package/dist/db/pg/schema/analytics.js +10 -0
  11. package/dist/db/pg/schema/documents.d.ts +17 -0
  12. package/dist/db/pg/schema/documents.js +10 -1
  13. package/dist/db/pg/schema/index.d.ts +85 -0
  14. package/dist/db/pg/sql/0021_jam_occurrence_recurrence_id.sql +10 -0
  15. package/dist/db/pg/sql/meta/0021_snapshot.json +4718 -0
  16. package/dist/db/pg/sql/meta/0022_snapshot.json +56 -1
  17. package/dist/db/pg/sql/meta/_journal.json +7 -0
  18. package/dist/events/index.d.ts +17 -0
  19. package/dist/events/index.js +50 -1
  20. package/dist/federation/actors.d.ts +17 -0
  21. package/dist/federation/actors.js +22 -1
  22. package/dist/federation/identity.d.ts +2 -0
  23. package/dist/federation/identity.js +2 -0
  24. package/dist/federation/index.d.ts +1 -1
  25. package/dist/federation/index.js +1 -1
  26. package/dist/federation/notes.d.ts +18 -0
  27. package/dist/federation/notes.js +11 -0
  28. package/dist/jams/export.d.ts +17 -4
  29. package/dist/jams/export.js +36 -6
  30. package/dist/jams/finders.js +5 -1
  31. package/dist/jams/index.js +3 -0
  32. package/dist/jams/livekit.d.ts +18 -3
  33. package/dist/jams/livekit.js +37 -5
  34. package/dist/jams/mapping.d.ts +0 -27
  35. package/dist/jams/mapping.js +0 -15
  36. package/dist/jams/token.js +14 -6
  37. package/dist/notifications/defaultNotifications/mention/index.js +9 -3
  38. package/dist/posts/helpers/index.d.ts +5 -0
  39. package/dist/posts/helpers/index.js +30 -4
  40. package/dist/posts/mutations.js +3 -0
  41. package/dist/stats/finders.js +34 -7
  42. package/package.json +4 -4
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "4a5587e2-755d-42e0-a8e0-4940132dbb19",
3
- "prevId": "2638df33-a41a-4afe-ad09-e0c4d76d959d",
3
+ "prevId": "a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d",
4
4
  "version": "7",
5
5
  "dialect": "postgresql",
6
6
  "tables": {
@@ -680,6 +680,12 @@
680
680
  "type": "timestamp with time zone",
681
681
  "primaryKey": false,
682
682
  "notNull": false
683
+ },
684
+ "recurrence_id": {
685
+ "name": "recurrence_id",
686
+ "type": "text",
687
+ "primaryKey": false,
688
+ "notNull": false
683
689
  }
684
690
  },
685
691
  "indexes": {
@@ -697,6 +703,27 @@
697
703
  "concurrently": false,
698
704
  "method": "btree",
699
705
  "with": {}
706
+ },
707
+ "jam_events_post_recurrence_idx": {
708
+ "name": "jam_events_post_recurrence_idx",
709
+ "columns": [
710
+ {
711
+ "expression": "post_id",
712
+ "isExpression": false,
713
+ "asc": true,
714
+ "nulls": "last"
715
+ },
716
+ {
717
+ "expression": "recurrence_id",
718
+ "isExpression": false,
719
+ "asc": true,
720
+ "nulls": "last"
721
+ }
722
+ ],
723
+ "isUnique": false,
724
+ "concurrently": false,
725
+ "method": "btree",
726
+ "with": {}
700
727
  }
701
728
  },
702
729
  "foreignKeys": {},
@@ -4340,6 +4367,34 @@
4340
4367
  "primaryKey": false,
4341
4368
  "notNull": true,
4342
4369
  "default": "now()"
4370
+ },
4371
+ "jam_peak_concurrent": {
4372
+ "name": "jam_peak_concurrent",
4373
+ "type": "integer",
4374
+ "primaryKey": false,
4375
+ "notNull": true,
4376
+ "default": "'0'::integer"
4377
+ },
4378
+ "jam_recordings_completed": {
4379
+ "name": "jam_recordings_completed",
4380
+ "type": "integer",
4381
+ "primaryKey": false,
4382
+ "notNull": true,
4383
+ "default": "'0'::integer"
4384
+ },
4385
+ "jam_minutes": {
4386
+ "name": "jam_minutes",
4387
+ "type": "integer",
4388
+ "primaryKey": false,
4389
+ "notNull": true,
4390
+ "default": "'0'::integer"
4391
+ },
4392
+ "jam_unique_attendees": {
4393
+ "name": "jam_unique_attendees",
4394
+ "type": "integer",
4395
+ "primaryKey": false,
4396
+ "notNull": true,
4397
+ "default": "'0'::integer"
4343
4398
  }
4344
4399
  },
4345
4400
  "indexes": {},
@@ -149,6 +149,13 @@
149
149
  "tag": "0020_add_audit_logs",
150
150
  "breakpoints": true
151
151
  },
152
+ {
153
+ "idx": 21,
154
+ "version": "7",
155
+ "when": 1795496571664,
156
+ "tag": "0021_jam_occurrence_recurrence_id",
157
+ "breakpoints": true
158
+ },
152
159
  {
153
160
  "idx": 22,
154
161
  "version": "7",
@@ -3,6 +3,8 @@ import type { Profile, EntryData, PostWithMeta, Notification, ReactionData, JamR
3
3
  export type CoreEvents = {
4
4
  profileCreated: (profile: Profile) => void;
5
5
  postCreated: (post: PostWithMeta) => void;
6
+ postUpdated: (post: PostWithMeta, previousJamModerators: string[]) => void;
7
+ postDeleted: (post: PostWithMeta) => void;
6
8
  jamRecordingCompleted: (recording: JamRecordingWithMeta) => void;
7
9
  followCreated: (follower: Profile, followed: Profile) => void;
8
10
  /** Follow edge removed (unfollow). Federation reacts by sending Undo(Follow) for outbound follows only. */
@@ -34,5 +36,20 @@ export declare const hub: {
34
36
  emit: (eventType: string, ...eventArgs: unknown[]) => Promise<void>;
35
37
  on: <T extends unknown[]>(eventType: string, handler: (...args: T) => unknown) => Unsubscribe;
36
38
  once: (eventType: string, handler: (...args: unknown[]) => unknown) => void;
39
+ /**
40
+ * Resolves once every `on` subscription registered so far has finished its
41
+ * asynchronous Redis connect + SUBSCRIBE. Await this before relying on
42
+ * pub/sub delivery: an `emit` published while a subscription is still
43
+ * pending is lost (Redis has no subscriber to deliver to). Federation
44
+ * attaches correctness-critical handlers (`postDeleted` tombstones), so
45
+ * `installFederation` awaits this before the server accepts writes.
46
+ *
47
+ * Bounded by `SUBSCRIBE_READY_TIMEOUT_MS`: node-redis retries `connect()`
48
+ * forever, so an unavailable Redis would otherwise hold server startup
49
+ * hostage. On timeout we proceed with a warning — a down Redis already
50
+ * degrades every hub consumer (emits fail too), so waiting longer buys
51
+ * nothing.
52
+ */
53
+ ready: () => Promise<void>;
37
54
  };
38
55
  export { onceWorker, onceQueue } from './once';
@@ -2,11 +2,15 @@ import { getConnection } from '../redis/connection.js';
2
2
  import { logger } from '../log/index.js';
3
3
  import { onceQueue, registerOnceHandler } from './once.js';
4
4
  const log = logger('app:events');
5
+ /** Upper bound on `hub.ready()`'s wait for in-flight `on` subscriptions. */
6
+ const SUBSCRIBE_READY_TIMEOUT_MS = 10_000;
5
7
  // `satisfies Record<CoreEventKey, true>` guarantees at compile time that every
6
8
  // event key is present and that no unexpected keys can slip in.
7
9
  const validEventKeyMap = {
8
10
  profileCreated: true,
9
11
  postCreated: true,
12
+ postUpdated: true,
13
+ postDeleted: true,
10
14
  jamRecordingCompleted: true,
11
15
  followCreated: true,
12
16
  followDeleted: true,
@@ -33,6 +37,11 @@ const publishConnection = async () => {
33
37
  };
34
38
  const baseHub = (prefix) => {
35
39
  const subscriptions = new Map();
40
+ // Subscribe promises in flight. `on` registers a handler and then subscribes
41
+ // asynchronously (Redis connect + SUBSCRIBE), so there is a window in which an
42
+ // `emit` publishes to a channel that has no subscriber yet. `ready()` lets a
43
+ // caller await that window closing before relying on delivery.
44
+ const pendingSubscriptions = new Set();
36
45
  return {
37
46
  /**
38
47
  * Fan-out must not fail the caller (register/react/etc.). Redis publish and
@@ -57,7 +66,8 @@ const baseHub = (prefix) => {
57
66
  },
58
67
  on: (eventType, handler) => {
59
68
  const channel = `${prefix}:${eventType}`;
60
- getConnection().then((conn) => {
69
+ const sub = getConnection()
70
+ .then((conn) => {
61
71
  conn.subscribe(channel, (message) => {
62
72
  const args = JSON.parse(message);
63
73
  handler(...args);
@@ -68,7 +78,15 @@ const baseHub = (prefix) => {
68
78
  subscriptions.set(channel, entry);
69
79
  }
70
80
  entry.channels.push(channel);
81
+ })
82
+ .catch((err) => {
83
+ // Subscribe is best-effort like emit, but a permanently failed
84
+ // subscription means this handler is dead — log it rather than
85
+ // leaving a floating rejected promise.
86
+ log.error({ channel, err }, 'hub subscribe failed');
71
87
  });
88
+ pendingSubscriptions.add(sub);
89
+ void sub.finally(() => pendingSubscriptions.delete(sub));
72
90
  return () => {
73
91
  getConnection().then((conn) => conn.unsubscribe(channel));
74
92
  const entry = subscriptions.get(channel);
@@ -83,6 +101,37 @@ const baseHub = (prefix) => {
83
101
  once: (eventType, handler) => {
84
102
  registerOnceHandler(`${prefix}:${eventType}`, handler);
85
103
  },
104
+ /**
105
+ * Resolves once every `on` subscription registered so far has finished its
106
+ * asynchronous Redis connect + SUBSCRIBE. Await this before relying on
107
+ * pub/sub delivery: an `emit` published while a subscription is still
108
+ * pending is lost (Redis has no subscriber to deliver to). Federation
109
+ * attaches correctness-critical handlers (`postDeleted` tombstones), so
110
+ * `installFederation` awaits this before the server accepts writes.
111
+ *
112
+ * Bounded by `SUBSCRIBE_READY_TIMEOUT_MS`: node-redis retries `connect()`
113
+ * forever, so an unavailable Redis would otherwise hold server startup
114
+ * hostage. On timeout we proceed with a warning — a down Redis already
115
+ * degrades every hub consumer (emits fail too), so waiting longer buys
116
+ * nothing.
117
+ */
118
+ ready: async () => {
119
+ const start = Date.now();
120
+ while (pendingSubscriptions.size > 0) {
121
+ const remaining = SUBSCRIBE_READY_TIMEOUT_MS - (Date.now() - start);
122
+ const settled = await Promise.race([
123
+ Promise.allSettled([...pendingSubscriptions]).then(() => 'settled'),
124
+ new Promise((resolve) => setTimeout(() => resolve('timeout'), Math.max(0, remaining)).unref()),
125
+ ]);
126
+ if (settled === 'timeout' && pendingSubscriptions.size > 0) {
127
+ log.warn({
128
+ pending: pendingSubscriptions.size,
129
+ elapsedMs: Date.now() - start,
130
+ }, 'hub subscriptions still pending; continuing without them');
131
+ return;
132
+ }
133
+ }
134
+ },
86
135
  };
87
136
  };
88
137
  export const hub = baseHub('allpeep:core');
@@ -26,6 +26,23 @@ export type RemoteActorInput = {
26
26
  bio?: string;
27
27
  avatar?: string | null;
28
28
  };
29
+ /**
30
+ * Derive a local `profiles.handle` for a federated actor from its
31
+ * `preferredUsername` (falling back to the actor URI).
32
+ *
33
+ * The handle is **lowercased** because the federated identity key
34
+ * `(handle, domain)` is case-insensitive: mention extraction
35
+ * (`matchFederatedMentionTokens`) already lowercases both halves, so
36
+ * `@Bob@Mastodon.Social` looks up `('bob', 'mastodon.social')`. Storing the
37
+ * raw `preferredUsername` verbatim (`Bob`) would make that exact-match lookup
38
+ * miss. Lowercasing at the single ingest source (both `upsertRemoteActor`
39
+ * callers) keeps the stored key and the lookup key in the same shape.
40
+ *
41
+ * Migration note: rows ingested before this normalisation keep their original
42
+ * case, so a mixed-case `(handle, domain)` may not resolve until backfilled —
43
+ * and the `(handle, domain)` uniqueness is now effectively case-insensitive,
44
+ * so `Bob`/`bob` on the same domain must be treated as one actor, not two.
45
+ */
29
46
  export declare const federatedHandleFrom: (preferred: string | null | undefined, uri: string) => string;
30
47
  export declare const loadLocalActor: (profileId: string) => Promise<LocalActor | null>;
31
48
  export declare const findLocalActorIdByHandle: (handle: string) => Promise<string | null>;
@@ -6,13 +6,34 @@ import { nowIso } from '../db/pg/mappers.js';
6
6
  import { profiles } from '../db/pg/schema/documents.js';
7
7
  import { profilesMapping } from '../profiles/mapping.js';
8
8
  import { findProfileByHandleAndDomain, findProfileByUri } from './profiles.js';
9
+ /**
10
+ * Derive a local `profiles.handle` for a federated actor from its
11
+ * `preferredUsername` (falling back to the actor URI).
12
+ *
13
+ * The handle is **lowercased** because the federated identity key
14
+ * `(handle, domain)` is case-insensitive: mention extraction
15
+ * (`matchFederatedMentionTokens`) already lowercases both halves, so
16
+ * `@Bob@Mastodon.Social` looks up `('bob', 'mastodon.social')`. Storing the
17
+ * raw `preferredUsername` verbatim (`Bob`) would make that exact-match lookup
18
+ * miss. Lowercasing at the single ingest source (both `upsertRemoteActor`
19
+ * callers) keeps the stored key and the lookup key in the same shape.
20
+ *
21
+ * Migration note: rows ingested before this normalisation keep their original
22
+ * case, so a mixed-case `(handle, domain)` may not resolve until backfilled —
23
+ * and the `(handle, domain)` uniqueness is now effectively case-insensitive,
24
+ * so `Bob`/`bob` on the same domain must be treated as one actor, not two.
25
+ */
9
26
  export const federatedHandleFrom = (preferred, uri) => {
10
27
  const fromName = (preferred ?? '')
11
28
  .replace(/[^a-zA-Z0-9_.-]/g, '')
29
+ .toLowerCase()
12
30
  .slice(0, 64);
13
31
  if (fromName.length >= 1)
14
32
  return fromName;
15
- const fromUri = uri.replace(/[^a-zA-Z0-9]/g, '').slice(-16);
33
+ const fromUri = uri
34
+ .replace(/[^a-zA-Z0-9]/g, '')
35
+ .toLowerCase()
36
+ .slice(-16);
16
37
  return `actor-${fromUri || 'remote'}`;
17
38
  };
18
39
  const clipDisplayName = (name) => name ? name.slice(0, 30) : undefined;
@@ -6,6 +6,8 @@ export declare const FOLLOWERS_PATH: "/ap/users/{identifier}/followers";
6
6
  export declare const NOTE_PATH: "/ap/objects/{id}";
7
7
  export declare const CREATE_PATH: "/ap/create/{id}";
8
8
  export declare const ACCEPT_PATH: "/ap/accept/{id}";
9
+ export declare const UPDATE_PATH: "/ap/update/{id}";
10
+ export declare const DELETE_PATH: "/ap/delete/{id}";
9
11
  export declare const federationOrigin: (domain: string) => string;
10
12
  export declare const actorUri: (domain: string, profileId: string) => string;
11
13
  export declare const objectUri: (domain: string, postId: string) => string;
@@ -10,6 +10,8 @@ export const FOLLOWERS_PATH = '/ap/users/{identifier}/followers';
10
10
  export const NOTE_PATH = '/ap/objects/{id}';
11
11
  export const CREATE_PATH = '/ap/create/{id}';
12
12
  export const ACCEPT_PATH = '/ap/accept/{id}';
13
+ export const UPDATE_PATH = '/ap/update/{id}';
14
+ export const DELETE_PATH = '/ap/delete/{id}';
13
15
  export const federationOrigin = (domain) => `https://${domain}`;
14
16
  export const actorUri = (domain, profileId) => `https://${domain}/ap/users/${profileId}`;
15
17
  export const objectUri = (domain, postId) => `https://${domain}/ap/objects/${postId}`;
@@ -2,7 +2,7 @@ export { deleteOutboundFollow, findApActivityByUri, findOutboundFollow, recordAp
2
2
  export type { ApActivity, ApActivityDirection } from './activities';
3
3
  export { federatedHandleFrom, findLocalActorIdByHandle, loadLocalActor, loadLocalActorKeys, upsertRemoteActor, } from './actors';
4
4
  export type { LocalActor, LocalActorKeys, RemoteActorInput } from './actors';
5
- export { ACCEPT_PATH, ACTOR_INBOX_PATH, ACTOR_PATH, CREATE_PATH, FOLLOWERS_PATH, NOTE_PATH, SHARED_INBOX_PATH, acceptActivityUri, actorUri, backfillLocalFederationIdentities, createActivityUri, federationOrigin, generateActorKeyPair, localActorScalars, localObjectScalars, objectUri, } from './identity';
5
+ export { ACCEPT_PATH, ACTOR_INBOX_PATH, ACTOR_PATH, CREATE_PATH, DELETE_PATH, FOLLOWERS_PATH, NOTE_PATH, SHARED_INBOX_PATH, UPDATE_PATH, acceptActivityUri, actorUri, backfillLocalFederationIdentities, createActivityUri, federationOrigin, generateActorKeyPair, localActorScalars, localObjectScalars, objectUri, } from './identity';
6
6
  export { ingestIncomingFollow, ingestIncomingUnfollow, listFederatedFollowerRecipients, withoutBlockedRecipients, } from './ingest';
7
7
  export type { FollowerRecipient } from './ingest';
8
8
  export { loadPublicNote } from './notes';
@@ -1,6 +1,6 @@
1
1
  export { deleteOutboundFollow, findApActivityByUri, findOutboundFollow, recordApActivity, } from './activities.js';
2
2
  export { federatedHandleFrom, findLocalActorIdByHandle, loadLocalActor, loadLocalActorKeys, upsertRemoteActor, } from './actors.js';
3
- export { ACCEPT_PATH, ACTOR_INBOX_PATH, ACTOR_PATH, CREATE_PATH, FOLLOWERS_PATH, NOTE_PATH, SHARED_INBOX_PATH, acceptActivityUri, actorUri, backfillLocalFederationIdentities, createActivityUri, federationOrigin, generateActorKeyPair, localActorScalars, localObjectScalars, objectUri, } from './identity.js';
3
+ export { ACCEPT_PATH, ACTOR_INBOX_PATH, ACTOR_PATH, CREATE_PATH, DELETE_PATH, FOLLOWERS_PATH, NOTE_PATH, SHARED_INBOX_PATH, UPDATE_PATH, acceptActivityUri, actorUri, backfillLocalFederationIdentities, createActivityUri, federationOrigin, generateActorKeyPair, localActorScalars, localObjectScalars, objectUri, } from './identity.js';
4
4
  export { ingestIncomingFollow, ingestIncomingUnfollow, listFederatedFollowerRecipients, withoutBlockedRecipients, } from './ingest.js';
5
5
  export { loadPublicNote } from './notes.js';
6
6
  export { federationIsActive, hostnameOf, peerHostAllowed } from './peers.js';
@@ -4,5 +4,23 @@ export type PublicNote = {
4
4
  content: string;
5
5
  published: string;
6
6
  inReplyToUri: string | null;
7
+ /**
8
+ * Actor URIs of remote (federated) profiles mentioned in the note.
9
+ * Populated only by `loadPublicNote`'s mention-join and consumed only by the
10
+ * server's Fedify Note dispatcher (which CCs the mentionees); there is no
11
+ * other consumer today. Keep any new consumer server-dispatcher-side so the
12
+ * join stays scoped to federation delivery.
13
+ *
14
+ * Deliberately **create-time-frozen**: `updatePost` re-links hashtags but
15
+ * does not re-resolve/re-connect mention edges (the pre-existing local
16
+ * semantic — a local edit has never changed who is mentioned, and
17
+ * notification re-fan-out on edit is not in scope). Every subsequent
18
+ * `Update(Note)` therefore CCs the *original* mention set: a mention added
19
+ * on an edit is not CC'd remotely, and a removed one stays CC'd until the
20
+ * note is deleted. That is a documented decision (Phase R review round 4,
21
+ * item 2), not an accident — if remote edit-time mention changes become
22
+ * required, re-link the mention edges in `updatePost` first.
23
+ */
24
+ mentionUris: string[];
7
25
  };
8
26
  export declare const loadPublicNote: (postId: string) => Promise<PublicNote | null>;
@@ -1,6 +1,8 @@
1
1
  import { and, eq, isNotNull, isNull } from 'drizzle-orm';
2
2
  import { pgDb } from '../db/pg/client.js';
3
3
  import { posts } from '../db/pg/schema/documents.js';
4
+ import { profiles } from '../db/pg/schema/documents.js';
5
+ import { mentions } from '../db/pg/schema/edges.js';
4
6
  export const loadPublicNote = async (postId) => {
5
7
  const db = pgDb();
6
8
  const [row] = await db
@@ -20,11 +22,20 @@ export const loadPublicNote = async (postId) => {
20
22
  if (!row || row.type !== 'note' || row.visibility !== 'public')
21
23
  return null;
22
24
  const body = (row.body ?? {});
25
+ const mentionRows = await db
26
+ .select({ uri: profiles.uri })
27
+ .from(mentions)
28
+ .innerJoin(profiles, eq(mentions.toId, profiles.id))
29
+ .where(and(eq(mentions.fromId, postId), isNull(profiles.deletedAt), eq(profiles.type, 'federated')));
30
+ const mentionUris = mentionRows
31
+ .map((m) => m.uri)
32
+ .filter((uri) => Boolean(uri));
23
33
  return {
24
34
  id: row.id,
25
35
  creatorId: row.creatorId,
26
36
  content: body.content ?? '',
27
37
  published: row.createdAt,
28
38
  inReplyToUri: row.inReplyToUri,
39
+ mentionUris,
29
40
  };
30
41
  };
@@ -3,19 +3,32 @@ export type JamAttendanceKind = 'community' | 'public';
3
3
  export type JamAttendanceExportRow = {
4
4
  kind: JamAttendanceKind | '';
5
5
  name: string;
6
- email: string;
7
6
  handle: string;
8
7
  joinedAt: string;
8
+ recurrenceId: string;
9
9
  };
10
- type JoinRecord = {
10
+ export type JoinRecord = {
11
11
  profileId: string;
12
12
  createdAt: string;
13
+ recurrenceId: string | undefined;
13
14
  };
14
- type AttendanceProfile = Pick<Profile, 'type' | 'displayName' | 'handle' | 'guestData'>;
15
- export declare const jamAttendanceExportHeaders: readonly ["Type", "Name", "Email", "Handle", "Joined At"];
15
+ type AttendanceProfile = Pick<Profile, 'type' | 'displayName' | 'handle'>;
16
+ export declare const jamAttendanceExportHeaders: readonly ["Type", "Name", "Handle", "Joined At", "Recurrence Id"];
17
+ /**
18
+ * Build one attendance row from a join event. The export carries no email
19
+ * column at all: community profiles can be controlled by multiple accounts
20
+ * (no single email is representative) and guest emails are personal data
21
+ * that must not leak into an attendance export.
22
+ */
16
23
  export declare const jamAttendanceRowFromJoin: (join: JoinRecord, profile: AttendanceProfile | undefined) => JamAttendanceExportRow;
17
24
  export declare const jamAttendanceExportCsv: (rows: JamAttendanceExportRow[]) => string;
18
25
  /** Profiles that joined the jam room. Recurring jams share one room. */
19
26
  export declare const listJamAttendeeProfileIds: (jamId: string) => Promise<string[]>;
27
+ /**
28
+ * One row per person: keep each profile's first join, in first-join order.
29
+ * Recurring jams share one room, so the same person rejoining a later
30
+ * occurrence must not produce a second row.
31
+ */
32
+ export declare const firstJoinByProfile: (joins: JoinRecord[]) => JoinRecord[];
20
33
  export declare const exportJamAttendanceCsv: (jamId: string) => Promise<string>;
21
34
  export {};
@@ -7,30 +7,42 @@ import { getProfiles } from '../profiles/index.js';
7
7
  export const jamAttendanceExportHeaders = [
8
8
  'Type',
9
9
  'Name',
10
- 'Email',
11
10
  'Handle',
12
11
  'Joined At',
12
+ 'Recurrence Id',
13
13
  ];
14
+ /**
15
+ * Build one attendance row from a join event. The export carries no email
16
+ * column at all: community profiles can be controlled by multiple accounts
17
+ * (no single email is representative) and guest emails are personal data
18
+ * that must not leak into an attendance export.
19
+ */
14
20
  export const jamAttendanceRowFromJoin = (join, profile) => {
15
21
  const isPublic = profile?.type === 'guest';
16
22
  return {
17
23
  kind: profile ? (isPublic ? 'public' : 'community') : '',
18
24
  name: profile?.displayName || (isPublic ? '' : (profile?.handle ?? '')),
19
- // Community emails aren't here: several accounts can control one profile.
20
- email: isPublic ? (profile?.guestData?.email ?? '') : '',
21
25
  handle: isPublic ? '' : (profile?.handle ?? ''),
22
26
  joinedAt: join.createdAt,
27
+ recurrenceId: join.recurrenceId ?? '',
23
28
  };
24
29
  };
25
30
  export const jamAttendanceExportCsv = (rows) => [
26
31
  toCsvRow([...jamAttendanceExportHeaders]),
27
- ...rows.map((row) => toCsvRow([row.kind, row.name, row.email, row.handle, row.joinedAt])),
32
+ ...rows.map((row) => toCsvRow([
33
+ row.kind,
34
+ row.name,
35
+ row.handle,
36
+ row.joinedAt,
37
+ row.recurrenceId,
38
+ ])),
28
39
  ].join('\n');
29
40
  const listJamJoinEvents = async (jamId) => {
30
41
  const db = await database();
31
42
  const rows = await db
32
43
  .select({
33
44
  createdAt: jamEvents.createdAt,
45
+ recurrenceId: jamEvents.recurrenceId,
34
46
  body: jamEvents.body,
35
47
  })
36
48
  .from(jamEvents)
@@ -45,6 +57,7 @@ const listJamJoinEvents = async (jamId) => {
45
57
  {
46
58
  profileId,
47
59
  createdAt: normalizeIsoDatetime(row.createdAt),
60
+ recurrenceId: row.recurrenceId ?? undefined,
48
61
  },
49
62
  ];
50
63
  });
@@ -54,10 +67,27 @@ export const listJamAttendeeProfileIds = async (jamId) => {
54
67
  const joins = await listJamJoinEvents(jamId);
55
68
  return [...new Set(joins.map((join) => join.profileId))];
56
69
  };
70
+ /**
71
+ * One row per person: keep each profile's first join, in first-join order.
72
+ * Recurring jams share one room, so the same person rejoining a later
73
+ * occurrence must not produce a second row.
74
+ */
75
+ export const firstJoinByProfile = (joins) => {
76
+ const seen = new Set();
77
+ const firstJoins = [];
78
+ for (const join of joins) {
79
+ if (!seen.has(join.profileId)) {
80
+ seen.add(join.profileId);
81
+ firstJoins.push(join);
82
+ }
83
+ }
84
+ return firstJoins;
85
+ };
57
86
  export const exportJamAttendanceCsv = async (jamId) => {
58
87
  const joins = await listJamJoinEvents(jamId);
59
- const profileIds = [...new Set(joins.map((join) => join.profileId))];
88
+ const firstJoins = firstJoinByProfile(joins);
89
+ const profileIds = firstJoins.map((join) => join.profileId);
60
90
  const profiles = profileIds.length ? await getProfiles(profileIds) : [];
61
91
  const profilesById = new Map(profiles.map((profile) => [profile.id, profile]));
62
- return jamAttendanceExportCsv(joins.map((join) => jamAttendanceRowFromJoin(join, profilesById.get(join.profileId))));
92
+ return jamAttendanceExportCsv(firstJoins.map((join) => jamAttendanceRowFromJoin(join, profilesById.get(join.profileId))));
63
93
  };
@@ -7,7 +7,11 @@ import { getJamState } from './cache.js';
7
7
  import { transformJamRecordingData } from './helpers.js';
8
8
  export const baseListJam = (props, { start, limit = 100 }) => addStartLimit(jamEventsMapping.filter({ matches: props }), start, limit);
9
9
  export const listJamEvents = (jamId, { start, limit } = {}) => allpeepDb().then(({ db }) => baseListJam({ jamId }, { start, limit }).all(db));
10
- export const listJamStarts = (jamId) => allpeepDb().then(({ db }) => baseListJam({ jamId, type: 'start' }, { limit: 200 }).all(db));
10
+ export const listJamStarts = (jamId) => allpeepDb().then(({ db }) =>
11
+ // baseListJam orders by idDesc — the unique primary key is a total order,
12
+ // so bulk-inserted rows (same createdAt in one transaction) cannot flip
13
+ // order and a downstream start/close pairing stays stable.
14
+ baseListJam({ jamId, type: 'start' }, { limit: 200 }).all(db));
11
15
  export const listAttendance = (jamId, { start, limit } = {}) => allpeepDb().then(({ db }) => baseListJam({ jamId, type: 'join' }, { start, limit }).all(db));
12
16
  export const findJamState = async (jam, hideParticipants, recurrenceId) => {
13
17
  const state = await getJamState(jam, recurrenceId);
@@ -129,6 +129,9 @@ export const closeJam = async (profile, jamEvent, recurrenceId) => {
129
129
  if (rs === undefined) {
130
130
  return undefined;
131
131
  }
132
+ // jamRoomName drops the occurrence (recurring jams share one LiveKit room
133
+ // per event), so stopRecording/stopRtmpStream/deleteRoom resolve the same
134
+ // room as the live jam while this close event keeps its own recurrenceId.
132
135
  await stopRecording(jamEvent, recurrenceId);
133
136
  await stopRtmpStream(jamEvent);
134
137
  return rs
@@ -108,10 +108,25 @@ export declare const stopRecording: (jamPost: PostWithMeta, recurrenceId?: strin
108
108
  post: PostWithMeta;
109
109
  } | undefined>;
110
110
  /**
111
- * Stops leftover egress and deletes an egress-only LiveKit room.
111
+ * Record the best-effort 'close' for a reclaimed (crashed) session so the
112
+ * start…close duration is not left dangling.
113
+ *
114
+ * The room name does not carry the occurrence (`jamRoomName` collapses it), so
115
+ * when the caller has no occurrence it is resolved from the jam's most recent
116
+ * persisted 'start' — the start of the crashed session. `computeJamStats`
117
+ * pairs a close with the start of the same occurrence, so a close written
118
+ * without the occurrence would latch onto the wrong one (or none) for a
119
+ * recurring series.
120
+ */
121
+ export declare const writeReclaimClose: (jam: PostWithMeta, recurrenceId?: string) => Promise<void>;
122
+ /**
123
+ * Stops leftover egress, deletes an egress-only LiveKit room, and emits a
124
+ * 'close' session event so an abandoned session (participants crashed before
125
+ * closeJam ran) still gets a duration in analytics instead of hanging open.
112
126
  * Do not call this for a room with zero participants — that room is still
113
- * inside emptyTimeout or departureTimeout. Safe to call repeatedly.
127
+ * inside emptyTimeout or departureTimeout. Safe to call repeatedly; a session
128
+ * with no matching 'start' simply records no duration.
114
129
  */
115
- export declare const reclaimOrphanJamRoom: (jam: PostWithMeta, roomName?: string) => Promise<void>;
130
+ export declare const reclaimOrphanJamRoom: (jam: PostWithMeta, roomName?: string, recurrenceId?: string) => Promise<void>;
116
131
  export declare const finishRecording: (jamRecording: JamRecordingWithMeta) => Promise<void>;
117
132
  export declare const jamState: (jam: PostWithMeta, hideParticipants?: boolean, recurrenceId?: string) => Promise<JamState>;
@@ -6,7 +6,7 @@ import { allpeepDb } from '../db/index.js';
6
6
  import { serverRootUrl } from '../server/index.js';
7
7
  import { uuidv7 } from 'uuidv7';
8
8
  import { createJamEvent, updateJamRecording } from './mutations.js';
9
- import { findActiveRecording, findActiveRtmpStream } from './finders.js';
9
+ import { findActiveRecording, findActiveRtmpStream, listJamStarts, } from './finders.js';
10
10
  import { cancelRecordingAutoStop, scheduleRecordingAutoStop } from './jobs.js';
11
11
  import { finalizeJamRecording } from './recording.js';
12
12
  import { jamRecordingUploadSecret } from './recordingUploadAuth.js';
@@ -276,11 +276,35 @@ export const stopRecording = async (jamPost, recurrenceId) => {
276
276
  return { ...jamRecording, status: 'finalizing' };
277
277
  };
278
278
  /**
279
- * Stops leftover egress and deletes an egress-only LiveKit room.
279
+ * Record the best-effort 'close' for a reclaimed (crashed) session so the
280
+ * start…close duration is not left dangling.
281
+ *
282
+ * The room name does not carry the occurrence (`jamRoomName` collapses it), so
283
+ * when the caller has no occurrence it is resolved from the jam's most recent
284
+ * persisted 'start' — the start of the crashed session. `computeJamStats`
285
+ * pairs a close with the start of the same occurrence, so a close written
286
+ * without the occurrence would latch onto the wrong one (or none) for a
287
+ * recurring series.
288
+ */
289
+ export const writeReclaimClose = async (jam, recurrenceId) => {
290
+ const closeRecurrenceId = recurrenceId ?? (await listJamStarts(jam.id))[0]?.recurrenceId;
291
+ await createJamEvent({
292
+ id: uuidv7(),
293
+ jamId: jam.id,
294
+ type: 'close',
295
+ profileId: 'system',
296
+ recurrenceId: closeRecurrenceId,
297
+ });
298
+ };
299
+ /**
300
+ * Stops leftover egress, deletes an egress-only LiveKit room, and emits a
301
+ * 'close' session event so an abandoned session (participants crashed before
302
+ * closeJam ran) still gets a duration in analytics instead of hanging open.
280
303
  * Do not call this for a room with zero participants — that room is still
281
- * inside emptyTimeout or departureTimeout. Safe to call repeatedly.
304
+ * inside emptyTimeout or departureTimeout. Safe to call repeatedly; a session
305
+ * with no matching 'start' simply records no duration.
282
306
  */
283
- export const reclaimOrphanJamRoom = async (jam, roomName = jam.id) => {
307
+ export const reclaimOrphanJamRoom = async (jam, roomName = jam.id, recurrenceId) => {
284
308
  try {
285
309
  await stopRecording(jam);
286
310
  }
@@ -300,6 +324,14 @@ export const reclaimOrphanJamRoom = async (jam, roomName = jam.id) => {
300
324
  catch (e) {
301
325
  log.warn(`Failed to delete orphan jam room ${roomName}: ${e.message}`);
302
326
  }
327
+ // Best-effort: a crashed session still records a close so the start…close
328
+ // duration is not left dangling. Never fail the reclaim on this.
329
+ try {
330
+ await writeReclaimClose(jam, recurrenceId);
331
+ }
332
+ catch (e) {
333
+ log.warn(`Failed to record close for reclaimed jam ${jam.id}: ${e.message}`);
334
+ }
303
335
  };
304
336
  export const finishRecording = async (jamRecording) => {
305
337
  const jamEvent = await createJamEvent({
@@ -333,7 +365,7 @@ export const jamState = async (jam, hideParticipants, recurrenceId) => {
333
365
  const identities = await listParticipantIdentities(roomName);
334
366
  const { humans, observers } = splitJamParticipants(identities);
335
367
  if (shouldReclaimJamRoom(room.numParticipants, humans.length)) {
336
- void reclaimOrphanJamRoom(jam, roomName);
368
+ void reclaimOrphanJamRoom(jam, roomName, recurrenceId);
337
369
  return inactive;
338
370
  }
339
371
  return {