update naming of classes and tests

This commit is contained in:
2025-03-24 09:20:10 -07:00
parent 135a294e5d
commit 619ef9a27f
8 changed files with 26 additions and 26 deletions

View File

@@ -0,0 +1,281 @@
import { GetterRepository } from "../../repositories/GetterRepository";
import jwt from "jsonwebtoken";
import fs from "fs";
import { TupleKey } from "../../types/TupleKey";
import { IEta } from "../../entities/entities";
import http2 from "http2";
export interface ScheduledNotificationData {
deviceId: string;
shuttleId: string;
stopId: string;
}
interface APNsUrl {
fullUrl: string;
path: string;
host: string;
}
export class ETANotificationScheduler {
public readonly secondsThresholdForNotificationToFire = 180;
private apnsToken: string | undefined = undefined;
private _lastRefreshedTimeMs: number | undefined = undefined;
get lastRefreshedTimeMs() {
return this._lastRefreshedTimeMs;
}
constructor(private repository: GetterRepository, private shouldActuallySendNotifications = true) {
this.etaSubscriberCallback = this.etaSubscriberCallback.bind(this);
this.reloadAPNsTokenIfTimePassed = this.reloadAPNsTokenIfTimePassed.bind(this);
this.lastReloadedTimeForAPNsIsTooRecent = this.lastReloadedTimeForAPNsIsTooRecent.bind(this);
this.sendEtaNotificationImmediately = this.sendEtaNotificationImmediately.bind(this);
this.etaSubscriberCallback = this.etaSubscriberCallback.bind(this);
this.sendEtaNotificationImmediatelyIfSecondsRemainingBelowThreshold = this.sendEtaNotificationImmediatelyIfSecondsRemainingBelowThreshold.bind(this);
this.scheduleNotification = this.scheduleNotification.bind(this);
}
/**
* An object of device ID arrays to deliver notifications to.
* The key should be a combination of the shuttle ID and
* stop ID, which can be generated using `TupleKey`.
* @private
*/
private deviceIdsToDeliverTo: { [key: string]: Set<string> } = {}
public reloadAPNsTokenIfTimePassed() {
if (this.lastReloadedTimeForAPNsIsTooRecent()) {
return;
}
const keyId = process.env.APNS_KEY_ID;
const teamId = process.env.APNS_TEAM_ID;
const privateKeyBase64 = process.env.APNS_PRIVATE_KEY;
if (!privateKeyBase64) return;
const privateKey = Buffer.from(privateKeyBase64, 'base64').toString('utf-8');
const tokenHeader = {
alg: "ES256",
"kid": keyId,
};
const nowMs = Date.now();
const claimsPayload = {
"iss": teamId,
"iat": Math.ceil(nowMs / 1000), // APNs requires number of seconds since Epoch
};
this.apnsToken = jwt.sign(claimsPayload, privateKey, {
algorithm: "ES256",
header: tokenHeader
});
this._lastRefreshedTimeMs = nowMs;
}
private lastReloadedTimeForAPNsIsTooRecent() {
const thirtyMinutesMs = 1800000;
return this._lastRefreshedTimeMs && Date.now() - this._lastRefreshedTimeMs < thirtyMinutesMs;
}
private async sendEtaNotificationImmediately(notificationData: ScheduledNotificationData): Promise<boolean> {
if (!this.shouldActuallySendNotifications) {
return true; // pretend that the notification sent
}
const { deviceId, shuttleId, stopId } = notificationData;
this.reloadAPNsTokenIfTimePassed();
const shuttle = await this.repository.getShuttleById(shuttleId);
const stop = await this.repository.getStopById(stopId);
const eta = await this.repository.getEtaForShuttleAndStopId(shuttleId, stopId);
if (!shuttle) {
console.warn(`Notification ${notificationData} fell through; no associated shuttle`);
return false;
}
if (!stop) {
console.warn(`Notification ${notificationData} fell through; no associated stop`);
return false;
}
// Notification may not be sent if ETA is unavailable at the moment;
// this is fine because it will be sent again when ETA becomes available
if (!eta) {
console.warn(`Notification ${notificationData} fell through; no associated ETA`);
return false;
}
// Send the fetch request
const bundleId = process.env.APNS_BUNDLE_ID;
if (typeof bundleId !== "string") {
throw new Error("APNS_BUNDLE_ID environment variable is not set correctly");
}
const { path, host } = ETANotificationScheduler.getAPNsFullUrlToUse(deviceId);
const headers = {
':method': 'POST',
':path': path,
'authorization': `bearer ${this.apnsToken}`,
"apns-push-type": "alert",
"apns-expiration": "0",
"apns-priority": "10",
"apns-topic": bundleId,
};
try {
const client = http2.connect(host);
const req = client.request(headers);
req.setEncoding('utf8');
await new Promise<void>((resolve, reject) => {
req.on('response', (headers, flags) => {
if (headers[":status"] !== 200) {
reject(`APNs request failed with status ${headers[":status"]}`);
}
resolve();
});
req.write(JSON.stringify({
aps: {
alert: {
title: "Shuttle is arriving",
body: `Shuttle is approaching ${stop.name} in ${Math.ceil(eta.secondsRemaining / 60)} minutes.`
}
}
}));
req.end();
});
return true;
} catch(e) {
console.error(e);
return false;
}
}
public static getAPNsFullUrlToUse(deviceId: string): APNsUrl {
// Construct the fetch request
const devBaseUrl = "https://api.development.push.apple.com"
const prodBaseUrl = "https://api.push.apple.com"
let hostToUse = devBaseUrl;
if (process.env.APNS_IS_PRODUCTION === "1") {
hostToUse = prodBaseUrl;
}
const path = "/3/device/" + deviceId;
const fullUrl = hostToUse + path;
const constructedObject = {
fullUrl,
host: hostToUse,
path,
}
return constructedObject;
}
private async etaSubscriberCallback(eta: IEta) {
const tuple = new TupleKey(eta.shuttleId, eta.stopId);
if (this.deviceIdsToDeliverTo[tuple.toString()] === undefined) {
return;
}
const deviceIdsToRemove = new Set<string>();
for (let deviceId of this.deviceIdsToDeliverTo[tuple.toString()].values()) {
const deliveredSuccessfully = await this.sendEtaNotificationImmediatelyIfSecondsRemainingBelowThreshold(deviceId, eta);
if (deliveredSuccessfully) {
deviceIdsToRemove.add(deviceId);
}
}
deviceIdsToRemove.forEach((deviceId) => {
this.deviceIdsToDeliverTo[tuple.toString()].delete(deviceId);
});
}
private async sendEtaNotificationImmediatelyIfSecondsRemainingBelowThreshold(deviceId: string, eta: IEta) {
if (eta.secondsRemaining > this.secondsThresholdForNotificationToFire) {
return false;
}
return await this.sendEtaNotificationImmediately({
deviceId,
shuttleId: eta.shuttleId,
stopId: eta.stopId,
});
}
/**
* Queue a notification to be sent.
* @param deviceId The device ID to send the notification to.
* @param shuttleId Shuttle ID of ETA object to check.
* @param stopId Stop ID of ETA object to check.
*/
public async scheduleNotification({ deviceId, shuttleId, stopId }: ScheduledNotificationData) {
const tuple = new TupleKey(shuttleId, stopId);
if (this.deviceIdsToDeliverTo[tuple.toString()] === undefined) {
this.deviceIdsToDeliverTo[tuple.toString()] = new Set();
}
this.deviceIdsToDeliverTo[tuple.toString()].add(deviceId);
this.repository.unsubscribeFromEtaUpdates(this.etaSubscriberCallback);
this.repository.subscribeToEtaUpdates(this.etaSubscriberCallback);
}
/**
* Cancel a pending notification.
* @param deviceId The device ID of the notification.
* @param shuttleId Shuttle ID of the ETA object.
* @param stopId Stop ID of the ETA object.
*/
public async cancelNotificationIfExists({ deviceId, shuttleId, stopId }: ScheduledNotificationData) {
const tupleKey = new TupleKey(shuttleId, stopId);
if (
this.deviceIdsToDeliverTo[tupleKey.toString()] === undefined
|| !this.deviceIdsToDeliverTo[tupleKey.toString()].has(deviceId)
) {
return;
}
this.deviceIdsToDeliverTo[tupleKey.toString()].delete(deviceId);
}
/**
* Check whether the notification is scheduled.
* @param deviceId
* @param shuttleId
* @param stopId
*/
public isNotificationScheduled({ deviceId, shuttleId, stopId }: ScheduledNotificationData): boolean {
const tuple = new TupleKey(shuttleId, stopId);
if (this.deviceIdsToDeliverTo[tuple.toString()] === undefined) {
return false;
}
return this.deviceIdsToDeliverTo[tuple.toString()].has(deviceId);
}
/**
* Return all scheduled notification for the given device ID.
* @param deviceId
*/
public async getAllScheduledNotificationsForDevice(deviceId: string): Promise<ScheduledNotificationData[]> {
const scheduledNotifications: ScheduledNotificationData[] = [];
for (const key of Object.keys(this.deviceIdsToDeliverTo)) {
if (this.deviceIdsToDeliverTo[key].has(deviceId)) {
const tupleKey = TupleKey.fromExistingStringKey(key);
const shuttleId = tupleKey.tuple[0]
const stopId = tupleKey.tuple[1];
scheduledNotifications.push({
shuttleId,
stopId,
deviceId,
});
}
}
return scheduledNotifications;
}
}