diff --git a/.changeset/peering-settlement-attempts.md b/.changeset/peering-settlement-attempts.md new file mode 100644 index 000000000..4b698982c --- /dev/null +++ b/.changeset/peering-settlement-attempts.md @@ -0,0 +1,12 @@ +--- +"nostream": patch +--- + +fix(peering): count failed invoice settlements and alert once + +A paid peering invoice whose settlement rolls back is now retried with a +persisted attempt counter and last error. After +`peering.settlementFailureThreshold` failures (default 5), one +`peering.payment.failed` notification is enqueued for the operator, and the +invoice stays in the retry set. Duplicate callbacks and underpayments are not +counted. diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 302dd322e..b7523e37c 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -304,6 +304,7 @@ The settings below are listed in alphabetical order by name. Please keep this ta | peering.scopes[].since | Inclusive lower bound of the feed's time range as a unix timestamp in seconds. Omit for no lower bound. Mutually exclusive with `windowSeconds`. | | peering.scopes[].until | Inclusive upper bound of the feed's time range as a unix timestamp in seconds. Omit for a feed that stays current. Mutually exclusive with `windowSeconds`. | | peering.scopes[].windowSeconds | Rolling window in seconds: the feed covers the most recent `windowSeconds` of events. Mutually exclusive with `since` and `until`. | +| peering.settlementFailureThreshold | Failed settlement attempts before one operator alert is enqueued for a completed-but-unconfirmed paid peering invoice. The invoice is still retried. Defaults to 5. | | peering.terms[].amount | Fee amount charged per peering period, denominated in `unit`. | | peering.terms[].period | Peering period in seconds. | | peering.terms[].unit | Fee unit (for example `msats`). An empty `terms` list means settlement-free peering. | diff --git a/docs/PEERING.md b/docs/PEERING.md index 9d1715c08..fd7ddaeeb 100644 --- a/docs/PEERING.md +++ b/docs/PEERING.md @@ -266,7 +266,16 @@ The invoice travels over the authenticated relay connection: An expired invoice is retired and reissued on request after a short cooldown. Before denying access, the relay rechecks a pending invoice with the processor, -so a missed webhook heals on its own. A peer can always authenticate and ask for +so a missed webhook heals on its own. + +A completed peering invoice whose settlement transaction rolled back stays +retryable. Every failed settlement increments `settlement_attempts` and stores +`last_settlement_error` on the invoice; the maintenance worker keeps retrying. +After `peering.settlementFailureThreshold` failures (default 5), the relay +enqueues one `peering.payment.failed` operator notification and keeps retrying. +Duplicate callbacks and underpayments are not counted as settlement failures. +Only completed invoices that are still unconfirmed are counted; a pending row +checked through the processor recheck path stays on the pending page. A peer can always authenticate and ask for its invoice, even while lapsed, but cannot read the feed. Billing state is stored in `peering_payments`, one row per peer and direction diff --git a/migrations/20261127_120000_add_invoice_settlement_attempts.js b/migrations/20261127_120000_add_invoice_settlement_attempts.js new file mode 100644 index 000000000..8a78921a5 --- /dev/null +++ b/migrations/20261127_120000_add_invoice_settlement_attempts.js @@ -0,0 +1,17 @@ +exports.up = async function (knex) { + await knex.schema.alterTable('invoices', (table) => { + table.integer('settlement_attempts').notNullable().defaultTo(0) + table.text('last_settlement_error').nullable() + table.timestamp('last_settlement_attempt_at', { useTz: true }).nullable() + table.timestamp('settlement_alerted_at', { useTz: true }).nullable() + }) +} + +exports.down = async function (knex) { + await knex.schema.alterTable('invoices', (table) => { + table.dropColumn('settlement_alerted_at') + table.dropColumn('last_settlement_attempt_at') + table.dropColumn('last_settlement_error') + table.dropColumn('settlement_attempts') + }) +} diff --git a/resources/admin/assets/notifications.js b/resources/admin/assets/notifications.js index bf0ed61ab..13c8d1ddc 100644 --- a/resources/admin/assets/notifications.js +++ b/resources/admin/assets/notifications.js @@ -61,6 +61,7 @@ 'peering.invoice.created': true, 'peering.invoice.paid': true, 'peering.invoice.failed': true, + 'peering.payment.failed': true, 'peering.access.lapsed': true, 'settings.changed': true, 'relay.restarted': false, diff --git a/resources/admin/dashboard.html b/resources/admin/dashboard.html index 50950decb..3f89febe6 100644 --- a/resources/admin/dashboard.html +++ b/resources/admin/dashboard.html @@ -468,6 +468,12 @@

Operator notifications

+
+
+ + +
+
diff --git a/resources/default-settings.yaml b/resources/default-settings.yaml index 67f6356bb..5eb07fa15 100755 --- a/resources/default-settings.yaml +++ b/resources/default-settings.yaml @@ -195,6 +195,10 @@ peering: # Configured peers are already trusted by pubkey, so their request does not # need to meet minRequestPowDifficulty. Set false to require it anyway. waiveRequestPowForConfiguredPeers: true + # A completed-but-unconfirmed paid peering invoice is retried by the + # maintenance worker. After this many failed settlements, enqueue one + # operator alert (peering.payment.failed) and keep retrying. + settlementFailureThreshold: 5 # Feeds this relay is willing to serve. Each scope lists event kinds and, # optionally, an absolute time range (unix seconds) or a rolling window. # At least one scope is required when peering is enabled. @@ -494,6 +498,7 @@ admin: peering.invoice.created: true peering.invoice.paid: true peering.invoice.failed: true + peering.payment.failed: true peering.access.lapsed: true settings.changed: true relay.restarted: false diff --git a/src/@types/invoice.ts b/src/@types/invoice.ts index f6cd05133..f1beb1a12 100644 --- a/src/@types/invoice.ts +++ b/src/@types/invoice.ts @@ -42,6 +42,12 @@ export interface Invoice { termAmountMsats?: bigint | null /** Peering period length in seconds for this invoice. */ termPeriodSeconds?: number | null + /** Failed peering settlement attempts for a completed-but-unconfirmed invoice. */ + settlementAttempts?: number + lastSettlementError?: string | null + lastSettlementAttemptAt?: Date | null + /** Set once the threshold alert has been enqueued. */ + settlementAlertedAt?: Date | null } export interface LnurlInvoice extends Invoice { @@ -68,4 +74,8 @@ export interface DBInvoice { period_end?: Date | null term_amount_msats?: string | null term_period_seconds?: number | null + settlement_attempts?: number + last_settlement_error?: string | null + last_settlement_attempt_at?: Date | null + settlement_alerted_at?: Date | null } diff --git a/src/@types/operator-notifications.ts b/src/@types/operator-notifications.ts index 31395b476..99e87a93f 100644 --- a/src/@types/operator-notifications.ts +++ b/src/@types/operator-notifications.ts @@ -5,6 +5,7 @@ export enum OperatorNotificationEventType { PEERING_INVOICE_CREATED = 'peering.invoice.created', PEERING_INVOICE_PAID = 'peering.invoice.paid', PEERING_INVOICE_FAILED = 'peering.invoice.failed', + PEERING_PAYMENT_FAILED = 'peering.payment.failed', PEERING_ACCESS_LAPSED = 'peering.access.lapsed', SETTINGS_CHANGED = 'settings.changed', RELAY_RESTARTED = 'relay.restarted', @@ -33,6 +34,7 @@ export interface OperatorNotificationEventToggles { 'peering.invoice.created'?: boolean 'peering.invoice.paid'?: boolean 'peering.invoice.failed'?: boolean + 'peering.payment.failed'?: boolean 'peering.access.lapsed'?: boolean 'settings.changed'?: boolean 'relay.restarted'?: boolean diff --git a/src/@types/repositories.ts b/src/@types/repositories.ts index 138df2d00..8b6a6a14d 100644 --- a/src/@types/repositories.ts +++ b/src/@types/repositories.ts @@ -82,6 +82,17 @@ export interface IInvoiceRepository { * maintenance worker can retry them instead of stranding a paid peer. */ findUnconfirmedPeeringInvoices(limit?: number, offset?: number, client?: DatabaseClient): Promise + /** Increments the failed settlement counter for a completed peering invoice. */ + recordPeeringSettlementFailure( + id: string, + error: string, + client?: DatabaseClient, + ): Promise<{ attempts: number; lastError: string } | undefined> + /** + * Claims the one-time alert for a completed peering invoice at the threshold. + * The caller enqueues the outbox row in the same transaction. + */ + claimPeeringSettlementAlert(id: string, threshold: number, client?: DatabaseClient): Promise } export interface IPeeringPaymentRepository { diff --git a/src/@types/settings.ts b/src/@types/settings.ts index 690205df8..54b770b6d 100644 --- a/src/@types/settings.ts +++ b/src/@types/settings.ts @@ -640,6 +640,11 @@ export interface PeeringSettings { * pubkey. Defaults to true: configured trust is the v1 path. */ waiveRequestPowForConfiguredPeers?: boolean + /** + * Failed settlement attempts before an operator alert is enqueued for a + * completed-but-unconfirmed peering invoice. Defaults to 5. + */ + settlementFailureThreshold?: number /** * Feeds this relay offers. At least one scope is required when enabled. */ diff --git a/src/repositories/invoice-repository.ts b/src/repositories/invoice-repository.ts index cd7428ab2..6db761d49 100644 --- a/src/repositories/invoice-repository.ts +++ b/src/repositories/invoice-repository.ts @@ -91,6 +91,52 @@ export class InvoiceRepository implements IInvoiceRepository { return dbInvoices.map(fromDBInvoice) } + public async recordPeeringSettlementFailure( + id: string, + error: string, + client: DatabaseClient = this.dbClient, + ): Promise<{ attempts: number; lastError: string } | undefined> { + // Only the completed retry contract is counted. A PENDING row that the + // recheck path asked the processor about stays on the pending page. + const now = new Date() + const [row] = await client('invoices') + .where({ id, purpose: InvoicePurpose.PEERING, status: InvoiceStatus.COMPLETED }) + .whereNull('confirmed_at') + .update({ + settlement_attempts: client.raw('settlement_attempts + 1'), + last_settlement_error: error, + last_settlement_attempt_at: now, + updated_at: now, + }) + .returning(['settlement_attempts', 'last_settlement_error']) + + if (!row) { + return undefined + } + + return { + attempts: Number(row.settlement_attempts ?? 0), + lastError: row.last_settlement_error ?? error, + } + } + + public async claimPeeringSettlementAlert( + id: string, + threshold: number, + client: DatabaseClient = this.dbClient, + ): Promise { + const now = new Date() + const [claimed] = await client('invoices') + .where({ id, purpose: InvoicePurpose.PEERING, status: InvoiceStatus.COMPLETED }) + .whereNull('confirmed_at') + .whereNull('settlement_alerted_at') + .where('settlement_attempts', '>=', threshold) + .update({ settlement_alerted_at: now, updated_at: now }) + .returning(['id']) + + return Boolean(claimed) + } + public updateStatus(invoice: Invoice, client: DatabaseClient = this.dbClient): Promise { logger('updating invoice status: %o', invoice) diff --git a/src/schemas/admin-notifications-schema.ts b/src/schemas/admin-notifications-schema.ts index 7f5a0e26c..dbc065446 100644 --- a/src/schemas/admin-notifications-schema.ts +++ b/src/schemas/admin-notifications-schema.ts @@ -24,6 +24,7 @@ export const adminNotificationsPatchBodySchema = z 'peering.invoice.created': z.boolean().optional(), 'peering.invoice.paid': z.boolean().optional(), 'peering.invoice.failed': z.boolean().optional(), + 'peering.payment.failed': z.boolean().optional(), 'peering.access.lapsed': z.boolean().optional(), 'settings.changed': z.boolean().optional(), 'relay.restarted': z.boolean().optional(), diff --git a/src/services/payments-service.ts b/src/services/payments-service.ts index 8f264157b..6eab6165a 100644 --- a/src/services/payments-service.ts +++ b/src/services/payments-service.ts @@ -305,6 +305,8 @@ export class PaymentsService implements IPaymentsService { logger('confirm invoice %s: %O', invoice.id, invoice) const transaction = new Transaction(this.dbClient) + let stored: Invoice | undefined + let peeringSettlementStarted = false try { if (!invoice.confirmedAt) { @@ -325,7 +327,14 @@ export class PaymentsService implements IPaymentsService { // whether the invoice was already confirmed come from the stored invoice. This read must // happen before confirmation and must not be gated on subscriptions: peering invoices // need it even when subscription plans are off. - const stored = await this.invoiceRepository.findById(invoice.id, transaction.transaction) + stored = await this.invoiceRepository.findById(invoice.id, transaction.transaction) + + // A completed, unconfirmed peering invoice is the retry contract. A + // recheck-path PENDING row is excluded again by the repository status + // filter, so it cannot consume the alert. + if (stored?.purpose === InvoicePurpose.PEERING && !stored.confirmedAt) { + peeringSettlementStarted = true + } await this.invoiceRepository.confirmInvoice( invoice.id, @@ -348,6 +357,7 @@ export class PaymentsService implements IPaymentsService { // a redelivered older callback must not buy another period even if the peer has // since settled a newer invoice. if (stored.confirmedAt) { + peeringSettlementStarted = false await transaction.commit() return } @@ -355,10 +365,17 @@ export class PaymentsService implements IPaymentsService { const result = await this.settlePeeringInvoice(invoice, stored, amountPaidMsat, transaction.transaction) if (result.duplicate) { + peeringSettlementStarted = false await transaction.commit() return } + if (!result.activated) { + // Underpayments are a deterministic business outcome, not a failed + // settlement. A later enqueue/commit error must not count them. + peeringSettlementStarted = false + } + await this.notificationOutboxRepository.enqueue( result.activated ? OperatorNotificationEventType.PEERING_INVOICE_PAID @@ -427,10 +444,75 @@ export class PaymentsService implements IPaymentsService { logger.error('Unable to confirm invoice. Reason:', error) await transaction.rollback() + if (peeringSettlementStarted && stored) { + await this.recordPeeringSettlementFailure(stored, error) + } + throw error } } + /** + * A completed peering invoice can keep failing settlement (missing term + * snapshot, missing peer row, a database error). Record every failure outside + * the rolled-back settlement transaction and alert the operator once when the + * configured threshold is reached. The invoice stays in the retry set. + */ + private async recordPeeringSettlementFailure(invoice: Invoice, error: unknown): Promise { + const message = error instanceof Error ? error.message : String(error) + const threshold = this.settings().peering?.settlementFailureThreshold ?? 5 + + let attempt: { attempts: number; lastError: string } | undefined + try { + attempt = await this.invoiceRepository.recordPeeringSettlementFailure(invoice.id, message) + } catch (recordError) { + logger.error('Unable to record peering settlement failure for %s: %o', invoice.id, recordError) + return + } + + if (!attempt || attempt.attempts < threshold) { + return + } + + // The claim and the outbox row commit together: a crash between the two + // cannot leave a marker without an alert. A failed transaction rolls the + // claim back, so the next attempt retries it. + const transaction = new Transaction(this.dbClient) + try { + await transaction.begin() + const claimed = await this.invoiceRepository.claimPeeringSettlementAlert( + invoice.id, + threshold, + transaction.transaction, + ) + if (!claimed) { + await transaction.rollback() + return + } + + await this.notificationOutboxRepository.enqueue( + OperatorNotificationEventType.PEERING_PAYMENT_FAILED, + { + invoiceId: invoice.id, + pubkey: invoice.pubkey, + attempts: attempt.attempts, + lastError: attempt.lastError, + amountRequested: invoice.amountRequested.toString(), + unit: invoice.unit, + }, + transaction.transaction, + ) + await transaction.commit() + } catch (alertError) { + try { + await transaction.rollback() + } catch (rollbackError) { + logger.error('Unable to roll back peering settlement alert for %s: %o', invoice.id, rollbackError) + } + logger.error('Unable to enqueue peering.payment.failed notification for %s: %o', invoice.id, alertError) + } + } + private async settlePeeringInvoice( invoice: Invoice, stored: Invoice, diff --git a/src/utils/settings-config.ts b/src/utils/settings-config.ts index 5817ab116..d2220b56e 100644 --- a/src/utils/settings-config.ts +++ b/src/utils/settings-config.ts @@ -1189,6 +1189,16 @@ const validatePeering = (settings: Settings, issues: ValidationIssue[]): void => }) } + if (peering.settlementFailureThreshold !== undefined) { + const threshold = peering.settlementFailureThreshold + if (!(typeof threshold === 'number' && Number.isInteger(threshold) && threshold > 0)) { + issues.push({ + path: 'peering.settlementFailureThreshold', + message: 'must be a positive integer', + }) + } + } + const endpoint = typeof peering.endpoint === 'string' ? peering.endpoint.trim() : '' if (endpoint) { try { diff --git a/src/utils/transform.ts b/src/utils/transform.ts index 2f083a927..1d3b29297 100644 --- a/src/utils/transform.ts +++ b/src/utils/transform.ts @@ -143,6 +143,10 @@ export const fromDBInvoice = applySpec({ pipe(prop('term_amount_msats') as () => string, toBigInt), ), termPeriodSeconds: prop('term_period_seconds'), + settlementAttempts: prop('settlement_attempts'), + lastSettlementError: prop('last_settlement_error'), + lastSettlementAttemptAt: prop('last_settlement_attempt_at'), + settlementAlertedAt: prop('settlement_alerted_at'), }) export const fromDBPeeringPayment = applySpec({ diff --git a/test/integration/features/peering/peering-settlement-retries.feature b/test/integration/features/peering/peering-settlement-retries.feature new file mode 100644 index 000000000..b8359d6dc --- /dev/null +++ b/test/integration/features/peering/peering-settlement-retries.feature @@ -0,0 +1,9 @@ +@peering-settlement-retries +Feature: Peering settlement retries + + Scenario: Failed settlements are counted and alert exactly once + Given a completed peering invoice without a term snapshot + When its settlement fails twice + Then the invoice has two settlement attempts and one alert + When its settlement fails once more + Then the invoice still has only one settlement alert diff --git a/test/integration/features/peering/peering-settlement-retries.feature.ts b/test/integration/features/peering/peering-settlement-retries.feature.ts new file mode 100644 index 000000000..02958f3c7 --- /dev/null +++ b/test/integration/features/peering/peering-settlement-retries.feature.ts @@ -0,0 +1,170 @@ +import { After, Before, Given, Then, When, World } from '@cucumber/cucumber' +import { expect } from 'chai' +import { randomBytes, randomUUID } from 'node:crypto' + +import { Invoice, InvoicePurpose, InvoiceStatus, InvoiceUnit } from '../../../../src/@types/invoice' +import { Settings } from '../../../../src/@types/settings' +import { getMasterDbClient } from '../../../../src/database/client' +import { InvoiceRepository } from '../../../../src/repositories/invoice-repository' +import { NotificationOutboxRepository } from '../../../../src/repositories/notification-outbox-repository' +import { PeeringPaymentRepository } from '../../../../src/repositories/peering-payment-repository' +import { PaymentsService } from '../../../../src/services/payments-service' + +const TERM_MSATS = 21000n +const TERM_SECONDS = 60 +const THRESHOLD = 2 + +const rejects = async (promise: Promise): Promise => { + try { + await promise + } catch { + return + } + + throw new Error('expected the settlement to fail') +} + +const makeCompletedInvoice = (id: string, pubkey: string): Invoice => { + const now = new Date() + return { + id, + pubkey, + bolt11: 'lnbc1settlementretry', + amountRequested: TERM_MSATS, + amountPaid: TERM_MSATS, + unit: InvoiceUnit.MSATS, + status: InvoiceStatus.COMPLETED, + description: 'settlement retry test', + confirmedAt: now, + expiresAt: new Date(now.getTime() + 3_600_000), + updatedAt: now, + createdAt: now, + purpose: InvoicePurpose.PEERING, + planId: null, + termAmountMsats: TERM_MSATS, + termPeriodSeconds: TERM_SECONDS, + } +} + +Before({ tags: '@peering-settlement-retries' }, function (this: World>) { + const db = getMasterDbClient() + const invoiceRepository = new InvoiceRepository(db) + const peeringPaymentRepository = new PeeringPaymentRepository(db) + const notificationOutboxRepository = new NotificationOutboxRepository(db) + const settings = { + info: { name: 'Retry Relay', relay_url: 'wss://retry.example.com' }, + payments: { enabled: true, invoiceExpirySeconds: 3600 }, + peering: { enabled: true, settlementFailureThreshold: THRESHOLD }, + } as Settings + + const service = new PaymentsService( + db, + {} as any, + {} as any, + invoiceRepository, + {} as any, + () => settings, + notificationOutboxRepository, + undefined, + peeringPaymentRepository, + ) + + this.parameters.settlementDb = db + this.parameters.settlementService = service + this.parameters.settlementInvoiceId = randomUUID() + this.parameters.settlementPeer = randomBytes(32).toString('hex') +}) + +After({ tags: '@peering-settlement-retries' }, async function (this: World>) { + const db = this.parameters.settlementDb + const id = this.parameters.settlementInvoiceId + if (db) { + await db('invoices').where({ id }).delete() + await db('notification_outbox') + .where({ event_type: 'peering.payment.failed' }) + .whereRaw("payload->>'invoiceId' = ?", [id]) + .delete() + } + this.parameters.settlementDb = undefined + this.parameters.settlementService = undefined + this.parameters.settlementInvoiceId = undefined + this.parameters.settlementPeer = undefined +}) + +Given('a completed peering invoice without a term snapshot', async function (this: World>) { + const db = this.parameters.settlementDb + const id = this.parameters.settlementInvoiceId as string + const peer = this.parameters.settlementPeer as string + const now = new Date() + + await db('invoices').insert({ + id, + pubkey: Buffer.from(peer, 'hex'), + bolt11: 'lnbc1settlementretry', + amount_requested: TERM_MSATS.toString(), + amount_paid: TERM_MSATS.toString(), + unit: InvoiceUnit.MSATS, + status: InvoiceStatus.COMPLETED, + description: 'settlement retry test', + confirmed_at: null, + expires_at: new Date(now.getTime() + 3_600_000), + updated_at: now, + created_at: now, + verify_url: null, + purpose: InvoicePurpose.PEERING, + plan_id: null, + period_start: null, + period_end: null, + term_amount_msats: null, + term_period_seconds: TERM_SECONDS, + }) + + this.parameters.settlementInvoice = makeCompletedInvoice(id, peer) +}) + +When('its settlement fails twice', async function (this: World>) { + const service = this.parameters.settlementService as PaymentsService + const invoice = this.parameters.settlementInvoice as Invoice + + await rejects(service.confirmInvoice(invoice)) + await rejects(service.confirmInvoice(invoice)) +}) + +Then('the invoice has two settlement attempts and one alert', async function (this: World>) { + const db = this.parameters.settlementDb + const id = this.parameters.settlementInvoiceId as string + const row = await db('invoices').where({ id }).first() + + expect(row.settlement_attempts).to.equal(2) + expect(row.last_settlement_error).to.include('no term snapshot') + expect(row.confirmed_at).to.equal(null) + expect(row.settlement_alerted_at).to.be.instanceOf(Date) + + const alerts = await db('notification_outbox') + .where({ event_type: 'peering.payment.failed' }) + .whereRaw("payload->>'invoiceId' = ?", [id]) + expect(alerts).to.have.length(1) + expect(alerts[0].payload).to.include({ + invoiceId: id, + attempts: 2, + }) +}) + +When('its settlement fails once more', async function (this: World>) { + const service = this.parameters.settlementService as PaymentsService + const invoice = this.parameters.settlementInvoice as Invoice + + await rejects(service.confirmInvoice(invoice)) +}) + +Then('the invoice still has only one settlement alert', async function (this: World>) { + const db = this.parameters.settlementDb + const id = this.parameters.settlementInvoiceId as string + const row = await db('invoices').where({ id }).first() + const alerts = await db('notification_outbox') + .where({ event_type: 'peering.payment.failed' }) + .whereRaw("payload->>'invoiceId' = ?", [id]) + + expect(row.settlement_attempts).to.equal(3) + expect(alerts).to.have.length(1) +}) diff --git a/test/unit/repositories/invoice-repository.spec.ts b/test/unit/repositories/invoice-repository.spec.ts index 79e85cc7f..15c430c93 100644 --- a/test/unit/repositories/invoice-repository.spec.ts +++ b/test/unit/repositories/invoice-repository.spec.ts @@ -8,6 +8,7 @@ import { DatabaseClient } from '../../../src/@types/base' import { Invoice, InvoicePurpose, InvoiceStatus, InvoiceUnit } from '../../../src/@types/invoice' import { IInvoiceRepository } from '../../../src/@types/repositories' import { InvoiceRepository } from '../../../src/repositories/invoice-repository' +import { createRecordingKnex } from './recording-knex' chai.use(sinonChai) chai.use(chaiAsPromised) @@ -414,3 +415,48 @@ describe('InvoiceRepository', () => { }) }) }) + +describe('InvoiceRepository settlement attempts', () => { + it('counts a completed unconfirmed failure and returns the attempts', async () => { + const recording = createRecordingKnex() + const repository = new InvoiceRepository(recording.db as any) + recording.respondWith([{ settlement_attempts: 2, last_settlement_error: 'missing peer' }]) + + const result = await repository.recordPeeringSettlementFailure('invoice-id', 'missing peer') + + expect(result).to.deep.equal({ attempts: 2, lastError: 'missing peer' }) + expect(recording.queries[0].sql).to.include('"settlement_attempts"') + expect(recording.queries[0].sql).to.include('"last_settlement_error"') + expect(recording.queries[0].sql).to.include('"status" =') + expect(recording.queries[0].sql).to.include('"confirmed_at" is null') + }) + + it('claims the one-time alert at the threshold', async () => { + const recording = createRecordingKnex() + const repository = new InvoiceRepository(recording.db as any) + recording.respondWith([{ id: 'invoice-id' }]) + + expect(await repository.claimPeeringSettlementAlert('invoice-id', 5)).to.equal(true) + expect(recording.queries[0].sql).to.include('"settlement_alerted_at"') + expect(recording.queries[0].sql).to.include('"settlement_alerted_at" is null') + expect(recording.queries[0].sql).to.include('"status" =') + expect(recording.queries[0].sql).to.include('"confirmed_at" is null') + expect(recording.queries[0].sql).to.include('"settlement_attempts" >=') + }) + + it('does not claim the alert when another caller already did', async () => { + const recording = createRecordingKnex() + const repository = new InvoiceRepository(recording.db as any) + recording.respondWith([]) + + expect(await repository.claimPeeringSettlementAlert('invoice-id', 5)).to.equal(false) + }) + + it('returns undefined when the invoice is missing or no longer eligible', async () => { + const recording = createRecordingKnex() + const repository = new InvoiceRepository(recording.db as any) + recording.respondWith([]) + + expect(await repository.recordPeeringSettlementFailure('missing', 'error')).to.equal(undefined) + }) +}) diff --git a/test/unit/services/payments-service.spec.ts b/test/unit/services/payments-service.spec.ts index 93ff6da87..313f2a72c 100644 --- a/test/unit/services/payments-service.spec.ts +++ b/test/unit/services/payments-service.spec.ts @@ -72,6 +72,11 @@ describe('PaymentsService', () => { updateStatus: sandbox.stub(), confirmInvoice: sandbox.stub().resolves(), updatePeriod: sandbox.stub().resolves(), + recordPeeringSettlementFailure: sandbox.stub().resolves({ + attempts: 1, + lastError: 'settlement failed', + }), + claimPeeringSettlementAlert: sandbox.stub().resolves(false), } eventRepository = { @@ -1161,6 +1166,193 @@ describe('PaymentsService', () => { ) }) + it('records a failed settlement and rethrows without alerting below the threshold', async () => { + settings.returns({ + payments: { enabled: true, feeSchedules: { admission: [] } }, + peering: { settlementFailureThreshold: 5 }, + }) + invoiceRepository.findById.resolves( + stubInvoice({ + purpose: InvoicePurpose.PEERING, + termAmountMsats: 0n, + termPeriodSeconds: 2592000, + }), + ) + + await expect(peeringService.confirmInvoice(makeCompletedInvoice())).to.be.rejectedWith('no term snapshot') + + expect(invoiceRepository.recordPeeringSettlementFailure).to.have.been.calledWith( + 'invoice-id', + Sinon.match('no term snapshot'), + ) + expect(invoiceRepository.claimPeeringSettlementAlert).not.to.have.been.called + expect(notificationOutboxRepository.enqueue).not.to.have.been.calledWith( + OperatorNotificationEventType.PEERING_PAYMENT_FAILED, + ) + }) + + it('enqueues one settlement alert when the threshold is reached', async () => { + settings.returns({ + payments: { enabled: true, feeSchedules: { admission: [] } }, + peering: { settlementFailureThreshold: 5 }, + }) + invoiceRepository.findById.resolves( + stubInvoice({ + purpose: InvoicePurpose.PEERING, + termAmountMsats: 0n, + termPeriodSeconds: 2592000, + }), + ) + invoiceRepository.recordPeeringSettlementFailure.resolves({ + attempts: 5, + lastError: 'no term snapshot', + }) + invoiceRepository.claimPeeringSettlementAlert.resolves(true) + + await expect(peeringService.confirmInvoice(makeCompletedInvoice())).to.be.rejectedWith('no term snapshot') + + expect(invoiceRepository.claimPeeringSettlementAlert).to.have.been.calledWith( + 'invoice-id', + 5, + mockTrx, + ) + expect(notificationOutboxRepository.enqueue).to.have.been.calledWith( + OperatorNotificationEventType.PEERING_PAYMENT_FAILED, + Sinon.match({ + invoiceId: 'invoice-id', + pubkey: 'pubkey1234', + attempts: 5, + lastError: 'no term snapshot', + }), + mockTrx, + ) + }) + + it('rolls back the claim when the notification cannot be enqueued', async () => { + settings.returns({ + payments: { enabled: true, feeSchedules: { admission: [] } }, + peering: { settlementFailureThreshold: 5 }, + }) + invoiceRepository.findById.resolves( + stubInvoice({ + purpose: InvoicePurpose.PEERING, + termAmountMsats: 0n, + termPeriodSeconds: 2592000, + }), + ) + invoiceRepository.recordPeeringSettlementFailure.resolves({ + attempts: 5, + lastError: 'no term snapshot', + }) + invoiceRepository.claimPeeringSettlementAlert.resolves(true) + notificationOutboxRepository.enqueue.rejects(new Error('outbox down')) + + await expect(peeringService.confirmInvoice(makeCompletedInvoice())).to.be.rejectedWith('no term snapshot') + + expect(mockTrx.rollback).to.have.been.called + }) + + it('keeps retrying without a second claim when the alert was already sent', async () => { + settings.returns({ + payments: { enabled: true, feeSchedules: { admission: [] } }, + peering: { settlementFailureThreshold: 5 }, + }) + invoiceRepository.findById.resolves( + stubInvoice({ + purpose: InvoicePurpose.PEERING, + termAmountMsats: 0n, + termPeriodSeconds: 2592000, + }), + ) + invoiceRepository.recordPeeringSettlementFailure.resolves({ + attempts: 6, + lastError: 'no term snapshot', + }) + invoiceRepository.claimPeeringSettlementAlert.resolves(false) + + await expect(peeringService.confirmInvoice(makeCompletedInvoice())).to.be.rejectedWith('no term snapshot') + + expect(notificationOutboxRepository.enqueue).not.to.have.been.calledWith( + OperatorNotificationEventType.PEERING_PAYMENT_FAILED, + ) + }) + + it('counts a confirmation-write failure for an eligible peering invoice', async () => { + settings.returns({ + payments: { enabled: true, feeSchedules: { admission: [] } }, + peering: { settlementFailureThreshold: 5 }, + }) + invoiceRepository.findById.resolves( + stubInvoice({ + purpose: InvoicePurpose.PEERING, + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + }), + ) + invoiceRepository.confirmInvoice.rejects(new Error('serialization failure')) + + await expect(peeringService.confirmInvoice(makeCompletedInvoice())).to.be.rejectedWith( + 'serialization failure', + ) + + expect(invoiceRepository.recordPeeringSettlementFailure).to.have.been.calledWith( + 'invoice-id', + 'serialization failure', + ) + }) + + it('does not count an underpayment when its notification fails', async () => { + settings.returns({ + payments: { enabled: true, feeSchedules: { admission: [] } }, + peering: { settlementFailureThreshold: 5 }, + }) + invoiceRepository.findById.resolves( + stubInvoice({ + purpose: InvoicePurpose.PEERING, + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + }), + ) + notificationOutboxRepository.enqueue.rejects(new Error('outbox down')) + + await expect( + peeringService.confirmInvoice(makeCompletedInvoice({ amountPaid: 1000n })), + ).to.be.rejectedWith('outbox down') + + expect(invoiceRepository.recordPeeringSettlementFailure).not.to.have.been.called + }) + + it('does not count a duplicate callback as a settlement failure', async () => { + settings.returns({ payments: { enabled: true, feeSchedules: { admission: [] } } }) + invoiceRepository.findById.resolves( + stubInvoice({ + purpose: InvoicePurpose.PEERING, + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + }), + ) + peeringPaymentRepository.lockByPeer.resolves(peeringRow({ lastSettledInvoiceId: 'invoice-id' })) + + await peeringService.confirmInvoice(makeCompletedInvoice()) + + expect(invoiceRepository.recordPeeringSettlementFailure).not.to.have.been.called + }) + + it('does not count an underpayment as a settlement failure', async () => { + settings.returns({ payments: { enabled: true, feeSchedules: { admission: [] } } }) + invoiceRepository.findById.resolves( + stubInvoice({ + purpose: InvoicePurpose.PEERING, + termAmountMsats: 21000n, + termPeriodSeconds: 2592000, + }), + ) + + await peeringService.confirmInvoice(makeCompletedInvoice({ amountPaid: 1000n })) + + expect(invoiceRepository.recordPeeringSettlementFailure).not.to.have.been.called + }) + it('publishes peering invoice events with the peering and invoice-id tags', async () => { settings.returns({ info: { relay_url: 'wss://relay.example.com' } }) const invoice = stubInvoice({ diff --git a/test/unit/utils/settings-config.spec.ts b/test/unit/utils/settings-config.spec.ts index 2afe73643..4b9623853 100644 --- a/test/unit/utils/settings-config.spec.ts +++ b/test/unit/utils/settings-config.spec.ts @@ -409,6 +409,13 @@ describe('settings-config', () => { expect(issues.some((issue) => issue.path === 'peering.peers[0].ownerPubkey')).to.equal(true) }) + it('requires a positive settlement failure threshold', () => { + expect(peeringIssues({ ...settlementFreePeering, settlementFailureThreshold: 3 })).to.deep.equal([]) + + const issues = peeringIssues({ ...settlementFreePeering, settlementFailureThreshold: 0 }) + expect(issues.some((issue) => issue.path === 'peering.settlementFailureThreshold')).to.equal(true) + }) + it('accepts configured peers by hex or npub', () => { expect( peeringIssues({