|
| 1 | +/** |
| 2 | + * Copyright (c) 2022 Gitpod GmbH. All rights reserved. |
| 3 | + * Licensed under the GNU Affero General Public License (AGPL). |
| 4 | + * See License-AGPL.txt in the project root for license information. |
| 5 | + */ |
| 6 | + |
| 7 | +import { injectable, inject } from "inversify"; |
| 8 | +import * as opentracing from "opentracing"; |
| 9 | +import { DBWithTracing, TracedWorkspaceDB, WorkspaceDB, WebhookEventDB } from "@gitpod/gitpod-db/lib"; |
| 10 | +import { Disposable } from "@gitpod/gitpod-protocol"; |
| 11 | +import { ConsensusLeaderQorum } from "../consensus/consensus-leader-quorum"; |
| 12 | +import { TraceContext } from "@gitpod/gitpod-protocol/lib/util/tracing"; |
| 13 | +import { log } from "@gitpod/gitpod-protocol/lib/util/logging"; |
| 14 | +import { repeat } from "@gitpod/gitpod-protocol/lib/util/repeat"; |
| 15 | + |
| 16 | +@injectable() |
| 17 | +export class WebhookEventGarbageCollector { |
| 18 | + static readonly GC_CYCLE_INTERVAL_SECONDS = 4 * 60; // every 6 minutes |
| 19 | + |
| 20 | + @inject(WebhookEventDB) protected readonly db: WebhookEventDB; |
| 21 | + |
| 22 | + @inject(ConsensusLeaderQorum) protected readonly leaderQuorum: ConsensusLeaderQorum; |
| 23 | + @inject(TracedWorkspaceDB) protected readonly workspaceDB: DBWithTracing<WorkspaceDB>; |
| 24 | + |
| 25 | + public async start(intervalSeconds?: number): Promise<Disposable> { |
| 26 | + const intervalSecs = intervalSeconds || WebhookEventGarbageCollector.GC_CYCLE_INTERVAL_SECONDS; |
| 27 | + return repeat(async () => { |
| 28 | + try { |
| 29 | + if (await this.leaderQuorum.areWeLeader()) { |
| 30 | + await this.collectObsoleteWebhookEvents(); |
| 31 | + } |
| 32 | + } catch (err) { |
| 33 | + log.error("webhook event garbage collector", err); |
| 34 | + } |
| 35 | + }, intervalSecs * 1000); |
| 36 | + } |
| 37 | + |
| 38 | + protected async collectObsoleteWebhookEvents() { |
| 39 | + const span = opentracing.globalTracer().startSpan("collectObsoleteWebhookEvents"); |
| 40 | + log.debug("webhook-event-gc: start collecting..."); |
| 41 | + try { |
| 42 | + await this.db.deleteOldEvents(10 /* days */, 600 /* limit per run */); |
| 43 | + log.debug("webhook-event-gc: done collecting."); |
| 44 | + } catch (err) { |
| 45 | + TraceContext.setError({ span }, err); |
| 46 | + log.error("webhook-event-gc: error collecting webhook events: ", err); |
| 47 | + throw err; |
| 48 | + } finally { |
| 49 | + span.finish(); |
| 50 | + } |
| 51 | + } |
| 52 | +} |
0 commit comments