gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitefe1b485efe1b485mission 046: re-vendor Hybriel master 60b2817b (integration 8, #203): plugins mpackdb + web (bin/ git-ignored: hybriel, libhlrt.a, hlc.o, hlrt/ from native/zig-out)mreefe1b485/lib/jobs.hl

49.1 KB

  1. // lib/jobs.hl — THE BACKGROUND JOBS (mission 028: out of project.hl, unchanged): the daily TMDB sync run, the adult and kind
  2. // backfills, the details repair, the credits job, the duplicate merge, the short-id backfill and the collection seed — each with
  3. // its queue, its pause, its log lines, and the clocks that drive them (which job runs when, which one waits for which) — and, last,
  4. // the curated franchise seed (tracker#40). The work of ONE step is the topic's own (sync.hl, backfill.hl, details.hl, credits.hl,
  5. // merge.hl, shortids.hl, collections.hl, franchiseseed.hl).
  6. // A CLASS, not statics: its state (queues, positions, totals) is rewritten on every step, and a static cannot be reassigned —
  7. // project.hl makes the one instance (`jobs = new Jobs()`) after the server, as these lines ran there before; constructing it
  8. // starts the clocks and logs which jobs are off.
  9. import { env } from 'hl:proc'
  10. import { readFile, exists } from 'hl:fs'
  11. import { now, timestamp, every } from 'hl:time'
  12. import { syncEnabled, pauseMsAfter, msPerRequest } from './tmdb.hl'
  13. import { persistSync } from './sync.hl'
  14. import { emptyTotals, addTotals, totalsLine } from './sync-helpers.hl'
  15. import { planStart, planStep, planIds, planLine, markSynced, syncRunStep } from './dailysync.hl'
  16. import { adultBackfillScan, adultPred, backfillTitle, kindBackfillScan, kindPred, kindTitle, tvmazeStatusScan, statusPred, tvmazeStatusTitle, artScan, artPred, artTitle } from './backfill.hl'
  17. import { collectStep, collected } from './slices.hl'
  18. import { photoQueueStart, photoQueueStep, photoStep, persistPhotos } from './people.hl'
  19. import { detailsRepairScan, repairClass, completeStep, persistDetails, applySynced } from './details.hl'
  20. import { persistCredits, creditsScanStart, creditsPred, creditsStep } from './credits.hl'
  21. import { allFollowedShowIds } from './follows.hl'
  22. import { refreshCatalogShow } from './catalog.hl'
  23. import { searchTitleChanged, searchTitleRenamed } from './search.hl'
  24. import { mergePrepare, mergeLeft, mergeStep, mergeStats, mergeLine, persistMerge } from './merge.hl'
  25. import { shortIdStep, shortIdStats, persistShortIds, shortIdsLeft } from './shortids.hl'
  26. import { seedPrepare, seedScan, seedLeft, seedStep, seedLine, seedPersist } from './collections.hl'
  27. import { franchiseSeedPrepare, franchiseSeedStep, franchiseSeedLine, franchiseSeedStats } from './franchiseseed.hl'
  28. // ---- THE DAILY TMDB SYNC (tracker.worldapi.org#9, sync.hl; tracker#18, dailysync.hl) -------------------------
  29. // Once a day at TRACKER_SYNC_HOUR (UTC, default 4 — hl:time has no time zones; the container runs UTC). hl:web serves ONE
  30. // request at a time, so the run never takes the server for itself: a 1-second clock does ONE step per tick and returns — the
  31. // requests that queued meanwhile are served between two ticks, and a tick never starts inside a page render.
  32. // tracker#18: the run first asks TMDB's and TVmaze's CHANGE LISTS since the last run (dailysync.hl — one list page per step)
  33. // and then syncs only the titles of ours that changed, followed ones first — every title stays current, not only the followed
  34. // ones. FULL WALK (every followed show, as before #18) on the first run, after a gap > 14 days, or when a change list fails.
  35. // A title's step: sync.hl syncShow (1–3 TMDB requests + maybe its poster, TVmaze) + details.hl applySynced (the record's
  36. // title, overview, tagline … and cast/crew from the same details answer). After a step that made n requests the next waits
  37. // n × 260 ms (TMDB: ≤ 40 requests / 10 s) + 550 ms per TVmaze request (≤ 20 / 10 s, tracker.worldapi.org#12).
  38. // The finished run stores its day (dailysync.hl markSynced). Log: "tmdb sync: start, …", the change lists ("tmdb sync:
  39. // changes since …"), errors, slow steps, "tmdb sync done: mode=… changeRequests=… <totals>".
  40. // TRACKER_SYNC=0 switches it off; without TMDB_READ_TOKEN it is off too (logged once).
  41. syncHour = env('TRACKER_SYNC_HOUR') != null ? toNumber(env('TRACKER_SYNC_HOUR')) : 4
  42. syncOn = env('TRACKER_SYNC') != '0' && syncEnabled
  43. syncQueue = []
  44. syncPlanning = false
  45. syncMode = ''
  46. syncMark = false
  47. syncChangeRequests = 0
  48. syncAt = 0
  49. syncDay = ''
  50. syncNextAt = 0
  51. syncTotals = emptyTotals()
  52. syncFinish = () => {
  53. persistDetails()
  54. if (syncMark) { markSynced(syncDay) }
  55. console.log('tmdb sync done: mode=' + syncMode + ' changeRequests=' + syncChangeRequests + ' ' + totalsLine(syncTotals) + ' seconds=' + ((now() - syncAt) / 1000))
  56. return null
  57. }
  58. syncTick = () => {
  59. t = now()
  60. if (syncQueue.length == 0 && !syncPlanning) {
  61. stamp = timestamp(t)
  62. day = stamp.slice(0, 10)
  63. if (toNumber(stamp.slice(11, 13)) != syncHour || day == syncDay) { return null }
  64. syncDay = day
  65. syncAt = t
  66. syncNextAt = 0
  67. syncTotals = emptyTotals()
  68. syncChangeRequests = 0
  69. p = planStart(day, null)
  70. syncMode = p.mode
  71. syncMark = true
  72. if (p.mode == 'delta') {
  73. syncPlanning = true
  74. console.log('tmdb sync: start, changes ' + p.why)
  75. return null
  76. }
  77. syncQueue = allFollowedShowIds()
  78. console.log('tmdb sync: start, ' + syncQueue.length + ' followed shows, full walk (' + p.why + ')')
  79. if (syncQueue.length == 0) { syncFinish() }
  80. return null
  81. }
  82. if (t < syncNextAt) { return null }
  83. if (syncPlanning) {
  84. ps = planStep()
  85. syncChangeRequests = syncChangeRequests + ps.requests + ps.tvmazeRequests
  86. syncTotals.requests = syncTotals.requests + ps.requests
  87. syncTotals.tvmazeRequests = syncTotals.tvmazeRequests + ps.tvmazeRequests
  88. syncNextAt = now() + pauseMsAfter(ps)
  89. if (!ps.done) { return null }
  90. syncPlanning = false
  91. console.log('tmdb sync: ' + planLine())
  92. if (ps.failed != '') {
  93. // a change list could not be read: the old full walk, and the day is not advanced (the next run asks again)
  94. syncMode = 'full'
  95. syncMark = false
  96. syncQueue = allFollowedShowIds()
  97. console.log('tmdb sync: change list failed, full walk of ' + syncQueue.length + ' followed shows instead')
  98. } else {
  99. syncQueue = planIds()
  100. }
  101. if (syncQueue.length == 0) { syncFinish() }
  102. return null
  103. }
  104. id = syncQueue[0]
  105. rest = []
  106. let i = 1
  107. while (i < syncQueue.length) { rest.push(syncQueue[i]) i = i + 1 }
  108. syncQueue = rest
  109. // tracker#18: in a delta run a title nobody follows gets the light step (changed seasons, no TVmaze); tracker#35: one only on
  110. // TVmaze's change list its TVmaze status (dailysync.hl syncRunStep)
  111. r = syncRunStep(id, syncMode == 'delta')
  112. // tracker#18 + #28: the record's own fields (title, overview, tagline …) and the cast + crew from the same details answer
  113. if (r.details != null) {
  114. c = applySynced(id, r.details)
  115. if (c.error != '') { console.log('tmdb sync: ' + c.error) }
  116. if (c.renamed) { searchTitleRenamed(id) }
  117. }
  118. // the public lists (catalog.hl, tracker.worldapi.org#13): this show's place by its newest released episode; the sync
  119. // also brings TMDB's adult flag (mission 054) → the search's view of it too
  120. refreshCatalogShow(id)
  121. searchTitleChanged(id)
  122. took = now() - t
  123. syncTotals = addTotals(syncTotals, r)
  124. if (r.error != '') { console.log('tmdb sync: ' + r.error) }
  125. // a step blocks every request meanwhile (Saturday Night Live, 53 seasons, 4 requests: ~1.7 s) — say so in the log
  126. if (took > 1500) { console.log('tmdb sync: slow step, show ' + id + ', ' + r.requests + ' requests, ' + took + ' ms') }
  127. syncNextAt = now() + pauseMsAfter(r)
  128. if (syncQueue.length > 0 && syncTotals.shows % 10 == 0) { persistDetails() }
  129. if (syncQueue.length == 0) { syncFinish() }
  130. return null
  131. }
  132. // ---- THE ADULT-FLAG BACKFILL (mission 054, backfill.hl backfillTitle) -----------------------------------
  133. // The public lists and the search show only titles TMDB says are not adult (shows.hl isPublicTitle; unknown = hidden). At
  134. // start the app collects every title whose flag is still unknown and asks TMDB for ONE title per step — like the daily
  135. // sync, on the same clock, so requests queued meanwhile are served between two steps: one details request (adult,
  136. // poster_path, external ids) + the poster file when missing, then a pause of 260 ms per TMDB API request (≤ 40 / 10 s;
  137. // the poster comes from TMDB's image host, not the API, and is not counted). Each answered title goes into the lists
  138. // (catalog.hl refreshCatalogShow) and the search at once. RESUMES after a restart: the queue is built from what is
  139. // still unknown. Stops when the queue is empty; titles TMDB answers 404 for are marked (`adultCheck`) and stay hidden; a
  140. // passing failure (no answer, 429, 5xx) goes to the back of the queue, at most 2 more tries per start.
  141. // While the daily sync runs, the backfill waits. Log: start, every TRACKER_BACKFILL_LOG_EVERY (500) titles, done.
  142. // TRACKER_BACKFILL=0 switches it off; without TMDB_READ_TOKEN it is off too.
  143. backfillOn = env('TRACKER_BACKFILL') != '0' && syncEnabled
  144. backfillLogEvery = env('TRACKER_BACKFILL_LOG_EVERY') != null ? toNumber(env('TRACKER_BACKFILL_LOG_EVERY')) : 500
  145. backfillQueue = null
  146. backfillScan = null
  147. backfillPos = 0
  148. backfillDone = false
  149. backfillAt = 0
  150. backfillNextAt = 0
  151. backfillTries = {}
  152. backfillTotals = { titles = 0 adult = 0 notAdult = 0 unknown = 0 posters = 0 ids = 0 requests = 0 errors = 0 retries = 0 }
  153. backfillLine = () => {
  154. b = backfillTotals
  155. return b.titles + '/' + backfillQueue.length + ' titles, adult=' + b.adult + ' notAdult=' + b.notAdult + ' unknown=' + b.unknown + ' posters=' + b.posters
  156. + ' ids=' + b.ids + ' requests=' + b.requests + ' errors=' + b.errors + ' retries=' + b.retries + ' seconds=' + ((now() - backfillAt) / 1000)
  157. }
  158. backfillTick = () => {
  159. if (backfillDone) { return null }
  160. t = now()
  161. if (backfillQueue == null) {
  162. // mission 044: the table is scanned in slices (slices.hl), a few ms per tick, pages are served between the ticks
  163. if (backfillScan == null) { backfillScan = adultBackfillScan() backfillAt = t }
  164. if (!collectStep(backfillScan, adultPred)) { return null }
  165. backfillQueue = collected(backfillScan)
  166. console.log('adult backfill: start, ' + backfillQueue.length + ' titles without an adult flag (' + (now() - backfillAt) + ' ms to find them, ' + backfillScan.ms + ' ms of scanning in ' + backfillScan.scan.slices + ' slices)')
  167. if (backfillQueue.length == 0) { backfillDone = true console.log('adult backfill: nothing to do') }
  168. return null
  169. }
  170. if (t < backfillNextAt) { return null }
  171. id = backfillQueue[backfillPos]
  172. backfillPos = backfillPos + 1
  173. r = backfillTitle(id)
  174. if (r.retry && (backfillTries[id] == null || backfillTries[id] < 2)) {
  175. backfillTries[id] = backfillTries[id] == null ? 1 : backfillTries[id] + 1
  176. q = backfillQueue
  177. q.push(id)
  178. backfillQueue = q
  179. backfillTotals.retries = backfillTotals.retries + 1
  180. } else {
  181. backfillTotals.titles = backfillTotals.titles + 1
  182. if (r.adult == true) { backfillTotals.adult = backfillTotals.adult + 1 } else if (r.adult == false) { backfillTotals.notAdult = backfillTotals.notAdult + 1 } else { backfillTotals.unknown = backfillTotals.unknown + 1 }
  183. }
  184. backfillTotals.posters = backfillTotals.posters + r.posters
  185. backfillTotals.ids = backfillTotals.ids + r.ids
  186. backfillTotals.requests = backfillTotals.requests + r.requests
  187. backfillTotals.errors = backfillTotals.errors + r.errors
  188. if (r.error != '') { console.log('adult backfill: ' + r.error) }
  189. if (r.adult != null) {
  190. refreshCatalogShow(id)
  191. searchTitleChanged(id)
  192. }
  193. took = now() - t
  194. if (took > 1500) { console.log('adult backfill: slow step, show ' + id + ', ' + took + ' ms') }
  195. backfillNextAt = now() + r.requests * msPerRequest
  196. finished = backfillPos >= backfillQueue.length
  197. if (finished || backfillPos % 25 == 0) { persistSync() }
  198. if (!finished && backfillTotals.titles > 0 && backfillTotals.titles % backfillLogEvery == 0 && !r.retry) { console.log('adult backfill: ' + backfillLine()) }
  199. if (finished) {
  200. backfillDone = true
  201. console.log('adult backfill done: ' + backfillLine())
  202. }
  203. return null
  204. }
  205. // ---- THE DETAILS REPAIR (tracker.worldapi.org#26, details.hl completeStep) ----------------------------------------
  206. // Titles the person pages added from a filmography (#16) are MINIMAL (no poster, seasons, ids, cast …), and (tracker#33, mission
  207. // 029) the old tracker's migrated rows were never synced (5,697 on the live copy, 691 series without seasons) — shows.hl
  208. // isIncomplete. Opening one completes it (components/show.hl); this job completes the rest in the background: at start it
  209. // collects every incomplete, non-adult title (the visibly reduced ones first, details.hl detailsRepairQueue) and does ONE per
  210. // step on the app's clock, like the adult backfill — a step is the daily sync's work for one title
  211. // (1–3 TMDB requests + poster + TVmaze), requests queued meanwhile are served between two steps; then a pause of 260 ms per
  212. // TMDB request + 550 ms per TVmaze request (pauseMsAfter: ≤ 40 / 10 s, ≤ 20 / 10 s). RESUMES after a restart (the queue is
  213. // what is still incomplete); TMDB 404 marks the title (`detailsCheck`), a passing failure goes to the back of the queue (at
  214. // most 2 more tries per start). Waits while the daily sync or the adult backfill runs. Persisted every 10 titles + at the end.
  215. // Log: start, every TRACKER_REPAIR_LOG_EVERY (100) titles, each failure, done. TRACKER_REPAIR=0 switches it off (off too
  216. // without TMDB_READ_TOKEN). TRACKER_REPAIR_FAST=1 (the gate, fake TMDB only): 20 ms pause instead.
  217. repairOn = env('TRACKER_REPAIR') != '0' && syncEnabled
  218. repairFast = env('TRACKER_REPAIR_FAST') == '1'
  219. repairLogEvery = env('TRACKER_REPAIR_LOG_EVERY') != null ? toNumber(env('TRACKER_REPAIR_LOG_EVERY')) : 100
  220. repairQueue = null
  221. repairScan = null
  222. repairPos = 0
  223. repairDone = false
  224. repairAt = 0
  225. repairNextAt = 0
  226. repairTries = {}
  227. repairTotals = { titles = 0 complete = 0 failed = 0 adult = 0 newSeasons = 0 newEpisodes = 0 posters = 0 cast = 0 requests = 0 tvmazeRequests = 0 retries = 0 }
  228. repairLine = () => {
  229. b = repairTotals
  230. return b.titles + '/' + repairQueue.length + ' titles, complete=' + b.complete + ' failed=' + b.failed + ' adult=' + b.adult + ' newSeasons=' + b.newSeasons + ' newEpisodes=' + b.newEpisodes
  231. + ' posters=' + b.posters + ' cast=' + b.cast + ' requests=' + b.requests + ' tvmazeRequests=' + b.tvmazeRequests + ' retries=' + b.retries + ' seconds=' + ((now() - repairAt) / 1000)
  232. }
  233. repairTick = () => {
  234. if (repairDone) { return null }
  235. t = now()
  236. if (repairQueue == null) {
  237. if (repairScan == null) { repairScan = detailsRepairScan() repairAt = t }
  238. if (!collectStep(repairScan, repairClass)) { return null }
  239. repairQueue = collected(repairScan)
  240. console.log('details repair: start, ' + repairQueue.length + ' incomplete titles (' + (now() - repairAt) + ' ms to find them, ' + repairScan.ms + ' ms of scanning in ' + repairScan.scan.slices + ' slices)')
  241. if (repairQueue.length == 0) { repairDone = true console.log('details repair: nothing to do') }
  242. return null
  243. }
  244. if (t < repairNextAt) { return null }
  245. id = repairQueue[repairPos]
  246. r = completeStep(id)
  247. took = now() - t
  248. if (took > 1500) { console.log('details repair: slow step, show ' + id + ', ' + took + ' ms') }
  249. if (r.error != '') { console.log('details repair: ' + r.error) }
  250. repairNextAt = now() + (repairFast ? 20 : pauseMsAfter(r))
  251. // a series takes several steps: the same title again next time
  252. if (!r.done && !r.retry) { return null }
  253. repairPos = repairPos + 1
  254. if (r.retry && (repairTries[id] == null || repairTries[id] < 2)) {
  255. repairTries[id] = repairTries[id] == null ? 1 : repairTries[id] + 1
  256. q = repairQueue
  257. q.push(id)
  258. repairQueue = q
  259. repairTotals.retries = repairTotals.retries + 1
  260. } else if (!r.skipped) {
  261. // done: its counts (a failed first step: the request alone)
  262. sum = r.sum
  263. repairTotals.titles = repairTotals.titles + 1
  264. if (r.adult == true) { repairTotals.adult = repairTotals.adult + 1 } else if (sum.steps == 0) { repairTotals.failed = repairTotals.failed + 1 } else { repairTotals.complete = repairTotals.complete + 1 }
  265. repairTotals.newSeasons = repairTotals.newSeasons + sum.newSeasons
  266. repairTotals.newEpisodes = repairTotals.newEpisodes + sum.newEpisodes
  267. repairTotals.posters = repairTotals.posters + sum.posters
  268. repairTotals.cast = repairTotals.cast + sum.cast
  269. repairTotals.requests = repairTotals.requests + (sum.steps == 0 ? r.requests : sum.requests)
  270. repairTotals.tvmazeRequests = repairTotals.tvmazeRequests + sum.tvmazeRequests
  271. }
  272. finished = repairPos >= repairQueue.length
  273. if (finished || repairPos % 10 == 0) { persistDetails() }
  274. if (!finished && !r.skipped && !r.retry && repairTotals.titles > 0 && repairTotals.titles % repairLogEvery == 0) { console.log('details repair: ' + repairLine()) }
  275. if (finished) {
  276. repairDone = true
  277. console.log('details repair done: ' + repairLine())
  278. }
  279. return null
  280. }
  281. // ---- THE TVMAZE STATUS BACKFILL (tracker#35, mission 030, backfill.hl tvmazeStatusTitle) — the details repair's second part ----
  282. // The page's status pill shows TVmaze's status when a series has one (fresher than TMDB's). The sync stores it whenever it merges
  283. // TVmaze's episodes (followed series, every completion); the series it never reached get it here: once the details repair is
  284. // done (same switch, TRACKER_REPAIR) every series with a TVmaze id and no tvmazeStatus, ONE TVmaze request per step, then 550 ms
  285. // (TVmaze: ≤ 20 / 10 s). RESUMES after a restart (the queue = what still has none); a 404 marks the series
  286. // (`tvmazeStatusCheck`), a passing failure goes to the back of the queue (at most 2 more tries per start). Waits while the daily
  287. // sync runs. Persisted every 25 series + at the end. Log: start, every TRACKER_REPAIR_LOG_EVERY series, done.
  288. statusQueue = null
  289. statusScan = null
  290. statusPos = 0
  291. statusDone = false
  292. statusAt = 0
  293. statusNextAt = 0
  294. statusTries = {}
  295. statusTotals = { series = 0 stored = 0 types = 0 moved = 0 notFound = 0 requests = 0 errors = 0 retries = 0 }
  296. statusLine = () => {
  297. b = statusTotals
  298. return b.series + '/' + statusQueue.length + ' series, stored=' + b.stored + ' types=' + b.types + ' moved=' + b.moved + ' notFound=' + b.notFound + ' tvmazeRequests=' + b.requests + ' errors=' + b.errors + ' retries=' + b.retries + ' seconds=' + ((now() - statusAt) / 1000)
  299. }
  300. statusTick = () => {
  301. if (statusDone) { return null }
  302. t = now()
  303. if (statusQueue == null) {
  304. if (statusScan == null) { statusScan = tvmazeStatusScan() statusAt = t }
  305. if (!collectStep(statusScan, statusPred)) { return null }
  306. statusQueue = collected(statusScan)
  307. console.log('tvmaze status: start, ' + statusQueue.length + ' series without a TVmaze status or type (' + (now() - statusAt) + ' ms to find them, ' + statusScan.ms + ' ms of scanning in ' + statusScan.scan.slices + ' slices)')
  308. if (statusQueue.length == 0) { statusDone = true console.log('tvmaze status: nothing to do') }
  309. return null
  310. }
  311. if (t < statusNextAt) { return null }
  312. id = statusQueue[statusPos]
  313. statusPos = statusPos + 1
  314. r = tvmazeStatusTitle(id)
  315. if (r.retry && (statusTries[id] == null || statusTries[id] < 2)) {
  316. statusTries[id] = statusTries[id] == null ? 1 : statusTries[id] + 1
  317. q = statusQueue
  318. q.push(id)
  319. statusQueue = q
  320. statusTotals.retries = statusTotals.retries + 1
  321. } else {
  322. statusTotals.series = statusTotals.series + 1
  323. if (r.status != null) { statusTotals.stored = statusTotals.stored + 1 } else if (r.errors > 0) { statusTotals.notFound = statusTotals.notFound + 1 }
  324. if (r.type != null) { statusTotals.types = statusTotals.types + 1 }
  325. // #43 (mission 037): TVmaze's type made it a show (or no longer one) — it moves between /series and /shows at once
  326. if (r.moved) { refreshCatalogShow(id) statusTotals.moved = statusTotals.moved + 1 console.log('tvmaze status: moved ' + id + ' (TVmaze type ' + r.type + ')') }
  327. }
  328. statusTotals.requests = statusTotals.requests + r.tvmazeRequests
  329. statusTotals.errors = statusTotals.errors + r.errors
  330. if (r.error != '') { console.log('tvmaze status: ' + r.error) }
  331. statusNextAt = now() + (repairFast ? 20 : pauseMsAfter(r))
  332. finished = statusPos >= statusQueue.length
  333. if (finished || statusPos % 25 == 0) { persistSync() }
  334. if (!finished && !r.retry && statusTotals.series > 0 && statusTotals.series % repairLogEvery == 0) { console.log('tvmaze status: ' + statusLine()) }
  335. if (finished) {
  336. statusDone = true
  337. console.log('tvmaze status done: ' + statusLine())
  338. }
  339. return null
  340. }
  341. // ---- THE KIND BACKFILL (tracker.worldapi.org#21, mission 068, backfill.hl kindTitle) ----------------------------------
  342. // Every TV title without a stored kind gets one: a title with a show genre (Reality / Talk / News) from the stored data (no
  343. // request), any other from TMDB's TV type (ONE request: GET /tv/<id>, then 260 ms pause). Starts once the adult backfill is
  344. // done (or off), waits while the daily sync runs, ONE title per step on the same clock. A title that becomes a SHOW moves from
  345. // /series to /shows at once (catalog.hl refreshCatalogShow). RESUMES after a restart (the queue = every TV title still without
  346. // a kind); a 404 stores the genres' answer + `kindCheck`; a passing failure goes to the back of the queue, at most 2 more tries
  347. // per start. Log: start, every TRACKER_KINDS_LOG_EVERY (500) titles, done. TRACKER_KINDS=0 switches it off; without
  348. // TMDB_READ_TOKEN it is off too (the lists still split by genre: shows.hl titleKind).
  349. kindsOn = env('TRACKER_KINDS') != '0' && syncEnabled
  350. kindsLogEvery = env('TRACKER_KINDS_LOG_EVERY') != null ? toNumber(env('TRACKER_KINDS_LOG_EVERY')) : 500
  351. kindQueue = null
  352. kindScan = null
  353. kindPos = 0
  354. kindDone = false
  355. kindAt = 0
  356. kindNextAt = 0
  357. kindTries = {}
  358. kindTotals = { titles = 0 series = 0 shows = 0 fromGenre = 0 moved = 0 requests = 0 errors = 0 retries = 0 }
  359. kindLine = () => {
  360. k = kindTotals
  361. return k.titles + '/' + kindQueue.length + ' titles, series=' + k.series + ' shows=' + k.shows + ' fromGenre=' + k.fromGenre + ' moved=' + k.moved
  362. + ' requests=' + k.requests + ' errors=' + k.errors + ' retries=' + k.retries + ' seconds=' + ((now() - kindAt) / 1000)
  363. }
  364. kindTick = () => {
  365. if (kindDone) { return null }
  366. t = now()
  367. if (kindQueue == null) {
  368. if (kindScan == null) { kindScan = kindBackfillScan() kindAt = t }
  369. if (!collectStep(kindScan, kindPred)) { return null }
  370. kindQueue = collected(kindScan)
  371. console.log('kind backfill: start, ' + kindQueue.length + ' TV titles without a kind (' + (now() - kindAt) + ' ms to find them, ' + kindScan.ms + ' ms of scanning in ' + kindScan.scan.slices + ' slices)')
  372. if (kindQueue.length == 0) { kindDone = true console.log('kind backfill: nothing to do') }
  373. return null
  374. }
  375. if (t < kindNextAt) { return null }
  376. id = kindQueue[kindPos]
  377. kindPos = kindPos + 1
  378. r = kindTitle(id)
  379. if (r.retry && (kindTries[id] == null || kindTries[id] < 2)) {
  380. kindTries[id] = kindTries[id] == null ? 1 : kindTries[id] + 1
  381. q = kindQueue
  382. q.push(id)
  383. kindQueue = q
  384. kindTotals.retries = kindTotals.retries + 1
  385. } else {
  386. kindTotals.titles = kindTotals.titles + 1
  387. if (r.kind == 'show') { kindTotals.shows = kindTotals.shows + 1 } else if (r.kind == 'series') { kindTotals.series = kindTotals.series + 1 }
  388. if (r.fromGenre) { kindTotals.fromGenre = kindTotals.fromGenre + 1 }
  389. }
  390. kindTotals.requests = kindTotals.requests + r.requests
  391. kindTotals.errors = kindTotals.errors + r.errors
  392. if (r.error != '') { console.log('kind backfill: ' + r.error) }
  393. // until now the genres decided (no show genre = series): only a title TMDB's type makes a SHOW changes its list
  394. if (r.kind == 'show' && !r.fromGenre) {
  395. refreshCatalogShow(id)
  396. kindTotals.moved = kindTotals.moved + 1
  397. }
  398. took = now() - t
  399. if (took > 1500) { console.log('kind backfill: slow step, show ' + id + ', ' + took + ' ms') }
  400. kindNextAt = now() + r.requests * msPerRequest
  401. finished = kindPos >= kindQueue.length
  402. if (finished || kindPos % 25 == 0) { persistSync() }
  403. if (!finished && kindTotals.titles > 0 && kindTotals.titles % kindsLogEvery == 0 && !r.retry) { console.log('kind backfill: ' + kindLine()) }
  404. if (finished) {
  405. kindDone = true
  406. console.log('kind backfill done: ' + kindLine())
  407. }
  408. return null
  409. }
  410. // ---- THE CREDITS JOB (tracker.worldapi.org#28, credits.hl creditsStep) ------------------------------------------------------
  411. // Every PUBLIC title (adult == false; adult/unknown are skipped) with a TMDB id gets its whole cast + crew once: at start (after
  412. // the adult backfill and the details repair are done) the job collects every such title without `creditsAt` and asks ONE per
  413. // step on the app's clock — one request (details + credits / aggregate_credits), then 260 ms (≤ 40 / 10 s); requests queued
  414. // meanwhile are served between two steps. Titles the details repair, the daily sync or an import already did carry `creditsAt`
  415. // and are not asked. RESUMES after a restart (the queue = what still has no credits); TMDB 404 / adult → `creditsCheck`, never
  416. // asked again; a passing failure goes to the back of the queue (at most 2 more tries per start). Waits while the daily sync
  417. // runs. Persisted (shows + people only) every 25 titles + at the end. Log: start, every TRACKER_CREDITS_LOG_EVERY (500) titles, failures, slow steps
  418. // (> 1.5 s), done. TRACKER_CREDITS=0 switches it off (off too without TMDB_READ_TOKEN). TRACKER_CREDITS_FAST=1 (the gate, fake
  419. // TMDB only): 20 ms pause instead.
  420. // MEMORY LIMIT: the runtime never frees what a fetch + JSON parse took (mission 061 measured ~6 MB more RSS per title on the real
  421. // data, 300 fetches of a 440 KB JSON = +2.7 GB in a 10-line script) — the whole job in one process would add ~35 GB. Before every
  422. // step the job reads its own RSS (/proc/self/status); above TRACKER_CREDITS_MAX_MB (16000) it PAUSES for this process (logged) and
  423. // goes on with what is left after the next restart (deploy, `docker restart`).
  424. creditsOn = env('TRACKER_CREDITS') != '0' && syncEnabled
  425. creditsFast = env('TRACKER_CREDITS_FAST') == '1'
  426. creditsLogEvery = env('TRACKER_CREDITS_LOG_EVERY') != null ? toNumber(env('TRACKER_CREDITS_LOG_EVERY')) : 500
  427. creditsQueueIds = null
  428. creditsScan = null
  429. creditsPos = 0
  430. creditsDone = false
  431. creditsAt = 0
  432. creditsNextAt = 0
  433. creditsTries = {}
  434. creditsMaxMb = env('TRACKER_CREDITS_MAX_MB') != null ? toNumber(env('TRACKER_CREDITS_MAX_MB')) : 16000
  435. creditsTotals = { titles = 0 done = 0 failed = 0 cast = 0 crew = 0 people = 0 requests = 0 retries = 0 slowest = 0 }
  436. // this process' resident memory in MB (VmRSS), 0 when unknown
  437. rssMb = () => {
  438. if (!exists('/proc/self/status')) { return 0 }
  439. t = readFile('/proc/self/status')
  440. i = t != null ? t.indexOf('VmRSS:') : -1
  441. if (i < 0) { return 0 }
  442. kb = toNumber(t.slice(i + 6, t.indexOf('kB', i)).trim())
  443. return kb != null ? (kb - kb % 1024) / 1024 : 0
  444. }
  445. creditsLine = () => {
  446. b = creditsTotals
  447. return b.titles + '/' + creditsQueueIds.length + ' titles, done=' + b.done + ' failed=' + b.failed + ' cast=' + b.cast + ' crew=' + b.crew + ' people=' + b.people
  448. + ' requests=' + b.requests + ' retries=' + b.retries + ' slowestStepMs=' + b.slowest + ' seconds=' + ((now() - creditsAt) / 1000)
  449. }
  450. creditsTick = () => {
  451. if (creditsDone) { return null }
  452. t = now()
  453. if (creditsQueueIds == null) {
  454. if (creditsScan == null) { creditsScan = creditsScanStart() creditsAt = t }
  455. if (!collectStep(creditsScan, creditsPred)) { return null }
  456. creditsQueueIds = collected(creditsScan)
  457. console.log('credits job: start, ' + creditsQueueIds.length + ' titles without credits (' + (now() - creditsAt) + ' ms to find them, ' + creditsScan.ms + ' ms of scanning in ' + creditsScan.scan.slices + ' slices)')
  458. if (creditsQueueIds.length == 0) { creditsDone = true console.log('credits job: nothing to do') }
  459. return null
  460. }
  461. if (t < creditsNextAt) { return null }
  462. mb = rssMb()
  463. if (mb > creditsMaxMb) {
  464. creditsDone = true
  465. persistCredits()
  466. console.log('credits job: paused, RSS ' + mb + ' MB > TRACKER_CREDITS_MAX_MB ' + creditsMaxMb + ' — ' + (creditsQueueIds.length - creditsPos) + ' titles left for the next start; ' + creditsLine())
  467. return null
  468. }
  469. id = creditsQueueIds[creditsPos]
  470. creditsPos = creditsPos + 1
  471. r = creditsStep(id)
  472. took = now() - t
  473. if (took > creditsTotals.slowest) { creditsTotals.slowest = took }
  474. if (took > 1500) { console.log('credits job: slow step, show ' + id + ', ' + took + ' ms, cast=' + r.cast + ' crew=' + r.crew + ' people=' + r.people) }
  475. if (r.error != '') { console.log('credits job: ' + r.error) }
  476. creditsNextAt = now() + (creditsFast ? 20 : r.requests * msPerRequest)
  477. if (r.retry && (creditsTries[id] == null || creditsTries[id] < 2)) {
  478. creditsTries[id] = creditsTries[id] == null ? 1 : creditsTries[id] + 1
  479. q = creditsQueueIds
  480. q.push(id)
  481. creditsQueueIds = q
  482. creditsTotals.retries = creditsTotals.retries + 1
  483. } else if (!r.skipped) {
  484. creditsTotals.titles = creditsTotals.titles + 1
  485. if (r.error != '') { creditsTotals.failed = creditsTotals.failed + 1 } else { creditsTotals.done = creditsTotals.done + 1 }
  486. creditsTotals.cast = creditsTotals.cast + r.cast
  487. creditsTotals.crew = creditsTotals.crew + r.crew
  488. creditsTotals.people = creditsTotals.people + r.people
  489. }
  490. creditsTotals.requests = creditsTotals.requests + r.requests
  491. finished = creditsPos >= creditsQueueIds.length
  492. if (finished || creditsPos % 25 == 0) { persistCredits() }
  493. if (!finished && !r.skipped && !r.retry && creditsTotals.titles > 0 && creditsTotals.titles % creditsLogEvery == 0) { console.log('credits job: ' + creditsLine()) }
  494. if (finished) {
  495. creditsDone = true
  496. console.log('credits job done: ' + creditsLine())
  497. }
  498. return null
  499. }
  500. // ---- THE DUPLICATE MERGE (tracker.worldapi.org#31, mission 026, merge.hl) ----------------------------------------------------
  501. // The old tracker's duplicate titles (same type + TMDB id) become ONE record each — follows, watches, seasons, cast, credits and
  502. // timelines moved to the keeper, the others kept as tombstones whose slug and short id lead to it — and seasons that name a title
  503. // without being in its list are merged into their twin or linked, and (tracker#39) a season's double episodes into one (merge.hl
  504. // has the rules). On its own clock (every 0.1 s) ONE
  505. // item per tick (a duplicate group, or one title's stray seasons; no TMDB), so pages are served between two items. The TMDB jobs
  506. // below (daily sync, backfills, repair, credits, collections) wait until it is done: none of them works on a record that is about
  507. // to become a tombstone. RESUMES after a restart (the queue = what is still duplicated / stray). Persisted every 10 items and at
  508. // the end. Log: start, one line per tombstone / repaired title, done; with nothing to do one line. TRACKER_MERGE=0 switches it off.
  509. mergeOn = env('TRACKER_MERGE') != '0'
  510. mergeRun = { started = false done = !mergeOn at = 0 items = 0 slowest = 0 }
  511. mergeTick = () => {
  512. if (mergeRun.done) { return null }
  513. t = now()
  514. if (!mergeRun.started) {
  515. if (mergeRun.at == 0) { mergeRun.at = t }
  516. if (!mergePrepare()) { return null }
  517. mergeRun.started = true
  518. n = mergeLeft()
  519. st = mergeStats()
  520. console.log('merge: start, ' + st.groups + ' duplicate groups (' + st.records + ' records), ' + st.strayTitles + ' titles with stray seasons, ' + st.doubleSeasons + ' seasons with double episodes (' + st.ms + ' ms to find them)')
  521. if (n == 0) {
  522. mergeRun.done = true
  523. console.log('merge: nothing to do')
  524. }
  525. return null
  526. }
  527. r = mergeStep()
  528. mergeRun.items = mergeRun.items + 1
  529. took = now() - t
  530. if (took > mergeRun.slowest) { mergeRun.slowest = took }
  531. if (took > 1500) { console.log('merge: slow step, ' + took + ' ms') }
  532. if (r.done || mergeRun.items % 10 == 0) { persistMerge() }
  533. if (r.done) {
  534. mergeRun.done = true
  535. console.log('merge done: ' + mergeLine() + ' items=' + mergeRun.items + ' slowestStepMs=' + mergeRun.slowest + ' seconds=' + ((now() - mergeRun.at) / 1000))
  536. }
  537. return null
  538. }
  539. if (!mergeOn) { console.log('merge: off (TRACKER_MERGE=0)') }
  540. else {
  541. mergeClock = every(0.1)
  542. on mergeClock.tick(x) {
  543. mergeTick()
  544. return null
  545. }
  546. }
  547. // ONE clock for all five (a tick every 0.1 s): the daily sync's step once a second as before; the backfill's steps in
  548. // between, only while no daily run is going on; the details repair only when neither has work (then its TVmaze status part,
  549. // tracker#35); then the kind backfill (#21);
  550. // the credits job (#28) last
  551. clockOn = syncOn || backfillOn || repairOn || kindsOn || creditsOn
  552. clockTicks = 0
  553. if (syncOn) { console.log('tmdb sync: daily at ' + syncHour + ':00 UTC') } else { console.log('tmdb sync: off (' + (syncEnabled ? 'TRACKER_SYNC=0' : 'no TMDB_READ_TOKEN') + ')') }
  554. if (!backfillOn) { console.log('adult backfill: off (' + (syncEnabled ? 'TRACKER_BACKFILL=0' : 'no TMDB_READ_TOKEN') + ')') }
  555. if (!repairOn) { console.log('details repair: off (' + (syncEnabled ? 'TRACKER_REPAIR=0' : 'no TMDB_READ_TOKEN') + ')') }
  556. if (!creditsOn) { console.log('credits job: off (' + (syncEnabled ? 'TRACKER_CREDITS=0' : 'no TMDB_READ_TOKEN') + ')') }
  557. if (!kindsOn) { console.log('kind backfill: off (' + (syncEnabled ? 'TRACKER_KINDS=0' : 'no TMDB_READ_TOKEN') + ')') }
  558. if (clockOn) {
  559. syncClock = every(0.1)
  560. on syncClock.tick(x) {
  561. clockTicks = clockTicks + 1
  562. // tracker#31: not before the duplicate merge is done
  563. if (!mergeRun.done) { return null }
  564. busy = syncQueue.length > 0 || syncPlanning
  565. if (syncOn && clockTicks % 10 == 0) { syncTick() }
  566. free = !busy && syncQueue.length == 0 && !syncPlanning
  567. if (backfillOn && free && !backfillDone) { backfillTick() }
  568. else if (repairOn && free && (!backfillOn || backfillDone) && !repairDone) { repairTick() }
  569. else if (repairOn && free && (!backfillOn || backfillDone) && !statusDone) { statusTick() }
  570. else if (kindsOn && free && (!backfillOn || backfillDone) && (!repairOn || (repairDone && statusDone)) && !kindDone) { kindTick() }
  571. else if (creditsOn && free && (!backfillOn || backfillDone) && (!repairOn || (repairDone && statusDone)) && (!kindsOn || kindDone)) { creditsTick() }
  572. return null
  573. }
  574. }
  575. // ---- THE SHORT-ID BACKFILL (mission 060, tracker.worldapi.org#27, shortids.hl shortIdStep) ----------------------------
  576. // Every show and person without a short id gets one in the background: on its own clock (every 0.1 s) ONE batch per tick,
  577. // as many records as fit into TRACKER_SHORTID_BUDGET_MS (default 40 ms) — no TMDB, only the tables — so a page waits at
  578. // most one batch. The queue is built at start (`ensureShortIds`) from what is still missing = it resumes after a restart.
  579. // Persisted every 20 batches and at the end. Log: start, every TRACKER_SHORTID_LOG_EVERY (5000) records, done; with nothing
  580. // to do one line. TRACKER_SHORTIDS=0 switches it off (the gate's resume check).
  581. shortIdOn = env('TRACKER_SHORTIDS') != '0'
  582. shortIdBudget = env('TRACKER_SHORTID_BUDGET_MS') != null ? toNumber(env('TRACKER_SHORTID_BUDGET_MS')) : 40
  583. shortIdLogEvery = env('TRACKER_SHORTID_LOG_EVERY') != null ? toNumber(env('TRACKER_SHORTID_LOG_EVERY')) : 5000
  584. shortIdRun = { at = 0 batches = 0 assigned = 0 nextLog = 0 slowest = 0 slowestPersist = 0 done = false }
  585. shortIdTick = () => {
  586. if (shortIdRun.done) { return null }
  587. t = now()
  588. r = shortIdStep(shortIdBudget)
  589. took = now() - t
  590. shortIdRun.batches = shortIdRun.batches + 1
  591. shortIdRun.assigned = shortIdRun.assigned + r.assigned
  592. if (took > shortIdRun.slowest) { shortIdRun.slowest = took }
  593. if (r.done || shortIdRun.batches % 20 == 0) {
  594. tp = now()
  595. persistShortIds()
  596. if (now() - tp > shortIdRun.slowestPersist) { shortIdRun.slowestPersist = now() - tp }
  597. }
  598. if (!r.done && shortIdRun.assigned >= shortIdRun.nextLog) {
  599. console.log('short ids: ' + shortIdRun.assigned + ' assigned, ' + r.left + ' left, ' + ((now() - shortIdRun.at) / 1000) + ' s')
  600. shortIdRun.nextLog = shortIdRun.nextLog + shortIdLogEvery
  601. }
  602. if (r.done) {
  603. shortIdRun.done = true
  604. s = shortIdStats()
  605. console.log('short ids done: assigned=' + shortIdRun.assigned + ' oldKept=' + s.oldKept + ' batches=' + shortIdRun.batches + ' slowestBatchMs=' + shortIdRun.slowest + ' slowestPersistMs=' + shortIdRun.slowestPersist + ' seconds=' + ((now() - shortIdRun.at) / 1000))
  606. }
  607. return null
  608. }
  609. if (!shortIdOn) { console.log('short ids: backfill off (TRACKER_SHORTIDS=0), ' + shortIdsLeft() + ' records without one') }
  610. else if (shortIdsLeft() == 0) { console.log('short ids: nothing to do') }
  611. else {
  612. shortIdRun.at = now()
  613. shortIdRun.nextLog = shortIdLogEvery
  614. console.log('short ids: backfill start, ' + shortIdsLeft() + ' records, ' + shortIdBudget + ' ms per batch')
  615. shortIdClock = every(0.1)
  616. on shortIdClock.tick(x) {
  617. shortIdTick()
  618. return null
  619. }
  620. }
  621. // ---- THE COLLECTION SEED (mission 066, tracker.worldapi.org#19, collections.hl seedStep) ------------------------------------
  622. // TMDB's movie collections become timelines: ONE movie per step (its details; once per collection the collection's parts), on
  623. // its own 0.1 s clock like the adult backfill — a pause of 260 ms per TMDB request made (≤ 40 / 10 s). It WAITS while the daily
  624. // sync or the adult backfill runs (they share TMDB's limit and the backfill brings the adult flags it skips by); since the merge
  625. // (mission 070) also until the details repair, the kind backfill and the credits job are done (or paused) — the LAST job. The queue =
  626. // every non-adult movie without a check row, so it RESUMES after a restart and does nothing once all are checked. Persisted
  627. // every TRACKER_COLLECTIONS_PERSIST_EVERY (25) steps and at the end. Log: start, every TRACKER_COLLECTIONS_LOG_EVERY (500) movies, done.
  628. // TRACKER_COLLECTIONS=0 switches it off; without TMDB_READ_TOKEN it is off too.
  629. collectionsOn = env('TRACKER_COLLECTIONS') != '0' && syncEnabled
  630. collectionsLogEvery = env('TRACKER_COLLECTIONS_LOG_EVERY') != null ? toNumber(env('TRACKER_COLLECTIONS_LOG_EVERY')) : 500
  631. collectionsPersistEvery = env('TRACKER_COLLECTIONS_PERSIST_EVERY') != null ? toNumber(env('TRACKER_COLLECTIONS_PERSIST_EVERY')) : 25
  632. collectionRun = { at = 0 steps = 0 nextAt = 0 done = false started = false slowest = 0 }
  633. collectionTick = () => {
  634. if (collectionRun.done) { return null }
  635. // mission 070 (merge): also behind the details repair, the kind backfill and the credits job — one TMDB pacing at a time
  636. if (!mergeRun.done || syncQueue.length > 0 || syncPlanning || (backfillOn && !backfillDone) || (repairOn && (!repairDone || !statusDone)) || (kindsOn && !kindDone) || (creditsOn && !creditsDone)) { return null }
  637. t = now()
  638. if (!collectionRun.started) {
  639. if (collectionRun.at == 0) { collectionRun.at = t }
  640. collectionRun.started = false
  641. if (!seedPrepare()) { return null }
  642. collectionRun.started = true
  643. n = seedLeft()
  644. console.log('collections: start, ' + n + ' movies to check (' + (now() - collectionRun.at) + ' ms to find them, ' + seedScan.ms + ' ms of scanning)')
  645. if (n == 0) { collectionRun.done = true console.log('collections: nothing to do') }
  646. return null
  647. }
  648. if (t < collectionRun.nextAt) { return null }
  649. r = seedStep()
  650. if (r.done) {
  651. collectionRun.done = true
  652. seedPersist()
  653. console.log('collections done: ' + seedLine() + ' seconds=' + ((now() - collectionRun.at) / 1000) + ' slowestStepMs=' + collectionRun.slowest)
  654. return null
  655. }
  656. collectionRun.steps = collectionRun.steps + 1
  657. took = now() - t
  658. if (took > collectionRun.slowest) { collectionRun.slowest = took }
  659. if (r.error != '') { console.log('collections: ' + r.error) }
  660. if (took > 1500) { console.log('collections: slow step, ' + took + ' ms') }
  661. collectionRun.nextAt = now() + r.requests * msPerRequest
  662. if (collectionRun.steps % collectionsPersistEvery == 0) { seedPersist() }
  663. if (collectionRun.steps % collectionsLogEvery == 0) { console.log('collections: ' + seedLine() + ' seconds=' + ((now() - collectionRun.at) / 1000)) }
  664. return null
  665. }
  666. if (!collectionsOn) { console.log('collections: off (' + (syncEnabled ? 'TRACKER_COLLECTIONS=0' : 'no TMDB_READ_TOKEN') + ')') }
  667. else {
  668. collectionClock = every(0.1)
  669. on collectionClock.tick(x) {
  670. collectionTick()
  671. return null
  672. }
  673. }
  674. // ---- THE CURATED FRANCHISE SEED (tracker.worldapi.org#40, mission 034, franchiseseed.hl) --------------------------------------
  675. // data/franchises.json → franchises + timelines, movies AND series. The LAST start job: it waits until the merge, the daily sync,
  676. // the backfills, the details repair, the kind backfill, the credits job and the collection seed are done (or off) — the
  677. // collection seed's timelines are what the file's `collections` attach. Then on its own 0.1 s clock ONE step per tick: the next
  678. // missing title imported (the search's import, complete with cast + crew; its log line `search import: …`), then the pause the daily sync makes after the same
  679. // requests (≤ 40 TMDB / 10 s, ≤ 20 TVmaze / 10 s); the queue done, the build (no TMDB). RESUMES after a restart (the queue = the
  680. // titles still missing), IDEMPOTENT (nothing missing + nothing changed = no write). Without TMDB_READ_TOKEN it only builds from
  681. // what we have. Log: start, every import, every TRACKER_FRANCHISE_SEED_LOG_EVERY (25) imports, done.
  682. // TRACKER_FRANCHISE_SEED=0 switches it off; TRACKER_FRANCHISE_FILE another data file (the gate's).
  683. franchiseSeedOn = env('TRACKER_FRANCHISE_SEED') != '0'
  684. franchiseSeedLogEvery = env('TRACKER_FRANCHISE_SEED_LOG_EVERY') != null ? toNumber(env('TRACKER_FRANCHISE_SEED_LOG_EVERY')) : 25
  685. franchiseRun = { at = 0 steps = 0 nextAt = 0 done = false started = false slowest = 0 }
  686. franchiseSeedTick = () => {
  687. if (franchiseRun.done) { return null }
  688. if (!mergeRun.done || syncQueue.length > 0 || syncPlanning || (backfillOn && !backfillDone) || (repairOn && (!repairDone || !statusDone)) || (kindsOn && !kindDone) || (creditsOn && !creditsDone) || (collectionsOn && !collectionRun.done)) { return null }
  689. t = now()
  690. if (!franchiseRun.started) {
  691. franchiseRun.started = true
  692. franchiseRun.at = t
  693. n = franchiseSeedPrepare(syncEnabled)
  694. st = franchiseSeedStats()
  695. if (!st.file) {
  696. franchiseRun.done = true
  697. console.log('franchise seed: ' + st.error + ' — nothing seeded')
  698. return null
  699. }
  700. console.log('franchise seed: start, ' + st.franchises + ' franchises, ' + st.timelines + ' timelines, ' + st.titles + ' titles in the file — ' + st.have + ' we have, ' + n + ' to import, ' + st.missing + ' TMDB lacks (' + (now() - t) + ' ms)')
  701. return null
  702. }
  703. if (t < franchiseRun.nextAt) { return null }
  704. r = franchiseSeedStep()
  705. took = now() - t
  706. if (took > franchiseRun.slowest) { franchiseRun.slowest = took }
  707. if (r.error != '') { console.log('franchise seed: ' + r.error) }
  708. if (took > 1500) { console.log('franchise seed: slow step, ' + took + ' ms') }
  709. if (r.done) {
  710. franchiseRun.done = true
  711. console.log('franchise seed done: ' + franchiseSeedLine() + ' seconds=' + ((now() - franchiseRun.at) / 1000) + ' slowestStepMs=' + franchiseRun.slowest)
  712. return null
  713. }
  714. franchiseRun.steps = franchiseRun.steps + 1
  715. franchiseRun.nextAt = now() + pauseMsAfter(r)
  716. if (franchiseRun.steps % franchiseSeedLogEvery == 0) { console.log('franchise seed: ' + franchiseSeedLine() + ' seconds=' + ((now() - franchiseRun.at) / 1000)) }
  717. return null
  718. }
  719. if (!franchiseSeedOn) { console.log('franchise seed: off (TRACKER_FRANCHISE_SEED=0)') }
  720. else {
  721. if (!syncEnabled) { console.log('franchise seed: no TMDB_READ_TOKEN — builds from the titles we have, imports nothing') }
  722. franchiseClock = every(0.1)
  723. on franchiseClock.tick(x) {
  724. franchiseSeedTick()
  725. return null
  726. }
  727. }
  728. // ---- THE ART BACKFILL + THE PHOTO BACKFILL (mission 032: tracker#33's The Remaining, tracker#37's /people) --------------------
  729. // The LAST start jobs, after the franchise seed (and everything it waits for): first every public title without a poster file /
  730. // public movie without runtime (backfill.hl artTitle: the poster, else the backdrop, + runtime), then every person without a photo
  731. // source (people.hl photoStep, /people's order). ONE item per step on their own 0.1 s clock, then n × 260 ms (≤ 40 TMDB requests
  732. // / 10 s). Resume after a restart (`artAt`/`artCheck`, `photoCheck`); a passing failure goes to the back of the queue (at most 2
  733. // more tries per start). Persisted every 25 items and at the end; the photo job pauses above TRACKER_PHOTOS_MAX_MB (16000) RSS
  734. // like the credits job. Log: start, every TRACKER_ART_LOG_EVERY (100) / TRACKER_PHOTOS_LOG_EVERY (1000) items, done.
  735. // TRACKER_ART=0 / TRACKER_PHOTOS=0 switch them off; without TMDB_READ_TOKEN they are off.
  736. artOn = env('TRACKER_ART') != '0' && syncEnabled
  737. photosOn = env('TRACKER_PHOTOS') != '0' && syncEnabled
  738. artLogEvery = env('TRACKER_ART_LOG_EVERY') != null ? toNumber(env('TRACKER_ART_LOG_EVERY')) : 100
  739. photosLogEvery = env('TRACKER_PHOTOS_LOG_EVERY') != null ? toNumber(env('TRACKER_PHOTOS_LOG_EVERY')) : 1000
  740. photosMaxMb = env('TRACKER_PHOTOS_MAX_MB') != null ? toNumber(env('TRACKER_PHOTOS_MAX_MB')) : 16000
  741. artRun = { queue = null scan = null pos = 0 done = !artOn at = 0 nextAt = 0 tries = {} titles = 0 posters = 0 backdrops = 0 runtimes = 0 failed = 0 requests = 0 retries = 0 slowest = 0 }
  742. photoRun = { queue = null scan = null pos = 0 done = !photosOn at = 0 nextAt = 0 tries = {} people = 0 found = 0 none = 0 failed = 0 requests = 0 retries = 0 slowest = 0 }
  743. artLine = () => {
  744. b = artRun
  745. return b.titles + '/' + b.queue.length + ' titles, posters=' + b.posters + ' backdrops=' + b.backdrops + ' runtimes=' + b.runtimes + ' failed=' + b.failed
  746. + ' requests=' + b.requests + ' retries=' + b.retries + ' slowestStepMs=' + b.slowest + ' seconds=' + ((now() - b.at) / 1000)
  747. }
  748. photoLine = () => {
  749. b = photoRun
  750. return b.people + '/' + b.queue.length + ' people, photos=' + b.found + ' none=' + b.none + ' failed=' + b.failed + ' requests=' + b.requests + ' retries=' + b.retries
  751. + ' slowestStepMs=' + b.slowest + ' seconds=' + ((now() - b.at) / 1000)
  752. }
  753. // everything the two wait for: the other start jobs (one TMDB pacing at a time)
  754. lastJobsMayRun = () => {
  755. return mergeRun.done && syncQueue.length == 0 && !syncPlanning && (!backfillOn || backfillDone) && (!repairOn || (repairDone && statusDone)) && (!kindsOn || kindDone)
  756. && (!creditsOn || creditsDone) && (!collectionsOn || collectionRun.done) && (!franchiseSeedOn || franchiseRun.done)
  757. }
  758. artTick = () => {
  759. t = now()
  760. if (artRun.queue == null) {
  761. if (artRun.scan == null) { artRun.scan = artScan() artRun.at = t }
  762. if (!collectStep(artRun.scan, artPred)) { return null }
  763. artRun.queue = collected(artRun.scan)
  764. console.log('art backfill: start, ' + artRun.queue.length + ' public titles without a poster file or a movie runtime (' + (now() - artRun.at) + ' ms to find them, ' + artRun.scan.ms + ' ms of scanning in ' + artRun.scan.scan.slices + ' slices)')
  765. if (artRun.queue.length == 0) { artRun.done = true console.log('art backfill: nothing to do') }
  766. return null
  767. }
  768. if (t < artRun.nextAt) { return null }
  769. id = artRun.queue[artRun.pos]
  770. artRun.pos = artRun.pos + 1
  771. r = artTitle(id)
  772. took = now() - t
  773. if (took > artRun.slowest) { artRun.slowest = took }
  774. if (r.error != '') { console.log('art backfill: ' + r.error) }
  775. artRun.nextAt = now() + r.requests * msPerRequest
  776. artRun.requests = artRun.requests + r.requests
  777. if (r.retry && (artRun.tries[id] == null || artRun.tries[id] < 2)) {
  778. artRun.tries[id] = artRun.tries[id] == null ? 1 : artRun.tries[id] + 1
  779. q = artRun.queue
  780. q.push(id)
  781. artRun.queue = q
  782. artRun.retries = artRun.retries + 1
  783. } else if (r.requests > 0) {
  784. artRun.titles = artRun.titles + 1
  785. artRun.posters = artRun.posters + r.posters
  786. artRun.backdrops = artRun.backdrops + r.backdrops
  787. if (r.runtime != null) { artRun.runtimes = artRun.runtimes + 1 }
  788. if (r.error != '') { artRun.failed = artRun.failed + 1 }
  789. if (r.posters + r.backdrops > 0) { refreshCatalogShow(id) }
  790. }
  791. finished = artRun.pos >= artRun.queue.length
  792. if (finished || artRun.pos % 25 == 0) { persistSync() }
  793. if (!finished && artRun.titles > 0 && artRun.pos % artLogEvery == 0) { console.log('art backfill: ' + artLine()) }
  794. if (finished) {
  795. artRun.done = true
  796. console.log('art backfill done: ' + artLine())
  797. }
  798. return null
  799. }
  800. photoTick = () => {
  801. t = now()
  802. if (photoRun.queue == null) {
  803. if (photoRun.scan == null) { photoRun.scan = photoQueueStart() photoRun.at = t }
  804. if (!photoQueueStep(photoRun.scan)) { return null }
  805. photoRun.queue = photoRun.scan.out
  806. console.log('photo backfill: start, ' + photoRun.queue.length + ' people without a photo source (' + (now() - photoRun.at) + ' ms to find them, ' + photoRun.scan.ms + ' ms of scanning in ' + photoRun.scan.steps + ' ticks, ' + photoRun.scan.skipped + ' non-rows skipped)')
  807. if (photoRun.queue.length == 0) { photoRun.done = true console.log('photo backfill: nothing to do') }
  808. return null
  809. }
  810. if (t < photoRun.nextAt) { return null }
  811. mb = rssMb()
  812. if (mb > photosMaxMb) {
  813. photoRun.done = true
  814. persistPhotos()
  815. console.log('photo backfill: paused, RSS ' + mb + ' MB > TRACKER_PHOTOS_MAX_MB ' + photosMaxMb + ' — ' + (photoRun.queue.length - photoRun.pos) + ' people left for the next start; ' + photoLine())
  816. return null
  817. }
  818. id = photoRun.queue[photoRun.pos]
  819. photoRun.pos = photoRun.pos + 1
  820. r = photoStep(id)
  821. took = now() - t
  822. if (took > photoRun.slowest) { photoRun.slowest = took }
  823. if (r.error != '') { console.log('photo backfill: ' + r.error) }
  824. photoRun.nextAt = now() + r.requests * msPerRequest
  825. photoRun.requests = photoRun.requests + r.requests
  826. if (r.retry && (photoRun.tries[id] == null || photoRun.tries[id] < 2)) {
  827. photoRun.tries[id] = photoRun.tries[id] == null ? 1 : photoRun.tries[id] + 1
  828. q = photoRun.queue
  829. q.push(id)
  830. photoRun.queue = q
  831. photoRun.retries = photoRun.retries + 1
  832. } else if (r.requests > 0) {
  833. photoRun.people = photoRun.people + 1
  834. if (r.found) { photoRun.found = photoRun.found + 1 } else if (r.error != '') { photoRun.failed = photoRun.failed + 1 } else { photoRun.none = photoRun.none + 1 }
  835. }
  836. finished = photoRun.pos >= photoRun.queue.length
  837. if (finished || photoRun.pos % 25 == 0) { persistPhotos() }
  838. if (!finished && photoRun.people > 0 && photoRun.pos % photosLogEvery == 0) { console.log('photo backfill: ' + photoLine()) }
  839. if (finished) {
  840. photoRun.done = true
  841. console.log('photo backfill done: ' + photoLine())
  842. }
  843. return null
  844. }
  845. if (!artOn) { console.log('art backfill: off (' + (syncEnabled ? 'TRACKER_ART=0' : 'no TMDB_READ_TOKEN') + ')') }
  846. if (!photosOn) { console.log('photo backfill: off (' + (syncEnabled ? 'TRACKER_PHOTOS=0' : 'no TMDB_READ_TOKEN') + ')') }
  847. if (artOn || photosOn) {
  848. lastClock = every(0.1)
  849. on lastClock.tick(x) {
  850. if (!lastJobsMayRun()) { return null }
  851. if (!artRun.done) { artTick() } else if (!photoRun.done) { photoTick() }
  852. return null
  853. }
  854. }

Branches

Latest commits

  • efe1b485mission 046: re-vendor Hybriel master 60b2817b (integration 8, #203): plugins mpackdb + web (bin/ git-ignored: hybriel, libhlrt.a, hlc.o, hlrt/ from native/zig-out)mre
  • 53099ffbmission 046: person page reads a slim per-title credit row cache (no whole-record fetch per credit); gate tests/person-lookup.mjsmre
  • 9b3828aemission 046a: report, LOGmre
  • 4b37356emission 046: franchise seed supersedeCollections reads the curated timelines once (10 s one-tick block at the end of boot)mre
  • ac6268e3mission 046a: re-vendor Hybriel 528bc89f (integration 6): plugins mpackdb/time/web (bin/ git-ignored)mre
  • 322b3293mission 046: photoQueue guard for non-row fetch results (damaged persons index)mre
  • e5b99aecmission 046: photoQueue in slices (people.hl photoQueueStart/Step, jobs.hl photoTick), tests/photoqueue.hlmre
  • 31dcf2admission 045: report, LOGmre
  • 9c3971d0tests/persons-skip-count.hlmre
  • 4d72e365mission 045mre
  • b9cae4c9slices: skip and count non-row values from range(); merge persons pass falls back to iterate; guard testmre
  • 3db7dc31merge w44-jobs-slices into w43-trkmemmre
  • 593dab6fmission 043: report, LOGmre
  • 1a5a4818boot scans back to iterate (slices measured slower: titles 114 s, episodes 141 s, persons failed); lambda per rowmre
  • 03d29893boot scans read primary-key slices (lib/slices.hl from mission 044): iterate is eager too; people view log line back; allShows/allEpisodes stay for toolsmre
  • 23375c58mission 044: report, LOG, STATUSmre
  • c6fd928emission 044: 4096 slices for tables over 200 K rows, 15 ms budget, TRACKER_SLICE_DEPTH for testsmre
  • fb057680mission 044: jobs.hl imports mergeLeft (gate found it), mission file, slices benchmre
  • 0d6293ebmission 043: mission filemre
  • d25bd14amission 044: sliced merge prepare + sliced collections prepare; jobs-dump old/new check + bulk fixturemre