Skip to content
Merged
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
30 changes: 24 additions & 6 deletions src/http/plugins/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,11 @@ export const db = fastifyPlugin(
request.db.dispose().catch((e) => {
logSchema.error(request.log, 'Error disposing db connection', {
type: 'db-connection',
error: e,
tenantId: request.tenantId,
project: request.tenantId,
reqId: request.id,
sbReqId: request.sbReqId,
error: e,
})
})
}
Expand All @@ -80,8 +83,11 @@ export const db = fastifyPlugin(
request.db.dispose().catch((e) => {
logSchema.error(request.log, 'Error disposing db connection', {
type: 'db-connection',
error: e,
tenantId: request.tenantId,
project: request.tenantId,
reqId: request.id,
sbReqId: request.sbReqId,
error: e,
})
})
}
Expand All @@ -92,8 +98,11 @@ export const db = fastifyPlugin(
request.db.dispose().catch((e) => {
logSchema.error(request.log, 'Error disposing db connection', {
type: 'db-connection',
error: e,
tenantId: request.tenantId,
project: request.tenantId,
reqId: request.id,
sbReqId: request.sbReqId,
error: e,
})
})
}
Expand Down Expand Up @@ -139,8 +148,11 @@ export const dbSuperUser = fastifyPlugin<DbSuperUserPluginOptions>(
request.db.dispose().catch((e) => {
logSchema.error(request.log, 'Error disposing db connection', {
type: 'db-connection',
error: e,
tenantId: request.tenantId,
project: request.tenantId,
reqId: request.id,
sbReqId: request.sbReqId,
error: e,
})
})
}
Expand All @@ -153,8 +165,11 @@ export const dbSuperUser = fastifyPlugin<DbSuperUserPluginOptions>(
request.db.dispose().catch((e) => {
logSchema.error(request.log, 'Error disposing db connection', {
type: 'db-connection',
error: e,
tenantId: request.tenantId,
project: request.tenantId,
reqId: request.id,
sbReqId: request.sbReqId,
error: e,
})
})
}
Expand All @@ -165,8 +180,11 @@ export const dbSuperUser = fastifyPlugin<DbSuperUserPluginOptions>(
request.db.dispose().catch((e) => {
logSchema.error(request.log, 'Error disposing db connection', {
type: 'db-connection',
error: e,
tenantId: request.tenantId,
project: request.tenantId,
reqId: request.id,
sbReqId: request.sbReqId,
error: e,
})
})
}
Expand Down
16 changes: 16 additions & 0 deletions src/http/plugins/log-request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ describe('log-request plugin', () => {
lines = []
app = createApp(lines)

app.decorateRequest('tenantId', 'tenant-a')
await app.register(requestContext)
await app.register(logRequest({}))

Expand Down Expand Up @@ -100,4 +101,19 @@ describe('log-request plugin', () => {
expect(requestLogLine).toContain('"sbReqId":"sb-req-123"')
expect(requestLogLine).not.toContain('"request_id"')
})

it('threads tenant context into the request log data', async () => {
const response = await app.inject({
method: 'GET',
url: '/request-log',
})

expect(response.statusCode).toBe(200)

const requestLogLine = lines.find((line) => line.includes('"type":"request"'))

expect(requestLogLine).toBeDefined()
expect(requestLogLine).toContain('"tenantId":"tenant-a"')
expect(requestLogLine).toContain('"project":"tenant-a"')
})
})
15 changes: 12 additions & 3 deletions src/http/plugins/log-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -178,16 +178,22 @@ function doRequestLog(req: FastifyRequest, options: LogRequestOptions) {
// do nothing
logSchema.warning(req.log, 'Failed to serialize log metadata', {
type: 'otel',
error: e,
tenantId,
project: tenantId,
reqId: rId,
sbReqId: req.sbReqId,
error: e,
})
}
}
} catch (e) {
logSchema.error(req.log, 'Failed to get log metadata', {
type: 'request',
error: e,
tenantId,
project: tenantId,
reqId: rId,
sbReqId: req.sbReqId,
error: e,
})
}
}
Expand All @@ -196,6 +202,10 @@ function doRequestLog(req: FastifyRequest, options: LogRequestOptions) {

logSchema.request(req.log, buildLogMessage, {
type: 'request',
tenantId,
project: tenantId,
reqId: rId,
sbReqId: req.sbReqId,
req,
reqMetadata,
res: options.reply,
Expand All @@ -207,6 +217,5 @@ function doRequestLog(req: FastifyRequest, options: LogRequestOptions) {
resources: req.resources,
operation: req.operation?.type ?? req.routeOptions.config.operation?.type,
serverTimes: req.serverTimings,
sbReqId: req.sbReqId,
})
}
74 changes: 74 additions & 0 deletions src/http/plugins/tenant-id.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import Fastify, { type FastifyInstance, type FastifyRequest } from 'fastify'
import { getConfig } from '../../config'
import { adminTenantId, tenantId } from './tenant-id'

const { tenantId: defaultTenantId } = getConfig()

function failOnRequestChildLogger(app: FastifyInstance) {
app.addHook('onRequest', async (request: FastifyRequest) => {
request.log.child = (() => {
throw new Error('request.log.child should not be called by the tenant id plugin')
}) as typeof request.log.child
})
}

describe('tenant id plugins', () => {
it('does not create an extra request child logger for API requests', async () => {
const app = Fastify()

failOnRequestChildLogger(app)
await app.register(tenantId)
app.get('/status', async () => ({ ok: true }))

try {
const response = await app.inject({
method: 'GET',
url: '/status',
})

expect(response.statusCode).toBe(200)
} finally {
await app.close()
}
})

it('does not create an extra request child logger for admin requests', async () => {
const app = Fastify()

failOnRequestChildLogger(app)
await app.register(adminTenantId)
app.get('/tenants/:tenantId', async (request) => ({ tenantId: request.tenantId }))

try {
const response = await app.inject({
method: 'GET',
url: '/tenants/tenant-a',
})

expect(response.statusCode).toBe(200)
expect(response.json()).toEqual({ tenantId: 'tenant-a' })
} finally {
await app.close()
}
})

it('sets the default tenant id for admin requests without tenant params', async () => {
const app = Fastify()

failOnRequestChildLogger(app)
await app.register(adminTenantId)
app.get('/status', async (request) => ({ tenantId: request.tenantId }))

try {
const response = await app.inject({
method: 'GET',
url: '/status',
})

expect(response.statusCode).toBe(200)
expect(response.json()).toEqual({ tenantId: defaultTenantId })
} finally {
await app.close()
}
})
})
25 changes: 2 additions & 23 deletions src/http/plugins/tenant-id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,7 @@ declare module 'fastify' {
}
}

const {
version,
isMultitenant,
tenantId: defaultTenantId,
requestXForwardedHostRegExp,
} = getConfig()
const { isMultitenant, tenantId: defaultTenantId, requestXForwardedHostRegExp } = getConfig()

export const tenantId = fastifyPlugin(
async (fastify) => {
Expand All @@ -26,35 +21,19 @@ export const tenantId = fastifyPlugin(

request.tenantId = result[1]
})

fastify.addHook('onRequest', async (request, reply) => {
reply.log = request.log = request.log.child({
tenantId: request.tenantId,
project: request.tenantId,
reqId: request.id,
appVersion: version,
})
})
},
{ name: 'tenant-id' }
)

export const adminTenantId = fastifyPlugin(
async (fastify) => {
fastify.decorateRequest('tenantId', defaultTenantId)
fastify.addHook('onRequest', async (request) => {
const tenantId = (request.params as Record<string, undefined | string>).tenantId
if (!tenantId) return

request.tenantId = tenantId
})

fastify.addHook('onRequest', async (request, reply) => {
reply.log = request.log = request.log.child({
tenantId: request.tenantId,
project: request.tenantId,
reqId: request.id,
})
})
},
{ name: 'admin-tenant-id' }
)
3 changes: 3 additions & 0 deletions src/http/plugins/tracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ export const tracing = fastifyPlugin(
logSchema.error(request.log, 'failed setting tracing mode', {
error: e,
type: 'tracing',
tenantId: request.tenantId,
project: request.tenantId,
reqId: request.id,
sbReqId: request.sbReqId,
})
}
Expand Down
5 changes: 4 additions & 1 deletion src/http/routes/admin/jwks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,8 +170,11 @@ export default async function routes(fastify: FastifyInstance) {
}).catch((e) => {
logSchema.error(request.log, 'Error generating url signing jwks for all tenants', {
type: 'jwk-generator',
error: e,
tenantId: request.tenantId,
project: request.tenantId,
reqId: request.id,
sbReqId: request.sbReqId,
error: e,
})
})
return reply.send({ started: true })
Expand Down
12 changes: 8 additions & 4 deletions src/http/routes/admin/objects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,12 @@ export default async function routes(fastify: FastifyInstance) {
} catch (e) {
logSchema.error(req.log, 'list orphaned objects stream failed', {
type: 'orphan',
tenantId: req.tenantId,
project: req.tenantId,
reqId: req.id,
sbReqId: req.sbReqId,
error: e,
project: req.params.tenantId,
metadata: JSON.stringify({ bucket }),
sbReqId: req.sbReqId,
})
writeNdjson(reply, {
event: 'error',
Expand Down Expand Up @@ -190,10 +192,12 @@ export default async function routes(fastify: FastifyInstance) {
} catch (e) {
logSchema.error(req.log, 'delete orphaned objects stream failed', {
type: 'orphan',
tenantId: req.tenantId,
project: req.tenantId,
reqId: req.id,
sbReqId: req.sbReqId,
error: e,
project: req.params.tenantId,
metadata: JSON.stringify({ bucket }),
sbReqId: req.sbReqId,
})
writeNdjson(reply, {
event: 'error',
Expand Down
6 changes: 4 additions & 2 deletions src/http/routes/tus/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,11 +246,12 @@ const authenticatedRoutes = fastifyPlugin(
fastify.addHook('preHandler', async (req) => {
;(req.raw as MultiPartRequest).log = req.log
;(req.raw as MultiPartRequest).upload = {
tenantId: req.tenantId,
storage: req.storage,
owner: req.owner,
tenantId: req.tenantId,
db: req.db,
isUpsert: req.headers['x-upsert'] === 'true',
reqId: req.id,
sbReqId: req.sbReqId,
}
})
Expand Down Expand Up @@ -349,11 +350,12 @@ export const publicRoutes = fastifyPlugin(
fastify.addHook('preHandler', async (req) => {
;(req.raw as MultiPartRequest).log = req.log
;(req.raw as MultiPartRequest).upload = {
tenantId: req.tenantId,
storage: req.storage,
owner: req.owner,
tenantId: req.tenantId,
db: req.db,
isUpsert: req.headers['x-upsert'] === 'true',
reqId: req.id,
sbReqId: req.sbReqId,
}
})
Expand Down
10 changes: 10 additions & 0 deletions src/http/routes/tus/lifecycle.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ function createRawTusRequest({
location: {},
},
tenantId: 'tenant-123',
reqId: 'req-123',
sbReqId,
},
url: '/upload/resumable',
Expand Down Expand Up @@ -79,6 +80,9 @@ describe('tus lifecycle logging', () => {

expect(errorSpy).toHaveBeenCalledWith(reqLog, 'Error disposing db connection', {
type: 'db-connection',
tenantId: 'tenant-123',
project: 'tenant-123',
reqId: 'req-123',
error,
sbReqId: 'sb-req-123',
})
Expand All @@ -97,6 +101,9 @@ describe('tus lifecycle logging', () => {

expect(warningSpy).toHaveBeenCalledWith(reqLog, 'Failed to parse upload metadata', {
type: 'tus',
tenantId: 'tenant-123',
project: 'tenant-123',
reqId: 'req-123',
error: expect.any(Error),
sbReqId: 'sb-req-123',
})
Expand All @@ -117,6 +124,9 @@ describe('tus lifecycle logging', () => {
expect(canUploadSpy).toHaveBeenCalledOnce()
expect(warningSpy).toHaveBeenCalledWith(reqLog, 'Failed to parse user metadata', {
type: 'tus',
tenantId: 'tenant-123',
project: 'tenant-123',
reqId: 'req-123',
error: expect.any(Error),
sbReqId: 'sb-req-123',
})
Expand Down
Loading