tracker
All repositories: gitoria
8.4 KB
// lib/shortids.hl — SHORT IDS (tracker.worldapi.org#27, mission 060): every movie, series and person has its own 5-character id// (`shortId`, like `a9s9a`), shown below its poster/photo; `/<shortId>` answers 301 to its page. Creator: "i wanted to give all// our movies, shows, series and persons own short ids like a9s9a … those ids show below the poster."//// OLD IDS: the old tracker had them on 702 of 9,453 shows (Show.jsonl field `id`, base62 counter '100jh'…'1012y', all of// them [a-z0-9]{5}). `data/old-short-ids.json` (made once by tools/old-short-ids.hl) maps the old Mongo `_id` (= our// `oldId`, tools/migrate.hl) → that id; such a show gets it back. Persons never had one.// NEW IDS: 5 random characters [a-z0-9] (36^5 = 60 M) — never one that is taken or one of the old ids (all 702 are// reserved, even where the show is gone).// UNIQUE ACROSS SHOWS AND PERSONS: one in-memory map `owners` (short id → { kind, id }) over BOTH tables — an mpackdb index// is per table and cannot span two. Built at start by `ensureShortIds` (one scan of each table); every id handed// out goes through it. A record whose short id another record already owns (never seen; logged) gets a new one.// NEW RECORDS get one when they are created: `claimShortId(kind, id, oldId)` in search.hl importTitle and people.hl// addMinimalTitle (the only places the app creates shows) and people.hl castPersonId (mission 062: the only place// the app creates persons — the cast/crew of #26/#28: completion, credits job, daily sync + tools/sync-tmdb.hl,// search import; and a guest star opened for the first time, people.hl guestPersonId).// THE BACKFILL: the records without one (at first every row: 9,453 shows + 15,157 persons) are given theirs in the// background, a time-boxed batch per clock tick (jobs.hl `shortIdTick` → `shortIdStep`), so pages are served// between two batches; after a restart it goes on with what is still missing. Real data: STATUS.md mission 060.//// ONE PROCESS PER STORAGE (hybriel#21): the map lives in the app's process; the tables are shows.hl's.import { now } from 'hl:time'import { env } from 'hl:proc'import { readFile, exists } from 'hl:fs'import { randomBytes } from 'hl:crypto'import { hexDigits } from './util.hl'import { showsTable, personsTable, titlePath, liveShowOf } from './shows.hl'static shortIdChars = 'abcdefghijklmnopqrstuvwxyz0123456789'// short id → { kind ('show' | 'person'), id }static owners = {}// the old tracker's ids: oldId → short id, and every one of them → true (reserved)static oldShortIds = {}static reserved = {}// the records still without a short id, [{ kind, id }], worked off from `state.queuePos`. Filled in place (push) and never// reassigned (a static cannot be) — kept OUT of `state`: reading `state.queue[i]` copied the whole 25k list on every access// (measured: ~3 ms per record instead of ~0.2)static queue = []static state = { built = false queuePos = 0 oldLoaded = 0 scanned = 0 existing = 0 duplicates = 0 ms = 0 assigned = 0 oldKept = 0 }// the file of old ids: TRACKER_OLD_SHORT_IDS, else data/old-short-ids.json beside project.hl (relative paths resolve against the// ENTRY script: a tool in tools/ — sync-tmdb.hl creates people since #28, mission 062 — finds it one folder up)static oldFile = () => {f = env('TRACKER_OLD_SHORT_IDS')if (f != null && f.trim() != '') { return f.trim() }return !exists('./data/old-short-ids.json') && exists('../data/old-short-ids.json') ? '../data/old-short-ids.json' : './data/old-short-ids.json'}// is this a short id at all (5 characters, a–z, 0–9)?static isShortId = (&s) => {if (s == null || hlTypeName(s) != 'String' || s.length != 5) { return false }let i = 0while (i < 5) {if (!shortIdChars.includes(s[i])) { return false }i = i + 1}return true}// 5 random characters a–z0–9, not taken and not an old one. Bytes ≥ 252 are skipped (252 = 7 × 36), so every character// is equally likely.static randomShortId = () => {while (true) {let hex = randomBytes(16, 'hex')let out = ''let i = 0while (i < hex.length && out.length < 5) {let b = hexDigits.indexOf(hex[i]) * 16 + hexDigits.indexOf(hex[i + 1])if (b < 252) { out = out + shortIdChars[b % 36] }i = i + 2}if (out.length == 5 && owners[out] == null && reserved[out] != true) { return out }}}// the short id for a record that has none: its old one when the old tracker had one (and nobody holds it), else a new// one — taken in `owners` at oncestatic claimShortId = (kind, id, &oldId) => {ensureShortIds()let sid = oldId != null ? oldShortIds['' + oldId] : nullif (sid != null && owners[sid] == null) { state.oldKept = state.oldKept + 1 } else { sid = randomShortId() }owners[sid] = { kind = kind id = id }return sid}// tracker#31 (merge.hl picks the keeper of duplicates): is this record's short id the one the old tracker gave it?static hasOldShortId = (&r) => {ensureShortIds()return r.oldId != null && r.shortId != null && oldShortIds['' + r.oldId] == r.shortId}// does this record own its short id? (null / malformed / held by another record → no)static ownsShortId = (&kind, &r) => {if (!isShortId(r.shortId)) { return false }o = owners[r.shortId]return o != null && o.kind == kind && o.id == r.id}// one table's rows into `owners`; the rows without a (valid, own) short id into the queuestatic scanTable = (kind, &table) => {for (r of table.find(null, null)) {state.scanned = state.scanned + 1if (isShortId(r.shortId) && owners[r.shortId] == null) {owners[r.shortId] = { kind = kind id = r.id }state.existing = state.existing + 1} else {if (r.shortId != null) {state.duplicates = state.duplicates + 1console.log('short ids: ' + kind + ' ' + r.id + ' has "' + r.shortId + '", ' + (isShortId(r.shortId) ? 'taken by ' + owners[r.shortId].kind + ' ' + owners[r.shortId].id : 'not a short id') + ' — gets a new one')}queue.push({ kind = kind id = r.id })}}return true}// at start (project.hl): the old ids, the map of every short id in use, the queue of records without onestatic ensureShortIds = () => {if (state.built) { return true }state.built = truet0 = now()f = oldFile()if (exists(f)) {m = JSON.parse(readFile(f))let n = 0for (k of m.keys()) {let sid = m[k]if (isShortId(sid)) { oldShortIds[k] = sid reserved[sid] = true n = n + 1 }}state.oldLoaded = n} else { console.log('short ids: no old ids (' + f + ' missing)') }scanTable('show', showsTable)scanTable('person', personsTable)state.ms = now() - t0console.log('short ids: ' + state.scanned + ' records, ' + state.existing + ' with a short id, ' + queue.length + ' without, ' + state.oldLoaded + ' old ids, ' + state.ms + ' ms')return true}static tableOf = (&kind) => { return kind == 'person' ? personsTable : showsTable }// the backfill, one batch: records from the queue until `budgetMs` is used up → { done, assigned, left }static shortIdStep = (&budgetMs) => {ensureShortIds()t0 = now()let n = 0while (state.queuePos < queue.length && now() - t0 < budgetMs) {let item = queue[state.queuePos]state.queuePos = state.queuePos + 1let table = tableOf(item.kind)let r = table.fetch(item.id)if (r != null && !ownsShortId(item.kind, r)) {let x = rx.shortId = claimShortId(item.kind, x.id, x.oldId)if (table.update(x.id, x) == null) { console.log('short ids: ' + item.kind + ' ' + x.id + ' not stored: ' + table.lastError()) } else { n = n + 1 }}}state.assigned = state.assigned + ndone = state.queuePos >= queue.lengthreturn { done = done assigned = n left = queue.length - state.queuePos }}static shortIdStats = () => { return state }static persistShortIds = () => {showsTable.persist()personsTable.persist()return true}static shortIdsLeft = () => { return queue.length - state.queuePos }// `/<shortId>` (project.hl): the page's path, or nullstatic shortIdPath = (&sid) => {if (!isShortId(sid)) { return null }ensureShortIds()o = owners[sid]if (o == null) { return null }// tracker#31: a merged tombstone's short id leads to its keeperr = o.kind == 'person' ? personsTable.fetch(o.id) : liveShowOf(showsTable.fetch(o.id))if (r == null || r.urlSegment == null) { return null }// a title's own page (/movies/, /series/, /shows/<slug>, tracker.worldapi.org#21)return o.kind == 'person' ? '/person/' + r.urlSegment : titlePath(r)}
Branches
- mainmain branch
Latest commits
- a386dc92tracker: reports 029 + 030mre
- 71e0fd7dtracker missions 029 + 030: README (What it does, Files, gate count), STATUS (real-copy numbers, how to repeat, open points), LOGmre
- d36ea6eatracker#34 + #35 (mission 030): Follow directly under the poster, as wide as the poster (show.hl, styles.hl); the status pill next to a series' title — TVmaze's status (new tvmazeStatus, stored by the sync's TVmaze merge) else TMDB's, TVmaze Ended + TMDB Canceled = Canceled, inverted (filled, dark text, no border), green running / yellow pending / red canceled / muted ended (shows.hl statusOf); the daily delta asks TVmaze's status of an unfollowed series TVmaze's change list names (dailysync.hl syncRunStep, sync.hl syncTvmazeStatus); the status backfill after the details repair (backfill.hl, jobs.hl statusTick; resumable, 550 ms per TVmaze request); gates 354/0, 32/0, 52/0mre
- 7d7d4487tracker#33 (mission 029): reduced titles — every title TMDB's details never went through this app (no detailsAt, no tmdbSync) is incomplete (shows.hl isIncomplete; the old tracker's migrated rows passed #26's test: 5,697 non-adult on the live copy, 691 series without seasons); the repair job does the visibly reduced first (shows.hl missingParts), the page completes one on open; a title TMDB has no poster for (The Remaining) shows the placeholder; tools/count-incomplete.hl; gate fixtures stand for synced titles (tmdbSync), tests/seed-reduced.hl + #33 checks; gates 347/0, 32/0, 52/0mre
- 661c2592tracker: report 028mre
- 27c916fatracker mission 028: README ("Code order", the new file map), STATUS (counts before/after, tests, how to repeat, open), LOGmre
- d924f398tracker mission 028: comments name the new files (sync.hl, dailysync.hl, backfill.hl, credits.hl, jobs.hl, images.hl …); tools/ref-params.py + tools/lambda-audit.py also scan lib/ (they globbed the root only), lambda-audit counts a plain `x = p` alias like `let x = p`mre
- 2e89b968tracker mission 028 (code order) 5/5 let: `let` only where a variable is reassigned — 667 never-reassigned lets became plain declarations (project.hl, lib/, components/, tools/, tests/); kept: 264 in loop bodies (a plain declaration there is 'Cannot reassign' on the 2nd pass), 234 reassigned, 27 whose name is also a member/outer/free name (a plain write would rebind it); tools/let-audit.py decides and fixes (README 'Code order'); tests/realdata-m028.{sh,mjs} = the page-output diff on a real copy; gates 342/0, 32/0, 52/0, real-copy pages identicalmre
- 54796ff2tracker mission 028 (code order) 4/5 thin faces + last copies: the show page's check/follow faces call lib/watches.hl toggleWatched / toggleSeasonWatched (seasonAllWatched moved there) and lib/follows.hl toggleFollowed; both logins (header selector face, /login/callback) share lib/users.hl userOfCode; todayStr/listOf copies in components and the export readers copied into tools/migrate.hl + tools/old-short-ids.hl now once (lib/util.hl, lib/export.hl); gates 342/0, 32/0, 52/0; old-short-ids output byte-identical, migrate output identicalmre
- 06b078e3tracker mission 028 (code order) 3/5 project.hl is the map: config, routes, wiring and a feature → file index (914 → 258 lines); the background jobs (daily sync run, backfills, details repair, credits job, merge, short ids, collection seed) moved unchanged into lib/jobs.hl (a class: their state is reassigned every step, a static cannot be; one instance made after the server), the login callback into lib/users.hl, poster/photo serving into lib/images.hl, the /shows/<slug> rule into lib/shows.hl showsMovedPath; route handlers are thin wrappers; gates 342/0, 32/0, 52/0, real-copy pages identicalmre
- 94716fd2tracker mission 028 (code order) 2/5 util + topics: lib/util.hl holds envOr, storageDir, postersDir, profilesDir, newId, hexDigits, todayStr, dateOr, textOr, hasId, listOr, firstOf, sortDesc once (were copied into up to 5 files); tmdbsync.hl split into tmdb.hl (TMDB/TVmaze requests), sync.hl (one title's sync), sync-helpers.hl, backfill.hl; details.hl split into details.hl, credits.hl, credits-helpers.hl (isIncomplete to shows.hl); search-helpers.hl (words, query, ranking, slugs); collections.hl (the TMDB collection seed, out of franchises.hl); deltasync.hl renamed dailysync.hl; no behaviour change: gates 342/0, 32/0, 52/0, real-copy pages identicalmre
- 186079b0tracker mission 028 (code order) 1/5 move: every root .hl except project.hl into lib/ (styles.hl into components/), import paths only; gates 342/0, 32/0, 52/0; real-copy pages identicalmre
- 4f47f181tracker: report 027mre
- dc1d4be4tracker mission 027: Hybriel master 06617221 vendored (plugin allocator fixes 3a781359 + 413f60e4); real copy RSS through first-start jobs + 400 loads flat ~2.55 GB (190aa11d 2.3 -> 5.6 GB), page times <= 1.1x; gates 342/0, 32/0, 52/0mre
- 84e1b3e1tracker: reports 025 + 026mre
- 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