gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit3c79b5763c79b576Pack short-ID ownership into byte buffersmre3c79b576/project.hl

20.6 KB

  1. // project.hl — tracker.worldapi.org: THE MAP (mission 028, docs: README "Files"). Config, the routes and how the parts are wired;
  2. // what each feature does is in the file named here, not in this one.
  3. //
  4. // login (ident only, the header's selector + button) lib/users.hl, components/main.hl, login.js, /login/* below
  5. // the shell: header, main menu, user menu, sidebar components/main.hl (theme/shell/*, vendored from layouts.worldapi.org)
  6. // /genres · /people (the main menu) · /settings lib/catalog.hl genreList · lib/people.hl peoplePage · components/settings.hl
  7. // titles: records, slugs, kinds, list caches lib/shows.hl a title's page: components/show.hl
  8. // public lists /movies /series /shows /genres, home lib/catalog.hl
  9. // components/{movies,allseries,allshows,genre,home,tilelist}.hl
  10. // follows · watches · /my/* lib/follows.hl · lib/watches.hl
  11. // components/{myshows,mymovies,unwatched,schedule}.hl
  12. // search, web search, import lib/search.hl (+ search-helpers.hl) components/search.hl
  13. // people, a person's page and filmography fill lib/people.hl components/person.hl
  14. // cast + crew, the credits job lib/credits.hl (+ credits-helpers.hl)
  15. // a title completed from TMDB (details repair) lib/details.hl
  16. // TMDB / TVmaze requests, posters lib/tmdb.hl
  17. // the sync of one title · which titles a day lib/sync.hl (+ sync-helpers.hl) · lib/dailysync.hl
  18. // adult flag + kind backfills lib/backfill.hl
  19. // short ids (/<shortId>) lib/shortids.hl
  20. // the boot scans: ONE streamed pass per table lib/bootscan.hl
  21. // franchises + timelines · TMDB collection seed lib/franchises.hl · lib/collections.hl
  22. // the curated franchises (data/franchises.json, #40) lib/franchiseseed.hl
  23. // components/franchise*.hl, timelineedit.hl
  24. // duplicate titles merged lib/merge.hl
  25. // the background jobs and their clocks lib/jobs.hl (one instance, made below after the server)
  26. // poster + photo files lib/images.hl
  27. // shared helpers (env, paths, dates, ids, lists) lib/util.hl
  28. // styles · design tokens · the WorldAPI theme components/styles.hl · shared/tokens.hl · theme/ (never edited here)
  29. //
  30. // Config (env; no committed secret — the first deploy registers this app in ident and sets these, done by the architect, as
  31. // with ident's own .env for SMTP): TRACKER_PORT (45008), TRACKER_URL (this app's own public address, for the return URL),
  32. // IDENT_URL (https://ident.worldapi.org), TRACKER_KEY (pk_…), TRACKER_SECRET (sk_…), TRACKER_STORAGE, TRACKER_SESSIONS,
  33. // TRACKER_WATCH, TMDB_READ_TOKEN; the jobs' switches and limits: lib/jobs.hl (README "Config").
  34. import WebFramework from 'hl:web'
  35. import { Response } from 'hl:http1'
  36. import { env, exit } from 'hl:proc'
  37. import { now, every } from 'hl:time'
  38. import Styles from './components/styles.hl'
  39. import Home from './components/home.hl'
  40. import LoginFailed from './components/loginfailed.hl'
  41. import Show from './components/show.hl'
  42. import Unwatched from './components/unwatched.hl'
  43. import Schedule from './components/schedule.hl'
  44. import MyShows from './components/myshows.hl'
  45. import MyMovies from './components/mymovies.hl'
  46. import Movies from './components/movies.hl'
  47. import AllShows from './components/allshows.hl'
  48. import AllSeries from './components/allseries.hl'
  49. import Search from './components/search.hl'
  50. import Person from './components/person.hl'
  51. import Genre from './components/genre.hl'
  52. import Genres from './components/genres.hl'
  53. import People from './components/people.hl'
  54. import Settings from './components/settings.hl'
  55. import Franchises from './components/franchises.hl'
  56. import Franchise from './components/franchise.hl'
  57. import FranchiseEdit from './components/franchiseedit.hl'
  58. import TimelineEdit from './components/timelineedit.hl'
  59. import { dark, darker } from './shared/tokens.hl'
  60. import { postersDir, profilesDir, movedResponse } from './lib/util.hl'
  61. import { loginCallbackOf } from './lib/users.hl'
  62. import { imageResponse, isSafePosterName } from './lib/images.hl'
  63. import { bootStep, bootBegin } from './lib/bootscan.hl'
  64. import { warmBlocked } from './lib/warm.hl'
  65. import { showsMovedPath, warmTitleCaches, warmEpisodeKeys, movedSlugCount, personById } from './lib/shows.hl'
  66. import { allWatchedEpisodeIds } from './lib/watches.hl'
  67. import { allFollowedShowIds } from './lib/follows.hl'
  68. import { shortIdPath } from './lib/shortids.hl'
  69. import { guestPersonId } from './lib/people.hl'
  70. import { moveCopiedSummaries } from './lib/dailysync.hl'
  71. import { ensureFranchises } from './lib/franchises.hl'
  72. import Jobs from './lib/jobs.hl'
  73. static appTitle = "tracker"
  74. // ---- THE INSTALLABLE APP (tracker.worldapi.org#10), the same way calendar.worldapi.org does it: hl:web's own web app
  75. // manifest (/__hl/manifest.webmanifest, linked from every head with the apple-touch-icon and theme-color) and service
  76. // worker (/__hl/sw.js) from these settings — no JavaScript of ours. Icons in icons/ (icon.svg is the source, the PNGs
  77. // are rendered from it with rsvg-convert, README "Icons"). The theme colour is the header's background (darker), the
  78. // splash background the page's (dark) — both off the tokens, not written out again.
  79. appThemeColor = darker.value
  80. appBackgroundColor = dark.value
  81. appIcons = [
  82. { src = '/icons/icon-192.png' sizes = '192x192' purpose = 'any' }
  83. { src = '/icons/icon-512.png' sizes = '512x512' purpose = 'any' }
  84. { src = '/icons/icon-192.png' sizes = '192x192' purpose = 'maskable' }
  85. { src = '/icons/icon-512.png' sizes = '512x512' purpose = 'maskable' }
  86. ]
  87. appTouchIcon = '/icons/apple-touch-icon.png'
  88. appFavicon = '/icons/favicon.svg'
  89. // OFFLINE: only the shell — the header and `/` (components/main.hl says "You are offline" while the browser has no
  90. // network). The data pages are not kept: without a network they get hl:web's "Unavailable offline" page.
  91. offline = [ Home ]
  92. styles = Styles
  93. port = env('TRACKER_PORT') != null ? toNumber(env('TRACKER_PORT')) : 45008
  94. watching = env('TRACKER_WATCH') != '0'
  95. // read by hl:web's own manifest config (WebFramework.hl `cfg.sessionDir`), not the constructor call below
  96. sessionDir = env('TRACKER_SESSIONS') != null ? env('TRACKER_SESSIONS') : null
  97. // ---- the function routes: each checks its input, asks the topic, answers ---------------------------------------------------
  98. // /login/callback?ident_code=… (lib/users.hl): the code exchanged, this app's session signed in, back to the page (`?next=`)
  99. loginCallback = (&route, &req) => { return loginCallbackOf(&server.sessions, &req, server.isHttps(req.headers, req.secure)) }
  100. // /posters/<name>, /profiles/<name> (lib/images.hl): the file, else the placeholder
  101. posterRoute = (&route, &req) => { return imageResponse(&postersDir, route.params != null ? route.params.name : null, 'poster') }
  102. profileRoute = (&route, &req) => { return imageResponse(&profilesDir, route.params != null ? route.params.name : null, 'photo') }
  103. // the old addresses of the personal lists (tracker.worldapi.org#8): they all live under /my/ now — a permanent redirect so old
  104. // links keep working (architect's decision)
  105. movedTo = (&path) => { return movedResponse(&path) }
  106. // mission T17: the start-up scan is still running (lib/warm.hl) — a short id / a guest star may be one it has not read yet
  107. startingUpText = () => { return new Response('tracker is starting up, try again in a minute', { status = 503 headers = { 'Retry-After' = '30' 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' } }) }
  108. notFoundText = (&text) => { return new Response(text, { status = 404 headers = { 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' } }) }
  109. unwatchedMoved = (&route, &req) => { return movedTo('/my/unwatched') }
  110. scheduleMoved = (&route, &req) => { return movedTo('/my/schedule') }
  111. // mission 058: the show page's genre pills linked `/genre/<x>` (no page there) — the genre pages are `/genres/<x>`
  112. genreMoved = (&route, &req) => {
  113. g = route.params != null ? route.params.genre : null
  114. return movedTo(isSafePosterName(&g) ? '/genres/' + g : '/')
  115. }
  116. // mission 060 (tracker.worldapi.org#27): `/<shortId>` → 301 to the title's or person's page (lib/shortids.hl); upper case is
  117. // read as lower case; anything else is a 404
  118. shortIdRoute = (&route, &req) => {
  119. sid = route.params != null ? route.params.sid : null
  120. path = sid != null && hlTypeName(sid) == 'String' ? shortIdPath(sid.toLowerCase()) : null
  121. if (path == null) { return warmBlocked() ? startingUpText() : notFoundText('not found') }
  122. return movedTo(&path)
  123. }
  124. // mission 062: a GUEST STAR's link (components/show.hl castRowsOf) — `/person/tmdb/<tmdbId>?show=<show id>` creates the person
  125. // (lib/people.hl guestPersonId) or finds the one we have, then 302 → `/person/<slug>`. A function route: the browser loads it
  126. // itself (hl:web's client router hands every non-component link to the browser)
  127. guestRoute = (&route, &req) => {
  128. t = route.params != null ? route.params.tmdb : null
  129. if (warmBlocked()) { return startingUpText() }
  130. tmdbId = t != null && hlTypeName(t) == 'String' && t.length <= 10 ? toNumber(t) : null
  131. if (tmdbId == null || tmdbId < 1) { return notFoundText('not found') }
  132. q = req.query != null ? req.query : {}
  133. r = guestPersonId(tmdbId, q.show)
  134. p = r.id != null ? personById(&r.id) : null
  135. if (p == null || p.urlSegment == null) { return notFoundText('not found: ' + (r.error != null ? r.error : 'no such person')) }
  136. 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' 'X-Content-Type-Options' = 'nosniff' } })
  137. }
  138. // tracker#32 (mission 031): the header's search field sends GET /find?q=<text> (the theme's AppHeader form); a page cannot read a
  139. // query string, so this answers 302 → /search/<text> ('/', '?', '#' as spaces, like components/search.hl), no text → /search
  140. findRoute = (&route, &req) => {
  141. q = req.query != null && req.query.q != null && hlTypeName(req.query.q) == 'String' ? req.query.q.replaceAll('/', ' ').replaceAll('?', ' ').replaceAll('#', ' ').trim() : ''
  142. to = q != '' ? '/search/' + encodeURIComponent(q) : '/search'
  143. return new Response('see ' + to, { status = 302 headers = { 'Location' = to 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' } })
  144. }
  145. // /shows/<slug> (tracker.worldapi.org#21, mission 068): a series or movie (or a merged duplicate's slug) answers 301 to its page
  146. // (lib/shows.hl showsMovedPath). hl:web has no way for a component route to answer a redirect, so this is a FUNCTION route, and
  147. // for a show (or an unknown slug: the page's own "Not found") it renders the title page the way hl:web renders a component
  148. // route (WebFramework.hl `on http.request`, the `component` branch): the Show component matched at /series/<slug> — same
  149. // component, same params — with the cookie's session, a transient one (no file, no cookie) when the browser brought none. In the browser
  150. // a link to /shows/<slug> is then a full page load; every other title page stays a client-side navigation.
  151. showsRoute = (&route, &req) => {
  152. slug = route.params != null ? route.params.slug : null
  153. to = showsMovedPath(&slug)
  154. if (to != null) { return movedTo(&to) }
  155. m = server.router.match('/series/' + slug)
  156. // RV28: like hl:web's own component branch (W124): a browser with no cookie renders with a transient session — no id, no file,
  157. // no cookie (mint() wrote a session file for every bot that asked for an unknown slug: tracker#50)
  158. let s = req.session
  159. if (s == null) { s = server.sessions.fresh() }
  160. return server.page(m, s, server.hostOf(req.headers['host']), server.requestHeaders(req.headers))
  161. }
  162. routes = [
  163. { pattern = "/favicon.ico" file = "./icons/favicon.ico" headers = { 'Cache-Control' = 'no-cache' } }
  164. // the installable app (tracker.worldapi.org#10): the icons (manifest and service worker are hl:web's own, from appIcons / offline)
  165. { pattern = "/icons/icon-192.png" file = "./icons/icon-192.png" headers = { 'Cache-Control' = 'no-cache' } }
  166. { pattern = "/icons/icon-512.png" file = "./icons/icon-512.png" headers = { 'Cache-Control' = 'no-cache' } }
  167. { pattern = "/icons/apple-touch-icon.png" file = "./icons/apple-touch-icon.png" headers = { 'Cache-Control' = 'no-cache' } }
  168. { pattern = "/icons/favicon.svg" file = "./icons/favicon.svg" headers = { 'Cache-Control' = 'no-cache' } }
  169. { pattern = "/login/callback" function = loginCallback }
  170. { pattern = "/login/failed" component = LoginFailed }
  171. { pattern = "/login.js" file = "./login.js" headers = { 'Cache-Control' = 'no-cache' } }
  172. { pattern = "/posters/:name" function = posterRoute }
  173. // tracker.worldapi.org#13: every movie / every series, 24 per page — the page is a PATH segment (`/movies/page/2`), a
  174. // page component cannot read `?page=` (hybriel#11) — and the movies the user follows
  175. { pattern = "/movies" component = Movies }
  176. { pattern = "/movies/page/:page" component = Movies }
  177. // tracker.worldapi.org#21 (mission 068): series and shows split — /series lists the series, /shows the shows; a title's page
  178. // is /movies/<slug>, /series/<slug> or /shows/<slug> (one component; /shows/<slug> is showsRoute above)
  179. { pattern = "/movies/:slug" component = Show }
  180. { pattern = "/series" component = AllSeries }
  181. { pattern = "/series/page/:page" component = AllSeries }
  182. { pattern = "/series/:slug" component = Show }
  183. { pattern = "/shows" component = AllShows }
  184. { pattern = "/shows/page/:page" component = AllShows }
  185. { pattern = "/shows/:slug" function = showsRoute }
  186. { pattern = "/my/movies" component = MyMovies }
  187. { pattern = "/my/unwatched" component = Unwatched }
  188. { pattern = "/my/schedule" component = Schedule }
  189. // #21: /my/series and /my/shows (one component, components/myshows.hl; any other word there is its "Not found")
  190. { pattern = "/my/:tv" component = MyShows }
  191. { pattern = "/unwatched" function = unwatchedMoved }
  192. { pattern = "/schedule" function = scheduleMoved }
  193. // tracker.worldapi.org#14: the search — `/search/<text>` (hl:web gives a page no query string, so not `?q=`)
  194. { pattern = "/search/:q?" component = Search }
  195. { pattern = "/find" function = findRoute }
  196. // tracker.worldapi.org#16: a person's page (the show page's cast and the search link here) and their photo
  197. { pattern = "/person/tmdb/:tmdb" function = guestRoute }
  198. { pattern = "/person/:slug" component = Person }
  199. { pattern = "/profiles/:name" function = profileRoute }
  200. // mission 058 (tracker.worldapi.org#25): a genre's movies and series, like /movies (the page in the path)
  201. { pattern = "/genres/:genre" component = Genre }
  202. { pattern = "/genres/:genre/page/:page" component = Genre }
  203. { pattern = "/genre/:genre" function = genreMoved }
  204. // tracker#32 (mission 031): the main menu's Genres and People, the user menu's Settings
  205. { pattern = "/genres" component = Genres }
  206. // tracker#37 (mission 032): /people = everyone, the one updated last first, 24 per page (the page in the path, like /movies)
  207. { pattern = "/people" component = People }
  208. { pattern = "/people/page/:page" component = People }
  209. { pattern = "/settings" component = Settings }
  210. // tracker.worldapi.org#19 (mission 066): franchises and timelines, the creator's editor (`/franchises/edit` before the slug)
  211. { pattern = "/franchises" component = Franchises }
  212. { pattern = "/franchises/page/:page" component = Franchises }
  213. { pattern = "/franchises/edit" component = FranchiseEdit }
  214. { pattern = "/franchises/:slug" component = Franchise }
  215. { pattern = "/timelines/:tslug" component = Franchise }
  216. { pattern = "/timelines/:slug/edit" component = TimelineEdit }
  217. { pattern = "/" component = Home }
  218. // mission 060 (tracker.worldapi.org#27): a short id → its page (LAST: every named one-segment route above wins)
  219. { pattern = "/:sid" function = shortIdRoute }
  220. ]
  221. // WHO GETS THE PUSH: the login state reaches the tabs of one session (components/main.hl trackerSignedIn/Out).
  222. tagOf = (&session) => { return session != null && session.data != null ? session.data.tag : null }
  223. audience = {
  224. trackerSignedIn = (tag, &session) => { return tag != null && tagOf(&session) == tag }
  225. trackerSignedOut = (tag, &session) => { return tag != null && tagOf(&session) == tag }
  226. }
  227. // cookies are per host, not per port: an own name keeps this app's session apart from
  228. // ident's own (and from any other worldapi app sharing a dev host), see ident README "Design
  229. // tokens" / hybriel#10 hybriel#17.
  230. sessionCookie = 'trackersid'
  231. // tracker#30 (mission 025): the slim list caches (lib/shows.hl cardOf / episodeRowsOf) of every followed title, before the first
  232. // /my/ load — not filled by that load
  233. titleCachesStart = now()
  234. titleCachesWarm = warmTitleCaches(allFollowedShowIds())
  235. episodeKeysWarm = warmEpisodeKeys(allWatchedEpisodeIds())
  236. console.log('list caches: ' + titleCachesWarm + ' followed titles, ' + episodeKeysWarm + ' watched episodes in ' + (now() - titleCachesStart) + ' ms')
  237. // tracker#18, ONCE (lib/dailysync.hl moveCopiedSummaries): a `summary` that is only the migrated copy of tmdbSummary is MOVED to
  238. // `migratedSummary` (mission 070: kept, not shown) — the current TMDB text shows; the creator's own texts stay
  239. summariesMoved = moveCopiedSummaries()
  240. 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') }
  241. // mission 066: which timelines every title is in (one scan of the timelines), before the first show page
  242. franchisesReady = ensureFranchises()
  243. // mission 043 (tracker#45): ONE streamed pass per table builds the public lists, the slug maps, the search index, the short ids, the
  244. // cast photos and /people's order (lib/bootscan.hl). Mission T17 (boot time): the pass is resumable — it runs here for up to
  245. // TRACKER_WARM_SYNC_MS (default 1000; the gates give 600000 = a complete start, as before) and, if the tables are bigger, goes
  246. // on from a clock AFTER the server listens (a 5 GB copy: 2.3 M rows, minutes of CPU). Pages that need more than is built say "starting up"
  247. // (components/warm*.hl); the jobs start when the scan is done (lib/jobs.hl needs the complete short-id map and indexes).
  248. warmSyncMs = env('TRACKER_WARM_SYNC_MS') != null ? toNumber(env('TRACKER_WARM_SYNC_MS')) : 1000
  249. warmStepMs = env('TRACKER_WARM_STEP_MS') != null ? toNumber(env('TRACKER_WARM_STEP_MS')) : 60
  250. // (test knob: TRACKER_WARM_HOLD_MS = the clock leaves the scan alone for that long after the server listens; tests/warmstart.mjs)
  251. warmHoldMs = env('TRACKER_WARM_HOLD_MS') != null ? toNumber(env('TRACKER_WARM_HOLD_MS')) : 0
  252. bootDone = false
  253. if (warmSyncMs > 0) { bootDone = bootStep(&warmSyncMs) } else { bootBegin() }
  254. if (bootDone) { console.log('moved slugs: ' + movedSlugCount() + ' (their pages show the keeper)') }
  255. // tracker#31 + #41 (missions 026, 037, 037b): the slug of a merged duplicate, or a keeper's former slug, has NO route of its own: hl:web
  256. // writes every route into each page's HTML (its client route table) — one per moved slug listed 56 of them, adult titles' among
  257. // them, on every page (#41). /movies/:slug and /series/:slug (component routes, which cannot redirect) find the keeper by the slug
  258. // map (lib/shows.hl showBySlug) and render its page with its canonical address in the head (components/show.hl `__meta` og:url);
  259. // /shows/<slug> (showsRoute, a function route) answers 301. No request tap: the class tap of mission 037 crashed hybriel 06617221
  260. // after ~37 answers.
  261. server = new WebFramework(routes = routes, styles = styles, port = port, sessionCookie = sessionCookie, watchMode = watching, sessionMaxAge = 3122064000)
  262. // ---- THE BACKGROUND JOBS (lib/jobs.hl): the daily TMDB sync, the backfills, the details repair, the credits job, the duplicate
  263. // merge, the short-id backfill, the collection seed, the curated franchise seed — constructing it starts their clocks and logs which ones are off
  264. jobs = null
  265. if (bootDone) { jobs = new Jobs() }
  266. else {
  267. console.log('boot scan: listening first, the scan goes on in steps of ' + warmStepMs + ' ms')
  268. warmListenAt = now()
  269. warmClock = every(0.004)
  270. on warmClock.tick(x) {
  271. if (bootDone || now() - warmListenAt < warmHoldMs) { return null }
  272. bootDone = bootStep(&warmStepMs)
  273. if (bootDone) {
  274. warmClock.stop()
  275. console.log('moved slugs: ' + movedSlugCount() + ' (their pages show the keeper)')
  276. jobs = new Jobs()
  277. }
  278. return null
  279. }
  280. }
  281. on Error(e) {
  282. if (e.phase == 'startup') { exit(1) }
  283. console.log('error absorbed: ' + e.message)
  284. }

Branches

Latest commits

  • 3c79b576Pack short-ID ownership into byte buffersmre
  • 2e7d6257log: HM1 startedmre
  • 2f790465mission HM1: heap object breakdownmre
  • a18957falog: evening re-measure after CBmre
  • aac9a98dlog: evening re-measure startmre
  • 45163bd4log: person/tmdb error hypothesismre
  • cb38de2blog: swap 503 causemre
  • fd10c3d5log: CB livemre
  • 7557c025log: CB deploy try 2mre
  • 06a7534aMerge branch 'cb'mre
  • 2f8030d6log: CB gates greenmre
  • 498bf644log: CB gates startmre
  • f59c2847gc1: bound the five request caches (shows.hl cacheLimit)mre
  • 6ea2c6d6log: morning re-measure 11-04mre
  • 446290f0log: GC1 livemre
  • 8e6aa91dlog: GC1 deploy retrymre
  • 87ad2dc1log: GC1 deployingmre
  • 53f10fb8Merge branch 'gc1-deploy'mre
  • 7fcbf1d2log: GC1 deploy GOmre
  • 1fb6664bcompose: TRACKER_QSTATS=1 (GC1 measurement)mre