Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/session-touch-after.md
Original file line number Diff line number Diff line change
@@ -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.
95 changes: 95 additions & 0 deletions packages/api/src/__tests__/sessionStore.int.test.ts
Original file line number Diff line number Diff line change
@@ -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(),
);
});
});
5 changes: 4 additions & 1 deletion packages/api/src/api-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 2 additions & 0 deletions packages/api/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
29 changes: 29 additions & 0 deletions packages/api/src/migrations.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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');
}
}
Loading