Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

feat(services): get the key at startup and share earlier place details

Maurice247d5fc51983
diff --git a/client/src/components/Admin/PlaceContribPrompt.tsx b/client/src/components/Admin/PlaceContribPrompt.tsx
index 88b09e450..ad457f7f1 100644
--- a/client/src/components/Admin/PlaceContribPrompt.tsx
+++ b/client/src/components/Admin/PlaceContribPrompt.tsx
@@ -175,7 +175,7 @@ export default function PlaceContribPrompt({
))}
</ul>
<p className="m-0 leading-normal text-content-muted" style={fs(12, 'body')}>
- {t('admin.contribute.prompt.how')}
+ {t('admin.contribute.prompt.how')} {t('admin.contribute.prompt.past')}
</p>
</section>
diff --git a/server/src/db/json-columns.ts b/server/src/db/json-columns.ts
index 8ed9e6e63..9fc84d252 100644
--- a/server/src/db/json-columns.ts
+++ b/server/src/db/json-columns.ts
@@ -14,6 +14,7 @@ import {
paddleRegionBoundarySchema,
paddleRegionGraphStatsSchema,
placeContribConsentSchema,
+ placeContribFieldSchema,
placeContribPauseReasonSchema,
skiPlannedLegsSchema,
skiRouteOptionsSchema,
@@ -484,6 +485,24 @@ export const PLACES_CONTRIBUTE_SNOOZE: JsonColumn<Record<string, string>> = {
fallback: () => ({}),
};
+/**
+ * The catch-up after an agreement, in `places_contribute_backfill`: the
+ * fields whose earlier values still go out, and the last place id it queued,
+ * so it goes on where it stopped after a restart. Absent once everything
+ * typed before the agreement is queued.
+ */
+const placesContributeBackfillSchema = z.object({
+ fields: z.array(placeContribFieldSchema).min(1),
+ afterId: z.number().int().nonnegative(),
+});
+export type PlacesContributeBackfill = z.infer<typeof placesContributeBackfillSchema>;
+
+export const PLACES_CONTRIBUTE_BACKFILL: JsonColumn<PlacesContributeBackfill | null> = {
+ column: 'app_settings.places_contribute_backfill',
+ schema: placesContributeBackfillSchema.nullable(),
+ fallback: () => null,
+};
+
/**
* 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
diff --git a/server/src/db/repositories/PlaceContribOutbox.repository.ts b/server/src/db/repositories/PlaceContribOutbox.repository.ts
index 52f8d5e46..26d83186a 100644
--- a/server/src/db/repositories/PlaceContribOutbox.repository.ts
+++ b/server/src/db/repositories/PlaceContribOutbox.repository.ts
@@ -20,6 +20,24 @@ export interface OutboxRow {
created_at: string;
}
+/** A place with values a user typed, and the hash each of those values had when it was typed. */
+export interface PlaceTypedRow {
+ place: {
+ id: number;
+ name: string;
+ lat: number | null;
+ lng: number | null;
+ osm_id: string | null;
+ website: string | null;
+ phone: string | null;
+ email: string | null;
+ opening_hours: string | null;
+ description: string | null;
+ image_url: string | null;
+ };
+ typed: { field: string; value_hash: string }[];
+}
+
/**
* A value the sender read: its settle writes touch the row only while it still
* holds that value, since a newer one keeps the row's id but brings a new cid.
@@ -252,4 +270,55 @@ export class PlaceContribOutboxRepository extends TrekRepository<PlaceContribOut
.where('o.id', 'in', ids)
.execute();
}
+
+ /**
+ * The next places after `afterId`, by id, with a value a user typed in one
+ * of these fields, each with the origins of those fields: the catch-up
+ * after an agreement walks them page by page.
+ */
+ async typedAfter(afterId: number, fields: string[], limit: number): Promise<PlaceTypedRow[]> {
+ if (fields.length === 0) return [];
+ const placeIds = (
+ await this.db()
+ .selectFrom('place_field_origin')
+ .select('place_id')
+ .distinct()
+ .where('origin', '=', 'user')
+ .where('field', 'in', fields)
+ .where('place_id', '>', afterId)
+ .orderBy('place_id')
+ .limit(limit)
+ .execute()
+ ).map((row) => row.place_id);
+ if (placeIds.length === 0) return [];
+ const typed = await this.db()
+ .selectFrom('place_field_origin')
+ .select(['place_id', 'field', 'value_hash'])
+ .where('origin', '=', 'user')
+ .where('field', 'in', fields)
+ .where('place_id', 'in', placeIds)
+ .execute();
+ const places = await this.db()
+ .selectFrom('places')
+ .select([
+ 'id',
+ 'name',
+ 'lat',
+ 'lng',
+ 'osm_id',
+ 'website',
+ 'phone',
+ 'email',
+ 'opening_hours',
+ 'description',
+ 'image_url',
+ ])
+ .where('id', 'in', placeIds)
+ .orderBy('id')
+ .execute();
+ return places.map((place) => ({
+ place,
+ typed: typed.filter((row) => row.place_id === place.id).map(({ field, value_hash }) => ({ field, value_hash })),
+ }));
+ }
}
diff --git a/server/src/nest/common/app-settings.registry.ts b/server/src/nest/common/app-settings.registry.ts
index 3775461c6..f7362d6ab 100644
--- a/server/src/nest/common/app-settings.registry.ts
+++ b/server/src/nest/common/app-settings.registry.ts
@@ -141,11 +141,13 @@ export const APP_SETTINGS = {
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.
+ // "not now" ends; why sending waits although an admin agreed (a refused key, a pause
+ // the service asked for); and how far the catch-up of values typed before the agreement
+ // got. 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 },
+ places_contribute_backfill: { 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. */
diff --git a/server/src/nest/place-contrib/place-contrib-backfill.service.ts b/server/src/nest/place-contrib/place-contrib-backfill.service.ts
new file mode 100644
index 000000000..73c56916d
--- /dev/null
+++ b/server/src/nest/place-contrib/place-contrib-backfill.service.ts
@@ -0,0 +1,103 @@
+import { PlaceContribOutbox } from '../../db/entities/PlaceContribOutbox.entity';
+import type { PlaceContribOutboxRepository, PlaceTypedRow } from '../../db/repositories/PlaceContribOutbox.repository';
+import { getCountryFromCoords } from '../../utils/country-borders';
+import { logInfo } from '../audit/audit-log.logger';
+import { inOrder } from '../common/in-order';
+import { valueHash } from '../common/value-hash';
+import { UnitOfWork } from '../database/unit-of-work';
+import { PlaceContribQueue } from './place-contrib-queue';
+import { PlaceContribSettings } from './place-contrib-settings';
+import { contribKeyOf } from './place-contrib.helpers';
+import type { ContribWrite } from './place-contrib.types';
+import { InjectRepository } from '@mikro-orm/nestjs';
+import { Injectable } from '@nestjs/common';
+import type { PlaceContribField } from '@trek/shared';
+
+/** Places read per step of the catch-up. */
+const BACKFILL_PAGE = 100;
+/** The catch-up only adds to the queue while it holds fewer values than this, so new writes never wait behind it. */
+export const BACKFILL_LOW_WATER = 200;
+
+const COLUMN = {
+ website: 'website',
+ phone: 'phone',
+ email: 'email',
+ opening_hours: 'opening_hours',
+ description: 'description',
+ image: 'image_url',
+} as const satisfies Record<PlaceContribField, keyof PlaceTypedRow['place']>;
+
+/**
+ * The catch-up after an agreement: everything users typed into places since
+ * the origin tracking began (TREK 5.1.0) goes out as well, not only what they
+ * type from the agreement on. It walks the places page by page on the sender's
+ * schedule and only tops the queue up, so it never fills it and a restart
+ * goes on where it stopped.
+ *
+ * A value goes only while it is still the one the user typed (its hash
+ * matches the origin), for a field switched on, and for a place the service
+ * can key; a place without such a key is passed over without a log line. A
+ * value a save queued for the same key and field is newer and stays.
+ */
+@Injectable()
+export class PlaceContribBackfill {
+ constructor(
+ @InjectRepository(PlaceContribOutbox) private readonly outbox: PlaceContribOutboxRepository,
+ private readonly store: PlaceContribSettings,
+ private readonly queue: PlaceContribQueue,
+ private readonly uow: UnitOfWork,
+ ) {}
+
+ /**
+ * One step: queues the next page of earlier values when the queue has room.
+ * Waits while sending is not possible (no key yet, not eligible), and ends
+ * the catch-up once no place is left. Answers how many places it queued.
+ */
+ async step(now: Date = new Date()): Promise<number> {
+ const pending = await this.store.backfill();
+ if (pending === null) return 0;
+ const active = await this.store.activeFields();
+ if (active.length === 0) return 0;
+ const fields = pending.fields.filter((field) => active.includes(field));
+ if (fields.length === 0) {
+ await this.store.writeBackfill(null);
+ return 0;
+ }
+ if ((await this.outbox.size()) >= BACKFILL_LOW_WATER) return 0;
+ const page = await this.outbox.typedAfter(pending.afterId, fields, BACKFILL_PAGE);
+ if (page.length === 0) {
+ await this.store.writeBackfill(null);
+ logInfo('Places contribution: the place details typed before the agreement are all queued');
+ return 0;
+ }
+ const writes = page.map((row) => typedWrite(row, fields)).filter((write) => write.values.length > 0);
+ await this.uow.transactional(async () => {
+ await inOrder(writes, (write) => this.queue.put(write, fields, now, { keepQueued: true }));
+ await this.store.writeBackfill({ fields, afterId: page[page.length - 1].place.id });
+ });
+ return writes.length;
+ }
+}
+
+/** The values of one place that are still the ones a user typed, for a place the service can key. */
+function typedWrite(row: PlaceTypedRow, fields: readonly PlaceContribField[]): ContribWrite {
+ const { place } = row;
+ const keyed = contribKeyOf(place.osm_id) !== null;
+ const values = row.typed.flatMap(({ field, value_hash }) => {
+ const known = fields.find((candidate) => candidate === field);
+ const value = known ? place[COLUMN[known]] : null;
+ if (!keyed || !known || typeof value !== 'string' || value.trim() === '') return [];
+ return valueHash(value) === value_hash ? [{ field: known, value }] : [];
+ });
+ return {
+ placeId: place.id,
+ osmId: place.osm_id,
+ name: place.name,
+ lat: place.lat,
+ lng: place.lng,
+ country:
+ values.length > 0 && place.lat !== null && place.lng !== null ? getCountryFromCoords(place.lat, place.lng) : null,
+ values,
+ dropped: [],
+ };
+}
diff --git a/server/src/nest/place-contrib/place-contrib-queue.ts b/server/src/nest/place-contrib/place-contrib-queue.ts
new file mode 100644
index 000000000..6c526a725
--- /dev/null
+++ b/server/src/nest/place-contrib/place-contrib-queue.ts
@@ -0,0 +1,94 @@
+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 { inOrder } from '../common/in-order';
+import { OUTBOX_CAP } from './place-contrib.constants';
+import { contribKeyOf, dayOf, 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 type { PlaceContribField } from '@trek/shared';
+
+/**
+ * Puts the user's values of one place into the contribution queue, for a
+ * place write and for the catch-up after an agreement alike. Runs inside the
+ * caller's transaction and sends nothing itself.
+ */
+@Injectable()
+export class PlaceContribQueue {
+ constructor(
+ @InjectRepository(PlaceContribOutbox) private readonly outbox: PlaceContribOutboxRepository,
+ @InjectRepository(PlaceContribLog) private readonly log: PlaceContribLogRepository,
+ ) {}
+
+ /**
+ * Values that are no longer the user's leave the queue; the user's values
+ * are queued for the fields switched on, and only for a place the service
+ * can key. The newest value replaces a queued one; with `keepQueued` (the
+ * catch-up, whose values are older than anything a save queued) a value
+ * already waiting for the same key and field is left as it is.
+ */
+ async put(
+ write: ContribWrite,
+ active: readonly PlaceContribField[],
+ now: Date,
+ opts: { keepQueued?: boolean } = {},
+ ): Promise<void> {
+ 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) => withheldLine(write, value, now, 'no_contrib_key')));
+ return;
+ }
+ const due = dbNow(now);
+ await inOrder(shared, (value) => this.queueOne(write, { key, value, due, now }, opts.keepQueued === true));
+ }
+
+ private async queueOne(
+ write: ContribWrite,
+ entry: { key: string; value: ContribValue; due: string; now: Date },
+ keepQueued: boolean,
+ ): Promise<void> {
+ if (keepQueued && (await this.outbox.hasEntry(entry.key, entry.value.field))) return;
+ 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([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([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,
+ });
+ }
+}
+
+function 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,
+ };
+}
diff --git a/server/src/nest/place-contrib/place-contrib-settings.ts b/server/src/nest/place-contrib/place-contrib-settings.ts
index f53756252..67f2d68df 100644
--- a/server/src/nest/place-contrib/place-contrib-settings.ts
+++ b/server/src/nest/place-contrib/place-contrib-settings.ts
@@ -1,7 +1,9 @@
import {
+ PLACES_CONTRIBUTE_BACKFILL,
PLACES_CONTRIBUTE_CONSENT,
PLACES_CONTRIBUTE_PAUSE,
PLACES_CONTRIBUTE_SNOOZE,
+ type PlacesContributeBackfill,
type PlacesContributePause,
} from '../../db/json-columns';
import { decodeJson, encodeJson } from '../../utils/json-column';
@@ -110,6 +112,26 @@ export class PlaceContribSettings {
await this.settings.deleteAppSettings(['places_contribute_pause']);
}
+ /** How far the catch-up of values typed before the agreement got; null when there is nothing to catch up. */
+ async backfill(): Promise<PlacesContributeBackfill | null> {
+ return decodeJson(
+ PLACES_CONTRIBUTE_BACKFILL,
+ await this.settings.getAppSetting('places_contribute_backfill'),
+ 'backfill',
+ );
+ }
+
+ /** Stores where the catch-up stands, or ends it with null. */
+ async writeBackfill(backfill: PlacesContributeBackfill | null): Promise<void> {
+ if (backfill === null) {
+ await this.settings.deleteAppSettings(['places_contribute_backfill']);
+ return;
+ }
+ await this.settings.setAppSettings({
+ places_contribute_backfill: encodeJson(PLACES_CONTRIBUTE_BACKFILL, backfill),
+ });
+ }
+
private async snoozes(): Promise<Record<string, string>> {
return decodeJson(
PLACES_CONTRIBUTE_SNOOZE,
diff --git a/server/src/nest/place-contrib/place-contrib.job.ts b/server/src/nest/place-contrib/place-contrib.job.ts
index 4ffee6b64..e214a4ee0 100644
--- a/server/src/nest/place-contrib/place-contrib.job.ts
+++ b/server/src/nest/place-contrib/place-contrib.job.ts
@@ -2,6 +2,7 @@ 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 { PlaceContribBackfill } from './place-contrib-backfill.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';
@@ -12,7 +13,8 @@ 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,
+ * which does nothing unless the installation is eligible and an admin agreed
+ * and first tops the queue up with the catch-up of earlier values,
* and the nightly retention of the transmission log (90 days), which runs
* whatever the decision so a log switched off still ages out.
*/
@@ -20,6 +22,7 @@ const DAY_MS = 24 * 3_600_000;
export class PlaceContribJob implements OnApplicationBootstrap {
constructor(
private readonly sender: PlaceContribSender,
+ private readonly backfill: PlaceContribBackfill,
@InjectRepository(PlaceContribLog) private readonly log: PlaceContribLogRepository,
private readonly registrar: CronRegistrarService,
) {}
@@ -56,6 +59,12 @@ export class PlaceContribJob implements OnApplicationBootstrap {
private async runOnce(): Promise<void> {
this.again = false;
+ // A failed catch-up step never keeps what is queued from going out.
+ try {
+ await this.backfill.step();
+ } catch (err: unknown) {
+ logError(`Places contribution: the catch-up failed: ${err instanceof Error ? err.message : String(err)}`);
+ }
try {
await this.sender.run();
} catch (err: unknown) {
diff --git a/server/src/nest/place-contrib/place-contrib.module.ts b/server/src/nest/place-contrib/place-contrib.module.ts
index 9c0f51c63..23829a085 100644
--- a/server/src/nest/place-contrib/place-contrib.module.ts
+++ b/server/src/nest/place-contrib/place-contrib.module.ts
@@ -6,6 +6,8 @@ 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 { PlaceContribBackfill } from './place-contrib-backfill.service';
+import { PlaceContribQueue } from './place-contrib-queue';
import { PlaceContribSender } from './place-contrib-sender.service';
import { PlaceContribSettings } from './place-contrib-settings';
import { PlaceContribStorageRefsService } from './place-contrib-storage-refs.service';
@@ -19,7 +21,8 @@ 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,
+ * the transmission log, and the catch-up of what users typed before an
+ * admin agreed. Exports PlaceContribService for the places domain,
* whose origin tracking feeds the queue after every place write.
*/
@Module({
@@ -40,6 +43,8 @@ import { Module } from '@nestjs/common';
PlaceContribSender,
PlaceContribJob,
PlaceContribStorageRefsService,
+ PlaceContribQueue,
+ PlaceContribBackfill,
],
exports: [PlaceContribService],
})
diff --git a/server/src/nest/place-contrib/place-contrib.service.ts b/server/src/nest/place-contrib/place-contrib.service.ts
index 535519e81..762b4df8d 100644
--- a/server/src/nest/place-contrib/place-contrib.service.ts
+++ b/server/src/nest/place-contrib/place-contrib.service.ts
@@ -2,18 +2,17 @@ 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 { inOrder } from '../common/in-order';
import { UnitOfWork } from '../database/unit-of-work';
import { SettingsService } from '../settings/settings.service';
+import { PlaceContribQueue } from './place-contrib-queue';
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, newEntryCid, payloadOf, summaryOf } from './place-contrib.helpers';
+import { dayOf } from './place-contrib.helpers';
import { PlaceContribJob } from './place-contrib.job';
-import type { ContribValue, ContribWrite } from './place-contrib.types';
+import type { ContribWrite } from './place-contrib.types';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import {
@@ -53,6 +52,7 @@ export class PlaceContribService {
private readonly client: PlaceContribClient,
private readonly uow: UnitOfWork,
private readonly job: PlaceContribJob,
+ private readonly queue: PlaceContribQueue,
) {}
async state(adminId: number, now: Date = new Date()): Promise<PlaceContribState> {
@@ -98,7 +98,8 @@ export class PlaceContribService {
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.
+ // service asked for is tried again on the next run, and what users
+ // typed before the agreement goes out too, caught up page by page.
await this.uow.transactional(async () => {
await this.store.writeConsent({
enabled: true,
@@ -106,9 +107,12 @@ export class PlaceContribService {
termsVersion: request.termsVersion,
decision: 'agreed',
...decided,
+ includesEarlier: true,
});
await this.store.clearPause();
+ await this.store.writeBackfill({ fields: switchedOn(request.fields), afterId: 0 });
});
+ this.job.sendSoon();
break;
case 'snooze':
await this.store.snooze(adminId, new Date(now.getTime() + SNOOZE_DAYS * DAY_MS));
@@ -173,8 +177,10 @@ export class PlaceContribService {
reason: 'withdraw_all',
}),
);
+ // Everything taken back stays back: the catch-up does not send it again.
const cleared = await this.uow.transactional(async () => {
await this.log.insertLines(lines);
+ await this.store.writeBackfill(null);
return this.outbox.deleteAll();
});
return { withdrawn, cleared };
@@ -192,63 +198,10 @@ export class PlaceContribService {
*/
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(now);
- await inOrder(shared, (value) => this.queueOne(write, { key, value, due, now }));
- });
+ await this.uow.transactional(() => this.queue.put(write, active, now));
this.job.sendSoon();
}
- 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 };
@@ -266,6 +219,7 @@ export class PlaceContribService {
await this.uow.transactional(async () => {
await this.store.writeConsent({ ...consent, ...change, enabled: false });
await this.outbox.deleteAll();
+ await this.store.writeBackfill(null);
});
}
@@ -279,10 +233,21 @@ export class PlaceContribService {
}
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]);
+ const added = PLACE_CONTRIB_FIELDS.filter((field) => !consent.fields[field] && fields[field]);
+ const catchUp = added.length > 0 && consent.includesEarlier === true;
await this.uow.transactional(async () => {
await this.store.writeConsent({ ...consent, fields, ...opts.decided });
await this.outbox.deleteFields(removed);
+ // A field switched on catches up too, under an agreement that said so.
+ // The catch-up keeps one position, so it starts over for every field it
+ // still had to do; what went out already is answered as a duplicate.
+ if (catchUp) {
+ const pending = (await this.store.backfill())?.fields ?? [];
+ const catchUpFields = PLACE_CONTRIB_FIELDS.filter((field) => added.includes(field) || pending.includes(field));
+ await this.store.writeBackfill({ fields: catchUpFields, afterId: 0 });
+ }
});
+ if (catchUp) this.job.sendSoon();
if (!opts.withdraw) return;
await Promise.all(
removed.map(async (field) => {
@@ -297,6 +262,10 @@ function anyField(fields: PlaceContribFieldSwitches): boolean {
return PLACE_CONTRIB_FIELDS.some((field) => fields[field]);
}
+function switchedOn(fields: PlaceContribFieldSwitches): PlaceContribField[] {
+ return PLACE_CONTRIB_FIELDS.filter((field) => fields[field]);
+}
+
function assertCurrentTerms(termsVersion: number): void {
if (termsVersion !== PLACE_CONTRIB_TERMS_VERSION) {
throw conflict('The contribution terms changed', {
diff --git a/server/src/nest/service-identity/service-key.job.ts b/server/src/nest/service-identity/service-key.job.ts
index 38191ea32..cc0b87fc6 100644
--- a/server/src/nest/service-identity/service-key.job.ts
+++ b/server/src/nest/service-identity/service-key.job.ts
@@ -1,16 +1,24 @@
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { ServiceKeyService } from './service-key.service';
-import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
+import { Injectable, type OnApplicationBootstrap, type OnApplicationShutdown } from '@nestjs/common';
import { randomInt } from 'node:crypto';
+/** The first check after startup comes within this window, at a moment picked per start. */
+export const FIRST_CHECK_MIN_MS = 60_000;
+export const FIRST_CHECK_MAX_MS = 10 * 60_000;
+
/**
- * Once a day, at a minute and hour picked per start, renews the installation
- * key when it is due. Spread out so the installations of the world do not all
- * knock on the issuer at the same moment.
+ * The installation key without anyone searching first: one check a few
+ * minutes after startup, then once a day at a minute and hour picked per
+ * start. Each registers a missing key and renews a due one. Both moments are
+ * spread out, so installations that update at the same hour do not all knock
+ * on the issuer at once.
*/
@Injectable()
-export class ServiceKeyJob implements OnApplicationBootstrap {
+export class ServiceKeyJob implements OnApplicationBootstrap, OnApplicationShutdown {
+ private firstCheck: ReturnType<typeof setTimeout> | null = null;
+
constructor(
private readonly keys: ServiceKeyService,
private readonly registrar: CronRegistrarService,
@@ -18,8 +26,20 @@ export class ServiceKeyJob implements OnApplicationBootstrap {
onApplicationBootstrap(): void {
if (!this.registrar.isEnabled()) return;
- this.registrar.register('service-key-renewal', `${randomInt(60)} ${randomInt(24)} * * *`, () =>
- this.keys.renewIfDue(),
+ this.registrar.register('service-key-renewal', `${randomInt(60)} ${randomInt(24)} * * *`, () => this.keys.settle());
+ this.firstCheck = setTimeout(
+ () => {
+ this.firstCheck = null;
+ // A failure is already logged by the key service and retried on its backoff.
+ this.keys.settle().catch(() => undefined);
+ },
+ randomInt(FIRST_CHECK_MIN_MS, FIRST_CHECK_MAX_MS),
);
+ this.firstCheck.unref();
+ }
+
+ onApplicationShutdown(): void {
+ if (this.firstCheck !== null) clearTimeout(this.firstCheck);
+ this.firstCheck = null;
}
}
diff --git a/server/src/nest/service-identity/service-key.service.ts b/server/src/nest/service-identity/service-key.service.ts
index 9a6a3cd15..d45894346 100644
--- a/server/src/nest/service-identity/service-key.service.ts
+++ b/server/src/nest/service-identity/service-key.service.ts
@@ -46,10 +46,10 @@ export interface KeySnapshot {
}
/**
- * The installation key: loaded lazily, registered in the background on the
- * first call to a liketrek service, renewed from day 60 on the next call or
- * the daily check, given up after repeated refusals and frozen when the
- * services revoke it.
+ * The installation key: loaded lazily, registered in the background a few
+ * minutes after startup or on the first call to a liketrek service, whichever
+ * comes first, renewed from day 60 on the next call or the daily check, given
+ * up after repeated refusals and frozen when the services revoke it.
*
* Nothing here ever makes a request wait. Until a key is there, requests go
* out as they always did, and the shared legacy pool answers them.
@@ -138,11 +138,20 @@ export class ServiceKeyService {
void this.inBackground(() => this.markRevoked(token));
}
- /** The daily check: renews the key once it is due. A key past its grace period is already gone on load. */
- async renewIfDue(): Promise<void> {
+ /**
+ * The check after startup and every day: registers when there is no key yet
+ * and the backoff of a failed attempt is over, and renews the key once it is
+ * due. So an installation gets its key without anyone searching for a place
+ * first. A key past its grace period is already gone on load.
+ */
+ async settle(): Promise<void> {
if (!this.inUse()) return;
await this.inBackground(async () => {
await this.load();
+ if (this.wantsRegistration()) {
+ await this.register();
+ return;
+ }
const key = this.dueForRenewal();
if (key) await this.renew(key);
});
diff --git a/server/tests/unit/db/repositories/PlaceContribOutbox.repository.test.ts b/server/tests/unit/db/repositories/PlaceContribOutbox.repository.test.ts
index 3fe52059a..0d8ae3446 100644
--- a/server/tests/unit/db/repositories/PlaceContribOutbox.repository.test.ts
+++ b/server/tests/unit/db/repositories/PlaceContribOutbox.repository.test.ts
@@ -191,4 +191,29 @@ describe('PlaceContribOutboxRepository', () => {
await queue(placeId, { value: 'https://luna.example', cid: 'cid-website-0002' });
expect(await outbox.queuedBefore('2026-06-01 00:00:00', 10)).toEqual([]);
});
+
+ it('PCOUTREPO-009: pages through the places with typed values of the fields asked for, by id, with their origins', async () => {
+ const one = await aPlace({ website: 'https://one.example', osm_id: 'node/1' });
+ const provider = await aPlace({ website: 'https://two.example' });
+ const three = await aPlace({ phone: '+49 381 3' });
+ const four = await aPlace({ website: 'https://four.example' });
+ const origin = (place: number, field: string, kind: string, hash: string) =>
+ insertRow(t, PlaceFieldOrigin, { place, field, origin: kind, value_hash: hash });
+ await origin(one, 'website', 'user', 'h1');
+ await origin(one, 'phone', 'trek', 'h2');
+ await origin(provider, 'website', 'trek', 'h3');
+ await origin(three, 'phone', 'user', 'h4');
+ await origin(four, 'website', 'user', 'h5');
+
+ expect(await outbox.typedAfter(0, [], 10)).toEqual([]);
+ const page = await outbox.typedAfter(0, ['website', 'phone'], 2);
+ expect(page.map((row) => row.place.id)).toEqual([one, three]);
+ expect(page[0]).toEqual({
+ place: expect.objectContaining({ id: one, website: 'https://one.example', osm_id: 'node/1' }),
+ typed: [{ field: 'website', value_hash: 'h1' }],
+ });
+ expect((await outbox.typedAfter(three, ['website', 'phone'], 2)).map((row) => row.place.id)).toEqual([four]);
+ expect(await outbox.typedAfter(four, ['website', 'phone'], 2)).toEqual([]);
+ expect((await outbox.typedAfter(0, ['phone'], 10)).map((row) => row.place.id)).toEqual([three]);
+ });
});
diff --git a/server/tests/unit/nest/place-contrib/place-contrib-backfill.service.test.ts b/server/tests/unit/nest/place-contrib/place-contrib-backfill.service.test.ts
new file mode 100644
index 000000000..78755466b
--- /dev/null
+++ b/server/tests/unit/nest/place-contrib/place-contrib-backfill.service.test.ts
@@ -0,0 +1,269 @@
+/**
+ * PlaceContribBackfill over the real tables on a migrated test db: after an
+ * admin agrees, what users typed into places before that goes out as well,
+ * page by page, only while it is still the user's value, only for fields that
+ * are switched on and only for places the service can key.
+ *
+ * Replaced: the client of the TREK Places API (no request leaves) and the
+ * deployment (a production instance with the index at the public address).
+ */
+import type { AppEnv } from '../../../../src/app-config';
+import { PlaceContribLog } from '../../../../src/db/entities/PlaceContribLog.entity';
+import { PlaceContribOutbox } from '../../../../src/db/entities/PlaceContribOutbox.entity';
+import { PlaceFieldOrigin } from '../../../../src/db/entities/PlaceFieldOrigin.entity';
+import { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service';
+import { servicesConfig } from '../../../../src/nest/app-config/tokens';
+import { valueHash } from '../../../../src/nest/common/value-hash';
+import {
+ BACKFILL_LOW_WATER,
+ PlaceContribBackfill,
+} from '../../../../src/nest/place-contrib/place-contrib-backfill.service';
+import { PlaceContribSettings } from '../../../../src/nest/place-contrib/place-contrib-settings';
+import { PlaceContribClient } from '../../../../src/nest/place-contrib/place-contrib.client';
+import { PlaceContribModule } from '../../../../src/nest/place-contrib/place-contrib.module';
+import { PlaceContribService } from '../../../../src/nest/place-contrib/place-contrib.service';
+import { createSnapshotTestDb } from '../../../helpers/db-mock';
+import { makePlace } from '../../../helpers/factories/places';
+import { countRows, findRows, insertRow } from '../../../helpers/factories/rows';
+import { makeTrip } from '../../../helpers/factories/trips';
+import { makeUser } from '../../../helpers/factories/users';
+import { resetTestDb } from '../../../helpers/test-db';
+import { createTestModule, type TestModule } from '../../../helpers/test-module';
+import { MikroORM } from '@mikro-orm/core';
+import { PLACE_CONTRIB_TERMS_VERSION, type PlaceContribFieldSwitches } from '@trek/shared';
+
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+class ProductionEnv extends RuntimeEnvService {
+ override env(): AppEnv {
+ const env = super.env();
+ return { ...env, maps: { ...env.maps, trekPlacesEnabled: true, trekPlacesUrl: undefined } };
+ }
+
+ override isProduction(): boolean {
+ return true;
+ }
+
+ override isDemoMode(): boolean {
+ return false;
+ }
+}
+
+const client = {
+ hasKey: vi.fn(() => true),
+ keyFingerprint: vi.fn(() => 'fp-1'),
+ withdraw: vi.fn(async (): Promise<unknown> => ({ kind: 'ok', body: { ok: true, withdrawn: { website: 1 } } })),
+};
+
+const ALL: PlaceContribFieldSwitches = {
+ website: true,
+ phone: true,
+ email: true,
+ opening_hours: true,
+ description: true,
+ image: true,
+};
+const GERS = 'gers:ceba0e62-172b-4343-bb3b-78b915a18383';
+const OSM = 'node/4242';
+const ADMIN = 1;
+const NOW = new Date('2026-11-02T12:00:00Z');
+
+const db = createSnapshotTestDb();
+let t: TestModule;
+
+beforeAll(async () => {
+ t = await createTestModule({
+ db,
+ imports: [PlaceContribModule],
+ overrides: [
+ { provide: RuntimeEnvService, useValue: new ProductionEnv() },
+ {
+ provide: servicesConfig.KEY,
+ useValue: {
+ mode: 'auto',
+ key: null,
+ hosts: ['places.liketrek.com'],
+ photonUrl: 'https://photon.liketrek.com',
+ valhallaUrl: 'https://valhalla.liketrek.com',
+ },
+ },
+ { provide: PlaceContribClient, useValue: client },
+ ],
+ });
+});
+
+beforeEach(() => {
+ resetTestDb(db);
+ vi.restoreAllMocks();
+ client.hasKey.mockReturnValue(true);
+});
+
+afterAll(async () => {
+ await t.close();
+ db.close();
+});
+
+const backfill = () => t.get(PlaceContribBackfill);
+const service = () => t.get(PlaceContribService);
+const store = () => t.get(PlaceContribSettings);
+const orm = () => t.get(MikroORM);
+
+async function agree(fields: PlaceContribFieldSwitches = ALL): Promise<void> {
+ await service().decide(ADMIN, { action: 'agree', termsVersion: PLACE_CONTRIB_TERMS_VERSION, fields }, NOW);
+}
+
+/** A place with a website, whose origin is recorded as `origin` for the value given (the current one by default). */
+async function placeWith(
+ opts: { osmId?: string | null; origin?: string; typed?: string; website?: string } = {},
+): Promise<number> {
+ const website = opts.website ?? 'https://cafe-luna.de';
+ const { user } = await makeUser(orm());
+ const trip = await makeTrip(orm(), user.id);
+ const { id } = await makePlace(orm(), trip.id, {
+ name: 'Café Luna',
+ osm_id: opts.osmId === undefined ? GERS : opts.osmId,
+ website,
+ lat: 54.08,
+ lng: 12.13,
+ });
+ await insertRow(orm(), PlaceFieldOrigin, {
+ place: id,
+ field: 'website',
+ origin: opts.origin ?? 'user',
+ value_hash: valueHash(opts.typed ?? website),
+ });
+ return id;
+}
+
+const queued = async () =>
+ (await findRows(orm(), PlaceContribOutbox, {})).map((row) => ({ place: row.place_id, field: row.field }));
+
+describe('PlaceContribBackfill', () => {
+ it('PCB-001: an agreement starts the catch-up for every field switched on', async () => {
+ await agree({ ...ALL, image: false });
+ expect(await store().backfill()).toEqual({
+ fields: ['website', 'phone', 'email', 'opening_hours', 'description'],
+ afterId: 0,
+ });
+ });
+
+ it('PCB-002: queues what a user typed earlier, and leaves provider values, changed values and unkeyed places', async () => {
+ const typed = await placeWith();
+ await placeWith({ origin: 'trek' });
+ await placeWith({ typed: 'https://old.example' });
+ const unkeyed = await placeWith({ osmId: null });
+ const osm = await placeWith({ osmId: OSM });
+ await agree();
+
+ expect(await backfill().step(NOW)).toBe(2);
+ expect(await queued()).toEqual([
+ { place: typed, field: 'website' },
+ { place: osm, field: 'website' },
+ ]);
+ // An unkeyed place is passed over without a line in the log.
+ expect(await countRows(orm(), PlaceContribLog)).toBe(0);
+ expect((await store().backfill())?.afterId).toBe(Math.max(typed, unkeyed, osm));
+ });
+
+ it('PCB-003: goes on after the last place it queued, and ends once nothing is left', async () => {
+ const first = await placeWith();
+ const second = await placeWith();
+ await agree();
+ await store().writeBackfill({ fields: ['website'], afterId: first });
+
+ expect(await backfill().step(NOW)).toBe(1);
+ expect(await queued()).toEqual([{ place: second, field: 'website' }]);
+ expect(await backfill().step(NOW)).toBe(0);
+ expect(await store().backfill()).toBeNull();
+ });
+
+ it('PCB-004: waits without a key, and while the queue is full enough', async () => {
+ await placeWith();
+ await agree();
+ client.hasKey.mockReturnValue(false);
+ expect(await backfill().step(NOW)).toBe(0);
+ expect(await store().backfill()).not.toBeNull();
+
+ client.hasKey.mockReturnValue(true);
+ const outbox = (backfill() as unknown as { outbox: { size: () => Promise<number> } }).outbox;
+ vi.spyOn(outbox, 'size').mockResolvedValueOnce(BACKFILL_LOW_WATER);
+ expect(await backfill().step(NOW)).toBe(0);
+ expect(await queued()).toEqual([]);
+ expect(await backfill().step(NOW)).toBe(1);
+ });
+
+ it('PCB-005: does nothing without a catch-up, and ends one whose fields were all switched off', async () => {
+ await placeWith();
+ expect(await backfill().step(NOW)).toBe(0);
+
+ await agree();
+ await store().writeBackfill({ fields: ['email'], afterId: 0 });
+ await service().decide(ADMIN, { action: 'fields', fields: { ...ALL, email: false } }, NOW);
+ expect(await backfill().step(NOW)).toBe(0);
+ expect(await store().backfill()).toBeNull();
+ expect(await queued()).toEqual([]);
+ });
+
+ it('PCB-006: a field switched on later catches up from the start, together with what was still to do', async () => {
+ await agree({ ...ALL, website: false, phone: false });
+ await store().writeBackfill({ fields: ['email'], afterId: 7 });
+ await service().decide(ADMIN, { action: 'fields', fields: { ...ALL, phone: false } }, NOW);
+ expect(await store().backfill()).toEqual({ fields: ['website', 'email'], afterId: 0 });
+
+ // A change that switches nothing on leaves the catch-up where it is.
+ await store().writeBackfill({ fields: ['email'], afterId: 7 });
+ await service().decide(ADMIN, { action: 'fields', fields: { ...ALL, phone: false, website: false } }, NOW);
+ expect(await store().backfill()).toEqual({ fields: ['email'], afterId: 7 });
+ });
+
+ it('PCB-008: a value a save queued for the same place key is newer and stays', async () => {
+ const older = await placeWith({ website: 'https://old-luna.example' });
+ const newer = await placeWith({ website: 'https://cafe-luna.de' });
+ await agree();
+ await service().enqueue(
+ {
+ placeId: newer,
+ osmId: GERS,
+ name: 'Café Luna',
+ lat: 54.08,
+ lng: 12.13,
+ country: 'DE',
+ values: [{ field: 'website', value: 'https://cafe-luna.de' }],
+ dropped: [],
+ },
+ NOW,
+ );
+ await store().writeBackfill({ fields: ['website'], afterId: 0 });
+ await backfill().step(NOW);
+ const rows = await findRows(orm(), PlaceContribOutbox, {});
+ expect(rows.map((row) => ({ place: row.place_id, value: row.value }))).toEqual([
+ { place: newer, value: expect.stringContaining('cafe-luna.de') },
+ ]);
+ expect(rows.some((row) => row.place_id === older)).toBe(false);
+ });
+
+ it('PCB-009: an agreement from 5.1.0 does not catch up when a field is switched on later', async () => {
+ await agree({ ...ALL, phone: false });
+ const consent = await store().consent();
+ await store().writeConsent({ ...consent, includesEarlier: undefined });
+ await store().writeBackfill(null);
+ await service().decide(ADMIN, { action: 'fields', fields: ALL }, NOW);
+ expect(await store().backfill()).toBeNull();
+ });
+
+ it('PCB-010: withdrawing everything ends the catch-up, so nothing taken back goes out again', async () => {
+ await agree();
+ await service().withdrawAll(NOW);
+ expect(await store().backfill()).toBeNull();
+ });
+
+ it('PCB-007: switching off or declining ends the catch-up', async () => {
+ await agree();
+ await service().decide(ADMIN, { action: 'off' }, NOW);
+ expect(await store().backfill()).toBeNull();
+
+ await agree();
+ await service().decide(ADMIN, { action: 'decline', termsVersion: PLACE_CONTRIB_TERMS_VERSION }, NOW);
+ expect(await store().backfill()).toBeNull();
+ });
+});
diff --git a/server/tests/unit/nest/place-contrib/place-contrib.job.test.ts b/server/tests/unit/nest/place-contrib/place-contrib.job.test.ts
index 642bda9ce..ba85e56cc 100644
--- a/server/tests/unit/nest/place-contrib/place-contrib.job.test.ts
+++ b/server/tests/unit/nest/place-contrib/place-contrib.job.test.ts
@@ -1,10 +1,12 @@
/**
* The two crons of the community enrichment: registration behind the test
* gate, the log retention cut-off, that a failing run or sweep stays inside
- * its tick, and the run a save starts at once.
+ * its tick, the run a save starts at once, and the catch-up step before
+ * every run.
*/
import type { PlaceContribLogRepository } from '../../../../src/db/repositories/PlaceContribLog.repository';
import { inOrder } from '../../../../src/nest/common/in-order';
+import type { PlaceContribBackfill } from '../../../../src/nest/place-contrib/place-contrib-backfill.service';
import type { PlaceContribSender } from '../../../../src/nest/place-contrib/place-contrib-sender.service';
import { PlaceContribJob } from '../../../../src/nest/place-contrib/place-contrib.job';
import type { CronRegistrarService } from '../../../../src/nest/scheduling/cron-registrar.service';
@@ -22,14 +24,16 @@ vi.mock('../../../../src/nest/audit/audit-log.logger', () => logMock);
function make(enabled = true) {
const sender = { run: vi.fn(async () => ({ skipped: null, places: 0, expired: 0 })) };
+ const backfill = { step: vi.fn(async () => 0) };
const log = { purgeBefore: vi.fn(async () => 0) };
const registrar = { isEnabled: vi.fn(() => enabled), register: vi.fn(() => enabled) };
const job = new PlaceContribJob(
sender as unknown as PlaceContribSender,
+ backfill as unknown as PlaceContribBackfill,
log as unknown as PlaceContribLogRepository,
registrar as unknown as CronRegistrarService,
);
- return { job, sender, log, registrar };
+ return { job, sender, backfill, log, registrar };
}
beforeEach(() => vi.clearAllMocks());
@@ -99,9 +103,22 @@ describe('PlaceContribJob', () => {
const first = job.send();
const second = job.send();
const third = job.send();
- expect(sender.run).toHaveBeenCalledTimes(1);
+ // The catch-up step comes first, so the sender starts a moment later.
+ await vi.waitFor(() => expect(sender.run).toHaveBeenCalledTimes(1));
release();
await Promise.all([first, second, third]);
expect(sender.run).toHaveBeenCalledTimes(2);
});
+
+ it('PCJ-008: every run first tops the queue up from the catch-up, and a failed step still sends', async () => {
+ const { job, sender, backfill } = make();
+ await job.send();
+ expect(backfill.step).toHaveBeenCalledTimes(1);
+ expect(backfill.step.mock.invocationCallOrder[0]).toBeLessThan(sender.run.mock.invocationCallOrder[0]);
+
+ backfill.step.mockRejectedValueOnce(new Error('database is locked'));
+ await job.send();
+ expect(sender.run).toHaveBeenCalledTimes(2);
+ expect(logMock.logError).toHaveBeenCalledWith(expect.stringContaining('catch-up'));
+ });
});
diff --git a/server/tests/unit/nest/place-contrib/place-contrib.service.test.ts b/server/tests/unit/nest/place-contrib/place-contrib.service.test.ts
index 86f4a23a5..14d273422 100644
--- a/server/tests/unit/nest/place-contrib/place-contrib.service.test.ts
+++ b/server/tests/unit/nest/place-contrib/place-contrib.service.test.ts
@@ -215,6 +215,7 @@ describe('the admin state and the decisions', () => {
decision: 'agreed',
decidedBy: ADMIN,
decidedAt: NOW.toISOString(),
+ includesEarlier: true,
});
expect(await store().activeFields()).toEqual(['website', 'phone', 'opening_hours', 'description', 'image']);
});
diff --git a/server/tests/unit/nest/service-identity/service-key.job.test.ts b/server/tests/unit/nest/service-identity/service-key.job.test.ts
index e530875c5..f77f11015 100644
--- a/server/tests/unit/nest/service-identity/service-key.job.test.ts
+++ b/server/tests/unit/nest/service-identity/service-key.job.test.ts
@@ -1,18 +1,22 @@
/**
- * ServiceKeyJob: one daily renewal check through the registrar, at a minute
- * and hour of its own, and nothing at all where the registrar schedules
- * nothing (NODE_ENV=test).
+ * ServiceKeyJob: one check a few minutes after startup and one daily check
+ * through the registrar, at a minute and hour of its own, and nothing at all
+ * where the registrar schedules nothing (NODE_ENV=test).
*/
import { CronRegistrarService } from '../../../../src/nest/scheduling/cron-registrar.service';
-import { ServiceKeyJob } from '../../../../src/nest/service-identity/service-key.job';
+import {
+ FIRST_CHECK_MAX_MS,
+ FIRST_CHECK_MIN_MS,
+ ServiceKeyJob,
+} from '../../../../src/nest/service-identity/service-key.job';
import { ServiceKeyService } from '../../../../src/nest/service-identity/service-key.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createTestModule, type TestModule } from '../../../helpers/test-module';
-import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const registrar = { isEnabled: vi.fn(() => true), register: vi.fn() };
-const keys = { renewIfDue: vi.fn(async () => undefined) };
+const keys = { settle: vi.fn(async (): Promise<void> => undefined) };
const testDb = createSnapshotTestDb();
let t: TestModule;
@@ -36,8 +40,13 @@ afterAll(async () => {
beforeEach(() => vi.clearAllMocks());
+afterEach(() => {
+ t.get(ServiceKeyJob).onApplicationShutdown();
+ vi.useRealTimers();
+});
+
describe('ServiceKeyJob', () => {
- it('SIJOB-001: registers a daily check at a minute and hour of its own, which renews when due', async () => {
+ it('SIJOB-001: registers a daily check at a minute and hour of its own, which registers or renews', async () => {
t.get(ServiceKeyJob).onApplicationBootstrap();
expect(registrar.register).toHaveBeenCalledTimes(1);
const [name, expression, tick] = registrar.register.mock.calls[0] as [string, string, () => Promise<void>];
@@ -48,12 +57,40 @@ describe('ServiceKeyJob', () => {
expect(Number(hour)).toBeLessThan(24);
expect(rest).toEqual(['*', '*', '*']);
await tick();
- expect(keys.renewIfDue).toHaveBeenCalledTimes(1);
+ expect(keys.settle).toHaveBeenCalledTimes(1);
});
- it('SIJOB-002: schedules nothing where the registrar is off', () => {
+ it('SIJOB-002: schedules nothing where the registrar is off, not even the first check', () => {
+ vi.useFakeTimers();
registrar.isEnabled.mockReturnValueOnce(false);
t.get(ServiceKeyJob).onApplicationBootstrap();
+ vi.advanceTimersByTime(FIRST_CHECK_MAX_MS);
expect(registrar.register).not.toHaveBeenCalled();
+ expect(keys.settle).not.toHaveBeenCalled();
+ });
+
+ it('SIJOB-003: checks the key once within minutes of startup, so nobody has to search first', () => {
+ vi.useFakeTimers();
+ t.get(ServiceKeyJob).onApplicationBootstrap();
+ vi.advanceTimersByTime(FIRST_CHECK_MIN_MS - 1);
+ expect(keys.settle).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(FIRST_CHECK_MAX_MS - FIRST_CHECK_MIN_MS + 1);
+ expect(keys.settle).toHaveBeenCalledTimes(1);
+ vi.advanceTimersByTime(FIRST_CHECK_MAX_MS);
+ expect(keys.settle).toHaveBeenCalledTimes(1);
+ });
+
+ it('SIJOB-004: a failed first check is left to the key service, and shutdown cancels a pending one', async () => {
+ vi.useFakeTimers();
+ keys.settle.mockRejectedValueOnce(new Error('fetch failed'));
+ t.get(ServiceKeyJob).onApplicationBootstrap();
+ vi.advanceTimersByTime(FIRST_CHECK_MAX_MS);
+ await Promise.resolve();
+ expect(keys.settle).toHaveBeenCalledTimes(1);
+
+ t.get(ServiceKeyJob).onApplicationBootstrap();
+ t.get(ServiceKeyJob).onApplicationShutdown();
+ vi.advanceTimersByTime(FIRST_CHECK_MAX_MS);
+ expect(keys.settle).toHaveBeenCalledTimes(1);
});
});
diff --git a/server/tests/unit/nest/service-identity/service-key.service.test.ts b/server/tests/unit/nest/service-identity/service-key.service.test.ts
index f14d181e0..921aa0676 100644
--- a/server/tests/unit/nest/service-identity/service-key.service.test.ts
+++ b/server/tests/unit/nest/service-identity/service-key.service.test.ts
@@ -333,6 +333,41 @@ describe('registration', () => {
});
});
+describe('the check after startup and every day', () => {
+ it('SIKEYS-039: registers without any request having asked first', async () => {
+ const { keys, store, issuer } = await build();
+ await keys.settle();
+ expect(issuer.register).toHaveBeenCalledTimes(1);
+ expect(store.current().key?.token).toBe(KEY);
+ expect(keys.bearer()).toBe(KEY);
+ });
+
+ it('SIKEYS-040: waits out the backoff of a failed attempt, then registers on the next check', async () => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ const issuer = fakeIssuer();
+ issuer.challenge.mockRejectedValueOnce(new Error('fetch failed'));
+ const { keys } = await build({ issuer });
+ await expect(keys.settle()).rejects.toThrow('fetch failed');
+ await keys.settle();
+ expect(issuer.challenge).toHaveBeenCalledTimes(1);
+ vi.setSystemTime(Date.now() + 5 * 60_000);
+ await keys.settle();
+ expect(issuer.register).toHaveBeenCalledTimes(1);
+ expect(keys.bearer()).toBe(KEY);
+ });
+
+ it.each([
+ ['the services are off', { config: { mode: 'off' as const } }],
+ ['the TREK index is off', { places: { enabled: false } }],
+ ['a key comes from the environment', { config: { key: KEY } }],
+ ['the index is an own copy', { places: { url: 'https://places.example.org' } }],
+ ])('SIKEYS-041: does not register when %s', async (_case, setup) => {
+ const { keys, issuer } = await build(setup);
+ await keys.settle();
+ expect(issuer.challenge).not.toHaveBeenCalled();
+ });
+});
+
describe('when it never registers', () => {
it('SIKEYS-010: never under NODE_ENV=test', async () => {
const { keys, issuer } = await build({ isTest: true });
@@ -481,14 +516,14 @@ describe('renewal', () => {
it('SIKEYS-030: leaves a key alone before it is due', async () => {
const { keys, issuer } = await build({ store: stored({ renewAfter: now() + DAY }) });
- await keys.renewIfDue();
+ await keys.settle();
expect(issuer.renew).not.toHaveBeenCalled();
});
it('SIKEYS-031: renews from day 60 with the old key, keeping the same installation', async () => {
const store = stored();
const { keys, issuer } = await build({ store });
- await keys.renewIfDue();
+ await keys.settle();
expect(issuer.renew).toHaveBeenCalledWith(oldKey);
expect(store.current().key?.token).toBe(RENEWED_KEY);
expect(store.current().state.renewAfter).toBeGreaterThan(now() + 149 * DAY);
@@ -500,7 +535,7 @@ describe('renewal', () => {
const issuer = fakeIssuer();
const { keys } = await build({ store, issuer });
t?.get(ServiceClock).learn(Date.now() + 2 * DAY * 1000);
- await keys.renewIfDue();
+ await keys.settle();
expect(issuer.renew).toHaveBeenCalledTimes(1);
});
@@ -509,12 +544,12 @@ describe('renewal', () => {
const refused = fakeIssuer();
refused.renew.mockRejectedValue(new IssuerError(401, null, null));
const first = await build({ store: stored(), issuer: refused });
- await first.keys.renewIfDue();
- await first.keys.renewIfDue();
+ await first.keys.settle();
+ await first.keys.settle();
expect(first.store.dropKey).not.toHaveBeenCalled();
await oneByOne(Array.from({ length: 2 }), () => {
vi.setSystemTime(Date.now() + 10 * 60_000);
- return first.keys.renewIfDue();
+ return first.keys.settle();
});
expect(first.store.dropKey).toHaveBeenCalledTimes(1);
vi.useRealTimers();
@@ -523,14 +558,14 @@ describe('renewal', () => {
const revoked = fakeIssuer();
revoked.renew.mockRejectedValueOnce(new IssuerError(403, null, null));
const second = await build({ store: stored(), issuer: revoked });
- await second.keys.renewIfDue();
+ await second.keys.settle();
expect(second.store.current().state.revoked).toBe(keyFingerprint(oldKey));
await t?.close();
const down = fakeIssuer();
down.renew.mockRejectedValueOnce(new Error('fetch failed'));
const third = await build({ store: stored(), issuer: down });
- await expect(third.keys.renewIfDue()).rejects.toThrow('fetch failed');
+ await expect(third.keys.settle()).rejects.toThrow('fetch failed');
expect(third.store.current().key?.token).toBe(oldKey);
});
@@ -544,7 +579,7 @@ describe('renewal', () => {
},
});
const { keys, issuer } = await build({ store });
- await keys.renewIfDue();
+ await keys.settle();
expect(issuer.renew).not.toHaveBeenCalled();
keys.bearer();
await settled(keys);
@@ -554,7 +589,7 @@ describe('renewal', () => {
it('SIKEYS-035: never renews a key from the environment', async () => {
const { keys, issuer } = await build({ store: stored(), config: { key: KEY } });
- await keys.renewIfDue();
+ await keys.settle();
expect(issuer.renew).not.toHaveBeenCalled();
});
diff --git a/shared/src/i18n/ar/admin.ts b/shared/src/i18n/ar/admin.ts
index dab66593b..9eef0ece6 100644
--- a/shared/src/i18n/ar/admin.ts
+++ b/shared/src/i18n/ar/admin.ts
@@ -1174,6 +1174,7 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'التفاصيل التي يملؤها Google أو مزوّد آخر',
'admin.contribute.prompt.how':
'فقط ما كتبه مستخدموك بأنفسهم، وفقط للأماكن التي يعرفها الفهرس. لا يُرسل معه أي مستخدم أو رحلة أو حساب. يعرض السجل كل عملية إرسال، ويمكنك إيقاف حقول أو سحب كل شيء في أي وقت.',
+ 'admin.contribute.prompt.past': 'تتم مشاركة التفاصيل التي كتبها مستخدموك منذ TREK 5.1 أيضًا، تدريجيًا.',
'admin.contribute.prompt.openRegistration':
'التسجيل مفتوح في هذا التثبيت، لذا يمكن لأي شخص لديه حساب كتابة التفاصيل. تُفحص كل قيمة قبل نشرها.',
'admin.contribute.prompt.footnote': 'أنت تقرر ذلك للتثبيت بأكمله. لا يُسأل مستخدموك.',
diff --git a/shared/src/i18n/az/admin.ts b/shared/src/i18n/az/admin.ts
index f2a96c5f0..23665fa76 100644
--- a/shared/src/i18n/az/admin.ts
+++ b/shared/src/i18n/az/admin.ts
@@ -1161,6 +1161,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Google və ya başqa provayderin doldurduğu məlumatlar',
'admin.contribute.prompt.how':
'Yalnız istifadəçilərinizin özlərinin yazdıqları və yalnız indeksin tanıdığı məkanlar üçün. Heç bir istifadəçi, səyahət və ya hesab bunlarla göndərilmir. Jurnal hər göndərməni göstərir, siz isə istənilən vaxt sahələri söndürə və ya hər şeyi geri götürə bilərsiniz.',
+ 'admin.contribute.prompt.past':
+ 'İstifadəçilərinizin TREK 5.1-dən bəri daxil etdiyi məlumatlar da tədricən paylaşılır.',
'admin.contribute.prompt.openRegistration':
'Bu quraşdırmada qeydiyyat açıqdır, ona görə hesabı olan hər kəs məlumat yaza bilər. Hər dəyər dərc edilməzdən əvvəl yoxlanılır.',
'admin.contribute.prompt.footnote':
diff --git a/shared/src/i18n/br/admin.ts b/shared/src/i18n/br/admin.ts
index 14f35b6de..1641dbd01 100644
--- a/shared/src/i18n/br/admin.ts
+++ b/shared/src/i18n/br/admin.ts
@@ -1137,6 +1137,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Detalhes preenchidos pelo Google ou por outro provedor',
'admin.contribute.prompt.how':
'Somente o que seus usuários digitaram por conta própria, e somente para locais que o índice conhece. Nenhum usuário, viagem ou conta vai junto. O registro mostra cada envio, e você pode desativar campos ou retirar tudo a qualquer momento.',
+ 'admin.contribute.prompt.past':
+ 'Os detalhes que seus usuários digitaram desde o TREK 5.1 também são compartilhados, aos poucos.',
'admin.contribute.prompt.openRegistration':
'O cadastro está aberto nesta instalação, então qualquer pessoa com uma conta pode digitar detalhes. Cada valor é verificado antes de ser publicado.',
'admin.contribute.prompt.footnote': 'Você decide isso para a instalação inteira. Seus usuários não são consultados.',
diff --git a/shared/src/i18n/ca/admin.ts b/shared/src/i18n/ca/admin.ts
index faea2c6e2..9c6900a2c 100644
--- a/shared/src/i18n/ca/admin.ts
+++ b/shared/src/i18n/ca/admin.ts
@@ -1151,6 +1151,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Detalls emplenats per Google o un altre proveïdor',
'admin.contribute.prompt.how':
"Només el que els teus usuaris han escrit ells mateixos, i només per a llocs que l'índex coneix. No s'envia cap usuari, viatge ni compte. El registre mostra cada enviament, i pots desactivar camps o retirar-ho tot en qualsevol moment.",
+ 'admin.contribute.prompt.past':
+ 'També es comparteixen, de mica en mica, els detalls que els vostres usuaris han escrit des de TREK 5.1.',
'admin.contribute.prompt.openRegistration':
'El registre és obert en aquesta instal·lació, així que qualsevol persona amb un compte pot escriure detalls. Cada valor es revisa abans de publicar-se.',
'admin.contribute.prompt.footnote': 'Ho decideixes per a tota la instal·lació. No es pregunta als teus usuaris.',
diff --git a/shared/src/i18n/cs/admin.ts b/shared/src/i18n/cs/admin.ts
index cacdc5650..ba2fdca9a 100644
--- a/shared/src/i18n/cs/admin.ts
+++ b/shared/src/i18n/cs/admin.ts
@@ -1138,6 +1138,7 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Údaje vyplněné Googlem nebo jiným poskytovatelem',
'admin.contribute.prompt.how':
'Jen to, co uživatelé zadali sami, a jen pro místa, která index zná. Žádný uživatel, cesta ani účet se neodesílá. Protokol ukazuje každé odeslání a pole můžete kdykoli vypnout nebo vše stáhnout zpět.',
+ 'admin.contribute.prompt.past': 'Údaje, které vaši uživatelé zadali od TREK 5.1, se sdílejí také, postupně.',
'admin.contribute.prompt.openRegistration':
'V této instalaci je otevřená registrace, takže údaje může zadávat kdokoli s účtem. Každá hodnota se před zveřejněním kontroluje.',
'admin.contribute.prompt.footnote': 'Rozhodujete za celou instalaci. Vaši uživatelé o souhlas požádáni nejsou.',
diff --git a/shared/src/i18n/de/admin.ts b/shared/src/i18n/de/admin.ts
index 23a4d8fad..0f0a8f9c4 100644
--- a/shared/src/i18n/de/admin.ts
+++ b/shared/src/i18n/de/admin.ts
@@ -1144,6 +1144,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Details, die Google oder ein anderer Anbieter ausgefüllt hat',
'admin.contribute.prompt.how':
'Nur was eure Nutzer selbst eingetippt haben, und nur für Orte, die der Index kennt. Kein Nutzer, keine Reise und kein Konto gehen mit. Das Protokoll zeigt jede Übertragung, und du kannst jederzeit Felder abschalten oder alles zurückziehen.',
+ 'admin.contribute.prompt.past':
+ 'Auch was eure Nutzer seit TREK 5.1 schon eingetippt haben, wird nach und nach geteilt.',
'admin.contribute.prompt.openRegistration':
'Auf dieser Installation ist die Registrierung offen, also kann jeder mit einem Konto Details eintragen. Jeder Wert wird vor der Veröffentlichung geprüft.',
'admin.contribute.prompt.footnote':
diff --git a/shared/src/i18n/en/admin.ts b/shared/src/i18n/en/admin.ts
index 8d60b0da0..4d435acc0 100644
--- a/shared/src/i18n/en/admin.ts
+++ b/shared/src/i18n/en/admin.ts
@@ -1109,6 +1109,7 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Details filled in by Google or another provider',
'admin.contribute.prompt.how':
'Only what your users typed themselves, and only for places the index knows. No user, trip or account goes with it. The log shows every transmission, and you can switch off fields or withdraw everything at any time.',
+ 'admin.contribute.prompt.past': 'Details your users typed since TREK 5.1 are shared as well, a few at a time.',
'admin.contribute.prompt.openRegistration':
'Registration is open on this installation, so anyone with an account can type details. Every value is checked before it is published.',
'admin.contribute.prompt.footnote': 'You decide this for the whole installation. Your users are not asked.',
diff --git a/shared/src/i18n/es/admin.ts b/shared/src/i18n/es/admin.ts
index f05cadaf9..08574f3ec 100644
--- a/shared/src/i18n/es/admin.ts
+++ b/shared/src/i18n/es/admin.ts
@@ -1155,6 +1155,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Detalles rellenados por Google u otro proveedor',
'admin.contribute.prompt.how':
'Solo lo que tus usuarios escribieron ellos mismos, y solo para lugares que el índice conoce. No se envía ningún usuario, viaje ni cuenta. El registro muestra cada envío, y puedes desactivar campos o retirarlo todo en cualquier momento.',
+ 'admin.contribute.prompt.past':
+ 'Los detalles que tus usuarios escribieron desde TREK 5.1 también se comparten, poco a poco.',
'admin.contribute.prompt.openRegistration':
'El registro está abierto en esta instalación, así que cualquiera con una cuenta puede escribir detalles. Cada valor se revisa antes de publicarse.',
'admin.contribute.prompt.footnote': 'Lo decides para toda la instalación. No se pregunta a tus usuarios.',
diff --git a/shared/src/i18n/et/admin.ts b/shared/src/i18n/et/admin.ts
index 371d0c203..0fa80b1f3 100644
--- a/shared/src/i18n/et/admin.ts
+++ b/shared/src/i18n/et/admin.ts
@@ -1131,6 +1131,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': "Google'i või mõne muu pakkuja täidetud andmed",
'admin.contribute.prompt.how':
'Ainult see, mida sinu kasutajad ise sisestasid, ja ainult kohtade kohta, mida indeks tunneb. Kaasa ei lähe ükski kasutaja, reis ega konto. Logi näitab iga edastust ning sa saad välju igal ajal välja lülitada või kõik tagasi võtta.',
+ 'admin.contribute.prompt.past':
+ 'Ka andmeid, mille teie kasutajad on sisestanud alates TREK 5.1-st, jagatakse järk-järgult.',
'admin.contribute.prompt.openRegistration':
'Sellel paigaldusel on registreerimine avatud, seega saab andmeid sisestada igaüks, kellel on konto. Iga väärtus kontrollitakse enne avaldamist.',
'admin.contribute.prompt.footnote': 'Sa otsustad selle kogu paigalduse eest. Sinu kasutajatelt ei küsita.',
diff --git a/shared/src/i18n/fr/admin.ts b/shared/src/i18n/fr/admin.ts
index 744f328b2..e9d2a822f 100644
--- a/shared/src/i18n/fr/admin.ts
+++ b/shared/src/i18n/fr/admin.ts
@@ -1158,6 +1158,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Détails renseignés par Google ou un autre fournisseur',
'admin.contribute.prompt.how':
"Seulement ce que vos utilisateurs ont saisi eux-mêmes, et seulement pour les lieux que l'index connaît. Aucun utilisateur, voyage ou compte n'accompagne ces données. Le journal montre chaque transmission, et vous pouvez désactiver des champs ou tout retirer à tout moment.",
+ 'admin.contribute.prompt.past':
+ 'Les détails que vos utilisateurs ont saisis depuis TREK 5.1 sont aussi partagés, petit à petit.',
'admin.contribute.prompt.openRegistration':
"L'inscription est ouverte sur cette installation : toute personne ayant un compte peut donc saisir des détails. Chaque valeur est vérifiée avant d'être publiée.",
'admin.contribute.prompt.footnote':
diff --git a/shared/src/i18n/gr/admin.ts b/shared/src/i18n/gr/admin.ts
index da104ed76..afa69cee8 100644
--- a/shared/src/i18n/gr/admin.ts
+++ b/shared/src/i18n/gr/admin.ts
@@ -1164,6 +1164,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Στοιχεία που συμπληρώνονται από την Google ή άλλον πάροχο',
'admin.contribute.prompt.how':
'Μόνο όσα πληκτρολόγησαν οι ίδιοι οι χρήστες σας και μόνο για τόπους που γνωρίζει το ευρετήριο. Κανένας χρήστης, ταξίδι ή λογαριασμός δεν συνοδεύει τα στοιχεία. Το αρχείο καταγραφής δείχνει κάθε αποστολή και μπορείτε να απενεργοποιήσετε πεδία ή να αποσύρετε τα πάντα οποιαδήποτε στιγμή.',
+ 'admin.contribute.prompt.past':
+ 'Και όσα έχουν πληκτρολογήσει οι χρήστες σας από το TREK 5.1 κοινοποιούνται σταδιακά.',
'admin.contribute.prompt.openRegistration':
'Η εγγραφή είναι ανοιχτή σε αυτήν την εγκατάσταση, επομένως όποιος έχει λογαριασμό μπορεί να πληκτρολογήσει στοιχεία. Κάθε τιμή ελέγχεται πριν δημοσιευτεί.',
'admin.contribute.prompt.footnote': 'Το αποφασίζετε για ολόκληρη την εγκατάσταση. Οι χρήστες σας δεν ερωτώνται.',
diff --git a/shared/src/i18n/he/admin.ts b/shared/src/i18n/he/admin.ts
index 385f703c0..99c3211a2 100644
--- a/shared/src/i18n/he/admin.ts
+++ b/shared/src/i18n/he/admin.ts
@@ -1088,6 +1088,7 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'פרטים שמולאו על ידי Google או ספק אחר',
'admin.contribute.prompt.how':
'רק מה שהמשתמשים שלכם הקלידו בעצמם, ורק עבור מקומות שהאינדקס מכיר. שום משתמש, טיול או חשבון לא נשלח יחד איתו. היומן מציג כל שליחה, ואפשר לכבות שדות או למשוך הכול בכל עת.',
+ 'admin.contribute.prompt.past': 'גם פרטים שהמשתמשים שלך הקלידו מאז TREK 5.1 משותפים, בהדרגה.',
'admin.contribute.prompt.openRegistration':
'ההרשמה פתוחה בהתקנה הזו, כך שכל מי שיש לו חשבון יכול להקליד פרטים. כל ערך נבדק לפני שהוא מתפרסם.',
'admin.contribute.prompt.footnote': 'אתם מחליטים על זה עבור ההתקנה כולה. המשתמשים שלכם לא נשאלים.',
diff --git a/shared/src/i18n/hu/admin.ts b/shared/src/i18n/hu/admin.ts
index d334d7914..3ed660c55 100644
--- a/shared/src/i18n/hu/admin.ts
+++ b/shared/src/i18n/hu/admin.ts
@@ -1151,6 +1151,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'A Google vagy más szolgáltató által kitöltött adatok',
'admin.contribute.prompt.how':
'Csak amit a felhasználóid maguk írtak be, és csak olyan helyekhez, amelyeket az index ismer. Felhasználó, út vagy fiók nem megy vele. A napló minden átvitelt megmutat, a mezőket bármikor kikapcsolhatod, vagy mindent visszavonhatsz.',
+ 'admin.contribute.prompt.past':
+ 'A felhasználók által a TREK 5.1 óta beírt adatok is megosztásra kerülnek, fokozatosan.',
'admin.contribute.prompt.openRegistration':
'Ezen a telepítésen nyitott a regisztráció, így bárki, akinek van fiókja, beírhat adatokat. Minden értéket ellenőrzünk a közzététel előtt.',
'admin.contribute.prompt.footnote': 'Ezt az egész telepítésre döntöd el. A felhasználóidat nem kérdezzük.',
diff --git a/shared/src/i18n/id/admin.ts b/shared/src/i18n/id/admin.ts
index 56ffc5c1b..9258ba4a6 100644
--- a/shared/src/i18n/id/admin.ts
+++ b/shared/src/i18n/id/admin.ts
@@ -1121,6 +1121,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Detail yang diisi oleh Google atau penyedia lain',
'admin.contribute.prompt.how':
'Hanya yang diketik sendiri oleh pengguna Anda, dan hanya untuk tempat yang dikenal indeks. Tidak ada pengguna, perjalanan, atau akun yang ikut terkirim. Log menunjukkan setiap pengiriman, dan Anda dapat mematikan bidang atau menarik semuanya kapan saja.',
+ 'admin.contribute.prompt.past':
+ 'Detail yang diketik pengguna Anda sejak TREK 5.1 juga dibagikan, sedikit demi sedikit.',
'admin.contribute.prompt.openRegistration':
'Pendaftaran terbuka di instalasi ini, jadi siapa pun yang punya akun dapat mengetik detail. Setiap nilai diperiksa sebelum dipublikasikan.',
'admin.contribute.prompt.footnote': 'Anda memutuskan ini untuk seluruh instalasi. Pengguna Anda tidak ditanya.',
diff --git a/shared/src/i18n/it/admin.ts b/shared/src/i18n/it/admin.ts
index 3e79a9c28..e79744486 100644
--- a/shared/src/i18n/it/admin.ts
+++ b/shared/src/i18n/it/admin.ts
@@ -1147,6 +1147,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Dettagli compilati da Google o da un altro provider',
'admin.contribute.prompt.how':
"Solo ciò che i tuoi utenti hanno scritto di persona, e solo per luoghi che l'indice conosce. Nessun utente, viaggio o account viene inviato insieme. Il registro mostra ogni invio e puoi disattivare i campi o ritirare tutto in qualsiasi momento.",
+ 'admin.contribute.prompt.past':
+ "Anche i dettagli che i tuoi utenti hanno inserito da TREK 5.1 vengono condivisi, un po' alla volta.",
'admin.contribute.prompt.openRegistration':
'La registrazione è aperta su questa installazione, quindi chiunque abbia un account può scrivere dei dettagli. Ogni valore viene controllato prima della pubblicazione.',
'admin.contribute.prompt.footnote': "Decidi tu per l'intera installazione. I tuoi utenti non vengono interpellati.",
diff --git a/shared/src/i18n/ja/admin.ts b/shared/src/i18n/ja/admin.ts
index 21de1b019..f538d4f16 100644
--- a/shared/src/i18n/ja/admin.ts
+++ b/shared/src/i18n/ja/admin.ts
@@ -1080,6 +1080,7 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Google などのプロバイダが入力した詳細',
'admin.contribute.prompt.how':
'ユーザー自身が入力した内容だけ、しかもインデックスが把握している場所に限って送ります。ユーザー、旅行、アカウントの情報は一切付きません。ログにはすべての送信が表示され、項目のオフや全件の撤回もいつでも可能です。',
+ 'admin.contribute.prompt.past': 'TREK 5.1 以降にユーザーが入力した情報も、少しずつ共有されます。',
'admin.contribute.prompt.openRegistration':
'このインストールは登録が開放されているため、アカウントがあれば誰でも詳細を入力できます。すべての値は公開前に確認されます。',
'admin.contribute.prompt.footnote': 'この設定はインストール全体で管理者が決めます。ユーザーには尋ねません。',
diff --git a/shared/src/i18n/ko/admin.ts b/shared/src/i18n/ko/admin.ts
index 7239950e8..790791814 100644
--- a/shared/src/i18n/ko/admin.ts
+++ b/shared/src/i18n/ko/admin.ts
@@ -1069,6 +1069,7 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Google이나 다른 제공자가 채운 정보',
'admin.contribute.prompt.how':
'사용자가 직접 입력한 내용만, 그리고 색인이 아는 장소에 대해서만 전송됩니다. 사용자, 여행, 계정 정보는 함께 가지 않습니다. 로그에 모든 전송이 표시되며, 필드를 끄거나 모두 철회하는 것은 언제든 가능합니다.',
+ 'admin.contribute.prompt.past': 'TREK 5.1 이후 사용자가 입력한 정보도 조금씩 공유됩니다.',
'admin.contribute.prompt.openRegistration':
'이 설치는 가입이 열려 있어 계정이 있는 누구나 정보를 입력할 수 있습니다. 모든 값은 게시 전에 확인됩니다.',
'admin.contribute.prompt.footnote': '이 결정은 설치 전체에 적용됩니다. 사용자에게는 묻지 않습니다.',
diff --git a/shared/src/i18n/nl/admin.ts b/shared/src/i18n/nl/admin.ts
index 0f419a85d..1417ba91d 100644
--- a/shared/src/i18n/nl/admin.ts
+++ b/shared/src/i18n/nl/admin.ts
@@ -1143,6 +1143,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Details die door Google of een andere aanbieder zijn ingevuld',
'admin.contribute.prompt.how':
'Alleen wat je gebruikers zelf hebben ingevuld, en alleen voor plaatsen die de index kent. Er gaat geen gebruiker, reis of account mee. Het logboek toont elke verzending, en je kunt velden uitzetten of alles op elk moment intrekken.',
+ 'admin.contribute.prompt.past':
+ 'Gegevens die je gebruikers sinds TREK 5.1 hebben ingevoerd, worden ook gedeeld, stukje bij beetje.',
'admin.contribute.prompt.openRegistration':
'De registratie staat open op deze installatie, dus iedereen met een account kan details invullen. Elke waarde wordt gecontroleerd voordat ze wordt gepubliceerd.',
'admin.contribute.prompt.footnote': 'Je beslist dit voor de hele installatie. Je gebruikers worden niet gevraagd.',
diff --git a/shared/src/i18n/pl/admin.ts b/shared/src/i18n/pl/admin.ts
index 9a54aedfc..af7ad9c6a 100644
--- a/shared/src/i18n/pl/admin.ts
+++ b/shared/src/i18n/pl/admin.ts
@@ -1187,6 +1187,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Dane uzupełnione przez Google lub innego dostawcę',
'admin.contribute.prompt.how':
'Tylko to, co wpisali sami Twoi użytkownicy, i tylko dla miejsc znanych indeksowi. Nie idzie z tym żaden użytkownik, podróż ani konto. Dziennik pokazuje każde przesłanie, a pola możesz wyłączyć lub wycofać wszystko w dowolnej chwili.',
+ 'admin.contribute.prompt.past':
+ 'Szczegóły wpisane przez użytkowników od TREK 5.1 też zostaną udostępnione, stopniowo.',
'admin.contribute.prompt.openRegistration':
'Rejestracja w tej instalacji jest otwarta, więc każdy, kto ma konto, może wpisywać dane. Każda wartość jest sprawdzana przed publikacją.',
'admin.contribute.prompt.footnote': 'Decydujesz o tym dla całej instalacji. Twoi użytkownicy nie są pytani.',
diff --git a/shared/src/i18n/ru/admin.ts b/shared/src/i18n/ru/admin.ts
index e65568ca2..6edcee7cd 100644
--- a/shared/src/i18n/ru/admin.ts
+++ b/shared/src/i18n/ru/admin.ts
@@ -1177,6 +1177,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Данные, заполненные Google или другим провайдером',
'admin.contribute.prompt.how':
'Только то, что ваши пользователи ввели сами, и только для мест, известных индексу. Никакой пользователь, поездка или учётная запись не передаётся. Журнал показывает каждую отправку, а поля можно отключить или отозвать всё в любой момент.',
+ 'admin.contribute.prompt.past':
+ 'Сведения, которые ваши пользователи ввели начиная с TREK 5.1, тоже передаются, понемногу.',
'admin.contribute.prompt.openRegistration':
'На этой установке открыта регистрация, поэтому детали может вводить любой, у кого есть учётная запись. Каждое значение проверяется до публикации.',
'admin.contribute.prompt.footnote': 'Вы решаете это для всей установки. Ваших пользователей об этом не спрашивают.',
diff --git a/shared/src/i18n/sk/admin.ts b/shared/src/i18n/sk/admin.ts
index 610699237..e43da8791 100644
--- a/shared/src/i18n/sk/admin.ts
+++ b/shared/src/i18n/sk/admin.ts
@@ -1150,6 +1150,7 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Údaje doplnené službou Google alebo iným poskytovateľom',
'admin.contribute.prompt.how':
'Len to, čo vaši používatelia napísali sami, a len pre miesta, ktoré index pozná. Nikto z používateľov, žiadna cesta ani účet sa neodovzdáva. Záznam ukazuje každé odoslanie a polia môžete kedykoľvek vypnúť alebo môžete všetko stiahnuť.',
+ 'admin.contribute.prompt.past': 'Údaje, ktoré vaši používatelia zadali od TREK 5.1, sa zdieľajú tiež, postupne.',
'admin.contribute.prompt.openRegistration':
'Registrácia je v tejto inštalácii otvorená, takže údaje môže zadať ktokoľvek s účtom. Každá hodnota sa pred zverejnením kontroluje.',
'admin.contribute.prompt.footnote': 'O tom rozhodujete za celú inštaláciu. Vaši používatelia sa nepýtajú.',
diff --git a/shared/src/i18n/sv/admin.ts b/shared/src/i18n/sv/admin.ts
index 7ccd79ecc..dda5932e3 100644
--- a/shared/src/i18n/sv/admin.ts
+++ b/shared/src/i18n/sv/admin.ts
@@ -1134,6 +1134,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Uppgifter som fyllts i av Google eller en annan leverantör',
'admin.contribute.prompt.how':
'Bara det dina användare skrivit själva, och bara för platser som indexet känner till. Ingen användare, resa eller konto följer med. Loggen visar varje överföring, och du kan stänga av fält eller återkalla allt när som helst.',
+ 'admin.contribute.prompt.past':
+ 'Uppgifter som dina användare har skrivit in sedan TREK 5.1 delas också, lite i taget.',
'admin.contribute.prompt.openRegistration':
'Registreringen är öppen på den här installationen, så alla med ett konto kan skriva in uppgifter. Varje värde kontrolleras innan det publiceras.',
'admin.contribute.prompt.footnote': 'Det här bestämmer du för hela installationen. Dina användare tillfrågas inte.',
diff --git a/shared/src/i18n/th/admin.ts b/shared/src/i18n/th/admin.ts
index ad7d36cd9..56f7389c6 100644
--- a/shared/src/i18n/th/admin.ts
+++ b/shared/src/i18n/th/admin.ts
@@ -1076,6 +1076,7 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'รายละเอียดที่ Google หรือผู้ให้บริการรายอื่นกรอกไว้',
'admin.contribute.prompt.how':
'เฉพาะสิ่งที่ผู้ใช้ของคุณพิมพ์เอง และเฉพาะสถานที่ที่ดัชนีรู้จัก จะไม่มีผู้ใช้ ทริป หรือบัญชีติดไปด้วย บันทึกแสดงทุกการส่งข้อมูล และคุณปิดบางช่องหรือถอนทั้งหมดได้ทุกเมื่อ',
+ 'admin.contribute.prompt.past': 'รายละเอียดที่ผู้ใช้ของคุณพิมพ์ไว้ตั้งแต่ TREK 5.1 จะถูกแบ่งปันด้วย ทีละน้อย',
'admin.contribute.prompt.openRegistration':
'การติดตั้งนี้เปิดให้ลงทะเบียน ใครก็ตามที่มีบัญชีจึงพิมพ์รายละเอียดได้ ทุกค่าจะถูกตรวจสอบก่อนเผยแพร่',
'admin.contribute.prompt.footnote': 'คุณเป็นผู้ตัดสินใจเรื่องนี้ให้ทั้งการติดตั้ง ผู้ใช้ของคุณจะไม่ถูกถาม',
diff --git a/shared/src/i18n/tr/admin.ts b/shared/src/i18n/tr/admin.ts
index e7325a899..2f8132997 100644
--- a/shared/src/i18n/tr/admin.ts
+++ b/shared/src/i18n/tr/admin.ts
@@ -1143,6 +1143,7 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Google veya başka bir sağlayıcının doldurduğu ayrıntılar',
'admin.contribute.prompt.how':
'Yalnızca kullanıcılarınızın kendi yazdıkları ve yalnızca dizinin tanıdığı yerler için. Hiçbir kullanıcı, gezi veya hesap bununla gitmez. Günlük her aktarımı gösterir; alanları kapatabilir veya her şeyi istediğiniz zaman geri çekebilirsiniz.',
+ 'admin.contribute.prompt.past': "Kullanıcılarınızın TREK 5.1'den beri girdiği bilgiler de azar azar paylaşılır.",
'admin.contribute.prompt.openRegistration':
'Bu kurulumda kayıt açık, yani hesabı olan herkes ayrıntı yazabilir. Her değer yayımlanmadan önce kontrol edilir.',
'admin.contribute.prompt.footnote': 'Buna tüm kurulum için siz karar verirsiniz. Kullanıcılarınıza sorulmaz.',
diff --git a/shared/src/i18n/uk/admin.ts b/shared/src/i18n/uk/admin.ts
index 05f67532f..6e43f4bb3 100644
--- a/shared/src/i18n/uk/admin.ts
+++ b/shared/src/i18n/uk/admin.ts
@@ -1174,6 +1174,8 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Дані, заповнені Google або іншим провайдером',
'admin.contribute.prompt.how':
'Лише те, що ваші користувачі ввели самі, і лише для місць, відомих індексу. Жоден користувач, поїздка чи обліковий запис не передається. Журнал показує кожне надсилання, а поля можна вимкнути або відкликати все в будь-який момент.',
+ 'admin.contribute.prompt.past':
+ 'Відомості, які ваші користувачі ввели починаючи з TREK 5.1, теж передаються, поступово.',
'admin.contribute.prompt.openRegistration':
'На цій інсталяції відкрита реєстрація, тож деталі може вводити кожен, хто має обліковий запис. Кожне значення перевіряється перед публікацією.',
'admin.contribute.prompt.footnote': 'Ви вирішуєте це для всієї інсталяції. Ваших користувачів про це не питають.',
diff --git a/shared/src/i18n/vi/admin.ts b/shared/src/i18n/vi/admin.ts
index c26bf2228..02646db9f 100644
--- a/shared/src/i18n/vi/admin.ts
+++ b/shared/src/i18n/vi/admin.ts
@@ -1119,6 +1119,7 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': 'Chi tiết do Google hoặc nhà cung cấp khác điền',
'admin.contribute.prompt.how':
'Chỉ những gì người dùng của bạn tự nhập, và chỉ cho các địa điểm mà chỉ mục biết. Không có người dùng, chuyến đi hay tài khoản nào đi kèm. Nhật ký cho thấy mọi lần truyền, và bạn có thể tắt từng trường hoặc rút lại tất cả bất cứ lúc nào.',
+ 'admin.contribute.prompt.past': 'Các thông tin người dùng của bạn đã nhập từ TREK 5.1 cũng được chia sẻ, dần dần.',
'admin.contribute.prompt.openRegistration':
'Bản cài đặt này đang mở đăng ký, nên bất kỳ ai có tài khoản đều có thể nhập chi tiết. Mọi giá trị đều được kiểm tra trước khi xuất bản.',
'admin.contribute.prompt.footnote':
diff --git a/shared/src/i18n/zh-TW/admin.ts b/shared/src/i18n/zh-TW/admin.ts
index 5e6ecf1ac..a7274d72f 100644
--- a/shared/src/i18n/zh-TW/admin.ts
+++ b/shared/src/i18n/zh-TW/admin.ts
@@ -1023,6 +1023,7 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': '由 Google 或其他提供者填寫的詳情',
'admin.contribute.prompt.how':
'只分享你的使用者親自填寫的內容,而且僅限索引已收錄的地點。不會附帶任何使用者、行程或帳號。記錄會顯示每一次傳輸,你可以隨時關閉欄位或撤回全部內容。',
+ 'admin.contribute.prompt.past': '使用者自 TREK 5.1 起填寫的資訊也會逐步分享。',
'admin.contribute.prompt.openRegistration':
'此安裝已開放註冊,因此任何有帳號的人都可以填寫詳情。每個值在發布前都會經過檢查。',
'admin.contribute.prompt.footnote': '這由你為整個安裝決定。不會詢問你的使用者。',
diff --git a/shared/src/i18n/zh/admin.ts b/shared/src/i18n/zh/admin.ts
index 17aed608d..ee22251ff 100644
--- a/shared/src/i18n/zh/admin.ts
+++ b/shared/src/i18n/zh/admin.ts
@@ -1022,6 +1022,7 @@ const admin: TranslationStrings = {
'admin.contribute.never.providers': '由 Google 或其他提供方填写的详情',
'admin.contribute.prompt.how':
'只分享你的用户亲自填写的内容,而且仅限索引已收录的地点。不会附带任何用户、行程或账号。日志会显示每一次传输,你可以随时关闭字段或撤回全部内容。',
+ 'admin.contribute.prompt.past': '用户自 TREK 5.1 起填写的信息也会逐步共享。',
'admin.contribute.prompt.openRegistration':
'此安装已开放注册,因此任何有账号的人都可以填写详情。每个值在发布前都会经过检查。',
'admin.contribute.prompt.footnote': '这由你为整个安装决定。不会询问你的用户。',
diff --git a/shared/src/place/place-contrib.schema.ts b/shared/src/place/place-contrib.schema.ts
index 8dd4e2f3b..cf5c2257f 100644
--- a/shared/src/place/place-contrib.schema.ts
+++ b/shared/src/place/place-contrib.schema.ts
@@ -108,6 +108,12 @@ export const placeContribConsentSchema = z.object({
decision: z.enum(['agreed', 'declined', 'off']).nullable(),
decidedBy: z.number().int().positive().nullable(),
decidedAt: z.string().nullable(),
+ /**
+ * The agreement was given in a prompt that said what users typed before it
+ * is shared as well (from TREK 5.1.1 on); only then does a field switched on
+ * later catch up too. Absent on an agreement from 5.1.0.
+ */
+ includesEarlier: z.boolean().optional(),
});
export type PlaceContribConsent = z.infer<typeof placeContribConsentSchema>;