-
Notifications
You must be signed in to change notification settings - Fork 231
Expand file tree
/
Copy pathmaintenance-worker.ts
More file actions
162 lines (132 loc) · 5.13 KB
/
maintenance-worker.ts
File metadata and controls
162 lines (132 loc) · 5.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import { mergeDeepLeft, path, pipe } from 'ramda'
import { IRunnable } from '../@types/base'
import { createLogger } from '../factories/logger-factory'
import { delayMs } from '../utils/misc'
import { INip05VerificationRepository } from '../@types/repositories'
import { InvoiceStatus } from '../@types/invoice'
import { IPaymentsService } from '../@types/services'
import { Nip05Verification } from '../@types/nip05'
import { Settings } from '../@types/settings'
import { verifyNip05Identifier } from '../utils/nip05'
const UPDATE_INVOICE_INTERVAL = 60000
const NIP05_REVERIFICATION_BATCH_SIZE = 50
const debug = createLogger('maintenance-worker')
export class MaintenanceWorker implements IRunnable {
private interval: NodeJS.Timeout | undefined
public constructor(
private readonly process: NodeJS.Process,
private readonly paymentsService: IPaymentsService,
private readonly settings: () => Settings,
private readonly nip05VerificationRepository: INip05VerificationRepository,
) {
this.process
.on('SIGINT', this.onExit.bind(this))
.on('SIGHUP', this.onExit.bind(this))
.on('SIGTERM', this.onExit.bind(this))
.on('uncaughtException', this.onError.bind(this))
.on('unhandledRejection', this.onError.bind(this))
}
public run(): void {
this.interval = setInterval(() => this.onSchedule(), UPDATE_INVOICE_INTERVAL)
}
private async onSchedule(): Promise<void> {
const currentSettings = this.settings()
await this.processNip05Reverifications(currentSettings)
if (!path(['payments','enabled'], currentSettings)) {
return
}
const invoices = await this.paymentsService.getPendingInvoices()
debug('found %d pending invoices', invoices.length)
const delay = () => delayMs(100 + Math.floor(Math.random() * 10))
let successful = 0
for (const invoice of invoices) {
try {
debug('getting invoice %s from payment processor: %o', invoice.id, invoice)
const updatedInvoice = await this.paymentsService.getInvoiceFromPaymentsProcessor(invoice)
await delay()
debug('updating invoice status %s: %o', updatedInvoice.id, updatedInvoice)
if (typeof updatedInvoice.id !== 'string' || typeof updatedInvoice.status !== 'string') {
continue
}
const { id, status } = updatedInvoice
await this.paymentsService.updateInvoiceStatus({ id, status })
if (
invoice.status !== updatedInvoice.status
&& updatedInvoice.status == InvoiceStatus.COMPLETED
&& updatedInvoice.confirmedAt
) {
debug('confirming invoice %s & notifying %s', invoice.id, invoice.pubkey)
const update = pipe(
mergeDeepLeft(updatedInvoice),
mergeDeepLeft({ amountPaid: invoice.amountRequested }),
)(invoice)
await Promise.all([
this.paymentsService.confirmInvoice(update),
this.paymentsService.sendInvoiceUpdateNotification(update),
])
await delay()
}
successful++
} catch (error) {
console.error('Unable to update invoice from payment processor. Reason:', error)
}
debug('updated %d of %d invoices successfully', successful, invoices.length)
}
}
private async processNip05Reverifications(currentSettings: Settings): Promise<void> {
const nip05Settings = currentSettings.nip05
if (!nip05Settings || nip05Settings.mode === 'disabled') {
return
}
try {
const updateFrequency = nip05Settings.verifyUpdateFrequency ?? 86400000
const maxFailures = nip05Settings.maxConsecutiveFailures ?? 20
const pendingVerifications = await this.nip05VerificationRepository.findPendingVerifications(
updateFrequency,
maxFailures,
NIP05_REVERIFICATION_BATCH_SIZE,
)
if (!pendingVerifications.length) {
return
}
debug('found %d NIP-05 verifications to re-check', pendingVerifications.length)
for (const verification of pendingVerifications) {
try {
const verified = await verifyNip05Identifier(verification.nip05, verification.pubkey)
const now = new Date()
const updated: Nip05Verification = {
...verification,
isVerified: verified,
lastVerifiedAt: verified ? now : verification.lastVerifiedAt,
lastCheckedAt: now,
failureCount: verified ? 0 : verification.failureCount + 1,
updatedAt: now,
}
await this.nip05VerificationRepository.upsert(updated)
await delayMs(200 + Math.floor(Math.random() * 100))
} catch (error) {
debug('failed to re-verify NIP-05 for %s: %o', verification.pubkey, error)
}
}
} catch (error) {
debug('NIP-05 re-verification batch failed: %o', error)
}
}
private onError(error: Error) {
debug('error: %o', error)
throw error
}
private onExit() {
debug('exiting')
this.close(() => {
this.process.exit(0)
})
}
public close(callback?: () => void) {
debug('closing')
clearInterval(this.interval)
if (typeof callback === 'function') {
callback()
}
}
}