Skip to content

Commit

Permalink
improve invoice creation speed by handling the payment notifier wait …
Browse files Browse the repository at this point in the history
…to start
  • Loading branch information
anarkrypto committed Oct 21, 2024
1 parent 5ec5851 commit 0b3a44f
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 6 deletions.
32 changes: 30 additions & 2 deletions src/durable/payment-notifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export type PaymentNotification = {
*/
export class PaymentNotifier extends DurableObject<Env> {
sessions = new Set<WebSocket>();
startPromises = new Set<{ promise: Promise<void>; start: () => void }>();
state: DurableObjectState;
storage: DurableObjectStorage;

Expand All @@ -40,8 +41,30 @@ export class PaymentNotifier extends DurableObject<Env> {

const started = await this.storage.get('started');
if (started !== 'true') {
logger.debug('Payment notifier not started');
return new Response('not started', { status: 503 });
let start = () => {};
const promise = new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => {
reject('Timeout');
}, 10000);
start = () => {
resolve();
clearTimeout(timeout);
};
});
const startPromise = { promise, start };
this.startPromises.add(startPromise);

return promise
.then(() => {
return new Response('started', { status: 200 });
})
.catch(() => {
logger.debug('Payment notifier not started');
return new Response('not started', { status: 503 });
})
.finally(() => {
this.startPromises.delete(startPromise);
});
}

if (this.sessions.size >= MAX_WEBSOCKET_SESSIONS_PER_PAYMENT_NOTIFIER) {
Expand All @@ -60,6 +83,11 @@ export class PaymentNotifier extends DurableObject<Env> {
}

async start() {
if (this.startPromises) {
this.startPromises.forEach((startPromise) => {
startPromise.start();
});
}
await this.storage.put('started', 'true');
logger.debug('Started payment notifier');
}
Expand Down
4 changes: 0 additions & 4 deletions src/invoice/invoice-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,6 @@ export class InvoiceService {
webhooks: service.webhooks || [],
});

const notifierId = this.env.PAYMENT_NOTIFIER.idFromName(invoice.id);
const paymentNotifier = this.env.PAYMENT_NOTIFIER.get(notifierId);
await paymentNotifier.start();

return SuccessResponse({
id: invoice.id,
pay_address,
Expand Down

0 comments on commit 0b3a44f

Please sign in to comment.