- Notifications
You must be signed in to change notification settings - Fork 234
feat: add opt-in event retention purge (#359)#412
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Uh oh!
There was an error while loading. Please reload this page.
Changes from all commits
File filter
Filter by extension
Conversations
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -2,10 +2,24 @@ import { PassThrough } from 'stream' | ||
| import { DatabaseClient, EventId, Pubkey } from './base' | ||
| import { DBEvent, Event } from './event' | ||
| import { EventKinds } from '../constants/base' | ||
| import { EventKindsRange } from './settings' | ||
| import { Invoice } from './invoice' | ||
| import { SubscriptionFilter } from './subscription' | ||
| import { User } from './user' | ||
| export interface EventRetentionOptions { | ||
| maxDays?: number | ||
| kindWhitelist?: (EventKinds | EventKindsRange)[] | ||
| pubkeyWhitelist?: Pubkey[] | ||
| } | ||
Justxd22 marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| export interface EventPurgeCounts { | ||
| deleted: number | ||
| expired: number | ||
| retained: number | ||
| } | ||
| export type ExposedPromiseKeys = 'then' | 'catch' | 'finally' | ||
| export interface IQueryResult<T> extends Pick<Promise<T>, keyof Promise<T> & ExposedPromiseKeys> { | ||
| @@ -21,6 +35,7 @@ export interface IEventRepository { | ||
| deleteByPubkeyAndIds(pubkey: Pubkey, ids: EventId[]): Promise<number> | ||
| deleteByPubkeyExceptKinds(pubkey: Pubkey, excludedKinds: number[]): Promise<number> | ||
| hasActiveRequestToVanish(pubkey: Pubkey): Promise<boolean> | ||
| deleteExpiredAndRetained(options?: EventRetentionOptions): Promise<EventPurgeCounts> | ||
| } | ||
| export interface IInvoiceRepository { | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,22 +1,25 @@ | ||
| import { IMaintenanceService, IPaymentsService } from '../@types/services' | ||
| import { mergeDeepLeft, path, pipe } from 'ramda' | ||
| import { IRunnable } from '../@types/base' | ||
| import { createLogger } from '../factories/logger-factory' | ||
| import { delayMs } from '../utils/misc' | ||
| import { InvoiceStatus } from '../@types/invoice' | ||
| import { IPaymentsService } from '../@types/services' | ||
| import { Settings } from '../@types/settings' | ||
| const UPDATE_INVOICE_INTERVAL = 60000 | ||
| const CLEAR_OLD_EVENTS_TIMEOUT_MS = 5000 | ||
| const debug = createLogger('maintenance-worker') | ||
| export class MaintenanceWorker implements IRunnable { | ||
| private interval: NodeJS.Timeout | undefined | ||
| private isRunning = false | ||
| public constructor( | ||
| private readonly process: NodeJS.Process, | ||
| private readonly paymentsService: IPaymentsService, | ||
| private readonly maintenanceService: IMaintenanceService, | ||
| private readonly settings: () => Settings, | ||
| ) { | ||
| this.process | ||
| @@ -27,14 +30,43 @@ export class MaintenanceWorker implements IRunnable { | ||
| .on('unhandledRejection', this.onError.bind(this)) | ||
| } | ||
| private async clearOldEventsSafely(): Promise<void> { | ||
| try { | ||
| await Promise.race([ | ||
| this.maintenanceService.clearOldEvents(), | ||
| delayMs(CLEAR_OLD_EVENTS_TIMEOUT_MS).then(() => { | ||
| throw new Error(`clearOldEvents timed out after ${CLEAR_OLD_EVENTS_TIMEOUT_MS}ms`) | ||
| }), | ||
| ]) | ||
| } catch (error) { | ||
| debug('unable to clear old events: %o', error) | ||
| } | ||
| } | ||
| public run(): void { | ||
| this.interval = setInterval(() => this.onSchedule(), UPDATE_INVOICE_INTERVAL) | ||
| this.interval = setInterval(async () => { | ||
| if (this.isRunning) { | ||
| debug('skipping scheduled maintenance run because previous run is still in progress') | ||
| return | ||
| } | ||
| this.isRunning = true | ||
| try { | ||
| await this.onSchedule() | ||
| } catch (error) { | ||
| this.onError(error as Error) | ||
| } finally { | ||
| this.isRunning = false | ||
| } | ||
| }, UPDATE_INVOICE_INTERVAL) | ||
| } | ||
| private async onSchedule(): Promise<void> { | ||
| const currentSettings = this.settings() | ||
| const clearOldEventsPromise = this.clearOldEventsSafely() | ||
| if (!path(['payments','enabled'], currentSettings)) { | ||
Justxd22 marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| await clearOldEventsPromise | ||
| return | ||
Justxd22 marked this conversation as resolved.
Uh oh!There was an error while loading. Please reload this page. | ||
| } | ||
| @@ -84,6 +116,8 @@ export class MaintenanceWorker implements IRunnable { | ||
| debug('updated %d of %d invoices successfully', successful, invoices.length) | ||
| } | ||
| await clearOldEventsPromise | ||
| } | ||
| private onError(error: Error) { | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| import { getMasterDbClient, getReadReplicaDbClient } from '../database/client' | ||
| import { createSettings } from './settings-factory' | ||
| import { EventRepository } from '../repositories/event-repository' | ||
| import { MaintenanceService } from '../services/maintenance-service' | ||
| export const createMaintenanceService = () => { | ||
| return new MaintenanceService( | ||
| new EventRepository(getMasterDbClient(), getReadReplicaDbClient()), | ||
| createSettings | ||
| ) | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,7 +1,13 @@ | ||
| import { createMaintenanceService } from './maintenance-service-factory' | ||
| import { createPaymentsService } from './payments-service-factory' | ||
| import { createSettings } from './settings-factory' | ||
| import { MaintenanceWorker } from '../app/maintenance-worker' | ||
| export const maintenanceWorkerFactory = () => { | ||
| return new MaintenanceWorker(process, createPaymentsService(), createSettings) | ||
| return new MaintenanceWorker( | ||
| process, | ||
| createPaymentsService(), | ||
| createMaintenanceService(), | ||
| createSettings | ||
| ) | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,38 @@ | ||
| import { createLogger } from '../factories/logger-factory' | ||
| import { IEventRepository } from '../@types/repositories' | ||
| import { IMaintenanceService } from '../@types/services' | ||
| import { Settings } from '../@types/settings' | ||
| const debug = createLogger('maintenance-service') | ||
| export class MaintenanceService implements IMaintenanceService { | ||
| public constructor( | ||
| private readonly eventRepository: IEventRepository, | ||
| private readonly settings: () => Settings, | ||
| ) {} | ||
| public async clearOldEvents(): Promise<void> { | ||
| const currentSettings = this.settings() | ||
| const retention = currentSettings.limits?.event?.retention | ||
| const maxDays = retention?.maxDays | ||
| if (typeof maxDays !== 'number' || isNaN(maxDays) || maxDays <= 0) { | ||
| return | ||
| } | ||
| try { | ||
| debug('purging deleted, expired and old events') | ||
| const deletedCounts = await this.eventRepository.deleteExpiredAndRetained({ | ||
| maxDays, | ||
| kindWhitelist: retention?.kind?.whitelist, | ||
| pubkeyWhitelist: retention?.pubkey?.whitelist, | ||
| }) | ||
| const totalDeleted = deletedCounts.deleted + deletedCounts.expired + deletedCounts.retained | ||
| if (totalDeleted > 0) { | ||
| console.info(`[Maintenance] Deleted events: deleted=${deletedCounts.deleted}, expired=${deletedCounts.expired}, retained=${deletedCounts.retained}.`) | ||
| } | ||
| } catch (error) { | ||
| console.error('Unable to purge events. Reason:', error) | ||
| } | ||
| } | ||
| } |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.