diff --git a/.changeset/session-touch-after.md b/.changeset/session-touch-after.md new file mode 100644 index 000000000..65b2b31d8 --- /dev/null +++ b/.changeset/session-touch-after.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/api': patch +--- + +perf: stop writing the login session to MongoDB on every API request. The +session's stored expiry now moves forward at most once an hour, and a startup +backfill applies this to sessions that already exist. diff --git a/packages/api/src/__tests__/sessionStore.int.test.ts b/packages/api/src/__tests__/sessionStore.int.test.ts new file mode 100644 index 000000000..d29b956e0 --- /dev/null +++ b/packages/api/src/__tests__/sessionStore.int.test.ts @@ -0,0 +1,95 @@ +import mongoose from 'mongoose'; + +import { SESSION_TOUCH_AFTER_SEC } from '@/config'; +import { getAgent, getServer } from '@/fixtures'; +import { backfillSessionLastModified } from '@/migrations'; + +const CREDENTIALS = { + email: 'session-store@example.com', + password: 'TacoCat!2#4X', +}; + +const sessions = () => + mongoose.connection.db!.collection<{ _id: string; expires: Date }>( + 'sessions', + ); + +describe('session store writes', () => { + const server = getServer(); + + beforeAll(async () => { + await server.start(); + // Registration fails if an earlier suite left a team behind. + await server.clearDBs(); + }); + + afterEach(async () => { + await server.clearDBs(); + }); + + afterAll(async () => { + await server.stop(); + }); + + // Registering also signs the user in. + const login = async () => { + const agent = getAgent(server); + const res = await agent + .post('/register/password') + .send({ ...CREDENTIALS, confirmPassword: CREDENTIALS.password }) + .expect(200); + const sid = decodeURIComponent(String(res.headers['set-cookie'])).match( + /connect\.sid[^=]*=s:([^.]+)/, + )![1]; + return { agent, sid }; + }; + + const storedExpiry = async (sid: string) => + (await sessions().findOne({ _id: sid }))?.expires; + + it('does not rewrite the session on every request', async () => { + const { agent, sid } = await login(); + const before = await storedExpiry(sid); + expect(before).toBeInstanceOf(Date); + + for (let i = 0; i < 3; i++) { + await agent.get('/me').expect(200); + } + + expect(await storedExpiry(sid)).toEqual(before); + }); + + it('stops rewriting sessions stored before touchAfter once backfilled', async () => { + const { agent, sid } = await login(); + await sessions().updateOne({ _id: sid }, { $unset: { lastModified: '' } }); + + await backfillSessionLastModified(); + // The first request touches it once; later ones skip. + await agent.get('/me').expect(200); + const before = await storedExpiry(sid); + await agent.get('/me').expect(200); + + expect(await storedExpiry(sid)).toEqual(before); + }); + + it('still removes the session on logout', async () => { + const { agent, sid } = await login(); + + await agent.get('/logout').expect(302); + + expect(await sessions().findOne({ _id: sid })).toBeNull(); + }); + + it('extends the session once the touch interval has passed', async () => { + const { agent, sid } = await login(); + const stale = new Date(Date.now() - (SESSION_TOUCH_AFTER_SEC + 60) * 1000); + await sessions().updateOne({ _id: sid }, { $set: { lastModified: stale } }); + const before = await storedExpiry(sid); + + await agent.get('/me').expect(200); + + expect((await storedExpiry(sid))!.getTime()).toBeGreaterThan( + before!.getTime(), + ); + }); +}); diff --git a/packages/api/src/api-app.ts b/packages/api/src/api-app.ts index cf1928230..c61f4167a 100644 --- a/packages/api/src/api-app.ts +++ b/packages/api/src/api-app.ts @@ -43,7 +43,10 @@ const sess: session.SessionOptions & { cookie: session.CookieOptions } = { maxAge: 1000 * 60 * 60 * 24 * 30, // 30 days }, rolling: true, - store: new MongoStore({ mongoUrl: config.MONGO_URI }), + store: new MongoStore({ + mongoUrl: config.MONGO_URI, + touchAfter: config.SESSION_TOUCH_AFTER_SEC, + }), }; app.set('trust proxy', 1); diff --git a/packages/api/src/config.ts b/packages/api/src/config.ts index 2fb4e311c..3a8c9391c 100644 --- a/packages/api/src/config.ts +++ b/packages/api/src/config.ts @@ -24,6 +24,8 @@ export const IS_EXPRESS_SESSION_SECRET_GENERATED = !env.EXPRESS_SESSION_SECRET || (!IS_LOCAL_APP_MODE && env.EXPRESS_SESSION_SECRET === LEGACY_PUBLIC_SESSION_SECRET); +// Write the session's expiry at most once an hour, not on every request. +export const SESSION_TOUCH_AFTER_SEC = 60 * 60; export const EXPRESS_SESSION_SECRET = !IS_EXPRESS_SESSION_SECRET_GENERATED && env.EXPRESS_SESSION_SECRET ? env.EXPRESS_SESSION_SECRET diff --git a/packages/api/src/migrations.ts b/packages/api/src/migrations.ts index 85fd2804c..821328ab5 100644 --- a/packages/api/src/migrations.ts +++ b/packages/api/src/migrations.ts @@ -1,5 +1,6 @@ import mongoose from 'mongoose'; +import * as config from '@/config'; import Alert, { IAlert } from '@/models/alert'; import Dashboard from '@/models/dashboard'; import { SavedSearch } from '@/models/savedSearch'; @@ -129,10 +130,38 @@ export async function backfillAlertDisplayFields() { ); } +// connect-mongo's touch() never adds lastModified, so without it older +// sessions keep being rewritten on every request. +export async function backfillSessionLastModified() { + const result = await mongoose.connection + .collection<{ _id: string; lastModified?: Date }>('sessions') + .updateMany( + { lastModified: { $exists: false } }, + { + $set: { + lastModified: new Date( + Date.now() - config.SESSION_TOUCH_AFTER_SEC * 1000, + ), + }, + }, + ); + if (result.modifiedCount > 0) { + logger.info( + { updatedCount: result.modifiedCount }, + 'Backfilled session lastModified', + ); + } +} + export async function runStartupMigrations() { try { await backfillAlertDisplayFields(); } catch (e) { logger.error({ err: e }, 'Error backfilling alert display names and tags'); } + try { + await backfillSessionLastModified(); + } catch (e) { + logger.error({ err: e }, 'Error backfilling session lastModified'); + } }