@openpeepshq/core 0.1.35 → 0.2.1

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 (92) hide show
  1. package/dist/accounts/mutations.js +9 -0
  2. package/dist/analytics/report.d.ts +1 -1
  3. package/dist/config/defaults/logs.d.ts +4 -0
  4. package/dist/config/defaults/logs.js +5 -0
  5. package/dist/config/index.d.ts +3 -328
  6. package/dist/db/explorer/index.d.ts +1 -1
  7. package/dist/db/explorer/index.js +1 -1
  8. package/dist/db/pg/filters/posts.js +1 -1
  9. package/dist/db/pg/map/registry.js +3 -2
  10. package/dist/groups/finders.d.ts +2 -2
  11. package/dist/groups/helpers.d.ts +6 -6
  12. package/dist/groups/mapping.d.ts +4 -4
  13. package/dist/jams/export.d.ts +2 -0
  14. package/dist/jams/export.js +5 -0
  15. package/dist/jams/finders.d.ts +1 -0
  16. package/dist/jams/finders.js +1 -0
  17. package/dist/jams/health.d.ts +23 -0
  18. package/dist/jams/health.js +79 -7
  19. package/dist/jams/helpers.d.ts +2 -2
  20. package/dist/jams/index.d.ts +1 -1
  21. package/dist/jams/index.js +10 -3
  22. package/dist/jams/livekit.d.ts +2 -2
  23. package/dist/jams/mapping.d.ts +10 -10
  24. package/dist/jams/mutations.d.ts +2 -2
  25. package/dist/jams/token.js +6 -2
  26. package/dist/jams/waitingRoom.js +3 -1
  27. package/dist/log/index.d.ts +1 -0
  28. package/dist/log/index.js +1 -0
  29. package/dist/log/retention.d.ts +9 -0
  30. package/dist/log/retention.js +83 -0
  31. package/dist/log/retentionJobs.d.ts +17 -0
  32. package/dist/log/retentionJobs.js +50 -0
  33. package/dist/media/garbageCollection.d.ts +109 -0
  34. package/dist/media/garbageCollection.js +603 -0
  35. package/dist/media/garbageCollectionJobs.d.ts +14 -0
  36. package/dist/media/garbageCollectionJobs.js +55 -0
  37. package/dist/media/index.d.ts +2 -0
  38. package/dist/media/index.js +91 -12
  39. package/dist/media/streaming.d.ts +2 -0
  40. package/dist/media/streaming.js +8 -0
  41. package/dist/mediaAttachments/mapping.d.ts +1 -1
  42. package/dist/notifications/defaultNotifications/index.js +2 -0
  43. package/dist/notifications/defaultNotifications/jamModerator/index.js +25 -16
  44. package/dist/notifications/defaultNotifications/jamModerator/recipients.d.ts +2 -0
  45. package/dist/notifications/defaultNotifications/jamModerator/recipients.js +5 -0
  46. package/dist/notifications/defaultNotifications/jamStarted/index.d.ts +1 -0
  47. package/dist/notifications/defaultNotifications/jamStarted/index.js +61 -13
  48. package/dist/notifications/defaultNotifications/newGroupPost/index.js +3 -3
  49. package/dist/notifications/defaultNotifications/newGroupPost/recipients.d.ts +5 -0
  50. package/dist/notifications/defaultNotifications/newGroupPost/recipients.js +23 -0
  51. package/dist/notifications/defaultNotifications/waitlistOffer/index.d.ts +24 -0
  52. package/dist/notifications/defaultNotifications/waitlistOffer/index.js +40 -0
  53. package/dist/notifications/eventIcsAttachment.d.ts +6 -0
  54. package/dist/notifications/eventIcsAttachment.js +32 -0
  55. package/dist/notifications/helpers.d.ts +11 -1
  56. package/dist/notifications/helpers.js +26 -0
  57. package/dist/notifications/index.d.ts +1 -1
  58. package/dist/notifications/index.js +1 -1
  59. package/dist/notifications/jobs.js +6 -0
  60. package/dist/notifications/mutations.js +9 -1
  61. package/dist/plugins/pluginAuth.js +1 -0
  62. package/dist/posts/activity.d.ts +1 -1
  63. package/dist/posts/activity.js +1 -1
  64. package/dist/posts/conversationQueries.d.ts +31 -0
  65. package/dist/posts/conversationQueries.js +150 -24
  66. package/dist/posts/eventAgenda.js +4 -2
  67. package/dist/posts/finders.d.ts +15 -6
  68. package/dist/posts/finders.js +23 -3
  69. package/dist/posts/helpers/index.d.ts +34 -26
  70. package/dist/posts/helpers/index.js +6 -0
  71. package/dist/posts/index.d.ts +3 -1
  72. package/dist/posts/index.js +3 -1
  73. package/dist/posts/mapping.d.ts +112 -98
  74. package/dist/posts/mutations.d.ts +24 -18
  75. package/dist/posts/mutations.js +222 -72
  76. package/dist/posts/rsvpExport.d.ts +47 -0
  77. package/dist/posts/rsvpExport.js +178 -0
  78. package/dist/posts/unseenCounts.d.ts +6 -0
  79. package/dist/posts/unseenCounts.js +51 -1
  80. package/dist/posts/waitlist.d.ts +13 -0
  81. package/dist/posts/waitlist.js +75 -0
  82. package/dist/posts/waitlistOfferJobs.d.ts +10 -0
  83. package/dist/posts/waitlistOfferJobs.js +91 -0
  84. package/dist/profileSettings/mapping.d.ts +1 -0
  85. package/dist/profiles/index.js +6 -1
  86. package/dist/profiles/mapping.d.ts +10 -10
  87. package/dist/reports/mapping.d.ts +1 -1
  88. package/dist/server/index.d.ts +1 -0
  89. package/dist/stats/mapping.d.ts +7 -6
  90. package/dist/stripe/connection.js +1 -1
  91. package/dist/stripe/helpers.js +7 -3
  92. package/package.json +11 -10
@@ -0,0 +1,603 @@
1
+ import { lstat, readdir, readFile, rename, rm, stat, unlink, writeFile, } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { inArray, sql } from 'drizzle-orm';
4
+ import { config } from '../config/index.js';
5
+ import { database } from '../db/index.js';
6
+ import { mediaAttachments } from '../db/pg/schema/documents.js';
7
+ import { logger } from '../log/index.js';
8
+ import { forgetStreamAccess, getStreamLastAccess } from './streaming.js';
9
+ const log = logger('app:media:gc');
10
+ const DAY_MS = 24 * 60 * 60 * 1000;
11
+ /**
12
+ * How long a file must stay unreferenced before it is deleted. The clock
13
+ * starts the first time a collection run sees the file with no live link, so
14
+ * the run that ships this job only records files — it does not delete them.
15
+ * In-progress uploads (stored, not yet saved onto a post or recording) survive
16
+ * the same window.
17
+ */
18
+ export const MEDIA_GC_GRACE_MS = 7 * DAY_MS;
19
+ /**
20
+ * When deleting HLS directories (derived stream caches), skip deletion if the
21
+ * stream was accessed within this window — a viewer may have a live playback
22
+ * session. The HLS segments are cache-only; they will be reclaimed by the next
23
+ * streaming-cleanup run once truly idle.
24
+ */
25
+ const STREAM_RECENT_ACCESS_MS = 10 * 60 * 1000;
26
+ /** Whether the stream cache for a storage id has been accessed recently.
27
+
28
+ Fails open (returns false) when Redis is unavailable — deletion should never
29
+ block on an inaccessible access log.
30
+ */
31
+ const streamIsRecentlyActive = async (storageId, now) => {
32
+ try {
33
+ const lastAccess = await getStreamLastAccess(storageId);
34
+ return lastAccess !== null && lastAccess > now - STREAM_RECENT_ACCESS_MS;
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ };
40
+ /** SHA-256 digest, base64url, no padding. */
41
+ export const STORAGE_ID_LENGTH = 43;
42
+ const STORAGE_ID_RE = /^[A-Za-z0-9_-]{43}$/;
43
+ /**
44
+ * POSIX regex (no lookahead) shared with the SQL scan. Matches
45
+ * `/storage/allpeep/<id>/<file>` and `/media/streaming/<id>/...`.
46
+ */
47
+ export const STORAGE_URL_SOURCE = '/(?:allpeep|media/streaming)/([A-Za-z0-9_-]{43})(?:[^A-Za-z0-9_-]|$)';
48
+ const IDENT = /^[a-z_][a-z0-9_]*$/;
49
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
50
+ /**
51
+ * Live content that can embed a media URL. The scan also covers every other
52
+ * public jsonb column, so a new page or plugin table is included without a
53
+ * code change. These are the ones GC refuses to run without.
54
+ */
55
+ export const REFERENCE_TABLES = [
56
+ 'posts',
57
+ 'profiles',
58
+ 'groups',
59
+ 'configs',
60
+ 'jam_recordings',
61
+ ];
62
+ /**
63
+ * Rows that store a media URL but are not a live link:
64
+ * - `media_attachments` is the upload registry. It keeps a copy of every file
65
+ * URL, including files whose post or recording is already gone.
66
+ * - `entries` snapshots the post at create and edit time. After the post is
67
+ * deleted those snapshots are the only remaining copy, so counting them
68
+ * would keep the file forever. The rendered post is the post row itself.
69
+ */
70
+ export const EXCLUDED_REFERENCE_TABLES = [
71
+ 'media_attachments',
72
+ 'entries',
73
+ ];
74
+ const excludedTables = new Set(EXCLUDED_REFERENCE_TABLES);
75
+ export const isStorageId = (value) => STORAGE_ID_RE.test(value);
76
+ /** Quick existence check for the stored source file (without the HLS dir). */
77
+ export const mediaFileExists = async (storageId) => {
78
+ if (!isStorageId(storageId))
79
+ return false;
80
+ const layout = await mediaLayout();
81
+ try {
82
+ await stat(join(layout.filesDir, storageId));
83
+ return true;
84
+ }
85
+ catch (error) {
86
+ if (isEnoent(error))
87
+ return false;
88
+ throw error;
89
+ }
90
+ };
91
+ export const quoteIdent = (name) => {
92
+ if (!IDENT.test(name)) {
93
+ throw new Error(`Refusing to scan unexpected identifier "${name}"`);
94
+ }
95
+ return `"${name}"`;
96
+ };
97
+ export const extractStorageIds = (text) => {
98
+ const ids = new Set();
99
+ for (const match of text.matchAll(new RegExp(STORAGE_URL_SOURCE, 'g'))) {
100
+ const id = match[1];
101
+ if (id && isStorageId(id))
102
+ ids.add(id);
103
+ }
104
+ return [...ids];
105
+ };
106
+ // Perf note: the LIKE pre-filter below can be accelerated on large instances
107
+ // by adding a gin_trgm index (pg_trgm extension) on (body::text) for the
108
+ // reference tables. Not applied automatically because CREATE EXTENSION requires
109
+ // superuser and may be unavailable in hosted Postgres environments.
110
+ export const buildReferenceScanSql = (columns, tablesWithDeletedAt) => {
111
+ if (STORAGE_URL_SOURCE.includes("'")) {
112
+ throw new Error('Storage URL pattern cannot contain quotes');
113
+ }
114
+ const branches = columns
115
+ .filter((column) => !excludedTables.has(column.tableName))
116
+ .map((column) => {
117
+ const table = `public.${quoteIdent(column.tableName)}`;
118
+ const col = `${table}.${quoteIdent(column.columnName)}`;
119
+ const text = `COALESCE(${col}::text, '')`;
120
+ const liveOnly = tablesWithDeletedAt.has(column.tableName)
121
+ ? `\n AND ${table}."deleted_at" IS NULL`
122
+ : '';
123
+ // Soft-deleted rows still hold the old URL, but the app renders a
124
+ // tombstone instead of the file. They are not a live link.
125
+ return `SELECT (m.matches)[1] AS storage_id
126
+ FROM ${table}
127
+ CROSS JOIN LATERAL regexp_matches(${text}, '${STORAGE_URL_SOURCE}', 'g') AS m(matches)
128
+ WHERE (${col}::text LIKE '%/allpeep/%' OR ${col}::text LIKE '%/media/streaming/%')${liveOnly}`;
129
+ });
130
+ if (branches.length === 0)
131
+ return null;
132
+ return `SELECT DISTINCT storage_id FROM (\n${branches.join('\nUNION ALL\n')}\n) refs WHERE storage_id IS NOT NULL`;
133
+ };
134
+ const stringField = (row, field) => {
135
+ const value = row[field];
136
+ return typeof value === 'string' ? value : undefined;
137
+ };
138
+ const COLUMN_SQL = `
139
+ SELECT c.table_name, c.column_name
140
+ FROM information_schema.columns c
141
+ JOIN information_schema.tables t
142
+ ON t.table_schema = c.table_schema
143
+ AND t.table_name = c.table_name
144
+ WHERE c.table_schema = 'public'
145
+ AND t.table_type = 'BASE TABLE'
146
+ AND c.udt_name = 'jsonb'
147
+ AND ${[...excludedTables]
148
+ .map((table) => `c.table_name <> '${table}'`)
149
+ .join('\n AND ')}`;
150
+ const DELETED_AT_SQL = `
151
+ SELECT table_name
152
+ FROM information_schema.columns
153
+ WHERE table_schema = 'public'
154
+ AND column_name = 'deleted_at'`;
155
+ const ATTACHMENT_SQL = `
156
+ SELECT id::text AS id, body::text AS body
157
+ FROM media_attachments
158
+ WHERE "deleted_at" IS NULL
159
+ AND (body::text LIKE '%/allpeep/%'
160
+ OR body::text LIKE '%/media/streaming/%')`;
161
+ export const loadReferencedStorageIds = async (executor) => {
162
+ const columnRows = await executor.execute(COLUMN_SQL);
163
+ const columns = [];
164
+ for (const row of columnRows.rows) {
165
+ const tableName = stringField(row, 'table_name');
166
+ const columnName = stringField(row, 'column_name');
167
+ if (!tableName || !columnName)
168
+ continue;
169
+ if (excludedTables.has(tableName))
170
+ continue;
171
+ quoteIdent(tableName);
172
+ quoteIdent(columnName);
173
+ columns.push({ tableName, columnName });
174
+ }
175
+ const scanned = new Set(columns.map((column) => column.tableName));
176
+ const missing = REFERENCE_TABLES.filter((table) => !scanned.has(table));
177
+ if (missing.length > 0) {
178
+ throw new Error(`Media GC refused to run; missing content tables: ${missing.join(', ')}`);
179
+ }
180
+ const deletedAtRows = await executor.execute(DELETED_AT_SQL);
181
+ const tablesWithDeletedAt = new Set();
182
+ for (const row of deletedAtRows.rows) {
183
+ const tableName = stringField(row, 'table_name');
184
+ if (tableName)
185
+ tablesWithDeletedAt.add(tableName);
186
+ }
187
+ const scanSql = buildReferenceScanSql(columns, tablesWithDeletedAt);
188
+ if (!scanSql) {
189
+ throw new Error('Media GC refused to run; nothing to scan');
190
+ }
191
+ const scannedRows = await executor.execute(scanSql);
192
+ const ids = new Set();
193
+ for (const row of scannedRows.rows) {
194
+ const id = stringField(row, 'storage_id');
195
+ if (id && isStorageId(id))
196
+ ids.add(id);
197
+ }
198
+ return ids;
199
+ };
200
+ /**
201
+ * Attachment rows whose local files are all gone. Rows that still point at a
202
+ * file on disk (referenced, or inside the grace window) stay so an in-progress
203
+ * upload can finish.
204
+ */
205
+ export const danglingMediaAttachmentIds = (rows, filesOnDisk) => rows.flatMap((row) => {
206
+ const ids = extractStorageIds(row.body);
207
+ if (ids.length === 0)
208
+ return [];
209
+ return ids.every((id) => !filesOnDisk.has(id)) ? [row.id] : [];
210
+ });
211
+ const emptySweep = () => ({
212
+ deleted: [],
213
+ marked: 0,
214
+ kept: 0,
215
+ skipped: [],
216
+ remainingIds: [],
217
+ tempDeleted: 0,
218
+ storageMissing: false,
219
+ });
220
+ const isEnoent = (error) => error.code === 'ENOENT';
221
+ const readState = async (statePath) => {
222
+ let raw;
223
+ try {
224
+ raw = await readFile(statePath, 'utf8');
225
+ }
226
+ catch (error) {
227
+ if (isEnoent(error))
228
+ return {};
229
+ throw error;
230
+ }
231
+ let parsed;
232
+ try {
233
+ parsed = JSON.parse(raw);
234
+ }
235
+ catch {
236
+ log.warn(`Ignoring unreadable GC state at ${statePath}`);
237
+ return {};
238
+ }
239
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
240
+ return {};
241
+ }
242
+ const state = {};
243
+ for (const [key, value] of Object.entries(parsed)) {
244
+ if (isStorageId(key) &&
245
+ typeof value === 'number' &&
246
+ Number.isFinite(value)) {
247
+ state[key] = value;
248
+ }
249
+ }
250
+ return state;
251
+ };
252
+ const writeState = async (statePath, state) => {
253
+ const tempPath = `${statePath}.${process.pid}.tmp`;
254
+ await writeFile(tempPath, JSON.stringify(state));
255
+ await rename(tempPath, statePath);
256
+ };
257
+ const removeHls = async (hlsRoot, storageId) => {
258
+ if (!isStorageId(storageId))
259
+ return;
260
+ await rm(join(hlsRoot, storageId), { recursive: true, force: true });
261
+ };
262
+ /**
263
+ * Delete stored files with no live reference, once they have stayed that way
264
+ * for the grace period. Also drops HLS directories for those files, stale
265
+ * upload temps, and HLS directories whose source file is already gone.
266
+ */
267
+ export const sweepUnreferencedMedia = async (options) => {
268
+ const now = options.now ?? Date.now();
269
+ const graceMs = options.graceMs ?? MEDIA_GC_GRACE_MS;
270
+ const cutoff = now - graceMs;
271
+ const result = emptySweep();
272
+ let names;
273
+ try {
274
+ names = await readdir(options.filesDir);
275
+ }
276
+ catch (error) {
277
+ if (isEnoent(error)) {
278
+ result.storageMissing = true;
279
+ return result;
280
+ }
281
+ throw error;
282
+ }
283
+ const previous = await readState(options.statePath);
284
+ const next = {};
285
+ const remaining = new Set();
286
+ const doomed = [];
287
+ for (const name of names) {
288
+ const fullPath = join(options.filesDir, name);
289
+ let stat;
290
+ try {
291
+ stat = await lstat(fullPath);
292
+ }
293
+ catch (error) {
294
+ if (isEnoent(error))
295
+ continue;
296
+ throw error;
297
+ }
298
+ if (stat.isSymbolicLink() || !stat.isFile()) {
299
+ result.skipped.push(name);
300
+ continue;
301
+ }
302
+ if (name.startsWith('.tmp-')) {
303
+ if (stat.mtimeMs <= cutoff) {
304
+ try {
305
+ await unlink(fullPath);
306
+ result.tempDeleted += 1;
307
+ }
308
+ catch (error) {
309
+ log.error(`Failed to delete temp upload ${name}: ${error.message}`);
310
+ }
311
+ }
312
+ continue;
313
+ }
314
+ if (!isStorageId(name)) {
315
+ result.skipped.push(name);
316
+ continue;
317
+ }
318
+ if (options.referencedIds.has(name)) {
319
+ result.kept += 1;
320
+ remaining.add(name);
321
+ continue;
322
+ }
323
+ const since = previous[name] ?? now;
324
+ if (since > cutoff) {
325
+ next[name] = since;
326
+ remaining.add(name);
327
+ result.marked += 1;
328
+ continue;
329
+ }
330
+ doomed.push({ name, fullPath, since });
331
+ }
332
+ // Persist clocks before unlinking. A crash mid-delete then retries from
333
+ // this state instead of treating a re-linked file as long-unreferenced.
334
+ await writeState(options.statePath, next);
335
+ let deleteFailed = false;
336
+ for (const item of doomed) {
337
+ try {
338
+ await unlink(item.fullPath);
339
+ }
340
+ catch (error) {
341
+ log.error(`Failed to delete unreferenced media ${item.name}: ${error.message}`);
342
+ next[item.name] = item.since;
343
+ remaining.add(item.name);
344
+ deleteFailed = true;
345
+ continue;
346
+ }
347
+ // Preserve an HLS cache with a recent viewer; streaming cleanup will
348
+ // reclaim it once genuinely idle.
349
+ if (await (options.streamActiveChecker ?? streamIsRecentlyActive)(item.name, now)) {
350
+ log.info(`Preserving HLS cache for ${item.name}; stream was accessed recently`);
351
+ }
352
+ else {
353
+ await removeHls(options.hlsRoot, item.name).catch((error) => {
354
+ log.error(`Failed to delete stream for ${item.name}: ${error.message}`);
355
+ });
356
+ }
357
+ result.deleted.push(item.name);
358
+ }
359
+ if (deleteFailed) {
360
+ await writeState(options.statePath, next);
361
+ }
362
+ await removeOrphanHls(options.hlsRoot, options.referencedIds, remaining, result, options.streamActiveChecker ?? streamIsRecentlyActive, now);
363
+ result.remainingIds = [...remaining];
364
+ return result;
365
+ };
366
+ const removeOrphanHls = async (hlsRoot, referencedIds, filesOnDisk, result, streamActiveChecker, now) => {
367
+ let names;
368
+ try {
369
+ names = await readdir(hlsRoot);
370
+ }
371
+ catch (error) {
372
+ if (isEnoent(error))
373
+ return;
374
+ throw error;
375
+ }
376
+ for (const name of names) {
377
+ if (!isStorageId(name)) {
378
+ result.skipped.push(name);
379
+ continue;
380
+ }
381
+ if (referencedIds.has(name) || filesOnDisk.has(name))
382
+ continue;
383
+ // Preserve an actively-watched stream's HLS cache.
384
+ if (await streamActiveChecker(name, now))
385
+ continue;
386
+ const fullPath = join(hlsRoot, name);
387
+ let stat;
388
+ try {
389
+ stat = await lstat(fullPath);
390
+ }
391
+ catch (error) {
392
+ if (isEnoent(error))
393
+ continue;
394
+ throw error;
395
+ }
396
+ if (!stat.isDirectory()) {
397
+ result.skipped.push(name);
398
+ continue;
399
+ }
400
+ await rm(fullPath, { recursive: true, force: true }).catch((error) => {
401
+ log.error(`Failed to delete orphan stream ${name}: ${error.message}`);
402
+ });
403
+ }
404
+ };
405
+ const defaultExecutor = async () => {
406
+ const db = await database();
407
+ return {
408
+ execute: async (query) => {
409
+ const result = await db.execute(sql.raw(query));
410
+ const rows = Array.isArray(result)
411
+ ? result
412
+ : result.rows;
413
+ if (!Array.isArray(rows)) {
414
+ throw new Error('Media GC query returned no rows');
415
+ }
416
+ return { rows: rows };
417
+ },
418
+ };
419
+ };
420
+ const mediaLayout = async () => {
421
+ const { path } = (await config()).media.storage.params;
422
+ return {
423
+ // Same concatenation the openpeeps storage driver uses for the file dir.
424
+ filesDir: `${path}/allpeep`,
425
+ hlsRoot: join(path, 'hls'),
426
+ statePath: join(path, 'gc-unreferenced.json'),
427
+ };
428
+ };
429
+ const loadAttachmentBodies = async (executor) => {
430
+ const result = await executor.execute(ATTACHMENT_SQL);
431
+ return result.rows.flatMap((row) => {
432
+ const id = stringField(row, 'id');
433
+ const body = stringField(row, 'body');
434
+ if (!id || !UUID_RE.test(id) || body === undefined)
435
+ return [];
436
+ return [{ id, body }];
437
+ });
438
+ };
439
+ export const deleteMediaAttachmentRows = async (ids) => {
440
+ const valid = ids.filter((id) => UUID_RE.test(id));
441
+ if (valid.length === 0)
442
+ return 0;
443
+ const db = await database();
444
+ let deleted = 0;
445
+ const chunkSize = 200;
446
+ for (let index = 0; index < valid.length; index += chunkSize) {
447
+ const chunk = valid.slice(index, index + chunkSize);
448
+ const removed = await db
449
+ .delete(mediaAttachments)
450
+ .where(inArray(mediaAttachments.id, chunk))
451
+ .returning({ id: mediaAttachments.id });
452
+ deleted += removed.length;
453
+ }
454
+ return deleted;
455
+ };
456
+ export const collectUnreferencedMedia = async (graceMs = MEDIA_GC_GRACE_MS) => {
457
+ const executor = await defaultExecutor();
458
+ const referencedIds = await loadReferencedStorageIds(executor);
459
+ const sweep = await sweepUnreferencedMedia({
460
+ ...(await mediaLayout()),
461
+ referencedIds,
462
+ graceMs,
463
+ });
464
+ if (sweep.storageMissing) {
465
+ log.warn('Media storage directory is missing; skipping garbage collection');
466
+ return { ...sweep, referenced: referencedIds.size, attachmentsDeleted: 0 };
467
+ }
468
+ const dangling = danglingMediaAttachmentIds(await loadAttachmentBodies(executor), new Set(sweep.remainingIds));
469
+ const attachmentsDeleted = await deleteMediaAttachmentRows(dangling);
470
+ return { ...sweep, referenced: referencedIds.size, attachmentsDeleted };
471
+ };
472
+ const statusRank = {
473
+ due: 0,
474
+ pending: 1,
475
+ unseen: 2,
476
+ referenced: 3,
477
+ };
478
+ /** How garbage collection treats one file, given the live link set and clock. */
479
+ export const classifyMediaFile = (storageId, referencedIds, unreferencedSinceMs, now, graceMs = MEDIA_GC_GRACE_MS) => {
480
+ if (referencedIds.has(storageId)) {
481
+ return { status: 'referenced', unreferencedSince: null, deletesAt: null };
482
+ }
483
+ if (unreferencedSinceMs === undefined) {
484
+ return { status: 'unseen', unreferencedSince: null, deletesAt: null };
485
+ }
486
+ const deletesAtMs = unreferencedSinceMs + graceMs;
487
+ return {
488
+ status: deletesAtMs <= now ? 'due' : 'pending',
489
+ unreferencedSince: new Date(unreferencedSinceMs).toISOString(),
490
+ deletesAt: new Date(deletesAtMs).toISOString(),
491
+ };
492
+ };
493
+ export const listStoredMedia = async () => {
494
+ const executor = await defaultExecutor();
495
+ const referencedIds = await loadReferencedStorageIds(executor);
496
+ const layout = await mediaLayout();
497
+ const state = await readState(layout.statePath);
498
+ const now = Date.now();
499
+ const prefix = (await config()).media.storage.params.prefix;
500
+ let names = [];
501
+ try {
502
+ names = await readdir(layout.filesDir);
503
+ }
504
+ catch (error) {
505
+ if (!isEnoent(error))
506
+ throw error;
507
+ }
508
+ const files = [];
509
+ for (const name of names) {
510
+ if (!isStorageId(name))
511
+ continue;
512
+ const fullPath = join(layout.filesDir, name);
513
+ let stat;
514
+ try {
515
+ stat = await lstat(fullPath);
516
+ }
517
+ catch (error) {
518
+ if (isEnoent(error))
519
+ continue;
520
+ throw error;
521
+ }
522
+ if (stat.isSymbolicLink() || !stat.isFile())
523
+ continue;
524
+ files.push({
525
+ storageId: name,
526
+ size: stat.size,
527
+ modifiedAt: new Date(stat.mtimeMs).toISOString(),
528
+ url: `${prefix}/allpeep/${name}/file`,
529
+ ...classifyMediaFile(name, referencedIds, state[name], now),
530
+ });
531
+ }
532
+ files.sort((a, b) => statusRank[a.status] - statusRank[b.status] || b.size - a.size);
533
+ return { files, graceMs: MEDIA_GC_GRACE_MS };
534
+ };
535
+ /**
536
+ * Remove one stored file immediately. The garbage-collection clock and
537
+ * dangling attachment rows are cleaned up too. Live links are left in place
538
+ * and will 404. The HLS cache is preserved if the stream was accessed within
539
+ * the recent-access window; it will be reclaimed by the streaming-cleanup cron.
540
+ */
541
+ export const deleteStoredMediaNow = async (storageId) => {
542
+ if (!isStorageId(storageId))
543
+ return false;
544
+ const layout = await mediaLayout();
545
+ const fullPath = join(layout.filesDir, storageId);
546
+ let removed = false;
547
+ try {
548
+ await unlink(fullPath);
549
+ removed = true;
550
+ }
551
+ catch (error) {
552
+ if (!isEnoent(error))
553
+ throw error;
554
+ }
555
+ const hlsPath = join(layout.hlsRoot, storageId);
556
+ // Don't tear down an HLS cache that someone is actively watching — the
557
+ // segments will be reclaimed by the streaming-cleanup cron instead.
558
+ const now = Date.now();
559
+ if (!(await streamIsRecentlyActive(storageId, now))) {
560
+ try {
561
+ const stat = await lstat(hlsPath);
562
+ if (stat.isDirectory() && !stat.isSymbolicLink()) {
563
+ await rm(hlsPath, { recursive: true, force: true });
564
+ removed = true;
565
+ }
566
+ }
567
+ catch (error) {
568
+ if (!isEnoent(error))
569
+ throw error;
570
+ }
571
+ }
572
+ else {
573
+ log.info(`Preserving HLS cache for ${storageId}; stream was accessed recently`);
574
+ }
575
+ const state = await readState(layout.statePath);
576
+ if (storageId in state) {
577
+ const next = { ...state };
578
+ delete next[storageId];
579
+ await writeState(layout.statePath, next);
580
+ }
581
+ const executor = await defaultExecutor();
582
+ let names = [];
583
+ try {
584
+ names = await readdir(layout.filesDir);
585
+ }
586
+ catch (error) {
587
+ if (!isEnoent(error))
588
+ throw error;
589
+ }
590
+ const onDisk = new Set(names.filter(isStorageId));
591
+ const rows = await loadAttachmentBodies(executor);
592
+ const attachmentIds = rows.flatMap((row) => {
593
+ const ids = extractStorageIds(row.body);
594
+ if (!ids.includes(storageId))
595
+ return [];
596
+ return ids.every((id) => !onDisk.has(id)) ? [row.id] : [];
597
+ });
598
+ await deleteMediaAttachmentRows(attachmentIds);
599
+ await forgetStreamAccess(storageId).catch((error) => {
600
+ log.warn(`Failed to forget stream access for ${storageId}: ${error.message}`);
601
+ });
602
+ return removed;
603
+ };
@@ -0,0 +1,14 @@
1
+ export declare const MEDIA_GC_CRON = "30 4 * * *";
2
+ export interface MediaGarbageCollectionJobData {
3
+ /** Override the unreferenced window; mostly for testing. */
4
+ graceMs?: number;
5
+ }
6
+ declare const mediaGarbageCollectionQueue: () => import("bullmq").Queue, mediaGarbageCollectionWorker: () => import("bullmq").Worker;
7
+ export declare const ensureMediaGarbageCollectionSchedule: () => Promise<void>;
8
+ export { mediaGarbageCollectionQueue, mediaGarbageCollectionWorker };
9
+ export interface MediaDeletionJobData {
10
+ storageId: string;
11
+ }
12
+ declare const mediaDeletionQueue: () => import("bullmq").Queue, mediaDeletionWorker: () => import("bullmq").Worker;
13
+ export declare const enqueueMediaDeletion: (storageId: string) => Promise<void>;
14
+ export { mediaDeletionQueue, mediaDeletionWorker };
@@ -0,0 +1,55 @@
1
+ import { queueAndWorker } from '../jobs/index.js';
2
+ import { logger } from '../log/index.js';
3
+ import { forgetStreamAccess } from './streaming.js';
4
+ import { collectUnreferencedMedia, deleteStoredMediaNow, MEDIA_GC_GRACE_MS, } from './garbageCollection.js';
5
+ const log = logger('app:media:gc');
6
+ const DAY_MS = 24 * 60 * 60 * 1000;
7
+ // 04:30 UTC: after stream cleanup (03:00) and clear of the 04:00 occurrence job.
8
+ export const MEDIA_GC_CRON = '30 4 * * *';
9
+ const SCHEDULER_ID = 'media-garbage-collection-daily';
10
+ const JOB_NAME = 'collect';
11
+ const [mediaGarbageCollectionQueue, mediaGarbageCollectionWorker] = queueAndWorker('media-garbage-collection', async (job) => {
12
+ const graceMs = job.data?.graceMs ?? MEDIA_GC_GRACE_MS;
13
+ log.info(`Running media garbage collection (graceMs=${graceMs}, ~${Math.round(graceMs / DAY_MS)}d)`);
14
+ const result = await collectUnreferencedMedia(graceMs);
15
+ log.info(`Media GC done: referenced=${result.referenced}, ` +
16
+ `deleted=${result.deleted.length}, marked=${result.marked}, ` +
17
+ `kept=${result.kept}, temps=${result.tempDeleted}, ` +
18
+ `attachments=${result.attachmentsDeleted}, ` +
19
+ `skipped=${result.skipped.length}`);
20
+ await Promise.all(result.deleted.map((storageId) => forgetStreamAccess(storageId).catch((error) => {
21
+ log.warn(`Failed to forget stream access for ${storageId}: ${error.message}`);
22
+ })));
23
+ }, {
24
+ defaultJobOptions: {
25
+ removeOnComplete: { count: 10 },
26
+ removeOnFail: { age: 86400 * 14, count: 50 },
27
+ },
28
+ });
29
+ export const ensureMediaGarbageCollectionSchedule = async () => {
30
+ const queue = mediaGarbageCollectionQueue();
31
+ await queue.upsertJobScheduler(SCHEDULER_ID, { pattern: MEDIA_GC_CRON }, { name: JOB_NAME });
32
+ log.info(`Media garbage collection schedule registered: cron="${MEDIA_GC_CRON}" ` +
33
+ `grace=${Math.round(MEDIA_GC_GRACE_MS / DAY_MS)}d`);
34
+ };
35
+ export { mediaGarbageCollectionQueue, mediaGarbageCollectionWorker };
36
+ const [mediaDeletionQueue, mediaDeletionWorker] = queueAndWorker('media-deletion', async (job) => {
37
+ const { storageId } = job.data;
38
+ log.info(`Deleting media file ${storageId}`);
39
+ const removed = await deleteStoredMediaNow(storageId);
40
+ if (!removed) {
41
+ log.warn(`Media file ${storageId} was not found during deletion job`);
42
+ }
43
+ else {
44
+ log.info(`Deleted media file ${storageId}`);
45
+ }
46
+ }, {
47
+ defaultJobOptions: {
48
+ removeOnComplete: { count: 50 },
49
+ removeOnFail: { age: 86400 * 7, count: 50 },
50
+ },
51
+ });
52
+ export const enqueueMediaDeletion = async (storageId) => {
53
+ await mediaDeletionQueue().add('delete', { storageId }, { jobId: `delete-${storageId}` });
54
+ };
55
+ export { mediaDeletionQueue, mediaDeletionWorker };
@@ -38,3 +38,5 @@ export * from './streaming';
38
38
  export * from './streamingJobs';
39
39
  export * from './streamingCleanupJobs';
40
40
  export * from './streamingPrewarm';
41
+ export * from './garbageCollection';
42
+ export * from './garbageCollectionJobs';