Skip to content

Commit 5bf7ef8

Browse files
perf(api): stream media with byte ranges, cached thumbnails, compression, indexes
Large videos took minutes to start because every file was sent whole and could not be seeked. Now: - Range/206 support everywhere file bytes are served (Drive, Shared Spaces, share links, REST API, WebDAV), plus ETag/304 and HEAD. SERVER files are AES-256-GCM: partial reads use AES-CTR at the matching GCM counter, so existing files stream with no re-encryption or migration (full reads are still GCM-verified). A download is audited/counted once, not per seek. - /files/:id/thumb and /spaces/:id/files/:fileId/thumb: ~10-30 KB WebP tiles (sharp) instead of full-size images, cached on disk ENCRYPTED with the file's key, immutable browser cache, bounded job pool, swept by maintenance. - gzip/brotli for API JSON (never for file bytes); roomier rate limit for media routes; full-decrypt stream no longer hangs on a storage error. - Composite indexes for folder listings (migration 20261102120000).
1 parent 7f5e25c commit 5bf7ef8

18 files changed

Lines changed: 1114 additions & 67 deletions

File tree

‎apps/api/package.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
"seed": "tsx prisma/seed.ts"
2020
},
2121
"dependencies": {
22+
"@fastify/compress": "^9.3.0",
2223
"@fastify/cookie": "^11.0.1",
2324
"@fastify/cors": "^10.0.1",
2425
"@fastify/helmet": "^13.0.0",
@@ -32,6 +33,7 @@
3233
"fastify-plugin": "^5.0.1",
3334
"pino": "^9.5.0",
3435
"qrcode": "^1.5.4",
36+
"sharp": "^0.35.5",
3537
"undici": "^6.21.0",
3638
"zod": "^3.24.1"
3739
},
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
-- Composite indexes for the hot "list this folder" queries (Drive, Shared Spaces, folder tree).
2+
CREATE INDEX "FileObject_ownerId_folderId_deletedAt_idx" ON "FileObject"("ownerId", "folderId", "deletedAt");
3+
CREATE INDEX "FileObject_spaceId_folderId_deletedAt_idx" ON "FileObject"("spaceId", "folderId", "deletedAt");
4+
CREATE INDEX "Folder_ownerId_spaceId_deletedAt_idx" ON "Folder"("ownerId", "spaceId", "deletedAt");

‎apps/api/prisma/schema.prisma‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,8 @@ model Folder {
195195
@@index([ownerId])
196196
@@index([spaceId])
197197
@@index([deletedAt])
198+
// The Drive's folder tree: "all of this owner's personal folders, not in the Trash".
199+
@@index([ownerId, spaceId, deletedAt])
198200
}
199201

200202
model FileObject {
@@ -249,6 +251,9 @@ model FileObject {
249251
@@index([folderId])
250252
@@index([spaceId])
251253
@@index([deletedAt])
254+
// Folder listings: "files in this folder of this owner (or space), not in the Trash".
255+
@@index([ownerId, folderId, deletedAt])
256+
@@index([spaceId, folderId, deletedAt])
252257
}
253258

254259
// A prior revision of a SERVER-mode file (kept for text-like files). Holds its own

‎apps/api/src/env.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ const envSchema = z.object({
3131
STORAGE_DRIVER: z.enum(['local']).default('local'),
3232
STORAGE_PATH: z.string().default('/data/storage'),
3333
QUARANTINE_PATH: z.string().default('/data/quarantine'),
34+
// Where generated image thumbnails are cached (encrypted like their source). Defaults to a
35+
// `thumbs` folder next to STORAGE_PATH. Safe to wipe: thumbnails are rebuilt on demand.
36+
THUMB_CACHE_PATH: z.string().optional(),
3437

3538
DEFAULT_USER_QUOTA_BYTES: z.coerce.number().int().nonnegative().default(10_737_418_240),
3639
REMOTE_UPLOAD_MAX_BYTES: z.coerce.number().int().positive().default(2_147_483_648),

‎apps/api/src/lib/media-route.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/**
2+
* Route options for endpoints that serve file bytes (downloads, streaming, thumbnails).
3+
*
4+
* - A playing/seeking video issues many small Range requests and a folder of photos loads dozens of
5+
* tiles at once, so these get a roomier rate limit than the API default.
6+
* - They are never gzip/brotli-compressed: media is already compressed, and on-the-fly compression
7+
* would drop Content-Length and break byte ranges.
8+
*/
9+
export const MEDIA_ROUTE = {
10+
compress: false,
11+
config: { rateLimit: { max: 5000, timeWindow: '1 minute' } },
12+
} as const;

‎apps/api/src/routes/api-v1.ts‎

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
*/
99
import type { FastifyPluginAsync } from 'fastify';
1010
import { prisma } from '../db.js';
11-
import { decryptServerFile } from '../services/download.js';
11+
import { sendStoredFile } from '../services/stream.js';
12+
import { MEDIA_ROUTE } from '../lib/media-route.js';
1213
import { FileTooLargeError, InfectedFileError } from '../services/ingest.js';
1314
import { storeUserFile, QuotaExhaustedError } from '../services/upload.js';
1415
import { toPublicFile, toPublicFolder } from '../lib/serialize.js';
@@ -108,18 +109,14 @@ export const apiV1Routes: FastifyPluginAsync = async (app) => {
108109
});
109110

110111
// GET /files/:id/download — stream a file's decrypted contents.
111-
app.get('/files/:id/download', { preHandler: app.tokenAuth('read') }, async (req, reply) => {
112+
app.get('/files/:id/download', { ...MEDIA_ROUTE, preHandler: app.tokenAuth('read') }, async (req, reply) => {
112113
const { id } = req.params as { id: string };
113114
const file = await prisma.fileObject.findFirst({
114115
where: { id, ownerId: req.user!.id, spaceId: null, encMode: 'SERVER', deletedAt: null },
115116
});
116117
if (!file) return reply.code(404).send({ error: 'File not found' });
117118
if (!folderAllowed(req, file.folderId)) return reply.code(403).send({ error: 'Token is restricted to another folder' });
118119

119-
reply
120-
.header('Content-Type', file.mimeType)
121-
.header('Content-Length', Number(file.sizeBytes))
122-
.header('Content-Disposition', `attachment; filename="${encodeURIComponent(file.name)}"`);
123-
return reply.send(decryptServerFile(app.ctx, file));
120+
return sendStoredFile(app.ctx, req, reply, file); // Range-capable (resumable / partial fetches)
124121
});
125122
};

‎apps/api/src/routes/files.ts‎

Lines changed: 32 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ import { prisma } from '../db.js';
44
import { parseOr400 } from '../lib/validate.js';
55
import { FileTooLargeError, InfectedFileError } from '../services/ingest.js';
66
import { storeUserFile, QuotaExhaustedError } from '../services/upload.js';
7-
import { decryptServerFile } from '../services/download.js';
7+
import { sendStoredFile, startsAtBeginning } from '../services/stream.js';
8+
import { sendThumbnail } from '../services/thumbs.js';
9+
import { MEDIA_ROUTE } from '../lib/media-route.js';
810
import { hardDeleteFile, trashFile } from '../services/trash.js';
911
import { pruneVersions, snapshotVersion } from '../services/versioning.js';
1012
import { adjustUsage } from '../services/quota.js';
@@ -95,34 +97,35 @@ export const fileRoutes: FastifyPluginAsync = async (app) => {
9597
}
9698
});
9799

98-
// GET /files/:id/download — decrypt and stream a SERVER-mode file. `?preview=1` is used for
99-
// inline previews / grid thumbnails and is NOT audited (so a folder of images doesn't flood the
100-
// audit log with one download entry per tile).
101-
app.get('/:id/download', async (req, reply) => {
100+
// GET /files/:id/download — stream a SERVER (decrypted) or PUBLIC (plaintext) file, with Range
101+
// support so videos/music start at once and can seek. `?inline=1` (viewer) or `?preview=1`
102+
// (tiles; not audited) display it in the page instead of downloading. A "download" is audited once
103+
// (on the request that starts at byte 0), not on every seek.
104+
app.get('/:id/download', MEDIA_ROUTE, async (req, reply) => {
102105
const { id } = req.params as { id: string };
103-
const { preview } = req.query as { preview?: string };
106+
const { preview, inline } = req.query as { preview?: string; inline?: string };
104107
const file = await prisma.fileObject.findFirst({
105108
where: { id, ownerId: req.user!.id, spaceId: null },
106109
});
107110
if (!file) return reply.code(404).send({ error: 'File not found' });
108111
if (file.encMode === 'ZK') {
109112
return reply.code(400).send({ error: 'Zero-Knowledge files are fetched via the vault API' });
110113
}
114+
if (preview !== '1' && req.method === 'GET' && startsAtBeginning(req) && !req.headers['if-none-match']) {
115+
await audit(req, 'file.download', { target: file.id });
116+
}
117+
const asInline = preview === '1' || inline === '1';
118+
return sendStoredFile(app.ctx, req, reply, file, { disposition: asInline ? 'inline' : 'attachment' });
119+
});
111120

112-
if (preview !== '1') await audit(req, 'file.download', { target: file.id });
113-
reply
114-
.header('Content-Type', file.mimeType)
115-
.header('Content-Length', Number(file.sizeBytes))
116-
.header(
117-
'Content-Disposition',
118-
`attachment; filename="${encodeURIComponent(file.name)}"`,
119-
);
120-
// PUBLIC files are stored plaintext (Public/Open space); everything else is decrypted.
121-
return reply.send(
122-
file.encMode === 'PUBLIC'
123-
? app.ctx.storage.createReadStream(file.storageKey)
124-
: decryptServerFile(app.ctx, file),
125-
);
121+
// GET /files/:id/thumb — small cached WebP for image tiles (415 when not an image).
122+
app.get('/:id/thumb', MEDIA_ROUTE, async (req, reply) => {
123+
const { id } = req.params as { id: string };
124+
const file = await prisma.fileObject.findFirst({
125+
where: { id, ownerId: req.user!.id, spaceId: null, deletedAt: null },
126+
});
127+
if (!file) return reply.code(404).send({ error: 'File not found' });
128+
return sendThumbnail(app.ctx, req, reply, file);
126129
});
127130

128131
// PATCH /files/:id — rename and/or move a SERVER-mode file.
@@ -179,17 +182,20 @@ export const fileRoutes: FastifyPluginAsync = async (app) => {
179182
});
180183

181184
// GET /files/:id/versions/:versionId/download — decrypt and stream a past version.
182-
app.get('/:id/versions/:versionId/download', async (req, reply) => {
185+
app.get('/:id/versions/:versionId/download', MEDIA_ROUTE, async (req, reply) => {
183186
const { id, versionId } = req.params as { id: string; versionId: string };
184187
const file = await prisma.fileObject.findFirst({ where: { id, ownerId: req.user!.id, spaceId: null } });
185188
if (!file) return reply.code(404).send({ error: 'File not found' });
186189
const version = await prisma.fileVersion.findFirst({ where: { id: versionId, fileId: id } });
187190
if (!version) return reply.code(404).send({ error: 'Version not found' });
188-
reply
189-
.header('Content-Type', version.mimeType)
190-
.header('Content-Length', Number(version.sizeBytes))
191-
.header('Content-Disposition', `attachment; filename="${encodeURIComponent(file.name)}"`);
192-
return reply.send(decryptServerFile(app.ctx, version));
191+
const { inline } = req.query as { inline?: string };
192+
return sendStoredFile(
193+
app.ctx,
194+
req,
195+
reply,
196+
{ ...version, name: file.name, encMode: 'SERVER' },
197+
{ disposition: inline === '1' ? 'inline' : 'attachment' },
198+
);
193199
});
194200

195201
// POST /files/:id/versions/:versionId/restore — make a past version current. The current

‎apps/api/src/routes/share-public.ts‎

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@ import type { FastifyPluginAsync } from 'fastify';
1010
import type { PublicShareView } from '@opencoperlock/shared';
1111
import { prisma } from '../db.js';
1212
import { decideAccess, isExhausted, isExpired, shareEntries, shareFile } from '../services/share.js';
13-
import { decryptServerFile } from '../services/download.js';
13+
import { sendStoredFile, startsAtBeginning } from '../services/stream.js';
14+
import { MEDIA_ROUTE } from '../lib/media-route.js';
1415
import { audit } from '../services/audit.js';
1516

1617
export const sharePublicRoutes: FastifyPluginAsync = async (app) => {
@@ -44,7 +45,7 @@ export const sharePublicRoutes: FastifyPluginAsync = async (app) => {
4445

4546
// GET /s/:token/file/:fileId — stream a shared file. `inline=1` previews without
4647
// counting against the download cap; otherwise it's an attachment and is counted.
47-
app.get('/:token/file/:fileId', async (req, reply) => {
48+
app.get('/:token/file/:fileId', MEDIA_ROUTE, async (req, reply) => {
4849
const { token, fileId } = req.params as { token: string; fileId: string };
4950
const { code, inline } = req.query as { code?: string; inline?: string };
5051
const isInline = inline === '1';
@@ -65,7 +66,9 @@ export const sharePublicRoutes: FastifyPluginAsync = async (app) => {
6566
if (!file) return reply.code(404).send({ error: 'File not found' });
6667
if (file.encMode === 'ZK') return reply.code(400).send({ error: 'Unsupported' });
6768

68-
if (!isInline) {
69+
// Count a download once: on the request that starts at byte 0 (a video's later seek/range
70+
// requests, a resumed download or a cache revalidation are not new downloads).
71+
if (!isInline && req.method === 'GET' && startsAtBeginning(req) && !req.headers['if-none-match']) {
6972
// Count the download atomically and respect the cap under concurrency.
7073
const claimed = await prisma.shareLink.updateMany({
7174
where: {
@@ -78,11 +81,6 @@ export const sharePublicRoutes: FastifyPluginAsync = async (app) => {
7881
await audit(req, 'share.download', { actorId: null, target: share.id });
7982
}
8083

81-
const disposition = isInline ? 'inline' : 'attachment';
82-
reply
83-
.header('Content-Type', file.mimeType)
84-
.header('Content-Length', Number(file.sizeBytes))
85-
.header('Content-Disposition', `${disposition}; filename="${encodeURIComponent(file.name)}"`);
86-
return reply.send(decryptServerFile(app.ctx, file));
84+
return sendStoredFile(app.ctx, req, reply, file, { disposition: isInline ? 'inline' : 'attachment' });
8785
});
8886
};

‎apps/api/src/routes/spaces.ts‎

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,9 @@ import {
3838
type SpaceAccess,
3939
} from '../services/spaces.js';
4040
import { storeUserFile, QuotaExhaustedError } from '../services/upload.js';
41-
import { decryptServerFile } from '../services/download.js';
41+
import { sendStoredFile, startsAtBeginning } from '../services/stream.js';
42+
import { sendThumbnail } from '../services/thumbs.js';
43+
import { MEDIA_ROUTE } from '../lib/media-route.js';
4244
import { FileTooLargeError, InfectedFileError } from '../services/ingest.js';
4345

4446
export const spaceRoutes: FastifyPluginAsync = async (app) => {
@@ -392,21 +394,34 @@ export const spaceRoutes: FastifyPluginAsync = async (app) => {
392394
}
393395
});
394396

395-
// GET /spaces/:id/files/:fileId/download — decrypt and stream (any member).
396-
app.get('/:id/files/:fileId/download', async (req, reply) => {
397+
// GET /spaces/:id/files/:fileId/download — decrypt and stream (any member), with Range support.
398+
// `?inline=1` / `?preview=1` display in-page; a download is audited once (first byte), not per seek.
399+
app.get('/:id/files/:fileId/download', MEDIA_ROUTE, async (req, reply) => {
397400
const acc = await access(req, reply);
398401
if (!acc) return;
399402
const { fileId } = req.params as { fileId: string };
403+
const { preview, inline } = req.query as { preview?: string; inline?: string };
400404
const file = await prisma.fileObject.findFirst({
401405
where: { id: fileId, spaceId: acc.space.id, deletedAt: null },
402406
});
403407
if (!file) return reply.code(404).send({ error: 'File not found' });
404-
await audit(req, 'space.file.download', { target: file.id });
405-
reply
406-
.header('Content-Type', file.mimeType)
407-
.header('Content-Length', Number(file.sizeBytes))
408-
.header('Content-Disposition', `attachment; filename="${encodeURIComponent(file.name)}"`);
409-
return reply.send(decryptServerFile(app.ctx, file));
408+
if (preview !== '1' && req.method === 'GET' && startsAtBeginning(req) && !req.headers['if-none-match']) {
409+
await audit(req, 'space.file.download', { target: file.id });
410+
}
411+
const asInline = preview === '1' || inline === '1';
412+
return sendStoredFile(app.ctx, req, reply, file, { disposition: asInline ? 'inline' : 'attachment' });
413+
});
414+
415+
// GET /spaces/:id/files/:fileId/thumb — small cached WebP for image tiles (any member).
416+
app.get('/:id/files/:fileId/thumb', MEDIA_ROUTE, async (req, reply) => {
417+
const acc = await access(req, reply);
418+
if (!acc) return;
419+
const { fileId } = req.params as { fileId: string };
420+
const file = await prisma.fileObject.findFirst({
421+
where: { id: fileId, spaceId: acc.space.id, deletedAt: null },
422+
});
423+
if (!file) return reply.code(404).send({ error: 'File not found' });
424+
return sendThumbnail(app.ctx, req, reply, file);
410425
});
411426

412427
// PATCH /spaces/:id/files/:fileId — rename and/or move within the space (editor+).

‎apps/api/src/routes/webdav.ts‎

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,8 @@ import type { Readable } from 'node:stream';
1515
import type { FileObject, Folder } from '@prisma/client';
1616
import { prisma } from '../db.js';
1717
import { authenticateToken } from '../services/apiToken.js';
18-
import { decryptServerFile } from '../services/download.js';
18+
import { sendStoredFile } from '../services/stream.js';
19+
import { MEDIA_ROUTE } from '../lib/media-route.js';
1920
import { storeUserFile, QuotaExhaustedError } from '../services/upload.js';
2021
import { FileTooLargeError, InfectedFileError } from '../services/ingest.js';
2122
import { trashFile, trashFolder } from '../services/trash.js';
@@ -229,13 +230,9 @@ export const webdavRoutes: FastifyPluginAsync = async (app) => {
229230

230231
if (method === 'GET' || method === 'HEAD') {
231232
if (node.type !== 'file') return reply.code(node.type === 'folder' || node.type === 'root' ? 405 : 404).send();
232-
reply
233-
.header('Content-Type', node.file.mimeType)
234-
.header('Content-Length', Number(node.file.sizeBytes))
235-
.header('Last-Modified', node.file.createdAt.toUTCString())
236-
.header('Accept-Ranges', 'none');
237-
if (method === 'HEAD') return reply.send();
238-
return reply.send(decryptServerFile(app.ctx, node.file));
233+
// Range-capable: a video opened from the mounted drive (VLC, Explorer, Finder) can start and
234+
// seek immediately instead of copying the whole file first.
235+
return sendStoredFile(app.ctx, req, reply, node.file);
239236
}
240237

241238
if (method === 'PUT') {
@@ -338,7 +335,7 @@ export const webdavRoutes: FastifyPluginAsync = async (app) => {
338335
// HEAD is intentionally omitted: Fastify auto-creates a HEAD route from each GET route and
339336
// reuses this handler (which special-cases method === 'HEAD'). Registering HEAD explicitly
340337
// would collide with that auto route (FST_ERR_DUPLICATED_ROUTE on boot).
341-
app.route({ method: method as never, url: '/', handler: handle });
342-
app.route({ method: method as never, url: '/*', handler: handle });
338+
app.route({ method: method as never, url: '/', handler: handle, ...MEDIA_ROUTE });
339+
app.route({ method: method as never, url: '/*', handler: handle, ...MEDIA_ROUTE });
343340
}
344341
};

0 commit comments

Comments
 (0)