feat(tours): let a background check hint at changes of your own wanderer trails

Settings, Integrations, wanderer gains an optional background check of the
trails you imported, off until you switch it on. While on, TREK reads the
short record of each such trail at most once a day (never its GPX file) and
leaves a hint when the trail may have moved on: "may have changed" when only
wanderer's change time moved, "changed" when its name or description proves
it, and "not checkable" when the trail is gone, no longer yours or carries no
change time. Nothing is ever said to be unchanged. A new hint arrives as a
notification that opens the tour (a new ?place= link in the planner); the
tour's provenance shows it with the source check right beside it, and the
card lists all open hints in a dialog, each leading to its tour. The check
reads the source in full as before and spends the hint; taking a change in
stays the confirmed reimport. No tour is ever changed or deleted.

The check only asks through your own connection, only about trails your
account imported into trips you can still open, and stops when you switch it
off, remove the connection, wanderer refuses the token (until a test passes
or a new token is saved) or the admin switches wanderer off; hints and
snapshots stay. A run asks at most 25 connections for at most 10 records
each, one after another, and an instance that fails (an outage, a rate
limit) is left alone for an hour, doubling up to two days.

Server: migration 046120 adds the switch and the run bookkeeping to
wanderer_connections and the tour_source_hints table (one row per snapshot,
for its importer, gone with it). WandererWatchService and an hourly
wanderer-watch job on the CronRegistrar live in the tours domain and read
through WandererService; GET and PUT /api/integrations/wanderer/watch and GET
/api/trips/:tripId/tours/wanderer/sources/:placeId/hint (place_edit, like the
check) answer with @trek/shared contracts. A new user notification event,
wanderer_source_hint, can be muted per channel. Saving a new token now clears
what the last check said about the old one. There is no MCP tool, as for the
rest of the personal wanderer connection. All 27 locales carry the strings,
and the admin wiki page says what the check does.
This commit is contained in:
Maurice
2026-10-20 14:40:50 +02:00
parent aacc7f2c8d
commit 2e1dca9fe9
202 changed files with 4791 additions and 57 deletions
@@ -0,0 +1,53 @@
import { EntityRepositoryType, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { TourSourceHintsRepository } from '../repositories/TourSourceHints.repository';
import { TourSources } from './TourSources.entity';
import { Users } from './Users.entity';
export class TourSourceHints {
[EntityRepositoryType]?: TourSourceHintsRepository;
[PrimaryKeyProp]?: 'place';
place?: Ref<TourSources> | null;
place_id?: number | null;
user!: Ref<Users>;
user_id!: number;
state?: TTourSourceHintsState | null;
changes?: string | null;
reason?: TTourSourceHintsReason | null;
external_updated?: string | null;
seen_hash?: string | null;
seen_updated?: string | null;
checked_at?: string | null;
}
export const TourSourceHintsState = {
POSSIBLE_CHANGE: 'possible_change',
CHANGED: 'changed',
UNVERIFIABLE: 'unverifiable',
} as const;
export type TTourSourceHintsState = (typeof TourSourceHintsState)[keyof typeof TourSourceHintsState];
export const TourSourceHintsReason = {
UNAVAILABLE: 'unavailable',
NO_CHANGE_TIME: 'no_change_time',
} as const;
export type TTourSourceHintsReason = (typeof TourSourceHintsReason)[keyof typeof TourSourceHintsReason];
export const TourSourceHintsSchema = defineEntity({
class: TourSourceHints,
repository: () => TourSourceHintsRepository,
properties: {
place: () => p.oneToOne(TourSources).primary().ref().name('place_id').deleteRule('cascade').nullable().hidden(),
place_id: p.integer().nullable().persist(false),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_tour_source_hints_user_id'),
user_id: p.integer().persist(false).index('idx_tour_source_hints_user_id'),
state: p.enum(() => TourSourceHintsState).nullable(),
changes: p.text().nullable(),
reason: p.enum(() => TourSourceHintsReason).nullable(),
external_updated: p.text().nullable(),
seen_hash: p.text().nullable(),
seen_updated: p.text().nullable(),
checked_at: p.text().nullable(),
},
});
@@ -1,5 +1,6 @@
import { EntityRepositoryType, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { TourSourcesRepository } from '../repositories/TourSources.repository';
import { TourSourceHints } from './TourSourceHints.entity';
import { DbTimestampType } from '../types';
import { Tours } from './Tours.entity';
import { Users } from './Users.entity';
@@ -19,6 +20,7 @@ export class TourSources {
imported_at?: string | null;
imported_by?: number | null;
importedByRef?: Ref<Users> | null;
tour_source_hints: Ref<TourSourceHints> | null = null;
}
export const TourSourcesSchema = defineEntity({
@@ -43,5 +45,6 @@ export const TourSourcesSchema = defineEntity({
imported_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
imported_by: p.integer().nullable().persist(false).index('idx_tour_sources_imported_by'),
importedByRef: () => p.manyToOne(Users).ref().joinColumn('imported_by').nullable().hidden().index('idx_tour_sources_imported_by'),
tour_source_hints: () => p.oneToOne(TourSourceHints).ref().mappedBy('place').hidden(),
},
});
+3
View File
@@ -55,6 +55,7 @@ import { TodoItems } from './TodoItems.entity';
import { TourActivities } from './TourActivities.entity';
import { TourActivityExclusions } from './TourActivityExclusions.entity';
import { TourPackingLinks } from './TourPackingLinks.entity';
import { TourSourceHints } from './TourSourceHints.entity';
import { TourSources } from './TourSources.entity';
import { TrekPhotos } from './TrekPhotos.entity';
import { TripAlbumLinks } from './TripAlbumLinks.entity';
@@ -186,6 +187,7 @@ export class Users {
tour_activities_collection = new Collection<TourActivities>(this);
tour_activity_exclusions_collection = new Collection<TourActivityExclusions>(this);
tour_packing_links_collection = new Collection<TourPackingLinks>(this);
tour_source_hints_collection = new Collection<TourSourceHints>(this);
tour_sources_collection = new Collection<TourSources>(this);
trek_photos_collection = new Collection<TrekPhotos>(this);
trip_album_links_collection = new Collection<TripAlbumLinks>(this);
@@ -335,6 +337,7 @@ export const UsersSchema = defineEntity({
tour_activities_collection: () => p.oneToMany(TourActivities).mappedBy('assignedByRef').hidden(),
tour_activity_exclusions_collection: () => p.oneToMany(TourActivityExclusions).mappedBy('user').hidden(),
tour_packing_links_collection: () => p.oneToMany(TourPackingLinks).mappedBy('linkedByRef').hidden(),
tour_source_hints_collection: () => p.oneToMany(TourSourceHints).mappedBy('user').hidden(),
tour_sources_collection: () => p.oneToMany(TourSources).mappedBy('importedByRef').hidden(),
trek_photos_collection: () => p.oneToMany(TrekPhotos).mappedBy('owner').hidden(),
trip_album_links_collection: () => p.oneToMany(TripAlbumLinks).mappedBy('user').hidden(),
@@ -16,6 +16,10 @@ export class WandererConnections {
last_check_error?: string | null;
created_at?: string | null;
updated_at?: string | null;
watch_enabled: number & Opt = 0;
watch_last_run_at?: string | null;
watch_failures: number & Opt = 0;
watch_paused_until?: string | null;
}
export const WandererConnectionsSchema = defineEntity({
@@ -32,5 +36,9 @@ export const WandererConnectionsSchema = defineEntity({
last_check_error: p.text().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
watch_enabled: p.integer().default(0),
watch_last_run_at: p.text().nullable(),
watch_failures: p.integer().default(0),
watch_paused_until: p.text().nullable(),
},
});
+2
View File
@@ -113,6 +113,7 @@ import { TourActivityExclusionsSchema } from './TourActivityExclusions.entity';
import { TourChangeStepsSchema } from './TourChangeSteps.entity';
import { TourObstacleReviewsSchema } from './TourObstacleReviews.entity';
import { TourPackingLinksSchema } from './TourPackingLinks.entity';
import { TourSourceHintsSchema } from './TourSourceHints.entity';
import { TourSourcesSchema } from './TourSources.entity';
import { TourStationVisitsSchema } from './TourStationVisits.entity';
import { TourTypesSchema } from './TourTypes.entity';
@@ -263,6 +264,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
TourChangeStepsSchema,
TourObstacleReviewsSchema,
TourPackingLinksSchema,
TourSourceHintsSchema,
TourSourcesSchema,
TourStationVisitsSchema,
TourTypesSchema,
+13
View File
@@ -10,6 +10,7 @@ import {
paddleRegionGraphStatsSchema,
tourChangeSchema,
tourFixedLegSchema,
tourSourceHintChangeSchema,
tourWaypointSchema,
trackMarksSchema,
type Ferrata,
@@ -22,6 +23,7 @@ import {
type PaddleRegionGraphStats,
type TourChange,
type TourFixedLeg,
type TourSourceHintChange,
type TourWaypoint,
type TrackMarks,
} from '@trek/shared';
@@ -278,3 +280,14 @@ export const COLLECTION_TOUR_WAYPOINTS: JsonColumn<TourWaypoint[]> = {
schema: z.array(tourWaypointSchema),
fallback: () => [],
};
/**
* WAN-02: the parts of a trail the background watch found proven changed in
* its record, for one snapshot's hint. A broken row names none; the hint's
* state still says that something changed.
*/
export const TOUR_SOURCE_HINT_CHANGES: JsonColumn<TourSourceHintChange[]> = {
column: 'tour_source_hints.changes',
schema: z.array(tourSourceHintChangeSchema),
fallback: () => [],
};
@@ -0,0 +1,15 @@
// 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 TourSourceHintsTable {
place_id: InsertOptional<number>;
user_id: number;
state: InsertOptional<string | null>;
changes: InsertOptional<string | null>;
reason: InsertOptional<string | null>;
external_updated: InsertOptional<string | null>;
seen_hash: InsertOptional<string | null>;
seen_updated: InsertOptional<string | null>;
checked_at: InsertOptional<string | null>;
}
@@ -12,4 +12,8 @@ export interface WandererConnectionsTable {
last_check_error: InsertOptional<string | null>;
created_at: InsertOptional<string | null>;
updated_at: InsertOptional<string | null>;
watch_enabled: InsertOptional<number>;
watch_last_run_at: InsertOptional<string | null>;
watch_failures: InsertOptional<number>;
watch_paused_until: InsertOptional<string | null>;
}
+2
View File
@@ -119,6 +119,7 @@ import type { TourActivityExclusionsTable } from './TourActivityExclusions.table
import type { TourChangeStepsTable } from './TourChangeSteps.table';
import type { TourObstacleReviewsTable } from './TourObstacleReviews.table';
import type { TourPackingLinksTable } from './TourPackingLinks.table';
import type { TourSourceHintsTable } from './TourSourceHints.table';
import type { TourSourcesTable } from './TourSources.table';
import type { TourStationVisitsTable } from './TourStationVisits.table';
import type { TourTypesTable } from './TourTypes.table';
@@ -275,6 +276,7 @@ export interface DB {
tour_change_steps: TourChangeStepsTable;
tour_obstacle_reviews: TourObstacleReviewsTable;
tour_packing_links: TourPackingLinksTable;
tour_source_hints: TourSourceHintsTable;
tour_sources: TourSourcesTable;
tour_station_visits: TourStationVisitsTable;
tour_types: TourTypesTable;
@@ -0,0 +1,43 @@
import { Migration } from '@mikro-orm/migrations';
/**
* WAN-02: a user may let TREK look now and then whether the wanderer trails
* they imported moved on since.
*
* `wanderer_connections` gets the switch, off for every existing connection,
* and what the background look needs to stay polite: when it last ran, how
* many runs in a row failed and until when it waits before it asks the
* instance again.
*
* `tour_source_hints` holds what a look found about one snapshot's source, for
* the user who imported it: the state (NULL while there is nothing to say,
* which is never a claim that nothing changed), the parts the trail's record
* proves changed, the reason a source could not be judged, the change time
* the trail said at the look, and what the user last saw of the trail in a
* manual check, which later looks compare against instead of the import. A
* hint never touches the tour; it goes with its snapshot and with its user.
*/
export class Migration20200101046120_a_wanderer_connection_can_watch_its_sources extends Migration {
override name = 'Migration20200101046120_a_wanderer_connection_can_watch_its_sources';
override up(): void {
this.addSql('ALTER TABLE wanderer_connections ADD COLUMN watch_enabled INTEGER NOT NULL DEFAULT 0');
this.addSql('ALTER TABLE wanderer_connections ADD COLUMN watch_last_run_at TEXT');
this.addSql('ALTER TABLE wanderer_connections ADD COLUMN watch_failures INTEGER NOT NULL DEFAULT 0');
this.addSql('ALTER TABLE wanderer_connections ADD COLUMN watch_paused_until TEXT');
this.addSql(`
CREATE TABLE IF NOT EXISTS tour_source_hints (
place_id INTEGER PRIMARY KEY REFERENCES tour_sources(place_id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
state TEXT CHECK (state IS NULL OR state IN ('possible_change', 'changed', 'unverifiable')),
changes TEXT,
reason TEXT CHECK (reason IS NULL OR reason IN ('unavailable', 'no_change_time')),
external_updated TEXT,
seen_hash TEXT,
seen_updated TEXT,
checked_at TEXT
)
`);
this.addSql('CREATE INDEX IF NOT EXISTS idx_tour_source_hints_user_id ON tour_source_hints(user_id)');
}
}
@@ -0,0 +1,210 @@
import type {
TourSourceHints,
TTourSourceHintsReason,
TTourSourceHintsState,
} from '../entities/TourSourceHints.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
type HintsDB = Pick<
DB,
'tour_source_hints' | 'tour_sources' | 'places' | 'trips' | 'trip_members' | 'wanderer_connections'
>;
const PROVIDER = 'wanderer';
/** A snapshot the watch may look at, with what was last seen of its source. */
export interface WatchedSourceRow {
place_id: number;
external_id: string;
/** The content as the import delivered it, `name.description.route`. */
content_hash: string;
/** The trail's change time at the import. */
external_updated: string | null;
/** The content and change time the user last saw in a manual check; null before one. */
seen_hash: string | null;
seen_updated: string | null;
/** What the last look found; null when it found nothing to say or never looked. */
state: TTourSourceHintsState | null;
}
/** What a look found about one source, written for the user it belongs to. */
interface TourSourceHintWrite {
place_id: number;
user_id: number;
state: TTourSourceHintsState | null;
/** The changed parts as a JSON array, null when none. */
changes: string | null;
reason: TTourSourceHintsReason | null;
external_updated: string | null;
checked_at: string;
}
export interface TourSourceHintRow {
place_id: number;
state: TTourSourceHintsState;
changes: string | null;
reason: TTourSourceHintsReason | null;
external_updated: string | null;
checked_at: string | null;
}
export interface TourSourceHintListRow extends TourSourceHintRow {
trip_id: number;
trip_title: string;
tour_name: string;
}
/**
* `tour_source_hints` (WAN-02): what the background watch over a user's own
* wanderer snapshots found, one row per snapshot, for the user who imported
* it. Nothing here reads or writes a tour; a hint goes with its snapshot and
* with its user. Only snapshots in trips the user can still open count, and a
* hint shows only while the user's connection points at the instance it came
* from, so a removed connection leaves the rows unread rather than deleted.
*/
export class TourSourceHintsRepository extends TrekRepository<TourSourceHints> {
private db() {
return this.kysely<HintsDB>();
}
/**
* The user's snapshots of one instance that are due for a look: never looked
* at, or last looked at before `checkedBefore`. Longest waiting first, at
* most `limit`, so every run stays within its budget and all get their turn.
*/
async listDue(userId: number, instance: string, checkedBefore: string, limit: number): Promise<WatchedSourceRow[]> {
return await this.db()
.selectFrom('tour_sources as s')
.innerJoin('places as p', 'p.id', 's.place_id')
.leftJoin('tour_source_hints as h', 'h.place_id', 's.place_id')
.select([
's.place_id',
's.external_id',
's.content_hash',
's.external_updated',
'h.seen_hash',
'h.seen_updated',
'h.state',
])
.where('s.provider', '=', PROVIDER)
.where('s.instance', '=', instance)
.where('s.imported_by', '=', userId)
.where('p.trip_id', 'in', this.reachableTripIds(userId))
.where((eb) => eb.or([eb('h.checked_at', 'is', null), eb('h.checked_at', '<', checkedBefore)]))
.orderBy((eb) => eb.fn.coalesce('h.checked_at', eb.val('')))
.orderBy('s.place_id')
.limit(limit)
.execute()
.then((rows) => rows.map((row) => ({ ...row, state: (row.state as TTourSourceHintsState | null) ?? null })));
}
/** Writes what one look found; what the user last saw in a manual check stays as it is. */
async record(rows: readonly TourSourceHintWrite[]): Promise<void> {
if (rows.length === 0) return;
await this.db()
.insertInto('tour_source_hints')
.values([...rows])
.onConflict((oc) =>
oc.column('place_id').doUpdateSet((eb) => ({
state: eb.ref('excluded.state'),
changes: eb.ref('excluded.changes'),
reason: eb.ref('excluded.reason'),
external_updated: eb.ref('excluded.external_updated'),
checked_at: eb.ref('excluded.checked_at'),
})),
)
.execute();
}
/**
* A manual check read the source: its answer is what the user has seen now,
* so the open hint goes and later looks compare against this. Only for the
* user who imported the snapshot; anyone else's check leaves the row alone.
*/
async markSeen(
placeId: number,
userId: number,
seen: { contentHash: string; externalUpdated: string | null; checkedAt: string },
): Promise<void> {
const source = await this.db()
.selectFrom('tour_sources')
.select('imported_by')
.where('place_id', '=', placeId)
.where('provider', '=', PROVIDER)
.executeTakeFirst();
if (!source || source.imported_by !== userId) return;
await this.db()
.insertInto('tour_source_hints')
.values({
place_id: placeId,
user_id: userId,
state: null,
changes: null,
reason: null,
external_updated: seen.externalUpdated,
seen_hash: seen.contentHash,
seen_updated: seen.externalUpdated,
checked_at: seen.checkedAt,
})
.onConflict((oc) =>
oc.column('place_id').doUpdateSet((eb) => ({
state: null,
changes: null,
reason: null,
external_updated: eb.ref('excluded.external_updated'),
seen_hash: eb.ref('excluded.seen_hash'),
seen_updated: eb.ref('excluded.seen_updated'),
checked_at: eb.ref('excluded.checked_at'),
})),
)
.execute();
}
/** The user's open hints, newest look first. */
async listOpen(userId: number): Promise<TourSourceHintListRow[]> {
return await this.openHints(userId).orderBy('h.checked_at', 'desc').orderBy('h.place_id', 'desc').execute();
}
/** The user's open hint on one snapshot of a trip; undefined when there is none. */
async findOpen(userId: number, tripId: number, placeId: number): Promise<TourSourceHintListRow | undefined> {
return await this.openHints(userId)
.where('p.trip_id', '=', tripId)
.where('h.place_id', '=', placeId)
.executeTakeFirst();
}
private openHints(userId: number) {
return this.db()
.selectFrom('tour_source_hints as h')
.innerJoin('tour_sources as s', 's.place_id', 'h.place_id')
.innerJoin('places as p', 'p.id', 'h.place_id')
.innerJoin('trips as t', 't.id', 'p.trip_id')
.innerJoin('wanderer_connections as c', 'c.user_id', 'h.user_id')
.select([
'h.place_id',
'h.state',
'h.changes',
'h.reason',
'h.external_updated',
'h.checked_at',
'p.trip_id',
't.title as trip_title',
'p.name as tour_name',
])
.where('h.user_id', '=', userId)
.where('h.state', 'is not', null)
.whereRef('c.url', '=', 's.instance')
.where('p.trip_id', 'in', this.reachableTripIds(userId))
.$narrowType<{ state: TTourSourceHintsState; reason: TTourSourceHintsReason | null }>();
}
/** The trips the user can still open: their own and those they are a member of. */
private reachableTripIds(userId: number) {
return this.db()
.selectFrom('trips')
.select('id')
.where('user_id', '=', userId)
.union(this.db().selectFrom('trip_members').select('trip_id as id').where('user_id', '=', userId));
}
}
@@ -18,6 +18,14 @@ export interface WandererConnectionRow {
last_check_error: string | null;
}
/** WAN-02: the background watch of one connection, as stored. */
interface WandererWatchRow {
watch_enabled: number;
watch_last_run_at: string | null;
watch_failures: number;
watch_paused_until: string | null;
}
/**
* `wanderer_connections`: one row per user who connected an instance, the
* user id its primary key. Only the owner's own requests read or write it.
@@ -42,8 +50,9 @@ export class WandererConnectionsRepository extends TrekRepository<WandererConnec
/**
* Write the address and the TLS choice, and the token when one is given:
* `undefined` keeps the stored token, `null` drops it. A changed address
* clears what the last check said, since it said it about another server.
* `undefined` keeps the stored token, `null` drops it. A changed address or
* a new token clears what the last check said, since it said it about
* another server or another token (a refused token stops the watch, WAN-02).
*/
async save(
userId: number,
@@ -51,7 +60,9 @@ export class WandererConnectionsRepository extends TrekRepository<WandererConnec
): Promise<void> {
const platform = this.platform();
const tokenColumns = data.token !== undefined ? { token: data.token } : {};
const checkColumns = data.hostChanged ? { last_checked_at: null, last_check_ok: null, last_check_error: null } : {};
// What the last check said was said about another server, or about another token.
const freshCredentials = data.hostChanged || (data.token !== undefined && data.token !== null);
const checkColumns = freshCredentials ? { last_checked_at: null, last_check_ok: null, last_check_error: null } : {};
await this.db()
.insertInto('wanderer_connections')
.values({
@@ -81,6 +92,54 @@ export class WandererConnectionsRepository extends TrekRepository<WandererConnec
);
}
/** WAN-02: the watch of the user's connection; undefined without a connection. */
async findWatch(userId: number): Promise<WandererWatchRow | undefined> {
return await this.db()
.selectFrom('wanderer_connections')
.select(['watch_enabled', 'watch_last_run_at', 'watch_failures', 'watch_paused_until'])
.where('user_id', '=', userId)
.executeTakeFirst();
}
/** Switches the watch on or off. Switching it on starts afresh, without the pause an earlier failure left. */
async setWatch(userId: number, enabled: boolean): Promise<void> {
await this.nativeUpdate(
{ user: userId },
enabled ? { watch_enabled: 1, watch_failures: 0, watch_paused_until: null } : { watch_enabled: 0 },
);
}
/**
* The connections the watch may ask now: switched on, holding a token
* wanderer has not refused, and not waiting out a pause. The ones that
* waited longest come first, at most `limit` of them.
*/
async listWatchable(now: string, limit: number): Promise<number[]> {
const rows = await this.db()
.selectFrom('wanderer_connections')
.select('user_id')
.where('watch_enabled', '=', 1)
.where('token', 'is not', null)
.where((eb) => eb.or([eb('last_check_error', 'is', null), eb('last_check_error', '!=', 'unauthorized')]))
.where((eb) => eb.or([eb('watch_paused_until', 'is', null), eb('watch_paused_until', '<=', now)]))
.orderBy((eb) => eb.fn.coalesce('watch_last_run_at', eb.val('')))
.orderBy('user_id')
.limit(limit)
.execute();
return rows.map((row) => row.user_id);
}
/** How a run of the watch went: when it ended, how many failed in a row and until when to wait. */
async recordWatchRun(
userId: number,
run: { lastRunAt: string; failures: number; pausedUntil: string | null },
): Promise<void> {
await this.nativeUpdate(
{ user: userId },
{ watch_last_run_at: run.lastRunAt, watch_failures: run.failures, watch_paused_until: run.pausedUntil },
);
}
async remove(userId: number): Promise<void> {
await this.nativeDelete({ user: userId });
}
@@ -42,6 +42,7 @@ export type NotifEventType =
| 'replica_failure'
| 'paddle_region_requested'
| 'synology_session_cleared'
| 'wanderer_source_hint'
| 'plugin_notification';
/** Every event, in the order the preferences UI lists them. */
@@ -60,6 +61,7 @@ export const ALL_EVENT_TYPES: NotifEventType[] = [
'replica_failure',
'paddle_region_requested',
'synology_session_cleared',
'wanderer_source_hint',
'plugin_notification',
];
@@ -228,6 +228,20 @@ const EVENT_NOTIFICATION_CONFIG: Record<string, EventNotifConfig> = {
navigateTextKey: 'notif.action.view_admin',
navigateTarget: () => '/admin?tab=addons',
},
// WAN-02: the wanderer watch found something about a snapshot's source; the
// text says which of the three it is, the button opens the tour in its trip.
wanderer_source_hint: {
inAppType: 'navigate',
titleKey: 'notif.wanderer_source_hint.title',
textKey: (p) =>
p.state === 'changed'
? 'notif.wanderer_source_hint.changed'
: p.state === 'unverifiable'
? 'notif.wanderer_source_hint.unverifiable'
: 'notif.wanderer_source_hint.possible_change',
navigateTextKey: 'notif.action.view_tour',
navigateTarget: (p) => (p.tripId && p.placeId ? `/trips/${p.tripId}?tab=plan&place=${p.placeId}` : null),
},
synology_session_cleared: {
inAppType: 'simple',
titleKey: 'notifications.synologySessionCleared.title',
@@ -35,6 +35,7 @@ const NTFY_EVENT_META: Partial<Record<NotifEventType, { priority: 1 | 2 | 3 | 4
replica_failure: { priority: 5, tags: ['warning', 'floppy_disk'] },
paddle_region_requested: { priority: 3, tags: ['canoe'] },
synology_session_cleared: { priority: 3, tags: ['warning'] },
wanderer_source_hint: { priority: 2, tags: ['hiking_boot'] },
};
const NTFY_DEFAULT_META = { priority: 3 as const, tags: [] as string[] };
@@ -0,0 +1,6 @@
/** createZodDto wrapper over the @trek/shared contract of the wanderer watch switch (WAN-02). */
import { wandererWatchRequestSchema } from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
export class WandererWatchDto extends createZodDto(wandererWatchRequestSchema) {}
@@ -9,9 +9,11 @@ import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.g
import { WandererEnabledGuard } from '../wanderer/wanderer-enabled.guard';
import { WandererImportDto, WandererSearchDto } from './dto/tours-wanderer.dto';
import { ToursWandererService } from './tours-wanderer.service';
import { WandererWatchService } from './wanderer-watch.service';
import { Body, Controller, Get, Headers, HttpCode, Param, Post, UseGuards } from '@nestjs/common';
import {
tourSourceCheckResponseSchema,
tourSourceHintResponseSchema,
wandererImportPreviewSchema,
wandererImportResponseSchema,
wandererSearchResponseSchema,
@@ -28,7 +30,10 @@ import {
@UseGuards(AddonGuard, JwtAuthGuard, WandererEnabledGuard, TripAccessGuard)
@RequireAddon(ADDON_IDS.TOURS, 'Tours')
export class ToursWandererController {
constructor(private readonly wanderer: ToursWandererService) {}
constructor(
private readonly wanderer: ToursWandererService,
private readonly watch: WandererWatchService,
) {}
@RequirePermission('place_edit')
@Post('search')
@@ -54,6 +59,17 @@ export class ToursWandererController {
return this.wanderer.checkSource(tripId, user.id, placeId);
}
/**
* WAN-02: the caller's own background hint on a wanderer snapshot, when
* their watch left one; it leads to the check above, so it asks the same right.
*/
@RequirePermission('place_edit')
@Get('sources/:placeId/hint')
@ResponseContract(tourSourceHintResponseSchema)
hint(@Param('tripId') tripId: string, @Param('placeId') placeId: string, @CurrentUser() user: User) {
return this.watch.hintFor(tripId, user.id, placeId);
}
@RequirePermission('place_edit')
@Post('import')
@ResponseContract(wandererImportResponseSchema)
@@ -13,6 +13,7 @@ import { PlacesService } from '../places/places.service';
import { WandererService } from '../wanderer/wanderer.service';
import { changedParts, computeTourMetrics, contentHashOf, localHashOf, parseRouteGeometry } from './tours.helpers';
import { ToursService } from './tours.service';
import { WandererWatchService } from './wanderer-watch.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable, Logger } from '@nestjs/common';
import type {
@@ -64,6 +65,7 @@ export class ToursWandererService {
private readonly placeImport: PlaceImportService,
private readonly places: PlacesService,
private readonly tours: ToursService,
private readonly watch: WandererWatchService,
@InjectRepository(Tours) private readonly toursRepo: ToursRepository,
@InjectRepository(Places) private readonly placesRepo: PlacesRepository,
@InjectRepository(TourSources) private readonly sources: TourSourcesRepository,
@@ -136,13 +138,15 @@ export class ToursWandererService {
* MF-03: ask the source of one wanderer snapshot whether the trail changed
* since it came in, on the caller's own connection. Reads only: the
* snapshot stays as it is whatever the source says, and taking a change
* over is the confirmed reimport, with the hash this answer carries.
* over is the confirmed reimport, with the hash this answer carries. What
* the check read is what the caller has now seen of the trail, so their
* background hint on the snapshot goes (WAN-02).
*/
async checkSource(tripId: string, userId: number, placeId: string): Promise<TourSourceCheckResponse> {
const tid = tripRowId(tripId);
const pid = toRowId(placeId);
const row = pid === null ? undefined : await this.toursRepo.findProvenance(tid, pid);
if (!row) throw new DomainError(404, 'Tour not found');
if (!row || pid === null) throw new DomainError(404, 'Tour not found');
if (row.origin !== 'wanderer') {
throw new DomainError(400, 'This tour has no wanderer source', {
code: 'wanderer_no_source',
@@ -177,6 +181,7 @@ export class ToursWandererService {
}
const reimport = { trailId: externalId, contentHash: fetched.contentHash };
const externalUpdated = fetched.trail.updated ?? null;
await this.watch.noteSeen(pid, userId, { contentHash: fetched.contentHash, externalUpdated });
if (row.source_content_hash === null) return { ...answer('unknown'), externalUpdated, reimport };
const changes = changedParts(row.source_content_hash, fetched.contentHash);
return changes.length === 0
+17
View File
@@ -70,6 +70,23 @@ export function changedParts(before: string, now: string): Array<(typeof CONTENT
return CONTENT_PARTS.filter((_, i) => a[i] !== b[i]);
}
/**
* WAN-02: the parts of a content fingerprint a trail's record alone proves
* changed. The record carries the name and the description, never the line,
* so a changed route is never claimed here.
*/
export function recordChangedParts(
contentHash: string,
name: string,
description: string | null,
): Array<'name' | 'description'> {
const [nameHash, descriptionHash] = contentHash.split('.');
return [
...(fingerprint(name.trim()) === nameHash ? [] : (['name'] as const)),
...(fingerprint((description ?? '').trim()) === descriptionHash ? [] : (['description'] as const)),
];
}
/**
* At most `most` points of a line, evenly spread along it with its ends kept:
* a preview or a search gets the whole shape without the thousands of points.
+17 -1
View File
@@ -5,6 +5,7 @@ import { TourActivityExclusions } from '../../db/entities/TourActivityExclusions
import { TourChangeSteps } from '../../db/entities/TourChangeSteps.entity';
import { TourObstacleReviews } from '../../db/entities/TourObstacleReviews.entity';
import { TourPackingLinks } from '../../db/entities/TourPackingLinks.entity';
import { TourSourceHints } from '../../db/entities/TourSourceHints.entity';
import { TourSources } from '../../db/entities/TourSources.entity';
import { TourStationVisits } from '../../db/entities/TourStationVisits.entity';
import { TourTypes } from '../../db/entities/TourTypes.entity';
@@ -15,6 +16,7 @@ import { AssignmentsDomainModule } from '../assignments/assignments-domain.modul
import { CollectionsModule } from '../collections/collections.module';
import { MapsModule } from '../maps/maps.module';
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
import { NotificationsModule } from '../notifications/notifications.module';
import { OverpassModule } from '../overpass/overpass.module';
import { PackingModule } from '../packing/packing.module';
import { PaddleObstaclesModule } from '../paddle-obstacles/paddle-obstacles.module';
@@ -22,6 +24,7 @@ import { PermissionsModule } from '../permissions/permissions.module';
import { PlaceImportModule } from '../place-import/place-import.module';
import { PlacesModule } from '../places/places.module';
import { RoadtripModule } from '../roadtrip/roadtrip.module';
import { SchedulingModule } from '../scheduling/scheduling.module';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
import { WandererModule } from '../wanderer/wanderer.module';
import { CityWalkBriefingService } from './city-walk-briefing.service';
@@ -71,6 +74,9 @@ import { ToursWandererService } from './tours-wanderer.service';
import { ToursController } from './tours.controller';
import { ToursMcp } from './tours.mcp';
import { ToursService } from './tours.service';
import { WandererWatchController } from './wanderer-watch.controller';
import { WandererWatchJob } from './wanderer-watch.job';
import { WandererWatchService } from './wanderer-watch.service';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module } from '@nestjs/common';
@@ -97,7 +103,10 @@ import { Module } from '@nestjs/common';
* collection (LIB-03) are this domain's own rows; the collection's roles and
* its live notice to its members come from CollectionsService. A tour points at
* the packing list of its trip (P2D-XD-01) through a row of its own; the list
* and who sees which of its items stay PackingService's.
* and who sees which of its items stay PackingService's. The optional watch
* over a user's own wanderer snapshots (WAN-02) reads through WandererService,
* keeps its hints in this domain's own rows, tells the user through
* NotificationsService and runs hourly on SchedulingModule's registrar.
*/
@Module({
imports: [
@@ -125,12 +134,16 @@ import { Module } from '@nestjs/common';
CollectionsModule,
// A tour's packing link is read against the items Packing lets the user see (P2D-XD-01).
PackingModule,
// The wanderer watch tells the user of a new hint (WAN-02) and runs as a cron.
NotificationsModule,
SchedulingModule,
MikroOrmModule.forFeature([
CollectionTours,
Tours,
TourTypes,
TourWaypoints,
TourSources,
TourSourceHints,
TourObstacleReviews,
TourPackingLinks,
TourStationVisits,
@@ -158,6 +171,7 @@ import { Module } from '@nestjs/common';
TourLibraryController,
CollectionToursController,
TourPackingLinkController,
WandererWatchController,
],
providers: [
ToursService,
@@ -183,6 +197,8 @@ import { Module } from '@nestjs/common';
TourActivityStatsService,
CollectionToursService,
TourPackingLinkService,
WandererWatchService,
WandererWatchJob,
ToursMcp,
TourLibraryMcp,
TourWalkImportMcp,
@@ -0,0 +1,40 @@
import { ADDON_IDS } from '../../addons';
import type { User } from '../../types';
import { AddonGuard } from '../addons/addon.guard';
import { RequireAddon } from '../addons/require-addon.decorator';
import { getClientIp } from '../audit/client-ip';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { WandererEnabledGuard } from '../wanderer/wanderer-enabled.guard';
import { WandererWatchDto } from './dto/wanderer-watch.dto';
import { WandererWatchService } from './wanderer-watch.service';
import { Body, Controller, Get, Put, Req, UseGuards } from '@nestjs/common';
import { wandererWatchSchema } from '@trek/shared';
import type { Request } from 'express';
/**
* `/api/integrations/wanderer/watch` (WAN-02): the optional background watch
* over the caller's own wanderer snapshots, beside the connection it runs on.
* It reads and switches only the caller's own watch, and lists only the
* caller's own hints.
*/
@Controller('api/integrations/wanderer/watch')
@UseGuards(AddonGuard, JwtAuthGuard, WandererEnabledGuard)
@RequireAddon(ADDON_IDS.TOURS, 'Tours')
export class WandererWatchController {
constructor(private readonly watch: WandererWatchService) {}
@Get()
@ResponseContract(wandererWatchSchema)
status(@CurrentUser() user: User) {
return this.watch.status(user.id);
}
@Put()
@ResponseContract(wandererWatchSchema)
setEnabled(@CurrentUser() user: User, @Body() body: WandererWatchDto, @Req() req: Request) {
return this.watch.setEnabled(user.id, body.enabled, getClientIp(req));
}
}
@@ -0,0 +1,74 @@
import type { WatchedSourceRow } from '../../db/repositories/TourSourceHints.repository';
import type { WandererTrailLook } from '../wanderer/wanderer.service';
import { recordChangedParts } from './tours.helpers';
import type { TourSourceHintChange, TourSourceHintReason, TourSourceHintState } from '@trek/shared';
/**
* WAN-02: the pure half of the background watch over a user's own wanderer
* snapshots: its budget and what a look at a trail's record says.
*
* The budget keeps a home instance unbothered. A run asks at most
* {@link WATCH_CONNECTIONS_PER_RUN} connections, each for at most
* {@link WATCH_SOURCES_PER_RUN} trail records one after another (plus the two
* small reads that name the account's own authors), and a source is looked at
* again no sooner than {@link WATCH_RECHECK_MS} later. A failing instance is
* left alone for longer after each failure in a row, up to
* {@link WATCH_BACKOFF_MAX_MS}; a rate limit or an outage is such a failure.
* Every read keeps the client's timeout and size cap.
*/
export const WATCH_CONNECTIONS_PER_RUN = 25;
export const WATCH_SOURCES_PER_RUN = 10;
export const WATCH_RECHECK_MS = 24 * 60 * 60 * 1000;
export const WATCH_BACKOFF_BASE_MS = 60 * 60 * 1000;
export const WATCH_BACKOFF_MAX_MS = 48 * 60 * 60 * 1000;
/** What a look found; a null state says nothing, least of all that nothing changed. */
export interface WatchVerdict {
state: TourSourceHintState | null;
changes: TourSourceHintChange[];
reason: TourSourceHintReason | null;
}
const NOTHING_TO_SAY: WatchVerdict = { state: null, changes: [], reason: null };
function unverifiable(reason: TourSourceHintReason): WatchVerdict {
return { state: 'unverifiable', changes: [], reason };
}
/** Two change times name the same moment, however the instance spelled them. */
function sameInstant(a: string, b: string): boolean {
if (a === b) return true;
const left = Date.parse(a);
return !Number.isNaN(left) && left === Date.parse(b);
}
/**
* What one look at a trail's record says about a snapshot. It compares with
* what the user last saw in a manual check, else with the import:
*
* - a name or description that differs is proven by the record: `changed`;
* - a change time that moved is only a suspicion: `possible_change`;
* - a trail that is gone or no longer the user's own, or a change time
* missing on either side, cannot be judged: `unverifiable`;
* - anything else says nothing. It never says "unchanged": the line may still
* differ, and only the manual check reads it.
*/
export function verdictOf(source: WatchedSourceRow, look: WandererTrailLook | undefined): WatchVerdict {
if (!look || look.kind === 'gone') return unverifiable('unavailable');
const reviewed = source.seen_hash !== null;
const changes = recordChangedParts(source.seen_hash ?? source.content_hash, look.name, look.description);
if (changes.length > 0) return { state: 'changed', changes, reason: null };
const baseline = reviewed ? source.seen_updated : source.external_updated;
if (baseline === null || look.updated === null) return unverifiable('no_change_time');
return sameInstant(baseline, look.updated) ? NOTHING_TO_SAY : { state: 'possible_change', changes: [], reason: null };
}
/** A hint the user has not been told about yet: something to say, and not what the last look said. */
export function isNewHint(source: WatchedSourceRow, verdict: WatchVerdict): boolean {
return verdict.state !== null && verdict.state !== source.state;
}
/** How long to leave an instance alone after this many failed runs in a row. */
export function backoffMs(failures: number): number {
return Math.min(WATCH_BACKOFF_BASE_MS * 2 ** Math.max(failures - 1, 0), WATCH_BACKOFF_MAX_MS);
}
@@ -0,0 +1,32 @@
import { logError } from '../audit/audit-log.logger';
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { WandererWatchService } from './wanderer-watch.service';
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
/**
* WAN-02: the hourly run of the optional wanderer watch. Hourly is how often
* a connection may get its turn, not how often a trail is read: a source is
* looked at again only a day later, and a run with nothing due asks no
* instance anything. Whether wanderer is on, and which users switched the
* watch on, is read per run, so a change lands without a restart.
*/
@Injectable()
export class WandererWatchJob implements OnApplicationBootstrap {
constructor(
private readonly watch: WandererWatchService,
private readonly registrar: CronRegistrarService,
) {}
onApplicationBootstrap(): void {
if (!this.registrar.isEnabled()) return;
this.registrar.register('wanderer-watch', '23 * * * *', () => this.tick());
}
async tick(): Promise<void> {
try {
await this.watch.run();
} catch (err: unknown) {
logError(`wanderer watch: ${err instanceof Error ? err.message : String(err)}`);
}
}
}
@@ -0,0 +1,219 @@
import { TourSourceHints } from '../../db/entities/TourSourceHints.entity';
import { TOUR_SOURCE_HINT_CHANGES } from '../../db/json-columns';
import type {
TourSourceHintListRow,
TourSourceHintRow,
TourSourceHintsRepository,
WatchedSourceRow,
} from '../../db/repositories/TourSourceHints.repository';
import { dbNow, utcSuffix } from '../../db/types';
import { decodeJson, encodeJson } from '../../utils/json-column';
import { AddonsService } from '../addons/addons.service';
import { logError } from '../audit/audit-log.logger';
import { toRowId } from '../common/row-id';
import { UnitOfWork } from '../database/unit-of-work';
import { NotificationsService } from '../notifications/notifications.service';
import { WandererService, type WandererTrailLook, type WandererWatchLooks } from '../wanderer/wanderer.service';
import {
backoffMs,
isNewHint,
verdictOf,
WATCH_CONNECTIONS_PER_RUN,
WATCH_RECHECK_MS,
WATCH_SOURCES_PER_RUN,
type WatchVerdict,
} from './wanderer-watch.helpers';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import type { TourSourceHint, TourSourceHintResponse, WandererSourceHintItem, WandererWatch } from '@trek/shared';
/** A hint as it goes out: the stored changes read back, the look's time in ISO. */
function hintOf(row: TourSourceHintRow): TourSourceHint {
return {
state: row.state,
changes: decodeJson(TOUR_SOURCE_HINT_CHANGES, row.changes, `hint ${row.place_id}`),
reason: row.reason,
externalUpdated: row.external_updated,
checkedAt: utcSuffix(row.checked_at) ?? '',
};
}
function itemOf(row: TourSourceHintListRow): WandererSourceHintItem {
return {
...hintOf(row),
placeId: row.place_id,
tripId: row.trip_id,
tripTitle: row.trip_title,
tourName: row.tour_name,
};
}
/** A look that had nothing due: no trail asked, nothing read. */
const NOTHING_READ: WandererWatchLooks = { ok: true, looks: new Map() };
interface Finding {
source: WatchedSourceRow;
verdict: WatchVerdict;
}
/**
* WAN-02: the optional background watch over a user's own wanderer snapshots.
*
* Off until the user switches it on for their connection. A run looks, within
* the budget of `wanderer-watch.helpers.ts`, at the small records of the
* trails the user imported into trips they can still open, and writes per
* snapshot what the record suggests. New hints reach the user as a
* notification that leads to the tour, where the manual check (MF-03) reads
* the source in full and a confirmed reimport takes a change in.
*
* It never writes a tour, never downloads a GPX and never asks through anyone
* else's connection. A removed connection, the switch off, a refused token or
* wanderer switched off by the admin end the looks; the hints and snapshots
* already there stay.
*/
@Injectable()
export class WandererWatchService {
/** A run still going when the next is due is not started twice in this process. */
private running = false;
constructor(
private readonly addons: AddonsService,
private readonly wanderer: WandererService,
private readonly notifications: NotificationsService,
private readonly uow: UnitOfWork,
@InjectRepository(TourSourceHints) private readonly hints: TourSourceHintsRepository,
) {}
/** The cron's entry: every connection that may be asked now, one after another. */
async run(now: Date = new Date()): Promise<void> {
if (this.running || !(await this.addons.isWandererAvailable())) return;
this.running = true;
try {
const userIds = await this.wanderer.watchableUserIds(dbNow(now), WATCH_CONNECTIONS_PER_RUN);
await userIds.reduce(async (previous, userId) => {
await previous;
// One instance that fails must not keep the others from their turn.
await this.watchUser(userId, now).catch((err: unknown) => {
logError(`wanderer watch failed for user ${userId}: ${err instanceof Error ? err.message : String(err)}`);
});
}, Promise.resolve());
} finally {
this.running = false;
}
}
/**
* One user's due snapshots. An instance that fails is left alone for longer
* after each failure in a row; the hints already there stay as they are.
*/
private async watchUser(userId: number, now: Date): Promise<void> {
const instance = await this.wanderer.instanceOf(userId);
const checkedBefore = dbNow(new Date(now.getTime() - WATCH_RECHECK_MS));
const due = await this.hints.listDue(userId, instance, checkedBefore, WATCH_SOURCES_PER_RUN);
// Nothing due asks the instance nothing.
const ids = due.map((source) => source.external_id);
const read = ids.length > 0 ? await this.wanderer.lookAtTrails(userId, ids) : NOTHING_READ;
if (!read.ok) {
const failures = (await this.wanderer.watchState(userId)).failures + 1;
await this.wanderer.noteWatchRun(userId, {
lastRunAt: dbNow(now),
failures,
pausedUntil: dbNow(new Date(now.getTime() + backoffMs(failures))),
});
return;
}
const findings = due.map((source) => ({ source, verdict: verdictOf(source, read.looks.get(source.external_id)) }));
await this.uow.transactional(async () => {
await this.hints.record(
findings.map(({ source, verdict }) => ({
place_id: source.place_id,
user_id: userId,
state: verdict.state,
changes: verdict.changes.length > 0 ? encodeJson(TOUR_SOURCE_HINT_CHANGES, verdict.changes) : null,
reason: verdict.reason,
external_updated: lookedUpdated(read.looks.get(source.external_id)),
checked_at: dbNow(now),
})),
);
await this.wanderer.noteWatchRun(userId, { lastRunAt: dbNow(now), failures: 0, pausedUntil: null });
});
await this.announce(userId, findings.filter(({ source, verdict }) => isNewHint(source, verdict)));
}
/**
* Tell the user about the hints they have not heard of, one notification per
* tour so each leads to its own.
* @txStandalone the notices stand on their own; a failed one never undoes what the look wrote
*/
private async announce(userId: number, fresh: readonly Finding[]): Promise<void> {
if (fresh.length === 0) return;
const rows = new Map((await this.hints.listOpen(userId)).map((row) => [row.place_id, row]));
await fresh.reduce(async (previous, { source, verdict }) => {
await previous;
const row = rows.get(source.place_id);
if (!row || !verdict.state) return;
await this.notifications
.send({
event: 'wanderer_source_hint',
actorId: null,
scope: 'user',
targetId: userId,
params: {
state: verdict.state,
tour: row.tour_name,
trip: row.trip_title,
tripId: String(row.trip_id),
placeId: String(row.place_id),
},
})
.catch((err: unknown) => {
logError(`wanderer watch notice for ${source.place_id}: ${err instanceof Error ? err.message : String(err)}`);
});
}, Promise.resolve());
}
/** The watch of the user's connection, with the open hints. */
async status(userId: number): Promise<WandererWatch> {
const state = await this.wanderer.watchState(userId);
return {
enabled: state.enabled,
connected: state.connected,
lastRunAt: utcSuffix(state.lastRunAt),
pausedUntil: utcSuffix(state.pausedUntil),
blocked: state.blocked,
hints: state.connected ? (await this.hints.listOpen(userId)).map(itemOf) : [],
};
}
/** Switch the watch on or off; switching it off ends further looks at once. */
async setEnabled(userId: number, enabled: boolean, clientIp: string | null): Promise<WandererWatch> {
await this.wanderer.setWatch(userId, enabled, clientIp);
return await this.status(userId);
}
/** The caller's own open hint on one snapshot of the trip; null when there is none. */
async hintFor(tripId: string, userId: number, placeId: string): Promise<TourSourceHintResponse> {
const tid = toRowId(tripId);
const pid = toRowId(placeId);
const row = tid === null || pid === null ? undefined : await this.hints.findOpen(userId, tid, pid);
return { hint: row ? hintOf(row) : null };
}
/**
* A manual check read the source in full: what it found is what the user has
* seen now, so their open hint goes and later looks compare with this.
* @txStandalone the note of what the user saw stands on its own; the check around it writes nothing else
*/
async noteSeen(
placeId: number,
userId: number,
seen: { contentHash: string; externalUpdated: string | null },
): Promise<void> {
await this.hints.markSeen(placeId, userId, { ...seen, checkedAt: dbNow() });
}
}
/** The change time a look read, kept for the hint to show; none when the trail could not be read. */
function lookedUpdated(look: WandererTrailLook | undefined): string | null {
return look?.kind === 'record' ? look.updated : null;
}
+125 -6
View File
@@ -43,6 +43,34 @@ export interface WandererTrailDownload {
gpx: string;
}
/**
* WAN-02: a trail as the background watch sees it, from its small record
* alone: its texts and its change time, or `gone` when it was deleted, is
* refused or is no longer the user's own.
*/
export type WandererTrailLook =
| { kind: 'record'; name: string; description: string | null; updated: string | null }
| { kind: 'gone' };
/**
* WAN-02: what one look of the watch read: a look per trail, or why the
* instance itself could not be asked, for the watch to back off from.
*/
export type WandererWatchLooks =
| { ok: true; looks: Map<string, WandererTrailLook> }
| { ok: false; code: WandererErrorCode };
/** WAN-02: the background watch of one user's connection. */
interface WandererWatchState {
connected: boolean;
enabled: boolean;
lastRunAt: string | null;
failures: number;
pausedUntil: string | null;
/** wanderer refused the token; the watch asks nothing until a test passes or a new token is saved. */
blocked: boolean;
}
/** An upstream failure as the API answers it: never a 401, which the app reads as its own session ending. */
function refusalOf(err: WandererError): DomainError {
const status = err.code === 'not_found' ? 404 : err.code === 'forbidden' || err.code === 'not_own_trail' ? 403 : 502;
@@ -145,12 +173,7 @@ export class WandererService {
private async credentials(userId: number): Promise<WandererCreds> {
const row = await this.connections.findRow(userId);
const token = row?.token ? decrypt_api_key(row.token) : null;
if (!row?.url || !token) {
throw new DomainError(409, 'wanderer is not connected', {
code: 'wanderer_not_connected',
details: { code: 'not_connected' },
});
}
if (!row?.url || !token) throw notConnected();
return { baseUrl: row.url, token, allowInsecureTls: !!row.allow_insecure_tls };
}
@@ -216,6 +239,95 @@ export class WandererService {
}
}
/** WAN-02: whether the user's connection is watched in the background, and how its last run went. */
async watchState(userId: number): Promise<WandererWatchState> {
const row = await this.connections.findRow(userId);
const watch = await this.connections.findWatch(userId);
return {
connected: !!(row?.url && row.token),
enabled: watch?.watch_enabled === 1,
lastRunAt: watch?.watch_last_run_at ?? null,
failures: watch?.watch_failures ?? 0,
pausedUntil: watch?.watch_paused_until ?? null,
blocked: row?.last_check_ok === 0 && row.last_check_error === 'unauthorized',
};
}
/**
* WAN-02: switch the background watch on or off. It only ever acts on the
* user's own connection, so there has to be one to switch it on for.
*/
async setWatch(userId: number, enabled: boolean, clientIp: string | null): Promise<void> {
if (enabled && !(await this.watchState(userId)).connected) throw notConnected();
await this.connections.setWatch(userId, enabled);
await this.audit.writeAudit({
userId,
action: enabled ? 'wanderer.watch_enabled' : 'wanderer.watch_disabled',
ip: clientIp,
details: {},
});
}
/** WAN-02: the users whose connection the watch may ask now, longest waiting first. */
async watchableUserIds(now: string, limit: number): Promise<number[]> {
return await this.connections.listWatchable(now, limit);
}
/**
* WAN-02: note how a run of the watch went on the connection.
* @txStandalone the run's bookkeeping stands on its own: it is true whatever the hints written beside it say
*/
async noteWatchRun(
userId: number,
run: { lastRunAt: string; failures: number; pausedUntil: string | null },
): Promise<void> {
await this.connections.recordWatchRun(userId, run);
}
/**
* WAN-02: the records of the given trails, for the background watch. One
* small read per trail, one after another, and never its GPX: the change
* time and the texts are what a look can afford. A trail that is gone,
* refused or someone else's reads as `gone`; a failure of the instance
* itself (unreachable, an error, a refused token, which is noted on the
* connection) ends the whole look with its reason.
*/
async lookAtTrails(userId: number, trailIds: readonly string[]): Promise<WandererWatchLooks> {
const creds = await this.credentials(userId);
const looks = new Map<string, WandererTrailLook>();
try {
const authors = await this.client.ownActors(creds);
await [...new Set(trailIds)].reduce(async (previous, id) => {
await previous;
looks.set(id, await this.lookAt(creds, id, authors));
}, Promise.resolve());
} catch (err: unknown) {
if (!(err instanceof WandererError)) throw err;
if (err.code === 'unauthorized') await this.noteCheck(userId, false, err.code);
return { ok: false, code: err.code };
}
return { ok: true, looks };
}
private async lookAt(creds: WandererCreds, id: string, authors: readonly string[]): Promise<WandererTrailLook> {
try {
const trail = await this.client.trail(creds, id);
if (!trail.author || !authors.includes(trail.author)) return { kind: 'gone' };
return {
kind: 'record',
name: trail.name,
description: trail.description ?? null,
updated: trail.updated ?? null,
};
} catch (err: unknown) {
// Deleted or refused: the trail is out of reach, not the instance.
if (err instanceof WandererError && (err.code === 'not_found' || err.code === 'forbidden')) {
return { kind: 'gone' };
}
throw err;
}
}
/** The list row of a trail by its id, as the search would show it. */
async findTrail(userId: number, trailId: string): Promise<WandererTrailFound | null> {
const creds = await this.credentials(userId);
@@ -229,6 +341,13 @@ export class WandererService {
}
}
function notConnected(): DomainError {
return new DomainError(409, 'wanderer is not connected', {
code: 'wanderer_not_connected',
details: { code: 'not_connected' },
});
}
function summaryOf(instance: string, hit: WandererSearchHit): WandererTrailFound {
const author = hit.author_name ? (hit.domain ? `${hit.author_name}@${hit.domain}` : hit.author_name) : null;
return {