@openpeepshq/core 0.12.0 → 0.14.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.
@@ -0,0 +1,64 @@
1
+ import { AccountWithMeta } from '@openpeepshq/common/types';
2
+ /**
3
+ * A binary media file that will be written to the zip.
4
+ */
5
+ export interface ExportMediaFile {
6
+ mediaAttachmentId?: string;
7
+ /** Zip-relative path, e.g. `media/<id>-<filename>`. */
8
+ path: string;
9
+ filename: string;
10
+ mimetype?: string;
11
+ size?: number;
12
+ /** Post/profile ids that reference this file. */
13
+ usedIn: string[];
14
+ }
15
+ export interface AccountExportManifest {
16
+ exportedAt: string;
17
+ accountId: string;
18
+ profileIds: string[];
19
+ counts: {
20
+ createdPosts: number;
21
+ contextPosts: number;
22
+ reactedPosts: number;
23
+ media: number;
24
+ mediaBytes: number;
25
+ /** Posts omitted because they could not be serialized to a public post. */
26
+ skipped: number;
27
+ /** Media omitted because the file could not be read from storage. */
28
+ skippedMedia: number;
29
+ };
30
+ }
31
+ /**
32
+ * Memory bound of the export assembly: every unbounded read (the account's
33
+ * created posts, the reaction/unreaction entry history, the id-hydrates and
34
+ * the ancestor-CTE seeds) is paged in chunks of at most this many rows, and
35
+ * every media file is streamed straight to the staging directory, so the
36
+ * worker holds at most one page of the account's data at once — memory stays
37
+ * flat for a very large account. The async job exists precisely because
38
+ * exports are unbounded (issue #237: "Media cap: no -> async job"); the bound
39
+ * is on how much the worker holds at once, not on what the export contains
40
+ * (there is deliberately no cap or truncation — a very large export is
41
+ * complete).
42
+ */
43
+ export declare const EXPORT_PAGE_SIZE = 200;
44
+ /**
45
+ * Materialize an account's export as a zip archive under `destDir`: stage the
46
+ * account's data in bounded passes (below), zip the staging directory into
47
+ * `export.zip`, then reclaim the staging directory.
48
+ *
49
+ * The assembly never holds the account's data set in memory whole — each
50
+ * unbounded read (created posts, reaction history, id-hydrates, ancestor CTE
51
+ * seeds) is id-keyed / keyset paginated at `EXPORT_PAGE_SIZE`, each post is
52
+ * serialized and written as its page is processed, and every media file is
53
+ * streamed straight to the staging directory (never buffered). The only
54
+ * retained state is O(distinct media) manifest metadata, which is small even
55
+ * for a very large account. Review #237 r13: the async job's whole reason to
56
+ * exist is that exports are unbounded, so the assembly must not re-introduce
57
+ * the unbounded-memory risk it was built to remove.
58
+ *
59
+ * Returns the zip path and the export manifest.
60
+ */
61
+ export declare const buildAccountExportZip: (account: AccountWithMeta, destDir: string) => Promise<{
62
+ zipPath: string;
63
+ manifest: AccountExportManifest;
64
+ }>;
@@ -0,0 +1,426 @@
1
+ import path from 'node:path';
2
+ import { mkdir, writeFile, rm, stat } from 'node:fs/promises';
3
+ import { createWriteStream } from 'node:fs';
4
+ import { Readable } from 'node:stream';
5
+ import { pipeline } from 'node:stream/promises';
6
+ import { and, asc, gt, inArray, sql } from 'drizzle-orm';
7
+ import { entries as entriesEdge, posts as postsTable } from '../db/pg/schema/index.js';
8
+ import { logger } from '../log/index.js';
9
+ import { allpeepDb } from '../db/index.js';
10
+ import { publicAccountSchema, publicPostSchema, publicProfileSchema, } from '@openpeepshq/common/types';
11
+ import { currentReactionsFromEntries } from '@openpeepshq/common/lib';
12
+ import { getProfiles } from '../profiles/cache.js';
13
+ import { postsAuthMapping } from '../posts/mapping.js';
14
+ import { transformPost } from '../posts/helpers/index.js';
15
+ import { fetchRowsByIds, hydrateMapData } from '../db/pg/map/relations.js';
16
+ import { mediaStorage } from '../media/index.js';
17
+ import { zipDirectory } from '../backups/index.js';
18
+ const log = logger('app:accounts:export');
19
+ /**
20
+ * Memory bound of the export assembly: every unbounded read (the account's
21
+ * created posts, the reaction/unreaction entry history, the id-hydrates and
22
+ * the ancestor-CTE seeds) is paged in chunks of at most this many rows, and
23
+ * every media file is streamed straight to the staging directory, so the
24
+ * worker holds at most one page of the account's data at once — memory stays
25
+ * flat for a very large account. The async job exists precisely because
26
+ * exports are unbounded (issue #237: "Media cap: no -> async job"); the bound
27
+ * is on how much the worker holds at once, not on what the export contains
28
+ * (there is deliberately no cap or truncation — a very large export is
29
+ * complete).
30
+ */
31
+ export const EXPORT_PAGE_SIZE = 200;
32
+ /**
33
+ * Read a set of posts by id, hydrating relations and transforming to their
34
+ * public shape (so other users' private data — e.g. emails — is never
35
+ * included). Soft-deleted rows are included (`fetchRowsByIds` only filters
36
+ * `deletedAt IS NULL` when its `softDelete` argument is not exactly `false`)
37
+ * so the export is a complete record of what the account authored or
38
+ * interacted with: a post the account deleted is still that account's data
39
+ * to receive back.
40
+ *
41
+ * Bounded: the ids are read + hydrated in pages of at most `EXPORT_PAGE_SIZE`
42
+ * (one `fetchRowsByIds`/`hydrateMapData` pair per page), so a very large id
43
+ * set is never fetched or hydrated in one pass. When `onPage` is given, each
44
+ * page is handed to it (and then dropped) as soon as it is hydrated, so the
45
+ * caller streams its work per page and never holds the whole id set's posts
46
+ * at once. Returns the number of posts hydrated across all pages.
47
+ */
48
+ const hydratePostsByIdsPaged = async (ids, onPage) => {
49
+ if (ids.length === 0)
50
+ return 0;
51
+ const { db } = await allpeepDb();
52
+ const mapData = postsAuthMapping.data();
53
+ let hydrated = 0;
54
+ for (let i = 0; i < ids.length; i += EXPORT_PAGE_SIZE) {
55
+ const rows = await fetchRowsByIds(db, mapData.collection, ids.slice(i, i + EXPORT_PAGE_SIZE), false);
56
+ const posts = (await Promise.all((await hydrateMapData(db, mapData, rows)).map((post) => transformPost(post, undefined, { embedThreadPreview: false }))));
57
+ hydrated += posts.length;
58
+ if (onPage)
59
+ await onPage(posts);
60
+ }
61
+ return hydrated;
62
+ };
63
+ /**
64
+ * Walk the `reply_to` chains above the given posts (post -> parent ->
65
+ * grandparent ... up to each thread root) in recursive-CTE queries and return
66
+ * every ancestor post id. Capped to guard against pathological chains.
67
+ *
68
+ * This mirrors the canonical `reply_to` walk in `posts/activity.ts`
69
+ * (`findReplyRootId`) — same edge direction (`from_id` = child, `to_id` =
70
+ * parent), same `depth < 64` cap — generalized to many starting posts at once.
71
+ * Keep the two in sync if the cap or the edge semantics ever change.
72
+ *
73
+ * Bounded: the start ids seed the CTE in pages (one `execute` per page of at
74
+ * most `EXPORT_PAGE_SIZE` ids, ancestors de-duplicated across pages), so a
75
+ * pathological account with thousands of replies does not render one
76
+ * multi-thousand-element `unnest` parameter.
77
+ */
78
+ const ancestorIdsOf = async (db, postIds) => {
79
+ if (postIds.length === 0)
80
+ return [];
81
+ const seen = new Set();
82
+ for (let i = 0; i < postIds.length; i += EXPORT_PAGE_SIZE) {
83
+ const page = postIds.slice(i, i + EXPORT_PAGE_SIZE);
84
+ const result = (await db.execute(sql `
85
+ WITH RECURSIVE walk AS (
86
+ SELECT id AS node_id, 0 AS depth
87
+ FROM (SELECT unnest(${sql.param(page)}::text[]))
88
+ AS ids (id)
89
+ UNION ALL
90
+ SELECT rt.to_id, walk.depth + 1
91
+ FROM reply_to rt
92
+ INNER JOIN walk ON rt.from_id = walk.node_id
93
+ WHERE walk.depth < 64
94
+ )
95
+ SELECT DISTINCT node_id
96
+ FROM walk
97
+ ORDER BY node_id
98
+ `));
99
+ for (const row of result.rows) {
100
+ seen.add(row.node_id);
101
+ }
102
+ }
103
+ // Drop the starting posts themselves; only their ancestors are context.
104
+ const starting = new Set(postIds);
105
+ return [...seen].filter((id) => !starting.has(id));
106
+ };
107
+ /**
108
+ * Return the ids of posts that one of the given profiles currently has a net
109
+ * (not retracted) reaction on. Reactions and unactions are de-duplicated
110
+ * exactly the way the UI computes current reactions (latest wins per
111
+ * (profile, emoji); only `reaction` entries survive).
112
+ *
113
+ * Bounded: the reaction/unreaction entry history is read in id-keyed keyset
114
+ * pages (at most `EXPORT_PAGE_SIZE` per read), retaining only the current
115
+ * per-post reaction set — never the whole entry history.
116
+ */
117
+ const reactedPostIdsOf = async (db, profileIds) => {
118
+ if (profileIds.length === 0)
119
+ return [];
120
+ const byPost = new Map();
121
+ let lastId = null;
122
+ for (;;) {
123
+ const conditions = [
124
+ inArray(entriesEdge.fromId, profileIds),
125
+ sql `body->>'type' in ('reaction', 'unreaction')`,
126
+ ];
127
+ if (lastId)
128
+ conditions.push(gt(entriesEdge.id, lastId));
129
+ const rows = (await db
130
+ .select({
131
+ id: entriesEdge.id,
132
+ fromId: entriesEdge.fromId,
133
+ toId: entriesEdge.toId,
134
+ body: entriesEdge.body,
135
+ createdAt: entriesEdge.createdAt,
136
+ })
137
+ .from(entriesEdge)
138
+ .where(and(...conditions))
139
+ .orderBy(asc(entriesEdge.id))
140
+ .limit(EXPORT_PAGE_SIZE));
141
+ for (const row of rows) {
142
+ const kind = row.body?.type;
143
+ if (kind !== 'reaction' && kind !== 'unreaction')
144
+ continue;
145
+ const reaction = row.body?.data?.reaction;
146
+ if (!reaction)
147
+ continue;
148
+ const list = byPost.get(row.toId) ?? [];
149
+ list.push({
150
+ type: kind,
151
+ data: { reaction },
152
+ profile: { id: row.fromId },
153
+ createdAt: row.createdAt,
154
+ });
155
+ byPost.set(row.toId, list);
156
+ }
157
+ lastId = rows[rows.length - 1]?.id ?? null;
158
+ if (!lastId || rows.length < EXPORT_PAGE_SIZE)
159
+ break;
160
+ }
161
+ const postIds = [];
162
+ for (const [postId, list] of byPost.entries()) {
163
+ const current = currentReactionsFromEntries(list);
164
+ if (current.length > 0)
165
+ postIds.push(postId);
166
+ }
167
+ return postIds;
168
+ };
169
+ const collectMediaFromPosts = (files, posts) => {
170
+ for (const post of posts) {
171
+ const attachments = post.data
172
+ ?.attachments ?? [];
173
+ for (const att of attachments) {
174
+ const id = idFromMediaUrl(att.url);
175
+ if (!id)
176
+ continue;
177
+ const filename = sanitizeFilename(att.filename || id);
178
+ const existing = files.get(id);
179
+ const usedIn = existing?.usedIn ?? [];
180
+ if (!usedIn.includes(post.id))
181
+ usedIn.push(post.id);
182
+ files.set(id, {
183
+ mediaAttachmentId: id,
184
+ path: `media/${id}-${filename}`,
185
+ filename,
186
+ mimetype: att.meta?.mimetype,
187
+ size: att.meta?.size,
188
+ usedIn,
189
+ });
190
+ }
191
+ }
192
+ };
193
+ const collectMediaFromProfiles = (files, profiles) => {
194
+ for (const profile of profiles) {
195
+ for (const url of [profile.avatar, profile.header]) {
196
+ if (!url)
197
+ continue;
198
+ const id = idFromMediaUrl(url);
199
+ if (!id)
200
+ continue;
201
+ const filename = sanitizeFilename(filenameFromMediaUrl(url) || id);
202
+ const existing = files.get(id);
203
+ const usedIn = existing?.usedIn ?? [];
204
+ if (!usedIn.includes(profile.id))
205
+ usedIn.push(profile.id);
206
+ files.set(id, {
207
+ mediaAttachmentId: id,
208
+ path: `media/${id}-${filename}`,
209
+ filename,
210
+ usedIn,
211
+ });
212
+ }
213
+ }
214
+ };
215
+ /**
216
+ * Materialize an account's export as a zip archive under `destDir`: stage the
217
+ * account's data in bounded passes (below), zip the staging directory into
218
+ * `export.zip`, then reclaim the staging directory.
219
+ *
220
+ * The assembly never holds the account's data set in memory whole — each
221
+ * unbounded read (created posts, reaction history, id-hydrates, ancestor CTE
222
+ * seeds) is id-keyed / keyset paginated at `EXPORT_PAGE_SIZE`, each post is
223
+ * serialized and written as its page is processed, and every media file is
224
+ * streamed straight to the staging directory (never buffered). The only
225
+ * retained state is O(distinct media) manifest metadata, which is small even
226
+ * for a very large account. Review #237 r13: the async job's whole reason to
227
+ * exist is that exports are unbounded, so the assembly must not re-introduce
228
+ * the unbounded-memory risk it was built to remove.
229
+ *
230
+ * Returns the zip path and the export manifest.
231
+ */
232
+ export const buildAccountExportZip = async (account, destDir) => {
233
+ const { db } = await allpeepDb();
234
+ await mkdir(destDir, { recursive: true });
235
+ const staging = path.join(destDir, 'staging');
236
+ await rm(staging, { recursive: true, force: true });
237
+ await mkdir(staging, { recursive: true });
238
+ const profiles = await getProfiles(account.profiles.map((p) => p.id));
239
+ const profileIds = profiles.map((p) => p.id);
240
+ // account.json — only this account's own data (its email is included,
241
+ // which is correct: it belongs to the exporting user).
242
+ await writeFile(path.join(staging, 'account.json'), JSON.stringify(publicAccountSchema.parse(account), null, 2));
243
+ // profiles/ — each controlled profile in its public shape.
244
+ await mkdir(path.join(staging, 'profiles'), { recursive: true });
245
+ for (const profile of profiles) {
246
+ const parsed = publicProfileSchema.safeParse(profile);
247
+ if (parsed.success) {
248
+ await writeFile(path.join(staging, 'profiles', `${profile.id}.json`), JSON.stringify(parsed.data, null, 2));
249
+ }
250
+ }
251
+ await mkdir(path.join(staging, 'posts/created'), { recursive: true });
252
+ await mkdir(path.join(staging, 'posts/context'), { recursive: true });
253
+ await mkdir(path.join(staging, 'posts/reacted-to'), { recursive: true });
254
+ const mediaDir = path.join(staging, 'media');
255
+ await mkdir(mediaDir, { recursive: true });
256
+ let createdWritten = 0;
257
+ let contextWritten = 0;
258
+ let reactedWritten = 0;
259
+ let createdHydrated = 0;
260
+ let contextHydrated = 0;
261
+ let reactedHydrated = 0;
262
+ // Media referenced by the exported posts + profiles, keyed by media id.
263
+ // O(distinct media) metadata only (the manifest) — the file bytes are
264
+ // streamed to disk, never held in memory.
265
+ const mediaFiles = new Map();
266
+ // Serialize one post to its public shape and write it to `<dir>/<id>.json`.
267
+ // Returns false when the post could not be serialized (it is then dropped
268
+ // from the artifact and counted in `skipped`, not hidden).
269
+ const writePost = async (post, dir) => {
270
+ const parsed = publicPostSchema.safeParse(post);
271
+ if (!parsed.success) {
272
+ log.warn(`Skipping post ${post.id} in export (could not serialize to public post)`);
273
+ return false;
274
+ }
275
+ await writeFile(path.join(staging, `${dir}/${post.id}.json`), JSON.stringify(parsed.data, null, 2));
276
+ return true;
277
+ };
278
+ // Pass 1 — the account's own created posts, id-keyed keyset pages. Soft
279
+ // deleted posts are included: the id walk applies no `deletedAt` filter and
280
+ // the hydrate reads with `softDelete: false`, so a post the account deleted
281
+ // still lands in the export (a complete record, not the live view).
282
+ const createdIds = [];
283
+ let lastCreatedId = null;
284
+ for (;;) {
285
+ const conditions = [inArray(postsTable.creatorId, profileIds)];
286
+ if (lastCreatedId)
287
+ conditions.push(gt(postsTable.id, lastCreatedId));
288
+ const page = (await db
289
+ .select({ id: postsTable.id })
290
+ .from(postsTable)
291
+ .where(and(...conditions))
292
+ .orderBy(asc(postsTable.id))
293
+ .limit(EXPORT_PAGE_SIZE));
294
+ if (page.length === 0)
295
+ break;
296
+ const pageIds = page.map((r) => r.id);
297
+ createdIds.push(...pageIds);
298
+ // Consume each page as it hydrates: write the posts, count them, and
299
+ // collect their media, then drop the page — never hold them all.
300
+ await hydratePostsByIdsPaged(pageIds, async (posts) => {
301
+ createdHydrated += posts.length;
302
+ for (const post of posts) {
303
+ const written = await writePost(post, 'posts/created');
304
+ if (written)
305
+ createdWritten += 1;
306
+ }
307
+ collectMediaFromPosts(mediaFiles, posts);
308
+ });
309
+ lastCreatedId = page[page.length - 1].id;
310
+ if (page.length < EXPORT_PAGE_SIZE)
311
+ break;
312
+ }
313
+ const createdIdSet = new Set(createdIds);
314
+ // Pass 2 — thread context: the created posts' `reply_to` ancestors (one
315
+ // bounded CTE per id page), excluding the created posts themselves. Written
316
+ // as context-only posts; their attachments are deliberately NOT bundled —
317
+ // context is other accounts' content shown only so the account's replies
318
+ // are readable in-thread, and the export must stay the account's own data.
319
+ const contextIds = (await ancestorIdsOf(db, createdIds)).filter((ancestor) => !createdIdSet.has(ancestor));
320
+ await hydratePostsByIdsPaged(contextIds, async (posts) => {
321
+ contextHydrated += posts.length;
322
+ for (const post of posts) {
323
+ const written = await writePost(post, 'posts/context');
324
+ if (written)
325
+ contextWritten += 1;
326
+ }
327
+ });
328
+ // Pass 3 — posts the controlled profiles reacted to (net reaction, deduped
329
+ // via `currentReactionsFromEntries`), the entry history read in keyset
330
+ // pages and each post hydrated + written as its page resolves.
331
+ const reactedIds = await reactedPostIdsOf(db, profileIds);
332
+ await hydratePostsByIdsPaged(reactedIds, async (posts) => {
333
+ reactedHydrated += posts.length;
334
+ for (const post of posts) {
335
+ const written = await writePost(post, 'posts/reacted-to');
336
+ if (written)
337
+ reactedWritten += 1;
338
+ }
339
+ collectMediaFromPosts(mediaFiles, posts);
340
+ });
341
+ // Profile avatar/header media, collected last so a file shared with a post
342
+ // keeps its post id(s) in `usedIn` first (the profile id is appended).
343
+ collectMediaFromProfiles(mediaFiles, profiles);
344
+ // media/ — every referenced file streamed to disk (never buffered) in
345
+ // pages; a file that cannot be read is omitted and revealed by
346
+ // `skippedMedia` rather than hidden.
347
+ let mediaBytes = 0;
348
+ const bundled = [];
349
+ const allMedia = [...mediaFiles.values()];
350
+ for (let i = 0; i < allMedia.length; i += EXPORT_PAGE_SIZE) {
351
+ for (const file of allMedia.slice(i, i + EXPORT_PAGE_SIZE)) {
352
+ const bytes = await copyMediaFile(file, staging);
353
+ if (bytes === null)
354
+ continue;
355
+ mediaBytes += bytes;
356
+ bundled.push(file);
357
+ }
358
+ }
359
+ await writeFile(path.join(mediaDir, 'manifest.json'), JSON.stringify(bundled, null, 2));
360
+ const manifest = {
361
+ exportedAt: new Date().toISOString(),
362
+ accountId: account.id,
363
+ profileIds,
364
+ counts: {
365
+ createdPosts: createdWritten,
366
+ contextPosts: contextWritten,
367
+ reactedPosts: reactedWritten,
368
+ media: bundled.length,
369
+ mediaBytes,
370
+ // Posts that hydrated but could not be serialized to a public post are
371
+ // dropped from the artifact; the counts reveal the shrink instead of
372
+ // hiding it (review #237 r2).
373
+ skipped: createdHydrated +
374
+ contextHydrated +
375
+ reactedHydrated -
376
+ (createdWritten + contextWritten + reactedWritten),
377
+ // Files referenced by the posts/profiles but missing from storage (or
378
+ // on remote storage): the manifest reveals the shrink instead of
379
+ // hiding it, like `skipped` for posts (review #237 r9).
380
+ skippedMedia: allMedia.length - bundled.length,
381
+ },
382
+ };
383
+ await writeFile(path.join(staging, 'meta.json'), JSON.stringify(manifest, null, 2));
384
+ const zipPath = path.join(destDir, 'export.zip');
385
+ await rm(zipPath, { force: true });
386
+ await zipDirectory(staging, zipPath);
387
+ await rm(staging, { recursive: true, force: true });
388
+ return { zipPath, manifest };
389
+ };
390
+ /**
391
+ * Copy one media file from storage into `<staging>/<file.path>`. Returns the
392
+ * byte size, or null if the file cannot be read (it is then omitted).
393
+ */
394
+ const copyMediaFile = async (file, staging) => {
395
+ const id = file.mediaAttachmentId;
396
+ if (!id)
397
+ return null;
398
+ try {
399
+ const storage = await mediaStorage();
400
+ if (!storage.isLocal()) {
401
+ log.warn(`Skipping non-local media ${id} (remote storage is not bundled)`);
402
+ return null;
403
+ }
404
+ // Stream (never buffer) — a multi-hundred-megabyte video must not be
405
+ // materialised as a Buffer (the media/index.ts convention).
406
+ const stream = await storage.getStream(id);
407
+ const finalPath = path.join(staging, file.path);
408
+ await mkdir(path.dirname(finalPath), { recursive: true });
409
+ await pipeline(Readable.fromWeb(stream), createWriteStream(finalPath));
410
+ return (await stat(finalPath)).size;
411
+ }
412
+ catch (error) {
413
+ log.warn(`Could not include media ${id} in export: ${error.message}`);
414
+ return null;
415
+ }
416
+ };
417
+ // Media URLs look like `<root><prefix>/allpeep/<id>/<filename>`.
418
+ const idFromMediaUrl = (url) => {
419
+ const m = url.match(/\/allpeep\/([A-Za-z0-9_-]+)/);
420
+ return m?.[1] ?? null;
421
+ };
422
+ const filenameFromMediaUrl = (url) => {
423
+ const parts = url.split('/');
424
+ return parts[parts.length - 1] || null;
425
+ };
426
+ const sanitizeFilename = (name) => name.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 128) || 'file';
@@ -0,0 +1,35 @@
1
+ import { type AccountExportManifest } from './export';
2
+ import type { AccountExportReady } from '@openpeepshq/common/types';
3
+ export interface AccountExportJobData {
4
+ accountId: string;
5
+ }
6
+ export interface AccountExportJobResult {
7
+ /**
8
+ * The shared ready triple (state + single-use token + expiry), single-sourced
9
+ * from `AccountExportReady` so it can't drift from the status endpoint's
10
+ * `downloadToken`/`expiresAt` payload. `path`/`manifest` are job-local book-
11
+ * keeping (where the zip landed, its counts) and are not part of the
12
+ * download-ready shape.
13
+ */
14
+ ready?: AccountExportReady;
15
+ path?: string;
16
+ manifest?: AccountExportManifest;
17
+ }
18
+ /**
19
+ * Run a single account export: gather the account's data, assemble the zip
20
+ * archive, and publish a short-lived download token. Failures are recorded
21
+ * (not thrown) so the BullMQ job itself does not end up in a noisy failed
22
+ * state — the status endpoint reports the error to the requester. `jobId` is
23
+ * the BullMQ job id.
24
+ *
25
+ * The zip is staged under `<media.storage.params.path>/exports/<accountId>-<jobId>`.
26
+ * `exportStore.ts` owns that path and the daily cleanup sweep reclaims it.
27
+ */
28
+ export declare const processAccountExportJob: (jobId: string, accountId: string) => Promise<AccountExportJobResult>;
29
+ declare const accountExportQueue: () => import("bullmq").Queue, accountExportWorker: () => import("bullmq").Worker;
30
+ /**
31
+ * Daily (02:15 UTC) sweep of stale export artifacts. Idempotent under
32
+ * `upsertJobScheduler`, safe to call on every worker boot.
33
+ */
34
+ export declare const ensureAccountExportCleanupSchedule: () => Promise<void>;
35
+ export { accountExportQueue, accountExportWorker };
@@ -0,0 +1,81 @@
1
+ import path from 'node:path';
2
+ import { queueAndWorker } from '../jobs/index.js';
3
+ import { logger } from '../log/index.js';
4
+ import { findAccount } from './finders.js';
5
+ import { buildAccountExportZip } from './export.js';
6
+ import { ensureExportDir, markExportBuilding, markExportReady, markExportError, cleanupExpiredExports, } from './exportStore.js';
7
+ const log = logger('app:accounts:exportJob');
8
+ /**
9
+ * Run a single account export: gather the account's data, assemble the zip
10
+ * archive, and publish a short-lived download token. Failures are recorded
11
+ * (not thrown) so the BullMQ job itself does not end up in a noisy failed
12
+ * state — the status endpoint reports the error to the requester. `jobId` is
13
+ * the BullMQ job id.
14
+ *
15
+ * The zip is staged under `<media.storage.params.path>/exports/<accountId>-<jobId>`.
16
+ * `exportStore.ts` owns that path and the daily cleanup sweep reclaims it.
17
+ */
18
+ export const processAccountExportJob = async (jobId, accountId) => {
19
+ await markExportBuilding(jobId, accountId);
20
+ try {
21
+ const account = await findAccount(accountId);
22
+ if (!account) {
23
+ throw new Error('Account no longer exists');
24
+ }
25
+ const exportRoot = await ensureExportDir();
26
+ const destDir = path.join(exportRoot, `${accountId}-${jobId}`);
27
+ // The assembly is bounded: created posts, thread context, reacted-to
28
+ // posts and media are each paged at `EXPORT_PAGE_SIZE` and every file is
29
+ // streamed straight to the staging directory, so the worker never holds
30
+ // the account's whole data set in memory (review #237 r13).
31
+ const { zipPath, manifest } = await buildAccountExportZip(account, destDir);
32
+ const { token, expiresAt } = await markExportReady(jobId, accountId, zipPath);
33
+ log.info(`Export ready for account ${accountId}: jobId=${jobId} ` +
34
+ `created=${manifest.counts.createdPosts} ` +
35
+ `context=${manifest.counts.contextPosts} ` +
36
+ `reacted=${manifest.counts.reactedPosts} ` +
37
+ `media=${manifest.counts.media} ` +
38
+ `expiresAt=${expiresAt}`);
39
+ // The ready triple is the shared `AccountExportReady` shape (same single
40
+ // source the status endpoint reports) — `path`/`manifest` stay job-local.
41
+ const ready = {
42
+ state: 'ready',
43
+ downloadToken: token,
44
+ expiresAt,
45
+ };
46
+ return { ready, path: zipPath, manifest };
47
+ }
48
+ catch (error) {
49
+ const message = error.message || 'Export failed';
50
+ log.error(`Export failed for account ${accountId}: ${message}`, error);
51
+ await markExportError(jobId, accountId, message).catch(() => { });
52
+ return {};
53
+ }
54
+ };
55
+ const [accountExportQueue, accountExportWorker] = queueAndWorker('account-export', async (job) => {
56
+ // The daily cleanup scheduler fires jobs named `cleanup` with no data.
57
+ if (job.name === 'cleanup') {
58
+ return cleanupExpiredExports();
59
+ }
60
+ // `job.id` keys the export record; a missing id would collide concurrent
61
+ // exports under any fallback key, so fail loudly instead of guessing.
62
+ if (!job.id) {
63
+ throw new Error(`account-export job ${job.name} has no job id`);
64
+ }
65
+ return processAccountExportJob(job.id, job.data.accountId);
66
+ }, {
67
+ defaultJobOptions: {
68
+ removeOnComplete: { count: 20 },
69
+ removeOnFail: { age: 86400 * 7, count: 20 },
70
+ },
71
+ });
72
+ /**
73
+ * Daily (02:15 UTC) sweep of stale export artifacts. Idempotent under
74
+ * `upsertJobScheduler`, safe to call on every worker boot.
75
+ */
76
+ export const ensureAccountExportCleanupSchedule = async () => {
77
+ const queue = accountExportQueue();
78
+ await queue.upsertJobScheduler('account-export-cleanup-daily', { pattern: '15 2 * * *' }, { name: 'cleanup' });
79
+ log.info('Account export cleanup schedule registered: cron="15 2 * * *"');
80
+ };
81
+ export { accountExportQueue, accountExportWorker };
@@ -0,0 +1,60 @@
1
+ /** Download tokens and the assembled archives live for 7 days. */
2
+ export declare const EXPORT_TTL_MS: number;
3
+ export declare const EXPORT_TTL_SECONDS: number;
4
+ export type ExportRecordState = 'building' | 'ready' | 'error' | 'expired';
5
+ export interface AccountExportCleanupResult {
6
+ removed: number;
7
+ }
8
+ export interface ExportRecord {
9
+ jobId: string;
10
+ accountId: string;
11
+ state: ExportRecordState;
12
+ token?: string;
13
+ /** Absolute path to the assembled zip (present once `ready`). */
14
+ path?: string;
15
+ /** ISO timestamp the token/zip stop working. */
16
+ expiresAt?: string;
17
+ error?: string;
18
+ }
19
+ /** Resolve the directory that holds assembled export zips. */
20
+ export declare const exportDir: () => Promise<string>;
21
+ /**
22
+ * Mark an export job as building. Called by the worker at the start of the
23
+ * job so the status endpoint reports "building" from the first moment on.
24
+ */
25
+ export declare const markExportBuilding: (jobId: string, accountId: string) => Promise<void>;
26
+ /**
27
+ * Mark an export as ready: mint a one-time download token and record the zip
28
+ * path + expiry under both the job and the token keys.
29
+ */
30
+ export declare const markExportReady: (jobId: string, accountId: string, zipPath: string) => Promise<{
31
+ token: `${string}-${string}-${string}-${string}-${string}`;
32
+ expiresAt: string;
33
+ }>;
34
+ /** Mark an export as failed (recorded so the status endpoint can report it). */
35
+ export declare const markExportError: (jobId: string, accountId: string, error: string) => Promise<void>;
36
+ /**
37
+ * Resolve the record for a job, or `null` when no record exists yet (the job
38
+ * has not started — the caller reports "not-found"). A `ready` record whose
39
+ * archive has expired or been cleaned up is reported as `expired` so the
40
+ * client stops polling and can tell the user to start a new export (instead
41
+ * of treating it as still building forever).
42
+ */
43
+ export declare const getExportByJob: (jobId: string) => Promise<ExportRecord | null>;
44
+ /**
45
+ * Resolve a download record from its one-time token. The token itself is the
46
+ * credential (random, single-use, 7-day TTL) — possession authorizes the
47
+ * download. Returns `null` when the token is unknown, expired, or its file is
48
+ * gone.
49
+ */
50
+ export declare const resolveDownloadByToken: (token: string) => Promise<ExportRecord | null>;
51
+ /** Invalidate a token after a successful download (one-time link). */
52
+ export declare const invalidateToken: (token: string) => Promise<void>;
53
+ /**
54
+ * Delete export artifacts (zips and their staging dirs) that are past the
55
+ * TTL. An artifact whose job record is gone, no longer `ready`, or older
56
+ * than the TTL is reclaimed. Runs on a schedule.
57
+ */
58
+ export declare const cleanupExpiredExports: () => Promise<AccountExportCleanupResult>;
59
+ /** Ensure the exports directory exists. */
60
+ export declare const ensureExportDir: () => Promise<string>;