Skip to content

Commit 5c53221

Browse files
committed
Add a background access_token cleanup job
1 parent d95e3a1 commit 5c53221

2 files changed

Lines changed: 33 additions & 0 deletions

File tree

api/src/db/token-cleanup.ts

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { sql } from 'kysely';
2+
import log from 'loglevel';
3+
4+
import { db } from './database.ts';
5+
import { reportError } from '../errors.ts';
6+
7+
const ONE_DAY = 1000 * 60 * 60 * 24;
8+
9+
async function deleteExpiredTokens() {
10+
try {
11+
const result = await db.deleteFrom('access_tokens')
12+
.where('expires_at', '<', sql<Date>`NOW() - INTERVAL '1 month'`)
13+
.executeTakeFirst();
14+
15+
const deletedCount = Number(result.numDeletedRows);
16+
if (deletedCount > 0) {
17+
log.info(`Cleaned up ${deletedCount} expired access tokens`);
18+
}
19+
} catch (e: unknown) {
20+
log.error('Failed to clean up expired access tokens');
21+
reportError(e as Error);
22+
}
23+
}
24+
25+
export function startTokenCleanup() {
26+
// Run once on startup, then daily
27+
deleteExpiredTokens();
28+
29+
const interval = setInterval(deleteExpiredTokens, ONE_DAY);
30+
interval.unref();
31+
}

api/src/server.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { reportError } from './errors.ts';
1212

1313
import { initializeDbConnection, testDbConnection, closeDatabase } from './db/database.ts';
1414
import { runMigrations } from './db/migrator.ts';
15+
import { startTokenCleanup } from './db/token-cleanup.ts';
1516
import { testEmailConnection } from './email/mailer.ts';
1617

1718
const app = express();
@@ -168,6 +169,7 @@ apiRouter.get('/health', async (req, res) => {
168169
export async function startApiServer() {
169170
const db = await initializeDbConnection();
170171
await runMigrations(db);
172+
startTokenCleanup();
171173

172174
const server = app.listen(process.env.PORT ?? 4000, () => {
173175
log.info(`Server (version ${process.env.VERSION}) listening on port ${(server.address() as any).port}`);

0 commit comments

Comments
 (0)