gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitaed12917aed12917Reference owned Style rules in genres and searchmreaed12917/lib/jobs.hl

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

Branches

Latest commits

  • aed12917Reference owned Style rules in genres and searchmre
  • 78ee6b56Move remaining component styles into Style blocksmre
  • 7f04de33log: HM49Bmre
  • 00616cf3log: #49 batch merged, DP67 startedmre
  • d7232e86Merge hm49-styles: tracker#49 first batch of component stylesmre
  • 079f376dMove seven components' styles into Style blocksmre
  • 17d66feelog: #58 mergedmre
  • 69a6640bMerge hm58-map: tracker#58 project.hl only the mapmre
  • a85f7900Move route logic out of the project mapmre
  • 13dea5belog: #56 live, HM49 and HM58 startedmre
  • a31c8f2fdocs: tracker#36 remaining listmre
  • 975d06d1log: #36 live, DP66 startedmre
  • d6d03fa3mission: T36Bmre
  • e7512d00status: #36 rolled back, retry askedmre
  • c98e2043log: T36A rollbackmre
  • ae905f15Merge t36a: tracker#36 apply rechecks, reportmre
  • 796bfaceT36A: report validated fixes, failed live SSH check and verified rollbackmre
  • 55257852log: #53 live, #56 mergedmre
  • 78b39f1bMerge hm56-rows: tracker#56 list builders insert oncemre
  • 7aea52batmdb fix: protect owners without slugs and record passing gatesmre