mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-25 22:27:32 +00:00
feat(photos): a photo keeps its quality signals, measured once off the event loop
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { TrekPhotoSignalsRepository } from '../repositories/TrekPhotoSignals.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { TrekPhotos } from './TrekPhotos.entity';
|
||||
|
||||
export class TrekPhotoSignals {
|
||||
[EntityRepositoryType]?: TrekPhotoSignalsRepository;
|
||||
id!: number & Opt;
|
||||
photo!: Ref<TrekPhotos>;
|
||||
photo_id!: number;
|
||||
algo!: number;
|
||||
phash?: string | null;
|
||||
sharpness?: number | null;
|
||||
luma?: number | null;
|
||||
clipped?: number | null;
|
||||
orig_width?: number | null;
|
||||
orig_height?: number | null;
|
||||
computed_at!: string & Opt;
|
||||
}
|
||||
|
||||
export const TrekPhotoSignalsSchema = defineEntity({
|
||||
class: TrekPhotoSignals,
|
||||
repository: () => TrekPhotoSignalsRepository,
|
||||
uniques: [{ properties: ['photo'] }],
|
||||
properties: {
|
||||
id: p.integer().primary(),
|
||||
photo: () => p.manyToOne(TrekPhotos).ref().deleteRule('cascade').hidden(),
|
||||
photo_id: p.integer().persist(false),
|
||||
algo: p.integer(),
|
||||
phash: p.text().nullable(),
|
||||
sharpness: p.double().nullable(),
|
||||
luma: p.double().nullable(),
|
||||
clipped: p.double().nullable(),
|
||||
orig_width: p.integer().nullable(),
|
||||
orig_height: p.integer().nullable(),
|
||||
computed_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p }
|
||||
import { TrekPhotosRepository } from '../repositories/TrekPhotos.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { JourneyPhotos } from './JourneyPhotos.entity';
|
||||
import { TrekPhotoSignals } from './TrekPhotoSignals.entity';
|
||||
import { TripPhotos } from './TripPhotos.entity';
|
||||
import { Users } from './Users.entity';
|
||||
|
||||
@@ -24,6 +25,7 @@ export class TrekPhotos {
|
||||
lat?: number | null;
|
||||
lng?: number | null;
|
||||
journey_photos_collection = new Collection<JourneyPhotos>(this);
|
||||
trek_photo_signals_collection = new Collection<TrekPhotoSignals>(this);
|
||||
trip_photos_collection = new Collection<TripPhotos>(this);
|
||||
}
|
||||
|
||||
@@ -62,6 +64,7 @@ export const TrekPhotosSchema = defineEntity({
|
||||
lat: p.double().nullable(),
|
||||
lng: p.double().nullable(),
|
||||
journey_photos_collection: () => p.oneToMany(JourneyPhotos).mappedBy('photo').hidden(),
|
||||
trek_photo_signals_collection: () => p.oneToMany(TrekPhotoSignals).mappedBy('photo').hidden(),
|
||||
trip_photos_collection: () => p.oneToMany(TripPhotos).mappedBy('photo').hidden(),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -129,6 +129,7 @@ import { TourTypesSchema } from './TourTypes.entity';
|
||||
import { TourWaypointsSchema } from './TourWaypoints.entity';
|
||||
import { ToursSchema } from './Tours.entity';
|
||||
import { TrekPhotoCacheMetaSchema } from './TrekPhotoCacheMeta.entity';
|
||||
import { TrekPhotoSignalsSchema } from './TrekPhotoSignals.entity';
|
||||
import { TrekPhotosSchema } from './TrekPhotos.entity';
|
||||
import { TripAlbumLinksSchema } from './TripAlbumLinks.entity';
|
||||
import { TripDocumentLinksSchema } from './TripDocumentLinks.entity';
|
||||
@@ -289,6 +290,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
|
||||
TourWaypointsSchema,
|
||||
ToursSchema,
|
||||
TrekPhotoCacheMetaSchema,
|
||||
TrekPhotoSignalsSchema,
|
||||
TrekPhotosSchema,
|
||||
TripAlbumLinksSchema,
|
||||
TripDocumentLinksSchema,
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
|
||||
// change the migration, then run `npm run gen:db-types`.
|
||||
import type { InsertOptional } from './columns';
|
||||
|
||||
export interface TrekPhotoSignalsTable {
|
||||
id: InsertOptional<number>;
|
||||
photo_id: number;
|
||||
algo: number;
|
||||
phash: InsertOptional<string | null>;
|
||||
sharpness: InsertOptional<number | null>;
|
||||
luma: InsertOptional<number | null>;
|
||||
clipped: InsertOptional<number | null>;
|
||||
orig_width: InsertOptional<number | null>;
|
||||
orig_height: InsertOptional<number | null>;
|
||||
computed_at: InsertOptional<string>;
|
||||
}
|
||||
@@ -135,6 +135,7 @@ import type { TourTypesTable } from './TourTypes.table';
|
||||
import type { TourWaypointsTable } from './TourWaypoints.table';
|
||||
import type { ToursTable } from './Tours.table';
|
||||
import type { TrekPhotoCacheMetaTable } from './TrekPhotoCacheMeta.table';
|
||||
import type { TrekPhotoSignalsTable } from './TrekPhotoSignals.table';
|
||||
import type { TrekPhotosTable } from './TrekPhotos.table';
|
||||
import type { TripAlbumLinksTable } from './TripAlbumLinks.table';
|
||||
import type { TripDocumentLinksTable } from './TripDocumentLinks.table';
|
||||
@@ -301,6 +302,7 @@ export interface DB {
|
||||
tour_waypoints: TourWaypointsTable;
|
||||
tours: ToursTable;
|
||||
trek_photo_cache_meta: TrekPhotoCacheMetaTable;
|
||||
trek_photo_signals: TrekPhotoSignalsTable;
|
||||
trek_photos: TrekPhotosTable;
|
||||
trip_album_links: TripAlbumLinksTable;
|
||||
trip_document_links: TripDocumentLinksTable;
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
/**
|
||||
* What a photo's pixels say, measured once so the assistant can pick photos
|
||||
* for a TREK Studio book without looking at them: a perceptual hash (`phash`,
|
||||
* 64 bits as 16 hex digits) to find near duplicates, how sharp it is
|
||||
* (`sharpness`, the variance of a Laplacian over the grey image), its mean
|
||||
* brightness (`luma`, 0 to 1) and the share of its pixels that are burnt out
|
||||
* or crushed black (`clipped`, 0 to 1), and the original's size in pixels
|
||||
* (`orig_width`, `orig_height`) for the print check.
|
||||
*
|
||||
* `algo` is the version of the measurement a row was made with, so a better
|
||||
* one later measures again instead of mixing the two. A null signal is one
|
||||
* that could not be measured (a format TREK cannot decode, a photo too large to
|
||||
* read), which is an answer too: the photo is not measured again.
|
||||
*
|
||||
* One row per photo, `photo_id UNIQUE` beside its own id rather than the photo
|
||||
* id as key: a key that is also a foreign key maps to a one-to-one on both
|
||||
* entities (see `trip_journal_links`). The row goes with its photo.
|
||||
*/
|
||||
export class Migration20200101046240_a_photo_keeps_its_quality_signals extends Migration {
|
||||
override name = 'Migration20200101046240_a_photo_keeps_its_quality_signals';
|
||||
|
||||
override up(): void {
|
||||
this.addSql(`
|
||||
CREATE TABLE IF NOT EXISTS trek_photo_signals (
|
||||
id INTEGER PRIMARY KEY,
|
||||
photo_id INTEGER NOT NULL UNIQUE REFERENCES trek_photos(id) ON DELETE CASCADE,
|
||||
algo INTEGER NOT NULL,
|
||||
phash TEXT,
|
||||
sharpness REAL,
|
||||
luma REAL,
|
||||
clipped REAL,
|
||||
orig_width INTEGER,
|
||||
orig_height INTEGER,
|
||||
computed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { TrekPhotoSignals } from '../entities/TrekPhotoSignals.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { dbNow } from '../types';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
type SignalsDB = Pick<DB, 'trek_photo_signals' | 'trek_photos' | 'journey_photos'>;
|
||||
|
||||
/** What one measurement of a photo found; a null is a signal that could not be measured. */
|
||||
export interface TrekPhotoSignalWrite {
|
||||
photo_id: number;
|
||||
algo: number;
|
||||
phash: string | null;
|
||||
sharpness: number | null;
|
||||
luma: number | null;
|
||||
clipped: number | null;
|
||||
orig_width: number | null;
|
||||
orig_height: number | null;
|
||||
}
|
||||
|
||||
/** A stored measurement, with when it was made. */
|
||||
export interface TrekPhotoSignalRow extends TrekPhotoSignalWrite {
|
||||
computed_at: string;
|
||||
}
|
||||
|
||||
/** A photo of a journey's gallery as the photo picker reads it: no bytes, no paths. */
|
||||
export interface GalleryPhotoFacts {
|
||||
photo_id: number;
|
||||
caption: string | null;
|
||||
provider: string;
|
||||
media_type: string;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
taken_at: string | null;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
}
|
||||
|
||||
/** SQLite binds at most so many values per statement; a gallery can hold more photos. */
|
||||
const IN_CHUNK = 400;
|
||||
|
||||
/**
|
||||
* `trek_photo_signals`: what a photo's pixels say, one row per photo, written
|
||||
* by `PhotoSignalsService` once its worker has measured the photo and read
|
||||
* again whenever photos are picked for a book. A new measurement of a photo
|
||||
* replaces the old one (upsert on `photo_id`).
|
||||
*/
|
||||
export class TrekPhotoSignalsRepository extends TrekRepository<TrekPhotoSignals> {
|
||||
private db() {
|
||||
return this.kysely<SignalsDB>();
|
||||
}
|
||||
|
||||
/** The measurements stored for these photos, whatever version made them; a photo without one is left out. */
|
||||
async listForPhotos(photoIds: number[]): Promise<TrekPhotoSignalRow[]> {
|
||||
const out: TrekPhotoSignalRow[] = [];
|
||||
for (let i = 0; i < photoIds.length; i += IN_CHUNK) {
|
||||
const rows = await this.db()
|
||||
.selectFrom('trek_photo_signals')
|
||||
.select([
|
||||
'photo_id',
|
||||
'algo',
|
||||
'phash',
|
||||
'sharpness',
|
||||
'luma',
|
||||
'clipped',
|
||||
'orig_width',
|
||||
'orig_height',
|
||||
'computed_at',
|
||||
])
|
||||
.where('photo_id', 'in', photoIds.slice(i, i + IN_CHUNK))
|
||||
.execute();
|
||||
out.push(...rows);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Stores a measurement, replacing the photo's earlier one. */
|
||||
async saveSignals(row: TrekPhotoSignalWrite): Promise<void> {
|
||||
const computedAt = dbNow();
|
||||
await this.db()
|
||||
.insertInto('trek_photo_signals')
|
||||
.values({ ...row, computed_at: computedAt })
|
||||
.onConflict((oc) =>
|
||||
oc.column('photo_id').doUpdateSet({
|
||||
algo: row.algo,
|
||||
phash: row.phash,
|
||||
sharpness: row.sharpness,
|
||||
luma: row.luma,
|
||||
clipped: row.clipped,
|
||||
orig_width: row.orig_width,
|
||||
orig_height: row.orig_height,
|
||||
computed_at: computedAt,
|
||||
}),
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* The photos of a journey's gallery with what their rows know about them
|
||||
* (capture time and place, size, kind), in gallery order. The size is a
|
||||
* thumbnail's for an uploaded photo and none for a provider's: good for the
|
||||
* shape, never for print.
|
||||
*/
|
||||
async listGalleryFacts(journeyId: number): Promise<GalleryPhotoFacts[]> {
|
||||
return await this.db()
|
||||
.selectFrom('journey_photos as gp')
|
||||
.innerJoin('trek_photos as tp', 'tp.id', 'gp.photo_id')
|
||||
.select([
|
||||
'gp.photo_id',
|
||||
'gp.caption',
|
||||
'tp.provider',
|
||||
'tp.media_type',
|
||||
'tp.width',
|
||||
'tp.height',
|
||||
'tp.taken_at',
|
||||
'tp.lat',
|
||||
'tp.lng',
|
||||
])
|
||||
.where('gp.journey_id', '=', journeyId)
|
||||
.orderBy('gp.sort_order', 'asc')
|
||||
.orderBy('gp.id', 'asc')
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,19 @@ import { TrekPhotoCacheService } from './trek-photo-cache.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
import { Response } from 'express';
|
||||
import fsPromises from 'node:fs/promises';
|
||||
|
||||
/**
|
||||
* What a photo's quality signals are measured on (photos/photo-signals.service.ts):
|
||||
* a local original, or a provider's thumbnail with the original's size as the
|
||||
* provider reports it. `none` is nothing to measure, `unavailable` a provider
|
||||
* that did not answer now, which a later try may reach.
|
||||
*/
|
||||
export type PhotoSignalSource =
|
||||
| { kind: 'original'; bytes: Buffer }
|
||||
| { kind: 'thumbnail'; bytes: Buffer; width: number | null; height: number | null }
|
||||
| { kind: 'none' }
|
||||
| { kind: 'unavailable' };
|
||||
|
||||
/**
|
||||
* Resolves a stored trek_photo to bytes or metadata by asking whichever provider
|
||||
@@ -150,6 +163,35 @@ export class PhotoResolverService {
|
||||
await provider.streamAsset(res, { ...ref, range }, kind);
|
||||
}
|
||||
|
||||
/**
|
||||
* The bytes a photo's quality signals are measured on, read with its
|
||||
* owner's access rather than a viewer's: the signals belong to the photo,
|
||||
* whoever asks. A local photo answers its original whole, so the size it
|
||||
* decodes to is the original's; a provider photo its thumbnail, since an
|
||||
* original can be hundreds of megabytes, with the size the provider reports.
|
||||
* `none` for a photo that is gone, a video, a local original over
|
||||
* `maxBytes` or missing, a provider TREK does not know.
|
||||
*/
|
||||
async readForSignals(photoId: number, maxBytes: number): Promise<PhotoSignalSource> {
|
||||
const photo = await this.photos.resolve(photoId);
|
||||
if (!photo || photo.media_type === 'video') return { kind: 'none' };
|
||||
if (photo.file_path) {
|
||||
const name = this.storageName(photo.file_path);
|
||||
const stat = name ? await this.storage.stat('journey', name).catch(() => null) : null;
|
||||
if (!name || !stat || stat.size > maxBytes) return { kind: 'none' };
|
||||
const bytes = await this.storage.withLocalFile('journey', name, (p) => fsPromises.readFile(p));
|
||||
return { kind: 'original', bytes };
|
||||
}
|
||||
const provider = this.providers.get(photo.provider);
|
||||
if (!provider || photo.owner_id == null || !photo.asset_id) return { kind: 'none' };
|
||||
const ref = this.refFor(photo, photo.owner_id);
|
||||
const thumbnail = await provider.fetchThumbnailBytes(ref);
|
||||
if ('error' in thumbnail) return { kind: 'unavailable' };
|
||||
const info = await provider.getAssetInfo(ref);
|
||||
const size = info.success ? info.data : null;
|
||||
return { kind: 'thumbnail', bytes: thumbnail.bytes, width: size?.width ?? null, height: size?.height ?? null };
|
||||
}
|
||||
|
||||
/**
|
||||
* The stored row as a provider-shaped request. One place decrypts the
|
||||
* Synology share passphrase, and one place decides which of the two user ids
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
import { Jimp } from 'jimp';
|
||||
|
||||
/**
|
||||
* The version of the measurement below. A stored row of another version is
|
||||
* measured again, so a better measurement never mixes with an older one.
|
||||
* Version 2 measures every photo at the same `SIGNAL_EDGE`, up or down.
|
||||
*/
|
||||
export const PHOTO_SIGNALS_ALGO = 2;
|
||||
|
||||
/**
|
||||
* The long edge every photo is scaled to, up or down, before it is measured. A
|
||||
* smaller picture has a higher Laplacian variance per pixel, so sharpness only
|
||||
* compares between photos measured at one size; this one is no larger than the
|
||||
* thumbnails the providers hand out (Immich about 250 px, Synology about 320).
|
||||
*/
|
||||
export const SIGNAL_EDGE = 240;
|
||||
|
||||
/** An image declaring more than this many megapixels is not decoded at all (a 48 MP decode takes about 200 MB). */
|
||||
const MAX_DECODE_MP = 48;
|
||||
|
||||
/** Grey levels at or beyond these count as burnt out or crushed black. */
|
||||
const CLIP_LOW = 5;
|
||||
const CLIP_HIGH = 250;
|
||||
|
||||
/** What a photo's pixels say. `width`/`height` are the decoded image's, before it is scaled to measure. */
|
||||
export interface PhotoPixels {
|
||||
/** The perceptual hash, 64 bits as 16 hex digits; null if the hash came out in another shape. */
|
||||
phash: string | null;
|
||||
/** The variance of the grey Laplacian at `SIGNAL_EDGE`: the higher, the sharper. */
|
||||
sharpness: number;
|
||||
/** The mean grey level, 0 (black) to 1 (white). */
|
||||
luma: number;
|
||||
/** The share of pixels burnt out or crushed black, 0 to 1. */
|
||||
clipped: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Measures one photo. CPU work on a decoded bitmap, so the server runs it in
|
||||
* its worker thread (photo-signals.worker.ts), never on the event loop.
|
||||
* Answers null for bytes that are no image TREK decodes (WebP, HEIC, TIFF, a
|
||||
* video, anything past `MAX_DECODE_MP`): such a photo has no pixel signals.
|
||||
*/
|
||||
export async function measurePhoto(bytes: Uint8Array): Promise<PhotoPixels | null> {
|
||||
if (!withinDecodeCap(bytes)) return null;
|
||||
try {
|
||||
const image = await Jimp.read(Buffer.from(bytes), { 'image/jpeg': { maxResolutionInMP: MAX_DECODE_MP } });
|
||||
const { width, height } = image.bitmap;
|
||||
if (width < 3 || height < 3) return null;
|
||||
image.scaleToFit({ w: SIGNAL_EDGE, h: SIGNAL_EDGE });
|
||||
// A strip far longer than it is wide ends up under 3 pixels across, which leaves no inner pixel.
|
||||
if (image.bitmap.width < 3 || image.bitmap.height < 3) return null;
|
||||
const grey = greyStats(image.bitmap.data, image.bitmap.width, image.bitmap.height);
|
||||
return { phash: bitsToHex(image.pHash()), ...grey, width, height };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether these bytes may be decoded: a JPEG, which Jimp holds to
|
||||
* `MAX_DECODE_MP` itself, or a PNG, GIF or BMP whose header declares at most
|
||||
* that many pixels. A small file can declare a canvas of gigabytes, and the
|
||||
* decoder allocates all of it before the first pixel, so the size is read
|
||||
* first. Anything else (TIFF among the formats Jimp reads) is not decoded.
|
||||
*/
|
||||
export function withinDecodeCap(bytes: Uint8Array): boolean {
|
||||
const data = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) return true;
|
||||
const size = declaredSize(data);
|
||||
return size !== null && size.width * size.height <= MAX_DECODE_MP * 1_000_000;
|
||||
}
|
||||
|
||||
/** The canvas a PNG (IHDR), GIF (logical screen) or BMP (info or core header) declares; null for anything else. */
|
||||
function declaredSize(data: Buffer): { width: number; height: number } | null {
|
||||
if (data.length >= 24 && data.readUInt32BE(0) === 0x89504e47) {
|
||||
return { width: data.readUInt32BE(16), height: data.readUInt32BE(20) };
|
||||
}
|
||||
if (data.length >= 10 && data.toString('latin1', 0, 4) === 'GIF8') {
|
||||
return { width: data.readUInt16LE(6), height: data.readUInt16LE(8) };
|
||||
}
|
||||
if (data.length >= 26 && data.toString('latin1', 0, 2) === 'BM') {
|
||||
// The old core header holds two 16-bit sides, every later one two signed 32-bit ones (negative: top-down).
|
||||
if (data.readUInt32LE(14) === 12) return { width: data.readUInt16LE(18), height: data.readUInt16LE(20) };
|
||||
return { width: Math.abs(data.readInt32LE(18)), height: Math.abs(data.readInt32LE(22)) };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Brightness, clipping and sharpness from one pass over the grey image. The
|
||||
* Laplacian is summed by hand rather than through Jimp's `convolute`, which
|
||||
* clamps every result to 0..255 and so loses the negative half of each edge.
|
||||
* The caller hands in at least 3 x 3 pixels, so there is an inner pixel.
|
||||
*/
|
||||
function greyStats(data: Uint8Array, width: number, height: number) {
|
||||
const total = width * height;
|
||||
const grey = new Float32Array(total);
|
||||
let sum = 0;
|
||||
let clipped = 0;
|
||||
for (let i = 0; i < total; i++) {
|
||||
const o = i * 4;
|
||||
const y = 0.299 * (data[o] ?? 0) + 0.587 * (data[o + 1] ?? 0) + 0.114 * (data[o + 2] ?? 0);
|
||||
grey[i] = y;
|
||||
sum += y;
|
||||
if (y <= CLIP_LOW || y >= CLIP_HIGH) clipped++;
|
||||
}
|
||||
// Welford's running variance over the inner pixels, so no second pass is needed.
|
||||
let n = 0;
|
||||
let mean = 0;
|
||||
let m2 = 0;
|
||||
const at = (k: number) => grey[k] ?? 0;
|
||||
for (let row = 1; row < height - 1; row++) {
|
||||
for (let col = 1; col < width - 1; col++) {
|
||||
const i = row * width + col;
|
||||
const lap = at(i - 1) + at(i + 1) + at(i - width) + at(i + width) - 4 * at(i);
|
||||
n++;
|
||||
const delta = lap - mean;
|
||||
mean += delta / n;
|
||||
m2 += delta * (lap - mean);
|
||||
}
|
||||
}
|
||||
return {
|
||||
sharpness: round(m2 / n, 2),
|
||||
luma: round(sum / (total * 255), 4),
|
||||
clipped: round(clipped / total, 4),
|
||||
};
|
||||
}
|
||||
|
||||
function round(value: number, digits: number): number {
|
||||
const f = 10 ** digits;
|
||||
return Math.round(value * f) / f;
|
||||
}
|
||||
|
||||
/** Jimp's pHash is 64 characters of 0 and 1; stored as 16 hex digits. */
|
||||
export function bitsToHex(bits: string): string | null {
|
||||
if (!/^[01]{64}$/.test(bits)) return null;
|
||||
let out = '';
|
||||
for (let i = 0; i < 64; i += 4) out += parseInt(bits.slice(i, i + 4), 2).toString(16);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Measures photos: in a worker thread in production, on the calling thread in tests. */
|
||||
export interface PhotoSignalsRunner {
|
||||
measure(bytes: Uint8Array): Promise<PhotoPixels | null>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export const PHOTO_SIGNALS_RUNNER = Symbol('PHOTO_SIGNALS_RUNNER');
|
||||
|
||||
/** The runner on the calling thread, for the tests (the TypeScript sources ship no compiled worker script). */
|
||||
export class InlinePhotoSignalsRunner implements PhotoSignalsRunner {
|
||||
measure(bytes: Uint8Array): Promise<PhotoPixels | null> {
|
||||
return measurePhoto(bytes);
|
||||
}
|
||||
|
||||
close(): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { TrekPhotoSignals } from '../../db/entities/TrekPhotoSignals.entity';
|
||||
import { MemoriesModule } from '../memories/memories.module';
|
||||
import { InlinePhotoSignalsRunner, PHOTO_SIGNALS_RUNNER } from './photo-signals-runner';
|
||||
import { PhotoSignalsService } from './photo-signals.service';
|
||||
import { WorkerPhotoSignalsRunner } from './worker-photo-signals-runner';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
import { existsSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
|
||||
/** The worker thread where the build ships its script; the calling thread under the TypeScript sources (the tests). */
|
||||
export function photoSignalsRunner(entry = join(__dirname, 'photo-signals.worker.js')) {
|
||||
return existsSync(entry) ? new WorkerPhotoSignalsRunner(entry) : new InlinePhotoSignalsRunner();
|
||||
}
|
||||
|
||||
/**
|
||||
* What a photo's pixels say, measured once per photo off the event loop and
|
||||
* kept in `trek_photo_signals` (PhotoSignalsService). Its own module rather
|
||||
* than part of TrekPhotosModule: reading a photo's bytes needs the memories
|
||||
* resolver, and MemoriesModule imports TrekPhotosModule, so the leaf has to
|
||||
* stay a leaf.
|
||||
*/
|
||||
@Module({
|
||||
imports: [MemoriesModule, MikroOrmModule.forFeature([TrekPhotoSignals])],
|
||||
providers: [PhotoSignalsService, { provide: PHOTO_SIGNALS_RUNNER, useFactory: () => photoSignalsRunner() }],
|
||||
exports: [PhotoSignalsService],
|
||||
})
|
||||
export class PhotoSignalsModule {}
|
||||
@@ -0,0 +1,229 @@
|
||||
import { TrekPhotoSignals } from '../../db/entities/TrekPhotoSignals.entity';
|
||||
import type {
|
||||
GalleryPhotoFacts,
|
||||
TrekPhotoSignalRow,
|
||||
TrekPhotoSignalsRepository,
|
||||
} from '../../db/repositories/TrekPhotoSignals.repository';
|
||||
import { logWarn } from '../audit/audit-log.logger';
|
||||
import { withRequestContext } from '../database/request-context';
|
||||
import { PhotoResolverService, type PhotoSignalSource } from '../memories/photo-resolver.service';
|
||||
import {
|
||||
PHOTO_SIGNALS_ALGO,
|
||||
PHOTO_SIGNALS_RUNNER,
|
||||
type PhotoPixels,
|
||||
type PhotoSignalsRunner,
|
||||
} from './photo-signals-runner';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Inject, Injectable, type OnModuleDestroy } from '@nestjs/common';
|
||||
import type { PhotoPickSignals } from '@trek/shared';
|
||||
|
||||
/** How long a caller waits for photos still being measured before it answers on what the rows know. */
|
||||
const SIGNALS_WAIT_MS = 8000;
|
||||
/** Photos in line or being measured at most; more are left for a later call. */
|
||||
export const MAX_QUEUED_PHOTOS = 500;
|
||||
/** Photos fetched at the same time (a provider is asked with its owner's credentials, so gently). */
|
||||
export const PARALLEL_FETCHES = 2;
|
||||
/** A local original larger than this is not read for its signals. */
|
||||
export const MAX_ORIGINAL_BYTES = 40 * 1024 * 1024;
|
||||
|
||||
/** Errors of the runner that say nothing about the photo: it is measured again on a later call. */
|
||||
const TRANSIENT = new Set(['busy', 'closed', 'unavailable']);
|
||||
|
||||
/**
|
||||
* What a photo's pixels say (a perceptual hash, sharpness, brightness, clipping,
|
||||
* the original's size), measured once per photo and kept in
|
||||
* `trek_photo_signals`, for picking photos for a book without a model looking
|
||||
* at them (`suggest_book_photos`).
|
||||
*
|
||||
* Measuring is CPU work on a decoded image, so it runs in a worker thread
|
||||
* (`PHOTO_SIGNALS_RUNNER`, one photo at a time) and never on the event loop;
|
||||
* reading the bytes is I/O, at most `PARALLEL_FETCHES` at once. A photo is in
|
||||
* line once however often it is asked for, the line is bounded, and a caller
|
||||
* waits at most `SIGNALS_WAIT_MS` before it answers with what is ready; the
|
||||
* rest keep being measured in the background, each in a request context of
|
||||
* its own. A photo that cannot be measured gets a row of nulls, which is an
|
||||
* answer too; one whose provider did not answer, or whose thread could not
|
||||
* start, gets none and is tried again on the next call, and so does one that
|
||||
* timed out once (the host may have been busy), not twice.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PhotoSignalsService implements OnModuleDestroy {
|
||||
private readonly waiting: number[] = [];
|
||||
/** Every photo in line or being measured, with what its callers wait on. */
|
||||
private readonly inLine = new Map<number, { done: Promise<void>; finish: () => void }>();
|
||||
private active = 0;
|
||||
private closed = false;
|
||||
/** Photos that timed out once; a second timeout stores them as unmeasurable. */
|
||||
private readonly timedOut = new Set<number>();
|
||||
private warnedUnavailable = false;
|
||||
|
||||
constructor(
|
||||
@InjectRepository(TrekPhotoSignals) private readonly signalsRepo: TrekPhotoSignalsRepository,
|
||||
private readonly resolver: PhotoResolverService,
|
||||
@Inject(PHOTO_SIGNALS_RUNNER) private readonly runner: PhotoSignalsRunner,
|
||||
private readonly orm: MikroORM,
|
||||
) {}
|
||||
|
||||
async onModuleDestroy(): Promise<void> {
|
||||
this.closed = true;
|
||||
this.waiting.length = 0;
|
||||
await this.runner.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* The photos of a journey's gallery, videos left out, without their signals
|
||||
* (`signalsFor`). The caller has checked that the user may see the journey.
|
||||
*/
|
||||
async galleryFacts(journeyId: number): Promise<GalleryPhotoFacts[]> {
|
||||
return (await this.signalsRepo.listGalleryFacts(journeyId)).filter((f) => f.media_type !== 'video');
|
||||
}
|
||||
|
||||
/**
|
||||
* The signals of these photos: the stored ones at once, the missing ones
|
||||
* after they are measured or `waitMs` has passed, whichever comes first.
|
||||
* `pending` counts the photos still without signals. The photos in `later`
|
||||
* answer what is stored for them too, and the missing ones join the line
|
||||
* behind the others, neither waited for nor counted: a caller asking about a
|
||||
* few photos of a large gallery gets those measured first.
|
||||
*/
|
||||
async signalsFor(
|
||||
photoIds: readonly number[],
|
||||
{ waitMs = SIGNALS_WAIT_MS, later = [] }: { waitMs?: number; later?: readonly number[] } = {},
|
||||
): Promise<{ byPhoto: Map<number, PhotoPickSignals>; pending: number }> {
|
||||
const ids = [...new Set(photoIds)];
|
||||
const wanted = new Set(ids);
|
||||
const rest = [...new Set(later)].filter((id) => !wanted.has(id));
|
||||
const byPhoto = await this.stored([...ids, ...rest]);
|
||||
const missing = ids.filter((id) => !byPhoto.has(id));
|
||||
const jobs = missing.map((id) => this.enqueue(id)).filter((job): job is Promise<void> => job !== null);
|
||||
for (const id of rest) if (!byPhoto.has(id)) void this.enqueue(id);
|
||||
if (missing.length > 0) {
|
||||
if (jobs.length > 0 && waitMs > 0) await waitAtMost(Promise.all(jobs), waitMs);
|
||||
for (const [id, signals] of await this.stored(missing)) byPhoto.set(id, signals);
|
||||
}
|
||||
return { byPhoto, pending: ids.filter((id) => !byPhoto.has(id)).length };
|
||||
}
|
||||
|
||||
/** The signals stored for these photos by the current measurement; older ones count as missing. */
|
||||
private async stored(ids: number[]): Promise<Map<number, PhotoPickSignals>> {
|
||||
if (ids.length === 0) return new Map();
|
||||
const rows = await this.signalsRepo.listForPhotos(ids);
|
||||
return new Map(rows.filter((r) => r.algo === PHOTO_SIGNALS_ALGO).map((r) => [r.photo_id, toSignals(r)]));
|
||||
}
|
||||
|
||||
/** Puts a photo in line once; null when the line is full or closed, so the photo stays pending. */
|
||||
private enqueue(photoId: number): Promise<void> | null {
|
||||
const known = this.inLine.get(photoId);
|
||||
if (known) return known.done;
|
||||
if (this.closed || this.inLine.size >= MAX_QUEUED_PHOTOS) return null;
|
||||
let finish: () => void = () => undefined;
|
||||
const done = new Promise<void>((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
this.inLine.set(photoId, { done, finish });
|
||||
this.waiting.push(photoId);
|
||||
this.pump();
|
||||
return done;
|
||||
}
|
||||
|
||||
private pump(): void {
|
||||
while (this.active < PARALLEL_FETCHES) {
|
||||
const photoId = this.waiting.shift();
|
||||
if (photoId === undefined) return;
|
||||
this.active++;
|
||||
void withRequestContext(this.orm, () => this.measureOne(photoId))
|
||||
.catch((err: unknown) => {
|
||||
logWarn(`[photo-signals] photo ${photoId} not measured: ${err instanceof Error ? err.message : String(err)}`);
|
||||
})
|
||||
.finally(() => {
|
||||
this.active--;
|
||||
this.inLine.get(photoId)?.finish();
|
||||
this.inLine.delete(photoId);
|
||||
this.pump();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Reads one photo, has it measured and stores what came out; a provider that did not answer stores nothing. */
|
||||
private async measureOne(photoId: number): Promise<void> {
|
||||
const source = await this.resolver.readForSignals(photoId, MAX_ORIGINAL_BYTES);
|
||||
if (source.kind === 'unavailable') return;
|
||||
let pixels: PhotoPixels | null = null;
|
||||
if (source.kind !== 'none') {
|
||||
try {
|
||||
pixels = await this.runner.measure(source.bytes);
|
||||
} catch (err: unknown) {
|
||||
const reason = err instanceof Error ? err.message : String(err);
|
||||
if (TRANSIENT.has(reason)) {
|
||||
this.warnOnceUnavailable(reason, err);
|
||||
return;
|
||||
}
|
||||
// The first timeout may be the host's load rather than the photo, so it is left for a later call.
|
||||
if (reason === 'timeout' && !this.timedOut.has(photoId)) {
|
||||
this.timedOut.add(photoId);
|
||||
return;
|
||||
}
|
||||
// A second timeout, or a thread that died over this photo: measured as nothing, so it is not tried forever.
|
||||
}
|
||||
}
|
||||
this.timedOut.delete(photoId);
|
||||
await this.signalsRepo.saveSignals({
|
||||
photo_id: photoId,
|
||||
algo: PHOTO_SIGNALS_ALGO,
|
||||
phash: pixels?.phash ?? null,
|
||||
sharpness: pixels?.sharpness ?? null,
|
||||
luma: pixels?.luma ?? null,
|
||||
clipped: pixels?.clipped ?? null,
|
||||
...originalSize(source, pixels),
|
||||
});
|
||||
}
|
||||
|
||||
/** A thread that cannot start fails every photo alike; the log says so once, not once per photo. */
|
||||
private warnOnceUnavailable(reason: string, err: unknown): void {
|
||||
if (reason !== 'unavailable' || this.warnedUnavailable) return;
|
||||
this.warnedUnavailable = true;
|
||||
const cause = err instanceof Error && err.cause instanceof Error ? `: ${err.cause.message}` : '';
|
||||
logWarn(`[photo-signals] the measuring thread is unavailable${cause}; photos stay pending`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The original's size: what the decoded original measured, or what the
|
||||
* provider says of it. A provider may report the sensor's sides, before the
|
||||
* camera's rotation; the thumbnail is drawn upright, so when the two disagree
|
||||
* on which side is the long one, the provider's sides are turned to match.
|
||||
*/
|
||||
function originalSize(source: PhotoSignalSource, pixels: PhotoPixels | null) {
|
||||
if (source.kind !== 'thumbnail') return { orig_width: pixels?.width ?? null, orig_height: pixels?.height ?? null };
|
||||
const { width, height } = source;
|
||||
const turned =
|
||||
width !== null &&
|
||||
height !== null &&
|
||||
pixels !== null &&
|
||||
Math.sign(width - height) * Math.sign(pixels.width - pixels.height) === -1;
|
||||
return turned ? { orig_width: height, orig_height: width } : { orig_width: width, orig_height: height };
|
||||
}
|
||||
|
||||
function toSignals(row: TrekPhotoSignalRow): PhotoPickSignals {
|
||||
return {
|
||||
phash: row.phash,
|
||||
sharpness: row.sharpness,
|
||||
clipped: row.clipped,
|
||||
origWidth: row.orig_width,
|
||||
origHeight: row.orig_height,
|
||||
};
|
||||
}
|
||||
|
||||
/** Resolves when `work` settles or after `ms`, whichever comes first; never rejects. */
|
||||
function waitAtMost(work: Promise<unknown>, ms: number): Promise<void> {
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(resolve, ms);
|
||||
timer.unref();
|
||||
const done = () => {
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
};
|
||||
work.then(done, done);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { measurePhoto } from './photo-signals-runner';
|
||||
|
||||
import { parentPort } from 'node:worker_threads';
|
||||
|
||||
/**
|
||||
* The photo signals' thread: says it is ready once its script has loaded (so
|
||||
* the runner can tell a thread that never started from a photo that broke
|
||||
* one), then measures the photos it is sent and answers each by its id.
|
||||
* `measurePhoto` answers null for anything it cannot read and never throws, so
|
||||
* every photo gets its answer.
|
||||
*/
|
||||
parentPort?.on('message', (message: { id: number; bytes?: Uint8Array }) => {
|
||||
if (!message.bytes) return;
|
||||
void measurePhoto(message.bytes).then((pixels) => parentPort?.postMessage({ id: message.id, pixels }));
|
||||
});
|
||||
parentPort?.postMessage({ ready: true });
|
||||
@@ -0,0 +1,141 @@
|
||||
import type { PhotoPixels, PhotoSignalsRunner } from './photo-signals-runner';
|
||||
|
||||
import { join } from 'node:path';
|
||||
import { Worker } from 'node:worker_threads';
|
||||
|
||||
/** A photo is decoded and measured in well under this; one that takes longer counts as unmeasurable. */
|
||||
export const MEASURE_TIMEOUT_MS = 20_000;
|
||||
/** With this many photos already in line for the thread, a new one is turned away as busy. */
|
||||
export const MAX_WAITING_PHOTOS = 16;
|
||||
/** A thread with nothing to do ends after ten minutes; the next photo starts one again. */
|
||||
const IDLE_MS = 10 * 60 * 1000;
|
||||
/** The thread's heap. The decoded pixels sit outside it, which is why the decoder checks a photo's size first. */
|
||||
const SIGNALS_HEAP_MB = 256;
|
||||
|
||||
type Reply = { id: number; pixels?: PhotoPixels | null; error?: string };
|
||||
/** What the thread sends once its script has loaded, before any photo. */
|
||||
type Ready = { ready: true };
|
||||
|
||||
/**
|
||||
* The photo signals' own thread, so decoding a photo never holds up the
|
||||
* server's requests (the piste router's thread is the precedent). Photos go to
|
||||
* it one at a time, in the order they came, each on its own clock from when
|
||||
* the thread takes it up: a photo not answered in time fails as `timeout` and
|
||||
* the thread is replaced, a thread that dies fails the photo it held, and the
|
||||
* next photo starts a fresh one. Started on the first photo, ended when idle.
|
||||
*
|
||||
* Only a thread that has said it is ready can blame a photo. One that cannot be
|
||||
* started, or dies before its script has loaded (a broken build, a bad flag),
|
||||
* fails its photos as `unavailable`, and one ended by `close()` as `closed`:
|
||||
* both say nothing about the photo, so the caller tries it again later.
|
||||
*/
|
||||
export class WorkerPhotoSignalsRunner implements PhotoSignalsRunner {
|
||||
private thread: Worker | null = null;
|
||||
private line: Promise<unknown> = Promise.resolve();
|
||||
private inLine = 0;
|
||||
private lastId = 0;
|
||||
private closed = false;
|
||||
private idleTimer: NodeJS.Timeout | null = null;
|
||||
/** The threads that have said they are ready. */
|
||||
private readonly started = new WeakSet<Worker>();
|
||||
|
||||
constructor(private readonly entry = join(__dirname, 'photo-signals.worker.js')) {}
|
||||
|
||||
measure(bytes: Uint8Array): Promise<PhotoPixels | null> {
|
||||
if (this.inLine >= MAX_WAITING_PHOTOS) return Promise.reject(new Error('busy'));
|
||||
this.inLine++;
|
||||
const turn = this.line.then(() => this.ask(bytes));
|
||||
this.line = turn.catch(() => undefined);
|
||||
return turn.finally(() => {
|
||||
this.inLine--;
|
||||
});
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
this.closed = true;
|
||||
if (this.idleTimer) clearTimeout(this.idleTimer);
|
||||
this.idleTimer = null;
|
||||
const worker = this.thread;
|
||||
this.thread = null;
|
||||
await worker?.terminate();
|
||||
}
|
||||
|
||||
/** One photo to the thread and its answer back. */
|
||||
private ask(bytes: Uint8Array): Promise<PhotoPixels | null> {
|
||||
if (this.closed) return Promise.reject(new Error('closed'));
|
||||
let worker: Worker;
|
||||
try {
|
||||
worker = this.ensureThread();
|
||||
} catch (err: unknown) {
|
||||
return Promise.reject(new Error('unavailable', { cause: err }));
|
||||
}
|
||||
const id = ++this.lastId;
|
||||
return new Promise<PhotoPixels | null>((resolve, reject) => {
|
||||
const settle = (outcome: () => void) => {
|
||||
clearTimeout(timer);
|
||||
worker.off('message', onMessage);
|
||||
worker.off('error', onError);
|
||||
worker.off('exit', onExit);
|
||||
outcome();
|
||||
};
|
||||
const onMessage = (reply: Reply | Ready) => {
|
||||
if (!('id' in reply) || reply.id !== id) return;
|
||||
const { pixels, error } = reply;
|
||||
if (pixels === undefined) settle(() => reject(new Error(error ?? 'measurement failed')));
|
||||
else settle(() => resolve(pixels));
|
||||
};
|
||||
// Why the photo failed: the thread's own fault once it was ready, else nothing to do with the photo.
|
||||
const blame = (err: Error) => {
|
||||
if (this.closed) return new Error('closed');
|
||||
return this.started.has(worker) ? err : new Error('unavailable', { cause: err });
|
||||
};
|
||||
const onError = (err: Error) => settle(() => reject(blame(err)));
|
||||
const onExit = () => settle(() => reject(blame(new Error('signals thread ended'))));
|
||||
const timer = setTimeout(() => {
|
||||
// The thread is stuck on this photo; the next photo gets a fresh one.
|
||||
this.thread = null;
|
||||
void worker.terminate();
|
||||
settle(() => reject(new Error('timeout')));
|
||||
}, MEASURE_TIMEOUT_MS);
|
||||
worker.on('message', onMessage);
|
||||
worker.on('error', onError);
|
||||
worker.on('exit', onExit);
|
||||
worker.postMessage({ id, bytes });
|
||||
});
|
||||
}
|
||||
|
||||
private ensureThread(): Worker {
|
||||
if (this.idleTimer) clearTimeout(this.idleTimer);
|
||||
this.idleTimer = setTimeout(() => void this.endIdle(), IDLE_MS);
|
||||
this.idleTimer.unref();
|
||||
if (this.thread) return this.thread;
|
||||
// The compiled thread needs the same --require hooks (path aliases) the server was started with.
|
||||
const hooks = process.execArgv.filter(
|
||||
(arg, i, all) => ['--require', '-r'].includes(arg) || ['--require', '-r'].includes(all[i - 1] ?? ''),
|
||||
);
|
||||
const worker = new Worker(this.entry, {
|
||||
execArgv: hooks,
|
||||
resourceLimits: { maxOldGenerationSizeMb: SIGNALS_HEAP_MB },
|
||||
});
|
||||
// Kept for the thread's whole life: a thread error with no listener would take the server down.
|
||||
const forget = () => {
|
||||
if (this.thread === worker) this.thread = null;
|
||||
};
|
||||
// Any message, its first being `ready`, says the script has loaded.
|
||||
worker.on('message', () => {
|
||||
this.started.add(worker);
|
||||
});
|
||||
worker.on('error', forget);
|
||||
worker.on('exit', forget);
|
||||
worker.unref();
|
||||
this.thread = worker;
|
||||
return worker;
|
||||
}
|
||||
|
||||
/** An idle thread ends; the runner stays open for the next photo. */
|
||||
private async endIdle(): Promise<void> {
|
||||
const worker = this.thread;
|
||||
this.thread = null;
|
||||
await worker?.terminate();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user