aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/opentelemetry/metric-helpers/bittorrent-tracker-observers-builder.ts
blob: ef40c0fa9d6dbcb075ac09f734788fc8bc40d071 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { Meter } from '@opentelemetry/api'

export class BittorrentTrackerObserversBuilder {

  constructor (private readonly meter: Meter, private readonly trackerServer: any) {

  }

  buildObservers () {
    const activeInfohashes = this.meter.createObservableGauge('peertube_bittorrent_tracker_active_infohashes_total', {
      description: 'Total active infohashes in the PeerTube BitTorrent Tracker'
    })
    const inactiveInfohashes = this.meter.createObservableGauge('peertube_bittorrent_tracker_inactive_infohashes_total', {
      description: 'Total inactive infohashes in the PeerTube BitTorrent Tracker'
    })
    const peers = this.meter.createObservableGauge('peertube_bittorrent_tracker_peers_total', {
      description: 'Total peers in the PeerTube BitTorrent Tracker'
    })

    this.meter.addBatchObservableCallback(observableResult => {
      const infohashes = Object.keys(this.trackerServer.torrents)

      const counters = {
        activeInfohashes: 0,
        inactiveInfohashes: 0,
        peers: 0,
        uncompletedPeers: 0
      }

      for (const infohash of infohashes) {
        const content = this.trackerServer.torrents[infohash]

        const peers = content.peers
        if (peers.keys.length !== 0) counters.activeInfohashes++
        else counters.inactiveInfohashes++

        for (const peerId of peers.keys) {
          const peer = peers.peek(peerId)
          if (peer == null) return

          counters.peers++
        }
      }

      observableResult.observe(activeInfohashes, counters.activeInfohashes)
      observableResult.observe(inactiveInfohashes, counters.inactiveInfohashes)
      observableResult.observe(peers, counters.peers)
    }, [ activeInfohashes, inactiveInfohashes, peers ])
  }

}