File size: 3,519 Bytes
5936c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fd704a9
56c49e4
5936c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36514c5
5936c9d
 
 
36514c5
5936c9d
 
 
 
 
 
 
 
 
 
 
 
36514c5
5936c9d
 
 
 
 
 
 
 
 
 
 
 
 
 
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
 * All background work, as independent loops. A loop never overlaps itself and
 * never blocks another loop (the old version queued everything behind one
 * lock, so a slow X scan delayed Telegram and seat checks).
 */
const log = require('./log')
const invites = require('./invites')
const alerts = require('./alerts')
const xscan = require('./x/scan')
const tg = require('./tg')
const pipeline = require('./pipeline')

const loops = {}

function every(name, ms, fn, initialDelay = 5000) {
  const loop = (loops[name] = { name, everyMs: ms, running: false, lastStart: null, lastEnd: null })
  const tick = async () => {
    if (loop.running) return
    loop.running = true
    loop.lastStart = log.now()
    try {
      await fn()
    } catch (err) {
      log.fail(name, err)
    } finally {
      loop.running = false
      loop.lastEnd = log.now()
    }
  }
  setTimeout(() => {
    tick()
    setInterval(tick, ms)
  }, initialDelay)
}

/** Free Spaces sleep after 48 h without visitors; a request through the public URL counts as one. */
async function keepAlive() {
  const host = process.env.SPACE_HOST
  if (!host) return
  await fetch(`https://${host}/api/ping?from=self`, { signal: AbortSignal.timeout(20000) }).catch(() => {})
}

function start() {
  every('invites', 15000, () => invites.checkDue(40), 4000)
  every('push', 60000, () => alerts.pushPending(), 8000)
  every('x-search', 60000, () => xscan.searchTick(), 12000)
  every('x-profiles', 180000, () => xscan.profileTick(), 40000)
  every('tg-watchdog', 60000, () => tg.watchdog(), 60000)
  every('tg-poll', 30000, () => tg.pollDialogs(), 60000)
  every('tg-catchup', 20000, () => tg.catchup(), 70000)
  every('tg-global', 180000, () => tg.globalSearch(), 130000)
  every('keepalive', 20 * 60000, keepAlive, 60000)
  tg.start().catch((err) => log.fail('telegram', err))
}

let scanning = null
let lastScan = null

/** The "抓取最新" button: run every source once, right now. */
function scanNow() {
  if (scanning) return scanning
  if (lastScan && Date.now() - lastScan.finishedMs < 20000) return Promise.resolve({ ...lastScan, cached: true })
  scanning = (async () => {
    const started = Date.now()
    const before = { posts: pipeline.stats.newPosts, codes: pipeline.stats.newCodes }
    const [xs, xp, tc, tp, tgl] = await Promise.all([
      xscan.searchTick({ all: true }).catch((err) => ({ error: err.message })),
      xscan.profileTick({ count: 8 }).catch((err) => ({ error: err.message })),
      tg.catchup().catch((err) => ({ error: err.message })),
      tg.pollDialogs().catch((err) => ({ error: err.message })),
      tg.globalSearch().catch((err) => ({ error: err.message })),
    ])
    const inv = await invites.checkDue(80).catch((err) => ({ error: err.message }))
    const push = await alerts.pushPending().catch((err) => ({ error: err.message }))
    lastScan = {
      finishedMs: Date.now(),
      seconds: Math.round((Date.now() - started) / 100) / 10,
      newPosts: pipeline.stats.newPosts - before.posts,
      newCodes: pipeline.stats.newCodes - before.codes,
      x: xs,
      profiles: xp,
      telegram: tc,
      telegramPoll: tp,
      telegramSearch: tgl,
      invites: inv,
      pushed: push.pushed || [],
    }
    return lastScan
  })().finally(() => (scanning = null))
  return scanning
}

function status() {
  return Object.values(loops).map(({ name, everyMs, running, lastStart, lastEnd }) => ({ name, everyMs, running, lastStart, lastEnd }))
}

module.exports = { start, scanNow, status }