Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/peering-lifecycle-sweep-cursor.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"nostream": patch
---

The peering lifecycle sweep now resumes after the last row it read instead of counting the rows it could not handle. A renewed peer keeps its `period_end` and only gains a `renewal_invoice_id`, so it stayed in the query that found it: the old offset never moved past it, each page re-read the same ten rows, and every peer behind them was never sent a renewal and was later lapsed.
23 changes: 19 additions & 4 deletions src/@types/repositories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,15 @@ export interface IInvoiceRepository {
claimPeeringSettlementAlert(id: string, threshold: number, client?: DatabaseClient): Promise<boolean>
}

/**
* The last row a page of peering payments ended on. Pages are ordered by
* `(period_end, peer_pubkey)` and the next one starts strictly after this.
*/
export interface PeeringPaymentCursor {
periodEnd: Date
peerPubkey: Pubkey
}

export interface IPeeringPaymentRepository {
findByPeer(pubkey: Pubkey, client?: DatabaseClient): Promise<PeeringPayment | undefined>
/** Inserts an unpaid row when one does not exist, so the following lock always finds it. */
Expand All @@ -105,10 +114,16 @@ export interface IPeeringPaymentRepository {
/** Updates only the processor-check diagnostics, so a concurrent settlement is not overwritten. */
recordCheck(pubkey: Pubkey, checkedAt: Date, error: string | null, client?: DatabaseClient): Promise<void>
list(): Promise<PeeringPayment[]>
/** Active or renewal-pending relationships whose period ends by `before`. */
findDueForRenewal(before: Date, limit: number, offset: number): Promise<PeeringPayment[]>
/** Active or renewal-pending relationships whose period has ended by `now`. */
findPeriodEnded(now: Date, limit: number, offset: number): Promise<PeeringPayment[]>
/**
* Active or renewal-pending relationships whose period ends by `before`, ordered by
* `(period_end, peer_pubkey)`. Pass the last row of a page as `after` to continue.
*/
findDueForRenewal(before: Date, limit: number, after?: PeeringPaymentCursor): Promise<PeeringPayment[]>
/**
* Active or renewal-pending relationships whose period has ended by `now`, ordered by
* `(period_end, peer_pubkey)`. Pass the last row of a page as `after` to continue.
*/
findPeriodEnded(now: Date, limit: number, after?: PeeringPaymentCursor): Promise<PeeringPayment[]>
}

export interface IPeeringAttestationRepository {
Expand Down
63 changes: 47 additions & 16 deletions src/repositories/peering-payment-repository.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { DatabaseClient, Pubkey } from '../@types/base'
import { DBPeeringPayment, PeeringPayment, PeeringPaymentDirection, PeeringPaymentStatus } from '../@types/peering'
import { IPeeringPaymentRepository } from '../@types/repositories'
import { IPeeringPaymentRepository, PeeringPaymentCursor } from '../@types/repositories'
import { createLogger } from '../factories/logger-factory'
import { fromDBPeeringPayment, toBuffer } from '../utils/transform'

Expand Down Expand Up @@ -108,31 +108,62 @@ export class PeeringPaymentRepository implements IPeeringPaymentRepository {
return rows.map(fromDBPeeringPayment)
}

public async findDueForRenewal(before: Date, limit: number, offset: number): Promise<PeeringPayment[]> {
const rows = await this.dbClient<DBPeeringPayment>('peering_payments')
.where('direction', PeeringPaymentDirection.SELL)
.whereIn('status', [PeeringPaymentStatus.ACTIVE, PeeringPaymentStatus.RENEWAL_PENDING])
.whereNotNull('period_end')
.where('period_end', '<=', before)
.orderBy('period_end', 'asc')
.offset(offset)
.limit(limit)
public async findDueForRenewal(
before: Date,
limit: number,
after?: PeeringPaymentCursor,
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
): Promise<PeeringPayment[]> {
const rows = await this.pageEndingBy(this.dbClient, before, limit, after)

return rows.map(fromDBPeeringPayment)
}

public async findPeriodEnded(now: Date, limit: number, offset: number): Promise<PeeringPayment[]> {
const rows = await this.dbClient<DBPeeringPayment>('peering_payments')
public async findPeriodEnded(
now: Date,
limit: number,
after?: PeeringPaymentCursor,
): Promise<PeeringPayment[]> {
const rows = await this.pageEndingBy(this.dbClient, now, limit, after)

logger('found %d peering period end(s)', rows.length)

return rows.map(fromDBPeeringPayment)
}

/**
* One page of relationships whose period ends by `before`, ordered by
* `(period_end, peer_pubkey)`. The ordering is part of the contract: the sweep resumes
* after the last row of the page, so it must be total and stable even when rows leave
* the result set between pages.
*/
private async pageEndingBy(
client: DatabaseClient,
before: Date,
limit: number,
after?: PeeringPaymentCursor,
): Promise<DBPeeringPayment[]> {
const query = client<DBPeeringPayment>('peering_payments')
.where('direction', PeeringPaymentDirection.SELL)
.whereIn('status', [PeeringPaymentStatus.ACTIVE, PeeringPaymentStatus.RENEWAL_PENDING])
.whereNotNull('period_end')
.where('period_end', '<=', now)
.where('period_end', '<=', before)
.orderBy('period_end', 'asc')
.offset(offset)
.orderBy('peer_pubkey', 'asc')
.limit(limit)

logger('found %d peering period end(s)', rows.length)
if (after) {
const cursorPubkey = toBuffer(after.peerPubkey)
query.where((builder) =>
builder
.where('period_end', '>', after.periodEnd)
.orWhere((samePeriod) =>
samePeriod
.where('period_end', '=', after.periodEnd)
.andWhere('peer_pubkey', '>', cursorPubkey),
),
)
}

return rows.map(fromDBPeeringPayment)
return query
}
}
58 changes: 38 additions & 20 deletions src/services/peering-billing-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,12 @@ import { DatabaseClient, Pubkey } from '../@types/base'
import { Invoice, InvoicePurpose, InvoiceStatus } from '../@types/invoice'
import { OperatorNotificationEventType } from '../@types/operator-notifications'
import { PeeringAccess, PeeringPayment, PeeringPaymentStatus, PeeringTermSnapshot } from '../@types/peering'
import { IInvoiceRepository, INotificationOutboxRepository, IPeeringPaymentRepository } from '../@types/repositories'
import {
IInvoiceRepository,
INotificationOutboxRepository,
IPeeringPaymentRepository,
PeeringPaymentCursor,
} from '../@types/repositories'
import { IPaymentsService, IPeeringBillingService } from '../@types/services'
import { Settings } from '../@types/settings'
import { Transaction } from '../database/transaction'
Expand All @@ -27,7 +32,10 @@ const isExpiredAt = (invoice: Invoice, now: Date): boolean =>
invoice.expiresAt instanceof Date && invoice.expiresAt.getTime() <= now.getTime()

export class PeeringBillingService implements IPeeringBillingService {
private readonly cursors = { renewal: 0, ended: 0 }
private readonly cursors: Record<'renewal' | 'ended', PeeringPaymentCursor | undefined> = {
renewal: undefined,
ended: undefined,
}

public constructor(
private readonly dbClient: DatabaseClient,
Expand Down Expand Up @@ -339,7 +347,7 @@ export class PeeringBillingService implements IPeeringBillingService {

return this.sweep(
'ended',
(limit, offset) => this.peeringPaymentRepository.findPeriodEnded(now, limit, offset),
(limit, after) => this.peeringPaymentRepository.findPeriodEnded(now, limit, after),
(payment) => this.handlePeriodEnded(payment.peerPubkey, now),
)
}
Expand All @@ -363,11 +371,11 @@ export class PeeringBillingService implements IPeeringBillingService {

const renewalChanged = await this.sweep(
'renewal',
(limit, offset) =>
(limit, after) =>
this.peeringPaymentRepository.findDueForRenewal(
new Date(now.getTime() + PEERING_RENEWAL_LEAD_SECONDS * 1000),
limit,
offset,
after,
),
async (payment) => {
// The ended-period sweep owns already-ended rows; issuing a renewal for one
Expand Down Expand Up @@ -487,40 +495,50 @@ export class PeeringBillingService implements IPeeringBillingService {
await this.enqueueFailed(invoice, 'expired')
}

/**
* Runs one lifecycle pass in pages of `SWEEP_PAGE_SIZE`, resuming after the last row it
* read rather than after the rows it could not handle.
*
* A handled renewal keeps its `period_end` and only gains a `renewal_invoice_id`, so it
* stays in the query that found it. Counting skipped rows as an offset therefore never
* moved past it: a pass re-read the same first page and every peer behind it was starved.
* The cursor is `(period_end, peer_pubkey)` — the query's own ordering — so a row that
* stays behind cannot hold the rest of the list back, and a row that leaves the result
* set cannot make the next page miss one.
*/
private async sweep(
name: 'renewal' | 'ended',
find: (limit: number, offset: number) => Promise<PeeringPayment[]>,
find: (limit: number, after?: PeeringPaymentCursor) => Promise<PeeringPayment[]>,
handle: (payment: PeeringPayment) => Promise<boolean>,
): Promise<number> {
let changed = 0
let skipped = this.cursors[name]
let reachedEnd = false
let cursor = this.cursors[name]

for (let page = 0; page < SWEEP_MAX_PAGES; page++) {
const payments = await find(SWEEP_PAGE_SIZE, skipped)
const payments = await find(SWEEP_PAGE_SIZE, cursor)

for (const payment of payments) {
let handled = false
try {
handled = await handle(payment)
if (await handle(payment)) {
changed++
}
} catch (error) {
logger.error('unable to process peering lifecycle for %s: %o', payment.peerPubkey, error)
}

if (handled) {
changed++
} else {
skipped++
}
}

if (payments.length < SWEEP_PAGE_SIZE) {
reachedEnd = true
const last = payments[payments.length - 1]
// Continue strictly after the last row read, whatever its handler returned.
cursor = last?.periodEnd ? { periodEnd: last.periodEnd, peerPubkey: last.peerPubkey } : undefined

if (payments.length < SWEEP_PAGE_SIZE || cursor === undefined) {
// A short page is the end of the list: the next pass starts from the front again.
cursor = undefined
break
}
}

this.cursors[name] = reachedEnd ? 0 : skipped
this.cursors[name] = cursor

return changed
}
Expand Down
4 changes: 4 additions & 0 deletions test/integration/features/peering/paid-peering-ledger.feature
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ Feature: Paid peering billing ledger
When the peer pays a 21000 msat peering invoice
Then the lifecycle offers a renewal without moving the paid period

Scenario: A renewal backlog larger than one page renews every peer
When a peering renewal backlog of 12 peers is due
Then the lifecycle renews every peer in the backlog

Scenario: A reconnect during a running period does not buy another period
When the peer pays a 21000 msat peering invoice
Then requesting an invoice during the running period creates nothing
Expand Down
90 changes: 82 additions & 8 deletions test/integration/features/peering/paid-peering-ledger.feature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ Before({ tags: '@paid-peering-ledger' }, function (this: World<Record<string, an
this.parameters.peeringPeerPubkeys = []
this.parameters.peeringInvoiceIds = []
this.parameters.peeringUserPubkeys = []
this.parameters.peeringBacklogPeers = []
this.parameters.peeringEvents = []
this.parameters.peeringNotifications = []
this.parameters.peeringEventCreates = 0
Expand Down Expand Up @@ -200,12 +201,22 @@ After({ tags: '@paid-peering-ledger' }, async function (this: World<Record<strin

try {
if (db && peers.length > 0) {
await db('peering_payments')
.whereIn(
'peer_pubkey',
peers.map((peer) => Buffer.from(peer, 'hex')),
)
.delete()
const peerPubkeys = peers.map((peer) => Buffer.from(peer, 'hex'))
// Collect the invoices from the rows before deleting them: a failed assertion in a
// scenario must not leave the invoices it minted behind in the test database.
const billed = await db('peering_payments')
.whereIn('peer_pubkey', peerPubkeys)
.select('current_invoice_id', 'renewal_invoice_id')

for (const row of billed) {
for (const invoiceId of [row.current_invoice_id, row.renewal_invoice_id]) {
if (typeof invoiceId === 'string' && !invoices.includes(invoiceId)) {
invoices.push(invoiceId)
}
}
}

await db('peering_payments').whereIn('peer_pubkey', peerPubkeys).delete()
}
if (db && invoices.length > 0) {
await db('invoices').whereIn('id', invoices).delete()
Expand Down Expand Up @@ -237,6 +248,7 @@ After({ tags: '@paid-peering-ledger' }, async function (this: World<Record<strin
this.parameters.peeringPeerPubkeys = []
this.parameters.peeringInvoiceIds = []
this.parameters.peeringUserPubkeys = []
this.parameters.peeringBacklogPeers = []
this.parameters.peeringInvoice = undefined
this.parameters.peeringPeer = undefined
this.parameters.peeringFirstPeriodEnd = undefined
Expand Down Expand Up @@ -287,10 +299,10 @@ Then(
expect(listed.some((payment) => payment.peerPubkey === peer)).to.equal(true)

const before = new Date(Date.now() + 2 * seconds * 1000)
const due = await repository.findDueForRenewal(before, 10, 0)
const due = await repository.findDueForRenewal(before, 10)
expect(due.some((payment) => payment.peerPubkey === peer)).to.equal(true)

const ended = await repository.findPeriodEnded(before, 10, 0)
const ended = await repository.findPeriodEnded(before, 10)
expect(ended.some((payment) => payment.peerPubkey === peer)).to.equal(true)
},
)
Expand Down Expand Up @@ -347,6 +359,68 @@ Then(
},
)

When(
'a peering renewal backlog of {int} peers is due',
async function (this: World<Record<string, any>>, count: number) {
const db = this.parameters.peeringDb
const now = new Date()
const peers = Array.from({ length: count }, () => randomPeer())

for (const peer of peers) {
this.parameters.peeringPeerPubkeys.push(peer)
this.parameters.peeringUserPubkeys.push(peer)
}

await db('users')
.insert(peers.map((peer) => ({ pubkey: Buffer.from(peer, 'hex') })))
.onConflict('pubkey')
.ignore()
await db('peering_payments').insert(
peers.map((peer) => ({
peer_pubkey: Buffer.from(peer, 'hex'),
direction: 'sell',
status: 'active',
period_start: new Date(now.getTime() - TERM_SECONDS * 1000),
// Running, but inside the renewal lead: the ended-period sweep must not own it.
period_end: new Date(now.getTime() + 60_000),
term_amount_msats: TERM_MSATS.toString(),
term_period_seconds: TERM_SECONDS,
created_at: now,
updated_at: now,
})),
)

this.parameters.peeringBacklogPeers = peers
},
)

Then(
'the lifecycle renews every peer in the backlog',
async function (this: World<Record<string, any>>) {
const billing = this.parameters.peeringBillingService as PeeringBillingService
const db = this.parameters.peeringDb
const peers: string[] = this.parameters.peeringBacklogPeers ?? []

// One pass reads at most SWEEP_PAGE_SIZE rows per page; the backlog is larger than one page.
const changed = await billing.processLifecycle(new Date())
expect(changed).to.be.greaterThanOrEqual(peers.length)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

for (const peer of peers) {
const row = await peerRow(this, peer)
expect(row.status, `peer ${peer} was not renewed`).to.equal('renewal_pending')
expect(row.renewal_invoice_id, `peer ${peer} has no renewal invoice`).to.be.a('string')
}

const renewed = await db('peering_payments')
.whereIn(
'peer_pubkey',
peers.map((peer) => Buffer.from(peer, 'hex')),
)
.where('status', 'renewal_pending')
expect(renewed).to.have.length(peers.length)
},
)

Then(
'requesting an invoice during the running period creates nothing',
async function (this: World<Record<string, any>>) {
Expand Down
Loading
Loading