places: let an admin share the details users typed with the TREK Places API

Every shareable field of a place now records where its value came from: typed
by a user, filled by a provider, written by the assistant, a plugin or an
import. Only values a user typed are ever sent, and only after an admin agreed
to the current terms for the whole installation, field by field.

The new place-contrib domain keeps the decision in app settings, queues values
in an outbox a cron job sends from, logs what the service made of each one and
can withdraw everything this installation sent. Development, test and demo
instances, an own TREK_PLACES_URL, TREK_SERVICES=off and
TREK_PLACES_CONTRIBUTE=off never send anything. Index results carry the
community version, so the details caches refresh when it changes.
This commit is contained in:
Maurice
2026-10-30 18:15:24 +01:00
parent f56f6ae11e
commit 182ed56fa4
69 changed files with 5758 additions and 8 deletions
+7
View File
@@ -165,6 +165,13 @@ export function deriveMaps(raw: RawEnv) {
* the install back to Nominatim.
*/
trekPlacesEnabled: parseBool(raw.TREK_PLACES_ENABLED) !== false,
/**
* The ceiling over sending place details back to the TREK Places API.
* `admin` (the default) lets an admin decide in the admin panel; `off` takes
* the choice away. Anything but `admin` reads as off, so a typo fails closed.
*/
trekPlacesContribute:
(raw.TREK_PLACES_CONTRIBUTE?.trim().toLowerCase() || 'admin') === 'admin' ? ('admin' as const) : ('off' as const),
placesApiKey: raw.PLACES_API_KEY || undefined,
/** The same two knobs for Amap (高德), which an install in China uses instead. */
amapApiBase: raw.AMAP_API_BASE || undefined,
+1
View File
@@ -185,6 +185,7 @@ export const envSchema = z.object({
GOOGLE_LIST_DATA_BASE: url,
TREK_PLACES_URL: url,
TREK_PLACES_ENABLED: boolStr,
TREK_PLACES_CONTRIBUTE: oneOf(['off', 'admin']),
TREK_SERVICES: oneOf(['auto', 'off']),
TREK_SERVICES_KEY: optionalWith(isServiceKeyShape, 'must be a TREK services key (tk1.<kid>.<payload>.<signature>)'),
TREK_SERVICES_HOSTS: anyString,
@@ -0,0 +1,29 @@
import { EntityRepositoryType, type Opt, defineEntity, p } from '@mikro-orm/core';
import { PlaceContribLogRepository } from '../repositories/PlaceContribLog.repository';
export class PlaceContribLog {
[EntityRepositoryType]?: PlaceContribLogRepository;
id!: number & Opt;
day!: string;
contrib_key!: string;
place_name!: string;
field!: string;
value_summary?: string | null;
result!: string;
reason?: string | null;
}
export const PlaceContribLogSchema = defineEntity({
class: PlaceContribLog,
repository: () => PlaceContribLogRepository,
properties: {
id: p.integer().primary(),
day: p.text().index('idx_place_contrib_log_day'),
contrib_key: p.text(),
place_name: p.text(),
field: p.text(),
value_summary: p.text().nullable(),
result: p.text(),
reason: p.text().nullable(),
},
});
@@ -0,0 +1,46 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { PlaceContribOutboxRepository } from '../repositories/PlaceContribOutbox.repository';
import { DbTimestampType } from '../types';
import { Places } from './Places.entity';
export class PlaceContribOutbox {
[EntityRepositoryType]?: PlaceContribOutboxRepository;
id!: number & Opt;
contrib_key!: string;
field!: string;
value!: string;
place!: Ref<Places>;
place_id!: number;
place_name!: string;
lat?: number | null;
lng?: number | null;
country?: string | null;
cid!: string;
attempts: number & Opt = 0;
eligible_at!: string;
next_attempt_at!: string;
created_at!: string & Opt;
}
export const PlaceContribOutboxSchema = defineEntity({
class: PlaceContribOutbox,
repository: () => PlaceContribOutboxRepository,
uniques: [{ properties: ['contrib_key', 'field'] }],
properties: {
id: p.integer().primary(),
contrib_key: p.text(),
field: p.text(),
value: p.text(),
place: () => p.manyToOne(Places).ref().deleteRule('cascade').hidden().index('idx_place_contrib_outbox_place'),
place_id: p.integer().persist(false).index('idx_place_contrib_outbox_place'),
place_name: p.text(),
lat: p.double().nullable(),
lng: p.double().nullable(),
country: p.text().nullable(),
cid: p.text(),
attempts: p.integer().default(0),
eligible_at: p.type(DbTimestampType),
next_attempt_at: p.type(DbTimestampType).index('idx_place_contrib_outbox_due'),
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,29 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { PlaceFieldOriginRepository } from '../repositories/PlaceFieldOrigin.repository';
import { DbTimestampType } from '../types';
import { Places } from './Places.entity';
export class PlaceFieldOrigin {
[EntityRepositoryType]?: PlaceFieldOriginRepository;
[PrimaryKeyProp]?: ['place', 'field'];
place!: Ref<Places>;
place_id!: number;
field!: string;
origin!: string;
value_hash!: string;
updated_at!: string & Opt;
}
export const PlaceFieldOriginSchema = defineEntity({
class: PlaceFieldOrigin,
repository: () => PlaceFieldOriginRepository,
uniques: [{ properties: ['place', 'field'] }],
properties: {
place: () => p.manyToOne(Places).primary().ref().deleteRule('cascade').hidden(),
place_id: p.integer().persist(false),
field: p.text().primary(),
origin: p.text(),
value_hash: p.text(),
updated_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
},
});
+6
View File
@@ -9,6 +9,8 @@ import { DayAssignments } from './DayAssignments.entity';
import { FileLinks } from './FileLinks.entity';
import { JourneyEntries } from './JourneyEntries.entity';
import { Photos } from './Photos.entity';
import { PlaceContribOutbox } from './PlaceContribOutbox.entity';
import { PlaceFieldOrigin } from './PlaceFieldOrigin.entity';
import { PlaceRatings } from './PlaceRatings.entity';
import { PlaceRegions } from './PlaceRegions.entity';
import { Reservations } from './Reservations.entity';
@@ -65,6 +67,8 @@ export class Places {
file_links_collection = new Collection<FileLinks>(this);
journey_entries_collection = new Collection<JourneyEntries>(this);
photos_collection = new Collection<Photos>(this);
place_contrib_outbox_collection = new Collection<PlaceContribOutbox>(this);
place_field_origin_collection = new Collection<PlaceFieldOrigin>(this);
place_ratings_collection = new Collection<PlaceRatings>(this);
place_regions: Ref<PlaceRegions> | null = null;
reservations_collection = new Collection<Reservations>(this);
@@ -123,6 +127,8 @@ export const PlacesSchema = defineEntity({
file_links_collection: () => p.oneToMany(FileLinks).mappedBy('place').hidden(),
journey_entries_collection: () => p.oneToMany(JourneyEntries).mappedBy('sourcePlace').hidden(),
photos_collection: () => p.oneToMany(Photos).mappedBy('place').hidden(),
place_contrib_outbox_collection: () => p.oneToMany(PlaceContribOutbox).mappedBy('place').hidden(),
place_field_origin_collection: () => p.oneToMany(PlaceFieldOrigin).mappedBy('place').hidden(),
place_ratings_collection: () => p.oneToMany(PlaceRatings).mappedBy('place').hidden(),
place_regions: () => p.oneToOne(PlaceRegions).ref().mappedBy('place').hidden(),
reservations_collection: () => p.oneToMany(Reservations).mappedBy('place').hidden(),
+6
View File
@@ -80,7 +80,10 @@ import { PasswordResetTokensSchema } from './PasswordResetTokens.entity';
import { PhotoProviderFieldsSchema } from './PhotoProviderFields.entity';
import { PhotoProvidersSchema } from './PhotoProviders.entity';
import { PhotosSchema } from './Photos.entity';
import { PlaceContribLogSchema } from './PlaceContribLog.entity';
import { PlaceContribOutboxSchema } from './PlaceContribOutbox.entity';
import { PlaceDetailsCacheSchema } from './PlaceDetailsCache.entity';
import { PlaceFieldOriginSchema } from './PlaceFieldOrigin.entity';
import { PlaceRatingsSchema } from './PlaceRatings.entity';
import { PlaceRegionsSchema } from './PlaceRegions.entity';
import { PlaceShadowPicksSchema } from './PlaceShadowPicks.entity';
@@ -244,7 +247,10 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
PhotoProviderFieldsSchema,
PhotoProvidersSchema,
PhotosSchema,
PlaceContribLogSchema,
PlaceContribOutboxSchema,
PlaceDetailsCacheSchema,
PlaceFieldOriginSchema,
PlaceRatingsSchema,
PlaceRegionsSchema,
PlaceShadowPicksSchema,
+60
View File
@@ -13,6 +13,8 @@ import {
paddleLockSchema,
paddleRegionBoundarySchema,
paddleRegionGraphStatsSchema,
placeContribConsentSchema,
placeContribPauseReasonSchema,
skiPlannedLegsSchema,
skiRouteOptionsSchema,
tourChangeSchema,
@@ -31,6 +33,8 @@ import {
type PaddleLock,
type PaddleRegionBoundary,
type PaddleRegionGraphStats,
type PlaceContribConsent,
type PlaceContribPauseReason,
type TourChange,
type TourFixedLeg,
type TourSourceHintChange,
@@ -454,3 +458,59 @@ export const TREK_PHOTO_SIGNAL_PALETTE: JsonColumn<string[]> = {
schema: z.array(z.string().regex(/^#[0-9a-f]{6}(?::(?:0|1)(?:\.\d{1,2})?)?$/)).max(5),
fallback: () => [],
};
/**
* The installation's decision on the community enrichment, in the
* `places_contribute` app setting. Undecided reads as off, with every field
* switch on: that is what the prompt proposes. A broken row reads the same, so
* nothing is sent on a value nobody can read.
*/
export const PLACES_CONTRIBUTE_CONSENT: JsonColumn<PlaceContribConsent> = {
column: 'app_settings.places_contribute',
schema: placeContribConsentSchema,
fallback: () => ({
enabled: false,
fields: { website: true, phone: true, email: true, opening_hours: true, description: true, image: true },
termsVersion: null,
decision: null,
decidedBy: null,
decidedAt: null,
}),
};
/** Per admin (by user id), the ISO moment their "not now" ends, in `places_contribute_snooze`. */
export const PLACES_CONTRIBUTE_SNOOZE: JsonColumn<Record<string, string>> = {
column: 'app_settings.places_contribute_snooze',
schema: z.record(z.string().regex(/^\d+$/), z.string()),
fallback: () => ({}),
};
/**
* Why sending waits although an admin agreed, in `places_contribute_pause`: a
* refused key (with the fingerprint of the key that was refused, so a new key
* resumes by itself) or the service asking to wait (until when).
*/
export interface PlacesContributePause {
reason: PlaceContribPauseReason;
key: string | null;
until: string | null;
}
export const PLACES_CONTRIBUTE_PAUSE: JsonColumn<PlacesContributePause | null> = {
column: 'app_settings.places_contribute_pause',
schema: z
.object({ reason: placeContribPauseReasonSchema, key: z.string().nullable(), until: z.string().nullable() })
.nullable(),
fallback: () => null,
};
/**
* A cached details or enrichment record in `place_details_cache.payload_json`,
* read by the origin tracking to see what a provider handed out for a place.
* Only its object shape is checked here; the reader picks the fields it knows.
*/
export const PLACE_DETAILS_CACHE_PAYLOAD: JsonColumn<Record<string, unknown> | null> = {
column: 'place_details_cache.payload_json',
schema: z.record(z.string(), z.unknown()).nullable(),
fallback: () => null,
};
@@ -0,0 +1,14 @@
// 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 PlaceContribLogTable {
id: InsertOptional<number>;
day: string;
contrib_key: string;
place_name: string;
field: string;
value_summary: InsertOptional<string | null>;
result: string;
reason: InsertOptional<string | null>;
}
@@ -0,0 +1,20 @@
// 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 PlaceContribOutboxTable {
id: InsertOptional<number>;
contrib_key: string;
field: string;
value: string;
place_id: number;
place_name: string;
lat: InsertOptional<number | null>;
lng: InsertOptional<number | null>;
country: InsertOptional<string | null>;
cid: string;
attempts: InsertOptional<number>;
eligible_at: string;
next_attempt_at: string;
created_at: InsertOptional<string>;
}
@@ -0,0 +1,11 @@
// 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 PlaceFieldOriginTable {
place_id: number;
field: string;
origin: string;
value_hash: string;
updated_at: InsertOptional<string>;
}
+6
View File
@@ -85,7 +85,10 @@ import type { PasswordResetTokensTable } from './PasswordResetTokens.table';
import type { PhotoProviderFieldsTable } from './PhotoProviderFields.table';
import type { PhotoProvidersTable } from './PhotoProviders.table';
import type { PhotosTable } from './Photos.table';
import type { PlaceContribLogTable } from './PlaceContribLog.table';
import type { PlaceContribOutboxTable } from './PlaceContribOutbox.table';
import type { PlaceDetailsCacheTable } from './PlaceDetailsCache.table';
import type { PlaceFieldOriginTable } from './PlaceFieldOrigin.table';
import type { PlaceRatingsTable } from './PlaceRatings.table';
import type { PlaceRegionsTable } from './PlaceRegions.table';
import type { PlaceShadowPicksTable } from './PlaceShadowPicks.table';
@@ -255,7 +258,10 @@ export interface DB {
photo_provider_fields: PhotoProviderFieldsTable;
photo_providers: PhotoProvidersTable;
photos: PhotosTable;
place_contrib_log: PlaceContribLogTable;
place_contrib_outbox: PlaceContribOutboxTable;
place_details_cache: PlaceDetailsCacheTable;
place_field_origin: PlaceFieldOriginTable;
place_ratings: PlaceRatingsTable;
place_regions: PlaceRegionsTable;
place_shadow_picks: PlaceShadowPicksTable;
@@ -0,0 +1,71 @@
import { Migration } from '@mikro-orm/migrations';
/**
* A place remembers where each of its shareable details came from, and an
* installation whose admin agreed can send the ones its users typed in to the
* TREK Places API (community enrichment).
*
* `place_field_origin` holds one row per place and field (website, phone,
* email, opening_hours, description, image): who set the value (`user`, a
* provider, the assistant, a plugin, an import, an attachment, or `unknown`)
* and the hash of the value the row describes. Only `user` rows whose hash
* still matches the column are ever sent, so every value that existed before
* this migration stays home: it has no row. The rows go with their place.
*
* `place_contrib_outbox` queues what waits to be sent, one row per place key
* and field (the newest value replaces a queued one); its place going takes
* the row with it. `place_contrib_log` is what the admin sees of what was
* sent and what became of it, by day, without user, trip or row ids; a job
* keeps 90 days of it.
*/
export class Migration20200101046320_a_place_knows_where_its_details_came_from extends Migration {
override name = 'Migration20200101046320_a_place_knows_where_its_details_came_from';
override up(): void {
this.addSql(`
CREATE TABLE IF NOT EXISTS place_field_origin (
place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
field TEXT NOT NULL CHECK(field IN ('website', 'phone', 'email', 'opening_hours', 'description', 'image')),
origin TEXT NOT NULL CHECK(origin IN ('user', 'attachment', 'agent', 'plugin', 'import', 'google', 'amap',
'osm', 'trek', 'wikimedia', 'website', 'unsplash', 'enrichment', 'unknown')),
value_hash TEXT NOT NULL,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (place_id, field)
)
`);
this.addSql(`
CREATE TABLE IF NOT EXISTS place_contrib_outbox (
id INTEGER PRIMARY KEY,
contrib_key TEXT NOT NULL,
field TEXT NOT NULL CHECK(field IN ('website', 'phone', 'email', 'opening_hours', 'description', 'image')),
value TEXT NOT NULL,
place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
place_name TEXT NOT NULL,
lat REAL,
lng REAL,
country TEXT,
cid TEXT NOT NULL,
attempts INTEGER NOT NULL DEFAULT 0,
eligible_at DATETIME NOT NULL,
next_attempt_at DATETIME NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE(contrib_key, field)
)
`);
this.addSql('CREATE INDEX IF NOT EXISTS idx_place_contrib_outbox_place ON place_contrib_outbox(place_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_place_contrib_outbox_due ON place_contrib_outbox(next_attempt_at)');
this.addSql(`
CREATE TABLE IF NOT EXISTS place_contrib_log (
id INTEGER PRIMARY KEY,
day TEXT NOT NULL,
contrib_key TEXT NOT NULL,
place_name TEXT NOT NULL,
field TEXT NOT NULL CHECK(field IN ('website', 'phone', 'email', 'opening_hours', 'description', 'image')),
value_summary TEXT,
result TEXT NOT NULL CHECK(result IN ('accepted', 'duplicate', 'rejected', 'withheld', 'retracted')),
reason TEXT
)
`);
this.addSql('CREATE INDEX IF NOT EXISTS idx_place_contrib_log_day ON place_contrib_log(day)');
}
}
@@ -0,0 +1,90 @@
import type { PlaceContribLog } from '../entities/PlaceContribLog.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
type LogKyselyDB = Pick<DB, 'place_contrib_log'>;
/** One line of the transmission log. */
interface PlaceContribLogRow {
id: number;
day: string;
contrib_key: string;
place_name: string;
field: string;
value_summary: string | null;
result: string;
reason: string | null;
}
export type PlaceContribLogWrite = Omit<PlaceContribLogRow, 'id'>;
/** Which lines a page of the log shows. */
interface PlaceContribLogFilter {
result?: string;
field?: string;
}
const LOG_COLUMNS = ['id', 'day', 'contrib_key', 'place_name', 'field', 'value_summary', 'result', 'reason'] as const;
/**
* `place_contrib_log`: what this installation sent to the TREK Places API and
* what became of it, or why it kept a value home. By day, with the place's key
* and name, never a user, trip or row id.
*/
export class PlaceContribLogRepository extends TrekRepository<PlaceContribLog> {
private db() {
return this.kysely<LogKyselyDB>();
}
async insertLines(rows: PlaceContribLogWrite[]): Promise<void> {
if (rows.length === 0) return;
await this.db().insertInto('place_contrib_log').values(rows).execute();
}
/** One page, newest first. */
async page(filter: PlaceContribLogFilter, limit: number, offset: number): Promise<PlaceContribLogRow[]> {
let query = this.db()
.selectFrom('place_contrib_log')
.select([...LOG_COLUMNS]);
if (filter.result) query = query.where('result', '=', filter.result);
if (filter.field) query = query.where('field', '=', filter.field);
return query.orderBy('id', 'desc').limit(limit).offset(offset).execute();
}
async total(filter: PlaceContribLogFilter): Promise<number> {
let query = this.db()
.selectFrom('place_contrib_log')
.select((eb) => eb.fn.countAll<number>().as('count'));
if (filter.result) query = query.where('result', '=', filter.result);
if (filter.field) query = query.where('field', '=', filter.field);
const row = await query.executeTakeFirst();
return Number(row?.count ?? 0);
}
/** Lines per result from `sinceDay` (YYYY-MM-DD) on. */
async countsSince(sinceDay: string): Promise<Array<{ result: string; count: number }>> {
const rows = await this.db()
.selectFrom('place_contrib_log')
.select(['result', (eb) => eb.fn.countAll<number>().as('count')])
.where('day', '>=', sinceDay)
.groupBy('result')
.execute();
return rows.map((row) => ({ result: row.result, count: Number(row.count) }));
}
/** The newest day a field was accepted, or null. */
async lastAcceptedDay(): Promise<string | null> {
const row = await this.db()
.selectFrom('place_contrib_log')
.select((eb) => eb.fn.max('day').as('day'))
.where('result', '=', 'accepted')
.executeTakeFirst();
return row?.day ?? null;
}
/** The retention sweep: drops the lines older than `beforeDay`. */
async purgeBefore(beforeDay: string): Promise<number> {
const result = await this.db().deleteFrom('place_contrib_log').where('day', '<', beforeDay).executeTakeFirst();
return Number(result.numDeletedRows);
}
}
@@ -0,0 +1,232 @@
import type { PlaceContribOutbox } from '../entities/PlaceContribOutbox.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
type OutboxKyselyDB = Pick<DB, 'place_contrib_outbox' | 'place_field_origin' | 'places'>;
/** One queued value as the sender reads it. */
export interface OutboxRow {
id: number;
contrib_key: string;
field: string;
value: string;
place_id: number;
place_name: string;
lat: number | null;
lng: number | null;
country: string | null;
cid: string;
attempts: number;
created_at: string;
}
/** A value to queue: the newest one for its key and field replaces what waits there. */
interface OutboxWrite {
contrib_key: string;
field: string;
value: string;
place_id: number;
place_name: string;
lat: number | null;
lng: number | null;
country: string | null;
cid: string;
eligible_at: string;
next_attempt_at: string;
}
/** What the place and its origin row say about a queued value right now. */
export interface OutboxCurrentRow {
id: number;
origin: string | null;
value_hash: string | null;
website: string | null;
phone: string | null;
email: string | null;
opening_hours: string | null;
description: string | null;
image_url: string | null;
}
const OUTBOX_COLUMNS = [
'id',
'contrib_key',
'field',
'value',
'place_id',
'place_name',
'lat',
'lng',
'country',
'cid',
'attempts',
'created_at',
] as const;
/**
* `place_contrib_outbox`: the values waiting to be sent to the TREK Places
* API, one per contribution key and field. A new value replaces the queued one
* (and its attempts); the sender takes what is due, oldest first.
*/
export class PlaceContribOutboxRepository extends TrekRepository<PlaceContribOutbox> {
private db() {
return this.kysely<OutboxKyselyDB>();
}
/** Queues a value, replacing whatever waited for the same key and field, attempts included. */
async upsertEntry(row: OutboxWrite): Promise<void> {
await this.db()
.insertInto('place_contrib_outbox')
.values({ ...row, attempts: 0 })
.onConflict((oc) =>
oc.columns(['contrib_key', 'field']).doUpdateSet({
value: (eb) => eb.ref('excluded.value'),
place_id: (eb) => eb.ref('excluded.place_id'),
place_name: (eb) => eb.ref('excluded.place_name'),
lat: (eb) => eb.ref('excluded.lat'),
lng: (eb) => eb.ref('excluded.lng'),
country: (eb) => eb.ref('excluded.country'),
cid: (eb) => eb.ref('excluded.cid'),
attempts: 0,
eligible_at: (eb) => eb.ref('excluded.eligible_at'),
next_attempt_at: (eb) => eb.ref('excluded.next_attempt_at'),
}),
)
.execute();
}
/** Whether a value waits for this key and field. */
async hasEntry(contribKey: string, field: string): Promise<boolean> {
const row = await this.db()
.selectFrom('place_contrib_outbox')
.select('id')
.where('contrib_key', '=', contribKey)
.where('field', '=', field)
.executeTakeFirst();
return row !== undefined;
}
/** Drops the queued values of these fields of one place. */
async deleteForPlace(placeId: number, fields: string[]): Promise<number> {
if (fields.length === 0) return 0;
const result = await this.db()
.deleteFrom('place_contrib_outbox')
.where('place_id', '=', placeId)
.where('field', 'in', fields)
.executeTakeFirst();
return Number(result.numDeletedRows);
}
/** Drops every queued value of these fields, for a field an admin switched off. */
async deleteFields(fields: string[]): Promise<number> {
if (fields.length === 0) return 0;
const result = await this.db().deleteFrom('place_contrib_outbox').where('field', 'in', fields).executeTakeFirst();
return Number(result.numDeletedRows);
}
async deleteIds(ids: number[]): Promise<number> {
if (ids.length === 0) return 0;
const result = await this.db().deleteFrom('place_contrib_outbox').where('id', 'in', ids).executeTakeFirst();
return Number(result.numDeletedRows);
}
/** Empties the queue; answers how many values went. */
async deleteAll(): Promise<number> {
const result = await this.db().deleteFrom('place_contrib_outbox').executeTakeFirst();
return Number(result.numDeletedRows);
}
async size(): Promise<number> {
const row = await this.db()
.selectFrom('place_contrib_outbox')
.select((eb) => eb.fn.countAll<number>().as('count'))
.executeTakeFirst();
return Number(row?.count ?? 0);
}
/** The keys whose first value is due at `now`, oldest first, at most `limit` of them. */
async dueKeys(now: string, limit: number): Promise<string[]> {
const rows = await this.db()
.selectFrom('place_contrib_outbox')
.select('contrib_key')
.where('next_attempt_at', '<=', now)
.groupBy('contrib_key')
.orderBy((eb) => eb.fn.min('next_attempt_at'))
.limit(limit)
.execute();
return rows.map((row) => row.contrib_key);
}
/** The due values of one key. */
async dueFor(contribKey: string, now: string): Promise<OutboxRow[]> {
return this.db()
.selectFrom('place_contrib_outbox')
.select([...OUTBOX_COLUMNS])
.where('contrib_key', '=', contribKey)
.where('next_attempt_at', '<=', now)
.orderBy('id')
.execute();
}
/**
* The queued values first queued before `before`, which the sender gives up
* on; at most `limit` per call, so a long sweep goes in passes.
*/
async queuedBefore(before: string, limit: number): Promise<OutboxRow[]> {
return this.db()
.selectFrom('place_contrib_outbox')
.select([...OUTBOX_COLUMNS])
.where('created_at', '<', before)
.orderBy('id')
.limit(limit)
.execute();
}
/** Counts the attempt and moves the values to their next try. */
async scheduleRetry(ids: number[], nextAttemptAt: string): Promise<void> {
if (ids.length === 0) return;
await this.db()
.updateTable('place_contrib_outbox')
.set((eb) => ({ attempts: eb('attempts', '+', 1), next_attempt_at: nextAttemptAt }))
.where('id', 'in', ids)
.execute();
}
/** Moves the values to a later try without counting one (the service is pausing, not failing). */
async postpone(ids: number[], nextAttemptAt: string): Promise<void> {
if (ids.length === 0) return;
await this.db()
.updateTable('place_contrib_outbox')
.set({ next_attempt_at: nextAttemptAt })
.where('id', 'in', ids)
.execute();
}
/**
* The value each queued row's place holds now, with the origin row of that
* field: the sender sends only what is still the user's.
*/
async currentOf(ids: number[]): Promise<Array<OutboxCurrentRow & { field: string }>> {
if (ids.length === 0) return [];
return this.db()
.selectFrom('place_contrib_outbox as o')
.innerJoin('places as p', 'p.id', 'o.place_id')
.leftJoin('place_field_origin as f', (join) =>
join.onRef('f.place_id', '=', 'o.place_id').onRef('f.field', '=', 'o.field'),
)
.select([
'o.id as id',
'o.field as field',
'f.origin as origin',
'f.value_hash as value_hash',
'p.website as website',
'p.phone as phone',
'p.email as email',
'p.opening_hours as opening_hours',
'p.description as description',
'p.image_url as image_url',
])
.where('o.id', 'in', ids)
.execute();
}
}
@@ -0,0 +1,148 @@
import type { PlaceFieldOrigin } from '../entities/PlaceFieldOrigin.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
type OriginKyselyDB = Pick<DB, 'place_field_origin' | 'places' | 'place_details_cache'>;
/** Where one field of a place got its current value, and the hash of that value. */
interface PlaceOriginRow {
field: string;
origin: string;
value_hash: string;
}
/** One origin as it is written. */
export interface PlaceOriginWrite {
place_id: number;
field: string;
origin: string;
value_hash: string;
updated_at: string;
}
/** The columns of a place the origin tracking and the contribution read: its shareable details and what names it. */
export interface PlaceShareableRow {
id: number;
name: string;
lat: number | null;
lng: number | null;
address: string | null;
osm_id: string | null;
google_place_id: string | null;
amap_poi_id: string | null;
website: string | null;
phone: string | null;
email: string | null;
opening_hours: string | null;
description: string | null;
image_url: string | null;
}
/** One cached details record: the provider id it is keyed by, its kind (0 lean, 1 expanded, 2 enrichment), the JSON. */
export interface CachedProviderPayload {
place_id: string;
expanded: number;
payload_json: string;
}
const SHAREABLE_COLUMNS = [
'id',
'name',
'lat',
'lng',
'address',
'osm_id',
'google_place_id',
'amap_poi_id',
'website',
'phone',
'email',
'opening_hours',
'description',
'image_url',
] as const;
/**
* `place_field_origin`: per place and shareable field, who set the value it
* holds (the user, a provider, the assistant, a plugin, an import, an
* attachment) and the hash of that value. A row whose hash no longer matches
* the column describes a value that is gone and counts as unknown.
*
* The two reads on other tables are the ones the origin rules need next to it:
* the place's own shareable columns, and the provider records this instance
* cached for the place's ids, so a value claimed as typed can be checked
* against what a provider handed out.
*/
export class PlaceFieldOriginRepository extends TrekRepository<PlaceFieldOrigin> {
private db() {
return this.kysely<OriginKyselyDB>();
}
/** The place's shareable columns, or null when there is no such place. */
async placeValues(placeId: number): Promise<PlaceShareableRow | null> {
const row = await this.db()
.selectFrom('places')
.select([...SHAREABLE_COLUMNS])
.where('id', '=', placeId)
.executeTakeFirst();
return row ?? null;
}
/** The shareable columns of several places, for an import that recorded them all at once. */
async placeValuesMany(placeIds: number[]): Promise<PlaceShareableRow[]> {
if (placeIds.length === 0) return [];
return this.db()
.selectFrom('places')
.select([...SHAREABLE_COLUMNS])
.where('id', 'in', placeIds)
.execute();
}
async originsOf(placeId: number): Promise<PlaceOriginRow[]> {
return this.db()
.selectFrom('place_field_origin')
.select(['field', 'origin', 'value_hash'])
.where('place_id', '=', placeId)
.execute();
}
/** Writes the origins in one statement; a field that has one already gets the new one. */
async upsertOrigins(rows: PlaceOriginWrite[]): Promise<void> {
if (rows.length === 0) return;
await this.db()
.insertInto('place_field_origin')
.values(rows)
.onConflict((oc) =>
oc.columns(['place_id', 'field']).doUpdateSet({
origin: (eb) => eb.ref('excluded.origin'),
value_hash: (eb) => eb.ref('excluded.value_hash'),
updated_at: (eb) => eb.ref('excluded.updated_at'),
}),
)
.execute();
}
/** Forgets the origins of these fields of a place, for a value that was cleared. */
async deleteOrigins(placeId: number, fields: string[]): Promise<number> {
if (fields.length === 0) return 0;
const result = await this.db()
.deleteFrom('place_field_origin')
.where('place_id', '=', placeId)
.where('field', 'in', fields)
.executeTakeFirst();
return Number(result.numDeletedRows);
}
/**
* The details records this instance cached for these provider ids (Google,
* Amap, OpenStreetMap, the TREK index), every language and kind, as stored.
*/
async cachedProviderPayloads(providerIds: string[]): Promise<CachedProviderPayload[]> {
if (providerIds.length === 0) return [];
return this.db()
.selectFrom('place_details_cache')
.select(['place_id', 'expanded', 'payload_json'])
.where('place_id', 'in', providerIds)
.execute();
}
}
+2
View File
@@ -69,6 +69,7 @@ import { PaddleObstaclesModule } from './paddle-obstacles/paddle-obstacles.modul
import { PaddleRoutingModule } from './paddle-routing/paddle-routing.module';
import { PermissionsModule } from './permissions/permissions.module';
import { PhotosModule } from './photos/photos.module';
import { PlaceContribModule } from './place-contrib/place-contrib.module';
import { PlaceEnrichmentModule } from './place-enrichment/place-enrichment.module';
import { PlaceImportModule } from './place-import/place-import.module';
import { PlaceShadowModule } from './place-shadow/place-shadow.module';
@@ -142,6 +143,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
MapsModule,
PlaceImportModule,
GoogleQuotaModule,
PlaceContribModule,
PlaceEnrichmentModule,
PlaceShadowModule,
RouteUsageModule,
+2
View File
@@ -31,6 +31,8 @@ const ACTION_LABELS: Record<string, string> = {
'admin.storage_backfill': 'started a storage sync',
'admin.storage_backfill_cancel': 'cancelled a storage sync',
'admin.storage_stats_refresh': 'refreshed storage usage stats',
'admin.places_contribute_decision': 'decided on sharing place details with TREK Places',
'admin.places_contribute_withdraw': 'withdrew the place details this installation shared',
'immich.private_ip_configured': 'configured Immich with private IP',
'oidc.role_change': 'role changed by OIDC claim mapping',
};
@@ -139,6 +139,13 @@ export const APP_SETTINGS = {
ai_assistant_web_search: { schema: flag, default: 'true' },
/** `urn:uuid:<uuid>`: this install as one host to Sign in with ChatGPT, created on the first sign-in. */
ai_siwc_host_id: { schema: text, default: null },
// Community enrichment of place details (place-contrib). The installation's decision as the
// JSON of placeContribConsentSchema, off until an admin agrees; per admin, when their
// "not now" ends; and why sending waits although an admin agreed (a refused key, a pause
// the service asked for). None is the operator's to set on a managed install.
places_contribute: { schema: text, default: null },
places_contribute_snooze: { schema: text, default: null },
places_contribute_pause: { schema: text, default: null },
/** This installation's key towards the liketrek services, issued on first use (service-identity). */
service_key: { schema: text, default: null, encrypted: 'always', managedLocked: true },
/** The key's bookkeeping as JSON: when to renew, when to ask again after a refusal, a revocation. */
+11
View File
@@ -0,0 +1,11 @@
import { createHash } from 'node:crypto';
/**
* The SHA-256 of a stored value, hex. The origin of a place's field is kept
* with the hash of the value it describes, so a value changed by any path that
* did not record an origin (a migration, a direct SQL fix, an older plugin SDK,
* a restore) no longer matches and counts as unknown.
*/
export function valueHash(value: string): string {
return createHash('sha256').update(value, 'utf8').digest('hex');
}
@@ -98,6 +98,8 @@ export interface TrekPlace {
hours: { osm: string; source: string | null; sourceUrl: string | null } | null;
/** Quoted from the place's own site, when it publishes one for machines. */
description?: { text: string; source: string | null; sourceUrl: string | null } | null;
/** Bumped by the service whenever the community values it overlays for this place change. */
community?: { version?: number } | null;
score?: number;
}
@@ -673,6 +675,8 @@ export function toPlaceRecord(p: TrekPlace): Record<string, unknown> {
// place cost two full round trips to the index. Left as the service shaped
// it — the reader validates the URL before it becomes a link.
description: p.description ?? null,
// Where the cached enrichment of this place has to be read again (place-enrichment).
community_version: typeof p.community?.version === 'number' ? p.community.version : null,
source: 'trek-places',
};
}
@@ -0,0 +1,38 @@
import { readImageHeader } from '../common/image-header';
import { IMAGE_JPEG_QUALITY, IMAGE_MAX_BYTES, IMAGE_MAX_EDGE, IMAGE_MAX_PIXELS } from './place-contrib.constants';
import { Jimp } from 'jimp';
/** The long edges tried, largest first, until the picture fits the byte cap. */
const EDGES = [IMAGE_MAX_EDGE, 1600, 1280, 1024] as const;
/**
* A place picture as it is sent: decoded, its long edge at most 2048 px,
* re-encoded as a JPEG at quality 85 and at most a megabyte. The re-encode is
* what strips the metadata: the encoder writes pixels only, so a camera's EXIF
* (the position it was taken at, the device, the owner) never leaves.
*
* Null for a picture that cannot be sent: one TREK cannot decode (WebP, a
* header that says nothing), one over the pixel cap, or one that stays over
* the byte cap at the smallest edge tried.
*/
export async function contribJpeg(data: Buffer): Promise<Buffer | null> {
const header = readImageHeader(data);
if (!header || header.mimeType === 'image/webp') return null;
if (header.width * header.height > IMAGE_MAX_PIXELS) return null;
try {
const image = await Jimp.read(data, { 'image/jpeg': { maxResolutionInMP: IMAGE_MAX_PIXELS / 1_000_000 } });
for (const edge of EDGES) {
const copy = image.clone();
if (Math.max(copy.width, copy.height) > edge) {
if (copy.width >= copy.height) copy.resize({ w: edge });
else copy.resize({ h: edge });
}
const encoded = Buffer.from(await copy.getBuffer('image/jpeg', { quality: IMAGE_JPEG_QUALITY }));
if (encoded.length <= IMAGE_MAX_BYTES) return encoded;
}
return null;
} catch {
return null;
}
}
@@ -0,0 +1,397 @@
import { PlaceContribLog } from '../../db/entities/PlaceContribLog.entity';
import { PlaceContribOutbox } from '../../db/entities/PlaceContribOutbox.entity';
import type { PlaceContribLogRepository, PlaceContribLogWrite } from '../../db/repositories/PlaceContribLog.repository';
import type {
OutboxCurrentRow,
OutboxRow,
PlaceContribOutboxRepository,
} from '../../db/repositories/PlaceContribOutbox.repository';
import { dbNow } from '../../db/types';
import { logInfo } from '../audit/audit-log.logger';
import { valueHash } from '../common/value-hash';
import { UnitOfWork } from '../database/unit-of-work';
import { StorageService } from '../storage/storage.service';
import { contribJpeg } from './place-contrib-image';
import { PlaceContribSettings } from './place-contrib-settings';
import { PlaceContribClient, type ContribAnswer, type ServedPlace } from './place-contrib.client';
import {
MAX_ATTEMPTS,
NOT_ACCEPTING_WAIT_MS,
OUTBOX_MAX_AGE_DAYS,
PLACE_BODY_MAX_BYTES,
PLACES_PER_RUN,
} from './place-contrib.constants';
import {
UPLOADED_IMAGE_PREFIX,
baseHashOf,
dayOf,
gersOf,
logResultOf,
payloadOf,
requestCid,
retryDelayMs,
summaryOf,
} from './place-contrib.helpers';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import {
PLACE_CONTRIB_TERMS_VERSION,
type PlaceContribField,
type PlaceContribImageAnswer,
type PlaceContribLogResult,
type PlaceContribPlaceAnswer,
type PlaceContribPlaceBody,
} from '@trek/shared';
const DAY_MS = 24 * 3_600_000;
/** The most a stored picture may weigh before it is read for sending: the upload cap. */
const STORED_IMAGE_MAX_BYTES = 20 * 1024 * 1024;
/** Old values are given up on in passes of this many. */
const EXPIRE_BATCH = 500;
/** Whether the run goes on with the next place or stops here (the service asked to wait, the key was refused). */
type Next = 'next' | 'stop';
/** What became of one queued value for good: the log line it gets, and it leaves the queue. */
interface Final {
entry: OutboxRow;
result: PlaceContribLogResult;
reason: string | null;
}
/** What one run did, for the job's log line and the tests. */
interface SendRun {
skipped: 'inactive' | 'paused' | null;
places: number;
expired: number;
}
/**
* Sends what the queue holds to the TREK Places API, one place after the
* other, at most PLACES_PER_RUN per run.
*
* Before a value goes, it is checked against the place once more: it must
* still be what the place holds, and its origin row must still say the user
* typed exactly that (C5). Anything else stays home and is logged as withheld.
* A value the index already serves is not sent either.
*
* Every outcome is one of three: final (logged and gone from the queue),
* another try later (10 min, 30 min, 2 h, 6 h, the service's Retry-After when
* it names one, at most MAX_ATTEMPTS), or a pause for the whole run (a refused
* key, the service not taking contributions). A refusal with a reason is
* final; only an answer that never came, or a server error, is tried again.
*/
@Injectable()
export class PlaceContribSender {
constructor(
@InjectRepository(PlaceContribOutbox) private readonly outbox: PlaceContribOutboxRepository,
@InjectRepository(PlaceContribLog) private readonly log: PlaceContribLogRepository,
private readonly store: PlaceContribSettings,
private readonly client: PlaceContribClient,
private readonly storage: StorageService,
private readonly uow: UnitOfWork,
) {}
/** @txIndependent one place after the other, with a request between each place's writes. */
async run(now: Date = new Date()): Promise<SendRun> {
const fields = await this.store.activeFields();
if (fields.length === 0) return { skipped: 'inactive', places: 0, expired: 0 };
if (await this.store.pauseReason(now)) return { skipped: 'paused', places: 0, expired: 0 };
const expired = await this.expire(now);
const keys = await this.outbox.dueKeys(dbNow(now), PLACES_PER_RUN);
let places = 0;
for (const key of keys) {
places += 1;
if ((await this.sendKey(key, fields, now)) === 'stop') break;
}
if (places > 0 || expired > 0) logInfo(`Places contribution: ${places} place(s) sent, ${expired} expired`);
return { skipped: null, places, expired };
}
/** Values queued for longer than OUTBOX_MAX_AGE_DAYS are dropped as withheld:expired. */
private async expire(now: Date): Promise<number> {
const before = dbNow(new Date(now.getTime() - OUTBOX_MAX_AGE_DAYS * DAY_MS));
const old = await this.outbox.queuedBefore(before, EXPIRE_BATCH);
await this.finish(
old.map((entry): Final => ({ entry, result: 'withheld', reason: 'expired' })),
now,
);
return old.length;
}
/** @txIndependent the stale values settle before the place's request, its answer after it. */
private async sendKey(key: string, fields: PlaceContribField[], now: Date): Promise<Next> {
const entries = await this.outbox.dueFor(key, dbNow(now));
const current = new Map((await this.outbox.currentOf(entries.map((e) => e.id))).map((row) => [row.id, row]));
const stale: Final[] = [];
const valid: OutboxRow[] = [];
for (const entry of entries) {
const reason = staleReason(entry, current.get(entry.id), fields);
if (reason) stale.push({ entry, result: 'withheld', reason });
else valid.push(entry);
}
await this.finish(stale, now);
const text = valid.filter((entry) => entry.field !== 'image');
if (text.length > 0 && (await this.sendText(key, text, now)) === 'stop') return 'stop';
for (const image of valid.filter((entry) => entry.field === 'image')) {
if ((await this.sendImage(image, now)) === 'stop') return 'stop';
}
return 'next';
}
/** @txIndependent the values the index already serves settle before the request, the rest after it. */
private async sendText(key: string, entries: OutboxRow[], now: Date): Promise<Next> {
const gers = gersOf(key);
const served = gers ? await this.client.servedPlace(gers) : null;
const unchanged = entries.filter((entry) => servedValue(served, entry.field) === entry.value);
await this.finish(
unchanged.map((entry): Final => ({ entry, result: 'withheld', reason: 'unchanged' })),
now,
);
const rest = entries.filter((entry) => !unchanged.includes(entry));
if (rest.length === 0) return 'next';
const body = placeBody(key, rest, served);
if (Buffer.byteLength(JSON.stringify(body), 'utf8') > PLACE_BODY_MAX_BYTES) {
await this.finish(
rest.map((entry): Final => ({ entry, result: 'withheld', reason: 'too_large' })),
now,
);
return 'next';
}
return this.settlePlace(rest, await this.client.postPlace(body), now);
}
/** @txIndependent a picture that cannot go settles at once, one that goes after its request. */
private async sendImage(entry: OutboxRow, now: Date): Promise<Next> {
const bytes = await this.storedImage(entry.value.slice(UPLOADED_IMAGE_PREFIX.length));
const jpeg = bytes ? await contribJpeg(bytes) : null;
if (!jpeg) {
await this.finish([{ entry, result: 'withheld', reason: bytes ? 'image_unreadable' : 'image_missing' }], now);
return 'next';
}
const answer = await this.client.postImage(entry.contrib_key, requestCid([entry.cid]), jpeg);
// Images are off on the service until it screens them. That is no failure
// to try again: the picture stays home and the log says so.
if (answer.kind === 'refused' && answer.error === 'images_disabled') {
await this.finish([{ entry, result: 'withheld', reason: 'images_disabled' }], now);
return 'next';
}
return this.settleImage(entry, answer, now);
}
private async settlePlace(
entries: OutboxRow[],
answer: ContribAnswer<PlaceContribPlaceAnswer>,
now: Date,
): Promise<Next> {
if (answer.kind === 'failed') return this.retry(entries, { now, retryAfterMs: answer.retryAfterMs });
if (answer.kind === 'refused') return this.refused(entries, answer, now);
const finals: Final[] = [];
const quota: OutboxRow[] = [];
for (const entry of entries) {
const outcome = answer.body.results[entry.field as PlaceContribField];
if (!outcome) {
finals.push({ entry, result: answer.body.duplicate ? 'duplicate' : 'rejected', reason: 'no_result' });
} else if (outcome.result === 'quota') {
quota.push(entry);
} else {
finals.push({ entry, result: logResultOf(outcome.result), reason: outcome.reason ?? outcome.result });
}
}
await this.uow.transactional(async () => {
await this.finish(finals, now);
if (quota.length > 0) await this.retry(quota, { now, retryAfterMs: null });
});
return 'next';
}
private async settleImage(
entry: OutboxRow,
answer: ContribAnswer<PlaceContribImageAnswer>,
now: Date,
): Promise<Next> {
if (answer.kind === 'failed') return this.retry([entry], { now, retryAfterMs: answer.retryAfterMs });
if (answer.kind === 'refused') return this.refused([entry], answer, now);
const outcome = answer.body.result;
if (outcome.result === 'quota') return this.retry([entry], { now, retryAfterMs: null });
await this.finish([{ entry, result: logResultOf(outcome.result), reason: outcome.reason ?? outcome.result }], now);
return 'next';
}
/** A status with the service's reason: its writes land together. */
private async refused(
entries: OutboxRow[],
refusal: { status: number; error: string; retryAfterMs: number | null },
now: Date,
): Promise<Next> {
return this.uow.transactional(() => this.settleRefusal(entries, refusal, now));
}
private async settleRefusal(
entries: OutboxRow[],
refusal: { status: number; error: string; retryAfterMs: number | null },
now: Date,
): Promise<Next> {
if (refusal.status === 401 || refusal.status === 403) {
// The key is not taken: wait for another one, never fall back to sending without.
await this.store.pauseFor(refusal.status === 401 ? 'key_invalid' : 'key_refused', null);
await this.outbox.postpone(ids(entries), dbNow(new Date(now.getTime() + NOT_ACCEPTING_WAIT_MS)));
return 'stop';
}
if (refusal.status === 429) {
await this.retry(entries, { now, retryAfterMs: refusal.retryAfterMs });
return 'stop';
}
if (refusal.status === 503) {
const until = new Date(now.getTime() + (refusal.retryAfterMs ?? NOT_ACCEPTING_WAIT_MS));
await this.store.pauseFor('not_accepting', until);
await this.outbox.postpone(ids(entries), dbNow(until));
return 'stop';
}
const refusedField = /^field_not_accepted:([a-z_]+)$/.exec(refusal.error)?.[1];
if (refusedField) {
// The service names the one field it does not take; the others go again
// on the next run, without it, and without counting an attempt.
const [taken, others] = partition(entries, (entry) => entry.field === refusedField);
await this.finish(
taken.map((entry): Final => ({ entry, result: 'rejected', reason: refusal.error })),
now,
);
await this.outbox.postpone(ids(others), dbNow(now));
return 'next';
}
await this.finish(
entries.map((entry): Final => ({ entry, result: 'rejected', reason: refusal.error })),
now,
);
return 'next';
}
/** Another try later, or given up after MAX_ATTEMPTS. */
private async retry(entries: OutboxRow[], opts: { now: Date; retryAfterMs: number | null }): Promise<Next> {
const [givenUp, again] = partition(entries, (entry) => entry.attempts + 1 >= MAX_ATTEMPTS);
const attempts = Math.max(1, ...again.map((entry) => entry.attempts + 1));
const next = dbNow(new Date(opts.now.getTime() + (opts.retryAfterMs ?? retryDelayMs(attempts))));
await this.uow.transactional(async () => {
await this.outbox.scheduleRetry(ids(again), next);
await this.finishInTx(
givenUp.map((entry): Final => ({ entry, result: 'withheld', reason: 'gave_up' })),
opts.now,
);
});
return 'next';
}
/** Logs the outcomes and takes the values out of the queue, together. */
private async finish(finals: Final[], now: Date): Promise<void> {
if (finals.length === 0) return;
await this.uow.transactional(() => this.finishInTx(finals, now));
}
private async finishInTx(finals: Final[], now: Date): Promise<void> {
if (finals.length === 0) return;
await this.log.insertLines(finals.map((final) => logLine(final, now)));
await this.outbox.deleteIds(finals.map((final) => final.entry.id));
}
/** The bytes of an uploaded place picture, null when it is gone or heavier than any upload could be. */
private async storedImage(name: string): Promise<Buffer | null> {
if (!name || name.includes('/')) return null;
try {
const stat = await this.storage.stat('places', name);
if (!stat || stat.size > STORED_IMAGE_MAX_BYTES) return null;
const { stream } = await this.storage.getStream('places', name);
const chunks: Buffer[] = [];
let total = 0;
for await (const chunk of stream) {
const part = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array);
total += part.length;
if (total > STORED_IMAGE_MAX_BYTES) {
stream.destroy();
return null;
}
chunks.push(part);
}
return Buffer.concat(chunks);
} catch {
return null;
}
}
}
/** Why a queued value may not go any more, or null when it still may. */
function staleReason(
entry: OutboxRow,
current: OutboxCurrentRow | undefined,
fields: readonly PlaceContribField[],
): string | null {
const field = entry.field as PlaceContribField;
if (!fields.includes(field)) return 'field_off';
if (!current || current.origin !== 'user' || !current.value_hash) return 'origin_changed';
const column = columnOf(current, field);
if (column === null || valueHash(column) !== current.value_hash) return 'origin_stale';
const payload = payloadOf(field, column);
return 'value' in payload && payload.value === entry.value ? null : 'value_changed';
}
/** The column a field is stored in. */
function columnOf(row: OutboxCurrentRow, field: PlaceContribField): string | null {
return field === 'image' ? row.image_url : row[field];
}
/** What the index serves for a field, in the form a queued value has; null when it serves nothing. */
function servedValue(served: ServedPlace | null, field: string): string | null {
if (!served || field === 'image') return null;
const raw = served[field as Exclude<PlaceContribField, 'image'>];
if (!raw) return null;
// Served hours are OSM syntax already, which is the form a queued value has.
if (field === 'opening_hours') return raw.trim() || null;
const payload = payloadOf(field as PlaceContribField, raw);
return 'value' in payload ? payload.value : null;
}
function placeBody(key: string, entries: OutboxRow[], served: ServedPlace | null): PlaceContribPlaceBody {
const first = entries[0];
const fields: PlaceContribPlaceBody['fields'] = {};
for (const entry of entries) {
const field = entry.field as Exclude<PlaceContribField, 'image'>;
fields[field] = { value: entry.value, baseHash: baseHashOf(served?.[field]) };
}
return {
v: 1,
termsVersion: PLACE_CONTRIB_TERMS_VERSION,
cid: requestCid(entries.map((entry) => entry.cid)),
key,
fields,
place: {
name: first.place_name.slice(0, 200),
lat: first.lat,
lng: first.lng,
country: first.country && /^[A-Z]{2}$/.test(first.country) ? first.country : null,
},
};
}
function logLine(final: Final, now: Date): PlaceContribLogWrite {
const field = final.entry.field as PlaceContribField;
return {
day: dayOf(now),
contrib_key: final.entry.contrib_key,
place_name: final.entry.place_name,
field,
value_summary: summaryOf(field, final.entry.value),
result: final.result,
reason: final.reason?.slice(0, 200) ?? null,
};
}
function ids(entries: OutboxRow[]): number[] {
return entries.map((entry) => entry.id);
}
function partition<T>(items: T[], test: (item: T) => boolean): [T[], T[]] {
const yes: T[] = [];
const no: T[] = [];
for (const item of items) (test(item) ? yes : no).push(item);
return [yes, no];
}
@@ -0,0 +1,135 @@
import {
PLACES_CONTRIBUTE_CONSENT,
PLACES_CONTRIBUTE_PAUSE,
PLACES_CONTRIBUTE_SNOOZE,
type PlacesContributePause,
} from '../../db/json-columns';
import { decodeJson, encodeJson } from '../../utils/json-column';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { servicesConfig } from '../app-config/tokens';
import { SettingsService } from '../settings/settings.service';
import { PlaceContribClient } from './place-contrib.client';
import { CONTRIB_ORIGIN } from './place-contrib.constants';
import { Inject, Injectable } from '@nestjs/common';
import type { ConfigType } from '@nestjs/config';
import {
PLACE_CONTRIB_FIELDS,
PLACE_CONTRIB_TERMS_VERSION,
type PlaceContribConsent,
type PlaceContribField,
type PlaceContribIneligibleReason,
type PlaceContribPauseReason,
} from '@trek/shared';
/** Where an installation stands before any admin decision: whether it may send at all, and if not, why. */
type Eligibility = { eligible: true; reason: null } | { eligible: false; reason: PlaceContribIneligibleReason };
/**
* The stored side of the community enrichment: the admin's decision, the
* per-admin snooze and the pause, all in app_settings, and whether this
* installation may send at all.
*
* Eligibility is not stored. It follows the deployment, read live: the
* TREK_PLACES_CONTRIBUTE ceiling, a production instance that is no demo, the
* index on and at the public address, TREK_SERVICES on and a key in hand.
* Development, test and demo instances never send, whatever an admin chose.
*/
@Injectable()
export class PlaceContribSettings {
constructor(
private readonly settings: SettingsService,
private readonly env: RuntimeEnvService,
@Inject(servicesConfig.KEY) private readonly services: ConfigType<typeof servicesConfig>,
private readonly client: PlaceContribClient,
) {}
ceiling(): 'off' | 'admin' {
return this.env.env().maps.trekPlacesContribute;
}
eligibility(): Eligibility {
const maps = this.env.env().maps;
const reason = ((): PlaceContribIneligibleReason | null => {
if (maps.trekPlacesContribute !== 'admin') return 'env_off';
if (!this.env.isProduction()) return 'not_production';
if (this.env.isDemoMode()) return 'demo';
if (!maps.trekPlacesEnabled) return 'index_off';
if (customPlacesUrl(maps.trekPlacesUrl)) return 'custom_places_url';
if (this.services.mode === 'off') return 'services_off';
if (!this.client.hasKey()) return 'no_key';
return null;
})();
return reason === null ? { eligible: true, reason: null } : { eligible: false, reason };
}
async consent(): Promise<PlaceContribConsent> {
return decodeJson(PLACES_CONTRIBUTE_CONSENT, await this.settings.getAppSetting('places_contribute'), 'consent');
}
async writeConsent(consent: PlaceContribConsent): Promise<void> {
await this.settings.setAppSettings({ places_contribute: encodeJson(PLACES_CONTRIBUTE_CONSENT, consent) });
}
/** The fields an agreement to the current terms switches on; none without one. */
async activeFields(): Promise<PlaceContribField[]> {
if (!this.eligibility().eligible) return [];
const consent = await this.consent();
if (!agreedToCurrentTerms(consent)) return [];
return PLACE_CONTRIB_FIELDS.filter((field) => consent.fields[field]);
}
async snoozedUntil(adminId: number, now: Date): Promise<string | null> {
const until = (await this.snoozes())[String(adminId)] ?? null;
return until && Date.parse(until) > now.getTime() ? until : null;
}
async snooze(adminId: number, until: Date): Promise<void> {
const snoozes = { ...(await this.snoozes()), [String(adminId)]: until.toISOString() };
await this.settings.setAppSettings({ places_contribute_snooze: encodeJson(PLACES_CONTRIBUTE_SNOOZE, snoozes) });
}
/** The pause in force now: a refused key until there is another one, the service's wait until it ends. */
async pauseReason(now: Date): Promise<PlaceContribPauseReason | null> {
const pause = await this.pause();
if (!pause) return null;
if (pause.reason === 'not_accepting')
return pause.until && Date.parse(pause.until) > now.getTime() ? pause.reason : null;
return pause.key === this.client.keyFingerprint() ? pause.reason : null;
}
async pauseFor(reason: PlaceContribPauseReason, until: Date | null): Promise<void> {
const pause: PlacesContributePause = {
reason,
key: reason === 'not_accepting' ? null : this.client.keyFingerprint(),
until: until?.toISOString() ?? null,
};
await this.settings.setAppSettings({ places_contribute_pause: encodeJson(PLACES_CONTRIBUTE_PAUSE, pause) });
}
async clearPause(): Promise<void> {
await this.settings.deleteAppSettings(['places_contribute_pause']);
}
private async snoozes(): Promise<Record<string, string>> {
return decodeJson(
PLACES_CONTRIBUTE_SNOOZE,
await this.settings.getAppSetting('places_contribute_snooze'),
'snooze',
);
}
private async pause(): Promise<PlacesContributePause | null> {
return decodeJson(PLACES_CONTRIBUTE_PAUSE, await this.settings.getAppSetting('places_contribute_pause'), 'pause');
}
}
/** Whether a decision is a standing agreement to the terms in force. */
export function agreedToCurrentTerms(consent: PlaceContribConsent): boolean {
return consent.enabled && consent.decision === 'agreed' && consent.termsVersion === PLACE_CONTRIB_TERMS_VERSION;
}
/** An own TREK_PLACES_URL: anything but unset or the public instance itself. */
function customPlacesUrl(configured: string | undefined): boolean {
const url = configured?.trim().replace(/\/+$/, '');
return !!url && url !== CONTRIB_ORIGIN;
}
@@ -0,0 +1,185 @@
import { discardBody, exceedsDeclaredLength, readCappedJson } from '../../utils/cappedFetch';
import { ServiceIdentityPort } from '../service-identity/service-identity.interface';
import { ANSWER_MAX_BYTES, CONTRIB_ORIGIN, REQUEST_TIMEOUT_MS } from './place-contrib.constants';
import { retryAfterMs } from './place-contrib.helpers';
import { Injectable } from '@nestjs/common';
import {
placeContribErrorSchema,
placeContribImageAnswerSchema,
placeContribPlaceAnswerSchema,
placeContribWithdrawAnswerSchema,
type PlaceContribImageAnswer,
type PlaceContribPlaceAnswer,
type PlaceContribPlaceBody,
type PlaceContribWithdrawAnswer,
} from '@trek/shared';
import { createHash } from 'node:crypto';
import { z, type ZodType } from 'zod';
/**
* What one request came back with:
* - `ok`: a 200 the schema describes;
* - `refused`: a status with the service's `{ error }` code;
* - `failed`: no answer, a server error, or an answer that is not what the
* service sends (worth another try later).
*/
export type ContribAnswer<T> =
| { kind: 'ok'; body: T }
| { kind: 'refused'; status: number; error: string; retryAfterMs: number | null }
| { kind: 'failed'; reason: string; retryAfterMs: number | null };
/** What the index serves for a place right now, community values included: the base of a contribution. */
export interface ServedPlace {
website: string | null;
phone: string | null;
email: string | null;
opening_hours: string | null;
description: string | null;
}
/** A place lookup is a few kB; it carries more than the contribution answers do. */
const PLACE_LOOKUP_MAX_BYTES = 512 * 1024;
const optionalText = z.string().max(4000).nullable().optional();
const servedPlaceSchema = z.object({
place: z.object({
contact: z.object({ website: optionalText, phone: optionalText, email: optionalText }).nullable().optional(),
hours: z.object({ osm: optionalText }).nullable().optional(),
description: z.object({ text: optionalText }).nullable().optional(),
}),
});
/**
* The client of the contribution routes on the TREK Places API.
*
* Every request carries the installation key and goes only out with one: there
* is no pool to fall back on for these routes, so a missing key sends nothing.
* The key goes to the allowlisted host only (ServiceIdentityPort decides, as for
* the search), and each answer is shown to the identity like every other, so a
* refused key is noticed there too.
*/
@Injectable()
export class PlaceContribClient {
constructor(private readonly identity: ServiceIdentityPort) {}
/** Whether a request would carry the installation key right now. */
hasKey(): boolean {
return this.authorization() !== null;
}
/** A short fingerprint of the key in use, so a pause over a refused key ends once there is a new one. */
keyFingerprint(): string | null {
const auth = this.authorization();
return auth ? createHash('sha256').update(auth).digest('hex').slice(0, 16) : null;
}
async postPlace(body: PlaceContribPlaceBody): Promise<ContribAnswer<PlaceContribPlaceAnswer>> {
return this.send(
'/v1/contrib/place',
{ method: 'POST', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } },
placeContribPlaceAnswerSchema,
);
}
async postImage(key: string, cid: string, jpeg: Buffer): Promise<ContribAnswer<PlaceContribImageAnswer>> {
return this.send(
'/v1/contrib/image',
{
method: 'POST',
body: new Uint8Array(jpeg),
headers: { 'Content-Type': 'image/jpeg', 'X-TREK-Contrib-Key': key, 'X-TREK-Contrib-Cid': cid },
},
placeContribImageAnswerSchema,
);
}
/** Withdraws what this installation sent: everything, or one field, key or image. */
async withdraw(
scope: { field?: string; key?: string; image?: string } = {},
): Promise<ContribAnswer<PlaceContribWithdrawAnswer>> {
const params = new URLSearchParams();
for (const [name, value] of Object.entries(scope)) if (value) params.set(name, value);
const query = params.toString();
return this.send(
`/v1/contrib/install${query ? `?${query}` : ''}`,
{ method: 'DELETE' },
placeContribWithdrawAnswerSchema,
);
}
/**
* What the index serves for a gers place now, null when it cannot say. Asked
* with the key like the search, so it is counted like one.
*/
async servedPlace(gers: string): Promise<ServedPlace | null> {
const answer = await this.send(
`/v1/place/${encodeURIComponent(gers)}`,
{ method: 'GET' },
servedPlaceSchema,
PLACE_LOOKUP_MAX_BYTES,
);
if (answer.kind !== 'ok') return null;
const { contact, hours, description } = answer.body.place;
return {
website: contact?.website ?? null,
phone: contact?.phone ?? null,
email: contact?.email ?? null,
opening_hours: hours?.osm ?? null,
description: description?.text ?? null,
};
}
private authorization(): string | null {
return this.identity.headersFor(new URL(CONTRIB_ORIGIN)).Authorization ?? null;
}
private async send<T>(
path: string,
init: { method: string; body?: string | Uint8Array; headers?: Record<string, string> },
schema: ZodType<T>,
maxBytes: number = ANSWER_MAX_BYTES,
): Promise<ContribAnswer<T>> {
const url = new URL(CONTRIB_ORIGIN + path);
const own = this.identity.headersFor(url);
if (!own.Authorization) return { kind: 'refused', status: 401, error: 'no_key', retryAfterMs: null };
let res: Response;
try {
res = await fetch(url, {
method: init.method,
body: init.body,
headers: { Accept: 'application/json', ...init.headers, ...own },
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
} catch (err) {
return { kind: 'failed', reason: err instanceof Error ? err.name : 'network', retryAfterMs: null };
}
this.identity.observe(url, res);
return readAnswer(res, schema, maxBytes);
}
}
async function readAnswer<T>(res: Response, schema: ZodType<T>, maxBytes: number): Promise<ContribAnswer<T>> {
const retryAfter = retryAfterMs(res.headers.get('retry-after'));
if (exceedsDeclaredLength(res, maxBytes)) {
discardBody(res);
return { kind: 'failed', reason: 'answer_too_large', retryAfterMs: retryAfter };
}
const body = await readCappedJson<unknown>(res, maxBytes).catch(() => undefined);
if (res.ok) {
const parsed = schema.safeParse(body);
return parsed.success
? { kind: 'ok', body: parsed.data }
: { kind: 'failed', reason: 'answer_unreadable', retryAfterMs: retryAfter };
}
if (res.status >= 500 && res.status !== 503) {
return { kind: 'failed', reason: `status_${res.status}`, retryAfterMs: retryAfter };
}
const refusal = placeContribErrorSchema.safeParse(body);
return {
kind: 'refused',
status: res.status,
error: refusal.success ? refusal.data.error : `status_${res.status}`,
retryAfterMs: retryAfter,
};
}
@@ -0,0 +1,57 @@
/**
* The numbers the community enrichment works with, in one place.
*/
/**
* Where contributions go. Only the public instance takes them: an install with
* its own TREK_PLACES_URL is not eligible, so this is never another host.
*/
export const CONTRIB_ORIGIN = 'https://places.liketrek.com';
/** One place per request, and the service refuses a body over this. */
export const PLACE_BODY_MAX_BYTES = 8 * 1024;
/** Every answer is a short JSON object; anything longer is not read. */
export const ANSWER_MAX_BYTES = 64 * 1024;
export const REQUEST_TIMEOUT_MS = 15_000;
/** A value waits a few minutes before it goes, a random share of this window per place. */
export const ELIGIBLE_DELAY_MIN_MS = 2 * 60_000;
export const ELIGIBLE_DELAY_MAX_MS = 10 * 60_000;
/** The waits after the first, second, ... failed attempt; the last one repeats. */
export const RETRY_DELAYS_MS = [10 * 60_000, 30 * 60_000, 2 * 3_600_000, 6 * 3_600_000] as const;
/** After this many failed attempts a value is given up on. */
export const MAX_ATTEMPTS = 8;
/** The longest Retry-After the sender honours; a larger one is capped to it. */
export const MAX_RETRY_AFTER_MS = 24 * 3_600_000;
/** How long the sender waits when the service is not taking contributions and says nothing about when. */
export const NOT_ACCEPTING_WAIT_MS = 30 * 60_000;
/** The queue never holds more than this; at the cap nothing more is queued. */
export const OUTBOX_CAP = 5_000;
/** A value still queued after this long is dropped and logged as withheld. */
export const OUTBOX_MAX_AGE_DAYS = 30;
/** At most this many places per run of the sender, one after the other. */
export const PLACES_PER_RUN = 20;
/** Every two minutes. */
export const SEND_SCHEDULE = '*/2 * * * *';
/** The log retention, nightly at 3:50, clear of the 3:00 idempotency purge and 3:40 shadow retention. */
export const LOG_RETENTION_SCHEDULE = '50 3 * * *';
export const LOG_RETENTION_DAYS = 90;
/** The admin state counts the log of this many days. */
export const COUNT_WINDOW_DAYS = 30;
/** "Not now" keeps the prompt away from this admin for two weeks. */
export const SNOOZE_DAYS = 14;
/** A picture is sent at most this large: long edge, JPEG quality, bytes. */
export const IMAGE_MAX_EDGE = 2048;
export const IMAGE_JPEG_QUALITY = 85;
export const IMAGE_MAX_BYTES = 1024 * 1024;
/** A picture is decoded only up to this many pixels; a larger one is not sent. */
export const IMAGE_MAX_PIXELS = 40_000_000;
/** The longest value a field sends, and the longest summary of it the log keeps. */
export const VALUE_MAX_CHARS = 4_000;
export const SUMMARY_MAX_CHARS = 80;
@@ -0,0 +1,95 @@
import type { User } from '../../types';
import { AuditService } from '../audit/audit.service';
import { getClientIp } from '../audit/client-ip';
import { AdminGuard } from '../auth-core/admin.guard';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { PlaceContribDecisionDto, PlaceContribLogQueryDto, PlaceContribWithdrawDto } from './place-contrib.dto';
import { PlaceContribService } from './place-contrib.service';
import { Body, Controller, Get, HttpCode, Post, Put, Query, Req, UseGuards } from '@nestjs/common';
import {
placeContribLogResponseSchema,
placeContribStateSchema,
placeContribWithdrawResponseSchema,
type PlaceContribDecisionRequest,
type PlaceContribLogResponse,
type PlaceContribState,
type PlaceContribWithdrawResponse,
} from '@trek/shared';
import type { Request } from 'express';
/**
* /api/admin/places-contribute: the admin's side of sharing place details with
* the TREK Places API. The state the panel and the first-visit prompt read, the
* decision, the transmission log, and withdrawing everything that was sent.
*
* Admin only, like every instance setting. On a managed install the tenant's
* own admin decides too: the operator never answers for them.
*/
@Controller('api/admin/places-contribute')
@UseGuards(JwtAuthGuard, AdminGuard)
export class PlaceContribController {
constructor(
private readonly contrib: PlaceContribService,
private readonly audit: AuditService,
) {}
@Get()
@ResponseContract(placeContribStateSchema)
async state(@CurrentUser() user: User): Promise<PlaceContribState> {
return this.contrib.state(user.id);
}
@Put('decision')
@ResponseContract(placeContribStateSchema)
async decide(
@CurrentUser() user: User,
@Body() body: PlaceContribDecisionDto,
@Req() req: Request,
): Promise<PlaceContribState> {
// The pipe validated the body against the full union; the DTO only types its shared fields.
const state = await this.contrib.decide(user.id, body as PlaceContribDecisionRequest);
await this.audit.writeAudit({
userId: user.id,
action: 'admin.places_contribute_decision',
details: decisionDetails(body),
ip: getClientIp(req),
});
return state;
}
@Get('log')
@ResponseContract(placeContribLogResponseSchema)
async log(@Query() query: PlaceContribLogQueryDto): Promise<PlaceContribLogResponse> {
return this.contrib.logPage(query);
}
@Post('withdraw')
@HttpCode(200)
@ResponseContract(placeContribWithdrawResponseSchema)
async withdraw(
@CurrentUser() user: User,
@Body() _body: PlaceContribWithdrawDto,
@Req() req: Request,
): Promise<PlaceContribWithdrawResponse> {
const result = await this.contrib.withdrawAll();
await this.audit.writeAudit({
userId: user.id,
action: 'admin.places_contribute_withdraw',
details: { cleared: result.cleared },
ip: getClientIp(req),
});
return result;
}
}
/** What the audit row keeps of a decision: the action, and the switches or terms it named. */
function decisionDetails(body: PlaceContribDecisionDto): Record<string, unknown> {
const details: Record<string, unknown> = { action: body.action };
if (body.termsVersion !== undefined) details.termsVersion = body.termsVersion;
if (body.fields !== undefined) details.fields = body.fields;
if (body.withdraw !== undefined) details.withdraw = body.withdraw;
return details;
}
@@ -0,0 +1,29 @@
import {
placeContribDecisionRequestSchema,
placeContribLogQuerySchema,
placeContribWithdrawRequestSchema,
type PlaceContribDecisionRequest,
type PlaceContribFieldSwitches,
} from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
import type { z } from 'zod';
/**
* The fields the decision's variants share. Its contract is a union over
* `action`, and a class cannot extend a union: the DTO is typed as this common
* shape while the pipe validates against the full union.
*/
interface PlaceContribDecisionFields {
action: PlaceContribDecisionRequest['action'];
termsVersion?: number;
fields?: PlaceContribFieldSwitches;
withdraw?: boolean;
}
/** Zod-pipe wrappers over the @trek/shared contracts of /api/admin/places-contribute. */
export class PlaceContribDecisionDto extends createZodDto(
placeContribDecisionRequestSchema as z.ZodType<PlaceContribDecisionFields>,
) {}
export class PlaceContribLogQueryDto extends createZodDto(placeContribLogQuerySchema) {}
export class PlaceContribWithdrawDto extends createZodDto(placeContribWithdrawRequestSchema) {}
@@ -0,0 +1,181 @@
import {
ELIGIBLE_DELAY_MAX_MS,
ELIGIBLE_DELAY_MIN_MS,
MAX_RETRY_AFTER_MS,
RETRY_DELAYS_MS,
SUMMARY_MAX_CHARS,
VALUE_MAX_CHARS,
} from './place-contrib.constants';
import {
parsePlaceHours,
placeWebsiteSchema,
type PlaceContribField,
type PlaceContribFieldResult,
type PlaceContribLogResult,
type PlaceHoursDay,
type PlaceOpeningHours,
} from '@trek/shared';
import { createHash, randomInt } from 'node:crypto';
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const HEX32 = /^[0-9a-f]{32}$/i;
const OSM_ID = /^(node|way|relation):(\d{1,15})$/;
/** Where the place pictures users upload live (the places domain's `placeImageUrl`). */
export const UPLOADED_IMAGE_PREFIX = '/uploads/places/';
/**
* The key the service files a place under: `gers:<id>` for a place from the
* TREK index, `osm:<type>/<id>` for an OpenStreetMap element. A place without
* one (a free pin, a Google or Amap place) is not sent in this version.
*/
export function contribKeyOf(osmId: string | null | undefined): string | null {
const id = osmId?.trim() ?? '';
if (id.startsWith('gers:')) {
const gers = id.slice('gers:'.length).toLowerCase();
return UUID.test(gers) || HEX32.test(gers) ? `gers:${gers}` : null;
}
const osm = OSM_ID.exec(id);
return osm ? `osm:${osm[1]}/${osm[2]}` : null;
}
/** The gers id inside a key, for the lookup of what the service serves for it. */
export function gersOf(key: string): string | null {
return key.startsWith('gers:') ? key.slice('gers:'.length) : null;
}
/** What a field sends, or why it stays home. */
type ContribPayload = { value: string } | { withheld: string };
const DAY_NAMES = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'] as const;
/** One day in OSM syntax: `off`, `HH:MM-HH:MM`, or null for a day nobody set. */
function daySpec(day: PlaceHoursDay): string | null {
if (day.closed) return 'off';
if (!day.open || !day.close) return null;
// An interval that ends before it starts runs past midnight, which OSM
// spells the same way: 22:00-02:00.
return `${day.open}-${day.close}`;
}
/**
* The week as an OSM opening_hours rule, consecutive days with the same hours
* folded into a range: `Mo-Fr 09:00-18:00; Sa 10:00-14:00; Su off`. Only the
* days the user set are named; a day without times stays out instead of being
* claimed as closed. Null for a week that says nothing.
*/
export function osmHoursOf(week: PlaceOpeningHours): string | null {
const specs = week.map(daySpec);
const parts: string[] = [];
let start = 0;
while (start < specs.length) {
let end = start;
while (end + 1 < specs.length && specs[end + 1] === specs[start]) end += 1;
const spec = specs[start];
if (spec !== null) {
const days = start === end ? DAY_NAMES[start] : `${DAY_NAMES[start]}-${DAY_NAMES[end]}`;
parts.push(`${days} ${spec}`);
}
start = end + 1;
}
return parts.length ? parts.join('; ') : null;
}
function hoursPayload(raw: string): ContribPayload {
const week = parsePlaceHours(raw);
if (!week) return { withheld: 'hours_unreadable' };
if (week.every((day) => day.closed)) return { withheld: 'hours_all_closed' };
const value = osmHoursOf(week);
return value ? { value } : { withheld: 'hours_empty' };
}
/**
* The value a field sends, normalized the way the service reads it, or the
* reason it is kept home. The service normalizes again and its reading wins;
* this only keeps out what it would refuse anyway.
*/
export function payloadOf(field: PlaceContribField, raw: string): ContribPayload {
const text = raw.trim();
if (!text) return { withheld: 'empty' };
switch (field) {
case 'website': {
const parsed = placeWebsiteSchema.safeParse(text);
return parsed.success && parsed.data ? { value: parsed.data } : { withheld: 'website_invalid' };
}
case 'email':
return { value: text.toLowerCase() };
case 'opening_hours':
return hoursPayload(text);
case 'image':
// Only a picture uploaded to the place itself; a link, a provider's photo
// or an inline image is not the user's to give away.
return text.startsWith(UPLOADED_IMAGE_PREFIX) ? { value: text } : { withheld: 'image_not_uploaded' };
default:
return text.length > VALUE_MAX_CHARS ? { withheld: 'too_long' } : { value: text };
}
}
/** A short line for the log: enough to recognise the value, never the whole description. */
export function summaryOf(field: PlaceContribField, value: string): string {
if (field === 'image') return 'image';
const line = value.replace(/\s+/g, ' ').trim();
return line.length > SUMMARY_MAX_CHARS ? `${line.slice(0, SUMMARY_MAX_CHARS - 1)}…` : line;
}
/** The `baseHash` the service compares with: a prefix of the SHA-256 of the value it served. */
export function baseHashOf(value: string | null | undefined): string | null {
const text = value?.trim();
return text ? createHash('sha256').update(text, 'utf8').digest('hex').slice(0, 16) : null;
}
/**
* The idempotency id of one request: stable for the same queued values, so a
* retry after a lost answer is recognised as the same contribution, and new
* as soon as one of them was replaced.
*/
export function requestCid(entryCids: readonly string[]): string {
const digest = createHash('sha256')
.update([...entryCids].sort().join(','))
.digest('base64url');
return digest.slice(0, 32);
}
/** A fresh id for a queued value. */
export function newEntryCid(): string {
return createHash('sha256')
.update(`${Date.now()}:${randomInt(2 ** 47)}`)
.digest('base64url')
.slice(0, 24);
}
/** A few minutes, a different share for every place, so a trip's places do not all go together. */
export function eligibleDelayMs(): number {
return randomInt(ELIGIBLE_DELAY_MIN_MS, ELIGIBLE_DELAY_MAX_MS + 1);
}
/** The wait after `attempts` failed attempts (1 for the first). */
export function retryDelayMs(attempts: number): number {
const index = Math.min(Math.max(attempts, 1), RETRY_DELAYS_MS.length) - 1;
return RETRY_DELAYS_MS[index];
}
/** A Retry-After header in milliseconds (seconds or an HTTP date), capped; null when there is none or it is unreadable. */
export function retryAfterMs(header: string | null, now: number = Date.now()): number | null {
const text = header?.trim();
if (!text) return null;
const seconds = /^\d+$/.test(text) ? Number(text) * 1000 : Date.parse(text) - now;
if (!Number.isFinite(seconds) || seconds < 0) return null;
return Math.min(seconds, MAX_RETRY_AFTER_MS);
}
/** How the log records what the service made of a field. */
export function logResultOf(result: Exclude<PlaceContribFieldResult, 'quota'>): PlaceContribLogResult {
if (result === 'unchanged') return 'duplicate';
if (result === 'rejected') return 'rejected';
return 'accepted';
}
/** The day of a moment as the log keeps it, UTC. */
export function dayOf(at: Date): string {
return at.toISOString().slice(0, 10);
}
@@ -0,0 +1,49 @@
import { PlaceContribLog } from '../../db/entities/PlaceContribLog.entity';
import type { PlaceContribLogRepository } from '../../db/repositories/PlaceContribLog.repository';
import { logError, logInfo } from '../audit/audit-log.logger';
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { PlaceContribSender } from './place-contrib-sender.service';
import { LOG_RETENTION_DAYS, LOG_RETENTION_SCHEDULE, SEND_SCHEDULE } from './place-contrib.constants';
import { dayOf } from './place-contrib.helpers';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
const DAY_MS = 24 * 3_600_000;
/**
* The two crons of the community enrichment: the sender every two minutes,
* which does nothing unless the installation is eligible and an admin agreed,
* and the nightly retention of the transmission log (90 days), which runs
* whatever the decision so a log switched off still ages out.
*/
@Injectable()
export class PlaceContribJob implements OnApplicationBootstrap {
constructor(
private readonly sender: PlaceContribSender,
@InjectRepository(PlaceContribLog) private readonly log: PlaceContribLogRepository,
private readonly registrar: CronRegistrarService,
) {}
onApplicationBootstrap(): void {
if (!this.registrar.isEnabled()) return;
this.registrar.register('place-contrib-send', SEND_SCHEDULE, () => this.send());
this.registrar.register('place-contrib-log-retention', LOG_RETENTION_SCHEDULE, () => this.retain());
}
async send(): Promise<void> {
try {
await this.sender.run();
} catch (err: unknown) {
logError(`Places contribution: the run failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
async retain(now: Date = new Date()): Promise<void> {
try {
const removed = await this.log.purgeBefore(dayOf(new Date(now.getTime() - LOG_RETENTION_DAYS * DAY_MS)));
if (removed > 0) logInfo(`Places contribution: removed ${removed} log line(s) past ${LOG_RETENTION_DAYS} days`);
} catch (err: unknown) {
logError(`Places contribution: log retention failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
}
@@ -0,0 +1,38 @@
import { PlaceContribLog } from '../../db/entities/PlaceContribLog.entity';
import { PlaceContribOutbox } from '../../db/entities/PlaceContribOutbox.entity';
import { AppConfigModule } from '../app-config/app-config.module';
import { AuditModule } from '../audit/audit.module';
import { SchedulingModule } from '../scheduling/scheduling.module';
import { ServiceIdentityModule } from '../service-identity/service-identity.module';
import { SettingsModule } from '../settings/settings.module';
import { StorageModule } from '../storage/storage.module';
import { PlaceContribSender } from './place-contrib-sender.service';
import { PlaceContribSettings } from './place-contrib-settings';
import { PlaceContribClient } from './place-contrib.client';
import { PlaceContribController } from './place-contrib.controller';
import { PlaceContribJob } from './place-contrib.job';
import { PlaceContribService } from './place-contrib.service';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module } from '@nestjs/common';
/**
* Community enrichment of place details: the admin's decision, the queue of
* values users typed in, the cron that sends them to the TREK Places API and
* the transmission log. Exports PlaceContribService for the places domain,
* whose origin tracking feeds the queue after every place write.
*/
@Module({
imports: [
AppConfigModule,
AuditModule,
SchedulingModule,
ServiceIdentityModule,
SettingsModule,
StorageModule,
MikroOrmModule.forFeature([PlaceContribOutbox, PlaceContribLog]),
],
controllers: [PlaceContribController],
providers: [PlaceContribService, PlaceContribSettings, PlaceContribClient, PlaceContribSender, PlaceContribJob],
exports: [PlaceContribService],
})
export class PlaceContribModule {}
@@ -0,0 +1,309 @@
import { PlaceContribLog } from '../../db/entities/PlaceContribLog.entity';
import { PlaceContribOutbox } from '../../db/entities/PlaceContribOutbox.entity';
import type { PlaceContribLogRepository, PlaceContribLogWrite } from '../../db/repositories/PlaceContribLog.repository';
import type { PlaceContribOutboxRepository } from '../../db/repositories/PlaceContribOutbox.repository';
import { dbNow } from '../../db/types';
import { logWarn } from '../audit/audit-log.logger';
import { DomainError, badRequest, conflict } from '../common/domain-error';
import { UnitOfWork } from '../database/unit-of-work';
import { SettingsService } from '../settings/settings.service';
import { agreedToCurrentTerms, PlaceContribSettings } from './place-contrib-settings';
import { PlaceContribClient } from './place-contrib.client';
import { COUNT_WINDOW_DAYS, OUTBOX_CAP, SNOOZE_DAYS } from './place-contrib.constants';
import { contribKeyOf, dayOf, eligibleDelayMs, newEntryCid, payloadOf, summaryOf } from './place-contrib.helpers';
import type { ContribValue, ContribWrite } from './place-contrib.types';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import {
PLACE_CONTRIB_FIELDS,
PLACE_CONTRIB_TERMS_VERSION,
type PlaceContribConsent,
type PlaceContribDecisionRequest,
type PlaceContribField,
type PlaceContribFieldSwitches,
type PlaceContribLogQuery,
type PlaceContribLogResponse,
type PlaceContribLogResult,
type PlaceContribState,
type PlaceContribWithdrawResponse,
} from '@trek/shared';
const DAY_MS = 24 * 3_600_000;
const LOG_RESULTS: readonly PlaceContribLogResult[] = ['accepted', 'duplicate', 'rejected', 'withheld', 'retracted'];
/**
* The community enrichment of place details, as the admin and the places
* domain see it: the admin's decision and the state the admin panel shows, the
* transmission log, withdrawing everything, and the queue a place write feeds.
*
* Nothing leaves here. The queue is drained by PlaceContribSender on its cron,
* and only while the installation is eligible and an admin agreed to the
* terms in force; every value it holds is one the origin tracking recorded as
* typed by a user.
*/
@Injectable()
export class PlaceContribService {
constructor(
@InjectRepository(PlaceContribOutbox) private readonly outbox: PlaceContribOutboxRepository,
@InjectRepository(PlaceContribLog) private readonly log: PlaceContribLogRepository,
private readonly store: PlaceContribSettings,
private readonly settings: SettingsService,
private readonly client: PlaceContribClient,
private readonly uow: UnitOfWork,
) {}
async state(adminId: number, now: Date = new Date()): Promise<PlaceContribState> {
const eligibility = this.store.eligibility();
const consent = await this.store.consent();
const snoozedUntil = await this.store.snoozedUntil(adminId, now);
const decidedForTerms = consent.decision !== null && consent.termsVersion === PLACE_CONTRIB_TERMS_VERSION;
const size = await this.outbox.size();
const active = eligibility.eligible && agreedToCurrentTerms(consent) && anyField(consent.fields);
return {
termsVersion: PLACE_CONTRIB_TERMS_VERSION,
ceiling: this.store.ceiling(),
eligible: eligibility.eligible,
ineligibleReason: eligibility.reason,
consent,
showPrompt: eligibility.eligible && !decidedForTerms && snoozedUntil === null,
snoozedUntil,
active,
counts: await this.counts(now),
lastSuccessDay: await this.log.lastAcceptedDay(),
queue: { size, cap: OUTBOX_CAP, full: size >= OUTBOX_CAP },
pauseReason: active ? await this.store.pauseReason(now) : null,
registrationOpen: (await this.settings.getAppSetting('allow_registration')) !== 'false',
};
}
/**
* One decision of an admin. An agreement or a refusal names the terms it
* was shown; a dialog built for older terms is refused with 409 and reloads.
* Answers the state that follows.
*
* @txIndependent switching off commits before the withdrawal asks the service, which is network I/O.
*/
async decide(
adminId: number,
request: PlaceContribDecisionRequest,
now: Date = new Date(),
): Promise<PlaceContribState> {
const consent = await this.store.consent();
const decided = { decidedBy: adminId, decidedAt: now.toISOString() };
switch (request.action) {
case 'agree':
assertCurrentTerms(request.termsVersion);
if (!anyField(request.fields)) throw badRequest('Pick at least one field to share', { reason: 'no_field' });
// A new agreement is a fresh start: a pause over a key or a wait the
// service asked for is tried again on the next run.
await this.uow.transactional(async () => {
await this.store.writeConsent({
enabled: true,
fields: request.fields,
termsVersion: request.termsVersion,
decision: 'agreed',
...decided,
});
await this.store.clearPause();
});
break;
case 'snooze':
await this.store.snooze(adminId, new Date(now.getTime() + SNOOZE_DAYS * DAY_MS));
break;
case 'decline':
assertCurrentTerms(request.termsVersion);
await this.switchOff(consent, { decision: 'declined', termsVersion: request.termsVersion, ...decided });
break;
case 'fields':
await this.changeFields(consent, request.fields, { withdraw: request.withdraw === true, decided });
break;
case 'off':
await this.switchOff(consent, { decision: 'off', termsVersion: consent.termsVersion, ...decided });
if (request.withdraw) await this.withdrawAll(now);
break;
}
return this.state(adminId, now);
}
async logPage(query: PlaceContribLogQuery): Promise<PlaceContribLogResponse> {
const filter = { result: query.result, field: query.field };
const rows = await this.log.page(filter, query.perPage, (query.page - 1) * query.perPage);
return {
entries: rows.map((row) => ({
id: row.id,
day: row.day,
key: row.contrib_key,
placeName: row.place_name,
field: row.field as PlaceContribField,
valueSummary: row.value_summary,
result: row.result as PlaceContribLogResult,
reason: row.reason,
})),
total: await this.log.total(filter),
page: query.page,
perPage: query.perPage,
};
}
/**
* Asks the service to withdraw everything this installation sent, then
* empties the queue here. When the service does not confirm, nothing is
* dropped and the admin sees why.
*/
async withdrawAll(now: Date = new Date()): Promise<PlaceContribWithdrawResponse> {
const answer = await this.client.withdraw();
if (answer.kind !== 'ok') {
const reason = answer.kind === 'refused' ? answer.error : answer.reason;
logWarn(`Places contribution: the withdrawal was not confirmed (${reason})`);
throw new DomainError(502, 'The TREK Places API did not confirm the withdrawal', { details: { reason } });
}
const withdrawn = countsOf(answer.body.withdrawn);
const day = dayOf(now);
const lines: PlaceContribLogWrite[] = PLACE_CONTRIB_FIELDS.filter((field) => (withdrawn[field] ?? 0) > 0).map(
(field) => ({
day,
contrib_key: '*',
place_name: '',
field,
value_summary: String(withdrawn[field]),
result: 'retracted',
reason: 'withdraw_all',
}),
);
const cleared = await this.uow.transactional(async () => {
await this.log.insertLines(lines);
return this.outbox.deleteAll();
});
return { withdrawn, cleared };
}
/**
* A place write the origin tracking saw. Values that are no longer the
* user's leave the queue whatever the decision; the user's values are
* queued only while the installation is eligible and an admin agreed, each
* for a field that is switched on, and only for a place the service can key.
* The newest value replaces a queued one; it goes a few minutes later.
*
* @txStandalone a derived write after the place write committed: it never fails that write.
*/
async enqueue(write: ContribWrite, now: Date = new Date()): Promise<void> {
const active = await this.store.activeFields();
await this.uow.transactional(async () => {
await this.outbox.deleteForPlace(write.placeId, write.dropped);
const shared = write.values.filter((value) => active.includes(value.field));
if (shared.length === 0) return;
const key = contribKeyOf(write.osmId);
if (!key) {
await this.log.insertLines(shared.map((value) => this.withheldLine(write, value, now, 'no_contrib_key')));
return;
}
const due = dbNow(new Date(now.getTime() + eligibleDelayMs()));
for (const value of shared) await this.queueOne(write, { key, value, due, now });
});
}
private async queueOne(
write: ContribWrite,
entry: { key: string; value: ContribValue; due: string; now: Date },
): Promise<void> {
const payload = payloadOf(entry.value.field, entry.value.value);
if ('withheld' in payload) {
await this.outbox.deleteForPlace(write.placeId, [entry.value.field]);
await this.log.insertLines([this.withheldLine(write, entry.value, entry.now, payload.withheld)]);
return;
}
// At the cap nothing new is queued; a value that replaces a queued one still does.
if ((await this.outbox.size()) >= OUTBOX_CAP && !(await this.outbox.hasEntry(entry.key, entry.value.field))) {
await this.log.insertLines([this.withheldLine(write, entry.value, entry.now, 'queue_full')]);
return;
}
await this.outbox.upsertEntry({
contrib_key: entry.key,
field: entry.value.field,
value: payload.value,
place_id: write.placeId,
place_name: write.name,
lat: write.lat,
lng: write.lng,
country: write.country,
cid: newEntryCid(),
eligible_at: entry.due,
next_attempt_at: entry.due,
});
}
private withheldLine(write: ContribWrite, value: ContribValue, now: Date, reason: string): PlaceContribLogWrite {
return {
day: dayOf(now),
contrib_key: contribKeyOf(write.osmId) ?? '-',
place_name: write.name,
field: value.field,
value_summary: summaryOf(value.field, value.value),
result: 'withheld',
reason,
};
}
private async counts(now: Date): Promise<PlaceContribState['counts']> {
const rows = await this.log.countsSince(dayOf(new Date(now.getTime() - COUNT_WINDOW_DAYS * DAY_MS)));
const counts = { accepted: 0, duplicate: 0, rejected: 0, withheld: 0, retracted: 0 };
for (const row of rows)
if (LOG_RESULTS.includes(row.result as PlaceContribLogResult))
counts[row.result as PlaceContribLogResult] = row.count;
return counts;
}
/** Off or declined: nothing more is sent, and what waits in the queue goes. */
private async switchOff(
consent: PlaceContribConsent,
change: Pick<PlaceContribConsent, 'decision' | 'termsVersion' | 'decidedBy' | 'decidedAt'>,
): Promise<void> {
await this.uow.transactional(async () => {
await this.store.writeConsent({ ...consent, ...change, enabled: false });
await this.outbox.deleteAll();
});
}
private async changeFields(
consent: PlaceContribConsent,
fields: PlaceContribFieldSwitches,
opts: { withdraw: boolean; decided: Pick<PlaceContribConsent, 'decidedBy' | 'decidedAt'> },
): Promise<void> {
if (!agreedToCurrentTerms(consent)) {
throw conflict('Sharing is not switched on', { reason: 'not_agreed' });
}
if (!anyField(fields)) throw badRequest('Pick at least one field to share', { reason: 'no_field' });
const removed = PLACE_CONTRIB_FIELDS.filter((field) => consent.fields[field] && !fields[field]);
await this.uow.transactional(async () => {
await this.store.writeConsent({ ...consent, fields, ...opts.decided });
await this.outbox.deleteFields(removed);
});
if (!opts.withdraw) return;
for (const field of removed) {
const answer = await this.client.withdraw({ field });
if (answer.kind !== 'ok') logWarn(`Places contribution: withdrawing ${field} was not confirmed`);
}
}
}
function anyField(fields: PlaceContribFieldSwitches): boolean {
return PLACE_CONTRIB_FIELDS.some((field) => fields[field]);
}
function assertCurrentTerms(termsVersion: number): void {
if (termsVersion !== PLACE_CONTRIB_TERMS_VERSION) {
throw conflict('The contribution terms changed', {
reason: 'terms_outdated',
termsVersion: PLACE_CONTRIB_TERMS_VERSION,
});
}
}
/** The service's per-kind counts, the numbers only. */
function countsOf(withdrawn: Record<string, unknown> | undefined): Record<string, number> {
const counts: Record<string, number> = {};
for (const [kind, value] of Object.entries(withdrawn ?? {})) {
if (typeof value === 'number' && Number.isInteger(value) && value >= 0) counts[kind] = value;
}
return counts;
}
@@ -0,0 +1,25 @@
import type { PlaceContribField } from '@trek/shared';
/** One field of a place whose current value the user typed, as the origin tracking hands it over. */
export interface ContribValue {
field: PlaceContribField;
/** The column's value: the place's own text, the hours' JSON, the uploaded picture's URL. */
value: string;
}
/**
* A place write the origin tracking saw, for the contribution queue: what names
* the place, the user-typed values it now holds, and the fields that are no
* longer the user's (cleared, or set by someone else), whose queued values go.
*/
export interface ContribWrite {
placeId: number;
/** `osm_id` of the place; only a `gers:` or OpenStreetMap id makes it contributable. */
osmId: string | null;
name: string;
lat: number | null;
lng: number | null;
country: string | null;
values: ContribValue[];
dropped: PlaceContribField[];
}
@@ -160,6 +160,22 @@ interface CachedEnrichment {
interface CachePayload extends CachedEnrichment {
v?: number;
/** The community version the index served for a gers place when the row was written. */
cv?: number | null;
}
/**
* The community version the index serves for a gers place, from the details
* record the request carries; null for any other place, or when it says none.
* A cached answer written under another version is read again, so a value
* another installation contributed shows up on the next open, not a week later.
* A sender who puts another number here only makes their own request compute
* afresh: nothing of the record is what gets cached.
*/
function communityVersion(placeId: string, details: Record<string, unknown> | null | undefined): number | null {
if (!placeId.startsWith('gers:')) return null;
const version = details?.community_version;
return typeof version === 'number' && Number.isInteger(version) && version >= 0 ? version : null;
}
/**
@@ -385,7 +401,8 @@ export class PlaceEnrichmentService {
const placeId = req.placeId?.trim() || `coords:${req.lat}:${req.lng}`;
const lang = req.lang;
const cached = await this.readCache(placeId, lang);
const served = communityVersion(placeId, req.details);
const cached = await this.readCache(placeId, lang, served);
if (cached) return cached;
// One details lookup feeds all three halves: the pictures need its Commons
@@ -434,7 +451,7 @@ export class PlaceEnrichmentService {
// A summary or a link the lookup here fetched itself is the map's and keeps.
const fromCaller =
req.details != null && (description?.source === 'osm' || ownFacts.some((fact) => fact.url != null));
if (!fromCaller) await this.writeCache(placeId, lang, result);
if (!fromCaller) await this.writeCache(placeId, lang, { ...result, cv: communityVersion(placeId, details) });
return result;
}
@@ -866,12 +883,17 @@ export class PlaceEnrichmentService {
// ── Result cache ───────────────────────────────────────────────────────────
private async readCache(placeId: string, lang: string | undefined): Promise<CachedEnrichment | null> {
private async readCache(
placeId: string,
lang: string | undefined,
servedVersion: number | null,
): Promise<CachedEnrichment | null> {
try {
const row = await this.cache.findEntry(placeId, lang ?? '', CACHE_KIND);
if (!row) return null;
const parsed = JSON.parse(row.payload_json) as CachePayload;
if (parsed.v !== CACHE_VERSION) return null;
if (servedVersion !== null && (parsed.cv ?? null) !== servedVersion) return null;
// A cached candidate is only usable while its bytes are still on disk, and
// the nightly sweep deletes every picture nobody picked — which is most of
@@ -898,7 +920,11 @@ export class PlaceEnrichmentService {
}
}
private async writeCache(placeId: string, lang: string | undefined, value: CachedEnrichment): Promise<void> {
private async writeCache(
placeId: string,
lang: string | undefined,
value: CachedEnrichment & { cv: number | null },
): Promise<void> {
try {
await this.cache.upsertEntry({
place_id: placeId,
@@ -0,0 +1,143 @@
import { PLACE_DETAILS_CACHE_PAYLOAD } from '../../db/json-columns';
import type { CachedProviderPayload, PlaceShareableRow } from '../../db/repositories/PlaceFieldOrigin.repository';
import { decodeJson } from '../../utils/json-column';
import {
PLACE_CONTRIB_FIELDS,
normalizePlaceWebsite,
type PlaceContribField,
type PlaceFieldOrigin,
type PlaceFieldOrigins,
} from '@trek/shared';
/** Who wrote a place: a client reporting per field, or a path that decides the origin of all it changed. */
export type OriginWriter =
{ kind: 'client'; claims: PlaceFieldOrigins | undefined } | { kind: 'fixed'; origin: PlaceFieldOrigin };
/** The shareable values of a place, one per field, null where it holds none. */
export type OriginSnapshot = Record<PlaceContribField, string | null>;
/** A value a provider handed out for the place, and which provider that was. */
export interface ProviderValue {
field: PlaceContribField;
value: string;
origin: PlaceFieldOrigin;
}
const COLUMN: Record<PlaceContribField, keyof PlaceShareableRow> = {
website: 'website',
phone: 'phone',
email: 'email',
opening_hours: 'opening_hours',
description: 'description',
image: 'image_url',
};
/** The place's shareable values as stored, an empty text read as none. */
export function snapshotOf(row: PlaceShareableRow): OriginSnapshot {
const snapshot = {} as OriginSnapshot;
for (const field of PLACE_CONTRIB_FIELDS) {
const value = row[COLUMN[field]];
snapshot[field] = typeof value === 'string' && value.trim() !== '' ? value : null;
}
return snapshot;
}
/** The fields whose value this write changed. */
export function changedFields(before: OriginSnapshot | null, after: OriginSnapshot): PlaceContribField[] {
return PLACE_CONTRIB_FIELDS.filter((field) => (before?.[field] ?? null) !== after[field]);
}
/** The provider ids a place carries, which its cached details records are keyed by. */
export function providerIdsOf(row: PlaceShareableRow): string[] {
return [row.google_place_id, row.amap_poi_id, row.osm_id].filter(
(id): id is string => typeof id === 'string' && id.trim() !== '',
);
}
/** Which provider a cached record belongs to, by the id it is keyed under. */
function originOfId(placeId: string): PlaceFieldOrigin {
if (placeId.startsWith('gers:')) return 'trek';
if (placeId.startsWith('amap:')) return 'amap';
if (/^(node|way|relation):/.test(placeId)) return 'osm';
return 'google';
}
/** The source an enrichment description names, as an origin. */
function originOfSource(source: unknown): PlaceFieldOrigin {
if (source === 'website') return 'website';
if (source === 'osm') return 'osm';
if (source === 'google') return 'google';
if (typeof source === 'string' && /^wiki/.test(source)) return 'wikimedia';
return 'enrichment';
}
function text(value: unknown): string | null {
return typeof value === 'string' && value.trim() !== '' ? value : null;
}
/**
* The values the cached records hand out for a place: a details record's
* website, phone, e-mail and description, an enrichment record's description.
* A record that does not read as an object adds nothing.
*/
export function providerValuesOf(payloads: CachedProviderPayload[]): ProviderValue[] {
const values: ProviderValue[] = [];
for (const payload of payloads) {
const record = decodeJson(PLACE_DETAILS_CACHE_PAYLOAD, payload.payload_json, payload.place_id);
if (!record) continue;
const origin = originOfId(payload.place_id);
for (const field of ['website', 'phone', 'email'] as const) {
const value = text(record[field]);
if (value) values.push({ field, value, origin });
}
const description = record.description;
const described =
typeof description === 'object' && description !== null ? (description as Record<string, unknown>) : null;
const descriptionText = described ? text(described.text) : text(description);
if (descriptionText) {
values.push({
field: 'description',
value: descriptionText,
origin: payload.expanded === 2 && described ? originOfSource(described.source) : origin,
});
}
}
return values;
}
/** Two values of one field compared the way they are read: case, spacing and a website's scheme aside. */
export function sameValue(field: PlaceContribField, a: string, b: string): boolean {
if (field === 'website') return (normalizePlaceWebsite(a) ?? a.trim()) === (normalizePlaceWebsite(b) ?? b.trim());
if (field === 'phone') return a.replace(/[^\d+]/g, '') === b.replace(/[^\d+]/g, '');
if (field === 'email') return a.trim().toLowerCase() === b.trim().toLowerCase();
return a.replace(/\s+/g, ' ').trim() === b.replace(/\s+/g, ' ').trim();
}
/**
* The origin a changed field is stored with.
*
* A path that decides (MCP, a plugin, an import, an attachment, an upload)
* gives its own. A client is believed for a provider, since claiming one only
* keeps a value home; a value it claims as typed is the user's only when no
* provider handed out the same, and otherwise the provider's. A changed field
* the client reported nothing for is unknown, and so is a picture a client
* claims: the user's own picture arrives through the upload route only.
*/
export function originFor(
field: PlaceContribField,
value: string,
writer: OriginWriter,
providers: readonly ProviderValue[],
): PlaceFieldOrigin {
if (writer.kind === 'fixed') return writer.origin;
const claim = writer.claims?.[field];
if (!claim) return 'unknown';
if (claim !== 'user') return claim;
if (field === 'image') return 'unknown';
return providers.find((p) => p.field === field && sameValue(field, p.value, value))?.origin ?? 'user';
}
/** Whether origins of this writer could need the cached provider records at all. */
export function needsProviders(writer: OriginWriter, fields: readonly PlaceContribField[]): boolean {
return writer.kind === 'client' && fields.some((field) => writer.claims?.[field] === 'user');
}
@@ -0,0 +1,90 @@
import { toRowId } from '../common/row-id';
import type { OriginSnapshot, OriginWriter } from './place-origins.helpers';
import { PlaceOriginsService } from './place-origins.service';
import {
applyDecorators,
Injectable,
SetMetadata,
UseInterceptors,
type CallHandler,
type ExecutionContext,
type NestInterceptor,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { placeFieldOriginsSchema } from '@trek/shared';
import type { Request } from 'express';
import { mergeMap, type Observable } from 'rxjs';
/**
* What a place route writes, for its origin tracking:
* - `client`: a create or update from the app, which reports `fieldOrigins`;
* - `upload`: the user's own picture for the place;
* - `attachment`: a trip file made the picture;
* - `import`: new places from a file or a shared list.
*/
type PlaceOriginRoute = 'client' | 'upload' | 'attachment' | 'import';
const ROUTE_KEY = 'trekPlaceOriginRoute';
/** Records where the shareable details a place route wrote came from, once the route answered. */
export function TrackPlaceOrigins(route: PlaceOriginRoute): MethodDecorator {
return applyDecorators(SetMetadata(ROUTE_KEY, route), UseInterceptors(PlaceOriginsInterceptor));
}
/**
* The REST side of the origin tracking. It reads the place's values before
* the handler runs and records what changed after it answered, so the
* controller's routes stay as they are, and an offline replay, which goes
* through the same routes, is recorded the same way. A handler that throws
* records nothing.
*/
@Injectable()
export class PlaceOriginsInterceptor implements NestInterceptor {
constructor(
private readonly origins: PlaceOriginsService,
private readonly reflector: Reflector,
) {}
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<unknown>> {
const route = this.reflector.get<PlaceOriginRoute | undefined>(ROUTE_KEY, context.getHandler()) ?? 'client';
const req = context.switchToHttp().getRequest<Request>();
const placeId = route === 'import' ? null : toRowId(req.params?.id);
const before = placeId === null ? null : await this.origins.valuesBefore(placeId);
return next.handle().pipe(
mergeMap(async (body: unknown) => {
await this.recordAnswer(route, { body, before, claims: req.body as unknown });
return body;
}),
);
}
private async recordAnswer(
route: PlaceOriginRoute,
answer: { body: unknown; before: OriginSnapshot | null; claims: unknown },
): Promise<void> {
if (route === 'import') {
await this.origins.recordImported(idsOf((answer.body as { places?: unknown } | null)?.places));
return;
}
const id = idsOf([(answer.body as { place?: unknown } | null)?.place])[0];
if (id === undefined) return;
await this.origins.record(id, answer.before, writerFor(route, answer.claims));
}
}
function writerFor(route: Exclude<PlaceOriginRoute, 'import'>, body: unknown): OriginWriter {
if (route === 'upload') return { kind: 'fixed', origin: 'user' };
if (route === 'attachment') return { kind: 'fixed', origin: 'attachment' };
// The pipe has refused a malformed body before the handler ran; this reads the same field again.
const parsed = placeFieldOriginsSchema.safeParse((body as { fieldOrigins?: unknown } | null)?.fieldOrigins);
return { kind: 'client', claims: parsed.success ? parsed.data : undefined };
}
/** The ids of the places in an answer. */
function idsOf(places: unknown): number[] {
if (!Array.isArray(places)) return [];
return places
.map((place: unknown) => (place as { id?: unknown } | null)?.id)
.filter((id): id is number => typeof id === 'number' && Number.isInteger(id) && id > 0);
}
@@ -0,0 +1,150 @@
import { PlaceFieldOrigin } from '../../db/entities/PlaceFieldOrigin.entity';
import type {
PlaceFieldOriginRepository,
PlaceOriginWrite,
PlaceShareableRow,
} from '../../db/repositories/PlaceFieldOrigin.repository';
import { dbNow } from '../../db/types';
import { resolveCountryCodeSync } from '../atlas/atlas-geo';
import { logWarn } from '../audit/audit-log.logger';
import { toRowId } from '../common/row-id';
import { valueHash } from '../common/value-hash';
import { UnitOfWork } from '../database/unit-of-work';
import { PlaceContribService } from '../place-contrib/place-contrib.service';
import {
changedFields,
needsProviders,
originFor,
providerIdsOf,
providerValuesOf,
snapshotOf,
type OriginSnapshot,
type OriginWriter,
type ProviderValue,
} from './place-origins.helpers';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import type { PlaceContribField } from '@trek/shared';
/**
* Where the shareable details of a place came from (website, phone, e-mail,
* opening hours, description, picture), recorded after every place write.
*
* A write records an origin for each field whose value it changed, with the
* hash of the new value: `user` for what a person typed, the provider for what
* a search pick or a details lookup filled, `agent`, `plugin`, `import` or
* `attachment` for the paths that decide themselves, `unknown` for a change
* nobody vouched for. A cleared value loses its row. An unchanged value keeps
* the row it had, so a value that existed before this tracking has none and is
* never shared.
*
* The user's values then go to the contribution queue, which decides whether
* anything is sent at all. Recording never fails the write it follows.
*/
@Injectable()
export class PlaceOriginsService {
constructor(
@InjectRepository(PlaceFieldOrigin) private readonly origins: PlaceFieldOriginRepository,
private readonly contrib: PlaceContribService,
private readonly uow: UnitOfWork,
) {}
/** The shareable values of a place before a write, for {@link record} to see what changed; null without one. */
async valuesBefore(placeId: number | string): Promise<OriginSnapshot | null> {
const id = toRowId(placeId);
if (id === null) return null;
try {
const row = await this.origins.placeValues(id);
return row ? snapshotOf(row) : null;
} catch (err) {
logWarn(`Place origins: reading place ${id} failed: ${err instanceof Error ? err.message : String(err)}`);
return null;
}
}
/**
* Records the origins of what this write changed, then hands the user's
* values to the contribution queue. `before` is null for a new place.
*
* @txStandalone a derived write after the place write committed; a failure is logged, never raised.
*/
async record(placeId: number, before: OriginSnapshot | null, writer: OriginWriter): Promise<void> {
try {
await this.recordChanges(placeId, before, writer);
} catch (err) {
logWarn(`Place origins: recording place ${placeId} failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
/**
* New places from a file or a list import: every value they hold is the
* import's. One read and one write for the whole batch.
*
* @txStandalone a derived write after the import committed; a failure is logged, never raised.
*/
async recordImported(placeIds: number[]): Promise<void> {
try {
const rows = await this.origins.placeValuesMany(placeIds);
const updatedAt = dbNow();
const writes = rows.flatMap((row) => {
const after = snapshotOf(row);
return changedFields(null, after).map((field) => originWrite(row.id, field, after, 'import', updatedAt));
});
await this.origins.upsertOrigins(writes);
} catch (err) {
logWarn(`Place origins: recording an import failed: ${err instanceof Error ? err.message : String(err)}`);
}
}
private async recordChanges(placeId: number, before: OriginSnapshot | null, writer: OriginWriter): Promise<void> {
const row = await this.origins.placeValues(placeId);
if (!row) return;
const after = snapshotOf(row);
const changed = changedFields(before, after);
if (changed.length === 0) return;
const providers = needsProviders(writer, changed) ? await this.providerValues(row) : [];
const updatedAt = dbNow();
const writes: PlaceOriginWrite[] = [];
const cleared: PlaceContribField[] = [];
const typed: PlaceContribField[] = [];
for (const field of changed) {
const value = after[field];
if (value === null) {
cleared.push(field);
continue;
}
const origin = originFor(field, value, writer, providers);
writes.push(originWrite(placeId, field, after, origin, updatedAt));
if (origin === 'user') typed.push(field);
}
await this.uow.transactional(async () => {
await this.origins.deleteOrigins(placeId, cleared);
await this.origins.upsertOrigins(writes);
});
await this.contrib.enqueue({
placeId,
osmId: row.osm_id,
name: row.name,
lat: row.lat,
lng: row.lng,
country: resolveCountryCodeSync(row),
values: typed.map((field) => ({ field, value: after[field] ?? '' })),
dropped: changed.filter((field) => !typed.includes(field)),
});
}
/** What the providers this instance asked handed out for the place, read from their cached records. */
private async providerValues(row: PlaceShareableRow): Promise<ProviderValue[]> {
return providerValuesOf(await this.origins.cachedProviderPayloads(providerIdsOf(row)));
}
}
function originWrite(
placeId: number,
field: PlaceContribField,
after: OriginSnapshot,
origin: PlaceOriginWrite['origin'],
updatedAt: string,
): PlaceOriginWrite {
return { place_id: placeId, field, origin, value_hash: valueHash(after[field] ?? ''), updated_at: updatedAt };
}
@@ -10,6 +10,7 @@ import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.g
import { isDirectionsUrl, isGoogleListDataUrl } from '../place-import/place-import.service';
import { StorageService } from '../storage/storage.service';
import { placeImageUrl } from './place-image';
import { TrackPlaceOrigins } from './place-origins.interceptor';
import {
PlaceBulkDeleteDto,
PlaceBulkUpdateDto,
@@ -157,6 +158,7 @@ export class PlacesController {
}
@Post()
@TrackPlaceOrigins('client')
async create(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@@ -176,6 +178,7 @@ export class PlacesController {
@Post('import/gpx')
@UseInterceptors(FileInterceptor('file', UPLOAD))
@TrackPlaceOrigins('import')
async importGpx(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@@ -240,6 +243,7 @@ export class PlacesController {
@Post('import/map')
@UseInterceptors(FileInterceptor('file', UPLOAD))
@TrackPlaceOrigins('import')
async importMap(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@@ -278,6 +282,7 @@ export class PlacesController {
}
@Post('import/google-list')
@TrackPlaceOrigins('import')
async importGoogle(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@@ -288,6 +293,7 @@ export class PlacesController {
}
@Post('import/naver-list')
@TrackPlaceOrigins('import')
async importNaver(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@@ -421,6 +427,7 @@ export class PlacesController {
@Post(':id/image')
@HttpCode(200)
@UseInterceptors(FileInterceptor('image', { fileFilter: PLACE_IMAGE_FILE_FILTER }))
@TrackPlaceOrigins('upload')
async uploadImage(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@@ -454,6 +461,7 @@ export class PlacesController {
}
@Put(':id/image/from-file')
@TrackPlaceOrigins('attachment')
async imageFromFile(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@@ -525,6 +533,7 @@ export class PlacesController {
}
@Put(':id')
@TrackPlaceOrigins('client')
async update(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
+17
View File
@@ -26,6 +26,8 @@ import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
import { UnitOfWork } from '../database/unit-of-work';
import { MapsService } from '../maps/maps.service';
import { PlacesService } from './places.service';
import { PlaceOriginsService } from './place-origins.service';
import type { OriginWriter } from './place-origins.helpers';
import { isUpdateConflict } from '../common/conflictResult';
import { isDirectionsUrl } from '../place-import/place-import.service';
import { TripAccessService } from '../trip-membership/trip-access.service';
@@ -38,6 +40,9 @@ function parseId(value: string | string[]): number | null {
/** Hours as the column keeps them: JSON text, or null to clear (#2472). */
const hoursText = (hours: PlaceOpeningHours | null | undefined): string | null => (hours ? JSON.stringify(hours) : null);
/** What the assistant writes is the agent's, never shared as a user's correction. */
const AGENT: OriginWriter = { kind: 'fixed', origin: 'agent' };
/**
* Places MCP surface — ported 1:1 from the legacy registrar
* src/mcp/tools/places.ts (ten tools) plus the trek://trips/{tripId}/places
@@ -65,6 +70,7 @@ export class PlacesMcp {
private readonly assignments: AssignmentsService,
private readonly guards: McpToolGuardsService,
private readonly uow: UnitOfWork,
private readonly origins: PlaceOriginsService,
) {}
@Tool({
@@ -109,6 +115,7 @@ export class PlacesMcp {
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
const place = await this.places.create(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, notes, website, phone, email, opening_hours: hoursText(opening_hours), image_url, price, currency, stop_type });
this.guards.safeBroadcast(tripId, 'place:created', { place });
await this.origins.record(place.id, null, AGENT);
// The journey hook the REST route and the plugin RPC run after the same write.
await this.places.onCreated(String(tripId), place.id);
return ok({ place });
@@ -165,6 +172,7 @@ export class PlacesMcp {
});
this.guards.safeBroadcast(tripId, 'place:created', { place: result.place });
this.guards.safeBroadcast(tripId, 'assignment:created', { assignment: result.assignment });
await this.origins.record(result.place.id, null, AGENT);
try { await this.journey.reconcileTripSkeletons(tripId); } catch { /* non-fatal */ }
return ok(result);
} catch {
@@ -221,10 +229,12 @@ export class PlacesMcp {
) {
if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
const before = await this.origins.valuesBefore(placeId);
const place = await this.places.update(String(tripId), String(placeId), { name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, email, opening_hours: opening_hours === undefined ? undefined : hoursText(opening_hours), image_url, transport_mode, osm_id, google_place_id, google_ftid, amap_poi_id, stop_type, fill_percent });
// No base version is sent, so the update never answers a conflict; the guard only narrows the type.
if (!place || isUpdateConflict(place)) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
this.guards.safeBroadcast(tripId, 'place:updated', { place });
await this.origins.record(place.id, before, AGENT);
// As on REST: the journey entries made from this place follow its new name, address and time.
await this.places.onUpdated(place.id);
return ok({ place });
@@ -247,12 +257,14 @@ export class PlacesMcp {
) {
if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
const before = await this.origins.valuesBefore(placeId);
const result = await this.places.setImageFromFile(String(tripId), String(placeId), fileId);
if (result === 'not_found') return errorResult('File not found.');
if (result === 'not_image') return errorResult('That file is not a jpg, png, gif or webp image.');
if (result === 'too_large') return errorResult('That image is too large.');
if (!result || isUpdateConflict(result)) return errorResult('Place not found.');
this.guards.safeBroadcast(tripId, 'place:updated', { place: result });
await this.origins.record(result.id, before, { kind: 'fixed', origin: 'attachment' });
await this.places.onUpdated(result.id);
return ok({ place: result });
}
@@ -400,6 +412,7 @@ export class PlacesMcp {
for (const place of result.places) {
this.guards.safeBroadcast(tripId, 'place:created', { place });
}
await this.origins.recordImported(result.places.map((place) => place.id));
return ok({ places: result.places, count: result.places.length, listName: result.listName, skipped: result.skipped });
}
@@ -418,6 +431,7 @@ export class PlacesMcp {
const imported = await this.places.importGpx(String(input.tripId), Buffer.from(input.gpx, 'utf8'), { importWaypoints: input.importWaypoints, importRoutes: input.importRoutes, importTracks: input.importTracks, defaultName: input.name });
if (!imported) return errorResult('No matching places found in GPX.');
for (const place of imported.places) this.guards.safeBroadcast(input.tripId, 'place:created', { place });
await this.origins.recordImported(imported.places.map((place) => place.id));
if (input.enrich) this.places.enrichImportedFilePlaces(String(input.tripId), ctx.userId, imported.places);
return ok(imported);
} catch {
@@ -526,10 +540,13 @@ export class PlacesMcp {
return { content: [{ type: 'text' as const, text: 'Provide at least one field to update.' }], isError: true };
}
const before = new Map<number, Awaited<ReturnType<PlaceOriginsService['valuesBefore']>>>();
for (const id of placeIds) before.set(id, await this.origins.valuesBefore(id));
const updated = await this.places.updateMany(String(tripId), placeIds, fields);
// Per place, the event and then the journey hook, in the order POST /places/bulk-update keeps.
for (const place of updated) {
this.guards.safeBroadcast(tripId, 'place:updated', { place });
await this.origins.record(place.id, before.get(place.id) ?? null, AGENT);
await this.places.onUpdated(place.id);
}
return ok({ count: updated.length, updatedIds: updated.map(p => p.id), skipped: placeIds.length - updated.length });
+8 -1
View File
@@ -2,6 +2,7 @@ import { BudgetItems } from '../../db/entities/BudgetItems.entity';
import { Categories } from '../../db/entities/Categories.entity';
import { CollectionPlaces } from '../../db/entities/CollectionPlaces.entity';
import { DayAssignments } from '../../db/entities/DayAssignments.entity';
import { PlaceFieldOrigin } from '../../db/entities/PlaceFieldOrigin.entity';
import { PlaceRatings } from '../../db/entities/PlaceRatings.entity';
import { Places } from '../../db/entities/Places.entity';
import { Tags } from '../../db/entities/Tags.entity';
@@ -16,6 +17,7 @@ import { JourneyDomainModule } from '../journey/journey-domain.module';
import { MapsModule } from '../maps/maps.module';
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { PlaceContribModule } from '../place-contrib/place-contrib.module';
import { PlaceImportModule } from '../place-import/place-import.module';
import { PlacePhotosModule } from '../place-photos/place-photos.module';
import { QueryHelpersModule } from '../query-helpers/query-helpers.module';
@@ -25,6 +27,7 @@ import { StorageModule } from '../storage/storage.module';
import { StorageService } from '../storage/storage.service';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
import { UnsplashModule } from '../unsplash/unsplash.module';
import { PlaceOriginsService } from './place-origins.service';
import { PlacesController } from './places.controller';
import { PlacesMcp } from './places.mcp';
import { PlacesRpc } from './places.rpc';
@@ -71,6 +74,9 @@ import { MulterModule } from '@nestjs/platform-express';
PluginGuardsModule,
AssignmentsDomainModule,
AccommodationsDomainModule,
// Every place write records where its shareable details came from, and the
// user's values go to the community enrichment's queue there.
PlaceContribModule,
// Plan 3c Task 4: `PlacesService`'s and `PlacesMcp`'s own `@InjectRepository`
// constructor params (`PlacesRepository`, `TagsRepository`,
// `PlaceRatingsRepository`, `TripMembersRepository`,
@@ -95,10 +101,11 @@ import { MulterModule } from '@nestjs/platform-express';
Categories,
BudgetItems,
CollectionPlaces,
PlaceFieldOrigin,
]),
],
controllers: [PlacesController],
providers: [PlacesService, PlacesMcp, PlacesRpc],
providers: [PlacesService, PlacesMcp, PlacesRpc, PlaceOriginsService],
exports: [PlacesService],
})
export class PlacesModule {}
+9
View File
@@ -5,6 +5,8 @@ import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types';
import { num, schemaMessage } from '../../nest-rpc/rpc-params';
import { JourneyDomainService } from '../journey/journey-domain.service';
import { RealtimeService } from '../realtime/realtime.service';
import type { OriginWriter } from './place-origins.helpers';
import { PlaceOriginsService } from './place-origins.service';
import { PlacesService } from './places.service';
import type { PlaceCreateInput, PlaceUpdateInput } from './places.service';
import {
@@ -16,6 +18,9 @@ import {
const PLACE_EDIT_ACTION = 'place_edit';
/** What a plugin writes is the plugin's, never shared as a user's correction. */
const PLUGIN: OriginWriter = { kind: 'fixed', origin: 'plugin' };
/**
* The @trek/shared write schemas carry no string-length caps, so the plugin path
* mirrors the ones the REST controller adds. Without them a plugin could store a
@@ -59,6 +64,7 @@ export class PlacesRpc {
private readonly journey: JourneyDomainService,
private readonly realtime: RealtimeService,
private readonly guards: PluginGuards,
private readonly origins: PlaceOriginsService,
) {}
@PluginMethod('places.create', { permission: 'db:write:places' })
@@ -72,6 +78,7 @@ export class PlacesRpc {
await this.guards.requireTripEdit(tripId, actor, PLACE_EDIT_ACTION);
const place = await this.places.create(String(tripId), parsed.data as unknown as PlaceCreateInput);
this.realtime.broadcast(tripId, 'place:created', { place });
await this.origins.record(place.id, null, PLUGIN);
await this.mirrorJourneys(() => this.journey.onPlaceCreated(tripId, place.id));
return place;
}
@@ -89,9 +96,11 @@ export class PlacesRpc {
// update is async (it may delete a superseded storage object): await it so the
// null-refusal check compares against the resolved place, not an always-truthy
// Promise, and the broadcast below carries the actual place.
const before = await this.origins.valuesBefore(placeId);
const place = await this.places.update(String(tripId), String(placeId), parsed.data as PlaceUpdateInput);
if (place === null) throw new ForbiddenResource(`no place ${placeId} on trip ${tripId}`);
this.realtime.broadcast(tripId, 'place:updated', { place });
if ('id' in place) await this.origins.record(place.id, before, PLUGIN);
await this.mirrorJourneys(() => this.journey.onPlaceUpdated(placeId));
return place;
}