tracker
All repositories: gitoria
36.4 KB
// lib/jobs.hl — THE BACKGROUND JOBS (mission 028: out of project.hl, unchanged): the daily TMDB sync run, the adult and kind// backfills, the details repair, the credits job, the duplicate merge, the short-id backfill and the collection seed — each with// its queue, its pause, its log lines, and the clocks that drive them (which job runs when, which one waits for which). The work// of ONE step is the topic's own (sync.hl, backfill.hl, details.hl, credits.hl, merge.hl, shortids.hl, collections.hl).// A CLASS, not statics: its state (queues, positions, totals) is rewritten on every step, and a static cannot be reassigned —// project.hl makes the one instance (`jobs = new Jobs()`) after the server, as these lines ran there before; constructing it// starts the clocks and logs which jobs are off.import { env } from 'hl:proc'import { readFile, exists } from 'hl:fs'import { now, timestamp, every } from 'hl:time'import { syncEnabled, pauseMsAfter, msPerRequest } from './tmdb.hl'import { persistSync } from './sync.hl'import { emptyTotals, addTotals, totalsLine } from './sync-helpers.hl'import { planStart, planStep, planIds, planLine, markSynced, syncRunStep } from './dailysync.hl'import { adultBackfillQueue, backfillTitle, kindBackfillQueue, kindTitle, tvmazeStatusQueue, tvmazeStatusTitle } from './backfill.hl'import { detailsRepairQueue, completeStep, persistDetails, applySynced } from './details.hl'import { persistCredits, creditsQueue, creditsStep } from './credits.hl'import { allFollowedShowIds } from './follows.hl'import { refreshCatalogShow } from './catalog.hl'import { searchTitleChanged, searchTitleRenamed } from './search.hl'import { mergePrepare, mergeStep, mergeStats, mergeLine, persistMerge } from './merge.hl'import { shortIdStep, shortIdStats, persistShortIds, shortIdsLeft } from './shortids.hl'import { seedPrepare, seedStep, seedLine, seedPersist } from './collections.hl'// ---- THE DAILY TMDB SYNC (tracker.worldapi.org#9, sync.hl; tracker#18, dailysync.hl) -------------------------// Once a day at TRACKER_SYNC_HOUR (UTC, default 4 — hl:time has no time zones; the container runs UTC). hl:web serves ONE// 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// requests that queued meanwhile are served between two ticks, and a tick never starts inside a page render.// tracker#18: the run first asks TMDB's and TVmaze's CHANGE LISTS since the last run (dailysync.hl — one list page per step)// and then syncs only the titles of ours that changed, followed ones first — every title stays current, not only the followed// ones. FULL WALK (every followed show, as before #18) on the first run, after a gap > 14 days, or when a change list fails.// A title's step: sync.hl syncShow (1–3 TMDB requests + maybe its poster, TVmaze) + details.hl applySynced (the record's// title, overview, tagline … and cast/crew from the same details answer). After a step that made n requests the next waits// n × 260 ms (TMDB: ≤ 40 requests / 10 s) + 550 ms per TVmaze request (≤ 20 / 10 s, tracker.worldapi.org#12).// The finished run stores its day (dailysync.hl markSynced). Log: "tmdb sync: start, …", the change lists ("tmdb sync:// changes since …"), errors, slow steps, "tmdb sync done: mode=… changeRequests=… <totals>".// TRACKER_SYNC=0 switches it off; without TMDB_READ_TOKEN it is off too (logged once).syncHour = env('TRACKER_SYNC_HOUR') != null ? toNumber(env('TRACKER_SYNC_HOUR')) : 4syncOn = env('TRACKER_SYNC') != '0' && syncEnabledsyncQueue = []syncPlanning = falsesyncMode = ''syncMark = falsesyncChangeRequests = 0syncAt = 0syncDay = ''syncNextAt = 0syncTotals = emptyTotals()syncFinish = () => {persistDetails()if (syncMark) { markSynced(syncDay) }console.log('tmdb sync done: mode=' + syncMode + ' changeRequests=' + syncChangeRequests + ' ' + totalsLine(syncTotals) + ' seconds=' + ((now() - syncAt) / 1000))return null}syncTick = () => {t = now()if (syncQueue.length == 0 && !syncPlanning) {stamp = timestamp(t)day = stamp.slice(0, 10)if (toNumber(stamp.slice(11, 13)) != syncHour || day == syncDay) { return null }syncDay = daysyncAt = tsyncNextAt = 0syncTotals = emptyTotals()syncChangeRequests = 0p = planStart(day, null)syncMode = p.modesyncMark = trueif (p.mode == 'delta') {syncPlanning = trueconsole.log('tmdb sync: start, changes ' + p.why)return null}syncQueue = allFollowedShowIds()console.log('tmdb sync: start, ' + syncQueue.length + ' followed shows, full walk (' + p.why + ')')if (syncQueue.length == 0) { syncFinish() }return null}if (t < syncNextAt) { return null }if (syncPlanning) {ps = planStep()syncChangeRequests = syncChangeRequests + ps.requests + ps.tvmazeRequestssyncTotals.requests = syncTotals.requests + ps.requestssyncTotals.tvmazeRequests = syncTotals.tvmazeRequests + ps.tvmazeRequestssyncNextAt = now() + pauseMsAfter(ps)if (!ps.done) { return null }syncPlanning = falseconsole.log('tmdb sync: ' + planLine())if (ps.failed != '') {// a change list could not be read: the old full walk, and the day is not advanced (the next run asks again)syncMode = 'full'syncMark = falsesyncQueue = allFollowedShowIds()console.log('tmdb sync: change list failed, full walk of ' + syncQueue.length + ' followed shows instead')} else {syncQueue = planIds()}if (syncQueue.length == 0) { syncFinish() }return null}id = syncQueue[0]rest = []let i = 1while (i < syncQueue.length) { rest.push(syncQueue[i]) i = i + 1 }syncQueue = rest// tracker#18: in a delta run a title nobody follows gets the light step (changed seasons, no TVmaze); tracker#35: one only on// TVmaze's change list its TVmaze status (dailysync.hl syncRunStep)r = syncRunStep(id, syncMode == 'delta')// tracker#18 + #28: the record's own fields (title, overview, tagline …) and the cast + crew from the same details answerif (r.details != null) {c = applySynced(id, r.details)if (c.error != '') { console.log('tmdb sync: ' + c.error) }if (c.renamed) { searchTitleRenamed(id) }}// the public lists (catalog.hl, tracker.worldapi.org#13): this show's place by its newest released episode; the sync// also brings TMDB's adult flag (mission 054) → the search's view of it toorefreshCatalogShow(id)searchTitleChanged(id)took = now() - tsyncTotals = addTotals(syncTotals, r)if (r.error != '') { console.log('tmdb sync: ' + r.error) }// a step blocks every request meanwhile (Saturday Night Live, 53 seasons, 4 requests: ~1.7 s) — say so in the logif (took > 1500) { console.log('tmdb sync: slow step, show ' + id + ', ' + r.requests + ' requests, ' + took + ' ms') }syncNextAt = now() + pauseMsAfter(r)if (syncQueue.length > 0 && syncTotals.shows % 10 == 0) { persistDetails() }if (syncQueue.length == 0) { syncFinish() }return null}// ---- THE ADULT-FLAG BACKFILL (mission 054, backfill.hl backfillTitle) -----------------------------------// The public lists and the search show only titles TMDB says are not adult (shows.hl isPublicTitle; unknown = hidden). At// start the app collects every title whose flag is still unknown and asks TMDB for ONE title per step — like the daily// sync, on the same clock, so requests queued meanwhile are served between two steps: one details request (adult,// poster_path, external ids) + the poster file when missing, then a pause of 260 ms per TMDB API request (≤ 40 / 10 s;// the poster comes from TMDB's image host, not the API, and is not counted). Each answered title goes into the lists// (catalog.hl refreshCatalogShow) and the search at once. RESUMES after a restart: the queue is built from what is// still unknown. Stops when the queue is empty; titles TMDB answers 404 for are marked (`adultCheck`) and stay hidden; a// passing failure (no answer, 429, 5xx) goes to the back of the queue, at most 2 more tries per start.// While the daily sync runs, the backfill waits. Log: start, every TRACKER_BACKFILL_LOG_EVERY (500) titles, done.// TRACKER_BACKFILL=0 switches it off; without TMDB_READ_TOKEN it is off too.backfillOn = env('TRACKER_BACKFILL') != '0' && syncEnabledbackfillLogEvery = env('TRACKER_BACKFILL_LOG_EVERY') != null ? toNumber(env('TRACKER_BACKFILL_LOG_EVERY')) : 500backfillQueue = nullbackfillPos = 0backfillDone = falsebackfillAt = 0backfillNextAt = 0backfillTries = {}backfillTotals = { titles = 0 adult = 0 notAdult = 0 unknown = 0 posters = 0 ids = 0 requests = 0 errors = 0 retries = 0 }backfillLine = () => {b = backfillTotalsreturn b.titles + '/' + backfillQueue.length + ' titles, adult=' + b.adult + ' notAdult=' + b.notAdult + ' unknown=' + b.unknown + ' posters=' + b.posters+ ' ids=' + b.ids + ' requests=' + b.requests + ' errors=' + b.errors + ' retries=' + b.retries + ' seconds=' + ((now() - backfillAt) / 1000)}backfillTick = () => {if (backfillDone) { return null }t = now()if (backfillQueue == null) {backfillQueue = adultBackfillQueue()backfillAt = tconsole.log('adult backfill: start, ' + backfillQueue.length + ' titles without an adult flag (' + (now() - t) + ' ms to find them)')if (backfillQueue.length == 0) { backfillDone = true console.log('adult backfill: nothing to do') }return null}if (t < backfillNextAt) { return null }id = backfillQueue[backfillPos]backfillPos = backfillPos + 1r = backfillTitle(id)if (r.retry && (backfillTries[id] == null || backfillTries[id] < 2)) {backfillTries[id] = backfillTries[id] == null ? 1 : backfillTries[id] + 1q = backfillQueueq.push(id)backfillQueue = qbackfillTotals.retries = backfillTotals.retries + 1} else {backfillTotals.titles = backfillTotals.titles + 1if (r.adult == true) { backfillTotals.adult = backfillTotals.adult + 1 } else if (r.adult == false) { backfillTotals.notAdult = backfillTotals.notAdult + 1 } else { backfillTotals.unknown = backfillTotals.unknown + 1 }}backfillTotals.posters = backfillTotals.posters + r.postersbackfillTotals.ids = backfillTotals.ids + r.idsbackfillTotals.requests = backfillTotals.requests + r.requestsbackfillTotals.errors = backfillTotals.errors + r.errorsif (r.error != '') { console.log('adult backfill: ' + r.error) }if (r.adult != null) {refreshCatalogShow(id)searchTitleChanged(id)}took = now() - tif (took > 1500) { console.log('adult backfill: slow step, show ' + id + ', ' + took + ' ms') }backfillNextAt = now() + r.requests * msPerRequestfinished = backfillPos >= backfillQueue.lengthif (finished || backfillPos % 25 == 0) { persistSync() }if (!finished && backfillTotals.titles > 0 && backfillTotals.titles % backfillLogEvery == 0 && !r.retry) { console.log('adult backfill: ' + backfillLine()) }if (finished) {backfillDone = trueconsole.log('adult backfill done: ' + backfillLine())}return null}// ---- THE DETAILS REPAIR (tracker.worldapi.org#26, details.hl completeStep) ----------------------------------------// Titles the person pages added from a filmography (#16) are MINIMAL (no poster, seasons, ids, cast …), and (tracker#33, mission// 029) the old tracker's migrated rows were never synced (5,697 on the live copy, 691 series without seasons) — shows.hl// isIncomplete. Opening one completes it (components/show.hl); this job completes the rest in the background: at start it// collects every incomplete, non-adult title (the visibly reduced ones first, details.hl detailsRepairQueue) and does ONE per// step on the app's clock, like the adult backfill — a step is the daily sync's work for one title// (1–3 TMDB requests + poster + TVmaze), requests queued meanwhile are served between two steps; then a pause of 260 ms per// TMDB request + 550 ms per TVmaze request (pauseMsAfter: ≤ 40 / 10 s, ≤ 20 / 10 s). RESUMES after a restart (the queue is// what is still incomplete); TMDB 404 marks the title (`detailsCheck`), a passing failure goes to the back of the queue (at// most 2 more tries per start). Waits while the daily sync or the adult backfill runs. Persisted every 10 titles + at the end.// Log: start, every TRACKER_REPAIR_LOG_EVERY (100) titles, each failure, done. TRACKER_REPAIR=0 switches it off (off too// without TMDB_READ_TOKEN). TRACKER_REPAIR_FAST=1 (the gate, fake TMDB only): 20 ms pause instead.repairOn = env('TRACKER_REPAIR') != '0' && syncEnabledrepairFast = env('TRACKER_REPAIR_FAST') == '1'repairLogEvery = env('TRACKER_REPAIR_LOG_EVERY') != null ? toNumber(env('TRACKER_REPAIR_LOG_EVERY')) : 100repairQueue = nullrepairPos = 0repairDone = falserepairAt = 0repairNextAt = 0repairTries = {}repairTotals = { titles = 0 complete = 0 failed = 0 adult = 0 newSeasons = 0 newEpisodes = 0 posters = 0 cast = 0 requests = 0 tvmazeRequests = 0 retries = 0 }repairLine = () => {b = repairTotalsreturn b.titles + '/' + repairQueue.length + ' titles, complete=' + b.complete + ' failed=' + b.failed + ' adult=' + b.adult + ' newSeasons=' + b.newSeasons + ' newEpisodes=' + b.newEpisodes+ ' posters=' + b.posters + ' cast=' + b.cast + ' requests=' + b.requests + ' tvmazeRequests=' + b.tvmazeRequests + ' retries=' + b.retries + ' seconds=' + ((now() - repairAt) / 1000)}repairTick = () => {if (repairDone) { return null }t = now()if (repairQueue == null) {repairQueue = detailsRepairQueue()repairAt = tconsole.log('details repair: start, ' + repairQueue.length + ' incomplete titles (' + (now() - t) + ' ms to find them)')if (repairQueue.length == 0) { repairDone = true console.log('details repair: nothing to do') }return null}if (t < repairNextAt) { return null }id = repairQueue[repairPos]r = completeStep(id)took = now() - tif (took > 1500) { console.log('details repair: slow step, show ' + id + ', ' + took + ' ms') }if (r.error != '') { console.log('details repair: ' + r.error) }repairNextAt = now() + (repairFast ? 20 : pauseMsAfter(r))// a series takes several steps: the same title again next timeif (!r.done && !r.retry) { return null }repairPos = repairPos + 1if (r.retry && (repairTries[id] == null || repairTries[id] < 2)) {repairTries[id] = repairTries[id] == null ? 1 : repairTries[id] + 1q = repairQueueq.push(id)repairQueue = qrepairTotals.retries = repairTotals.retries + 1} else if (!r.skipped) {// done: its counts (a failed first step: the request alone)sum = r.sumrepairTotals.titles = repairTotals.titles + 1if (r.adult == true) { repairTotals.adult = repairTotals.adult + 1 } else if (sum.steps == 0) { repairTotals.failed = repairTotals.failed + 1 } else { repairTotals.complete = repairTotals.complete + 1 }repairTotals.newSeasons = repairTotals.newSeasons + sum.newSeasonsrepairTotals.newEpisodes = repairTotals.newEpisodes + sum.newEpisodesrepairTotals.posters = repairTotals.posters + sum.postersrepairTotals.cast = repairTotals.cast + sum.castrepairTotals.requests = repairTotals.requests + (sum.steps == 0 ? r.requests : sum.requests)repairTotals.tvmazeRequests = repairTotals.tvmazeRequests + sum.tvmazeRequests}finished = repairPos >= repairQueue.lengthif (finished || repairPos % 10 == 0) { persistDetails() }if (!finished && !r.skipped && !r.retry && repairTotals.titles > 0 && repairTotals.titles % repairLogEvery == 0) { console.log('details repair: ' + repairLine()) }if (finished) {repairDone = trueconsole.log('details repair done: ' + repairLine())}return null}// ---- THE TVMAZE STATUS BACKFILL (tracker#35, mission 030, backfill.hl tvmazeStatusTitle) — the details repair's second part ----// 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// TVmaze's episodes (followed series, every completion); the series it never reached get it here: once the details repair is// done (same switch, TRACKER_REPAIR) every series with a TVmaze id and no tvmazeStatus, ONE TVmaze request per step, then 550 ms// (TVmaze: ≤ 20 / 10 s). RESUMES after a restart (the queue = what still has none); a 404 marks the series// (`tvmazeStatusCheck`), a passing failure goes to the back of the queue (at most 2 more tries per start). Waits while the daily// sync runs. Persisted every 25 series + at the end. Log: start, every TRACKER_REPAIR_LOG_EVERY series, done.statusQueue = nullstatusPos = 0statusDone = falsestatusAt = 0statusNextAt = 0statusTries = {}statusTotals = { series = 0 stored = 0 notFound = 0 requests = 0 errors = 0 retries = 0 }statusLine = () => {b = statusTotalsreturn b.series + '/' + statusQueue.length + ' series, stored=' + b.stored + ' notFound=' + b.notFound + ' tvmazeRequests=' + b.requests + ' errors=' + b.errors + ' retries=' + b.retries + ' seconds=' + ((now() - statusAt) / 1000)}statusTick = () => {if (statusDone) { return null }t = now()if (statusQueue == null) {statusQueue = tvmazeStatusQueue()statusAt = tconsole.log('tvmaze status: start, ' + statusQueue.length + ' series without a TVmaze status (' + (now() - t) + ' ms to find them)')if (statusQueue.length == 0) { statusDone = true console.log('tvmaze status: nothing to do') }return null}if (t < statusNextAt) { return null }id = statusQueue[statusPos]statusPos = statusPos + 1r = tvmazeStatusTitle(id)if (r.retry && (statusTries[id] == null || statusTries[id] < 2)) {statusTries[id] = statusTries[id] == null ? 1 : statusTries[id] + 1q = statusQueueq.push(id)statusQueue = qstatusTotals.retries = statusTotals.retries + 1} else {statusTotals.series = statusTotals.series + 1if (r.status != null) { statusTotals.stored = statusTotals.stored + 1 } else if (r.errors > 0) { statusTotals.notFound = statusTotals.notFound + 1 }}statusTotals.requests = statusTotals.requests + r.tvmazeRequestsstatusTotals.errors = statusTotals.errors + r.errorsif (r.error != '') { console.log('tvmaze status: ' + r.error) }statusNextAt = now() + (repairFast ? 20 : pauseMsAfter(r))finished = statusPos >= statusQueue.lengthif (finished || statusPos % 25 == 0) { persistSync() }if (!finished && !r.retry && statusTotals.series > 0 && statusTotals.series % repairLogEvery == 0) { console.log('tvmaze status: ' + statusLine()) }if (finished) {statusDone = trueconsole.log('tvmaze status done: ' + statusLine())}return null}// ---- THE KIND BACKFILL (tracker.worldapi.org#21, mission 068, backfill.hl kindTitle) ----------------------------------// Every TV title without a stored kind gets one: a title with a show genre (Reality / Talk / News) from the stored data (no// request), any other from TMDB's TV type (ONE request: GET /tv/<id>, then 260 ms pause). Starts once the adult backfill is// 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// /series to /shows at once (catalog.hl refreshCatalogShow). RESUMES after a restart (the queue = every TV title still without// a kind); a 404 stores the genres' answer + `kindCheck`; a passing failure goes to the back of the queue, at most 2 more tries// per start. Log: start, every TRACKER_KINDS_LOG_EVERY (500) titles, done. TRACKER_KINDS=0 switches it off; without// TMDB_READ_TOKEN it is off too (the lists still split by genre: shows.hl titleKind).kindsOn = env('TRACKER_KINDS') != '0' && syncEnabledkindsLogEvery = env('TRACKER_KINDS_LOG_EVERY') != null ? toNumber(env('TRACKER_KINDS_LOG_EVERY')) : 500kindQueue = nullkindPos = 0kindDone = falsekindAt = 0kindNextAt = 0kindTries = {}kindTotals = { titles = 0 series = 0 shows = 0 fromGenre = 0 moved = 0 requests = 0 errors = 0 retries = 0 }kindLine = () => {k = kindTotalsreturn k.titles + '/' + kindQueue.length + ' titles, series=' + k.series + ' shows=' + k.shows + ' fromGenre=' + k.fromGenre + ' moved=' + k.moved+ ' requests=' + k.requests + ' errors=' + k.errors + ' retries=' + k.retries + ' seconds=' + ((now() - kindAt) / 1000)}kindTick = () => {if (kindDone) { return null }t = now()if (kindQueue == null) {kindQueue = kindBackfillQueue()kindAt = tconsole.log('kind backfill: start, ' + kindQueue.length + ' TV titles without a kind (' + (now() - t) + ' ms to find them)')if (kindQueue.length == 0) { kindDone = true console.log('kind backfill: nothing to do') }return null}if (t < kindNextAt) { return null }id = kindQueue[kindPos]kindPos = kindPos + 1r = kindTitle(id)if (r.retry && (kindTries[id] == null || kindTries[id] < 2)) {kindTries[id] = kindTries[id] == null ? 1 : kindTries[id] + 1q = kindQueueq.push(id)kindQueue = qkindTotals.retries = kindTotals.retries + 1} else {kindTotals.titles = kindTotals.titles + 1if (r.kind == 'show') { kindTotals.shows = kindTotals.shows + 1 } else if (r.kind == 'series') { kindTotals.series = kindTotals.series + 1 }if (r.fromGenre) { kindTotals.fromGenre = kindTotals.fromGenre + 1 }}kindTotals.requests = kindTotals.requests + r.requestskindTotals.errors = kindTotals.errors + r.errorsif (r.error != '') { console.log('kind backfill: ' + r.error) }// until now the genres decided (no show genre = series): only a title TMDB's type makes a SHOW changes its listif (r.kind == 'show' && !r.fromGenre) {refreshCatalogShow(id)kindTotals.moved = kindTotals.moved + 1}took = now() - tif (took > 1500) { console.log('kind backfill: slow step, show ' + id + ', ' + took + ' ms') }kindNextAt = now() + r.requests * msPerRequestfinished = kindPos >= kindQueue.lengthif (finished || kindPos % 25 == 0) { persistSync() }if (!finished && kindTotals.titles > 0 && kindTotals.titles % kindsLogEvery == 0 && !r.retry) { console.log('kind backfill: ' + kindLine()) }if (finished) {kindDone = trueconsole.log('kind backfill done: ' + kindLine())}return null}// ---- THE CREDITS JOB (tracker.worldapi.org#28, credits.hl creditsStep) ------------------------------------------------------// Every PUBLIC title (adult == false; adult/unknown are skipped) with a TMDB id gets its whole cast + crew once: at start (after// the adult backfill and the details repair are done) the job collects every such title without `creditsAt` and asks ONE per// step on the app's clock — one request (details + credits / aggregate_credits), then 260 ms (≤ 40 / 10 s); requests queued// meanwhile are served between two steps. Titles the details repair, the daily sync or an import already did carry `creditsAt`// and are not asked. RESUMES after a restart (the queue = what still has no credits); TMDB 404 / adult → `creditsCheck`, never// asked again; a passing failure goes to the back of the queue (at most 2 more tries per start). Waits while the daily sync// runs. Persisted (shows + people only) every 25 titles + at the end. Log: start, every TRACKER_CREDITS_LOG_EVERY (500) titles, failures, slow steps// (> 1.5 s), done. TRACKER_CREDITS=0 switches it off (off too without TMDB_READ_TOKEN). TRACKER_CREDITS_FAST=1 (the gate, fake// TMDB only): 20 ms pause instead.// MEMORY LIMIT: the runtime never frees what a fetch + JSON parse took (mission 061 measured ~6 MB more RSS per title on the real// 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// step the job reads its own RSS (/proc/self/status); above TRACKER_CREDITS_MAX_MB (16000) it PAUSES for this process (logged) and// goes on with what is left after the next restart (deploy, `docker restart`).creditsOn = env('TRACKER_CREDITS') != '0' && syncEnabledcreditsFast = env('TRACKER_CREDITS_FAST') == '1'creditsLogEvery = env('TRACKER_CREDITS_LOG_EVERY') != null ? toNumber(env('TRACKER_CREDITS_LOG_EVERY')) : 500creditsQueueIds = nullcreditsPos = 0creditsDone = falsecreditsAt = 0creditsNextAt = 0creditsTries = {}creditsMaxMb = env('TRACKER_CREDITS_MAX_MB') != null ? toNumber(env('TRACKER_CREDITS_MAX_MB')) : 16000creditsTotals = { titles = 0 done = 0 failed = 0 cast = 0 crew = 0 people = 0 requests = 0 retries = 0 slowest = 0 }// this process' resident memory in MB (VmRSS), 0 when unknownrssMb = () => {if (!exists('/proc/self/status')) { return 0 }t = readFile('/proc/self/status')i = t != null ? t.indexOf('VmRSS:') : -1if (i < 0) { return 0 }kb = toNumber(t.slice(i + 6, t.indexOf('kB', i)).trim())return kb != null ? (kb - kb % 1024) / 1024 : 0}creditsLine = () => {b = creditsTotalsreturn b.titles + '/' + creditsQueueIds.length + ' titles, done=' + b.done + ' failed=' + b.failed + ' cast=' + b.cast + ' crew=' + b.crew + ' people=' + b.people+ ' requests=' + b.requests + ' retries=' + b.retries + ' slowestStepMs=' + b.slowest + ' seconds=' + ((now() - creditsAt) / 1000)}creditsTick = () => {if (creditsDone) { return null }t = now()if (creditsQueueIds == null) {creditsQueueIds = creditsQueue()creditsAt = tconsole.log('credits job: start, ' + creditsQueueIds.length + ' titles without credits (' + (now() - t) + ' ms to find them)')if (creditsQueueIds.length == 0) { creditsDone = true console.log('credits job: nothing to do') }return null}if (t < creditsNextAt) { return null }mb = rssMb()if (mb > creditsMaxMb) {creditsDone = truepersistCredits()console.log('credits job: paused, RSS ' + mb + ' MB > TRACKER_CREDITS_MAX_MB ' + creditsMaxMb + ' — ' + (creditsQueueIds.length - creditsPos) + ' titles left for the next start; ' + creditsLine())return null}id = creditsQueueIds[creditsPos]creditsPos = creditsPos + 1r = creditsStep(id)took = now() - tif (took > creditsTotals.slowest) { creditsTotals.slowest = took }if (took > 1500) { console.log('credits job: slow step, show ' + id + ', ' + took + ' ms, cast=' + r.cast + ' crew=' + r.crew + ' people=' + r.people) }if (r.error != '') { console.log('credits job: ' + r.error) }creditsNextAt = now() + (creditsFast ? 20 : r.requests * msPerRequest)if (r.retry && (creditsTries[id] == null || creditsTries[id] < 2)) {creditsTries[id] = creditsTries[id] == null ? 1 : creditsTries[id] + 1q = creditsQueueIdsq.push(id)creditsQueueIds = qcreditsTotals.retries = creditsTotals.retries + 1} else if (!r.skipped) {creditsTotals.titles = creditsTotals.titles + 1if (r.error != '') { creditsTotals.failed = creditsTotals.failed + 1 } else { creditsTotals.done = creditsTotals.done + 1 }creditsTotals.cast = creditsTotals.cast + r.castcreditsTotals.crew = creditsTotals.crew + r.crewcreditsTotals.people = creditsTotals.people + r.people}creditsTotals.requests = creditsTotals.requests + r.requestsfinished = creditsPos >= creditsQueueIds.lengthif (finished || creditsPos % 25 == 0) { persistCredits() }if (!finished && !r.skipped && !r.retry && creditsTotals.titles > 0 && creditsTotals.titles % creditsLogEvery == 0) { console.log('credits job: ' + creditsLine()) }if (finished) {creditsDone = trueconsole.log('credits job done: ' + creditsLine())}return null}// ---- THE DUPLICATE MERGE (tracker.worldapi.org#31, mission 026, merge.hl) ----------------------------------------------------// The old tracker's duplicate titles (same type + TMDB id) become ONE record each — follows, watches, seasons, cast, credits and// timelines moved to the keeper, the others kept as tombstones whose slug and short id lead to it — and seasons that name a title// without being in its list are merged into their twin or linked, and (tracker#39) a season's double episodes into one (merge.hl// has the rules). On its own clock (every 0.1 s) ONE// item per tick (a duplicate group, or one title's stray seasons; no TMDB), so pages are served between two items. The TMDB jobs// below (daily sync, backfills, repair, credits, collections) wait until it is done: none of them works on a record that is about// to become a tombstone. RESUMES after a restart (the queue = what is still duplicated / stray). Persisted every 10 items and at// the end. Log: start, one line per tombstone / repaired title, done; with nothing to do one line. TRACKER_MERGE=0 switches it off.mergeOn = env('TRACKER_MERGE') != '0'mergeRun = { started = false done = !mergeOn at = 0 items = 0 slowest = 0 }mergeTick = () => {if (mergeRun.done) { return null }t = now()if (!mergeRun.started) {mergeRun.started = truemergeRun.at = tn = mergePrepare()st = mergeStats()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)')if (n == 0) {mergeRun.done = trueconsole.log('merge: nothing to do')}return null}r = mergeStep()mergeRun.items = mergeRun.items + 1took = now() - tif (took > mergeRun.slowest) { mergeRun.slowest = took }if (took > 1500) { console.log('merge: slow step, ' + took + ' ms') }if (r.done || mergeRun.items % 10 == 0) { persistMerge() }if (r.done) {mergeRun.done = trueconsole.log('merge done: ' + mergeLine() + ' items=' + mergeRun.items + ' slowestStepMs=' + mergeRun.slowest + ' seconds=' + ((now() - mergeRun.at) / 1000))}return null}if (!mergeOn) { console.log('merge: off (TRACKER_MERGE=0)') }else {mergeClock = every(0.1)on mergeClock.tick(x) {mergeTick()return null}}// 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// between, only while no daily run is going on; the details repair only when neither has work (then its TVmaze status part,// tracker#35); then the kind backfill (#21);// the credits job (#28) lastclockOn = syncOn || backfillOn || repairOn || kindsOn || creditsOnclockTicks = 0if (syncOn) { console.log('tmdb sync: daily at ' + syncHour + ':00 UTC') } else { console.log('tmdb sync: off (' + (syncEnabled ? 'TRACKER_SYNC=0' : 'no TMDB_READ_TOKEN') + ')') }if (!backfillOn) { console.log('adult backfill: off (' + (syncEnabled ? 'TRACKER_BACKFILL=0' : 'no TMDB_READ_TOKEN') + ')') }if (!repairOn) { console.log('details repair: off (' + (syncEnabled ? 'TRACKER_REPAIR=0' : 'no TMDB_READ_TOKEN') + ')') }if (!creditsOn) { console.log('credits job: off (' + (syncEnabled ? 'TRACKER_CREDITS=0' : 'no TMDB_READ_TOKEN') + ')') }if (!kindsOn) { console.log('kind backfill: off (' + (syncEnabled ? 'TRACKER_KINDS=0' : 'no TMDB_READ_TOKEN') + ')') }if (clockOn) {syncClock = every(0.1)on syncClock.tick(x) {clockTicks = clockTicks + 1// tracker#31: not before the duplicate merge is doneif (!mergeRun.done) { return null }busy = syncQueue.length > 0 || syncPlanningif (syncOn && clockTicks % 10 == 0) { syncTick() }free = !busy && syncQueue.length == 0 && !syncPlanningif (backfillOn && free && !backfillDone) { backfillTick() }else if (repairOn && free && (!backfillOn || backfillDone) && !repairDone) { repairTick() }else if (repairOn && free && (!backfillOn || backfillDone) && !statusDone) { statusTick() }else if (kindsOn && free && (!backfillOn || backfillDone) && (!repairOn || (repairDone && statusDone)) && !kindDone) { kindTick() }else if (creditsOn && free && (!backfillOn || backfillDone) && (!repairOn || (repairDone && statusDone)) && (!kindsOn || kindDone)) { creditsTick() }return null}}// ---- THE SHORT-ID BACKFILL (mission 060, tracker.worldapi.org#27, shortids.hl shortIdStep) ----------------------------// 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,// as many records as fit into TRACKER_SHORTID_BUDGET_MS (default 40 ms) — no TMDB, only the tables — so a page waits at// most one batch. The queue is built at start (`ensureShortIds`) from what is still missing = it resumes after a restart.// Persisted every 20 batches and at the end. Log: start, every TRACKER_SHORTID_LOG_EVERY (5000) records, done; with nothing// to do one line. TRACKER_SHORTIDS=0 switches it off (the gate's resume check).shortIdOn = env('TRACKER_SHORTIDS') != '0'shortIdBudget = env('TRACKER_SHORTID_BUDGET_MS') != null ? toNumber(env('TRACKER_SHORTID_BUDGET_MS')) : 40shortIdLogEvery = env('TRACKER_SHORTID_LOG_EVERY') != null ? toNumber(env('TRACKER_SHORTID_LOG_EVERY')) : 5000shortIdRun = { at = 0 batches = 0 assigned = 0 nextLog = 0 slowest = 0 slowestPersist = 0 done = false }shortIdTick = () => {if (shortIdRun.done) { return null }t = now()r = shortIdStep(shortIdBudget)took = now() - tshortIdRun.batches = shortIdRun.batches + 1shortIdRun.assigned = shortIdRun.assigned + r.assignedif (took > shortIdRun.slowest) { shortIdRun.slowest = took }if (r.done || shortIdRun.batches % 20 == 0) {tp = now()persistShortIds()if (now() - tp > shortIdRun.slowestPersist) { shortIdRun.slowestPersist = now() - tp }}if (!r.done && shortIdRun.assigned >= shortIdRun.nextLog) {console.log('short ids: ' + shortIdRun.assigned + ' assigned, ' + r.left + ' left, ' + ((now() - shortIdRun.at) / 1000) + ' s')shortIdRun.nextLog = shortIdRun.nextLog + shortIdLogEvery}if (r.done) {shortIdRun.done = trues = shortIdStats()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))}return null}if (!shortIdOn) { console.log('short ids: backfill off (TRACKER_SHORTIDS=0), ' + shortIdsLeft() + ' records without one') }else if (shortIdsLeft() == 0) { console.log('short ids: nothing to do') }else {shortIdRun.at = now()shortIdRun.nextLog = shortIdLogEveryconsole.log('short ids: backfill start, ' + shortIdsLeft() + ' records, ' + shortIdBudget + ' ms per batch')shortIdClock = every(0.1)on shortIdClock.tick(x) {shortIdTick()return null}}// ---- THE COLLECTION SEED (mission 066, tracker.worldapi.org#19, collections.hl seedStep) ------------------------------------// TMDB's movie collections become timelines: ONE movie per step (its details; once per collection the collection's parts), on// 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// sync or the adult backfill runs (they share TMDB's limit and the backfill brings the adult flags it skips by); since the merge// (mission 070) also until the details repair, the kind backfill and the credits job are done (or paused) — the LAST job. The queue =// every non-adult movie without a check row, so it RESUMES after a restart and does nothing once all are checked. Persisted// every TRACKER_COLLECTIONS_PERSIST_EVERY (25) steps and at the end. Log: start, every TRACKER_COLLECTIONS_LOG_EVERY (500) movies, done.// TRACKER_COLLECTIONS=0 switches it off; without TMDB_READ_TOKEN it is off too.collectionsOn = env('TRACKER_COLLECTIONS') != '0' && syncEnabledcollectionsLogEvery = env('TRACKER_COLLECTIONS_LOG_EVERY') != null ? toNumber(env('TRACKER_COLLECTIONS_LOG_EVERY')) : 500collectionsPersistEvery = env('TRACKER_COLLECTIONS_PERSIST_EVERY') != null ? toNumber(env('TRACKER_COLLECTIONS_PERSIST_EVERY')) : 25collectionRun = { at = 0 steps = 0 nextAt = 0 done = false started = false slowest = 0 }collectionTick = () => {if (collectionRun.done) { return null }// mission 070 (merge): also behind the details repair, the kind backfill and the credits job — one TMDB pacing at a timeif (!mergeRun.done || syncQueue.length > 0 || syncPlanning || (backfillOn && !backfillDone) || (repairOn && (!repairDone || !statusDone)) || (kindsOn && !kindDone) || (creditsOn && !creditsDone)) { return null }t = now()if (!collectionRun.started) {collectionRun.started = truecollectionRun.at = tn = seedPrepare()console.log('collections: start, ' + n + ' movies to check (' + (now() - t) + ' ms to find them)')if (n == 0) { collectionRun.done = true console.log('collections: nothing to do') }return null}if (t < collectionRun.nextAt) { return null }r = seedStep()if (r.done) {collectionRun.done = trueseedPersist()console.log('collections done: ' + seedLine() + ' seconds=' + ((now() - collectionRun.at) / 1000) + ' slowestStepMs=' + collectionRun.slowest)return null}collectionRun.steps = collectionRun.steps + 1took = now() - tif (took > collectionRun.slowest) { collectionRun.slowest = took }if (r.error != '') { console.log('collections: ' + r.error) }if (took > 1500) { console.log('collections: slow step, ' + took + ' ms') }collectionRun.nextAt = now() + r.requests * msPerRequestif (collectionRun.steps % collectionsPersistEvery == 0) { seedPersist() }if (collectionRun.steps % collectionsLogEvery == 0) { console.log('collections: ' + seedLine() + ' seconds=' + ((now() - collectionRun.at) / 1000)) }return null}if (!collectionsOn) { console.log('collections: off (' + (syncEnabled ? 'TRACKER_COLLECTIONS=0' : 'no TMDB_READ_TOKEN') + ')') }else {collectionClock = every(0.1)on collectionClock.tick(x) {collectionTick()return null}}
Branches
- mainmain branch
Latest commits
- b10f00c8tracker#39: double episodes — migrated episodes whose TMDB id TMDB replaced are adopted by their number in the sync (old id -> migratedTmdbId); merge.hl step 3 merges each season's doubles at start (keeper: most watches > synced > first; watches moved/parked; tombstones into mergedEpisodes, nothing deleted); tools/count-duplicate-episodes.hl; gate fixture + paths-m039; live copy 850 -> 0 in 64 s; gates 373/0, 32/0, 52/0mre
- 8751adb8tracker: report 032mre
- 9bce1f65tracker mission 032: STATUS gate files + the hour-boundary flakemre
- 718bfb89tracker#37 (mission 032): /people = everyone, last updated first (updatedAt stamped by the person fill; view built at boot, touched people first at once), photo + name tiles (person colour) with the /movies pagination, /people/<letter> removed; photo = our file, tmdbProfile, a cast/crew entry's profile (in-memory map at boot), else the new 'no photo' placeholder; new cast/crew/created_by people keep tmdbProfile; search people rows with the photo; /settings = the heading only; util.hl sortDesc starts from sorted runs (same result, 105k: 1.6 s -> 0.15 s); gates 369/0, 32/0, 52/0, check-theme 0; README/STATUS/LOGmre
- 96ba683adeploy.sh: a gate without a 'passed,' line (check-theme) no longer ends the scriptmre
- eb3b9205tracker: report 031mre
- 9b5d2e89tracker mission 031: README (What it does, Test: four gates + the #32 checks, Files: theme/, new pages), STATUS (real copy, A/B load, how to repeat, open points), LOGmre
- 39950e4ctracker#32 (mission 031): the WorldAPI theme (theme/ vendored verbatim from layouts.worldapi.org 85b5654; styles.hl inherits it: accent green-dark, type colours 1-6; own base/header rules, row lines, genre-pill and inverted-button frames removed, the season foldable keeps its line; check-theme 21 -> 0, 4th deploy gate; main actions class primary) and the #32 header (theme AppHeader/MainMenu/UserMenu/Sidebar/ContentFirst: desktop brand, search, Series|Shows|Movies|Genres|People, user icon with Unwatched..Settings, Logout; signed out the ident selector, phone the iD icon dropdown; phone menu in the sidebar overlay; marked entry by :has); /find -> /search/<q>, /genres, /people(/<letter>), /settings; main { ContentFirst { slot } } works around the hl:web one-line slot bug; gates 365/0, 32/0, 52/0, check-theme 0mre
- a386dc92tracker: reports 029 + 030mre
- 71e0fd7dtracker missions 029 + 030: README (What it does, Files, gate count), STATUS (real-copy numbers, how to repeat, open points), LOGmre
- d36ea6eatracker#34 + #35 (mission 030): Follow directly under the poster, as wide as the poster (show.hl, styles.hl); the status pill next to a series' title — TVmaze's status (new tvmazeStatus, stored by the sync's TVmaze merge) else TMDB's, TVmaze Ended + TMDB Canceled = Canceled, inverted (filled, dark text, no border), green running / yellow pending / red canceled / muted ended (shows.hl statusOf); the daily delta asks TVmaze's status of an unfollowed series TVmaze's change list names (dailysync.hl syncRunStep, sync.hl syncTvmazeStatus); the status backfill after the details repair (backfill.hl, jobs.hl statusTick; resumable, 550 ms per TVmaze request); gates 354/0, 32/0, 52/0mre
- 7d7d4487tracker#33 (mission 029): reduced titles — every title TMDB's details never went through this app (no detailsAt, no tmdbSync) is incomplete (shows.hl isIncomplete; the old tracker's migrated rows passed #26's test: 5,697 non-adult on the live copy, 691 series without seasons); the repair job does the visibly reduced first (shows.hl missingParts), the page completes one on open; a title TMDB has no poster for (The Remaining) shows the placeholder; tools/count-incomplete.hl; gate fixtures stand for synced titles (tmdbSync), tests/seed-reduced.hl + #33 checks; gates 347/0, 32/0, 52/0mre
- 661c2592tracker: report 028mre
- 27c916fatracker mission 028: README ("Code order", the new file map), STATUS (counts before/after, tests, how to repeat, open), LOGmre
- d924f398tracker mission 028: comments name the new files (sync.hl, dailysync.hl, backfill.hl, credits.hl, jobs.hl, images.hl …); tools/ref-params.py + tools/lambda-audit.py also scan lib/ (they globbed the root only), lambda-audit counts a plain `x = p` alias like `let x = p`mre
- 2e89b968tracker mission 028 (code order) 5/5 let: `let` only where a variable is reassigned — 667 never-reassigned lets became plain declarations (project.hl, lib/, components/, tools/, tests/); kept: 264 in loop bodies (a plain declaration there is 'Cannot reassign' on the 2nd pass), 234 reassigned, 27 whose name is also a member/outer/free name (a plain write would rebind it); tools/let-audit.py decides and fixes (README 'Code order'); tests/realdata-m028.{sh,mjs} = the page-output diff on a real copy; gates 342/0, 32/0, 52/0, real-copy pages identicalmre
- 54796ff2tracker mission 028 (code order) 4/5 thin faces + last copies: the show page's check/follow faces call lib/watches.hl toggleWatched / toggleSeasonWatched (seasonAllWatched moved there) and lib/follows.hl toggleFollowed; both logins (header selector face, /login/callback) share lib/users.hl userOfCode; todayStr/listOf copies in components and the export readers copied into tools/migrate.hl + tools/old-short-ids.hl now once (lib/util.hl, lib/export.hl); gates 342/0, 32/0, 52/0; old-short-ids output byte-identical, migrate output identicalmre
- 06b078e3tracker mission 028 (code order) 3/5 project.hl is the map: config, routes, wiring and a feature → file index (914 → 258 lines); the background jobs (daily sync run, backfills, details repair, credits job, merge, short ids, collection seed) moved unchanged into lib/jobs.hl (a class: their state is reassigned every step, a static cannot be; one instance made after the server), the login callback into lib/users.hl, poster/photo serving into lib/images.hl, the /shows/<slug> rule into lib/shows.hl showsMovedPath; route handlers are thin wrappers; gates 342/0, 32/0, 52/0, real-copy pages identicalmre
- 94716fd2tracker mission 028 (code order) 2/5 util + topics: lib/util.hl holds envOr, storageDir, postersDir, profilesDir, newId, hexDigits, todayStr, dateOr, textOr, hasId, listOr, firstOf, sortDesc once (were copied into up to 5 files); tmdbsync.hl split into tmdb.hl (TMDB/TVmaze requests), sync.hl (one title's sync), sync-helpers.hl, backfill.hl; details.hl split into details.hl, credits.hl, credits-helpers.hl (isIncomplete to shows.hl); search-helpers.hl (words, query, ranking, slugs); collections.hl (the TMDB collection seed, out of franchises.hl); deltasync.hl renamed dailysync.hl; no behaviour change: gates 342/0, 32/0, 52/0, real-copy pages identicalmre
- 186079b0tracker mission 028 (code order) 1/5 move: every root .hl except project.hl into lib/ (styles.hl into components/), import paths only; gates 342/0, 32/0, 52/0; real-copy pages identicalmre