@openpeepshq/core 0.13.0 → 0.15.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.
- package/dist/accounts/export.d.ts +64 -0
- package/dist/accounts/export.js +426 -0
- package/dist/accounts/exportJob.d.ts +35 -0
- package/dist/accounts/exportJob.js +81 -0
- package/dist/accounts/exportStore.d.ts +60 -0
- package/dist/accounts/exportStore.js +151 -0
- package/dist/accounts/index.d.ts +3 -0
- package/dist/accounts/index.js +3 -0
- package/dist/backups/index.d.ts +1 -0
- package/dist/backups/index.js +1 -1
- package/dist/config/index.d.ts +96 -0
- package/dist/config/index.js +16 -0
- package/dist/media/index.d.ts +2 -2
- package/dist/media/index.js +76 -7
- package/dist/media/processing.d.ts +16 -0
- package/dist/media/processing.js +16 -0
- package/dist/profiles/autoFollow.js +23 -5
- package/package.json +4 -4
|
@@ -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>;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { mkdir, rm, stat, readdir } from 'node:fs/promises';
|
|
4
|
+
import { getSharedConnection } from '../redis/index.js';
|
|
5
|
+
import { config } from '../config/index.js';
|
|
6
|
+
import { logger } from '../log/index.js';
|
|
7
|
+
const log = logger('app:accounts:exportStore');
|
|
8
|
+
/** Download tokens and the assembled archives live for 7 days. */
|
|
9
|
+
export const EXPORT_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
10
|
+
export const EXPORT_TTL_SECONDS = Math.floor(EXPORT_TTL_MS / 1000);
|
|
11
|
+
const byJobKey = (jobId) => `openpeeps:account-export:${jobId}`;
|
|
12
|
+
const byTokenKey = (token) => `openpeeps:account-export:token:${token}`;
|
|
13
|
+
const readRecord = async (key) => {
|
|
14
|
+
const redis = await getSharedConnection();
|
|
15
|
+
const raw = await redis.get(key);
|
|
16
|
+
return raw ? JSON.parse(raw) : undefined;
|
|
17
|
+
};
|
|
18
|
+
const writeRecord = async (key, record, ttlSeconds = EXPORT_TTL_SECONDS) => {
|
|
19
|
+
const redis = await getSharedConnection();
|
|
20
|
+
await redis.set(key, JSON.stringify(record), { EX: ttlSeconds });
|
|
21
|
+
};
|
|
22
|
+
/** Resolve the directory that holds assembled export zips. */
|
|
23
|
+
export const exportDir = async () => {
|
|
24
|
+
const { media: { storage: { params }, }, } = await config();
|
|
25
|
+
return path.join(params.path, 'exports');
|
|
26
|
+
};
|
|
27
|
+
/**
|
|
28
|
+
* Mark an export job as building. Called by the worker at the start of the
|
|
29
|
+
* job so the status endpoint reports "building" from the first moment on.
|
|
30
|
+
*/
|
|
31
|
+
export const markExportBuilding = async (jobId, accountId) => {
|
|
32
|
+
await writeRecord(byJobKey(jobId), {
|
|
33
|
+
jobId,
|
|
34
|
+
accountId,
|
|
35
|
+
state: 'building',
|
|
36
|
+
});
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* Mark an export as ready: mint a one-time download token and record the zip
|
|
40
|
+
* path + expiry under both the job and the token keys.
|
|
41
|
+
*/
|
|
42
|
+
export const markExportReady = async (jobId, accountId, zipPath) => {
|
|
43
|
+
const token = randomUUID();
|
|
44
|
+
const expiresAt = new Date(Date.now() + EXPORT_TTL_MS).toISOString();
|
|
45
|
+
const record = {
|
|
46
|
+
jobId,
|
|
47
|
+
accountId,
|
|
48
|
+
state: 'ready',
|
|
49
|
+
token,
|
|
50
|
+
path: zipPath,
|
|
51
|
+
expiresAt,
|
|
52
|
+
};
|
|
53
|
+
await writeRecord(byJobKey(jobId), record);
|
|
54
|
+
await writeRecord(byTokenKey(token), record);
|
|
55
|
+
return { token, expiresAt };
|
|
56
|
+
};
|
|
57
|
+
/** Mark an export as failed (recorded so the status endpoint can report it). */
|
|
58
|
+
export const markExportError = async (jobId, accountId, error) => {
|
|
59
|
+
await writeRecord(byJobKey(jobId), {
|
|
60
|
+
jobId,
|
|
61
|
+
accountId,
|
|
62
|
+
state: 'error',
|
|
63
|
+
error,
|
|
64
|
+
});
|
|
65
|
+
};
|
|
66
|
+
/**
|
|
67
|
+
* Resolve the record for a job, or `null` when no record exists yet (the job
|
|
68
|
+
* has not started — the caller reports "not-found"). A `ready` record whose
|
|
69
|
+
* archive has expired or been cleaned up is reported as `expired` so the
|
|
70
|
+
* client stops polling and can tell the user to start a new export (instead
|
|
71
|
+
* of treating it as still building forever).
|
|
72
|
+
*/
|
|
73
|
+
export const getExportByJob = async (jobId) => {
|
|
74
|
+
const record = await readRecord(byJobKey(jobId));
|
|
75
|
+
if (!record)
|
|
76
|
+
return null;
|
|
77
|
+
if (record.state === 'ready') {
|
|
78
|
+
const stillThere = record.path
|
|
79
|
+
? await stat(record.path).then((s) => s.isFile(), () => false)
|
|
80
|
+
: false;
|
|
81
|
+
const expired = record.expiresAt
|
|
82
|
+
? Date.parse(record.expiresAt) < Date.now()
|
|
83
|
+
: false;
|
|
84
|
+
// Past the TTL, or the archive was reclaimed by the cleanup sweep: the
|
|
85
|
+
// token no longer works and the user must start a new export.
|
|
86
|
+
if (expired || !stillThere)
|
|
87
|
+
return { ...record, state: 'expired' };
|
|
88
|
+
}
|
|
89
|
+
return record;
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* Resolve a download record from its one-time token. The token itself is the
|
|
93
|
+
* credential (random, single-use, 7-day TTL) — possession authorizes the
|
|
94
|
+
* download. Returns `null` when the token is unknown, expired, or its file is
|
|
95
|
+
* gone.
|
|
96
|
+
*/
|
|
97
|
+
export const resolveDownloadByToken = async (token) => {
|
|
98
|
+
const record = await readRecord(byTokenKey(token));
|
|
99
|
+
if (!record || record.state !== 'ready')
|
|
100
|
+
return null;
|
|
101
|
+
if (record.expiresAt && Date.parse(record.expiresAt) < Date.now()) {
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
const exists = record.path
|
|
105
|
+
? await stat(record.path).then((s) => s.isFile(), () => false)
|
|
106
|
+
: false;
|
|
107
|
+
if (!exists)
|
|
108
|
+
return null;
|
|
109
|
+
return record;
|
|
110
|
+
};
|
|
111
|
+
/** Invalidate a token after a successful download (one-time link). */
|
|
112
|
+
export const invalidateToken = async (token) => {
|
|
113
|
+
const redis = await getSharedConnection();
|
|
114
|
+
await redis.del(byTokenKey(token)).catch(() => { });
|
|
115
|
+
};
|
|
116
|
+
/**
|
|
117
|
+
* Delete export artifacts (zips and their staging dirs) that are past the
|
|
118
|
+
* TTL. An artifact whose job record is gone, no longer `ready`, or older
|
|
119
|
+
* than the TTL is reclaimed. Runs on a schedule.
|
|
120
|
+
*/
|
|
121
|
+
export const cleanupExpiredExports = async () => {
|
|
122
|
+
const dir = await exportDir();
|
|
123
|
+
let entries = [];
|
|
124
|
+
try {
|
|
125
|
+
entries = await readdir(dir);
|
|
126
|
+
}
|
|
127
|
+
catch {
|
|
128
|
+
return { removed: 0 };
|
|
129
|
+
}
|
|
130
|
+
let removed = 0;
|
|
131
|
+
for (const entry of entries) {
|
|
132
|
+
const full = path.join(dir, entry);
|
|
133
|
+
const statMaybe = await stat(full).catch(() => undefined);
|
|
134
|
+
if (!statMaybe)
|
|
135
|
+
continue;
|
|
136
|
+
const age = Date.now() - statMaybe.mtimeMs;
|
|
137
|
+
if (age < EXPORT_TTL_MS)
|
|
138
|
+
continue;
|
|
139
|
+
await rm(full, { recursive: true, force: true }).catch(() => { });
|
|
140
|
+
removed += 1;
|
|
141
|
+
}
|
|
142
|
+
if (removed > 0)
|
|
143
|
+
log.info(`Export cleanup removed ${removed} item(s)`);
|
|
144
|
+
return { removed };
|
|
145
|
+
};
|
|
146
|
+
/** Ensure the exports directory exists. */
|
|
147
|
+
export const ensureExportDir = async () => {
|
|
148
|
+
const dir = await exportDir();
|
|
149
|
+
await mkdir(dir, { recursive: true });
|
|
150
|
+
return dir;
|
|
151
|
+
};
|
package/dist/accounts/index.d.ts
CHANGED
|
@@ -3,4 +3,7 @@ export { accountsMapping } from './mapping';
|
|
|
3
3
|
export { sendEmailValidationMail } from './helpers';
|
|
4
4
|
export * from './mutations';
|
|
5
5
|
export * from './finders';
|
|
6
|
+
export * from './export';
|
|
7
|
+
export * from './exportStore';
|
|
8
|
+
export * from './exportJob';
|
|
6
9
|
export declare const checkPassword: (account: Account, password: string) => Promise<boolean>;
|
package/dist/accounts/index.js
CHANGED
|
@@ -3,4 +3,7 @@ export { accountsMapping } from './mapping.js';
|
|
|
3
3
|
export { sendEmailValidationMail } from './helpers.js';
|
|
4
4
|
export * from './mutations.js';
|
|
5
5
|
export * from './finders.js';
|
|
6
|
+
export * from './export.js';
|
|
7
|
+
export * from './exportStore.js';
|
|
8
|
+
export * from './exportJob.js';
|
|
6
9
|
export const checkPassword = async (account, password) => compare(password, account.passwordHash);
|
package/dist/backups/index.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ export declare const extractZipArchive: (zipPath: string, tempDir: string) => {
|
|
|
9
9
|
promise: Promise<void>;
|
|
10
10
|
kill: () => void;
|
|
11
11
|
};
|
|
12
|
+
export declare const zipDirectory: (sourceDir: string, zipPath: string) => Promise<void>;
|
|
12
13
|
export declare const createBackup: () => Promise<string | undefined>;
|
|
13
14
|
export declare const downloadBackup: (name: string) => Promise<string>;
|
|
14
15
|
export declare const listAllBackups: () => Promise<string[]>;
|
package/dist/backups/index.js
CHANGED
|
@@ -94,7 +94,7 @@ const hostnameFromServerHost = (host) => {
|
|
|
94
94
|
const serverUrl = host.includes('://') ? host : `http://${host}`;
|
|
95
95
|
return new URL(serverUrl).hostname;
|
|
96
96
|
};
|
|
97
|
-
const zipDirectory = (sourceDir, zipPath) => new Promise((resolve, reject) => {
|
|
97
|
+
export const zipDirectory = (sourceDir, zipPath) => new Promise((resolve, reject) => {
|
|
98
98
|
const output = createWriteStream(zipPath);
|
|
99
99
|
const archive = new ZipArchive({ zlib: { level: 9 } });
|
|
100
100
|
output.on('close', () => resolve());
|
package/dist/config/index.d.ts
CHANGED
|
@@ -96,6 +96,102 @@ export declare const communityConfig: () => Promise<{
|
|
|
96
96
|
}[] | undefined;
|
|
97
97
|
} | undefined;
|
|
98
98
|
}>;
|
|
99
|
+
/**
|
|
100
|
+
* Reads the community config straight from the DB, bypassing the in-memory
|
|
101
|
+
* cache. Use for low-frequency worker-side reads where a missed pub/sub
|
|
102
|
+
* invalidation is not acceptable; the cached `config()` + `configUpdated`
|
|
103
|
+
* stays the default path.
|
|
104
|
+
*
|
|
105
|
+
* Currently used by the auto-follow designation read, which runs in the
|
|
106
|
+
* worker process, whose cache is only refreshed on a redis pub/sub
|
|
107
|
+
* `configUpdated` event that a worker connection can miss (connect timing,
|
|
108
|
+
* a redelivery gap, or a worker restart); a fresh read keeps the designated
|
|
109
|
+
* accounts on the settings the admin actually saved. Only that read is
|
|
110
|
+
* fresh: the same handler's `capabilitiesConfig` follow-eligibility check
|
|
111
|
+
* intentionally stays on the cached `config` path, so a future reader should
|
|
112
|
+
* not "fix" that read to be fresh without a behavior change.
|
|
113
|
+
*/
|
|
114
|
+
export declare const communityConfigFresh: () => Promise<{
|
|
115
|
+
theme: {
|
|
116
|
+
base: string;
|
|
117
|
+
light: {
|
|
118
|
+
primaryHex: string;
|
|
119
|
+
secondaryHex?: string | undefined;
|
|
120
|
+
fontFamily?: string | undefined;
|
|
121
|
+
buttonRadius?: string | undefined;
|
|
122
|
+
radius?: string | undefined;
|
|
123
|
+
logoSmall?: string | undefined;
|
|
124
|
+
defaultProfileAvatar?: string | undefined;
|
|
125
|
+
defaultGroupAvatar?: string | undefined;
|
|
126
|
+
backgroundAuth?: string | undefined;
|
|
127
|
+
background?: string | undefined;
|
|
128
|
+
};
|
|
129
|
+
dark: {
|
|
130
|
+
primaryHex: string;
|
|
131
|
+
secondaryHex?: string | undefined;
|
|
132
|
+
fontFamily?: string | undefined;
|
|
133
|
+
buttonRadius?: string | undefined;
|
|
134
|
+
radius?: string | undefined;
|
|
135
|
+
logoSmall?: string | undefined;
|
|
136
|
+
defaultProfileAvatar?: string | undefined;
|
|
137
|
+
defaultGroupAvatar?: string | undefined;
|
|
138
|
+
backgroundAuth?: string | undefined;
|
|
139
|
+
background?: string | undefined;
|
|
140
|
+
};
|
|
141
|
+
icon?: string | undefined;
|
|
142
|
+
mobileIcon?: string | undefined;
|
|
143
|
+
primaryHex?: string | undefined;
|
|
144
|
+
logoFull?: string | undefined;
|
|
145
|
+
logoSmall?: string | undefined;
|
|
146
|
+
defaultProfileAvatar?: string | undefined;
|
|
147
|
+
defaultGroupAvatar?: string | undefined;
|
|
148
|
+
backgroundAuth?: string | undefined;
|
|
149
|
+
background?: string | undefined;
|
|
150
|
+
};
|
|
151
|
+
info: {
|
|
152
|
+
name: string;
|
|
153
|
+
tagLine: string;
|
|
154
|
+
contactEmail?: string | undefined;
|
|
155
|
+
privacyPolicy?: string | undefined;
|
|
156
|
+
termsAndConditions?: string | undefined;
|
|
157
|
+
bugReportUrl?: string | undefined;
|
|
158
|
+
};
|
|
159
|
+
content: {
|
|
160
|
+
aboutPage?: string | undefined;
|
|
161
|
+
welcomePage?: string | undefined;
|
|
162
|
+
codeOfConduct?: string | undefined;
|
|
163
|
+
welcomeEmail?: string | undefined;
|
|
164
|
+
pinnedPost?: string | undefined;
|
|
165
|
+
autoFollow?: string[] | undefined;
|
|
166
|
+
allowedReactions?: string[] | undefined;
|
|
167
|
+
};
|
|
168
|
+
settings: {
|
|
169
|
+
openRegistrations: boolean;
|
|
170
|
+
defaultLanguage?: string | undefined;
|
|
171
|
+
defaultTimeZone?: string | undefined;
|
|
172
|
+
defaultFeedFormat?: "threaded" | "linear" | undefined;
|
|
173
|
+
indexProfiles?: boolean | undefined;
|
|
174
|
+
additionalForbiddenHandles?: string[] | undefined;
|
|
175
|
+
};
|
|
176
|
+
roles: {
|
|
177
|
+
onRegistration: {
|
|
178
|
+
add: string[];
|
|
179
|
+
remove: string[];
|
|
180
|
+
};
|
|
181
|
+
onEmailValidation: {
|
|
182
|
+
add: string[];
|
|
183
|
+
remove: string[];
|
|
184
|
+
};
|
|
185
|
+
};
|
|
186
|
+
profiles?: {
|
|
187
|
+
additionalFields?: {
|
|
188
|
+
key: string;
|
|
189
|
+
label: string;
|
|
190
|
+
icon?: string | undefined;
|
|
191
|
+
linkPattern?: string | undefined;
|
|
192
|
+
}[] | undefined;
|
|
193
|
+
} | undefined;
|
|
194
|
+
}>;
|
|
99
195
|
export declare const capabilitiesConfig: () => Promise<CapabilitiesConfig>;
|
|
100
196
|
export declare const sanitizedConfigWithDefaults: <T = CoreConfig>(namespace?: string, name?: string) => Promise<{
|
|
101
197
|
config: unknown;
|
package/dist/config/index.js
CHANGED
|
@@ -72,6 +72,22 @@ export const config = (namespace = 'openpeeps', name = 'core') => {
|
|
|
72
72
|
return configPromises.get(key);
|
|
73
73
|
};
|
|
74
74
|
export const communityConfig = () => config('openpeeps', 'community');
|
|
75
|
+
/**
|
|
76
|
+
* Reads the community config straight from the DB, bypassing the in-memory
|
|
77
|
+
* cache. Use for low-frequency worker-side reads where a missed pub/sub
|
|
78
|
+
* invalidation is not acceptable; the cached `config()` + `configUpdated`
|
|
79
|
+
* stays the default path.
|
|
80
|
+
*
|
|
81
|
+
* Currently used by the auto-follow designation read, which runs in the
|
|
82
|
+
* worker process, whose cache is only refreshed on a redis pub/sub
|
|
83
|
+
* `configUpdated` event that a worker connection can miss (connect timing,
|
|
84
|
+
* a redelivery gap, or a worker restart); a fresh read keeps the designated
|
|
85
|
+
* accounts on the settings the admin actually saved. Only that read is
|
|
86
|
+
* fresh: the same handler's `capabilitiesConfig` follow-eligibility check
|
|
87
|
+
* intentionally stays on the cached `config` path, so a future reader should
|
|
88
|
+
* not "fix" that read to be fresh without a behavior change.
|
|
89
|
+
*/
|
|
90
|
+
export const communityConfigFresh = () => initConfig('openpeeps', 'community');
|
|
75
91
|
export const capabilitiesConfig = () => config('openpeeps', 'capabilities').then((loaded) => ({
|
|
76
92
|
...loaded,
|
|
77
93
|
accessToken: deepmerge(defaultCapabilitiesConfig.accessToken ?? {}, loaded.accessToken ?? {}),
|
package/dist/media/index.d.ts
CHANGED
|
@@ -33,8 +33,8 @@ export declare const storeFromPath: (filePath: string) => Promise<{
|
|
|
33
33
|
}>;
|
|
34
34
|
/**
|
|
35
35
|
* Returns the on-disk file to store for the attachment plus its final
|
|
36
|
-
* filename. Videos are transcoded to
|
|
37
|
-
* else is stored as-is (the returned `path` is the input
|
|
36
|
+
* filename. Videos and non-AAC audio are transcoded to temp files (fresh
|
|
37
|
+
* paths); everything else is stored as-is (the returned `path` is the input).
|
|
38
38
|
*/
|
|
39
39
|
export declare const transcodeIncomingMedia: (type: string, inputPath: string, originalName: string, sourceMimetype: string) => Promise<MediaFile & {
|
|
40
40
|
filename: string;
|
package/dist/media/index.js
CHANGED
|
@@ -9,7 +9,7 @@ import { createReadStream, createWriteStream } from 'node:fs';
|
|
|
9
9
|
import { Readable } from 'node:stream';
|
|
10
10
|
import { pipeline } from 'node:stream/promises';
|
|
11
11
|
import { spawn } from 'node:child_process';
|
|
12
|
-
import { getTheme, randomString } from '@openpeepshq/common/lib';
|
|
12
|
+
import { getTheme, randomString, VOICE_NOTE_MAX_SECONDS, } from '@openpeepshq/common/lib';
|
|
13
13
|
import { logger } from '../log/index.js';
|
|
14
14
|
import { hub } from '../events/index.js';
|
|
15
15
|
let storagePromise = null;
|
|
@@ -63,9 +63,41 @@ export const writeStorageToTemp = async (storageId, name) => {
|
|
|
63
63
|
};
|
|
64
64
|
/** Content-address and store a file by streaming it from disk. */
|
|
65
65
|
export const storeFromPath = (filePath) => mediaStorage().then((storage) => storage.storeStream(Readable.toWeb(createReadStream(filePath))));
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
66
|
+
/**
|
|
67
|
+
* Normalizes any audio upload to MP4/AAC in a temp `.m4a` (a fresh path).
|
|
68
|
+
* Browsers record webm/ogg, which iOS cannot decode; AAC-in-MP4 plays on
|
|
69
|
+
* every client, so the uploaded format is never what ships.
|
|
70
|
+
*/
|
|
71
|
+
const transcodeAudio = (inputPath) => {
|
|
72
|
+
const tempOutputPath = join(tmpdir(), `output-${randomString(16)}.m4a`);
|
|
73
|
+
return new Promise((resolve, reject) => {
|
|
74
|
+
ffmpeg(inputPath)
|
|
75
|
+
.noVideo()
|
|
76
|
+
.outputOptions('-c:a aac')
|
|
77
|
+
.outputOptions('-b:a 128k')
|
|
78
|
+
.output(tempOutputPath)
|
|
79
|
+
.on('end', () => resolve(tempOutputPath))
|
|
80
|
+
.on('error', (error) => reject(new Error(`Audio transcode failed: ${error}`)))
|
|
81
|
+
.run();
|
|
82
|
+
});
|
|
83
|
+
};
|
|
84
|
+
/**
|
|
85
|
+
* Probes a file's duration in seconds via ffprobe. Throws `MediaContentError`
|
|
86
|
+
* when the duration cannot be determined, so an unprobeable file fails closed
|
|
87
|
+
* as a 400 in the sync upload path (the handler maps `MediaContentError` to
|
|
88
|
+
* `badRequest`), not as an opaque 500.
|
|
89
|
+
*/
|
|
90
|
+
const probeAudioDuration = (inputPath) => new Promise((resolve, reject) => {
|
|
91
|
+
ffmpeg.ffprobe(inputPath, (err, metadata) => {
|
|
92
|
+
const duration = metadata?.format?.duration;
|
|
93
|
+
if (err || !duration) {
|
|
94
|
+
reject(new MediaContentError(`Could not probe audio duration: ${err || 'no duration in metadata'}`));
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
resolve(duration);
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
const transcodeVideo = (inputPath, isLargeFile) => {
|
|
69
101
|
const tempOutputPath = join(tmpdir(), `output-${randomString(16)}.mp4`);
|
|
70
102
|
const baseOutput = [
|
|
71
103
|
'-c:v h264', // Better for iOS hardware acceleration
|
|
@@ -94,17 +126,54 @@ const transcodeVideo = async (inputPath) => {
|
|
|
94
126
|
};
|
|
95
127
|
/**
|
|
96
128
|
* Returns the on-disk file to store for the attachment plus its final
|
|
97
|
-
* filename. Videos are transcoded to
|
|
98
|
-
* else is stored as-is (the returned `path` is the input
|
|
129
|
+
* filename. Videos and non-AAC audio are transcoded to temp files (fresh
|
|
130
|
+
* paths); everything else is stored as-is (the returned `path` is the input).
|
|
99
131
|
*/
|
|
132
|
+
// Container + codec every client can decode: MP4/AAC is native on iOS and
|
|
133
|
+
// Android (react-native-sound) and playable by every browser. Browsers
|
|
134
|
+
// cannot record it directly, so webm/ogg uploads are normalized here. MP3
|
|
135
|
+
// (audio/mpeg) is normalized too: react-native-sound on iOS does not
|
|
136
|
+
// guarantee MP3 playback, so a picked MP3 would be silent on iOS even though
|
|
137
|
+
// it plays everywhere else.
|
|
100
138
|
export const transcodeIncomingMedia = async (type, inputPath, originalName, sourceMimetype) => {
|
|
101
139
|
if (type === 'video') {
|
|
140
|
+
const { size } = await fs.stat(inputPath);
|
|
141
|
+
const isLargeFile = size > 10 * 1024 * 1024;
|
|
102
142
|
return {
|
|
103
|
-
path: await transcodeVideo(inputPath),
|
|
143
|
+
path: await transcodeVideo(inputPath, isLargeFile),
|
|
104
144
|
filename: path.parse(originalName).name + '.mp4',
|
|
105
145
|
mimetype: 'video/mp4',
|
|
106
146
|
};
|
|
107
147
|
}
|
|
148
|
+
if (type === 'audio') {
|
|
149
|
+
// The voice-note cap is a single source of truth in common; the server
|
|
150
|
+
// enforces it too so a crafted upload cannot bypass the client cap.
|
|
151
|
+
//
|
|
152
|
+
// Boundary: `>` (not `>=`) — the recorders auto-stop at
|
|
153
|
+
// `VOICE_NOTE_AUTO_STOP_SECONDS` (half a second under the cap) so an
|
|
154
|
+
// honest take's probed duration lands strictly under 90 s, while a
|
|
155
|
+
// genuinely-overshot or crafted upload (≥ 90.5 s) probes at/above it.
|
|
156
|
+
// See the `VOICE_NOTE_MAX_SECONDS` docs.
|
|
157
|
+
const duration = await probeAudioDuration(inputPath);
|
|
158
|
+
if (duration > VOICE_NOTE_MAX_SECONDS) {
|
|
159
|
+
throw new MediaContentError(`Audio exceeds the ${VOICE_NOTE_MAX_SECONDS}s voice-note limit.`);
|
|
160
|
+
}
|
|
161
|
+
if (!['audio/mp4', 'audio/aac'].includes(sourceMimetype)) {
|
|
162
|
+
return {
|
|
163
|
+
path: await transcodeAudio(inputPath),
|
|
164
|
+
filename: path.parse(originalName).name + '.m4a',
|
|
165
|
+
mimetype: 'audio/mp4',
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
// Pass-through trade-off (round-17 item 2): `audio/mp4` and `audio/aac`
|
|
169
|
+
// are trusted by their reported/derived mimetype without re-probing
|
|
170
|
+
// container semantics. A video file renamed to `.mp4` but reported as
|
|
171
|
+
// `audio/mp4` would therefore be stored as an audio attachment with a
|
|
172
|
+
// video payload. The realistic exposure is small — the RN picker filters
|
|
173
|
+
// to audio and web's file input only accepts `audio/*` — so this is a
|
|
174
|
+
// documented trade rather than a byte-level container check (which would
|
|
175
|
+
// need full `mvhd`/`stsd` parsing, not just header sniffing).
|
|
176
|
+
}
|
|
108
177
|
return { path: inputPath, filename: originalName, mimetype: sourceMimetype };
|
|
109
178
|
};
|
|
110
179
|
export const createPreview = async (inputPath, mimetype, originalName) => {
|
|
@@ -1,4 +1,20 @@
|
|
|
1
1
|
import type { MediaAttachment } from '@openpeepshq/common/types';
|
|
2
|
+
/**
|
|
3
|
+
* Uploads smaller than this are processed synchronously in the request (the
|
|
4
|
+
* client gets the final attachment, or a 400 if processing rejects it); larger
|
|
5
|
+
* uploads go to the worker and the client is told "processing" first.
|
|
6
|
+
*
|
|
7
|
+
* Voice-note cap interaction: the server-side 90 s cap (VOICE_NOTE_MAX_SECONDS,
|
|
8
|
+
* enforced in `transcodeIncomingMedia`) only reaches the client as a
|
|
9
|
+
* fail-closed 400 on this sync path — a bigger upload bypasses the cap until
|
|
10
|
+
* the worker runs, after the client has already been told the attachment
|
|
11
|
+
* succeeded. The threshold must therefore stay above a realistic 90 s
|
|
12
|
+
* voice note so recorded notes take the sync path and the cap can reject them:
|
|
13
|
+
* a web note recorded at a low bitrate (opus, ~0.4 MB) is well under, and a
|
|
14
|
+
* high-bitrate AAC take (~128 kbps, ~1.4 MB) is only marginally above. Lowering
|
|
15
|
+
* this threshold toward typical note sizes would silently weaken that
|
|
16
|
+
* guarantee, so a change here is not a routine tuning.
|
|
17
|
+
*/
|
|
2
18
|
export declare const SYNC_PROCESSING_LIMIT: number;
|
|
3
19
|
export interface RunProcessingInput {
|
|
4
20
|
mediaAttachmentId: string;
|
package/dist/media/processing.js
CHANGED
|
@@ -5,6 +5,22 @@ import { logger } from '../log/index.js';
|
|
|
5
5
|
import { withSpan } from '../performance/index.js';
|
|
6
6
|
import { mediaStorage, transcodeIncomingMedia, createPreview, storeFromPath, writeStorageToTemp, writeStreamToTemp, } from './index.js';
|
|
7
7
|
const log = logger('app:media:processing');
|
|
8
|
+
/**
|
|
9
|
+
* Uploads smaller than this are processed synchronously in the request (the
|
|
10
|
+
* client gets the final attachment, or a 400 if processing rejects it); larger
|
|
11
|
+
* uploads go to the worker and the client is told "processing" first.
|
|
12
|
+
*
|
|
13
|
+
* Voice-note cap interaction: the server-side 90 s cap (VOICE_NOTE_MAX_SECONDS,
|
|
14
|
+
* enforced in `transcodeIncomingMedia`) only reaches the client as a
|
|
15
|
+
* fail-closed 400 on this sync path — a bigger upload bypasses the cap until
|
|
16
|
+
* the worker runs, after the client has already been told the attachment
|
|
17
|
+
* succeeded. The threshold must therefore stay above a realistic 90 s
|
|
18
|
+
* voice note so recorded notes take the sync path and the cap can reject them:
|
|
19
|
+
* a web note recorded at a low bitrate (opus, ~0.4 MB) is well under, and a
|
|
20
|
+
* high-bitrate AAC take (~128 kbps, ~1.4 MB) is only marginally above. Lowering
|
|
21
|
+
* this threshold toward typical note sizes would silently weaken that
|
|
22
|
+
* guarantee, so a change here is not a routine tuning.
|
|
23
|
+
*/
|
|
8
24
|
export const SYNC_PROCESSING_LIMIT = Number(process.env.MEDIA_SYNC_PROCESSING_LIMIT || 1024 * 1024);
|
|
9
25
|
/**
|
|
10
26
|
* Transcode + generate a preview for an attachment, working entirely with
|
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { communityConfigFresh } from '../config/index.js';
|
|
2
|
+
import { logger } from '../log/index.js';
|
|
2
3
|
import { hub } from '../events/index.js';
|
|
3
4
|
import { getProfile } from './cache.js';
|
|
4
5
|
import { followDesignatedProfiles } from './mutations.js';
|
|
6
|
+
const log = logger('app:profiles:autoFollow');
|
|
5
7
|
const handleProfileCreated = async (profileArg) => {
|
|
6
8
|
const profile = profileArg;
|
|
7
9
|
if (!profile?.id)
|
|
@@ -11,10 +13,26 @@ const handleProfileCreated = async (profileArg) => {
|
|
|
11
13
|
const fresh = await getProfile(profile.id);
|
|
12
14
|
if (!fresh)
|
|
13
15
|
return;
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
// Read the community config fresh from the DB rather than through the
|
|
17
|
+
// in-memory cache: this handler runs in the worker process, whose cache is
|
|
18
|
+
// only refreshed on a redis pub/sub `configUpdated` event that a worker
|
|
19
|
+
// connection can miss. A stale cache left empty/old `content.autoFollow`
|
|
20
|
+
// would silently skip the designated follows after an admin saved them.
|
|
21
|
+
try {
|
|
22
|
+
const autoFollow = (await communityConfigFresh()).content.autoFollow;
|
|
23
|
+
if (!autoFollow?.length)
|
|
24
|
+
return;
|
|
25
|
+
await followDesignatedProfiles(fresh, autoFollow);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
// Re-throw so the once-queue job fails; it stays retained for diagnosis
|
|
29
|
+
// (30-day removeOnFail age) with its failedReason — the queue sets no
|
|
30
|
+
// attempts, so no retry is scheduled. The worker's last-five-errors table
|
|
31
|
+
// prints only the raw failedReason (no profile id), so the handler-level
|
|
32
|
+
// log line is what makes the failed profile identifiable.
|
|
33
|
+
log.error(`auto-follow handler failed for profile ${profile.id}`, error);
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
18
36
|
};
|
|
19
37
|
let registered = false;
|
|
20
38
|
/** Subscribes the designated-account follows to profileCreated (once queue). */
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openpeepshq/core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.15.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"license": "GPL-3.0-or-later",
|
|
6
6
|
"dependencies": {
|
|
@@ -37,10 +37,10 @@
|
|
|
37
37
|
"type-fest": "^4.31.0",
|
|
38
38
|
"uuidv7": "^1.0.2",
|
|
39
39
|
"web-push": "^3.6.7",
|
|
40
|
-
"@openpeepshq/common": "0.
|
|
40
|
+
"@openpeepshq/common": "0.16.0",
|
|
41
41
|
"@openpeepshq/fetch-client": "^0.2.1",
|
|
42
|
-
"@openpeepshq/
|
|
43
|
-
"@openpeepshq/
|
|
42
|
+
"@openpeepshq/geocoder": "^0.1.2",
|
|
43
|
+
"@openpeepshq/i18n": "^0.17.0"
|
|
44
44
|
},
|
|
45
45
|
"main": "dist/index.js",
|
|
46
46
|
"types": "dist/index.d.ts",
|