Skip to content
Merged
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
2 changes: 2 additions & 0 deletions apps/randomness/src/Drand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ export enum DrandStatus {
FAILED = "FAILED",
}

export const FinalizedDrandStatuses = [DrandStatus.SUCCESS, DrandStatus.FAILED]

export class Drand {
#round: bigint
#signature: Hex
Expand Down
20 changes: 19 additions & 1 deletion apps/randomness/src/DrandRepository.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { type Hex, type UUID, bigIntToZeroPadded, unknownToError } from "@happy.tech/common"
import { type Result, ResultAsync } from "neverthrow"
import { Drand } from "./Drand"
import { Drand, FinalizedDrandStatuses } from "./Drand"
import { DIGITS_MAX_UINT256 } from "./constants"
import { db } from "./db/driver"
import type { DrandRow } from "./db/types"

const PRUNE_INTERVAL_ROUNDS = 20n // 1 minute

export class DrandRepository {
private cache: Drand[] = []

Expand Down Expand Up @@ -80,4 +82,20 @@ export class DrandRepository {
unknownToError,
).map(() => undefined)
}

async pruneDrands(latestRound: bigint): Promise<Result<void, Error>> {
const cutoffRound = latestRound - PRUNE_INTERVAL_ROUNDS

this.cache = this.cache.filter(
(drand) => !(drand.round <= cutoffRound && FinalizedDrandStatuses.includes(drand.status)),
)
return await ResultAsync.fromPromise(
db
.deleteFrom("drands")
.where("round", "<=", bigIntToZeroPadded(cutoffRound, DIGITS_MAX_UINT256))
.where("status", "in", FinalizedDrandStatuses)
.execute(),
unknownToError,
).map(() => undefined)
}
}
7 changes: 7 additions & 0 deletions apps/randomness/src/DrandService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ export class DrandService {
this.handleNewDrandBeacons()

setInterval(this.handleNewDrandBeacons.bind(this), periodMs)
setInterval(this.pruneDrands.bind(this), MS_IN_SECOND * 20)
}

async getDrandBeacon(round: bigint): Promise<Result<DrandBeacon, DrandError>> {
Expand Down Expand Up @@ -140,8 +141,14 @@ export class DrandService {
this.pendingGetDrandBeaconPromises.forEach((p) => p.reject())
}

private async pruneDrands() {
const currentRound = this.currentRound()
await this.drandRepository.pruneDrands(currentRound)
}

private async _handleNewDrandBeacons() {
const currentRound = this.currentRound()

const drandGaps = this.drandRepository.findRoundGapsInRange(currentRound - env.EVM_DRAND_MARGIN, currentRound)

await Promise.all(
Expand Down