|
| 1 | +import { PeerList } from './list.js' |
| 2 | +import type { Metric, Metrics, PeerId } from '@libp2p/interface' |
| 3 | + |
| 4 | +export interface TrackedPeerListInit { |
| 5 | + name: string |
| 6 | + metrics: Metrics |
| 7 | +} |
| 8 | + |
| 9 | +class TrackedPeerList extends PeerList { |
| 10 | + private readonly metric: Metric |
| 11 | + |
| 12 | + constructor (init: TrackedPeerListInit) { |
| 13 | + super() |
| 14 | + |
| 15 | + const { name, metrics } = init |
| 16 | + |
| 17 | + this.metric = metrics.registerMetric(name) |
| 18 | + this.updateComponentMetric() |
| 19 | + } |
| 20 | + |
| 21 | + pop (): PeerId | undefined { |
| 22 | + const peerId = super.pop() |
| 23 | + this.updateComponentMetric() |
| 24 | + return peerId |
| 25 | + } |
| 26 | + |
| 27 | + push (...peerIds: PeerId[]): void { |
| 28 | + super.push(...peerIds) |
| 29 | + this.updateComponentMetric() |
| 30 | + } |
| 31 | + |
| 32 | + shift (): PeerId | undefined { |
| 33 | + const peerId = super.shift() |
| 34 | + this.updateComponentMetric() |
| 35 | + return peerId |
| 36 | + } |
| 37 | + |
| 38 | + unshift (...peerIds: PeerId[]): number { |
| 39 | + const result = super.unshift(...peerIds) |
| 40 | + this.updateComponentMetric() |
| 41 | + return result |
| 42 | + } |
| 43 | + |
| 44 | + clear (): void { |
| 45 | + super.clear() |
| 46 | + this.updateComponentMetric() |
| 47 | + } |
| 48 | + |
| 49 | + private updateComponentMetric (): void { |
| 50 | + this.metric.update(this.length) |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +export interface CreateTrackedPeerListInit { |
| 55 | + /** |
| 56 | + * The metric name to use |
| 57 | + */ |
| 58 | + name: string |
| 59 | + |
| 60 | + /** |
| 61 | + * A metrics implementation |
| 62 | + */ |
| 63 | + metrics?: Metrics |
| 64 | +} |
| 65 | + |
| 66 | +/** |
| 67 | + * Creates a PeerList that reports it's size to the libp2p Metrics service |
| 68 | + * |
| 69 | + * @example |
| 70 | + * |
| 71 | + * * ```Typescript |
| 72 | + * import { trackedPeerList } from '@libp2p/peer-collections' |
| 73 | + * import { createLibp2p } from 'libp2p' |
| 74 | + * |
| 75 | + * const libp2p = await createLibp2p() |
| 76 | + * |
| 77 | + * const list = trackedPeerList({ name: 'my_metric_name', metrics: libp2p.metrics }) |
| 78 | + * list.push(peerId) |
| 79 | + * ``` |
| 80 | + */ |
| 81 | +export function trackedPeerList (config: CreateTrackedPeerListInit): PeerList { |
| 82 | + const { name, metrics } = config |
| 83 | + let map: PeerList |
| 84 | + |
| 85 | + if (metrics != null) { |
| 86 | + map = new TrackedPeerList({ name, metrics }) |
| 87 | + } else { |
| 88 | + map = new PeerList() |
| 89 | + } |
| 90 | + |
| 91 | + return map |
| 92 | +} |
0 commit comments