add test and code for client closure events

This commit is contained in:
2025-04-30 18:17:27 -07:00
parent 31e9c78ebd
commit f74376c8ed
2 changed files with 22 additions and 7 deletions

View File

@@ -18,12 +18,20 @@ export class AppleNotificationSender {
private apnsToken: string | undefined = undefined;
private _lastRefreshedTimeMs: number | undefined = undefined;
private client: ClientHttp2Session | undefined = undefined;
constructor(private shouldActuallySendNotifications = true) {
constructor(
private shouldActuallySendNotifications = true,
private client: ClientHttp2Session | undefined = undefined,
) {
this.sendNotificationImmediately = this.sendNotificationImmediately.bind(this);
this.lastReloadedTimeForAPNsIsTooRecent = this.lastReloadedTimeForAPNsIsTooRecent.bind(this);
this.reloadAPNsTokenIfTimePassed = this.reloadAPNsTokenIfTimePassed.bind(this);
this.openConnectionIfNoneExists = this.openConnectionIfNoneExists.bind(this);
this.closeConnectionIfExists = this.closeConnectionIfExists.bind(this);
this.registerClosureEventsForClient = this.registerClosureEventsForClient.bind(this);
if (this.client !== undefined) {
this.registerClosureEventsForClient();
}
}
get lastRefreshedTimeMs(): number | undefined {
@@ -101,8 +109,7 @@ export class AppleNotificationSender {
};
try {
if (!this.client) { return false }
const client = this.client;
const req = client.request(headers);
const req = this.client.request(headers);
req.setEncoding('utf8');
await new Promise<void>((resolve, reject) => {
@@ -142,9 +149,17 @@ export class AppleNotificationSender {
if (!this.client) {
this.client = http2.connect(host);
this.registerClosureEventsForClient();
}
}
private registerClosureEventsForClient() {
this.client?.on('close', this.closeConnectionIfExists);
this.client?.on('error', this.closeConnectionIfExists);
this.client?.on('goaway', this.closeConnectionIfExists);
this.client?.on('timeout', this.closeConnectionIfExists);
}
private closeConnectionIfExists() {
this.client?.close();
this.client = undefined;