mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 18:04:18 +00:00
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:
@@ -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(),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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(),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
+43
@@ -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 });
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user