tracker
All repositories: gitoria
9.9 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 packed lookup `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 PackedOwners from './shortid-owners.hl'import { now } from 'hl:time'import { warm } from './warm.hl'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'import { warmBlocked, startingUpText } from './warm.hl'import { movedResponse, notFoundText } from './util.hl'static shortIdChars = 'abcdefghijklmnopqrstuvwxyz0123456789'// HM60: the hash slots and prefixed owner text live in Bytes (shortid-owners.hl).// A lookup decodes just its owner: 's<id>' for a show or 'p<id>' for a person.static owners = new PackedOwners()static ownerValue = (&kind, &id) => { return (kind == 'person' ? 'p' : 's') + id }static ownerKind = (&v) => { return v.slice(0, 1) == 'p' ? 'person' : 'show' }static ownerId = (&v) => { return v.slice(1) }// 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) {hex = randomBytes(16, 'hex')let out = ''let i = 0while (i < hex.length && out.length < 5) {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.fetch(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.fetch(sid) == null) { state.oldKept = state.oldKept + 1 } else { sid = randomShortId() }owners.put(sid, ownerValue(&kind, &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.fetch(r.shortId)return o != null && o == ownerValue(&kind, &r.id)}// one record into `owners`; a record without a (valid, own) short id into the queuestatic noteShortIdRow = (kind, &r) => {state.scanned = state.scanned + 1if (isShortId(&r.shortId) && owners.fetch(r.shortId) == null) {owners.put(r.shortId, ownerValue(&kind, &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 ' + ownerKind(owners.fetch(r.shortId)) + ' ' + ownerId(owners.fetch(r.shortId)) : 'not a short id') + ' — gets a new one')}queue.push({ kind = kind id = r.id })}return true}// one table's rows into `owners` (streamed, mission 043)static scanTable = (kind, &table) => {for (r of table.iterate(null, null)) { noteShortIdRow(kind, &r) }return true}// the old tracker's ids (data/old-short-ids.json) into oldShortIds + reservedstatic loadOldShortIds = () => {f = oldFile()if (exists(f)) {m = JSON.parse(readFile(f))let n = 0for (k of m.keys()) {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)') }return true}// the scan is done (bootscan.hl streams the tables itself): the log linestatic finishShortIds = (&t0) => {state.built = truestate.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}// at start (bootscan.hl does it inside its passes; this is the lazy fallback): the old ids, the map of every short id in use, the// queue of records without onestatic ensureShortIds = () => {if (state.built) { return true }// mission T17: the progressive start is filling `owners` (bootscan.hl); nothing hands out an id before it is done (warm.hl warmBlocked)if (warm.running) { return false }state.built = truet0 = now()loadOldShortIds()scanTable('show', &showsTable)scanTable('person', &personsTable)finishShortIds(&t0)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) {item = queue[state.queuePos]state.queuePos = state.queuePos + 1table = tableOf(&item.kind)r = table.fetch(item.id)if (r != null && !ownsShortId(&item.kind, &r)) {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.fetch(sid)if (o == null) { return null }// tracker#31: a merged tombstone's short id leads to its keeperoKind = ownerKind(&o)oId = ownerId(&o)r = oKind == 'person' ? personsTable.fetch(oId) : liveShowOf(showsTable.fetch(oId))if (r == null || r.urlSegment == null) { return null }// a title's own page (/movies/, /series/, /shows/<slug>, tracker.worldapi.org#21)return oKind == 'person' ? '/person/' + r.urlSegment : titlePath(&r)}static shortIdRoute = (&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 movedResponse(&path)}
Branches
Latest commits
- 6fe1896cHM50: re-vendor Hybriel set day50 (source 0ae38232, bin d3ef9d16)mre
- 2f391aa9Log: HM50 startedmre
- 4b59c03dHM50 mission: doc pathmre
- ed526d67HM50 missionmre
- 2f986ca3Log: RT50 passmre
- 1c4715a4RT50 mission: day50 repro retestmre
- 57d1c0dcLog: day50 retest requestmre
- 60b1f419Log: Anton #336 result, wake checkmre
- 919a18aalog: scratchmre
- 6b504440status tidymre
- 9332bd10log: DP70 livemre
- be11daa0DP70 brief fixmre
- 886a7028DP70 brief, HM67 mergedmre
- b41cdd6dMerge hm67-searchids: packed search IDsmre
- 385904eaReport HM67 matched heap measurements and gate proofmre
- e5c9b659Pack retained search IDs into UTF-8 bytesmre
- 62a5f6c7HM67 brief, HM66 mergedmre
- b32b8440Merge hm66-catalogindex: packed catalog indexmre
- 2db0f7adReport HM66 heap measurements and validationmre
- 6ce15623Pack catalog lists and membership maps in UTF-8 bytesmre