Repository navigation
Add operator-only Convex function to clear app and Better Auth tables #43
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| import { v } from 'convex/values'; | ||
| import type { TableNames } from './_generated/dataModel'; | ||
| import { components, internal } from './_generated/api'; | ||
| import { internalAction, internalMutation } from './_generated/server'; | ||
| import schema from './schema'; | ||
|
|
||
| const batchSize = 100; | ||
|
|
||
| // Delete dependent records before users. Keep this list in sync with the installed | ||
| // Better Auth component schema; its tables cannot be queried through the app db. | ||
| const authTables = [ | ||
| 'session', | ||
| 'account', | ||
| 'verification', | ||
| 'twoFactor', | ||
| 'oauthAccessToken', | ||
| 'oauthConsent', | ||
| 'oauthApplication', | ||
| 'rateLimit', | ||
| 'user', | ||
| 'jwks', | ||
| ] as const; | ||
|
|
||
| /** Operator-only: run with `npx convex run maintenance:clearAll '{"confirm":"DELETE_ALL_DATA"}'`. */ | ||
| export const clearAll = internalAction({ | ||
| args: { confirm: v.literal('DELETE_ALL_DATA') }, | ||
| handler: async (ctx) => { | ||
| const deleted: Record<string, number> = {}; | ||
|
|
||
| for (const table of Object.keys(schema.tables)) { | ||
| let count = 0; | ||
| let batch: number; | ||
| do { | ||
| batch = await ctx.runMutation(internal.maintenance.clearAppBatch, { table }); | ||
| count += batch; | ||
| } while (batch > 0); | ||
| deleted[table] = count; | ||
| } | ||
|
|
||
| for (const model of authTables) { | ||
| let count = 0; | ||
| let batch: number; | ||
| do { | ||
| const result = await ctx.runMutation(components.betterAuth.adapter.deleteMany, { | ||
| input: { model }, | ||
| paginationOpts: { numItems: batchSize, cursor: null }, | ||
| }); | ||
| batch = result.count; | ||
| count += batch; | ||
| } while (batch > 0); | ||
| deleted[`betterAuth.${model}`] = count; | ||
| } | ||
|
|
||
| return deleted; | ||
| }, | ||
| }); | ||
|
|
||
| export const clearAppBatch = internalMutation({ | ||
| args: { table: v.string() }, | ||
| handler: async (ctx, { table }) => { | ||
| if (!(table in schema.tables)) throw new Error(`Unknown app table: ${table}`); | ||
| const docs = await ctx.db.query(table as TableNames).take(batchSize); | ||
| for (const doc of docs) await ctx.db.delete(doc._id); | ||
| return docs.length; | ||
| }, | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| import { expect, it } from 'vitest'; | ||
| import betterAuth from '@convex-dev/better-auth/test'; | ||
| import { components, internal } from '../convex/_generated/api'; | ||
| import schema from '../convex/schema'; | ||
| import { authenticatedBackend } from './fixtures/auth'; | ||
|
|
||
| it('clears every app and Better Auth table in batches and can be rerun', async () => { | ||
| const { unauthenticated, account } = await authenticatedBackend(); | ||
| const now = Date.now(); | ||
| const collectionId = await unauthenticated.run((ctx) => | ||
| ctx.db.insert('collections', { | ||
| nodes: [], | ||
| revision: 0, | ||
| sourceDevice: 'test', | ||
| createdAt: now, | ||
| }), | ||
| ); | ||
| const deviceId = await unauthenticated.run((ctx) => | ||
| ctx.db.insert('devices', { | ||
| collectionId, | ||
| name: 'Test', | ||
| browser: 'Chrome', | ||
| lastSeen: now, | ||
| cursor: 0, | ||
| sequence: 0, | ||
| revoked: false, | ||
| }), | ||
| ); | ||
| await unauthenticated.run(async (ctx) => { | ||
| await ctx.db.insert('operations', { | ||
| collectionId, | ||
| deviceId, | ||
| operationId: 'op', | ||
| sequence: 1, | ||
| revision: 1, | ||
| nodeId: 'node', | ||
| title: 'Node', | ||
| kind: 'create', | ||
| device: 'Test', | ||
| at: now, | ||
| conflict: false, | ||
| }); | ||
| for (let i = 0; i < 101; i++) { | ||
| await ctx.db.insert('backups', { | ||
| collectionId, | ||
| deviceId, | ||
| nodes: [], | ||
| at: now, | ||
| reason: `test-${i}`, | ||
| }); | ||
| } | ||
| }); | ||
|
|
||
| const authRows = [ | ||
| { | ||
| model: 'verification', | ||
| data: { identifier: 'test', value: 'code', expiresAt: now, createdAt: now, updatedAt: now }, | ||
| }, | ||
| { model: 'twoFactor', data: { secret: 'secret', backupCodes: 'codes', userId: 'test' } }, | ||
| { model: 'oauthApplication', data: { clientId: 'test' } }, | ||
| { model: 'oauthAccessToken', data: { accessToken: 'test' } }, | ||
| { model: 'oauthConsent', data: { clientId: 'test' } }, | ||
| { model: 'jwks', data: { publicKey: 'public', privateKey: 'private', createdAt: now } }, | ||
| ] as const; | ||
| for (const row of authRows) { | ||
| await unauthenticated.run((ctx) => | ||
| ctx.runMutation(components.betterAuth.adapter.create, { input: row }), | ||
| ); | ||
| } | ||
| for (let i = 0; i < 101; i++) { | ||
| await unauthenticated.run((ctx) => | ||
| ctx.runMutation(components.betterAuth.adapter.create, { | ||
| input: { model: 'rateLimit', data: { key: `test-${i}`, count: 1, lastRequest: now } }, | ||
| }), | ||
| ); | ||
| } | ||
| // The fixture account contributes user and session rows. | ||
| await account('another@example.com'); | ||
| await unauthenticated.run((ctx) => | ||
| ctx.runMutation(components.betterAuth.adapter.create, { | ||
| input: { | ||
| model: 'account', | ||
| data: { | ||
| accountId: 'test', | ||
| providerId: 'credential', | ||
| userId: 'test', | ||
| createdAt: now, | ||
| updatedAt: now, | ||
| }, | ||
| }, | ||
| }), | ||
| ); | ||
|
|
||
| await expect( | ||
| unauthenticated.action(internal.maintenance.clearAll, { confirm: 'no' as 'DELETE_ALL_DATA' }), | ||
| ).rejects.toThrow(); | ||
| const deleted = await unauthenticated.action(internal.maintenance.clearAll, { | ||
| confirm: 'DELETE_ALL_DATA', | ||
| }); | ||
| expect(deleted).toMatchObject({ | ||
| collections: 1, | ||
| devices: 1, | ||
| operations: 1, | ||
| backups: 101, | ||
| 'betterAuth.user': 2, | ||
| 'betterAuth.session': 2, | ||
| 'betterAuth.account': 1, | ||
| 'betterAuth.rateLimit': 101, | ||
| }); | ||
| expect(Object.keys(deleted).sort()).toEqual( | ||
| [ | ||
| ...Object.keys(schema.tables), | ||
| ...Object.keys(betterAuth.schema.tables).map((table) => `betterAuth.${table}`), | ||
| ].sort(), | ||
| ); | ||
| await unauthenticated.run(async (ctx) => { | ||
| for (const table of Object.keys(schema.tables)) { | ||
| expect(await ctx.db.query(table as keyof typeof schema.tables).first()).toBeNull(); | ||
| } | ||
| for (const model of Object.keys(betterAuth.schema.tables)) { | ||
| const result = await ctx.runQuery(components.betterAuth.adapter.findMany, { | ||
| model: model as 'user', | ||
| paginationOpts: { numItems: 1, cursor: null }, | ||
| }); | ||
| expect(result.page).toEqual([]); | ||
| } | ||
| }); | ||
| expect( | ||
| await unauthenticated.action(internal.maintenance.clearAll, { | ||
| confirm: 'DELETE_ALL_DATA', | ||
| }), | ||
| ).toEqual(Object.fromEntries(Object.keys(deleted).map((table) => [table, 0]))); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
batchSizebounds this mutation by document count, butcollectionsandbackupseach embed a whole snapshot tree, so the batch is bounded by bytes in practice.packages/model's ownvalidateTreeallows 2,000 nodes / 600 KB per snapshot, and Convex caps a transaction at 16 MiB read — about 168 KB per document at 100 docs, so any deployment whose snapshots average ~600 bookmarks makes this call throwRead too much data in a single function execution.Two consequences beyond the throw:
collections/devices/operationsare already gone by then, so the reset stops half-finished, and the same first 100 documents fail on every rerun, which makes the documented "run the same command again to finish" recovery indocs/auth-setup.md:73unreachable. Bound the batch by bytes instead (details in the review body).