/** Verified mutable metadata. Operations preflight every target and never revive retained keys. */ import { ConvexError, v } from "convex/values"; import { mutation, internalMutation } from "./_generated/server"; import type { Doc } from "./_generated/dataModel"; import { scopeArgs, authority, actor, mutableRow, candidates, check, fresh, finalChecks, canonicalFields, newResource, sourceId, tombstone, readAuthority, readResourceAuthority, newTarget, resource, response, page, invalid } from "./runtimeMetadataAuth"; const keyArgs = { namespace: v.string(), key: v.string(), ...scopeArgs }; const filterArgs = { namespace: v.string(), ...scopeArgs, keyPrefix: v.optional(v.string()), userId: v.optional(v.string()), updatedBefore: v.optional(v.number()), updatedAfter: v.optional(v.number()) }; interface Filters { namespace: string; keyPrefix?: string; userId?: string; updatedBefore?: number; updatedAfter?: number } function filter(rows: Doc<"mutable">[], args: Filters) { return rows.filter((row) => row.namespace === args.namespace && (args.keyPrefix === undefined || row.key.startsWith(args.keyPrefix)) && (args.userId === undefined || row.userId === args.userId) && (args.updatedBefore === undefined || row.updatedAt < args.updatedBefore) && (args.updatedAfter === undefined || row.updatedAt > args.updatedAfter)); } function numeric(value: unknown, amount: unknown, decrement = false): number { const delta = amount === undefined ? 1 : amount; if (typeof value !== "number" || !Number.isFinite(value) || typeof delta !== "number" || !Number.isFinite(delta)) invalid(); const result = value + (decrement ? -delta : delta); if (!Number.isFinite(result)) invalid(); return result; } function updateValue(value: unknown, operation: string, operand: unknown): unknown { if (operation === "increment" || operation === "decrement") return numeric(value, operand, operation === "decrement"); if (operation === "append") { if (operand === undefined) invalid(); if (!Array.isArray(value)) throw new ConvexError("MUTABLE_VALUE_NOT_ARRAY"); return [...value, operand]; } if (operand === undefined) invalid(); return operand; } export const set = mutation({ args: { ...keyArgs, value: v.any(), userId: v.optional(v.string()), metadata: v.optional(v.any()) }, handler: async (ctx, args) => { const auth = await authority(ctx, "write", args); actor(auth, args.userId); const row = await mutableRow(ctx, auth, args.namespace, args.key, "write"); const key = sourceId("mutable", args.namespace, args.key); await newResource(ctx, auth, key); const read = row ? await readAuthority(ctx, auth, "mutable", row) : await readResourceAuthority(ctx, auth, newTarget(auth, key)); const now = Date.now(); if (row) { await check(ctx, "mutable", row, auth, "write"); await ctx.db.patch("mutable", row._id, { value: args.value, metadata: args.metadata === undefined ? row.metadata : args.metadata, updatedAt: now }); } else await newResource(ctx, auth, key); const id = row?._id ?? await ctx.db.insert("mutable", { namespace: args.namespace, key: args.key, value: args.value, ...canonicalFields(auth), metadata: args.metadata, createdAt: now, updatedAt: now }); const updated = await ctx.db.get("mutable", id); if (!updated) throw new ConvexError("MUTABLE_KEY_NOT_FOUND"); return await response(ctx, auth, "mutable", updated, read, () => updated, () => ({ updated: true as const, namespace: args.namespace, key: args.key, ...(row ? {} : { createdId: id }) })); } }); export const update = mutation({ args: { ...keyArgs, operation: v.union(v.literal("increment"), v.literal("decrement"), v.literal("append"), v.literal("custom")), operand: v.optional(v.any()) }, handler: async (ctx, args) => { const auth = await authority(ctx, "write", args); const row = await mutableRow(ctx, auth, args.namespace, args.key, "write"); if (!row) throw new ConvexError("MUTABLE_KEY_NOT_FOUND"); const read = await readAuthority(ctx, auth, "mutable", row); const value = updateValue(row.value, args.operation, args.operand); await check(ctx, "mutable", row, auth, "write"); await ctx.db.patch("mutable", row._id, { value, updatedAt: Date.now() }); const updated = await ctx.db.get("mutable", row._id); if (!updated) throw new ConvexError("MUTABLE_KEY_NOT_FOUND"); return await response(ctx, auth, "mutable", updated, read, () => updated, () => ({ updated: true, namespace: args.namespace, key: args.key })); } }); export const get = mutation({ args: keyArgs, handler: async (ctx, args) => await mutableRow(ctx, await authority(ctx, "read", args), args.namespace, args.key, "read") }); export const exists = mutation({ args: keyArgs, handler: async (ctx, args) => (await mutableRow(ctx, await authority(ctx, "read", args), args.namespace, args.key, "read")) !== null }); export const list = mutation({ args: { ...filterArgs, limit: v.optional(v.number()), offset: v.optional(v.number()), sortBy: v.optional(v.string()), sortOrder: v.optional(v.string()) }, handler: async (ctx, args) => { const rows = filter(await candidates(ctx, "mutable", await authority(ctx, "read", args), "read"), args); rows.sort((a, b) => (args.sortBy === "updatedAt" ? a.updatedAt - b.updatedAt : a.key.localeCompare(b.key)) * (args.sortOrder === "desc" ? -1 : 1)); const offset = page(args.offset, 0); return rows.slice(offset, offset + page(args.limit, 100)); } }); export const count = mutation({ args: filterArgs, handler: async (ctx, args) => filter(await candidates(ctx, "mutable", await authority(ctx, "read", args), "read"), args).length }); export const deleteKey = mutation({ args: keyArgs, handler: async (ctx, args) => { const auth = await authority(ctx, "write", args); const row = await mutableRow(ctx, auth, args.namespace, args.key, "write"); if (!row) throw new ConvexError("MUTABLE_KEY_NOT_FOUND"); await check(ctx, "mutable", row, auth, "write"); await tombstone(ctx, "mutable", row); await fresh(ctx, auth, "write"); return { deleted: true, namespace: args.namespace, key: args.key }; } }); export const purgeMany = mutation({ args: filterArgs, handler: async (ctx, args) => { const auth = await authority(ctx, "write", args); const rows = filter(await candidates(ctx, "mutable", auth, "write"), args); const reads = await Promise.all(rows.map((row) => readAuthority(ctx, auth, "mutable", row))); for (const row of rows) await check(ctx, "mutable", row, auth, "write"); for (const row of rows) { await check(ctx, "mutable", row, auth, "write"); await tombstone(ctx, "mutable", row); } await finalChecks(ctx, [{ auth, capability: "write" }, ...reads.flatMap((read) => read ? [{ auth: read, capability: "read" as const }] : [])]); return { deleted: rows.length, namespace: args.namespace, ...(reads.every(Boolean) ? { keys: rows.map((row) => row.key) } : {}) }; } }); export const purgeNamespace = mutation({ args: { namespace: v.string(), ...scopeArgs, dryRun: v.optional(v.boolean()) }, handler: async (ctx, args) => { const auth = await authority(ctx, "write", args); const rows = filter(await candidates(ctx, "mutable", auth, "write"), args); const reads = await Promise.all(rows.map((row) => readAuthority(ctx, auth, "mutable", row))); for (const row of rows) await check(ctx, "mutable", row, auth, "write"); if (!args.dryRun) for (const row of rows) { await check(ctx, "mutable", row, auth, "write"); await tombstone(ctx, "mutable", row); } await finalChecks(ctx, [{ auth, capability: "write" }, ...reads.flatMap((read, index) => read ? [{ auth: read, capability: "read" as const, ...(args.dryRun ? { resource: resource("mutable", rows[index]!) } : {}) }] : [])]); return { deleted: rows.length, namespace: args.namespace, dryRun: args.dryRun ?? false, ...(args.dryRun && reads.every(Boolean) ? { keys: rows.map((row) => row.key) } : {}) }; } }); export const transaction = mutation({ args: { ...scopeArgs, operations: v.array(v.object({ op: v.union(v.literal("set"), v.literal("update"), v.literal("delete"), v.literal("increment"), v.literal("decrement")), namespace: v.string(), key: v.string(), value: v.optional(v.any()), amount: v.optional(v.number()) })) }, handler: async (ctx, args) => { const auth = await authority(ctx, "write", args); const state = new Map | null; value: unknown; deleted: boolean; read: Awaited> }>(); const plans: Array<{ operation: typeof args.operations[number]; value: unknown }> = []; // Validate authorization and functional operations for the ENTIRE batch before the first write. for (const operation of args.operations) { const key = sourceId("mutable", operation.namespace, operation.key); let current = state.get(key); if (!current) { const row = await mutableRow(ctx, auth, operation.namespace, operation.key, "write"); await newResource(ctx, auth, key); const read = row ? await readAuthority(ctx, auth, "mutable", row) : await readResourceAuthority(ctx, auth, newTarget(auth, key)); current = { row, value: row?.value, deleted: false, read }; state.set(key, current); } if (current.deleted) invalid(); if (operation.op !== "set" && current.value === undefined) throw new ConvexError("MUTABLE_KEY_NOT_FOUND"); if (operation.op === "delete") current.deleted = true; else if (operation.op === "increment" || operation.op === "decrement") current.value = numeric(current.value, operation.amount, operation.op === "decrement"); else { if (operation.value === undefined) invalid(); current.value = operation.value; } plans.push({ operation, value: current.value }); } const results: Array | { deleted: boolean; namespace: string; key: string } | { updated: boolean; namespace: string; key: string }> = []; for (const { operation, value } of plans) { const key = sourceId("mutable", operation.namespace, operation.key); const current = state.get(key)!; const row = await mutableRow(ctx, auth, operation.namespace, operation.key, "write"); if (operation.op === "delete") { if (!row) throw new ConvexError("MUTABLE_KEY_NOT_FOUND"); await check(ctx, "mutable", row, auth, "write"); await tombstone(ctx, "mutable", row); results.push({ deleted: true, namespace: operation.namespace, key: operation.key }); } else { const now = Date.now(); if (row) { await check(ctx, "mutable", row, auth, "write"); await ctx.db.patch("mutable", row._id, { value, updatedAt: now }); } else await newResource(ctx, auth, key); const id = row?._id ?? await ctx.db.insert("mutable", { namespace: operation.namespace, key: operation.key, value, ...canonicalFields(auth), createdAt: now, updatedAt: now }); const updated = await ctx.db.get("mutable", id); if (!updated) throw new ConvexError("MUTABLE_KEY_NOT_FOUND"); await check(ctx, "mutable", updated, auth, "write"); results.push(current.read ? updated : { updated: true, namespace: operation.namespace, key: operation.key }); current.row = updated; } } await finalChecks(ctx, [{ auth, capability: "write" }, ...[...state.values()].flatMap((current) => current.read ? [{ auth: current.read, capability: "read" as const, ...(!current.deleted && current.row ? { resource: resource("mutable", current.row) } : {}) }] : [])]); return { success: true, operationsExecuted: plans.length, results }; } }); export const purgeAll = internalMutation({ args: { tenantId: v.optional(v.string()) }, handler: async (ctx, args) => { const rows = args.tenantId === undefined ? await ctx.db.query("mutable").collect() : await ctx.db.query("mutable").withIndex("by_tenantId", (q) => q.eq("tenantId", args.tenantId)).collect(); for (const row of rows) { if (row.tenantId && row.ownerPrincipalId) await tombstone(ctx, "mutable", row); else await ctx.db.patch("mutable", row._id, { tombstonedAt: Date.now() }); } return { deleted: rows.filter((row) => row.tombstonedAt === undefined).length }; } });