-
Notifications
You must be signed in to change notification settings - Fork 33
feat: rolling feed #1254
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
Open
slapec93
wants to merge
8
commits into
upcoming
Choose a base branch
from
feat/rolling-feed
base: upcoming
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+503
−1
Open
feat: rolling feed #1254
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
1dad690
feat: implement rolling feed
6db057e
fix: remove sleeps to speed up tests
58085c0
fix: edge-case bug
af7fb35
fix: stabilize tests
8d7757c
fix: backfill should only write periods before current
4b87a04
fix: heartbeat bug
8a4d63f
fix: backfill logic
b760303
fix: bound catchUp's scan and backfill depth
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,255 @@ | ||
| import { BatchId, EthAddress, keccak256, numberToUint64, PrivateKey, Reference, Topic } from '@ethersphere/core-sdk' | ||
| import { BeeError, Bytes } from '..' | ||
| import { | ||
| FeedPayloadResult, | ||
| FeedReferenceResult, | ||
| FeedUpdateOptions, | ||
| fetchLatestFeedUpdate, | ||
| probeFeed, | ||
| } from '../api/feed' | ||
| import { uploadSingleOwnerChunkWithWrappedChunk } from '../chunk/soc' | ||
| import { | ||
| downloadFeedUpdate, | ||
| downloadFeedUpdateAsCAC, | ||
| FeedUploadOptions, | ||
| updateFeedWithPayload, | ||
| updateFeedWithReference, | ||
| } from '../feed' | ||
| import { makeFeedIdentifier } from '../feed/identifier' | ||
| import { BeeRequestOptions, UploadResult } from '../types' | ||
| import { BeeResponseError } from '../utils/error' | ||
| import { BeeContext } from './context' | ||
|
|
||
| // RollingFeedReader.downloadPayload/downloadReference only ever fall back one period, so | ||
| // backfilling deeper than that serves no reader by default - see catchUp's maxBackfill param. | ||
| const DEFAULT_MAX_BACKFILL = 1 | ||
|
|
||
| function periodIndex(t: number, periodLength: number): number { | ||
| if (periodLength <= 0) { | ||
| throw new BeeError('Period length must be greater than zero!') | ||
| } | ||
|
|
||
| return Math.floor(t / periodLength) | ||
| } | ||
|
|
||
| function topicFor(baseTopic: Topic, periodIdx: number): Topic { | ||
| const baseTopicBytes = baseTopic.toUint8Array() | ||
|
|
||
| return new Topic(keccak256(Bytes.concat(baseTopicBytes, numberToUint64(BigInt(periodIdx), 'BE')))) | ||
| } | ||
|
|
||
| async function isPeriodPopulated(requestOptions: BeeRequestOptions, owner: EthAddress, topic: Topic): Promise<boolean> { | ||
| try { | ||
| await probeFeed(requestOptions, owner, topic) | ||
|
|
||
| return true | ||
| } catch (e) { | ||
| if (e instanceof BeeResponseError) { | ||
| return false | ||
| } | ||
| throw e | ||
| } | ||
| } | ||
|
|
||
| async function fetchLatestReference( | ||
| requestOptions: BeeRequestOptions, | ||
| owner: EthAddress, | ||
| topic: Topic, | ||
| ): Promise<FeedReferenceResult> { | ||
| const { feedIndex } = await probeFeed(requestOptions, owner, topic) | ||
| const update = await downloadFeedUpdate(requestOptions, owner, topic, feedIndex, true) | ||
|
|
||
| return { | ||
| reference: new Reference(update.payload.toUint8Array()), | ||
| feedIndex, | ||
| feedIndexNext: feedIndex.next(), | ||
| } | ||
| } | ||
|
|
||
| export class RollingFeed { | ||
| constructor(private readonly context: BeeContext) {} | ||
|
|
||
| makeWriter(baseTopic: Topic, signer: PrivateKey, periodLength: number): RollingFeedWriter { | ||
| return new RollingFeedWriter(this.context, baseTopic, signer, periodLength) | ||
| } | ||
|
|
||
| makeReader(baseTopic: Topic, owner: EthAddress, periodLength: number): RollingFeedReader { | ||
| return new RollingFeedReader(this.context, baseTopic, owner, periodLength) | ||
| } | ||
| } | ||
|
|
||
| export class RollingFeedWriter { | ||
| constructor( | ||
| private readonly context: BeeContext, | ||
| private readonly baseTopic: Topic, | ||
| private readonly signer: PrivateKey, | ||
| private readonly periodLength: number, | ||
| ) {} | ||
|
|
||
| async uploadPayload( | ||
| postageBatchId: string | BatchId, | ||
| payload: Uint8Array | string, | ||
| options?: FeedUploadOptions, | ||
| ): Promise<UploadResult> { | ||
| const requestOptions = this.context.getRequestOptionsForCall() | ||
| const stamp = new BatchId(postageBatchId) | ||
| const { currentTopic, nextTopic, mirrorOptions } = this.currentAndNextTopics(options) | ||
|
|
||
| const [result] = await Promise.all([ | ||
| updateFeedWithPayload(requestOptions, this.signer, currentTopic, payload, stamp, options), | ||
| updateFeedWithPayload(requestOptions, this.signer, nextTopic, payload, stamp, mirrorOptions), | ||
| ]) | ||
|
|
||
| return result | ||
| } | ||
|
|
||
| async uploadReference( | ||
| postageBatchId: string | BatchId, | ||
| reference: Reference | string | Uint8Array, | ||
| options?: FeedUploadOptions, | ||
| ): Promise<UploadResult> { | ||
| const requestOptions = this.context.getRequestOptionsForCall() | ||
| const stamp = new BatchId(postageBatchId) | ||
| const { currentTopic, nextTopic, mirrorOptions } = this.currentAndNextTopics(options) | ||
|
|
||
| const [result] = await Promise.all([ | ||
| updateFeedWithReference(requestOptions, this.signer, currentTopic, reference, stamp, options), | ||
| updateFeedWithReference(requestOptions, this.signer, nextTopic, reference, stamp, mirrorOptions), | ||
| ]) | ||
|
|
||
| return result | ||
| } | ||
|
|
||
| /** | ||
| * True unless the period right before `periodIdx` (default: current) never got mirrored | ||
| * forward into it, i.e. the writer went silent for at least one whole period. | ||
| */ | ||
| async isCaughtUp(periodIdx?: number): Promise<boolean> { | ||
| const requestOptions = this.context.getRequestOptionsForCall() | ||
| const targetPeriod = periodIdx ?? periodIndex(Date.now() / 1000, this.periodLength) | ||
| const owner = this.signer.publicKey().address() | ||
|
|
||
| return isPeriodPopulated(requestOptions, owner, topicFor(this.baseTopic, targetPeriod)) | ||
| } | ||
|
|
||
| /** | ||
| * Backfills up to `maxBackfill` periods strictly between the last populated one and | ||
| * `periodIdx` (default: current) with that period's last known payload/reference. Never | ||
| * writes `periodIdx` itself - keeping it populated during silence is the caller's job (a | ||
| * periodic `uploadPayload`/`uploadReference` heartbeat), not catchUp's. A conditional | ||
| * "write it if empty" would race that heartbeat: there's no compare-and-swap on a SOC | ||
| * address, so a stale write can still land after a concurrent fresh one and shadow it. | ||
| * | ||
| * `maxBackfill` bounds both the backward scan and the backfill itself, since scanning | ||
| * further back than you're willing to backfill only wastes round trips. Defaults to 1, | ||
| * matching the reader's one-period fallback - nothing deeper is ever read anyway. Throws | ||
| * if no populated period is found within that bound. | ||
| */ | ||
| async catchUp( | ||
| postageBatchId: string | BatchId, | ||
| periodIdx?: number, | ||
| maxBackfill = DEFAULT_MAX_BACKFILL, | ||
| ): Promise<void> { | ||
| const requestOptions = this.context.getRequestOptionsForCall() | ||
| const stamp = new BatchId(postageBatchId) | ||
| const owner = this.signer.publicKey().address() | ||
| const targetPeriod = periodIdx ?? periodIndex(Date.now() / 1000, this.periodLength) | ||
|
|
||
| // periods before 0 can't exist (period index is derived from Unix time), so the scan | ||
| // must not probe them even when the lookback window would otherwise reach that far | ||
| const scanFloor = Math.max(0, targetPeriod - 1 - maxBackfill) | ||
| let lastGoodPeriod = targetPeriod - 1 | ||
|
|
||
| while (lastGoodPeriod >= scanFloor) { | ||
| if (await isPeriodPopulated(requestOptions, owner, topicFor(this.baseTopic, lastGoodPeriod))) { | ||
| break | ||
| } | ||
| lastGoodPeriod-- | ||
| } | ||
|
|
||
| if (lastGoodPeriod < scanFloor) { | ||
| throw new BeeError(`No populated period found within ${maxBackfill} periods to catch up from!`) | ||
| } | ||
|
|
||
| if (lastGoodPeriod === targetPeriod - 1) { | ||
| return // no gap - nothing to backfill | ||
| } | ||
|
|
||
| const sourceTopic = topicFor(this.baseTopic, lastGoodPeriod) | ||
| const { feedIndex: sourceIndex } = await probeFeed(requestOptions, owner, sourceTopic) | ||
| const sourceChunk = await downloadFeedUpdateAsCAC(requestOptions, owner, sourceTopic, sourceIndex) | ||
|
|
||
| const periodsToBackfill = Array.from( | ||
| { length: targetPeriod - 1 - lastGoodPeriod }, | ||
| (_, i) => lastGoodPeriod + 1 + i, | ||
| ) | ||
|
|
||
| await Promise.all( | ||
| periodsToBackfill.map(async period => { | ||
| const identifier = makeFeedIdentifier(topicFor(this.baseTopic, period), 0) | ||
|
|
||
| return uploadSingleOwnerChunkWithWrappedChunk(requestOptions, this.signer, stamp, identifier, sourceChunk) | ||
| }), | ||
| ) | ||
| } | ||
|
|
||
| private currentAndNextTopics(options?: FeedUploadOptions): { | ||
| currentTopic: Topic | ||
| nextTopic: Topic | ||
| mirrorOptions: FeedUploadOptions | ||
| } { | ||
| const currentPeriod = periodIndex(Date.now() / 1000, this.periodLength) | ||
|
|
||
| return { | ||
| currentTopic: topicFor(this.baseTopic, currentPeriod), | ||
| nextTopic: topicFor(this.baseTopic, currentPeriod + 1), | ||
| mirrorOptions: { ...options, index: undefined }, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| export class RollingFeedReader { | ||
| constructor( | ||
| private readonly context: BeeContext, | ||
| private readonly baseTopic: Topic, | ||
| private readonly owner: EthAddress, | ||
| private readonly periodLength: number, | ||
| ) {} | ||
|
|
||
| /** | ||
| * Reads the current period's feed; falls back to the previous period once if empty, | ||
| * to tolerate clock skew between writer and reader. | ||
| */ | ||
| async downloadPayload(options?: Omit<FeedUpdateOptions, 'index'>): Promise<FeedPayloadResult> { | ||
| const requestOptions = this.context.getRequestOptionsForCall() | ||
| const currentPeriod = periodIndex(Date.now() / 1000, this.periodLength) | ||
|
|
||
| try { | ||
| return await fetchLatestFeedUpdate(requestOptions, this.owner, topicFor(this.baseTopic, currentPeriod), options) | ||
| } catch (e) { | ||
| if (!(e instanceof BeeResponseError)) { | ||
| throw e | ||
| } | ||
|
|
||
| return fetchLatestFeedUpdate(requestOptions, this.owner, topicFor(this.baseTopic, currentPeriod - 1), options) | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Same as `downloadPayload`, but for a reference to data uploaded elsewhere. | ||
| */ | ||
| async downloadReference(): Promise<FeedReferenceResult> { | ||
| const requestOptions = this.context.getRequestOptionsForCall() | ||
| const currentPeriod = periodIndex(Date.now() / 1000, this.periodLength) | ||
|
|
||
| try { | ||
| return await fetchLatestReference(requestOptions, this.owner, topicFor(this.baseTopic, currentPeriod)) | ||
| } catch (e) { | ||
| if (!(e instanceof BeeResponseError)) { | ||
| throw e | ||
| } | ||
|
|
||
| return fetchLatestReference(requestOptions, this.owner, topicFor(this.baseTopic, currentPeriod - 1)) | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Filename should be rolling-feed.ts