Files
puter/extensions/thumbnails.ts
T
Nariman Jelveh e62418f7a9 fix(thumbnails): files edited or written by apps get a thumbnail in the dashboard (#4691)
* fix(thumbnails): files edited or written by apps get a thumbnail in the dashboard

An overwrite clears a file's thumbnail and nothing made a new one, so a file
an app saved over lost its picture, and files apps created never had one.

The dashboard now makes a thumbnail for a file with none as its row comes
into view, with the upload thumbnail generator, within budgets on size,
downloads at a time, files per minute, and bytes per page load. A version
that gives no thumbnail is remembered so it isn't downloaded again.

/update-fsentry-thumbnail takes an optional expectedModified and refuses a
thumbnail made from an older version with 409, tells the owner's other
clients about the new thumbnail, and has its own rate-limit scope instead of
sharing the one opening a file uses. Overwrites and replacements emit
thumbnail.discarded, and the thumbnails extension deletes the object behind
it, so replaced thumbnails no longer stay in the bucket.

* fix(thumbnails): expectedModified must be a whole number of seconds the column can hold

A fraction or a value past the column's range reached the UPDATE, which
Postgres refuses with an error after the thumbnail was already uploaded.
The route now answers 400 before it uploads anything.

* fix(thumbnails): setting a thumbnail keeps the current one when the new one can't be stored

The route stored whatever the thumbnail.created listeners left behind:
a pointer whose upload failed, or the null left for an image that can't
be decoded. Either replaced a working thumbnail and answered 200. It now
answers 500 or 400 and leaves the entry as it was.

* fix(thumbnails): the update announced after setting a thumbnail carries the entry's current name and path

The event was built from the entry read before the thumbnail was
uploaded, so a rename or move that landed during the upload was
announced with the name and path it had just replaced, and open clients
put the row back on a path that no longer exists. The entry is read
again after the thumbnail is stored.

* fix(thumbnails): a file that stops needing a thumbnail is no longer downloaded for one

A file waiting its turn, or already downloading, was still read and its
thumbnail stored after another tab had made one, or after the file was
saved again as something the generator can't read. A queued file is now
checked again before its download starts, and a change that makes the
thumbnail unwanted drops the queued job and cancels the download.

* fix(thumbnails): refreshing the folder on screen keeps its thumbnail downloads

A refresh of the folder on screen (a sort, a view switch, an upload
finishing, coming back to the tab) cancelled the downloads under way.
The rows drawn right after were skipped, because their files still
counted as being tried, so they stayed without a thumbnail until some
later render. The rest were downloaded again from the start.

A download is now cancelled only if its file's row isn't drawn again in
the same task, and the new row takes it over. A row that comes back
while a cancelled download is still ending is queued again.

* fix(thumbnails): a stored thumbnail is recorded on the row's own entry

The filler handed its callback a copy of the row's entry, so the
thumbnail was written to an object nothing else reads, and the row's
entry kept saying the file had none. It now passes the row's entry, and
skips a row whose file was saved again while the thumbnail was being
stored, which would otherwise show the older version's picture.

* fix(thumbnails): the download budget counts the bytes that were downloaded

A cancelled download gave its whole size back to the page's download
budget, though the bytes it had received were already billed as egress.
A file saved over and over while its row was on screen could be started
again each time, well past the budget. A download the server refused
kept its size charged with nothing downloaded.

The file is now read as a stream and the budget is charged what arrived.
Reading also stops as soon as a file turns out to be over the size cap,
where before a file larger than its listed size was buffered whole.

* fix(thumbnails): a thumbnail download that fails to connect is tried again

A download that failed on the network counted as tried, so the file went
without a thumbnail for the rest of the page load. A laptop waking before
its Wi-Fi is back marked every row on screen that way. A failed
connection now pauses the filler like a 429 does, and the file is tried
again after the pause.

* fix(thumbnails): a thumbnail that couldn't be stored yet is sent again, not made again

When storing a thumbnail got a 429, the file was queued again and
downloaded a second time after the pause. When the request failed to
connect, the thumbnail was dropped and the file went without one. The
thumbnail is now kept with the queued job and sent again after the
pause, as long as the file is still at the version it shows.

* fix(thumbnails): a file whose thumbnail the server refuses isn't downloaded again on every page load

When the server answers 400 for a thumbnail, the file's version is now
remembered like one that gave no thumbnail at all. It counted as tried
for the page load only, so each later page load downloaded the file and
sent the same image again.

* fix(thumbnails): only pictures a browser can draw are downloaded for a thumbnail

Any file typed image/ counted as one the generator reads, so TIFF scans,
CAD drawings, DjVu books and the like were each downloaded in full, up
to 20 MiB, to make a thumbnail no browser can draw. A file is now
downloaded only when its type or name is one browsers decode. Uploads
are unchanged: the generator still tries any image there, where the file
is already local.

* fix(thumbnails): missing thumbnails are downloaded one file at a time

Each download holds one of the account's concurrent file reads until it
ends. Two at a time left a temporary account, which has three, a single
read for everything its apps do, so an app reading two files at once got
a 429 while a folder's thumbnails were being filled in. The per-minute
cap of 20 files already bounds how fast they're made.

* fix(thumbnails): an update refreshes the icon of every item it matches

An update can match the Files row and the same item in a file dialog
open over the dashboard. The row updater set the new thumbnail on the
first match only, where it used to set it on all of them.

* perf(thumbnails): an update works out a row's icon again only when its thumbnail changed

Every update event carries a thumbnail key, so the row updater worked
out the icon on each one. For a .app file or a web link that reads the
file, once per event. The icon is now refreshed only when the event's
thumbnail differs from the one the row has.

* perf(thumbnails): drawing a large folder doesn't rescan the thumbnail queue for every row

Each row handed to the filler went through every row queued before it,
looking for a job to start, so drawing a folder of files without
thumbnails took the square of its length: about a second for 20,000
rows. A row that isn't on screen yet has nothing to start, so the queue
is now only gone through when a row is reported on screen, a job ends,
or a wait is over.

* fix(thumbnails): one tab no longer drops the failed files another tab remembered

Each tab read the list of files that gave no thumbnail once, then wrote
its own copy back whole on every addition, which dropped whatever
another tab had added in between. Those files were downloaded again on
a later page load. The stored list is now read again and merged before
each write.

* perf(thumbnails): files downloaded for a thumbnail stay out of the browser's HTTP cache

The download asked the cache to revalidate, which still writes each
response to it, up to 100 MiB of originals per page load that nothing
reads back. The read route doesn't answer conditional requests, so a
cached copy could never save a download either.

* bench(thumbnails): scenario for setting a file's thumbnail from the dashboard

The dashboard calls the route for each file it fills in a thumbnail
for, up to 20 a minute, so its round trips are measured from here on.

* docs(thumbnails): list the picture formats downloaded for a missing thumbnail

* perf(thumbnails): setting a thumbnail reads the entry again alongside the write, not after it

The read that keeps the announced name and path current ran after the
update, which added a serial round trip to the route. It now runs with
the update. The window it closes is the upload before both.

* feat(thumbnails): a file saved over keeps showing its old thumbnail until the new one is ready

A save cleared the row to its type icon for the few seconds it takes to
make the new thumbnail, so a file an app saves repeatedly flashed
between the two. The row now keeps the old thumbnail while a new one is
on its way.

It goes back to the type icon at once when no thumbnail will be made
(the file is too large, the download budget is spent, the filler is
paused), as soon as the attempt fails, and after 10 seconds at most,
counted from the first save, so an old picture can't stay on a file
that keeps changing.

* fix(thumbnails): a document gets its thumbnail when the view goes to the list and back while it's made

A list row shows a document's type icon, so switching to the list gave up
on the thumbnail being made for it. Switching back before that ended found
the version already tried and queued nothing, and the row kept its type
icon until the folder was drawn again. The row now takes the job back.

* fix(thumbnails): a file being saved waits to settle whatever the computer's clock says

The wait before a saved file is downloaded was measured from its modified
time, which the server sets, against the browser's clock. On a computer
whose clock runs a few seconds ahead the wait came out as zero, so every
save of a file an app keeps saving started a download that the next save
cancelled. A file an update just arrived for now waits at least two
seconds, the least it waits when the clocks agree.

* fix(thumbnails): an item in a file dialog gets a new thumbnail when its folder isn't the one on screen

The row updater only set a thumbnail through the entry a Files row
carries. An update for a file shown only in a file dialog, with another
folder open in Files, matched an item that has no entry, and the item
kept the picture it had.

* refactor(thumbnails): the row observer asks for no margin around the screen

The 200px margin never took effect. The rows scroll inside the listing's
own pane, and a margin on the viewport doesn't widen what that pane clips,
so a row was only ever reported once it was on screen. That's also what
the download budget is written for, so the option goes rather than being
made to work.

* test(thumbnails): a version tried once, a hidden tab, and a browser saving data

Three of the filler's cost guards had no test: a version whose thumbnail
the server turned away isn't downloaded again in the page load, nothing
starts while the tab is hidden, and nothing is downloaded when the
browser asks to use less data.
2026-11-18 18:58:43 -07:00

587 lines
21 KiB
TypeScript

import {
DeleteObjectCommand,
GetObjectCommand,
HeadObjectCommand,
PutObjectCommand,
S3Client,
} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { extension } from '@heyputer/backend/src/extensions';
import type { FSEntryStore } from '@heyputer/backend/src/stores/fs/FSEntryStore';
import { isMissingObjectError } from '@heyputer/backend/src/stores/fs/S3ObjectStore';
import { BoundedTtlMap } from '@heyputer/backend/src/util/boundedTtlMap.js';
import crypto from 'node:crypto';
import type { Readable } from 'node:stream';
import sharp from 'sharp';
const clients = extension.import('client');
const stores = extension.import('store');
type ThumbnailEntryStore = Pick<FSEntryStore, 'updateEntryThumbnailByUuid'>;
const MAX_THUMBNAIL_BYTES = 2 * 1024 * 1024;
const MAX_THUMBNAIL_PIXELS = 64e6;
// Namespace every object this extension writes. An fs object's key is its
// bare fsentry uuid and the default config points `thumbnailStore.name` at
// the same bucket as `s3_bucket`, so without a prefix of our own there is no
// way to tell a thumbnail we minted from any other object in the deployment.
const THUMBNAIL_KEY_PREFIX = 'thumbnails/';
const UUID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const isUuid = (value: unknown): value is string =>
typeof value === 'string' && UUID_PATTERN.test(value);
// `thumbnails/<entry uuid>/<random uuid>`: the entry segment binds the object
// to the entry it was minted for, which is what writes and deletes check.
const mintThumbnailKey = (entryUuid: string): string =>
`${THUMBNAIL_KEY_PREFIX}${entryUuid}/${crypto.randomUUID()}`;
/**
* Extract the object key from a stored thumbnail pointer, or null when the
* pointer isn't one this extension minted.
*
* `fsentries.thumbnail` is writable through the FS API, so neither half of the
* stored string is trusted: the bucket is discarded (callers always pass their
* own) and the key must sit under {@link THUMBNAIL_KEY_PREFIX} as either
* `<uuid>` (minted before keys were bound to entries) or `<entry uuid>/<uuid>`.
* Honouring an arbitrary key would lend this extension's storage credentials to
* whatever object the caller named — in the shared-bucket layout that is every
* user's file, since an fs object's key is its fsentry uuid. Bare-uuid keys
* from before the prefix fail the check and are treated as absent; they are
* indistinguishable from a planted pointer, so there is nothing safer to do
* with them than stop signing them.
*/
const resolveThumbnailKey = (pointer: string): string | null => {
let key: string;
if (pointer.startsWith('s3://')) {
const rest = pointer.slice('s3://'.length);
const slash = rest.indexOf('/');
if (slash === -1) return null;
key = rest.slice(slash + 1);
} else {
let pathname: string;
try {
pathname = new URL(pointer).pathname;
} catch {
return null;
}
const segments = pathname.replace(/^\/+/, '').split('/');
segments.shift(); // bucket
key = segments.join('/');
}
if (!key.startsWith(THUMBNAIL_KEY_PREFIX)) return null;
const segments = key.slice(THUMBNAIL_KEY_PREFIX.length).split('/');
return segments.length <= 2 && segments.every(isUuid) ? key : null;
};
// The entry a resolved key was minted for. Null for an unbound key, whose
// holder can't be told apart from a row that copied or planted the pointer.
const thumbnailKeyOwner = (key: string): string | null => {
const segments = key.slice(THUMBNAIL_KEY_PREFIX.length).split('/');
return segments.length === 2 ? segments[0] : null;
};
// Whether a stored thumbnail names an object in our storage. Anything else is
// an external image URL the client supplied: shown as given, never copied or
// deleted.
const isStoragePointer = (pointer: string, bucketEndpoint: string): boolean =>
pointer.startsWith('s3://') ||
// Legacy format — remove after full migration
(pointer.startsWith('https') &&
pointer.includes(new URL(bucketEndpoint).hostname));
// S3 client + bucket config — lazily resolved after boot from config.
let s3Client: S3Client | null = null;
let s3PresignClient: S3Client | null = null;
let thumbnailBucketName = 'puter-local';
let extensionBucketEndpoint = 'http://127.0.0.1:4566/puter-local/';
function resolveClients(): { send: S3Client; presign: S3Client } {
if (s3Client && s3PresignClient) {
return { send: s3Client, presign: s3PresignClient };
}
// Top-level `thumbnailStore` config when the extension should use a
// dedicated S3 bucket instead of the main one.
const thumbStore = extension.config.thumbnailStore;
if (thumbStore?.endpoint && thumbStore.credentials) {
s3Client = new S3Client({
region: 'auto',
endpoint: thumbStore.endpoint,
credentials: thumbStore.credentials,
});
// Dedicated thumbnail buckets use a single endpoint for both
// server-side ops and browser-facing presigned URLs.
s3PresignClient = s3Client;
thumbnailBucketName = thumbStore.name ?? 'puter-local';
extensionBucketEndpoint = thumbStore.endpoint;
} else {
// Fall back to the project's S3 wrapper. `clients.s3` is the Puter
// `S3Client` wrapper (region-cache + lifecycle), not an AWS
// `S3Client`. `.get()` is for server-side ops (uses the internal
// `endpoint`); `.getForPresign()` is for browser-facing presigned
// URLs (uses `publicEndpoint` when configured — required for
// self-host where the docker-internal endpoint isn't reachable
// from the browser).
const wrapper = clients.s3;
s3Client = wrapper.get();
s3PresignClient = wrapper.getForPresign();
}
return { send: s3Client, presign: s3PresignClient };
}
function getClient(): S3Client {
return resolveClients().send;
}
function getPresignClient(): S3Client {
return resolveClients().presign;
}
// Strictly decode a data: URL and validate the decoded image. Encoded-string
// length lies about decoded byte count (whitespace, padding) and says nothing
// about pixel count — a 2MB PNG can decompress to hundreds of MB of raster.
async function decodeAndValidateThumbnail(
dataURL: string,
): Promise<{ mimeType: string; data: Buffer } | null> {
const commaIdx = dataURL.indexOf(',');
if (commaIdx === -1) return null;
const mimeType = dataURL.slice(5, commaIdx).split(';')[0];
const data = Buffer.from(dataURL.slice(commaIdx + 1), 'base64');
if (data.length === 0 || data.length > MAX_THUMBNAIL_BYTES) return null;
try {
await sharp(data, {
limitInputPixels: MAX_THUMBNAIL_PIXELS,
density: 72,
failOn: 'error',
}).metadata();
} catch {
return null;
}
return { mimeType, data };
}
// A storage pointer a client hands back after a presigned upload is kept only
// if it names a key minted for this entry and an object within the size bound.
async function vetUploadedThumbnail(
pointer: string,
entryUuid: unknown,
deps: { s3: S3Client; bucketName: string },
): Promise<string | null> {
const key = resolveThumbnailKey(pointer);
if (!key || thumbnailKeyOwner(key) !== entryUuid) return null;
let size: number | undefined;
try {
const head = await deps.s3.send(
new HeadObjectCommand({ Bucket: deps.bucketName, Key: key }),
);
size = head.ContentLength;
} catch (err) {
if (!isMissingObjectError(err)) {
console.warn(
'[thumbnails] failed to check uploaded thumbnail',
err,
);
}
return null;
}
if (typeof size !== 'number') return null;
if (size > MAX_THUMBNAIL_BYTES) {
// Only reachable on a store that doesn't enforce the signed length.
// The key is this entry's own, so removing it is safe.
try {
await deps.s3.send(
new DeleteObjectCommand({ Bucket: deps.bucketName, Key: key }),
);
} catch (err) {
console.warn(
'[thumbnails] failed to remove oversized thumbnail',
err,
);
}
return null;
}
return `s3://${deps.bucketName}/${key}`;
}
// -- thumbnail.created -----------------------------------------------
// Intercept data-URL thumbnails before they hit the DB: upload to S3
// and replace the URL with an s3:// pointer bound to the entry.
export async function handleThumbnailCreated(
event: Record<string, unknown>,
deps: { s3: S3Client; bucketName: string; bucketEndpoint: string },
): Promise<void> {
const url = event.url;
if (typeof url !== 'string') return;
if (!url.startsWith('data:')) {
if (isStoragePointer(url, deps.bucketEndpoint)) {
event.url = await vetUploadedThumbnail(url, event.uuid, deps);
}
return;
}
const entryUuid = event.uuid;
if (!isUuid(entryUuid)) {
event.url = null;
return;
}
const decoded = await decodeAndValidateThumbnail(url);
if (!decoded) {
event.url = null;
return;
}
const key = mintThumbnailKey(entryUuid);
event.url = `s3://${deps.bucketName}/${key}`;
await deps.s3.send(
new PutObjectCommand({
Bucket: deps.bucketName,
Key: key,
Body: decoded.data,
ContentType: decoded.mimeType,
}),
);
}
export const handleThumbnailUploadPrepare = async (
event: Record<string, unknown>,
deps: { s3Presign: S3Client; bucketName: string },
): Promise<void> => {
if (!event || !Array.isArray(event.items)) return;
const presignClient = deps.s3Presign;
for (const item of event.items as Array<Record<string, unknown>>) {
if (!item || typeof item !== 'object') {
throw new Error('thumbnail.upload.prepare item is invalid');
}
const contentType =
typeof item.contentType === 'string' ? item.contentType.trim() : '';
if (!contentType) continue;
const size = item.size;
if (
typeof size !== 'number' ||
!Number.isInteger(size) ||
size < 0 ||
size > MAX_THUMBNAIL_BYTES
)
continue;
if (!isUuid(item.item_uid)) continue;
const key = mintThumbnailKey(item.item_uid);
const command = new PutObjectCommand({
Bucket: deps.bucketName,
Key: key,
ContentType: contentType,
// Signing covers `content-length`, so a body of any other size
// fails the signature instead of landing.
ContentLength: size,
});
item.uploadUrl = await getSignedUrl(presignClient, command, {
expiresIn: 900,
});
item.thumbnailUrl = `s3://${deps.bucketName}/${key}`;
}
};
const SIGNING_PERIOD_MS = 3_600_000;
const SIGNED_URL_CACHE_ENTRIES = 5_000;
// Read URLs signed this hour, per signing client. A URL is the same all hour,
// so a repeat listing reuses it; the key names the signing key too, so a
// credential rotation signs afresh.
const signedReadUrls = new WeakMap<S3Client, BoundedTtlMap<string, string>>();
const signThumbnailRead = async (
client: S3Client,
bucket: string,
key: string,
): Promise<string> => {
// Registered before any await, so a listing's concurrent signings share it.
let cache = signedReadUrls.get(client);
if (!cache) {
cache = new BoundedTtlMap({
maxEntries: SIGNED_URL_CACHE_ENTRIES,
ttlMs: SIGNING_PERIOD_MS,
});
signedReadUrls.set(client, cache);
}
const period = Math.floor(Date.now() / SIGNING_PERIOD_MS);
const { accessKeyId } = await client.config.credentials();
const cacheKey = `${accessKeyId}\0${period}\0${bucket}\0${key}`;
const cached = cache.get(cacheKey);
if (cached) return cached;
const url = await getSignedUrl(
client,
new GetObjectCommand({ Bucket: bucket, Key: key }),
{
expiresIn: 604800,
signingDate: new Date(period * SIGNING_PERIOD_MS),
},
);
cache.set(cacheKey, url);
return url;
};
export const handleThumbnailRead = async (
entry: Record<string, unknown>,
deps: {
s3: S3Client;
s3Presign: S3Client;
bucketName: string;
bucketEndpoint: string;
fsEntry: ThumbnailEntryStore;
},
): Promise<void> => {
const thumb = entry.thumbnail;
if (typeof thumb !== 'string' || !thumb) return;
const presignClient = deps.s3Presign;
if (isStoragePointer(thumb, deps.bucketEndpoint)) {
const key = resolveThumbnailKey(thumb);
if (!key) {
// Not a pointer we minted — refuse to sign it rather than hand
// out a presigned read of whatever object it names.
entry.thumbnail = null;
return;
}
entry.thumbnail = await signThumbnailRead(
presignClient,
deps.bucketName,
key,
);
} else if (thumb.startsWith('data')) {
// Move an inline thumbnail into storage. The row only takes the new
// pointer while it still holds this data URL, so of concurrent reads
// one wins and the rest discard their upload.
const uuid = entry.uuid ?? entry.uid;
if (!isUuid(uuid)) return;
// Same bar as an upload; anything else stays inline, unmigrated.
const decoded = await decodeAndValidateThumbnail(thumb);
if (!decoded) return;
const key = mintThumbnailKey(uuid);
await deps.s3.send(
new PutObjectCommand({
Bucket: deps.bucketName,
Key: key,
Body: decoded.data,
ContentType: decoded.mimeType,
}),
);
let migrated: boolean;
try {
migrated = await deps.fsEntry.updateEntryThumbnailByUuid(
uuid,
`s3://${deps.bucketName}/${key}`,
{ thumbnail: thumb },
);
} catch (err) {
// The row may or may not point at the object now, so keep it.
console.warn('[thumbnails] inline migration failed', err);
return;
}
if (!migrated) {
try {
await deps.s3.send(
new DeleteObjectCommand({
Bucket: deps.bucketName,
Key: key,
}),
);
} catch (err) {
console.warn(
'[thumbnails] failed to remove unused thumbnail',
err,
);
}
return;
}
entry.thumbnail = await signThumbnailRead(
presignClient,
deps.bucketName,
key,
);
}
};
export const handleFsCopyNodeThumbnail = async (
payload: { copy?: { thumbnail?: string | null; uuid?: string } | null },
deps: {
s3: S3Client;
bucketName: string;
bucketEndpoint: string;
fsEntry: ThumbnailEntryStore;
},
): Promise<void> => {
const copy = payload.copy;
const thumbnailUrl = copy?.thumbnail;
if (!copy || !isUuid(copy.uuid) || typeof thumbnailUrl !== 'string') return;
if (!isStoragePointer(thumbnailUrl, deps.bucketEndpoint)) return;
// Same trust rule as the read and remove paths: only touch objects this
// extension minted.
const sourceKey = resolveThumbnailKey(thumbnailUrl);
if (!sourceKey) return;
// The copied row points at the SAME object as its source. Give the copy
// an object of its own, bound to it, so removing either entry leaves the
// other's thumbnail alone.
const newKey = mintThumbnailKey(copy.uuid);
try {
// Nothing larger than an upload may produce gets duplicated; such an
// object came in through an unbounded upload URL.
const head = await deps.s3.send(
new HeadObjectCommand({ Bucket: deps.bucketName, Key: sourceKey }),
);
if (
typeof head.ContentLength !== 'number' ||
head.ContentLength > MAX_THUMBNAIL_BYTES
) {
throw new Error('thumbnail exceeds the size bound');
}
// Read and rewrite rather than CopyObject: a copy source skips any path
// in the client's endpoint, so it can miss an object Bucket/Key reach.
const source = await deps.s3.send(
new GetObjectCommand({ Bucket: deps.bucketName, Key: sourceKey }),
);
// The object can be replaced after the HEAD; bound what gets buffered.
if ((source.ContentLength ?? 0) > MAX_THUMBNAIL_BYTES) {
(source.Body as Readable | undefined)?.destroy();
throw new Error('thumbnail exceeds the size bound');
}
const body = await source.Body?.transformToByteArray();
if (!body) throw new Error('thumbnail has no body');
await deps.s3.send(
new PutObjectCommand({
Bucket: deps.bucketName,
Key: newKey,
Body: body,
ContentType: source.ContentType,
}),
);
} catch (err) {
// The shared object is gone or oversized — drop the pointer rather
// than leave the row advertising a thumbnail it doesn't have.
await deps.fsEntry.updateEntryThumbnailByUuid(copy.uuid, null);
console.warn('[thumbnails] failed to duplicate thumbnail on copy', err);
return;
}
await deps.fsEntry.updateEntryThumbnailByUuid(
copy.uuid,
`s3://${deps.bucketName}/${newKey}`,
);
};
export const handleFsRemoveNodeThumbnail = async (
payload: { target: { thumbnail?: string | null; uuid?: string } },
deps: { s3: S3Client; bucketName: string; bucketEndpoint: string },
): Promise<void> => {
const { thumbnail: thumbnailUrl, uuid } = payload.target;
if (!thumbnailUrl || !isStoragePointer(thumbnailUrl, deps.bucketEndpoint))
return;
// The pointer decides which object gets deleted, and a key is visible to
// anyone who can list the entry holding it. Only a key minted for this
// entry is deleted; an unbound one may be shared or planted, so it stays.
const key = resolveThumbnailKey(thumbnailUrl);
if (!key || thumbnailKeyOwner(key) !== uuid) return;
await deps.s3.send(
new DeleteObjectCommand({ Bucket: deps.bucketName, Key: key }),
);
};
extension.on(
'thumbnail.created',
async (_key, event: Record<string, unknown>) => {
await handleThumbnailCreated(event, {
s3: getClient(),
bucketName: thumbnailBucketName,
bucketEndpoint: extensionBucketEndpoint,
});
},
);
// -- thumbnail.upload.prepare ----------------------------------------
// Generate pre-signed upload URLs so the client can PUT directly to S3.
extension.on(
'thumbnail.upload.prepare',
async (_key, event: Record<string, unknown>) => {
await handleThumbnailUploadPrepare(event, {
s3Presign: getPresignClient(),
bucketName: thumbnailBucketName,
});
},
);
// -- thumbnail.read --------------------------------------------------
// Convert s3:// or legacy https:// thumbnails to signed URLs.
extension.on('thumbnail.read', async (_key, entry: Record<string, unknown>) => {
await handleThumbnailRead(entry, {
s3: getClient(),
s3Presign: getPresignClient(),
bucketName: thumbnailBucketName,
bucketEndpoint: extensionBucketEndpoint,
fsEntry: stores.fsEntry,
});
});
// -- fs.copy.node ----------------------------------------------------
// A copied entry initially shares its source's thumbnail object; duplicate
// it so removing either entry can't break the other's thumbnail.
extension.on('fs.copy.node', async (_key, payload) => {
await handleFsCopyNodeThumbnail(
payload as {
copy?: { thumbnail?: string | null; uuid?: string } | null;
},
{
s3: getClient(),
bucketName: thumbnailBucketName,
bucketEndpoint: extensionBucketEndpoint,
fsEntry: stores.fsEntry,
},
);
});
// -- fs.remove.node --------------------------------------------------
// Delete S3 thumbnail when the file is removed.
extension.on('fs.remove.node', async (_key, payload) => {
await handleFsRemoveNodeThumbnail(payload, {
s3: getClient(),
bucketName: thumbnailBucketName,
bucketEndpoint: extensionBucketEndpoint,
});
});
// -- thumbnail.discarded ---------------------------------------------
// An overwrite or a newer thumbnail replaced this one; delete its object.
extension.on('thumbnail.discarded', async (_key, { uuid, url }) => {
await handleFsRemoveNodeThumbnail(
{ target: { uuid, thumbnail: url } },
{
s3: getClient(),
bucketName: thumbnailBucketName,
bucketEndpoint: extensionBucketEndpoint,
},
);
});