Skip to content

Commit a19c914

Browse files
committed
refactor: Improve PaymentListenerDurable
1 parent 75181d3 commit a19c914

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

src/durable/payment-listener-durable.ts

+18-10
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,8 @@ export class PaymentListenerDurable extends DurableObject<Env> {
3838
throw new Error(e.message);
3939
});
4040

41-
this.nanoWebsocket.onClose((e) => {
42-
if (e.code !== 1000 || !this.nanoWebsocket.closedByClient) {
41+
this.nanoWebsocket.onClose((e, closedByClient) => {
42+
if (e.code !== 1000 || !closedByClient) {
4343
throw new Error(`Websocket connection closed: ${this.env.NANO_WEBSOCKET_URL} ${e.reason ? ', ' + e.reason : ''}`);
4444
}
4545
});
@@ -51,14 +51,14 @@ export class PaymentListenerDurable extends DurableObject<Env> {
5151
this.onPayment(payment, invoice, service, webhooks);
5252
});
5353

54-
await this.alarm();
55-
5654
this.pendingInvoices.push({
5755
id: invoice.id,
5856
expiresAt: invoice.expires_at,
5957
payAddress: invoice.pay_address,
6058
payments: [],
6159
});
60+
61+
await this.alarm();
6262
}
6363

6464
private async onPayment(payment: SendEvent, invoice: Invoice, service: Service, webhooks: Webhook[]) {
@@ -147,7 +147,10 @@ export class PaymentListenerDurable extends DurableObject<Env> {
147147
}
148148

149149
async alarm() {
150-
this.pendingInvoices.forEach(async (activeInvoice) => {
150+
/*
151+
Alarm: Expire invoices, keep websocket connection alive or close it
152+
*/
153+
for (const activeInvoice of this.pendingInvoices) {
151154
const expired = new Date(activeInvoice.expiresAt).getTime() < Date.now();
152155
if (expired) {
153156
logger.info(`Invoice expired: ${activeInvoice.id}`, {
@@ -156,15 +159,20 @@ export class PaymentListenerDurable extends DurableObject<Env> {
156159
this.nanoWebsocket.unsubscribe(activeInvoice.payAddress);
157160
this.removePendingInvoice(activeInvoice.id);
158161
}
159-
});
160-
if (this.nanoWebsocket.listeningAccounts.length > 0) {
162+
}
163+
if (this.pendingInvoices.length > 0) {
161164
const currentAlarm = await this.ctx.storage.getAlarm();
162165
if (!currentAlarm) {
163-
// Call alarm to keep websocket connection alive
164-
this.ctx.storage.setAlarm(Date.now() + 1000 * 15);
166+
const nearestExpiresAt = this.pendingInvoices.reduce((acc, activeInvoice) => {
167+
return acc < new Date(activeInvoice.expiresAt).getTime() ? acc : new Date(activeInvoice.expiresAt).getTime();
168+
}, Infinity);
169+
170+
const defaultScheduledTime = Date.now() + 1000 * 30; // 30 seconds
171+
const scheduledTime = nearestExpiresAt < defaultScheduledTime ? nearestExpiresAt : defaultScheduledTime;
172+
173+
this.ctx.storage.setAlarm(scheduledTime);
165174
}
166175
} else {
167-
// No more listening accounts, close the websocket connection
168176
this.nanoWebsocket.close();
169177
}
170178
}

0 commit comments

Comments
 (0)