gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2667da052667da05tracker#30 (mission 025): /my/ pages from slim cached title cards, episode rows and watch sets (after the jobs /my/series 1.8 s -> 0.06 s, /my/unwatched 4.1 -> 0.18 s); timeline page shows its name once; franchise widget under the poster/title; movies with TV leftovers (First Contact) go through the details repair; tools/count-tmdb-ids.hl; gates 327/0, 52/0, 32/0mre2667da05/project.hl

48.9 KB

  1. // project.hl — tracker.worldapi.org: STEP 1 (tracker.worldapi.org#1), an empty shell. Login copied unchanged from
  2. // calendar.worldapi.org (rejected once for a centered sign-in and no header selector — architect, 2026-09-27):
  3. // ident only, no own passwords (README "How apps use ident" of ident.worldapi.org), the identity selector in the
  4. // header (components/main.hl). No shows, no data yet — later steps come from the creator (CONCEPT.md).
  5. //
  6. // the header's ident-selector / "Log in with ident" -> <ident>/login?key=&return=<this app>/login/callback
  7. // /login/callback?ident_code=<code> the app's server exchanges the code for the identity's short id
  8. // (POST <ident>/api/exchange) and signs this app's OWN session in
  9. // (session.user = { id = <users @id> }, users.hl)
  10. // the header's "Log out" button signs this app's session out via the face trackerLogOut (components/main.hl)
  11. // — ident's own session, and the browser's ident cookie, are untouched
  12. //
  13. // Config (env; no committed secret — the first deploy registers this app in ident and sets these, done by the
  14. // architect, as with ident's own .env for SMTP):
  15. // TRACKER_PORT (45008), TRACKER_URL (this app's own public address, for the return URL),
  16. // IDENT_URL (https://ident.worldapi.org), TRACKER_KEY (pk_…), TRACKER_SECRET (sk_…)
  17. import WebFramework from 'hl:web'
  18. import { Response } from 'hl:http1'
  19. import { randomBytes } from 'hl:crypto'
  20. import { env } from 'hl:proc'
  21. import { readBytes, readFile, exists } from 'hl:fs'
  22. import { now, timestamp, every } from 'hl:time'
  23. import Styles from './styles.hl'
  24. import { exchangeCode, ensureUser } from './users.hl'
  25. import Home from './components/home.hl'
  26. import LoginFailed from './components/loginfailed.hl'
  27. import Show from './components/show.hl'
  28. import Unwatched from './components/unwatched.hl'
  29. import Schedule from './components/schedule.hl'
  30. import MyShows from './components/myshows.hl'
  31. import MyMovies from './components/mymovies.hl'
  32. import Movies from './components/movies.hl'
  33. import AllShows from './components/allshows.hl'
  34. import AllSeries from './components/allseries.hl'
  35. import Search from './components/search.hl'
  36. import Person from './components/person.hl'
  37. import Genre from './components/genre.hl'
  38. import Franchises from './components/franchises.hl'
  39. import Franchise from './components/franchise.hl'
  40. import FranchiseEdit from './components/franchiseedit.hl'
  41. import TimelineEdit from './components/timelineedit.hl'
  42. import { ensureIndex, searchTitleChanged, searchTitleRenamed } from './search.hl'
  43. import { syncEnabled, syncShow, syncShowDelta, persistSync, emptyTotals, addTotals, totalsLine, pauseMsAfter, msPerRequest, adultBackfillQueue, backfillTitle, kindBackfillQueue, kindTitle } from './tmdbsync.hl'
  44. import { detailsRepairQueue, completeStep, completeLine, persistDetails, persistCredits, applySynced, creditsQueue, creditsStep } from './details.hl'
  45. import { planStart, planStep, planIds, planLine, markSynced, moveCopiedSummaries, isFollowedInRun } from './deltasync.hl'
  46. import { showBySlug, titleKind, titlePath, warmTitleCaches, warmEpisodeKeys } from './shows.hl'
  47. import { allWatchedEpisodeIds } from './watches.hl'
  48. import { allFollowedShowIds } from './follows.hl'
  49. import { refreshCatalogShow } from './catalog.hl'
  50. import { ensureShortIds, shortIdStep, shortIdPath, shortIdsLeft, shortIdStats, persistShortIds } from './shortids.hl'
  51. import { guestPersonId } from './people.hl'
  52. import { personById } from './shows.hl'
  53. import { dark, darker } from './shared/tokens.hl'
  54. import { ensureFranchises, seedPrepare, seedStep, seedLine, seedPersist } from './franchises.hl'
  55. static appTitle = "tracker"
  56. // ---- THE INSTALLABLE APP (tracker.worldapi.org#10), the same way calendar.worldapi.org does it: hl:web's own web app
  57. // manifest (/__hl/manifest.webmanifest, linked from every head with the apple-touch-icon and theme-color) and service
  58. // worker (/__hl/sw.js) from these settings — no JavaScript of ours. Icons in icons/ (icon.svg is the source, the PNGs
  59. // are rendered from it with rsvg-convert, README "Icons"). The theme colour is the header's background (darker), the
  60. // splash background the page's (dark) — both off the tokens, not written out again.
  61. appThemeColor = darker.value
  62. appBackgroundColor = dark.value
  63. appIcons = [
  64. { src = '/icons/icon-192.png' sizes = '192x192' purpose = 'any' }
  65. { src = '/icons/icon-512.png' sizes = '512x512' purpose = 'any' }
  66. { src = '/icons/icon-192.png' sizes = '192x192' purpose = 'maskable' }
  67. { src = '/icons/icon-512.png' sizes = '512x512' purpose = 'maskable' }
  68. ]
  69. appTouchIcon = '/icons/apple-touch-icon.png'
  70. appFavicon = '/icons/favicon.svg'
  71. // OFFLINE: only the shell — the header and `/` (components/main.hl says "You are offline" while the browser has no
  72. // network). The data pages are not kept: without a network they get hl:web's "Unavailable offline" page.
  73. offline = [ Home ]
  74. styles = Styles
  75. port = env('TRACKER_PORT') != null ? toNumber(env('TRACKER_PORT')) : 45008
  76. watching = env('TRACKER_WATCH') != '0'
  77. // read by hl:web's own manifest config (WebFramework.hl `cfg.sessionDir`), not the constructor call below
  78. sessionDir = env('TRACKER_SESSIONS') != null ? env('TRACKER_SESSIONS') : null
  79. // ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident"), copied from calendar.worldapi.org's project.hl
  80. // BACK TO THE PAGE: /login.js puts `?next=` into the button's return URL at the click. Only a same-origin PATH
  81. // goes (one `/`, URL-safe characters, ≤ 500). Anything else → `/`.
  82. nextChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;@!$()*:'
  83. safePath = (&want) => {
  84. if (want == null || hlTypeName(want) != 'String' || want == '' || want.length > 500) { return '/' }
  85. if (want.slice(0, 1) != '/' || want.slice(0, 2) == '//' || want.slice(0, 7) == '/login/') { return '/' }
  86. let i = 0
  87. while (i < want.length) {
  88. if (!nextChars.includes(want[i])) { return '/' }
  89. i = i + 1
  90. }
  91. return want
  92. }
  93. // A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked in the session, then → /login/failed
  94. failed = (&req, why) => {
  95. let s = req.session
  96. let fresh = s == null
  97. if (fresh) { s = server.sessions.mint() }
  98. s.data.loginError = why
  99. server.sessions.save(s)
  100. let res = new Response('login failed: ' + why, { status = 302 headers = { 'Location' = '/login/failed' 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })
  101. if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }
  102. return res
  103. }
  104. // the function route gets the cookie's session as req.session (hybriel #11); none yet → minted here
  105. loginCallback = (&route, &req) => {
  106. if (req.method != 'GET') { return failed(req, 'GET only') }
  107. let q = req.query != null ? req.query : {}
  108. let code = q.ident_code
  109. if (code == null || code == '') { return failed(req, 'ident sent no login code') }
  110. let x = exchangeCode(code)
  111. if (x.error != null) { return failed(req, x.error) }
  112. let u = ensureUser(x.identity)
  113. if (u == null) { return failed(req, 'could not store the user') }
  114. let s = req.session
  115. let fresh = s == null
  116. if (fresh) { s = server.sessions.mint() }
  117. s.user = { id = u.id }
  118. s.data.tag = randomBytes(16)
  119. s.data.loginError = null
  120. server.sessions.save(s)
  121. let res = new Response('logged in', { status = 302 headers = { 'Location' = safePath(q.next) 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })
  122. if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }
  123. return res
  124. }
  125. // ---- /posters/<name> (tracker.worldapi.org#4): a show's poster image, served dynamically from
  126. // storage/mpackdb/posters/ (the poster's file name is the show's oldId + its migrated extension,
  127. // shows.hl posterName) — falls back to a placeholder svg when the real file isn't there yet (the
  128. // mongo export never included the actual poster bytes, see the report's `open`).
  129. postersDir = (env('TRACKER_STORAGE') != null ? env('TRACKER_STORAGE') : './storage/mpackdb') + '/posters'
  130. placeholderPoster = './assets/poster-placeholder.svg'
  131. posterNameChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-_'
  132. isSafePosterName = (&name) => {
  133. if (name == null || hlTypeName(name) != 'String' || name == '' || name.length > 100) { return false }
  134. let i = 0
  135. while (i < name.length) {
  136. if (!posterNameChars.includes(name[i])) { return false }
  137. i = i + 1
  138. }
  139. return true
  140. }
  141. endsWithStr = (&s, suffix) => { return s.length >= suffix.length && s.slice(s.length - suffix.length) == suffix }
  142. mimeOfPoster = (&name) => {
  143. if (endsWithStr(name, '.png')) { return 'image/png' }
  144. if (endsWithStr(name, '.webp')) { return 'image/webp' }
  145. if (endsWithStr(name, '.svg')) { return 'image/svg+xml' }
  146. return 'image/jpeg'
  147. }
  148. posterRoute = (&route, &req) => {
  149. let name = route.params != null ? route.params.name : null
  150. if (!isSafePosterName(name)) { return new Response('bad poster name', { status = 400 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }
  151. let path = postersDir + '/' + name
  152. if (exists(path)) { return new Response(readBytes(path), { headers = { 'Content-Type' = mimeOfPoster(name) 'Cache-Control' = 'public, max-age=86400' } }) }
  153. return new Response(readBytes(placeholderPoster), { headers = { 'Content-Type' = 'image/svg+xml' 'Cache-Control' = 'public, max-age=3600' } })
  154. }
  155. // ---- /profiles/<name> (tracker.worldapi.org#16): a person's photo, from storage/mpackdb/profiles/ (people.hl syncProfile
  156. // downloads it on the first visit of the person page) — the same checks and placeholder as /posters/<name>
  157. profilesDir = (env('TRACKER_STORAGE') != null ? env('TRACKER_STORAGE') : './storage/mpackdb') + '/profiles'
  158. profileRoute = (&route, &req) => {
  159. let name = route.params != null ? route.params.name : null
  160. if (!isSafePosterName(name)) { return new Response('bad photo name', { status = 400 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }
  161. let path = profilesDir + '/' + name
  162. if (exists(path)) { return new Response(readBytes(path), { headers = { 'Content-Type' = mimeOfPoster(name) 'Cache-Control' = 'public, max-age=86400' } }) }
  163. return new Response(readBytes(placeholderPoster), { headers = { 'Content-Type' = 'image/svg+xml' 'Cache-Control' = 'public, max-age=3600' } })
  164. }
  165. // ---- the old addresses of the personal lists (tracker.worldapi.org#8): they all live under /my/ now —
  166. // a permanent redirect so old links keep working (architect's decision)
  167. movedTo = (&path) => { return new Response('moved to ' + path, { status = 301 headers = { 'Location' = path 'Content-Type' = 'text/plain; charset=utf-8' } }) }
  168. unwatchedMoved = (&route, &req) => { return movedTo('/my/unwatched') }
  169. scheduleMoved = (&route, &req) => { return movedTo('/my/schedule') }
  170. // mission 058: the show page's genre pills linked `/genre/<x>` (no page there) — the genre pages are `/genres/<x>`
  171. genreMoved = (&route, &req) => {
  172. let g = route.params != null ? route.params.genre : null
  173. return movedTo(isSafePosterName(g) ? '/genres/' + g : '/')
  174. }
  175. // mission 060 (tracker.worldapi.org#27): `/<shortId>` → 301 to the title's or person's page (shortids.hl); upper case is
  176. // read as lower case; anything else is a 404
  177. shortIdRoute = (&route, &req) => {
  178. let sid = route.params != null ? route.params.sid : null
  179. let path = sid != null && hlTypeName(sid) == 'String' ? shortIdPath(sid.toLowerCase()) : null
  180. if (path == null) { return new Response('not found', { status = 404 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }
  181. return movedTo(path)
  182. }
  183. // mission 062: a GUEST STAR's link (components/show.hl castRowsOf) — guests are no person records until someone opens one:
  184. // `/person/tmdb/<tmdbId>?show=<show id>` creates the person (people.hl guestPersonId: name + role from that title, a short id) or
  185. // finds the one we have, then 302 → `/person/<slug>` (the page fills from TMDB as for any new person). A function route: the
  186. // browser loads it itself (hl:web's client router hands every non-component link to the browser)
  187. guestRoute = (&route, &req) => {
  188. let t = route.params != null ? route.params.tmdb : null
  189. let tmdbId = t != null && hlTypeName(t) == 'String' && t.length <= 10 ? toNumber(t) : null
  190. if (tmdbId == null || tmdbId < 1) { return new Response('not found', { status = 404 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }
  191. let q = req.query != null ? req.query : {}
  192. let r = guestPersonId(tmdbId, q.show)
  193. let p = r.id != null ? personById(r.id) : null
  194. if (p == null || p.urlSegment == null) { return new Response('not found: ' + (r.error != null ? r.error : 'no such person'), { status = 404 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }
  195. return new Response('see /person/' + p.urlSegment, { status = 302 headers = { 'Location' = '/person/' + p.urlSegment 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })
  196. }
  197. // ---- /shows/<slug> (tracker.worldapi.org#21, mission 068): since the split only the game / reality / talk / news SHOWS live
  198. // here; a series answers 301 to /series/<slug>, a movie to /movies/<slug> (old links and bookmarks keep working). hl:web has no
  199. // way for a component route to answer a redirect, so this is a FUNCTION route, and for a show (or an unknown slug: the page's own
  200. // "Not found") it renders the title page the way hl:web renders a component route (WebFramework.hl `on http.request`, the
  201. // `component` branch): the Show component matched at /series/<slug> — same component, same params — with the cookie's session,
  202. // a new one (and its cookie) when the browser brought none. In the browser a link to /shows/<slug> is then a full page load
  203. // (the client router only navigates component routes itself); every other title page stays a client-side navigation.
  204. showsRoute = (&route, &req) => {
  205. let slug = route.params != null ? route.params.slug : null
  206. let show = showBySlug(slug)
  207. if (show != null && titleKind(show) != 'show') { return movedTo(titlePath(show)) }
  208. let m = server.router.match('/series/' + slug)
  209. let s = req.session
  210. let fresh = s == null
  211. if (fresh) { s = server.sessions.mint() }
  212. let res = server.page(m, s, server.hostOf(req.headers['host']), server.requestHeaders(req.headers))
  213. if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }
  214. return res
  215. }
  216. routes = [
  217. { pattern = "/favicon.ico" file = "./icons/favicon.ico" headers = { 'Cache-Control' = 'no-cache' } }
  218. // the installable app (tracker.worldapi.org#10): the icons (manifest and service worker are hl:web's own, from appIcons / offline)
  219. { pattern = "/icons/icon-192.png" file = "./icons/icon-192.png" headers = { 'Cache-Control' = 'no-cache' } }
  220. { pattern = "/icons/icon-512.png" file = "./icons/icon-512.png" headers = { 'Cache-Control' = 'no-cache' } }
  221. { pattern = "/icons/apple-touch-icon.png" file = "./icons/apple-touch-icon.png" headers = { 'Cache-Control' = 'no-cache' } }
  222. { pattern = "/icons/favicon.svg" file = "./icons/favicon.svg" headers = { 'Cache-Control' = 'no-cache' } }
  223. { pattern = "/login/callback" function = loginCallback }
  224. { pattern = "/login/failed" component = LoginFailed }
  225. { pattern = "/login.js" file = "./login.js" headers = { 'Cache-Control' = 'no-cache' } }
  226. { pattern = "/posters/:name" function = posterRoute }
  227. // tracker.worldapi.org#13: every movie / every series, 24 per page — the page is a PATH segment (`/movies/page/2`), a
  228. // page component cannot read `?page=` (hybriel#11) — and the movies the user follows
  229. { pattern = "/movies" component = Movies }
  230. { pattern = "/movies/page/:page" component = Movies }
  231. // tracker.worldapi.org#21 (mission 068): series and shows split — /series lists the series, /shows the shows; a title's page
  232. // is /movies/<slug>, /series/<slug> or /shows/<slug> (one component; /shows/<slug> is showsRoute above)
  233. { pattern = "/movies/:slug" component = Show }
  234. { pattern = "/series" component = AllSeries }
  235. { pattern = "/series/page/:page" component = AllSeries }
  236. { pattern = "/series/:slug" component = Show }
  237. { pattern = "/shows" component = AllShows }
  238. { pattern = "/shows/page/:page" component = AllShows }
  239. { pattern = "/shows/:slug" function = showsRoute }
  240. { pattern = "/my/movies" component = MyMovies }
  241. { pattern = "/my/unwatched" component = Unwatched }
  242. { pattern = "/my/schedule" component = Schedule }
  243. // #21: /my/series and /my/shows (one component, components/myshows.hl; any other word there is its "Not found")
  244. { pattern = "/my/:tv" component = MyShows }
  245. { pattern = "/unwatched" function = unwatchedMoved }
  246. { pattern = "/schedule" function = scheduleMoved }
  247. // tracker.worldapi.org#14: the search — `/search/<text>` (hl:web gives a page no query string, so not `?q=`)
  248. { pattern = "/search/:q?" component = Search }
  249. // tracker.worldapi.org#16: a person's page (the show page's cast and the search link here) and their photo
  250. { pattern = "/person/tmdb/:tmdb" function = guestRoute }
  251. { pattern = "/person/:slug" component = Person }
  252. { pattern = "/profiles/:name" function = profileRoute }
  253. // mission 058 (tracker.worldapi.org#25): a genre's movies and series, like /movies (the page in the path)
  254. { pattern = "/genres/:genre" component = Genre }
  255. { pattern = "/genres/:genre/page/:page" component = Genre }
  256. { pattern = "/genre/:genre" function = genreMoved }
  257. // tracker.worldapi.org#19 (mission 066): franchises and timelines, the creator's editor (`/franchises/edit` before the slug)
  258. { pattern = "/franchises" component = Franchises }
  259. { pattern = "/franchises/edit" component = FranchiseEdit }
  260. { pattern = "/franchises/:slug" component = Franchise }
  261. { pattern = "/timelines/:tslug" component = Franchise }
  262. { pattern = "/timelines/:slug/edit" component = TimelineEdit }
  263. { pattern = "/" component = Home }
  264. // mission 060 (tracker.worldapi.org#27): a short id → its page (LAST: every named one-segment route above wins)
  265. { pattern = "/:sid" function = shortIdRoute }
  266. ]
  267. // WHO GETS THE PUSH: the login state reaches the tabs of one session (components/main.hl trackerSignedIn/Out).
  268. tagOf = (&session) => { return session != null && session.data != null ? session.data.tag : null }
  269. audience = {
  270. trackerSignedIn = (tag, &session) => { return tag != null && tagOf(session) == tag }
  271. trackerSignedOut = (tag, &session) => { return tag != null && tagOf(session) == tag }
  272. }
  273. // cookies are per host, not per port: an own name keeps this app's session apart from
  274. // ident's own (and from any other worldapi app sharing a dev host), see ident README "Design
  275. // tokens" / hybriel#10 hybriel#17.
  276. sessionCookie = 'trackersid'
  277. // tracker.worldapi.org#14: the search index (search.hl) is built once here at boot (~0.6 s on the real data), not by the
  278. // first search
  279. searchIndexReady = ensureIndex()
  280. // mission 060: every short id in use (one map over shows AND persons) and the records still without one, before the first request
  281. shortIdsReady = ensureShortIds()
  282. // tracker#30 (mission 025): the slim list caches (shows.hl cardOf / episodeRowsOf) of every followed title, before the first
  283. // /my/ load — not filled by that load
  284. titleCachesStart = now()
  285. titleCachesWarm = warmTitleCaches(allFollowedShowIds())
  286. episodeKeysWarm = warmEpisodeKeys(allWatchedEpisodeIds())
  287. console.log('list caches: ' + titleCachesWarm + ' followed titles, ' + episodeKeysWarm + ' watched episodes in ' + (now() - titleCachesStart) + ' ms')
  288. // tracker#18, ONCE (deltasync.hl moveCopiedSummaries): a `summary` that is only the migrated copy of tmdbSummary is MOVED to
  289. // `migratedSummary` (mission 070: kept, not shown) — the current TMDB text shows; the creator's own texts stay
  290. summariesMoved = moveCopiedSummaries()
  291. if (summariesMoved.ran) { console.log('summaries: moved ' + summariesMoved.moved + ' copies of tmdbSummary to migratedSummary, kept ' + summariesMoved.kept + ' own texts, errors ' + summariesMoved.errors + ', ' + summariesMoved.ms + ' ms') }
  292. // mission 066: which timelines every title is in (one scan of the timelines), before the first show page
  293. franchisesReady = ensureFranchises()
  294. server = new WebFramework(routes = routes, styles = styles, port = port, sessionCookie = sessionCookie, watchMode = watching)
  295. // ---- THE DAILY TMDB SYNC (tracker.worldapi.org#9, tmdbsync.hl; tracker#18, deltasync.hl) -------------------------
  296. // Once a day at TRACKER_SYNC_HOUR (UTC, default 4 — hl:time has no time zones; the container runs UTC). hl:web serves ONE
  297. // 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
  298. // requests that queued meanwhile are served between two ticks, and a tick never starts inside a page render.
  299. // tracker#18: the run first asks TMDB's and TVmaze's CHANGE LISTS since the last run (deltasync.hl — one list page per step)
  300. // and then syncs only the titles of ours that changed, followed ones first — every title stays current, not only the followed
  301. // ones. FULL WALK (every followed show, as before #18) on the first run, after a gap > 14 days, or when a change list fails.
  302. // A title's step: tmdbsync.hl syncShow (1–3 TMDB requests + maybe its poster, TVmaze) + details.hl applySynced (the record's
  303. // title, overview, tagline … and cast/crew from the same details answer). After a step that made n requests the next waits
  304. // n × 260 ms (TMDB: ≤ 40 requests / 10 s) + 550 ms per TVmaze request (≤ 20 / 10 s, tracker.worldapi.org#12).
  305. // The finished run stores its day (deltasync.hl markSynced). Log: "tmdb sync: start, …", the change lists ("tmdb sync:
  306. // changes since …"), errors, slow steps, "tmdb sync done: mode=… changeRequests=… <totals>".
  307. // TRACKER_SYNC=0 switches it off; without TMDB_READ_TOKEN it is off too (logged once).
  308. syncHour = env('TRACKER_SYNC_HOUR') != null ? toNumber(env('TRACKER_SYNC_HOUR')) : 4
  309. syncOn = env('TRACKER_SYNC') != '0' && syncEnabled
  310. syncQueue = []
  311. syncPlanning = false
  312. syncMode = ''
  313. syncMark = false
  314. syncChangeRequests = 0
  315. syncAt = 0
  316. syncDay = ''
  317. syncNextAt = 0
  318. syncTotals = emptyTotals()
  319. syncFinish = () => {
  320. persistDetails()
  321. if (syncMark) { markSynced(syncDay) }
  322. console.log('tmdb sync done: mode=' + syncMode + ' changeRequests=' + syncChangeRequests + ' ' + totalsLine(syncTotals) + ' seconds=' + ((now() - syncAt) / 1000))
  323. return null
  324. }
  325. syncTick = () => {
  326. let t = now()
  327. if (syncQueue.length == 0 && !syncPlanning) {
  328. let stamp = timestamp(t)
  329. let day = stamp.slice(0, 10)
  330. if (toNumber(stamp.slice(11, 13)) != syncHour || day == syncDay) { return null }
  331. syncDay = day
  332. syncAt = t
  333. syncNextAt = 0
  334. syncTotals = emptyTotals()
  335. syncChangeRequests = 0
  336. let p = planStart(day, null)
  337. syncMode = p.mode
  338. syncMark = true
  339. if (p.mode == 'delta') {
  340. syncPlanning = true
  341. console.log('tmdb sync: start, changes ' + p.why)
  342. return null
  343. }
  344. syncQueue = allFollowedShowIds()
  345. console.log('tmdb sync: start, ' + syncQueue.length + ' followed shows, full walk (' + p.why + ')')
  346. if (syncQueue.length == 0) { syncFinish() }
  347. return null
  348. }
  349. if (t < syncNextAt) { return null }
  350. if (syncPlanning) {
  351. let ps = planStep()
  352. syncChangeRequests = syncChangeRequests + ps.requests + ps.tvmazeRequests
  353. syncTotals.requests = syncTotals.requests + ps.requests
  354. syncTotals.tvmazeRequests = syncTotals.tvmazeRequests + ps.tvmazeRequests
  355. syncNextAt = now() + pauseMsAfter(ps)
  356. if (!ps.done) { return null }
  357. syncPlanning = false
  358. console.log('tmdb sync: ' + planLine())
  359. if (ps.failed != '') {
  360. // a change list could not be read: the old full walk, and the day is not advanced (the next run asks again)
  361. syncMode = 'full'
  362. syncMark = false
  363. syncQueue = allFollowedShowIds()
  364. console.log('tmdb sync: change list failed, full walk of ' + syncQueue.length + ' followed shows instead')
  365. } else {
  366. syncQueue = planIds()
  367. }
  368. if (syncQueue.length == 0) { syncFinish() }
  369. return null
  370. }
  371. let id = syncQueue[0]
  372. let rest = []
  373. let i = 1
  374. while (i < syncQueue.length) { rest.push(syncQueue[i]) i = i + 1 }
  375. syncQueue = rest
  376. // tracker#18: in a delta run a title nobody follows gets the light step (changed seasons, no TVmaze)
  377. let r = syncMode == 'delta' && !isFollowedInRun(id) ? syncShowDelta(id) : syncShow(id)
  378. // tracker#18 + #28: the record's own fields (title, overview, tagline …) and the cast + crew from the same details answer
  379. if (r.details != null) {
  380. let c = applySynced(id, r.details)
  381. if (c.error != '') { console.log('tmdb sync: ' + c.error) }
  382. if (c.renamed) { searchTitleRenamed(id) }
  383. }
  384. // the public lists (catalog.hl, tracker.worldapi.org#13): this show's place by its newest released episode; the sync
  385. // also brings TMDB's adult flag (mission 054) → the search's view of it too
  386. refreshCatalogShow(id)
  387. searchTitleChanged(id)
  388. let took = now() - t
  389. syncTotals = addTotals(syncTotals, r)
  390. if (r.error != '') { console.log('tmdb sync: ' + r.error) }
  391. // a step blocks every request meanwhile (Saturday Night Live, 53 seasons, 4 requests: ~1.7 s) — say so in the log
  392. if (took > 1500) { console.log('tmdb sync: slow step, show ' + id + ', ' + r.requests + ' requests, ' + took + ' ms') }
  393. syncNextAt = now() + pauseMsAfter(r)
  394. if (syncQueue.length > 0 && syncTotals.shows % 10 == 0) { persistDetails() }
  395. if (syncQueue.length == 0) { syncFinish() }
  396. return null
  397. }
  398. // ---- THE ADULT-FLAG BACKFILL (mission 054, tmdbsync.hl backfillTitle) -----------------------------------
  399. // The public lists and the search show only titles TMDB says are not adult (shows.hl isPublicTitle; unknown = hidden). At
  400. // start the app collects every title whose flag is still unknown and asks TMDB for ONE title per step — like the daily
  401. // sync, on the same clock, so requests queued meanwhile are served between two steps: one details request (adult,
  402. // poster_path, external ids) + the poster file when missing, then a pause of 260 ms per TMDB API request (≤ 40 / 10 s;
  403. // the poster comes from TMDB's image host, not the API, and is not counted). Each answered title goes into the lists
  404. // (catalog.hl refreshCatalogShow) and the search at once. RESUMES after a restart: the queue is built from what is
  405. // still unknown. Stops when the queue is empty; titles TMDB answers 404 for are marked (`adultCheck`) and stay hidden; a
  406. // passing failure (no answer, 429, 5xx) goes to the back of the queue, at most 2 more tries per start.
  407. // While the daily sync runs, the backfill waits. Log: start, every TRACKER_BACKFILL_LOG_EVERY (500) titles, done.
  408. // TRACKER_BACKFILL=0 switches it off; without TMDB_READ_TOKEN it is off too.
  409. backfillOn = env('TRACKER_BACKFILL') != '0' && syncEnabled
  410. backfillLogEvery = env('TRACKER_BACKFILL_LOG_EVERY') != null ? toNumber(env('TRACKER_BACKFILL_LOG_EVERY')) : 500
  411. backfillQueue = null
  412. backfillPos = 0
  413. backfillDone = false
  414. backfillAt = 0
  415. backfillNextAt = 0
  416. backfillTries = {}
  417. backfillTotals = { titles = 0 adult = 0 notAdult = 0 unknown = 0 posters = 0 ids = 0 requests = 0 errors = 0 retries = 0 }
  418. backfillLine = () => {
  419. let b = backfillTotals
  420. return b.titles + '/' + backfillQueue.length + ' titles, adult=' + b.adult + ' notAdult=' + b.notAdult + ' unknown=' + b.unknown + ' posters=' + b.posters
  421. + ' ids=' + b.ids + ' requests=' + b.requests + ' errors=' + b.errors + ' retries=' + b.retries + ' seconds=' + ((now() - backfillAt) / 1000)
  422. }
  423. backfillTick = () => {
  424. if (backfillDone) { return null }
  425. let t = now()
  426. if (backfillQueue == null) {
  427. backfillQueue = adultBackfillQueue()
  428. backfillAt = t
  429. console.log('adult backfill: start, ' + backfillQueue.length + ' titles without an adult flag (' + (now() - t) + ' ms to find them)')
  430. if (backfillQueue.length == 0) { backfillDone = true console.log('adult backfill: nothing to do') }
  431. return null
  432. }
  433. if (t < backfillNextAt) { return null }
  434. let id = backfillQueue[backfillPos]
  435. backfillPos = backfillPos + 1
  436. let r = backfillTitle(id)
  437. if (r.retry && (backfillTries[id] == null || backfillTries[id] < 2)) {
  438. backfillTries[id] = backfillTries[id] == null ? 1 : backfillTries[id] + 1
  439. let q = backfillQueue
  440. q.push(id)
  441. backfillQueue = q
  442. backfillTotals.retries = backfillTotals.retries + 1
  443. } else {
  444. backfillTotals.titles = backfillTotals.titles + 1
  445. 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 }
  446. }
  447. backfillTotals.posters = backfillTotals.posters + r.posters
  448. backfillTotals.ids = backfillTotals.ids + r.ids
  449. backfillTotals.requests = backfillTotals.requests + r.requests
  450. backfillTotals.errors = backfillTotals.errors + r.errors
  451. if (r.error != '') { console.log('adult backfill: ' + r.error) }
  452. if (r.adult != null) {
  453. refreshCatalogShow(id)
  454. searchTitleChanged(id)
  455. }
  456. let took = now() - t
  457. if (took > 1500) { console.log('adult backfill: slow step, show ' + id + ', ' + took + ' ms') }
  458. backfillNextAt = now() + r.requests * msPerRequest
  459. let finished = backfillPos >= backfillQueue.length
  460. if (finished || backfillPos % 25 == 0) { persistSync() }
  461. if (!finished && backfillTotals.titles > 0 && backfillTotals.titles % backfillLogEvery == 0 && !r.retry) { console.log('adult backfill: ' + backfillLine()) }
  462. if (finished) {
  463. backfillDone = true
  464. console.log('adult backfill done: ' + backfillLine())
  465. }
  466. return null
  467. }
  468. // ---- THE DETAILS REPAIR (tracker.worldapi.org#26, details.hl completeStep) ----------------------------------------
  469. // Titles the person pages added from a filmography (#16) are MINIMAL (no poster, seasons, ids, cast …). Opening one completes
  470. // it (components/show.hl); this job completes the rest in the background: at start it collects every incomplete, non-adult
  471. // title 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
  472. // (1–3 TMDB requests + poster + TVmaze), requests queued meanwhile are served between two steps; then a pause of 260 ms per
  473. // TMDB request + 550 ms per TVmaze request (pauseMsAfter: ≤ 40 / 10 s, ≤ 20 / 10 s). RESUMES after a restart (the queue is
  474. // what is still incomplete); TMDB 404 marks the title (`detailsCheck`), a passing failure goes to the back of the queue (at
  475. // most 2 more tries per start). Waits while the daily sync or the adult backfill runs. Persisted every 10 titles + at the end.
  476. // Log: start, every TRACKER_REPAIR_LOG_EVERY (100) titles, each failure, done. TRACKER_REPAIR=0 switches it off (off too
  477. // without TMDB_READ_TOKEN). TRACKER_REPAIR_FAST=1 (the gate, fake TMDB only): 20 ms pause instead.
  478. repairOn = env('TRACKER_REPAIR') != '0' && syncEnabled
  479. repairFast = env('TRACKER_REPAIR_FAST') == '1'
  480. repairLogEvery = env('TRACKER_REPAIR_LOG_EVERY') != null ? toNumber(env('TRACKER_REPAIR_LOG_EVERY')) : 100
  481. repairQueue = null
  482. repairPos = 0
  483. repairDone = false
  484. repairAt = 0
  485. repairNextAt = 0
  486. repairTries = {}
  487. repairTotals = { titles = 0 complete = 0 failed = 0 adult = 0 newSeasons = 0 newEpisodes = 0 posters = 0 cast = 0 requests = 0 tvmazeRequests = 0 retries = 0 }
  488. repairLine = () => {
  489. let b = repairTotals
  490. return b.titles + '/' + repairQueue.length + ' titles, complete=' + b.complete + ' failed=' + b.failed + ' adult=' + b.adult + ' newSeasons=' + b.newSeasons + ' newEpisodes=' + b.newEpisodes
  491. + ' posters=' + b.posters + ' cast=' + b.cast + ' requests=' + b.requests + ' tvmazeRequests=' + b.tvmazeRequests + ' retries=' + b.retries + ' seconds=' + ((now() - repairAt) / 1000)
  492. }
  493. repairTick = () => {
  494. if (repairDone) { return null }
  495. let t = now()
  496. if (repairQueue == null) {
  497. repairQueue = detailsRepairQueue()
  498. repairAt = t
  499. console.log('details repair: start, ' + repairQueue.length + ' incomplete titles (' + (now() - t) + ' ms to find them)')
  500. if (repairQueue.length == 0) { repairDone = true console.log('details repair: nothing to do') }
  501. return null
  502. }
  503. if (t < repairNextAt) { return null }
  504. let id = repairQueue[repairPos]
  505. let r = completeStep(id)
  506. let took = now() - t
  507. if (took > 1500) { console.log('details repair: slow step, show ' + id + ', ' + took + ' ms') }
  508. if (r.error != '') { console.log('details repair: ' + r.error) }
  509. repairNextAt = now() + (repairFast ? 20 : pauseMsAfter(r))
  510. // a series takes several steps: the same title again next time
  511. if (!r.done && !r.retry) { return null }
  512. repairPos = repairPos + 1
  513. if (r.retry && (repairTries[id] == null || repairTries[id] < 2)) {
  514. repairTries[id] = repairTries[id] == null ? 1 : repairTries[id] + 1
  515. let q = repairQueue
  516. q.push(id)
  517. repairQueue = q
  518. repairTotals.retries = repairTotals.retries + 1
  519. } else if (!r.skipped) {
  520. // done: its counts (a failed first step: the request alone)
  521. let sum = r.sum
  522. repairTotals.titles = repairTotals.titles + 1
  523. 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 }
  524. repairTotals.newSeasons = repairTotals.newSeasons + sum.newSeasons
  525. repairTotals.newEpisodes = repairTotals.newEpisodes + sum.newEpisodes
  526. repairTotals.posters = repairTotals.posters + sum.posters
  527. repairTotals.cast = repairTotals.cast + sum.cast
  528. repairTotals.requests = repairTotals.requests + (sum.steps == 0 ? r.requests : sum.requests)
  529. repairTotals.tvmazeRequests = repairTotals.tvmazeRequests + sum.tvmazeRequests
  530. }
  531. let finished = repairPos >= repairQueue.length
  532. if (finished || repairPos % 10 == 0) { persistDetails() }
  533. if (!finished && !r.skipped && !r.retry && repairTotals.titles > 0 && repairTotals.titles % repairLogEvery == 0) { console.log('details repair: ' + repairLine()) }
  534. if (finished) {
  535. repairDone = true
  536. console.log('details repair done: ' + repairLine())
  537. }
  538. return null
  539. }
  540. // ---- THE KIND BACKFILL (tracker.worldapi.org#21, mission 068, tmdbsync.hl kindTitle) ----------------------------------
  541. // Every TV title without a stored kind gets one: a title with a show genre (Reality / Talk / News) from the stored data (no
  542. // request), any other from TMDB's TV type (ONE request: GET /tv/<id>, then 260 ms pause). Starts once the adult backfill is
  543. // 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
  544. // /series to /shows at once (catalog.hl refreshCatalogShow). RESUMES after a restart (the queue = every TV title still without
  545. // a kind); a 404 stores the genres' answer + `kindCheck`; a passing failure goes to the back of the queue, at most 2 more tries
  546. // per start. Log: start, every TRACKER_KINDS_LOG_EVERY (500) titles, done. TRACKER_KINDS=0 switches it off; without
  547. // TMDB_READ_TOKEN it is off too (the lists still split by genre: shows.hl titleKind).
  548. kindsOn = env('TRACKER_KINDS') != '0' && syncEnabled
  549. kindsLogEvery = env('TRACKER_KINDS_LOG_EVERY') != null ? toNumber(env('TRACKER_KINDS_LOG_EVERY')) : 500
  550. kindQueue = null
  551. kindPos = 0
  552. kindDone = false
  553. kindAt = 0
  554. kindNextAt = 0
  555. kindTries = {}
  556. kindTotals = { titles = 0 series = 0 shows = 0 fromGenre = 0 moved = 0 requests = 0 errors = 0 retries = 0 }
  557. kindLine = () => {
  558. let k = kindTotals
  559. return k.titles + '/' + kindQueue.length + ' titles, series=' + k.series + ' shows=' + k.shows + ' fromGenre=' + k.fromGenre + ' moved=' + k.moved
  560. + ' requests=' + k.requests + ' errors=' + k.errors + ' retries=' + k.retries + ' seconds=' + ((now() - kindAt) / 1000)
  561. }
  562. kindTick = () => {
  563. if (kindDone) { return null }
  564. let t = now()
  565. if (kindQueue == null) {
  566. kindQueue = kindBackfillQueue()
  567. kindAt = t
  568. console.log('kind backfill: start, ' + kindQueue.length + ' TV titles without a kind (' + (now() - t) + ' ms to find them)')
  569. if (kindQueue.length == 0) { kindDone = true console.log('kind backfill: nothing to do') }
  570. return null
  571. }
  572. if (t < kindNextAt) { return null }
  573. let id = kindQueue[kindPos]
  574. kindPos = kindPos + 1
  575. let r = kindTitle(id)
  576. if (r.retry && (kindTries[id] == null || kindTries[id] < 2)) {
  577. kindTries[id] = kindTries[id] == null ? 1 : kindTries[id] + 1
  578. let q = kindQueue
  579. q.push(id)
  580. kindQueue = q
  581. kindTotals.retries = kindTotals.retries + 1
  582. } else {
  583. kindTotals.titles = kindTotals.titles + 1
  584. if (r.kind == 'show') { kindTotals.shows = kindTotals.shows + 1 } else if (r.kind == 'series') { kindTotals.series = kindTotals.series + 1 }
  585. if (r.fromGenre) { kindTotals.fromGenre = kindTotals.fromGenre + 1 }
  586. }
  587. kindTotals.requests = kindTotals.requests + r.requests
  588. kindTotals.errors = kindTotals.errors + r.errors
  589. if (r.error != '') { console.log('kind backfill: ' + r.error) }
  590. // until now the genres decided (no show genre = series): only a title TMDB's type makes a SHOW changes its list
  591. if (r.kind == 'show' && !r.fromGenre) {
  592. refreshCatalogShow(id)
  593. kindTotals.moved = kindTotals.moved + 1
  594. }
  595. let took = now() - t
  596. if (took > 1500) { console.log('kind backfill: slow step, show ' + id + ', ' + took + ' ms') }
  597. kindNextAt = now() + r.requests * msPerRequest
  598. let finished = kindPos >= kindQueue.length
  599. if (finished || kindPos % 25 == 0) { persistSync() }
  600. if (!finished && kindTotals.titles > 0 && kindTotals.titles % kindsLogEvery == 0 && !r.retry) { console.log('kind backfill: ' + kindLine()) }
  601. if (finished) {
  602. kindDone = true
  603. console.log('kind backfill done: ' + kindLine())
  604. }
  605. return null
  606. }
  607. // ---- THE CREDITS JOB (tracker.worldapi.org#28, details.hl creditsStep) ------------------------------------------------------
  608. // Every PUBLIC title (adult == false; adult/unknown are skipped) with a TMDB id gets its whole cast + crew once: at start (after
  609. // the adult backfill and the details repair are done) the job collects every such title without `creditsAt` and asks ONE per
  610. // step on the app's clock — one request (details + credits / aggregate_credits), then 260 ms (≤ 40 / 10 s); requests queued
  611. // meanwhile are served between two steps. Titles the details repair, the daily sync or an import already did carry `creditsAt`
  612. // and are not asked. RESUMES after a restart (the queue = what still has no credits); TMDB 404 / adult → `creditsCheck`, never
  613. // asked again; a passing failure goes to the back of the queue (at most 2 more tries per start). Waits while the daily sync
  614. // runs. Persisted (shows + people only) every 25 titles + at the end. Log: start, every TRACKER_CREDITS_LOG_EVERY (500) titles, failures, slow steps
  615. // (> 1.5 s), done. TRACKER_CREDITS=0 switches it off (off too without TMDB_READ_TOKEN). TRACKER_CREDITS_FAST=1 (the gate, fake
  616. // TMDB only): 20 ms pause instead.
  617. // MEMORY LIMIT: the runtime never frees what a fetch + JSON parse took (mission 061 measured ~6 MB more RSS per title on the real
  618. // 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
  619. // step the job reads its own RSS (/proc/self/status); above TRACKER_CREDITS_MAX_MB (16000) it PAUSES for this process (logged) and
  620. // goes on with what is left after the next restart (deploy, `docker restart`).
  621. creditsOn = env('TRACKER_CREDITS') != '0' && syncEnabled
  622. creditsFast = env('TRACKER_CREDITS_FAST') == '1'
  623. creditsLogEvery = env('TRACKER_CREDITS_LOG_EVERY') != null ? toNumber(env('TRACKER_CREDITS_LOG_EVERY')) : 500
  624. creditsQueueIds = null
  625. creditsPos = 0
  626. creditsDone = false
  627. creditsAt = 0
  628. creditsNextAt = 0
  629. creditsTries = {}
  630. creditsMaxMb = env('TRACKER_CREDITS_MAX_MB') != null ? toNumber(env('TRACKER_CREDITS_MAX_MB')) : 16000
  631. creditsTotals = { titles = 0 done = 0 failed = 0 cast = 0 crew = 0 people = 0 requests = 0 retries = 0 slowest = 0 }
  632. // this process' resident memory in MB (VmRSS), 0 when unknown
  633. rssMb = () => {
  634. if (!exists('/proc/self/status')) { return 0 }
  635. let t = readFile('/proc/self/status')
  636. let i = t != null ? t.indexOf('VmRSS:') : -1
  637. if (i < 0) { return 0 }
  638. let kb = toNumber(t.slice(i + 6, t.indexOf('kB', i)).trim())
  639. return kb != null ? (kb - kb % 1024) / 1024 : 0
  640. }
  641. creditsLine = () => {
  642. let b = creditsTotals
  643. return b.titles + '/' + creditsQueueIds.length + ' titles, done=' + b.done + ' failed=' + b.failed + ' cast=' + b.cast + ' crew=' + b.crew + ' people=' + b.people
  644. + ' requests=' + b.requests + ' retries=' + b.retries + ' slowestStepMs=' + b.slowest + ' seconds=' + ((now() - creditsAt) / 1000)
  645. }
  646. creditsTick = () => {
  647. if (creditsDone) { return null }
  648. let t = now()
  649. if (creditsQueueIds == null) {
  650. creditsQueueIds = creditsQueue()
  651. creditsAt = t
  652. console.log('credits job: start, ' + creditsQueueIds.length + ' titles without credits (' + (now() - t) + ' ms to find them)')
  653. if (creditsQueueIds.length == 0) { creditsDone = true console.log('credits job: nothing to do') }
  654. return null
  655. }
  656. if (t < creditsNextAt) { return null }
  657. let mb = rssMb()
  658. if (mb > creditsMaxMb) {
  659. creditsDone = true
  660. persistCredits()
  661. console.log('credits job: paused, RSS ' + mb + ' MB > TRACKER_CREDITS_MAX_MB ' + creditsMaxMb + ' — ' + (creditsQueueIds.length - creditsPos) + ' titles left for the next start; ' + creditsLine())
  662. return null
  663. }
  664. let id = creditsQueueIds[creditsPos]
  665. creditsPos = creditsPos + 1
  666. let r = creditsStep(id)
  667. let took = now() - t
  668. if (took > creditsTotals.slowest) { creditsTotals.slowest = took }
  669. if (took > 1500) { console.log('credits job: slow step, show ' + id + ', ' + took + ' ms, cast=' + r.cast + ' crew=' + r.crew + ' people=' + r.people) }
  670. if (r.error != '') { console.log('credits job: ' + r.error) }
  671. creditsNextAt = now() + (creditsFast ? 20 : r.requests * msPerRequest)
  672. if (r.retry && (creditsTries[id] == null || creditsTries[id] < 2)) {
  673. creditsTries[id] = creditsTries[id] == null ? 1 : creditsTries[id] + 1
  674. let q = creditsQueueIds
  675. q.push(id)
  676. creditsQueueIds = q
  677. creditsTotals.retries = creditsTotals.retries + 1
  678. } else if (!r.skipped) {
  679. creditsTotals.titles = creditsTotals.titles + 1
  680. if (r.error != '') { creditsTotals.failed = creditsTotals.failed + 1 } else { creditsTotals.done = creditsTotals.done + 1 }
  681. creditsTotals.cast = creditsTotals.cast + r.cast
  682. creditsTotals.crew = creditsTotals.crew + r.crew
  683. creditsTotals.people = creditsTotals.people + r.people
  684. }
  685. creditsTotals.requests = creditsTotals.requests + r.requests
  686. let finished = creditsPos >= creditsQueueIds.length
  687. if (finished || creditsPos % 25 == 0) { persistCredits() }
  688. if (!finished && !r.skipped && !r.retry && creditsTotals.titles > 0 && creditsTotals.titles % creditsLogEvery == 0) { console.log('credits job: ' + creditsLine()) }
  689. if (finished) {
  690. creditsDone = true
  691. console.log('credits job done: ' + creditsLine())
  692. }
  693. return null
  694. }
  695. // 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
  696. // between, only while no daily run is going on; the details repair only when neither has work; then the kind backfill (#21);
  697. // the credits job (#28) last
  698. clockOn = syncOn || backfillOn || repairOn || kindsOn || creditsOn
  699. clockTicks = 0
  700. 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') + ')') }
  701. if (!backfillOn) { console.log('adult backfill: off (' + (syncEnabled ? 'TRACKER_BACKFILL=0' : 'no TMDB_READ_TOKEN') + ')') }
  702. if (!repairOn) { console.log('details repair: off (' + (syncEnabled ? 'TRACKER_REPAIR=0' : 'no TMDB_READ_TOKEN') + ')') }
  703. if (!creditsOn) { console.log('credits job: off (' + (syncEnabled ? 'TRACKER_CREDITS=0' : 'no TMDB_READ_TOKEN') + ')') }
  704. if (!kindsOn) { console.log('kind backfill: off (' + (syncEnabled ? 'TRACKER_KINDS=0' : 'no TMDB_READ_TOKEN') + ')') }
  705. if (clockOn) {
  706. syncClock = every(0.1)
  707. on syncClock.tick(x) {
  708. clockTicks = clockTicks + 1
  709. let busy = syncQueue.length > 0 || syncPlanning
  710. if (syncOn && clockTicks % 10 == 0) { syncTick() }
  711. let free = !busy && syncQueue.length == 0 && !syncPlanning
  712. if (backfillOn && free && !backfillDone) { backfillTick() }
  713. else if (repairOn && free && (!backfillOn || backfillDone) && !repairDone) { repairTick() }
  714. else if (kindsOn && free && (!backfillOn || backfillDone) && (!repairOn || repairDone) && !kindDone) { kindTick() }
  715. else if (creditsOn && free && (!backfillOn || backfillDone) && (!repairOn || repairDone) && (!kindsOn || kindDone)) { creditsTick() }
  716. return null
  717. }
  718. }
  719. // ---- THE SHORT-ID BACKFILL (mission 060, tracker.worldapi.org#27, shortids.hl shortIdStep) ----------------------------
  720. // 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,
  721. // as many records as fit into TRACKER_SHORTID_BUDGET_MS (default 40 ms) — no TMDB, only the tables — so a page waits at
  722. // most one batch. The queue is built at start (`ensureShortIds`) from what is still missing = it resumes after a restart.
  723. // Persisted every 20 batches and at the end. Log: start, every TRACKER_SHORTID_LOG_EVERY (5000) records, done; with nothing
  724. // to do one line. TRACKER_SHORTIDS=0 switches it off (the gate's resume check).
  725. shortIdOn = env('TRACKER_SHORTIDS') != '0'
  726. shortIdBudget = env('TRACKER_SHORTID_BUDGET_MS') != null ? toNumber(env('TRACKER_SHORTID_BUDGET_MS')) : 40
  727. shortIdLogEvery = env('TRACKER_SHORTID_LOG_EVERY') != null ? toNumber(env('TRACKER_SHORTID_LOG_EVERY')) : 5000
  728. shortIdRun = { at = 0 batches = 0 assigned = 0 nextLog = 0 slowest = 0 slowestPersist = 0 done = false }
  729. shortIdTick = () => {
  730. if (shortIdRun.done) { return null }
  731. let t = now()
  732. let r = shortIdStep(shortIdBudget)
  733. let took = now() - t
  734. shortIdRun.batches = shortIdRun.batches + 1
  735. shortIdRun.assigned = shortIdRun.assigned + r.assigned
  736. if (took > shortIdRun.slowest) { shortIdRun.slowest = took }
  737. if (r.done || shortIdRun.batches % 20 == 0) {
  738. let tp = now()
  739. persistShortIds()
  740. if (now() - tp > shortIdRun.slowestPersist) { shortIdRun.slowestPersist = now() - tp }
  741. }
  742. if (!r.done && shortIdRun.assigned >= shortIdRun.nextLog) {
  743. console.log('short ids: ' + shortIdRun.assigned + ' assigned, ' + r.left + ' left, ' + ((now() - shortIdRun.at) / 1000) + ' s')
  744. shortIdRun.nextLog = shortIdRun.nextLog + shortIdLogEvery
  745. }
  746. if (r.done) {
  747. shortIdRun.done = true
  748. let s = shortIdStats()
  749. 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))
  750. }
  751. return null
  752. }
  753. if (!shortIdOn) { console.log('short ids: backfill off (TRACKER_SHORTIDS=0), ' + shortIdsLeft() + ' records without one') }
  754. else if (shortIdsLeft() == 0) { console.log('short ids: nothing to do') }
  755. else {
  756. shortIdRun.at = now()
  757. shortIdRun.nextLog = shortIdLogEvery
  758. console.log('short ids: backfill start, ' + shortIdsLeft() + ' records, ' + shortIdBudget + ' ms per batch')
  759. shortIdClock = every(0.1)
  760. on shortIdClock.tick(x) {
  761. shortIdTick()
  762. return null
  763. }
  764. }
  765. // ---- THE COLLECTION SEED (mission 066, tracker.worldapi.org#19, franchises.hl seedStep) ------------------------------------
  766. // TMDB's movie collections become timelines: ONE movie per step (its details; once per collection the collection's parts), on
  767. // 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
  768. // sync or the adult backfill runs (they share TMDB's limit and the backfill brings the adult flags it skips by); since the merge
  769. // (mission 070) also until the details repair, the kind backfill and the credits job are done (or paused) — the LAST job. The queue =
  770. // every non-adult movie without a check row, so it RESUMES after a restart and does nothing once all are checked. Persisted
  771. // every TRACKER_COLLECTIONS_PERSIST_EVERY (25) steps and at the end. Log: start, every TRACKER_COLLECTIONS_LOG_EVERY (500) movies, done.
  772. // TRACKER_COLLECTIONS=0 switches it off; without TMDB_READ_TOKEN it is off too.
  773. collectionsOn = env('TRACKER_COLLECTIONS') != '0' && syncEnabled
  774. collectionsLogEvery = env('TRACKER_COLLECTIONS_LOG_EVERY') != null ? toNumber(env('TRACKER_COLLECTIONS_LOG_EVERY')) : 500
  775. collectionsPersistEvery = env('TRACKER_COLLECTIONS_PERSIST_EVERY') != null ? toNumber(env('TRACKER_COLLECTIONS_PERSIST_EVERY')) : 25
  776. collectionRun = { at = 0 steps = 0 nextAt = 0 done = false started = false slowest = 0 }
  777. collectionTick = () => {
  778. if (collectionRun.done) { return null }
  779. // mission 070 (merge): also behind the details repair, the kind backfill and the credits job — one TMDB pacing at a time
  780. if (syncQueue.length > 0 || syncPlanning || (backfillOn && !backfillDone) || (repairOn && !repairDone) || (kindsOn && !kindDone) || (creditsOn && !creditsDone)) { return null }
  781. let t = now()
  782. if (!collectionRun.started) {
  783. collectionRun.started = true
  784. collectionRun.at = t
  785. let n = seedPrepare()
  786. console.log('collections: start, ' + n + ' movies to check (' + (now() - t) + ' ms to find them)')
  787. if (n == 0) { collectionRun.done = true console.log('collections: nothing to do') }
  788. return null
  789. }
  790. if (t < collectionRun.nextAt) { return null }
  791. let r = seedStep()
  792. if (r.done) {
  793. collectionRun.done = true
  794. seedPersist()
  795. console.log('collections done: ' + seedLine() + ' seconds=' + ((now() - collectionRun.at) / 1000) + ' slowestStepMs=' + collectionRun.slowest)
  796. return null
  797. }
  798. collectionRun.steps = collectionRun.steps + 1
  799. let took = now() - t
  800. if (took > collectionRun.slowest) { collectionRun.slowest = took }
  801. if (r.error != '') { console.log('collections: ' + r.error) }
  802. if (took > 1500) { console.log('collections: slow step, ' + took + ' ms') }
  803. collectionRun.nextAt = now() + r.requests * msPerRequest
  804. if (collectionRun.steps % collectionsPersistEvery == 0) { seedPersist() }
  805. if (collectionRun.steps % collectionsLogEvery == 0) { console.log('collections: ' + seedLine() + ' seconds=' + ((now() - collectionRun.at) / 1000)) }
  806. return null
  807. }
  808. if (!collectionsOn) { console.log('collections: off (' + (syncEnabled ? 'TRACKER_COLLECTIONS=0' : 'no TMDB_READ_TOKEN') + ')') }
  809. else {
  810. collectionClock = every(0.1)
  811. on collectionClock.tick(x) {
  812. collectionTick()
  813. return null
  814. }
  815. }
  816. on Error(e) { console.log('error absorbed: ' + e.message) }

Branches

Latest commits

  • 2667da05tracker#30 (mission 025): /my/ pages from slim cached title cards, episode rows and watch sets (after the jobs /my/series 1.8 s -> 0.06 s, /my/unwatched 4.1 -> 0.18 s); timeline page shows its name once; franchise widget under the poster/title; movies with TV leftovers (First Contact) go through the details repair; tools/count-tmdb-ids.hl; gates 327/0, 52/0, 32/0mre
  • 3909810dantcolony#40: mission references in README/STATUS/docs point to the moved missionsmre
  • e63b1d28antcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • 1cda451dtracker: Hybriel master 190aa11d (#127 both shapes, GC correctness fc838894) — conductor adopts despite /my/series 2.4x after jobs (memory 8.0 → 1.7 GB boot); see reports/071mre
  • c1fa2f2etracker (mission 071): Hybriel master 190aa11d measured on the real copy vs the live binary 8590df63 — NOT adopted (after the first-start jobs /my/series 2.4x slower, /series 1.6x, RSS swings 7.4-12.2 GB; fresh it is flat at 1.7-2.2 GB and /my/unwatched faster), vendor stays 8efba065, candidate kept in .scratch/w071/vendor-190aa11d; tests/kinds.mjs: collection seed off (its TMDB request broke check 1 in 1 of 4 runs); tests/realdata-071.sh + realdata-071-bench.mjs + tools/realdata-071-table.py; README + STATUS (numbers, how to repeat); gates 325/0, 32/0, 50/0mre
  • 8081350atracker docs (mission 070): README (summary, Config HL_GC_BYTES — kept at Hybriel's default, the 256 MiB setting is taken out of docker-compose.yml again: the jobs grew to 12+ GB with it too, see STATUS), Test (three gates), Deploy (first start ~50 min: kinds then seed, restart once after collections done, memory numbers), Vendored Hybriel 8efba065 + #48 audit, Files; STATUS mission 070 entry (merges, migrated counts, lambda audit, gates, RSS old vs new, how to repeat, open points); docs/kinds.md + docs/franchises.md job order; tests/realdata-070-*.sh, tools/count-migrated.hl, tools/ref-params.py, tools/lambda-audit.pymre
  • 1ad19c8ctracker: re-vendor Hybriel master 8efba065 (#126 GC by bytes, #48 lambda parameters copy) (mission 070): bin/hybriel sha256 50361e95…, plugins core crypto data fetch fs http http1 mpackdb proc smtp time web; lambda audit: 13 lambdas change a passed record/list (11 through a local alias), no caller relies on it — unchanged; 319 read-only lambda parameters get & (no copy per call: /my/schedule 2.35 → 0.46 s, /my/unwatched 13.7 → 5.7 s on the real copy); /my/unwatched one merge sort instead of n² inserts; docker-compose HL_GC_BYTES=268435456; deploy.sh runs kinds.mjs + franchises.mjs too (default ports 8700–8710); tests/realdata-070.mjs; gates browser 325/0, kinds 32/0, franchises 50/0mre
  • 46b21389tracker (mission 070, conductor): the sync never destroys migrated data — the one-time summary step MOVES a copied summary to migratedSummary (marker summaries-moved.txt) instead of clearing it; a migrated record's first title/genres/homepage/tagline TMDB replaces → migratedTitle/migratedGenres/migratedHomepage/migratedTagline, a migrated season's/episode's title/summary → migratedTitle/migratedSummary (set once); tests/peek-shows.hl prints them; gate 325/0mre
  • 749019b0Merge t19 (tracker#19 franchises + timelines) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/browser.mjs/faketmdb.mjs, both sides kept; franchise/timeline pages get #20's typed heading (Franchise | …, Timeline | …), their title links via titlePath (/movies|/series|/shows); the collection seed waits for repair, kinds and credits too; franchises.mjs URLs + 2 new checks; gates browser 323/0, kinds 32/0, franchises 50/0mre
  • daf49feaMerge t20 (tracker#20 typed headings + #21 series/shows split) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/search.hl/components/search.hl/browser.mjs/faketmdb.mjs, both sides kept; clock order backfill → repair → kinds → credits; withDetailsFields stores tmdbType + kind; gates: browser.mjs URLs → /series|/movies, typed h1 selectors; kinds.mjs repair/credits off, fixture name = seed name; browser 323/0, kinds 32/0mre
  • 20e09d89Merge t18 (tracker#18 delta sync) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/browser.mjs, both sides kept; pageShowOf summary = summaryOfmre
  • f83571c3tracker#18 (mission 067): daily sync by change lists — TMDB /tv|movie/changes (since the stored day, paged) + TVmaze /updates/shows → only our changed titles (followed: full step, unfollowed: light step — changed seasons, no TVmaze), full walk on first run / gap > 14 days / failed list; show record refreshed (title, tmdbSummary, tagline, status, genres …; renamed titles re-indexed); summary = the creator's own text (page: summary > tmdbSummary > tvmazeSummary), one-time clear of copied summaries (9,647 on the live copy); gate 261, tests/realdata-018*.mjs, README + STATUSmre
  • 1ed5457etracker#20 + #21 (mission 068): typed headings "<Type> | <name>" in type colours; TV titles split into Series (/series) and Shows (/shows) by TMDB type + Reality/Talk/News genres — kind stored by sync/import/adult backfill + new kind backfill (resumes), /movies/<slug>, /shows/<slug> of a series/movie → 301, /my/series + /my/shows, home 5 tiles + 3 rows, search/filmography labels; gates kinds 32 + browser 266, tests/realdata-068.mjs, tools/count-kinds.hl, docs/kinds.md, README + STATUSmre
  • f2b00674Merge t26 (tracker#26 + #28) into main (mission 062): short ids for every new person (castPersonId, guest route), guest stars stored on the title and created as people only when opened (/person/tmdb/<id>?show=<id> → 302), lean watch/follow clicks (showRow a small object, cast/crew from the slug, watches cached per user, face rows only after a season toggle); gate 311, tests/realdata-062.mjs, README + STATUSmre
  • 0553b51ftracker#19 (mission 066): franchises and timelines — tables, /franchises, /franchises/<slug>, /timelines/<slug> (Timeline | Release sort, series by last episode), the Prequel | Timeline | Sequel widget with the franchise above, the creator's editor, TMDB collection seed in the app (resumes, paced); gate tests/franchises.mjs 48/0 + browser.mjs 266/0, tests/realdata-066.mjs, docs/franchises.md, README + STATUSmre
  • fa1f9dfatracker#29 (mission 063): unwatched check muted grey outline + check (accent only on hover), watched stays solid — no code regression, the accent outline read as ticked; gate checks real checks visibly (computed style + screenshot pixel) on /my/unwatched, show, movie, /my/movies; gate 266, tests/realdata-063.mjs, README + STATUSmre
  • 10bb3f93tracker#28 (mission 061): full cast (all seasons, main cast by episodes, guest stars) + crew (created by, directed by, written by, screenplay, story, music) — stored by the details completion, the daily sync, the search import (one details request) and a background credits job (resumes, RSS limit); show page collapsed after 20 with client-side Show all; showBySlug via a slug map; gate 249, tests/realdata-028.mjs, README + STATUSmre
  • d8b12d67tracker#27 (mission 060): short ids for movies, series and persons — old 702 kept (data/old-short-ids.json), new random [a-z0-9]{5} unique across both, claimed at creation, background backfill (resumes), shown under poster/photo, /<shortId> → 301; gate 259, tests/realdata-060*, README + STATUSmre
  • 25a50bc4tracker#26 (mission 059): titles from a filmography are completed — on open (skeleton, step-wise face showComplete, no reload) and by the in-app details repair (resumes, TMDB-paced, series in parts); cast from TMDB credits; gate 231, tests/realdata-026.mjs, README + STATUSmre
  • f14db671tracker#22-#25 (mission 058): episode air dates, season check = all episodes watched, movie watched check (+ /my/movies count), /genres/<genre> pages (movies + series, newest first, paginated); gate 238, tests/realdata-058.mjs, README + STATUSmre