tracker
All repositories: gitoria
20.6 KB
// project.hl — tracker.worldapi.org: THE MAP (mission 028, docs: README "Files"). Config, the routes and how the parts are wired;// what each feature does is in the file named here, not in this one.//// login (ident only, the header's selector + button) lib/users.hl, components/main.hl, login.js, /login/* below// the shell: header, main menu, user menu, sidebar components/main.hl (theme/shell/*, vendored from layouts.worldapi.org)// /genres · /people (the main menu) · /settings lib/catalog.hl genreList · lib/people.hl peoplePage · components/settings.hl// titles: records, slugs, kinds, list caches lib/shows.hl a title's page: components/show.hl// public lists /movies /series /shows /genres, home lib/catalog.hl// components/{movies,allseries,allshows,genre,home,tilelist}.hl// follows · watches · /my/* lib/follows.hl · lib/watches.hl// components/{myshows,mymovies,unwatched,schedule}.hl// search, web search, import lib/search.hl (+ search-helpers.hl) components/search.hl// people, a person's page and filmography fill lib/people.hl components/person.hl// cast + crew, the credits job lib/credits.hl (+ credits-helpers.hl)// a title completed from TMDB (details repair) lib/details.hl// TMDB / TVmaze requests, posters lib/tmdb.hl// the sync of one title · which titles a day lib/sync.hl (+ sync-helpers.hl) · lib/dailysync.hl// adult flag + kind backfills lib/backfill.hl// short ids (/<shortId>) lib/shortids.hl// the boot scans: ONE streamed pass per table lib/bootscan.hl// franchises + timelines · TMDB collection seed lib/franchises.hl · lib/collections.hl// the curated franchises (data/franchises.json, #40) lib/franchiseseed.hl// components/franchise*.hl, timelineedit.hl// duplicate titles merged lib/merge.hl// the background jobs and their clocks lib/jobs.hl (one instance, made below after the server)// poster + photo files lib/images.hl// shared helpers (env, paths, dates, ids, lists) lib/util.hl// styles · design tokens · the WorldAPI theme components/styles.hl · shared/tokens.hl · theme/ (never edited here)//// Config (env; no committed secret — the first deploy registers this app in ident and sets these, done by the architect, as// with ident's own .env for SMTP): TRACKER_PORT (45008), TRACKER_URL (this app's own public address, for the return URL),// IDENT_URL (https://ident.worldapi.org), TRACKER_KEY (pk_…), TRACKER_SECRET (sk_…), TRACKER_STORAGE, TRACKER_SESSIONS,// TRACKER_WATCH, TMDB_READ_TOKEN; the jobs' switches and limits: lib/jobs.hl (README "Config").import WebFramework from 'hl:web'import { Response } from 'hl:http1'import { env, exit } from 'hl:proc'import { now, every } from 'hl:time'import Styles from './components/styles.hl'import Home from './components/home.hl'import LoginFailed from './components/loginfailed.hl'import Show from './components/show.hl'import Unwatched from './components/unwatched.hl'import Schedule from './components/schedule.hl'import MyShows from './components/myshows.hl'import MyMovies from './components/mymovies.hl'import Movies from './components/movies.hl'import AllShows from './components/allshows.hl'import AllSeries from './components/allseries.hl'import Search from './components/search.hl'import Person from './components/person.hl'import Genre from './components/genre.hl'import Genres from './components/genres.hl'import People from './components/people.hl'import Settings from './components/settings.hl'import Franchises from './components/franchises.hl'import Franchise from './components/franchise.hl'import FranchiseEdit from './components/franchiseedit.hl'import TimelineEdit from './components/timelineedit.hl'import { dark, darker } from './shared/tokens.hl'import { postersDir, profilesDir, movedResponse } from './lib/util.hl'import { loginCallbackOf } from './lib/users.hl'import { imageResponse, isSafePosterName } from './lib/images.hl'import { bootStep, bootBegin } from './lib/bootscan.hl'import { warmBlocked } from './lib/warm.hl'import { showsMovedPath, warmTitleCaches, warmEpisodeKeys, movedSlugCount, personById } from './lib/shows.hl'import { allWatchedEpisodeIds } from './lib/watches.hl'import { allFollowedShowIds } from './lib/follows.hl'import { shortIdPath } from './lib/shortids.hl'import { guestPersonId } from './lib/people.hl'import { moveCopiedSummaries } from './lib/dailysync.hl'import { ensureFranchises } from './lib/franchises.hl'import Jobs from './lib/jobs.hl'static appTitle = "tracker"// ---- THE INSTALLABLE APP (tracker.worldapi.org#10), the same way calendar.worldapi.org does it: hl:web's own web app// manifest (/__hl/manifest.webmanifest, linked from every head with the apple-touch-icon and theme-color) and service// worker (/__hl/sw.js) from these settings — no JavaScript of ours. Icons in icons/ (icon.svg is the source, the PNGs// are rendered from it with rsvg-convert, README "Icons"). The theme colour is the header's background (darker), the// splash background the page's (dark) — both off the tokens, not written out again.appThemeColor = darker.valueappBackgroundColor = dark.valueappIcons = [{ src = '/icons/icon-192.png' sizes = '192x192' purpose = 'any' }{ src = '/icons/icon-512.png' sizes = '512x512' purpose = 'any' }{ src = '/icons/icon-192.png' sizes = '192x192' purpose = 'maskable' }{ src = '/icons/icon-512.png' sizes = '512x512' purpose = 'maskable' }]appTouchIcon = '/icons/apple-touch-icon.png'appFavicon = '/icons/favicon.svg'// OFFLINE: only the shell — the header and `/` (components/main.hl says "You are offline" while the browser has no// network). The data pages are not kept: without a network they get hl:web's "Unavailable offline" page.offline = [ Home ]styles = Stylesport = env('TRACKER_PORT') != null ? toNumber(env('TRACKER_PORT')) : 45008watching = env('TRACKER_WATCH') != '0'// read by hl:web's own manifest config (WebFramework.hl `cfg.sessionDir`), not the constructor call belowsessionDir = env('TRACKER_SESSIONS') != null ? env('TRACKER_SESSIONS') : null// ---- the function routes: each checks its input, asks the topic, answers ---------------------------------------------------// /login/callback?ident_code=… (lib/users.hl): the code exchanged, this app's session signed in, back to the page (`?next=`)loginCallback = (&route, &req) => { return loginCallbackOf(&server.sessions, &req, server.isHttps(req.headers, req.secure)) }// /posters/<name>, /profiles/<name> (lib/images.hl): the file, else the placeholderposterRoute = (&route, &req) => { return imageResponse(&postersDir, route.params != null ? route.params.name : null, 'poster') }profileRoute = (&route, &req) => { return imageResponse(&profilesDir, route.params != null ? route.params.name : null, 'photo') }// the old addresses of the personal lists (tracker.worldapi.org#8): they all live under /my/ now — a permanent redirect so old// links keep working (architect's decision)movedTo = (&path) => { return movedResponse(&path) }// 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 yetstartingUpText = () => { 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' } }) }notFoundText = (&text) => { return new Response(text, { status = 404 headers = { 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' } }) }unwatchedMoved = (&route, &req) => { return movedTo('/my/unwatched') }scheduleMoved = (&route, &req) => { return movedTo('/my/schedule') }// mission 058: the show page's genre pills linked `/genre/<x>` (no page there) — the genre pages are `/genres/<x>`genreMoved = (&route, &req) => {g = route.params != null ? route.params.genre : nullreturn movedTo(isSafePosterName(&g) ? '/genres/' + g : '/')}// mission 060 (tracker.worldapi.org#27): `/<shortId>` → 301 to the title's or person's page (lib/shortids.hl); upper case is// read as lower case; anything else is a 404shortIdRoute = (&route, &req) => {sid = route.params != null ? route.params.sid : nullpath = sid != null && hlTypeName(sid) == 'String' ? shortIdPath(sid.toLowerCase()) : nullif (path == null) { return warmBlocked() ? startingUpText() : notFoundText('not found') }return movedTo(&path)}// mission 062: a GUEST STAR's link (components/show.hl castRowsOf) — `/person/tmdb/<tmdbId>?show=<show id>` creates the person// (lib/people.hl guestPersonId) or finds the one we have, then 302 → `/person/<slug>`. A function route: the browser loads it// itself (hl:web's client router hands every non-component link to the browser)guestRoute = (&route, &req) => {t = route.params != null ? route.params.tmdb : nullif (warmBlocked()) { return startingUpText() }tmdbId = t != null && hlTypeName(t) == 'String' && t.length <= 10 ? toNumber(t) : nullif (tmdbId == null || tmdbId < 1) { return notFoundText('not found') }q = req.query != null ? req.query : {}r = guestPersonId(tmdbId, q.show)p = r.id != null ? personById(&r.id) : nullif (p == null || p.urlSegment == null) { return notFoundText('not found: ' + (r.error != null ? r.error : 'no such person')) }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' } })}// tracker#32 (mission 031): the header's search field sends GET /find?q=<text> (the theme's AppHeader form); a page cannot read a// query string, so this answers 302 → /search/<text> ('/', '?', '#' as spaces, like components/search.hl), no text → /searchfindRoute = (&route, &req) => {q = req.query != null && req.query.q != null && hlTypeName(req.query.q) == 'String' ? req.query.q.replaceAll('/', ' ').replaceAll('?', ' ').replaceAll('#', ' ').trim() : ''to = q != '' ? '/search/' + encodeURIComponent(q) : '/search'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' } })}// /shows/<slug> (tracker.worldapi.org#21, mission 068): a series or movie (or a merged duplicate's slug) answers 301 to its page// (lib/shows.hl showsMovedPath). hl:web has no 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 "Not found") it renders the title page the way hl:web renders a component// route (WebFramework.hl `on http.request`, the `component` branch): the Show component matched at /series/<slug> — same// component, same params — with the cookie's session, a transient one (no file, no cookie) when the browser brought none. In the browser// a link to /shows/<slug> is then a full page load; every other title page stays a client-side navigation.showsRoute = (&route, &req) => {slug = route.params != null ? route.params.slug : nullto = showsMovedPath(&slug)if (to != null) { return movedTo(&to) }m = server.router.match('/series/' + slug)// RV28: like hl:web's own component branch (W124): a browser with no cookie renders with a transient session — no id, no file,// no cookie (mint() wrote a session file for every bot that asked for an unknown slug: tracker#50)let s = req.sessionif (s == null) { s = server.sessions.fresh() }return server.page(m, s, server.hostOf(req.headers['host']), server.requestHeaders(req.headers))}routes = [{ pattern = "/favicon.ico" file = "./icons/favicon.ico" headers = { 'Cache-Control' = 'no-cache' } }// the installable app (tracker.worldapi.org#10): the icons (manifest and service worker are hl:web's own, from appIcons / offline){ pattern = "/icons/icon-192.png" file = "./icons/icon-192.png" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/icons/icon-512.png" file = "./icons/icon-512.png" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/icons/apple-touch-icon.png" file = "./icons/apple-touch-icon.png" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/icons/favicon.svg" file = "./icons/favicon.svg" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/login/callback" function = loginCallback }{ pattern = "/login/failed" component = LoginFailed }{ pattern = "/login.js" file = "./login.js" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/posters/:name" function = posterRoute }// tracker.worldapi.org#13: every movie / every series, 24 per page — the page is a PATH segment (`/movies/page/2`), a// page component cannot read `?page=` (hybriel#11) — and the movies the user follows{ pattern = "/movies" component = Movies }{ pattern = "/movies/page/:page" component = Movies }// tracker.worldapi.org#21 (mission 068): series and shows split — /series lists the series, /shows the shows; a title's page// is /movies/<slug>, /series/<slug> or /shows/<slug> (one component; /shows/<slug> is showsRoute above){ pattern = "/movies/:slug" component = Show }{ pattern = "/series" component = AllSeries }{ pattern = "/series/page/:page" component = AllSeries }{ pattern = "/series/:slug" component = Show }{ pattern = "/shows" component = AllShows }{ pattern = "/shows/page/:page" component = AllShows }{ pattern = "/shows/:slug" function = showsRoute }{ pattern = "/my/movies" component = MyMovies }{ pattern = "/my/unwatched" component = Unwatched }{ pattern = "/my/schedule" component = Schedule }// #21: /my/series and /my/shows (one component, components/myshows.hl; any other word there is its "Not found"){ pattern = "/my/:tv" component = MyShows }{ pattern = "/unwatched" function = unwatchedMoved }{ pattern = "/schedule" function = scheduleMoved }// tracker.worldapi.org#14: the search — `/search/<text>` (hl:web gives a page no query string, so not `?q=`){ pattern = "/search/:q?" component = Search }{ pattern = "/find" function = findRoute }// tracker.worldapi.org#16: a person's page (the show page's cast and the search link here) and their photo{ pattern = "/person/tmdb/:tmdb" function = guestRoute }{ pattern = "/person/:slug" component = Person }{ pattern = "/profiles/:name" function = profileRoute }// mission 058 (tracker.worldapi.org#25): a genre's movies and series, like /movies (the page in the path){ pattern = "/genres/:genre" component = Genre }{ pattern = "/genres/:genre/page/:page" component = Genre }{ pattern = "/genre/:genre" function = genreMoved }// tracker#32 (mission 031): the main menu's Genres and People, the user menu's Settings{ pattern = "/genres" component = Genres }// tracker#37 (mission 032): /people = everyone, the one updated last first, 24 per page (the page in the path, like /movies){ pattern = "/people" component = People }{ pattern = "/people/page/:page" component = People }{ pattern = "/settings" component = Settings }// tracker.worldapi.org#19 (mission 066): franchises and timelines, the creator's editor (`/franchises/edit` before the slug){ pattern = "/franchises" component = Franchises }{ pattern = "/franchises/page/:page" component = Franchises }{ pattern = "/franchises/edit" component = FranchiseEdit }{ pattern = "/franchises/:slug" component = Franchise }{ pattern = "/timelines/:tslug" component = Franchise }{ pattern = "/timelines/:slug/edit" component = TimelineEdit }{ pattern = "/" component = Home }// mission 060 (tracker.worldapi.org#27): a short id → its page (LAST: every named one-segment route above wins){ pattern = "/:sid" function = shortIdRoute }]// WHO GETS THE PUSH: the login state reaches the tabs of one session (components/main.hl trackerSignedIn/Out).tagOf = (&session) => { return session != null && session.data != null ? session.data.tag : null }audience = {trackerSignedIn = (tag, &session) => { return tag != null && tagOf(&session) == tag }trackerSignedOut = (tag, &session) => { return tag != null && tagOf(&session) == tag }}// cookies are per host, not per port: an own name keeps this app's session apart from// ident's own (and from any other worldapi app sharing a dev host), see ident README "Design// tokens" / hybriel#10 hybriel#17.sessionCookie = 'trackersid'// tracker#30 (mission 025): the slim list caches (lib/shows.hl cardOf / episodeRowsOf) of every followed title, before the first// /my/ load — not filled by that loadtitleCachesStart = now()titleCachesWarm = warmTitleCaches(allFollowedShowIds())episodeKeysWarm = warmEpisodeKeys(allWatchedEpisodeIds())console.log('list caches: ' + titleCachesWarm + ' followed titles, ' + episodeKeysWarm + ' watched episodes in ' + (now() - titleCachesStart) + ' ms')// tracker#18, ONCE (lib/dailysync.hl moveCopiedSummaries): a `summary` that is only the migrated copy of tmdbSummary is MOVED to// `migratedSummary` (mission 070: kept, not shown) — the current TMDB text shows; the creator's own texts staysummariesMoved = moveCopiedSummaries()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') }// mission 066: which timelines every title is in (one scan of the timelines), before the first show pagefranchisesReady = ensureFranchises()// mission 043 (tracker#45): ONE streamed pass per table builds the public lists, the slug maps, the search index, the short ids, the// cast photos and /people's order (lib/bootscan.hl). Mission T17 (boot time): the pass is resumable — it runs here for up to// TRACKER_WARM_SYNC_MS (default 1000; the gates give 600000 = a complete start, as before) and, if the tables are bigger, goes// 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"// (components/warm*.hl); the jobs start when the scan is done (lib/jobs.hl needs the complete short-id map and indexes).warmSyncMs = env('TRACKER_WARM_SYNC_MS') != null ? toNumber(env('TRACKER_WARM_SYNC_MS')) : 1000warmStepMs = env('TRACKER_WARM_STEP_MS') != null ? toNumber(env('TRACKER_WARM_STEP_MS')) : 60// (test knob: TRACKER_WARM_HOLD_MS = the clock leaves the scan alone for that long after the server listens; tests/warmstart.mjs)warmHoldMs = env('TRACKER_WARM_HOLD_MS') != null ? toNumber(env('TRACKER_WARM_HOLD_MS')) : 0bootDone = falseif (warmSyncMs > 0) { bootDone = bootStep(&warmSyncMs) } else { bootBegin() }if (bootDone) { console.log('moved slugs: ' + movedSlugCount() + ' (their pages show the keeper)') }// 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// writes every route into each page's HTML (its client route table) — one per moved slug listed 56 of them, adult titles' among// them, on every page (#41). /movies/:slug and /series/:slug (component routes, which cannot redirect) find the keeper by the slug// map (lib/shows.hl showBySlug) and render its page with its canonical address in the head (components/show.hl `__meta` og:url);// /shows/<slug> (showsRoute, a function route) answers 301. No request tap: the class tap of mission 037 crashed hybriel 06617221// after ~37 answers.server = new WebFramework(routes = routes, styles = styles, port = port, sessionCookie = sessionCookie, watchMode = watching, sessionMaxAge = 3122064000)// ---- THE BACKGROUND JOBS (lib/jobs.hl): the daily TMDB sync, the backfills, the details repair, the credits job, the duplicate// merge, the short-id backfill, the collection seed, the curated franchise seed — constructing it starts their clocks and logs which ones are offjobs = nullif (bootDone) { jobs = new Jobs() }else {console.log('boot scan: listening first, the scan goes on in steps of ' + warmStepMs + ' ms')warmListenAt = now()warmClock = every(0.004)on warmClock.tick(x) {if (bootDone || now() - warmListenAt < warmHoldMs) { return null }bootDone = bootStep(&warmStepMs)if (bootDone) {warmClock.stop()console.log('moved slugs: ' + movedSlugCount() + ' (their pages show the keeper)')jobs = new Jobs()}return null}}on Error(e) {if (e.phase == 'startup') { exit(1) }console.log('error absorbed: ' + e.message)}
Branches
Latest commits
- 89e91ef3log: RV39 livemre
- ee2b677alog: RV39 deployingmre
- c1c4178cMerge branch 'rv39'mre
- a016e9abReapply "Merge branch 'rv39'"mre
- f29e2502log: RV39 gate fixmre
- d9fce111browser gate #26: exact frame count incl. SL1 people step (hybriel#308)mre
- ad529ac1log: m572 verdictmre
- 1b37d404RV39 on hold: hybriel#308mre
- f9127c68Revert "Merge branch 'rv39'"mre
- cd39f3d3log: hybriel#308mre
- 51341d6elog: RV39 deploy startedmre
- c9e29e06Merge branch 'rv39'mre
- 0f8d1fdclog: RV39 report, browser 387/2mre
- 50249b0bRV39: reportmre
- 10ed9581compose: HL_GC_STATS=1mre
- 955da19bRV39: re-vendor Hybriel set day39 (source 51e921d7, bin 6b481aa7)mre
- 64b8d1dclog: RV39 startedmre
- 1f2df72amission RV39mre
- 6c1936f9log+status: GC planmre
- 2846a840log: m569 result, GC hypothesismre