mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 21:11:14 +00:00
feat(native): a silent push keeps every watch on a trip current
A change to a trip's packing lists or to-dos (any writer: REST, MCP, plugin RPC) is noted from the realtime broadcast and, a couple of seconds later, each member with the iPhone app gets a silent push through the app relay, marked as a background push. The push carries no content: the woken app reads both lists of the trip its watch shows from the server with its own session and hands them to the watch. The app gains the remote-notification background mode for it.
This commit is contained in:
@@ -4,6 +4,7 @@ import { Notifications } from '../../db/entities/Notifications.entity';
|
||||
import { PushSubscriptions } from '../../db/entities/PushSubscriptions.entity';
|
||||
import { Settings } from '../../db/entities/Settings.entity';
|
||||
import { TodoItems } from '../../db/entities/TodoItems.entity';
|
||||
import { TripMembers } from '../../db/entities/TripMembers.entity';
|
||||
import { Trips } from '../../db/entities/Trips.entity';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
@@ -16,6 +17,7 @@ import { NotificationsService } from './notifications.service';
|
||||
import { PushSubscriptionsService } from './push/push-subscriptions.service';
|
||||
import { PushController } from './push/push.controller';
|
||||
import { VapidKeysService } from './push/vapid-keys.service';
|
||||
import { WatchSyncPushService } from './push/watch-sync-push.service';
|
||||
import { ReminderJobsService } from './reminder-jobs.service';
|
||||
import { StorageHealthNotifierService } from './storage-health-notifier.service';
|
||||
import { NtfyService } from './transports/ntfy.service';
|
||||
@@ -62,6 +64,7 @@ import { Module } from '@nestjs/common';
|
||||
Trips,
|
||||
TodoItems,
|
||||
PushSubscriptions,
|
||||
TripMembers,
|
||||
]),
|
||||
|
||||
AddonsModule,
|
||||
@@ -78,6 +81,7 @@ import { Module } from '@nestjs/common';
|
||||
WebPushService,
|
||||
VapidKeysService,
|
||||
PushSubscriptionsService,
|
||||
WatchSyncPushService,
|
||||
NotificationsMcp,
|
||||
ReminderJobsService,
|
||||
StorageHealthNotifierService,
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { TripMembers } from '../../../db/entities/TripMembers.entity';
|
||||
import type { TripMembersRepository } from '../../../db/repositories/TripMembers.repository';
|
||||
import { logError } from '../../audit/audit-log.logger';
|
||||
import { withRequestContext } from '../../database/request-context';
|
||||
import { RealtimeService } from '../../realtime/realtime.service';
|
||||
import { WebPushService } from '../transports/web-push.service';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable, type OnModuleDestroy, type OnModuleInit } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* How long the changes of one trip are gathered into one sync. Ticking off a
|
||||
* list goes in runs, and Apple throttles background pushes to a device that
|
||||
* gets too many, so a run of ticks becomes one push a couple of seconds later.
|
||||
*/
|
||||
export const WATCH_SYNC_SETTLE_MS = 2000;
|
||||
|
||||
/** The lists the watch shows: the packing lists (items and bags) and the to-dos. */
|
||||
const LIST_EVENT = /^(packing|todo):/;
|
||||
|
||||
interface PendingSync {
|
||||
timer: ReturnType<typeof setTimeout>;
|
||||
/** A change everyone on the trip sees; otherwise only `users` (a private packing item). */
|
||||
everyone: boolean;
|
||||
users: Set<number>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the Apple Watches of a trip's members current while their iPhone app is
|
||||
* in the background. The watch only gets what its phone sends it, and a phone
|
||||
* app in the background hears nothing over the WebSocket, so a tick by someone
|
||||
* else used to reach a watch only once its phone app was next opened.
|
||||
*
|
||||
* Every trip broadcast of a list event (whoever made it, over REST, MCP or a
|
||||
* plugin's RPC) is noted here; a couple of seconds later each member with the
|
||||
* iPhone app gets a silent push (WebPushService.sendWatchSync), which wakes the
|
||||
* app to read the lists and pass them to its watch. The push carries no content
|
||||
* and no trip: the app reads what it needs from this server with its own
|
||||
* session. A private packing item syncs only its owner.
|
||||
*/
|
||||
@Injectable()
|
||||
export class WatchSyncPushService implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly pending = new Map<string, PendingSync>();
|
||||
private stopListening: (() => void) | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly push: WebPushService,
|
||||
@InjectRepository(TripMembers) private readonly members: TripMembersRepository,
|
||||
private readonly orm: MikroORM,
|
||||
) {}
|
||||
|
||||
onModuleInit(): void {
|
||||
this.stopListening = this.realtime.onTripBroadcast((tripId, eventType, onlyUserId) =>
|
||||
this.note(tripId, eventType, onlyUserId),
|
||||
);
|
||||
}
|
||||
|
||||
onModuleDestroy(): void {
|
||||
this.stopListening?.();
|
||||
this.stopListening = null;
|
||||
for (const entry of this.pending.values()) clearTimeout(entry.timer);
|
||||
this.pending.clear();
|
||||
}
|
||||
|
||||
/** A broadcast went out: a list event joins its trip's next sync. */
|
||||
note(tripId: number | string, eventType: string, onlyUserId?: number): void {
|
||||
if (!LIST_EVENT.test(eventType)) return;
|
||||
const key = String(tripId);
|
||||
let entry = this.pending.get(key);
|
||||
if (!entry) {
|
||||
const timer = setTimeout(() => void this.flush(key), WATCH_SYNC_SETTLE_MS);
|
||||
// A sync still waiting never holds the process open on shutdown.
|
||||
timer.unref?.();
|
||||
entry = { timer, everyone: false, users: new Set() };
|
||||
this.pending.set(key, entry);
|
||||
}
|
||||
if (onlyUserId == null) entry.everyone = true;
|
||||
else entry.users.add(onlyUserId);
|
||||
}
|
||||
|
||||
/** Sends one trip's gathered sync. */
|
||||
async flush(key: string): Promise<void> {
|
||||
const entry = this.pending.get(key);
|
||||
if (!entry) return;
|
||||
this.pending.delete(key);
|
||||
clearTimeout(entry.timer);
|
||||
try {
|
||||
const users = entry.everyone
|
||||
? await withRequestContext(this.orm, () => this.members.rosterUserIds(key))
|
||||
: entry.users;
|
||||
await Promise.all([...users].map((userId) => this.push.sendWatchSync(userId)));
|
||||
} catch (err) {
|
||||
logError(`Watch sync failed trip=${key}: ${err instanceof Error ? err.message : err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,7 +48,37 @@ export const FORBIDDEN_FAILURES_BEFORE_REMOVAL = 3;
|
||||
*/
|
||||
const COLLAPSING_EVENT = 'collab_message';
|
||||
|
||||
type Urgency = 'normal' | 'high';
|
||||
type Urgency = 'low' | 'normal' | 'high';
|
||||
|
||||
/**
|
||||
* The watch sync (WatchSyncPushService): a silent push to the TREK iPhone app
|
||||
* that a packing list or the to-dos of one of its trips changed, so the app can
|
||||
* refresh its Apple Watch while it is in the background. The relay sends it as
|
||||
* an APNs background push (content-available, no alert) when it carries this
|
||||
* header; the record itself says nothing beyond that.
|
||||
*/
|
||||
export const BACKGROUND_PUSH_HEADER = 'X-Trek-Push';
|
||||
const WATCH_SYNC_PAYLOAD = Buffer.from(JSON.stringify({ type: 'watch-sync' }), 'utf8');
|
||||
/** A refresh that arrives ten minutes late is stale; the next change sends another. */
|
||||
const WATCH_SYNC_TTL_SECONDS = 10 * 60;
|
||||
/** Later syncs replace a queued one at Apple: only the newest state matters. */
|
||||
const WATCH_SYNC_TOPIC = 'trek-watch-sync';
|
||||
|
||||
/** The relay's APNs endpoints, the only devices with a watch to refresh. */
|
||||
export function isAppleRelayEndpoint(endpoint: string): boolean {
|
||||
try {
|
||||
const url = new URL(endpoint);
|
||||
return url.protocol === 'https:' && url.hostname === 'push.liketrek.com' && url.pathname.startsWith('/v1/apns/');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
interface DeliveryOptions {
|
||||
ttlSeconds?: number;
|
||||
/** Sent as a background push by the relay, never shown. */
|
||||
background?: boolean;
|
||||
}
|
||||
/** The events that are about a date, where arriving late defeats the point (RFC 8030 section 5.3). */
|
||||
const HIGH_URGENCY_EVENTS: ReadonlySet<string> = new Set(['trip_reminder', 'todo_due']);
|
||||
|
||||
@@ -169,6 +199,29 @@ export class WebPushService {
|
||||
return this.deliver(userId, buildPushPayload(msg), urgency, msg.event);
|
||||
}
|
||||
|
||||
/**
|
||||
* The watch sync to each of the user's iPhones (the relay's APNs endpoints):
|
||||
* true when at least one took it. Browsers and Android devices have no watch
|
||||
* and get nothing. Nothing is sent while the server has no usable key pair.
|
||||
*/
|
||||
async sendWatchSync(userId: number): Promise<boolean> {
|
||||
try {
|
||||
if (!(await this.isAvailable())) return false;
|
||||
const rows = (await this.subscriptions.listForUser(userId)).filter((row) => isAppleRelayEndpoint(row.endpoint));
|
||||
if (rows.length === 0) return false;
|
||||
const keys = await this.keys.getKeys();
|
||||
const sign = createVapidSigner(keys, this.keys.getSubject());
|
||||
const options: DeliveryOptions = { ttlSeconds: WATCH_SYNC_TTL_SECONDS, background: true };
|
||||
const results = await Promise.all(
|
||||
rows.map((row) => this.deliverTo(row, WATCH_SYNC_PAYLOAD, keys.publicKey, sign, 'low', 'watch_sync', options)),
|
||||
);
|
||||
return results.includes(true);
|
||||
} catch (err) {
|
||||
logError(`Web Push failed event=watch_sync user=${userId}: ${err instanceof Error ? err.message : err}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** The Send test button: a short fixed message to every browser the user turned push on in. */
|
||||
async sendTest(userId: number): Promise<ChannelTestResult> {
|
||||
if (!(await this.isAvailable())) return { success: false, error: PUSH_UNAVAILABLE_ERROR };
|
||||
@@ -200,6 +253,7 @@ export class WebPushService {
|
||||
sign: VapidSigner,
|
||||
urgency: Urgency,
|
||||
event: string,
|
||||
options: DeliveryOptions = {},
|
||||
): Promise<boolean> {
|
||||
const host = hostOf(row.endpoint);
|
||||
if (row.vapid_public_key !== publicKey) {
|
||||
@@ -230,11 +284,12 @@ export class WebPushService {
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
TTL: String(PUSH_TTL_SECONDS),
|
||||
TTL: String(options.ttlSeconds ?? PUSH_TTL_SECONDS),
|
||||
Urgency: urgency,
|
||||
'Content-Encoding': 'aes128gcm',
|
||||
'Content-Type': 'application/octet-stream',
|
||||
Authorization: sign(row.endpoint),
|
||||
...(options.background ? { [BACKGROUND_PUSH_HEADER]: 'background', Topic: WATCH_SYNC_TOPIC } : {}),
|
||||
},
|
||||
body: new Uint8Array(body),
|
||||
signal: AbortSignal.timeout(PUSH_TIMEOUT_MS),
|
||||
|
||||
@@ -17,8 +17,26 @@ import type { TrekWsPayload, TrekWsPluginEventName, TrekWsTripEventName, TrekWsU
|
||||
* The service is deliberately dependency-free so out-of-container code (the
|
||||
* no-Nest test harnesses) can construct it with a bare `new RealtimeService()`.
|
||||
*/
|
||||
/**
|
||||
* Told of every trip broadcast once it went out: the trip, the event and, for a
|
||||
* private item, the one user it went to. The watch sync (WatchSyncPushService)
|
||||
* listens here, so every writer that broadcasts (REST, MCP, plugin RPC) reaches
|
||||
* it without knowing of it.
|
||||
*/
|
||||
export type TripBroadcastListener = (tripId: number | string, eventType: string, onlyUserId?: number) => void;
|
||||
|
||||
@Injectable()
|
||||
export class RealtimeService {
|
||||
private readonly listeners = new Set<TripBroadcastListener>();
|
||||
|
||||
/** Registers a listener for trip broadcasts; returns the way to remove it. */
|
||||
onTripBroadcast(listener: TripBroadcastListener): () => void {
|
||||
this.listeners.add(listener);
|
||||
return () => {
|
||||
this.listeners.delete(listener);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Broadcast an event to all sockets in a trip room. Mirrors the
|
||||
* ws-state.ts signature exactly: `excludeSid` is the X-Socket-Id
|
||||
@@ -59,6 +77,15 @@ export class RealtimeService {
|
||||
]
|
||||
): void {
|
||||
broadcast(...args);
|
||||
const [tripId, eventType, , , onlyUserId] = args;
|
||||
for (const listener of this.listeners) {
|
||||
// A listener is a side matter: it never costs the broadcast or the next listener.
|
||||
try {
|
||||
listener(tripId, eventType, onlyUserId);
|
||||
} catch {
|
||||
/* the listener logs its own failures */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user