From 920d9a0bdcb13030e17354f7cc368eaba1816147 Mon Sep 17 00:00:00 2001 From: Stephan Cilliers <5469870+stephancill@users.noreply.github.com> Date: Tue, 17 Sep 2024 22:23:35 +0200 Subject: [PATCH] fix: from event id --- src/lib/hubSubscriber.ts | 4 ++-- src/lib/utils.ts | 27 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/lib/hubSubscriber.ts b/src/lib/hubSubscriber.ts index f17de45..74b3544 100644 --- a/src/lib/hubSubscriber.ts +++ b/src/lib/hubSubscriber.ts @@ -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 @@ -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}` diff --git a/src/lib/utils.ts b/src/lib/utils.ts index 3805b90..de88204 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -1,5 +1,6 @@ import { ContactInfoContentBody, + FARCASTER_EPOCH, FidRequest, HubResult, Message, @@ -238,3 +239,29 @@ export async function inBatchesOf( 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) +}