gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitdc40d859dc40d859tracker#31 (mission 026): duplicate titles merged — the 68 type+tmdbId pairs held by 157 records were the old tracker's (all migrated); merge.hl repair job (own clock, before the TMDB jobs) keeps one keeper per title (follows/watches > old short id > oldest), moves follows, watches, seasons, cast, credits, timelines, tombstones the rest (mergedInto, never deleted), slugs + short ids 301 to the keeper; stray seasons merged into their listed twin (Reacher S3 watches) or linked when watched; search import re-checks before its put; deploy.sh waits up to 90 s for 200; real copy 68 -> 0 dup ids, az5b2 follows/watches equal; gates 342/0, 32/0, 52/0mredc40d859/project.hl

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

Branches

Latest commits

  • dc40d859tracker#31 (mission 026): duplicate titles merged — the 68 type+tmdbId pairs held by 157 records were the old tracker's (all migrated); merge.hl repair job (own clock, before the TMDB jobs) keeps one keeper per title (follows/watches > old short id > oldest), moves follows, watches, seasons, cast, credits, timelines, tombstones the rest (mergedInto, never deleted), slugs + short ids 301 to the keeper; stray seasons merged into their listed twin (Reacher S3 watches) or linked when watched; search import re-checks before its put; deploy.sh waits up to 90 s for 200; real copy 68 -> 0 dup ids, az5b2 follows/watches equal; gates 342/0, 32/0, 52/0mre
  • 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