diff --git a/.changeset/wot-invalidate-graph-across-workers.md b/.changeset/wot-invalidate-graph-across-workers.md new file mode 100644 index 00000000..fb18ec82 --- /dev/null +++ b/.changeset/wot-invalidate-graph-across-workers.md @@ -0,0 +1,7 @@ +--- +'nostream': patch +--- + +fix(wot): rebuild the trust graph of every worker when a contact list changes it + +Each worker keeps its own Web of Trust graph, and only the worker that handled a contact list rebuilt it. The other workers kept granting a proof-of-work discount for a relationship the author had just removed, until their next rebuild, which could be a whole `wot.refreshIntervalHours` away. A worker that applies a contact list now publishes a token in the cache, and every worker compares it with the one its graph was built under and rebuilds when it differs, and asks again if that rebuild fails, spaced out by `wot.minRebuildIntervalSeconds` like a rebuild for a contact list it handled itself. A lookup reads the token at most once a second. If the cache cannot be read or written, the worker keeps answering from its own graph. diff --git a/src/services/wot-graph-service.ts b/src/services/wot-graph-service.ts index 791f1ddb..50ede430 100644 --- a/src/services/wot-graph-service.ts +++ b/src/services/wot-graph-service.ts @@ -1,3 +1,5 @@ +import { randomBytes } from 'node:crypto' + import { ICacheAdapter } from '../@types/adapters' import { Pubkey, Tag } from '../@types/base' import { IEventRepository } from '../@types/repositories' @@ -17,6 +19,12 @@ export const DEFAULT_WOT_MAX_EDGES = 2_000_000 export const DEFAULT_WOT_MIN_REBUILD_INTERVAL_SECONDS = 60 export const WOT_FOLLOW_LIST_BATCH_SIZE = 100 +// Every worker holds its own graph. A worker that applies a contact list publishes a new token here, and the others +// compare it with the one their graph was built under, so they rebuild too instead of keeping the old relationships. +export const WOT_INVALIDATION_KEY = 'wot:graph:invalidation' +// How long a worker trusts the token it read, so a lookup costs a cache read at most once per interval. +export const WOT_INVALIDATION_CHECK_INTERVAL_MS = 1000 + // The longest delay a Node.js timer accepts; a longer wait is re-armed. const MAX_TIMER_DELAY_MS = 2 ** 31 - 1 @@ -78,6 +86,13 @@ export class WotGraphService implements IWotGraphService { private lastRebuildEndedAt: number | undefined + // The invalidation token the current graph was built under, and the last one a rebuild was requested for. + private builtInvalidation: string | undefined + + private requestedInvalidation: string | undefined + + private invalidationCheckedAt: number | undefined + public constructor( private readonly cache: ICacheAdapter, private readonly eventRepository: IEventRepository, @@ -111,6 +126,7 @@ export class WotGraphService implements IWotGraphService { return 0 } + await this.checkInvalidation() await this.ensureBuilt() // Fail closed: if the settings changed and the rebuild for them did not @@ -137,15 +153,59 @@ export class WotGraphService implements IWotGraphService { await this.cache.addToSet(followSetKey(pubkey), follows) } - // A pubkey outside the current trust graph publishing a new follow list - // can't change anyone's distance from the seed, so only rebuild when the - // change could actually matter. The event path never waits for the + // The other workers are told of every contact list: this worker's graph cannot say whether theirs holds the + // pubkey, because it may not be built yet, or may not have caught up with a change the others already applied. + // Each worker rebuilds at most once per wot.minRebuildIntervalSeconds however many tokens arrive. + await this.publishInvalidation() + + // A pubkey outside this worker's trust graph publishing a new follow list can't change anyone's distance from + // the seed here, so only rebuild when the change could actually matter. The event path never waits for the // rebuild, and requestRebuild() spaces these rebuilds out. if (pubkey === wot.seedPubkey || this.distances.has(pubkey)) { this.requestRebuild() } } + // Tells the other workers that a contact list changed. The follow lists are written before this, so a worker that + // sees the token and rebuilds reads the change. + private async publishInvalidation(): Promise { + const token = `${Date.now()}-${randomBytes(8).toString('hex')}` + try { + await this.cache.setKey(WOT_INVALIDATION_KEY, token) + this.requestedInvalidation = token + } catch (error) { + logger('could not publish the wot graph invalidation: %o', error) + } + } + + private async readInvalidation(): Promise { + try { + return (await this.cache.getKey(WOT_INVALIDATION_KEY)) || '' + } catch (error) { + logger('could not read the wot graph invalidation: %o', error) + return this.builtInvalidation ?? '' + } + } + + // A token other than the one this graph was built under means another worker applied a contact list since. The + // rebuild is requested like one for a contact list this worker handled, so it is spaced out the same way. + private async checkInvalidation(): Promise { + const now = performance.now() + if ( + this.invalidationCheckedAt !== undefined && + now - this.invalidationCheckedAt < WOT_INVALIDATION_CHECK_INTERVAL_MS + ) { + return + } + this.invalidationCheckedAt = now + + const token = await this.readInvalidation() + if (this.ready && token !== this.builtInvalidation && token !== this.requestedInvalidation) { + this.requestedInvalidation = token + this.requestRebuild() + } + } + private async ensureBuilt(): Promise { // scheduleRebuild() hands back a rebuild that may already be in flight for // the previous settings, so check the key again once it finishes; a @@ -181,6 +241,9 @@ export class WotGraphService implements IWotGraphService { this.building = this.rebuild() .catch((error) => { logger.error('wot graph rebuild failed: %o', error) + // The graph was not replaced, so it is still older than the change that asked for this rebuild. Forgetting the + // request lets the next token check ask again, spaced out like any other. + this.requestedInvalidation = undefined }) .finally(() => { this.building = undefined @@ -249,6 +312,10 @@ export class WotGraphService implements IWotGraphService { return } + // Read before any follow list, so a change published after this is seen as newer than the graph. It becomes the + // graph's token only when the graph replaces the old one. + const startedUnder = await this.readInvalidation() + const maxDepth = wot.maxDepth ?? 2 const minimumFollowers = wot.minimumFollowers ?? 1 const limits = rebuildLimits(wot) @@ -333,6 +400,7 @@ export class WotGraphService implements IWotGraphService { this.distances = distances this.builtKey = key + this.builtInvalidation = startedUnder this.ready = true if (stoppedAt) { logger.warn( diff --git a/test/unit/services/wot-graph-service.spec.ts b/test/unit/services/wot-graph-service.spec.ts index 90dfb520..9bd9e386 100644 --- a/test/unit/services/wot-graph-service.spec.ts +++ b/test/unit/services/wot-graph-service.spec.ts @@ -16,7 +16,11 @@ import { DBEvent } from '../../../src/@types/event' import { IEventRepository } from '../../../src/@types/repositories' import { Settings } from '../../../src/@types/settings' import { logger as baseLogger } from '../../../src/logger' -import { WOT_FOLLOW_LIST_BATCH_SIZE, WotGraphService } from '../../../src/services/wot-graph-service' +import { + WOT_FOLLOW_LIST_BATCH_SIZE, + WOT_INVALIDATION_KEY, + WotGraphService, +} from '../../../src/services/wot-graph-service' describe('WotGraphService', () => { const seedPubkey = 'a'.repeat(64) @@ -48,6 +52,7 @@ describe('WotGraphService', () => { }) as any const followsOf: Record = {} + const plainKeys: Record = {} const service = () => new WotGraphService(cache, eventRepository, () => settings) @@ -74,7 +79,15 @@ describe('WotGraphService', () => { delete followsOf[pubkey] return 1 }) + for (const key of Object.keys(plainKeys)) { + delete plainKeys[key] + } cache = { + getKey: sandbox.stub().callsFake(async (key: string) => plainKeys[key] ?? ''), + setKey: sandbox.stub().callsFake(async (key: string, value: string) => { + plainKeys[key] = value + return true + }), getSetMembers: getSetMembersStub, addToSet: addToSetStub, deleteKey: deleteKeyStub, @@ -612,6 +625,131 @@ describe('WotGraphService', () => { }) }) + describe('invalidation across workers', () => { + let clock: Sinon.SinonFakeTimers + + beforeEach(() => { + clock = sandbox.useFakeTimers() + followsOf[seedPubkey] = ['a'] + followsOf.a = ['x'] + }) + + it('stops a worker that did not handle the contact list from granting a removed relationship', async () => { + const handler = service() + const peer = service() // another worker: its own graph, the same cache and database + expect(await handler.getDistance('x')).to.equal(2) + expect(await peer.getDistance('x')).to.equal(2) + + await handler.updateFollowList('a', ['y']) // a no longer follows x + await clock.tickAsync(2000) + await peer.getDistance('x') // sees the new token and starts its rebuild + await clock.tickAsync(0) + + expect(await peer.getDistance('x')).to.be.undefined + expect(await peer.getDistance('y')).to.equal(2) + }) + + it('publishes a token for every accepted contact list, whether or not this worker holds the pubkey', async () => { + const wot = service() + await wot.getDistance('x') + expect(plainKeys[WOT_INVALIDATION_KEY]).to.equal(undefined) + + await wot.updateFollowList('stranger', ['x']) + const first = plainKeys[WOT_INVALIDATION_KEY] + expect(first).to.be.a('string').and.not.equal('') + + await wot.updateFollowList('a', ['y']) + expect(plainKeys[WOT_INVALIDATION_KEY]).to.be.a('string').and.not.equal(first) + }) + + it('tells a built peer of a change received by a worker that has not built its graph', async () => { + const peer = service() + expect(await peer.getDistance('x')).to.equal(2) + const handler = service() // has not built anything, so it does not hold `a` + + await handler.updateFollowList('a', ['y']) // a no longer follows x + await clock.tickAsync(2000) + await peer.getDistance('x') // sees the token and starts its rebuild + await clock.tickAsync(0) + + expect(await peer.getDistance('x')).to.be.undefined + expect(await peer.getDistance('y')).to.equal(2) + }) + + it('asks again after a rebuild fails, without another contact list', async () => { + const handler = service() + const peer = service() + await handler.getDistance('x') + await peer.getDistance('x') + await handler.updateFollowList('a', ['y']) + await clock.tickAsync(2000) + + getSetMembersStub.rejects(new Error('cache unavailable')) + await peer.getDistance('x') // sees the token; the rebuild it starts fails + await clock.tickAsync(0) + expect(await peer.getDistance('x')).to.equal(2) // still the old graph + + getSetMembersStub.callsFake(async (key: string) => followsOf[key.replace('wot:follows:', '')] ?? []) + await clock.tickAsync(2000) + await peer.getDistance('x') // the token is still newer than the graph, so it asks again + await clock.tickAsync(0) + + expect(await peer.getDistance('x')).to.be.undefined + expect(await peer.getDistance('y')).to.equal(2) + }) + + it('does not rebuild a worker again for a token it already acted on', async () => { + const handler = service() + const peer = service() + await handler.getDistance('x') + await peer.getDistance('x') + await handler.updateFollowList('a', ['y']) + await clock.tickAsync(2000) + await peer.getDistance('x') + await clock.tickAsync(0) + getSetMembersStub.resetHistory() + + for (let second = 0; second < 10; second++) { + await clock.tickAsync(1000) + await peer.getDistance('y') + } + + expect(getSetMembersStub).not.to.have.been.called + }) + + it('reads the token at most once per interval however many lookups arrive', async () => { + const wot = service() + await wot.getDistance('x') + ;(cache.getKey as Sinon.SinonStub).resetHistory() + + for (let lookup = 0; lookup < 50; lookup++) { + await wot.getDistance('x') + } + expect(cache.getKey).not.to.have.been.called + + await clock.tickAsync(1000) + await wot.getDistance('x') + expect(cache.getKey).to.have.been.calledOnce + }) + + it('keeps granting from its graph when the token cannot be read', async () => { + const wot = service() + expect(await wot.getDistance('x')).to.equal(2) + ;(cache.getKey as Sinon.SinonStub).rejects(new Error('cache unavailable')) + await clock.tickAsync(2000) + + expect(await wot.getDistance('x')).to.equal(2) + }) + + it('still answers when the token cannot be published', async () => { + const wot = service() + await wot.getDistance('x') + ;(cache.setKey as Sinon.SinonStub).rejects(new Error('cache unavailable')) + + await expect(wot.updateFollowList('a', ['y'])).to.eventually.be.fulfilled + }) + }) + describe('rebuilds triggered by contact lists', () => { const day = 24 * 60 * 60 * 1000 let clock: Sinon.SinonFakeTimers