@lupinum/ginko-server 0.0.0-stage → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +21 -0
  3. package/README.md +176 -2
  4. package/convex/_generated/api.d.ts +185 -0
  5. package/convex/_generated/api.js +23 -0
  6. package/convex/_generated/dataModel.d.ts +60 -0
  7. package/convex/_generated/server.d.ts +162 -0
  8. package/convex/_generated/server.js +101 -0
  9. package/convex/account.ts +110 -0
  10. package/convex/agent.ts +814 -0
  11. package/convex/auth.config.ts +4 -0
  12. package/convex/auth.ts +62 -0
  13. package/convex/backup.ts +94 -0
  14. package/convex/betterAuth/_generated/api.ts +56 -0
  15. package/convex/betterAuth/_generated/component.ts +431 -0
  16. package/convex/betterAuth/_generated/dataModel.ts +60 -0
  17. package/convex/betterAuth/_generated/server.ts +169 -0
  18. package/convex/betterAuth/adapter.ts +7 -0
  19. package/convex/betterAuth/convex.config.ts +3 -0
  20. package/convex/betterAuth/schema.ts +102 -0
  21. package/convex/betterAuth/schemaMetadata.ts +697 -0
  22. package/convex/betterAuth/schemaOptions.ts +13 -0
  23. package/convex/betterAuth/schemaPlugins.ts +13 -0
  24. package/convex/bundle.ts +183 -0
  25. package/convex/changes.ts +136 -0
  26. package/convex/cleanup.ts +44 -0
  27. package/convex/connect.ts +143 -0
  28. package/convex/convex.config.ts +7 -0
  29. package/convex/crons.ts +14 -0
  30. package/convex/demo.ts +72 -0
  31. package/convex/entries.ts +1770 -0
  32. package/convex/facts.ts +129 -0
  33. package/convex/files.ts +631 -0
  34. package/convex/http.ts +21 -0
  35. package/convex/image.ts +45 -0
  36. package/convex/images.ts +54 -0
  37. package/convex/invites.ts +227 -0
  38. package/convex/lib/access.ts +180 -0
  39. package/convex/lib/agentTools.ts +331 -0
  40. package/convex/lib/content.ts +317 -0
  41. package/convex/lib/corpus.ts +83 -0
  42. package/convex/lib/diff.ts +50 -0
  43. package/convex/lib/fail.ts +27 -0
  44. package/convex/lib/files.ts +70 -0
  45. package/convex/lib/history.ts +103 -0
  46. package/convex/lib/i18n.ts +52 -0
  47. package/convex/lib/input.ts +57 -0
  48. package/convex/lib/library.ts +28 -0
  49. package/convex/lib/lifecycle.ts +100 -0
  50. package/convex/lib/list.ts +112 -0
  51. package/convex/lib/migrations.ts +126 -0
  52. package/convex/lib/names.ts +56 -0
  53. package/convex/lib/pending.ts +84 -0
  54. package/convex/lib/policy.ts +155 -0
  55. package/convex/lib/publicness.ts +87 -0
  56. package/convex/lib/reminders.ts +27 -0
  57. package/convex/lib/search.ts +132 -0
  58. package/convex/lib/siteUrl.ts +95 -0
  59. package/convex/lib/status.ts +109 -0
  60. package/convex/lib/translation.ts +56 -0
  61. package/convex/lib/trees.ts +43 -0
  62. package/convex/lib/write.ts +296 -0
  63. package/convex/mail.ts +136 -0
  64. package/convex/members.ts +129 -0
  65. package/convex/migrations.ts +105 -0
  66. package/convex/navigation.ts +276 -0
  67. package/convex/ops.ts +50 -0
  68. package/convex/proposals.ts +753 -0
  69. package/convex/refresh.ts +163 -0
  70. package/convex/release.ts +435 -0
  71. package/convex/reminders.ts +116 -0
  72. package/convex/retention.ts +121 -0
  73. package/convex/routes/bundle.ts +62 -0
  74. package/convex/routes/connect.ts +80 -0
  75. package/convex/routes/export.ts +23 -0
  76. package/convex/routes/file.ts +34 -0
  77. package/convex/routes/key.ts +53 -0
  78. package/convex/routes/mcp.ts +300 -0
  79. package/convex/routes/release.ts +66 -0
  80. package/convex/routes/upload.ts +94 -0
  81. package/convex/schema.ts +443 -0
  82. package/convex/search.ts +58 -0
  83. package/convex/seed.ts +624 -0
  84. package/convex/siteDeletion.ts +78 -0
  85. package/convex/sites.ts +393 -0
  86. package/convex/tasks.ts +51 -0
  87. package/convex/tsconfig.json +27 -0
  88. package/convex/uploads.ts +429 -0
  89. package/convex/uploadsNode.ts +86 -0
  90. package/convex/views.ts +111 -0
  91. package/i18n/de.json +364 -0
  92. package/i18n/en.json +364 -0
  93. package/i18n/es.json +364 -0
  94. package/i18n/fr.json +364 -0
  95. package/package.json +45 -3
@@ -0,0 +1,429 @@
1
+ // Uploads (SPEC 3, 4.3, 12): the rows of files that fields point to, their processing state,
2
+ // the read path for members of the site, and the daily sweep. A member gets a one-time ticket
3
+ // (prepare); the HTTP route routes/upload.ts redeems it, stores the file and registers it for that
4
+ // member and site; uploadsNode.ts checks the content and processes images (Node runtime).
5
+ import { v } from 'convex/values'
6
+ import { internal } from './_generated/api'
7
+ import { sha256 } from '@lupinum/ginko/internal'
8
+ import type { Doc, Id } from './_generated/dataModel'
9
+ import { internalMutation, internalQuery, mutation, query, type MutationCtx } from './_generated/server'
10
+ import { windowOf } from './bundle'
11
+ import { actorFor, fail, type Actor } from './lib/access'
12
+ import { cleanName } from './lib/files'
13
+ import { t, type MessageKey } from './lib/i18n'
14
+ import { deleteStorage, isKeptUpload, purgeUpload } from './lib/library'
15
+
16
+ const DAY = 24 * 60 * 60 * 1000
17
+ export const MAX_ATTEMPTS = 3
18
+ const RETRY_MS = 30_000
19
+ /** Longer than an action may run (10 minutes): a `processing` row this far past its run has lost it. */
20
+ export const STALE_MS = 15 * 60 * 1000
21
+ /** Gap between the runs a retry schedules, so many re-queued files do not write at the same moment. */
22
+ const RETRY_STAGGER_MS = 2000
23
+ /** Wait before queued revision bumps are applied, so one import raises contentRev once. */
24
+ const REV_BUMP_MS = 3_000
25
+
26
+ const TICKET_MS = 10 * 60 * 1000
27
+ /** Upload tickets per person, site and hour. A busy editor uploads a few dozen files; this bounds what a script or a stolen session stores. */
28
+ export const UPLOAD_LIMIT = 200
29
+
30
+ /** Counts one ticket in the person's current hour on this site, or refuses the one over the limit. Platform admins are not counted, as for invites. */
31
+ async function countUpload(ctx: MutationCtx, actor: Actor) {
32
+ if (actor.role === 'admin') return
33
+ const site = actor.site._id
34
+ const user = actor.user.id
35
+ const hour = Math.floor(windowOf(Date.now()) / 60) * 60
36
+ const row = await ctx.db.query('rateWindows').withIndex('by_site_kind_window', (q) => q.eq('site', site).eq('kind', 'upload').eq('window', hour).eq('user', user)).unique()
37
+ if (row && row.count >= UPLOAD_LIMIT) fail('RATE_LIMITED', 'errors.tooManyUploads')
38
+ if (row) await ctx.db.patch(row._id, { count: row.count + 1 })
39
+ else await ctx.db.insert('rateWindows', { site, kind: 'upload', user, window: hour, count: 1 })
40
+ }
41
+
42
+ /** 32 random bytes, base64url without padding. */
43
+ function newToken(): string {
44
+ const bytes = crypto.getRandomValues(new Uint8Array(32))
45
+ return btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
46
+ }
47
+
48
+ /**
49
+ * Step 1 (SPEC 4.3): a member gets a ticket for one upload to this site, valid 10 minutes. The
50
+ * browser sends the file with it to POST /upload; the route stores the file itself, so a stored file
51
+ * belongs to its ticket's member and site from the start and can never be claimed by anyone else.
52
+ */
53
+ export const prepare = mutation({
54
+ args: { site: v.string(), folder: v.optional(v.string()), library: v.optional(v.boolean()) },
55
+ handler: async (ctx, { site, folder, library }) => ({ ticket: await ticketFor(ctx, await actorFor(ctx, site), { folder, library }) }),
56
+ })
57
+
58
+ /** A one-time upload ticket for this person and site (`prepare`, and the agent door's ginko_upload). Counts toward UPLOAD_LIMIT. */
59
+ export async function ticketFor(ctx: MutationCtx, actor: Actor, { folder, library }: { folder?: string; library?: boolean }): Promise<string> {
60
+ // A folder of another site looks like a missing one (SPEC 4.3).
61
+ const folderId = folder === undefined ? null : ctx.db.normalizeId('folders', folder)
62
+ const row = folderId ? await ctx.db.get(folderId) : null
63
+ if (folder !== undefined && (!row || row.site !== actor.site._id)) fail('NOT_FOUND', 'errors.folderNotFound')
64
+ await countUpload(ctx, actor)
65
+ const ticket = newToken()
66
+ await ctx.db.insert('uploadTickets', {
67
+ tokenHash: sha256(ticket), site: actor.site._id, user: actor.user.id, expiresAt: Date.now() + TICKET_MS,
68
+ ...(row ? { folder: row._id } : {}), ...(library ? { library: true } : {}),
69
+ })
70
+ return ticket
71
+ }
72
+
73
+ /** The route's first step: a valid ticket is used up and names the site and member; anything else is null. */
74
+ export const redeem = internalMutation({
75
+ args: { ticket: v.string() },
76
+ handler: async (ctx, { ticket }) => {
77
+ const row = await ctx.db.query('uploadTickets').withIndex('by_tokenHash', (q) => q.eq('tokenHash', sha256(ticket))).unique()
78
+ if (!row) return null
79
+ await ctx.db.delete(row._id)
80
+ if (row.expiresAt <= Date.now()) return null
81
+ // The ticket outlives no membership: a member removed since then cannot upload.
82
+ const site = await ctx.db.get(row.site)
83
+ const member = await ctx.db.query('memberships').withIndex('by_user_site', (q) => q.eq('user', row.user).eq('site', row.site)).unique()
84
+ const admin = await ctx.db.query('admins').withIndex('by_user', (q) => q.eq('user', row.user)).unique()
85
+ if (!site || site.deleting || (!member && !admin)) return null
86
+ // A folder deleted since the ticket was made is dropped; the file is still a library file.
87
+ const folder = row.folder && await ctx.db.get(row.folder) ? row.folder : undefined
88
+ return { site: row.site, user: row.user, ...(folder ? { folder } : {}), ...(row.library || row.folder ? { library: true } : {}) }
89
+ },
90
+ })
91
+
92
+ /** Records a file the route stored. It stays `processing` until uploadsNode has checked (and for images processed) it. */
93
+ export const register = internalMutation({
94
+ args: {
95
+ site: v.id('sites'), uploader: v.string(), storageId: v.id('_storage'), name: v.string(), size: v.number(), mime: v.string(),
96
+ folder: v.optional(v.id('folders')), library: v.optional(v.boolean()),
97
+ },
98
+ handler: async (ctx, { library, ...args }) => {
99
+ // A long name is shortened by cleanName (extension kept); only a missing one is refused.
100
+ const given = args.name.trim()
101
+ if (!given) fail('INVALID', 'errors.fileNameInvalid')
102
+ // A library upload, or one put straight into a folder, is kept: the 7-day sweep leaves it alone.
103
+ const id = await ctx.db.insert('uploads', { ...args, name: cleanName(given), attempts: 0, status: 'processing', kept: !!(library || args.folder) })
104
+ await ctx.scheduler.runAfter(0, internal.uploadsNode.run, { upload: id })
105
+ return id
106
+ },
107
+ })
108
+
109
+ /**
110
+ * A file that entries already name (an import writes the entries before their files are processed) reaches the site
111
+ * only now: contentRev rises like after a save, so a site's cache fetches the content again.
112
+ */
113
+ async function showWhereUsed(ctx: MutationCtx, row: Doc<'uploads'>) {
114
+ const used = await ctx.db.query('fileRefs').withIndex('by_file', (q) => q.eq('file', row._id)).filter((q) => q.eq(q.field('holder'), 'entry')).first()
115
+ if (!used) return
116
+ // Only a new row, not the shared site document: hundreds of uploads finishing at once would otherwise conflict on it.
117
+ await ctx.db.insert('revBumps', { site: row.site })
118
+ await ctx.scheduler.runAfter(REV_BUMP_MS, internal.uploads.applyRevBumps, { site: row.site })
119
+ }
120
+
121
+ /** Raises contentRev once for all bumps that finished uploads queued since the last run. Later runs find nothing and return. */
122
+ export const applyRevBumps = internalMutation({
123
+ args: { site: v.id('sites') },
124
+ handler: async (ctx, { site }) => {
125
+ const bumps = await ctx.db.query('revBumps').withIndex('by_site', (q) => q.eq('site', site)).collect()
126
+ if (bumps.length === 0) return
127
+ for (const bump of bumps) await ctx.db.delete(bump._id)
128
+ const row = await ctx.db.get(site)
129
+ if (row) await ctx.db.patch(site, { contentRev: row.contentRev + 1 })
130
+ },
131
+ })
132
+
133
+ /** A PDF whose content checked out is ready as stored; nothing is processed or removed. Repeats are no-ops. */
134
+ export const markFileReady = internalMutation({
135
+ args: { upload: v.id('uploads'), sha256: v.optional(v.string()) },
136
+ handler: async (ctx, { upload, sha256 }) => {
137
+ const row = await ctx.db.get(upload)
138
+ if (!row || row.status !== 'processing') return false
139
+ await ctx.db.patch(upload, { status: 'ready', processedId: row.storageId, ...(sha256 ? { sha256 } : {}) })
140
+ await showWhereUsed(ctx, row)
141
+ return true
142
+ },
143
+ })
144
+
145
+ /** Stores variants made later (backfill). Only while the row still has the same processed file and no variants; otherwise false. */
146
+ export const setVariants = internalMutation({
147
+ args: { upload: v.id('uploads'), processedId: v.id('_storage'), variants: v.array(v.object({ width: v.number(), storageId: v.id('_storage') })) },
148
+ handler: async (ctx, { upload, processedId, variants }) => {
149
+ const row = await ctx.db.get(upload)
150
+ if (!row || row.status !== 'ready' || row.processedId !== processedId || row.variants !== undefined) return false
151
+ await ctx.db.patch(upload, { variants })
152
+ return true
153
+ },
154
+ })
155
+
156
+ /** One page of ready image uploads; `todo` are those without variants (never processed for them). */
157
+ export const variantsTodo = internalQuery({
158
+ args: { cursor: v.union(v.string(), v.null()), numItems: v.number() },
159
+ handler: async (ctx, { cursor, numItems }) => {
160
+ const page = await ctx.db.query('uploads').withIndex('by_status', (q) => q.eq('status', 'ready')).paginate({ numItems, cursor })
161
+ const todo = page.page.filter((r) => r.mime.startsWith('image/') && r.variants === undefined && r.processedId).map((r) => ({ upload: r._id, processedId: r.processedId! }))
162
+ return { todo, next: page.isDone ? null : page.continueCursor }
163
+ },
164
+ })
165
+
166
+ export const load = internalQuery({
167
+ args: { upload: v.id('uploads') },
168
+ handler: (ctx, { upload }) => ctx.db.get(upload),
169
+ })
170
+
171
+ /** Writes the processed file, its size and dimensions and `ready`, then plans the removal of the original. Repeats are no-ops. */
172
+ export const markReady = internalMutation({
173
+ args: {
174
+ upload: v.id('uploads'),
175
+ processedId: v.id('_storage'),
176
+ size: v.number(),
177
+ width: v.number(),
178
+ height: v.number(),
179
+ /** SHA-256 (hex) of the original bytes. */
180
+ sha256: v.optional(v.string()),
181
+ variants: v.optional(v.array(v.object({ width: v.number(), storageId: v.id('_storage') }))),
182
+ },
183
+ handler: async (ctx, args) => {
184
+ const row = await ctx.db.get(args.upload)
185
+ if (!row || row.status !== 'processing') return false
186
+ await ctx.db.patch(row._id, { processedId: args.processedId, size: args.size, width: args.width, height: args.height, status: 'ready', ...(args.variants ? { variants: args.variants } : {}), ...(args.sha256 ? { sha256: args.sha256 } : {}) })
187
+ await ctx.scheduler.runAfter(0, internal.uploads.dropFile, { storageId: row.storageId })
188
+ await showWhereUsed(ctx, row)
189
+ return true
190
+ },
191
+ })
192
+
193
+ /** Counts a failed attempt. Permanent failures and the third attempt end in `failed`; others retry later. */
194
+ export const markFailed = internalMutation({
195
+ args: { upload: v.id('uploads'), key: v.string(), permanent: v.boolean() },
196
+ handler: async (ctx, args) => {
197
+ const row = await ctx.db.get(args.upload)
198
+ if (!row || row.status !== 'processing') return
199
+ await retryOrFail(ctx, row, args.key, args.permanent)
200
+ },
201
+ })
202
+
203
+ async function retryOrFail(ctx: MutationCtx, row: Doc<'uploads'>, key: string, permanent: boolean) {
204
+ const attempts = row.attempts + 1
205
+ if (permanent || attempts >= MAX_ATTEMPTS) {
206
+ await ctx.db.patch(row._id, { status: 'failed', attempts, error: key })
207
+ return
208
+ }
209
+ await ctx.db.patch(row._id, { attempts, error: key, runAt: Date.now() + RETRY_MS * attempts })
210
+ await ctx.scheduler.runAfter(RETRY_MS * attempts, internal.uploadsNode.run, { upload: row._id })
211
+ }
212
+
213
+ /**
214
+ * Cron: a `processing` row whose run is long overdue lost it (the action crashed, timed out or failed to write its
215
+ * result); it would otherwise wait for the sweep. It counts as a failed attempt, so a file that always crashes the run
216
+ * ends in `failed` after MAX_ATTEMPTS.
217
+ */
218
+ export const requeueStale = internalMutation({
219
+ args: {},
220
+ handler: async (ctx) => {
221
+ const before = Date.now() - STALE_MS
222
+ const rows = await ctx.db.query('uploads').withIndex('by_status', (q) => q.eq('status', 'processing').lt('_creationTime', before)).take(500)
223
+ let queued = 0
224
+ for (const row of rows) {
225
+ if ((row.runAt ?? row._creationTime) >= before) continue
226
+ await retryOrFail(ctx, row, 'errors.uploadRetrying', false)
227
+ queued++
228
+ }
229
+ if (queued) console.log(`uploads.requeueStale: ${queued} stuck upload(s) queued again`)
230
+ return queued
231
+ },
232
+ })
233
+
234
+ /** A `processing` row far past its due run (requeueStale picks these up every 10 minutes). */
235
+ export const isStale = (row: Doc<'uploads'>, now: number) => row.status === 'processing' && (row.runAt ?? row._creationTime) < now - STALE_MS
236
+
237
+ /**
238
+ * Puts these uploads back to `processing` with a fresh attempt count and schedules their run, 2 s apart.
239
+ * A row whose stored original is gone cannot be processed again: it is listed as `missing` and left as it is.
240
+ */
241
+ async function requeue(ctx: MutationCtx, rows: Doc<'uploads'>[], dryRun: boolean) {
242
+ const ids: Id<'uploads'>[] = []
243
+ const missing: Id<'uploads'>[] = []
244
+ for (const row of rows) {
245
+ if (!(await ctx.db.system.get(row.storageId))) {
246
+ missing.push(row._id)
247
+ continue
248
+ }
249
+ if (!dryRun) {
250
+ const delay = ids.length * RETRY_STAGGER_MS
251
+ await ctx.db.patch(row._id, { status: 'processing', attempts: 0, error: undefined, runAt: Date.now() + delay })
252
+ await ctx.scheduler.runAfter(delay, internal.uploadsNode.run, { upload: row._id })
253
+ }
254
+ ids.push(row._id)
255
+ }
256
+ return { count: ids.length, ids, missing }
257
+ }
258
+
259
+ /**
260
+ * Operator repair (internal, `convex run uploads:retry`): re-queues the `failed` and stuck `processing` uploads of one
261
+ * site (`site` slug), of the given `ids`, or of every site when both are left out. A dry run (the default) only lists them.
262
+ */
263
+ export const retry = internalMutation({
264
+ args: { site: v.optional(v.string()), ids: v.optional(v.array(v.id('uploads'))), dryRun: v.optional(v.boolean()) },
265
+ handler: async (ctx, { site, ids, dryRun }) => {
266
+ const now = Date.now()
267
+ const siteRow = site === undefined ? null : await ctx.db.query('sites').withIndex('by_slug', (q) => q.eq('slug', site)).unique()
268
+ if (site !== undefined && !siteRow) fail('NOT_FOUND', 'errors.siteNotFound')
269
+ const rows: Doc<'uploads'>[] = []
270
+ if (ids) {
271
+ for (const id of ids) {
272
+ const row = await ctx.db.get(id)
273
+ if (row && (!siteRow || row.site === siteRow._id)) rows.push(row)
274
+ }
275
+ } else {
276
+ for (const status of ['failed', 'processing'] as const) {
277
+ rows.push(...await ctx.db.query('uploads').withIndex('by_status', (q) => q.eq('status', status)).collect())
278
+ }
279
+ }
280
+ const matching = rows.filter((row) => (!siteRow || row.site === siteRow._id) && (row.status === 'failed' || isStale(row, now)))
281
+ return requeue(ctx, matching, dryRun ?? true)
282
+ },
283
+ })
284
+
285
+ /** Studio (Files, Problems): a member re-queues one failed upload of their site. Another site's upload is NOT_FOUND, like everywhere else. */
286
+ export const retryOne = mutation({
287
+ args: { site: v.string(), upload: v.string() },
288
+ handler: async (ctx, { site, upload }) => {
289
+ const actor = await actorFor(ctx, site)
290
+ const id = ctx.db.normalizeId('uploads', upload)
291
+ const row = id ? await ctx.db.get(id) : null
292
+ if (!row || row.site !== actor.site._id) fail('NOT_FOUND', 'errors.fileNotFound')
293
+ if (row.status !== 'failed') return { queued: false as const }
294
+ const { count } = await requeue(ctx, [row], false)
295
+ // The original is gone: nothing to process again.
296
+ if (!count) fail('NOT_FOUND', 'errors.fileNotFound')
297
+ return { queued: true as const }
298
+ },
299
+ })
300
+
301
+ export const dropFile = internalMutation({
302
+ args: { storageId: v.id('_storage') },
303
+ handler: (ctx, { storageId }) => deleteStorage(ctx, storageId),
304
+ })
305
+
306
+ /** Read path for the uploader's site: status and, once ready, the public URL. Other sites get NOT_FOUND. */
307
+ export const get = query({
308
+ args: { site: v.string(), upload: v.string() },
309
+ handler: async (ctx, { site, upload }) => {
310
+ const actor = await actorFor(ctx, site)
311
+ const id = ctx.db.normalizeId('uploads', upload)
312
+ const row = id ? await ctx.db.get(id) : null
313
+ if (!row || row.site !== actor.site._id) fail('NOT_FOUND', 'errors.fileNotFound')
314
+ const url = row.status === 'ready' && row.processedId ? await ctx.storage.getUrl(row.processedId) : null
315
+ return { status: row.status, url, name: row.name, mime: row.mime, width: row.width ?? null, height: row.height ?? null,
316
+ // `error` is the catalog key of the reason; `errorText` its German text, for agents and logs.
317
+ error: row.error ?? null, errorText: row.error ? t('de', row.error as MessageKey) : null }
318
+ },
319
+ })
320
+
321
+ /**
322
+ * Read path for fields that show a stored file (a saved image or PDF): the URL of each READY upload
323
+ * of this site, with its focus point (the Studio preview crops like the site). Unknown ids, uploads of
324
+ * another site and uploads that are not ready give null, so a reply never shows whether an id exists
325
+ * elsewhere. A file in the trash says so (`trashed`): a field keeps showing it, but a text may not name it.
326
+ */
327
+ export const urls = query({
328
+ args: { site: v.string(), ids: v.array(v.string()) },
329
+ handler: async (ctx, { site, ids }) => {
330
+ const actor = await actorFor(ctx, site)
331
+ // A page shows at most a few dozen files (gallery max 24); a bound keeps one query small.
332
+ if (ids.length > 200) fail('INVALID', 'errors.tooManyFiles')
333
+ const found: Record<string, { url: string; name: string; size: number; width: number | null; height: number | null; alt: Record<string, string>; focus?: { x: number; y: number }; trashed?: true } | null> = {}
334
+ for (const id of ids) {
335
+ const uploadId = ctx.db.normalizeId('uploads', id)
336
+ const row = uploadId ? await ctx.db.get(uploadId) : null
337
+ const url = row && row.site === actor.site._id && row.status === 'ready' && row.processedId ? await ctx.storage.getUrl(row.processedId) : null
338
+ found[id] = row && url ? { url, name: row.name, size: row.size, width: row.width ?? null, height: row.height ?? null, alt: row.alt ?? {}, ...(row.focus ? { focus: row.focus } : {}), ...(row.trashedAt ? { trashed: true as const } : {}) } : null
339
+ }
340
+ return found
341
+ },
342
+ })
343
+
344
+ /**
345
+ * Daily cleanup (SPEC 3, 4.3, 12): storage files without an upload row older than 24 h; uploads
346
+ * that never became ready older than 24 h; ready uploads without a file reference older than 7 days.
347
+ */
348
+ const BATCH = 200
349
+ const phases = ['storage', 'processing', 'failed', 'ready', 'tickets'] as const
350
+
351
+ /**
352
+ * Daily cleanup (SPEC 3, 4.3, 12), in batches of 200 that reschedule themselves:
353
+ * - storage: files without an uploads row, created more than 24 h ago. Every older file is
354
+ * checked, so a missed daily run is caught by the next one.
355
+ * - processing/failed: uploads older than 24 h that are neither kept nor referenced; a referenced stale
356
+ * processing upload becomes failed instead
357
+ * - ready: uploads older than 7 days without any file reference; kept, foldered and trashed uploads stay
358
+ * - tickets: upload tickets that expired (unused ones; a used ticket is deleted at once)
359
+ */
360
+ export const sweep = internalMutation({
361
+ args: { phase: v.optional(v.union(...phases.map((p) => v.literal(p)))), cursor: v.optional(v.union(v.string(), v.null())), dryRun: v.optional(v.boolean()) },
362
+ handler: async (ctx, args) => {
363
+ const now = Date.now()
364
+ const dryRun = args.dryRun ?? false
365
+ let purged = 0, kept = 0, markedFailed = 0
366
+ const phase = args.phase ?? 'storage'
367
+ const cursor = args.cursor ?? null
368
+ let page
369
+ if (phase === 'storage') {
370
+ page = await ctx.db.system.query('_storage')
371
+ .withIndex('by_creation_time', (q) => q.lt('_creationTime', now - DAY))
372
+ .paginate({ numItems: BATCH, cursor })
373
+ // Storage of replaced files (`previous`) has no row of its own until retention removes it.
374
+ const earlier = new Set<string>()
375
+ for (const row of await ctx.db.query('uploads').withIndex('by_previous', (q) => q.eq('hasPrevious', true)).collect()) {
376
+ for (const old of row.previous ?? []) {
377
+ earlier.add(old.storageId)
378
+ if (old.processedId) earlier.add(old.processedId)
379
+ }
380
+ }
381
+ // Variant copies have no index; the set is built once, and only when a file looks unreferenced.
382
+ let variantIds: Set<string> | undefined
383
+ for (const file of page.page) {
384
+ if (earlier.has(file._id)) continue
385
+ const row = await ctx.db.query('uploads').withIndex('by_storage', (q) => q.eq('storageId', file._id)).first()
386
+ ?? await ctx.db.query('uploads').withIndex('by_processed', (q) => q.eq('processedId', file._id)).first()
387
+ if (row) continue
388
+ if (!variantIds) {
389
+ variantIds = new Set()
390
+ for (const upload of await ctx.db.query('uploads').collect()) {
391
+ for (const variant of upload.variants ?? []) variantIds.add(variant.storageId)
392
+ for (const old of upload.previous ?? []) for (const variant of old.variants ?? []) variantIds.add(variant.storageId)
393
+ }
394
+ }
395
+ if (variantIds.has(file._id)) { kept++; continue }
396
+ purged++
397
+ if (!dryRun) await ctx.storage.delete(file._id)
398
+ }
399
+ } else if (phase === 'tickets') {
400
+ page = await ctx.db.query('uploadTickets').withIndex('by_expires', (q) => q.lt('expiresAt', now)).paginate({ numItems: BATCH, cursor })
401
+ for (const ticket of page.page) {
402
+ purged++
403
+ if (!dryRun) await ctx.db.delete(ticket._id)
404
+ }
405
+ } else {
406
+ const before = phase === 'ready' ? now - 7 * DAY : now - DAY
407
+ page = await ctx.db.query('uploads').withIndex('by_status', (q) => q.eq('status', phase).lt('_creationTime', before)).paginate({ numItems: BATCH, cursor })
408
+ for (const row of page.page) {
409
+ // Content that still uses an upload keeps it in every phase; a stale processing row that is used
410
+ // is marked failed so Studio and ops can see it.
411
+ const used = isKeptUpload(row) || await ctx.db.query('fileRefs').withIndex('by_file', (q) => q.eq('file', row._id)).first()
412
+ if (!used) {
413
+ purged++
414
+ if (!dryRun) await purgeUpload(ctx, row)
415
+ continue
416
+ }
417
+ kept++
418
+ if (phase === 'processing') {
419
+ markedFailed++
420
+ if (!dryRun) await ctx.db.patch(row._id, { status: 'failed', error: 'errors.uploadRetrying' })
421
+ }
422
+ }
423
+ }
424
+ console.log(`sweep ${phase}${dryRun ? ' (dry run)' : ''}: purged ${purged}, kept ${kept}, marked failed ${markedFailed}`)
425
+ const next = page.isDone ? phases[phases.indexOf(phase) + 1] : phase
426
+ if (next) await ctx.scheduler.runAfter(0, internal.uploads.sweep, { phase: next, cursor: page.isDone ? null : page.continueCursor, dryRun })
427
+ return null
428
+ },
429
+ })
@@ -0,0 +1,86 @@
1
+ 'use node'
2
+ // Check and processing of uploads (SPEC 4.3 point 2). Node runtime because sharp is native.
3
+ // Scheduled by uploads.register and by uploads.markFailed (retries); safe to run twice.
4
+ // The first bytes must match the declared type; a PDF is then ready as is, an image is processed.
5
+ import { v } from 'convex/values'
6
+ import { createHash } from 'node:crypto'
7
+ import { internal } from './_generated/api'
8
+ import { internalAction, type ActionCtx } from './_generated/server'
9
+ import type { Id } from './_generated/dataModel'
10
+ import { processImage, UnreadableImageError } from './image'
11
+ import { kindOf, WRONG_CONTENT } from './lib/files'
12
+
13
+
14
+ export const run = internalAction({
15
+ args: { upload: v.id('uploads') },
16
+ handler: async (ctx, { upload }) => {
17
+ try {
18
+ await processUpload(ctx, upload)
19
+ } catch (error) {
20
+ // Anything unexpected (storage, a lost write) is a failed attempt that retries; uncaught, the row would stay
21
+ // `processing` until uploads.requeueStale finds it.
22
+ console.error(`uploadsNode.run ${upload}:`, error)
23
+ await ctx.runMutation(internal.uploads.markFailed, { upload, key: 'errors.uploadRetrying', permanent: false })
24
+ }
25
+ return null
26
+ },
27
+ })
28
+
29
+ async function processUpload(ctx: ActionCtx, upload: Id<'uploads'>) {
30
+ const row = await ctx.runQuery(internal.uploads.load, { upload })
31
+ if (!row || row.status !== 'processing') return
32
+
33
+ const original = await ctx.storage.get(row.storageId)
34
+ if (!original) {
35
+ await ctx.runMutation(internal.uploads.markFailed, { upload, key: 'errors.uploadMissing', permanent: true })
36
+ return
37
+ }
38
+
39
+ const bytes = new Uint8Array(await original.arrayBuffer())
40
+ if (!kindOf(row.mime)?.signature(bytes)) {
41
+ await ctx.runMutation(internal.uploads.markFailed, { upload, key: WRONG_CONTENT.key, permanent: true })
42
+ return
43
+ }
44
+ // The hash of the original bytes finds the same file uploaded twice (library view "Doppelt").
45
+ const sha256 = createHash('sha256').update(bytes).digest('hex')
46
+ if (row.mime === 'application/pdf') {
47
+ await ctx.runMutation(internal.uploads.markFileReady, { upload, sha256 })
48
+ return
49
+ }
50
+
51
+ let result: Awaited<ReturnType<typeof processImage>>
52
+ try {
53
+ result = await processImage(bytes)
54
+ } catch (error) {
55
+ const permanent = error instanceof UnreadableImageError
56
+ const key = permanent ? error.key : 'errors.uploadRetrying'
57
+ await ctx.runMutation(internal.uploads.markFailed, { upload, key, permanent })
58
+ return
59
+ }
60
+
61
+ const processedId = await ctx.storage.store(new Blob([result.bytes], { type: 'image/webp' }))
62
+ // One after the other: convex-test loses a store that overlaps another one ("Write outside of transaction"), and
63
+ // three small files gain little from running in parallel.
64
+ const variants: { width: number; storageId: typeof processedId }[] = []
65
+ for (const variant of result.variants) variants.push({ width: variant.width, storageId: await ctx.storage.store(new Blob([variant.bytes], { type: 'image/webp' })) })
66
+ const copies = [processedId, ...variants.map((x) => x.storageId)]
67
+ let applied: boolean
68
+ try {
69
+ applied = await ctx.runMutation(internal.uploads.markReady, {
70
+ upload,
71
+ processedId,
72
+ size: result.bytes.byteLength,
73
+ width: result.width,
74
+ height: result.height,
75
+ variants,
76
+ sha256,
77
+ })
78
+ } catch (error) {
79
+ // markReady raises the site's contentRev, so many uploads of one site finishing at once (an import) can keep
80
+ // losing that write until Convex gives up. The copies are not referenced; the retry makes new ones.
81
+ await Promise.all(copies.map((id) => ctx.storage.delete(id)))
82
+ throw error
83
+ }
84
+ // Another run finished first (or the row is gone): the new copies would be unreferenced.
85
+ if (!applied) await Promise.all(copies.map((id) => ctx.storage.delete(id)))
86
+ }
@@ -0,0 +1,111 @@
1
+ // Saved list views (SPEC 4.2): a person's named filter and sort of one brick's entry list.
2
+ // A view belongs to one person; nobody else sees it, not even an admin. It is no content, so it
3
+ // writes no change row and needs no opId; the name is unique per person and brick.
4
+ import type { Json } from '@lupinum/ginko'
5
+ import { byteSize, labelOf, type Schema } from '@lupinum/ginko/internal'
6
+ import { v } from 'convex/values'
7
+ import type { Doc } from './_generated/dataModel'
8
+ import { mutation, query, type QueryCtx } from './_generated/server'
9
+ import { actorFor, fail, type Actor } from './lib/access'
10
+
11
+ export const VIEWS_MAX = 20
12
+ export const NAME_MIN = 1
13
+ export const NAME_MAX = 60
14
+ const TEXT_MAX = 200
15
+ /** Filters are small values (a choice, a flag, a range); this keeps a row far below any document limit. */
16
+ const FILTERS_BYTES = 4 * 1024
17
+
18
+ export interface ViewQuery {
19
+ text?: string
20
+ filters?: Record<string, Json>
21
+ sort?: { field: string; dir: 'asc' | 'desc' }
22
+ }
23
+
24
+ const isObject = (value: unknown): value is Record<string, Json> => typeof value === 'object' && value !== null && !Array.isArray(value)
25
+
26
+ /** The query in its stored form, or INVALID. Unknown keys are refused; filters and sort may only name live fields of the brick. */
27
+ export function checkQuery(schema: Schema, brick: string, input: unknown): ViewQuery {
28
+ const def = Object.hasOwn(schema.bricks, brick) ? schema.bricks[brick] : undefined
29
+ if (!def || def.retired) fail('INVALID', 'errors.brickNotFoundAnymore')
30
+ if (def.kind !== 'collection') fail('INVALID', 'errors.viewOnlyForCollections', undefined, { brick })
31
+ if (!isObject(input)) fail('INVALID', 'errors.viewInvalid')
32
+ for (const key of Object.keys(input)) if (key !== 'text' && key !== 'filters' && key !== 'sort') fail('INVALID', 'errors.keyNotInView', { key }, { key })
33
+ const live = (field: string) => Object.hasOwn(def.fields, field) && !def.fields[field]!.retired
34
+ const out: ViewQuery = {}
35
+
36
+ if (input.text !== undefined) {
37
+ if (typeof input.text !== 'string' || input.text.length > TEXT_MAX) fail('INVALID', 'errors.searchTextInvalid', { textMax: TEXT_MAX })
38
+ if (input.text.trim()) out.text = input.text.trim()
39
+ }
40
+ if (input.filters !== undefined) {
41
+ if (!isObject(input.filters)) fail('INVALID', 'errors.filtersInvalid')
42
+ for (const field of Object.keys(input.filters)) {
43
+ if (!live(field)) fail('INVALID', 'errors.fieldNotInBrick', { field, label: labelOf(def.label, schema.locales[0]!, schema.locales[0]!) }, { field })
44
+ }
45
+ if (byteSize(input.filters) > FILTERS_BYTES) fail('TOO_LARGE', 'errors.filtersTooLarge')
46
+ if (Object.keys(input.filters).length) out.filters = input.filters
47
+ }
48
+ if (input.sort !== undefined) {
49
+ const sort = input.sort
50
+ if (!isObject(sort) || typeof sort.field !== 'string' || (sort.dir !== 'asc' && sort.dir !== 'desc') || Object.keys(sort).length !== 2) {
51
+ fail('INVALID', 'errors.sortInvalid')
52
+ }
53
+ if (!live(sort.field)) fail('INVALID', 'errors.fieldNotInBrick', { field: sort.field, label: labelOf(def.label, schema.locales[0]!, schema.locales[0]!) }, { field: sort.field })
54
+ out.sort = { field: sort.field, dir: sort.dir }
55
+ }
56
+ return out
57
+ }
58
+
59
+ const shown = (row: Doc<'views'>) => ({ id: row._id, brick: row.brick, name: row.name, query: row.query as ViewQuery })
60
+
61
+ async function ownRows(ctx: QueryCtx, actor: Actor, brick: string) {
62
+ return ctx.db.query('views').withIndex('by_site_user_brick', (q) => q.eq('site', actor.site._id).eq('user', actor.user.id).eq('brick', brick)).collect()
63
+ }
64
+
65
+ /** Creates a view, or with `id` renames and changes one of the caller's own. */
66
+ export const save = mutation({
67
+ args: { site: v.string(), id: v.optional(v.string()), brick: v.string(), name: v.string(), query: v.any() },
68
+ handler: async (ctx, args) => {
69
+ const actor = await actorFor(ctx, args.site)
70
+ const name = args.name.trim()
71
+ if (name.length < NAME_MIN || name.length > NAME_MAX) fail('INVALID', 'errors.nameLengthRange', { nameMin: NAME_MIN, nameMax: NAME_MAX })
72
+ const query = checkQuery(actor.site.schema as Schema, args.brick, args.query)
73
+ const own = await ownRows(ctx, actor, args.brick)
74
+ const same = (row: Doc<'views'>) => row.name.toLowerCase() === name.toLowerCase()
75
+
76
+ if (args.id !== undefined) {
77
+ const id = ctx.db.normalizeId('views', args.id)
78
+ const row = id ? await ctx.db.get(id) : null
79
+ // Another person's view looks like a missing one.
80
+ if (!row || row.site !== actor.site._id || row.user !== actor.user.id) fail('NOT_FOUND', 'errors.viewNotFound')
81
+ if (row.brick !== args.brick) fail('INVALID', 'errors.viewCannotMoveBrick')
82
+ if (own.some((other) => other._id !== row._id && same(other))) fail('INVALID', 'errors.nameAlreadyUsedHere', undefined, { name })
83
+ await ctx.db.patch(row._id, { name, query })
84
+ return { id: row._id }
85
+ }
86
+ if (own.length >= VIEWS_MAX) fail('INVALID', 'errors.viewLimitPerBrick', { viewsMax: VIEWS_MAX }, { max: VIEWS_MAX })
87
+ if (own.some(same)) fail('INVALID', 'errors.nameAlreadyUsedHere', undefined, { name })
88
+ return { id: await ctx.db.insert('views', { site: actor.site._id, user: actor.user.id, brick: args.brick, name, query }) }
89
+ },
90
+ })
91
+
92
+ export const remove = mutation({
93
+ args: { site: v.string(), id: v.string() },
94
+ handler: async (ctx, args) => {
95
+ const actor = await actorFor(ctx, args.site)
96
+ const id = ctx.db.normalizeId('views', args.id)
97
+ const row = id ? await ctx.db.get(id) : null
98
+ if (!row || row.site !== actor.site._id || row.user !== actor.user.id) fail('NOT_FOUND', 'errors.viewNotFound')
99
+ await ctx.db.delete(row._id)
100
+ return null
101
+ },
102
+ })
103
+
104
+ /** The caller's own views of a brick, oldest first. */
105
+ export const list = query({
106
+ args: { site: v.string(), brick: v.string() },
107
+ handler: async (ctx, args) => {
108
+ const actor = await actorFor(ctx, args.site)
109
+ return (await ownRows(ctx, actor, args.brick)).map(shown)
110
+ },
111
+ })