import { DEFAULT_SESSION_MIN_PROVIDERS, DEFAULT_SESSION_MAX_PROVIDERS, DEFAULT_CID_PEER_FILTER_SIZE, InsufficientProvidersError } from '@helia/interface' import { AbortError, TypedEventEmitter, setMaxListeners } from '@libp2p/interface' import { createScalableCuckooFilter, Queue } from '@libp2p/utils' import { base64 } from 'multiformats/bases/base64' import pDefer from 'p-defer' import { raceSignal } from 'race-signal' import type { BlockBroker, BlockRetrievalOptions, CreateSessionOptions } from '@helia/interface' import type { AbortOptions, ComponentLogger, Logger } from '@libp2p/interface' import type { Filter } from '@libp2p/utils' import type { Multiaddr } from '@multiformats/multiaddr' import type { CID } from 'multiformats/cid' import type { DeferredPromise } from 'p-defer' import type { ProgressEvent } from 'progress-events' export interface AbstractSessionComponents { logger: ComponentLogger } export interface AbstractCreateSessionOptions extends CreateSessionOptions { name: string } export interface BlockstoreSessionEvents { provider: CustomEvent } export interface SessionProvider { fallback: boolean } interface Request { promise: Promise observers: number queryFilter: Filter } export abstract class AbstractSession extends TypedEventEmitter> implements BlockBroker { public abstract name: string private initialPeerSearchComplete?: Promise private readonly requests: Map private readonly logName: string protected log: Logger protected logger: ComponentLogger private readonly minProviders: number private readonly maxProviders: number public readonly providers: Provider[] private readonly evictionFilter: Filter private readonly initialProviders: Array private readonly cidPeerFilterSize: number constructor (components: AbstractSessionComponents, init: AbstractCreateSessionOptions) { super() setMaxListeners(Infinity, this) this.logName = init.name this.logger = components.logger this.log = components.logger.forComponent(this.logName) this.requests = new Map() this.minProviders = init.minProviders ?? DEFAULT_SESSION_MIN_PROVIDERS this.maxProviders = init.maxProviders ?? DEFAULT_SESSION_MAX_PROVIDERS this.cidPeerFilterSize = init.cidPeerFilterSize ?? DEFAULT_CID_PEER_FILTER_SIZE this.providers = [] this.evictionFilter = createScalableCuckooFilter(this.maxProviders) this.initialProviders = [...(init.providers ?? [])] } async retrieve (cid: CID, options: BlockRetrievalOptions = {}): Promise { // see if we are already requesting this CID in this session const cidStr = base64.encode(cid.multihash.bytes) const existingJob = this.requests.get(cidStr) if (existingJob != null) { this.log('join existing request for %c', cid) existingJob.observers++ return existingJob.promise } const deferred: DeferredPromise = pDefer() const request = { promise: deferred.promise, observers: 1, queryFilter: createScalableCuckooFilter(this.cidPeerFilterSize) } this.requests.set(cidStr, request) // if this is the first time this session has been used let first = false if (this.initialPeerSearchComplete == null) { first = true this.log = this.logger.forComponent(`${this.logName}:${cid}`) this.initialPeerSearchComplete = this.findProviders(cid, this.minProviders, options) } let foundBlock = false // this queue manages outgoing requests - as new peers are added to the // session they will be added to the queue so we can request the current // block from multiple peers as they are discovered const queue = new Queue({ concurrency: this.maxProviders }) queue.addEventListener('failure', (evt) => { if (evt.detail.job.options.provider.fallback) { this.log.error('error querying fallback provider %s - %e', evt.detail.job.options.provider, evt.detail.error) return } if (evt.detail.error.name === 'NoEvictionError') { this.log.error('no-eviction error querying provider %s - %e', evt.detail.job.options.provider, evt.detail.error) return } this.log.error('error querying provider %s, evicting from session - %e', evt.detail.job.options.provider, evt.detail.error) this.evict(evt.detail.job.options.provider) }) queue.addEventListener('success', (evt) => { // peer has sent block, return it to the caller foundBlock = true deferred.resolve(evt.detail.result) }) queue.addEventListener('idle', () => { if (foundBlock) { this.log.trace('session idle, found block') // we either found the block or the user gave up return } if (options.signal?.aborted === true) { this.log.trace('session idle, signal aborted') return } // find more session peers and retry Promise.resolve() .then(async () => { this.log('no session peers had block for for %c, finding new providers', cid) // evict this.minProviders random providers to make room for more for (let i = 0; i < this.minProviders; i++) { if (this.providers.length === 0) { break } const provider = this.providers[Math.floor(Math.random() * this.providers.length)] // do not evict fallback peer if (provider.fallback) { continue } this.log('evicting %s to make room for more providers', provider) this.evict(provider) } // find new providers for the CID await this.findProviders(cid, this.minProviders, options) // keep trying until the abort signal fires this.log('found new providers re-retrieving %c', cid) this.requests.delete(cidStr) deferred.resolve(await this.retrieve(cid, options)) }) .catch(err => { this.log.error('could not find new providers for %c - %e', cid, err) deferred.reject(err) }) }) const peerAddedToSessionListener = (event: CustomEvent): void => { const filterKey = this.toFilterKey(event.detail) if (request.queryFilter.has(filterKey)) { return } request.queryFilter.add(filterKey) // dispatch progress notification this.emitFoundProviderProgressEvent(cid, event.detail, options) queue.add(async () => { return this.queryProvider(cid, event.detail, options) }, { provider: event.detail }) .catch(err => { if (options.signal?.aborted === true) { // skip logging error if signal was aborted because abort can happen // on success (e.g. another session found the block) return } this.log.error('error retrieving session block for %c - %e', cid, err) }) } // add new session peers to query as they are discovered this.addEventListener('provider', peerAddedToSessionListener) if (first) { try { await raceSignal(this.initialPeerSearchComplete, options.signal) if (first) { this.log('found initial session peers for %c', cid) } } catch (err) { if (first) { this.log('failed to find initial session peers for %c - %e', cid, err) } this.requests.delete(cidStr) if (request.observers > 1) { // only need to reject request if another context is now also waiting // for the result - otherwise we can end up with an unhandled promise // rejection deferred.reject(err) } throw err } } // query each session peer directly Promise.all( [...this.providers] .filter(provider => { const filterKey = this.toFilterKey(provider) const has = request.queryFilter.has(filterKey) if (!has) { request.queryFilter.add(this.toFilterKey(provider)) } return !has }) .map(async (provider) => { return queue.add(async () => this.queryProvider(cid, provider, options), { provider }) }) ) .catch(err => { if (options.signal?.aborted === true) { // skip logging error if signal was aborted because abort can happen // on success (e.g. another session found the block) return } this.log.error('error retrieving session block for %c - %e', cid, err) }) const signalAbortedListener = (): void => { deferred.reject(new AbortError(options.signal?.reason ?? 'Session aborted')) queue.abort() } options.signal?.addEventListener('abort', signalAbortedListener) try { return await deferred.promise } finally { this.removeEventListener('provider', peerAddedToSessionListener) options.signal?.removeEventListener('abort', signalAbortedListener) queue.clear() this.requests.delete(cidStr) } } evict (provider: Provider): void { this.evictionFilter.add(this.toFilterKey(provider)) const index = this.providers.findIndex(prov => this.equals(prov, provider)) if (index === -1) { return } this.providers.splice(index, 1) } isEvicted (provider: Provider): boolean { return this.evictionFilter.has(this.toFilterKey(provider)) } hasProvider (provider: Provider): boolean { // dedupe existing gateways if (this.providers.find(prov => this.equals(prov, provider)) != null) { return true } // dedupe failed session peers if (this.isEvicted(provider)) { return true } return false } async addPeer (peer: CID | Multiaddr | Multiaddr[], options?: AbortOptions): Promise { const provider = await this.convertToProvider(peer, 'manually-added', options) if (provider == null || this.hasProvider(provider)) { return } this.providers.push(provider) // let the new peer join current queries this.safeDispatchEvent('provider', { detail: provider }) } private async findProviders (cid: CID, count: number, options: BlockRetrievalOptions): Promise { const deferred: DeferredPromise = pDefer() let found = 0 // run async to resolve the deferred promise when `count` providers are // found but continue util this.providers reaches this.maxProviders void Promise.resolve() .then(async () => { this.log('finding %d-%d new provider(s) for %c - %d initial providers', count, this.maxProviders, cid, this.initialProviders.length) const self = this // process any specific providers for this session const initialProviders = async function * (): AsyncGenerator { while (self.initialProviders.length > 0) { const initialProvider = self.initialProviders.pop() if (initialProvider == null) { continue } const provider = await self.convertToProvider(initialProvider, 'manual', options) if (provider == null) { continue } yield provider } } const providers = async function * (): AsyncGenerator { yield * initialProviders() yield * self.findNewProviders(cid, options) } // still not got enough providers, search routing for more for await (const provider of providers()) { if (this.providers.length === this.maxProviders || options.signal?.aborted === true) { break } if (this.hasProvider(provider)) { continue } this.log('found %d providers, %d in session', found, this.providers.length) this.providers.push(provider) // let the new peer join current queries this.safeDispatchEvent('provider', { detail: provider }) found++ if (this.providers.length === count) { this.log('session is ready with %d peer(s), new peers present', this.providers.length) deferred.resolve() // continue finding peers until we reach this.maxProviders } if (this.providers.length === this.maxProviders) { this.log('found max session peers %d', this.providers.length) break } } this.log('found %d new session peers while trying to find %d, %d in session', found, count, this.providers.length) if (this.providers.length < count) { throw new InsufficientProvidersError(`Found ${found} of ${count} ${this.name} providers for ${cid}, ${this.providers.length} in session after evictions`) } }) .catch(err => { this.log.error('error searching routing for potential session peers for %c - %e', cid, err) deferred.reject(err) }) return deferred.promise } /** * If this session was created with specific providers, convert one of them * into the format required or return `undefined` if the provider is not * compatible with this session implementation */ abstract convertToProvider (provider: CID | Multiaddr | Multiaddr[], routing: string, options?: AbortOptions): Promise /** * This method should search for new providers and yield them. */ abstract findNewProviders (cid: CID, options: BlockRetrievalOptions): AsyncGenerator /** * The subclass should contact the provider and request the block from it. * * If the provider cannot provide the block an error should be thrown. * * The provider will then be excluded from ongoing queries. */ abstract queryProvider (cid: CID, provider: Provider, options: AbortOptions): Promise /** * Turn a provider into a concise Uint8Array representation for use in a Bloom * or Cuckoo filter */ abstract toFilterKey (provider: Provider): Uint8Array | string /** * Return `true` if we consider one provider to be the same as another */ abstract equals (providerA: Provider, providerB: Provider): boolean /** * Invoke the progress handler with the session-specific found provider event */ abstract emitFoundProviderProgressEvent (cid: CID, provider: Provider, options: BlockRetrievalOptions): void }