Skip to content

Commit

Permalink
fix: from event id
Browse files Browse the repository at this point in the history
  • Loading branch information
stephancill committed Sep 17, 2024
1 parent ee1b97f commit 920d9a0
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/lib/hubSubscriber.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { EventStreamConnection } from './eventStream.js'
import { Logger } from './logger.js'
import { RedisClient } from './redis.js'
import type { HubClient } from './types'
import { sleep } from './utils.js'
import { eventIdFromTimestamp, sleep } from './utils.js'

interface HubEventsEmitter {
event: (hubEvent: HubEvent) => void
Expand Down Expand Up @@ -109,7 +109,7 @@ export class BaseHubSubscriber extends HubSubscriber {
this.log.info(`HubSubscriber ${this.label} connected to hub`)

// TODO: Fix this
const fromId = undefined // await this.getLastEventId()
const fromId = eventIdFromTimestamp(Date.now()) // await this.getLastEventId()
if (fromId) {
this.log.info(
`HubSubscriber ${this.label} Found last hub event ID: ${fromId}`
Expand Down
27 changes: 27 additions & 0 deletions src/lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
ContactInfoContentBody,
FARCASTER_EPOCH,
FidRequest,
HubResult,
Message,
Expand Down Expand Up @@ -238,3 +239,29 @@ export async function inBatchesOf<T>(
export function sleep(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}

const SEQUENCE_BITS = 12

export const extractEventTimestamp = (eventId: number): number => {
const binaryEventId = eventId.toString(2)
const binaryTimestamp = binaryEventId.slice(
0,
binaryEventId.length - SEQUENCE_BITS
)
return parseInt(binaryTimestamp, 2) + FARCASTER_EPOCH
}

export const eventIdFromTimestamp = (
timestamp: number,
sequence: number = 0
): number => {
if (sequence < 0 || sequence >= 1 << SEQUENCE_BITS) {
throw new Error(
`Sequence must be between 0 and ${(1 << SEQUENCE_BITS) - 1}`
)
}
const adjustedTimestamp = timestamp - FARCASTER_EPOCH
const timestampBits = adjustedTimestamp.toString(2)
const sequenceBits = sequence.toString(2).padStart(SEQUENCE_BITS, '0')
return parseInt(timestampBits + sequenceBits, 2)
}

0 comments on commit 920d9a0

Please sign in to comment.