gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitb638e99db638e99dMerge t38 (tracker#38 pagination, #35 Returning/Airing label) into main: LOG/STATUS keep both sides; pager gate follows #37's /people (everyone, last updated first: seed updatedAt); gates pager 229/0, browser 374/0mreb638e99d/lib/shortids.hl

8.4 KB

  1. // lib/shortids.hl — SHORT IDS (tracker.worldapi.org#27, mission 060): every movie, series and person has its own 5-character id
  2. // (`shortId`, like `a9s9a`), shown below its poster/photo; `/<shortId>` answers 301 to its page. Creator: "i wanted to give all
  3. // our movies, shows, series and persons own short ids like a9s9a … those ids show below the poster."
  4. //
  5. // OLD IDS: the old tracker had them on 702 of 9,453 shows (Show.jsonl field `id`, base62 counter '100jh'…'1012y', all of
  6. // them [a-z0-9]{5}). `data/old-short-ids.json` (made once by tools/old-short-ids.hl) maps the old Mongo `_id` (= our
  7. // `oldId`, tools/migrate.hl) → that id; such a show gets it back. Persons never had one.
  8. // 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
  9. // reserved, even where the show is gone).
  10. // UNIQUE ACROSS SHOWS AND PERSONS: one in-memory map `owners` (short id → { kind, id }) over BOTH tables — an mpackdb index
  11. // is per table and cannot span two. Built at start by `ensureShortIds` (one scan of each table); every id handed
  12. // out goes through it. A record whose short id another record already owns (never seen; logged) gets a new one.
  13. // NEW RECORDS get one when they are created: `claimShortId(kind, id, oldId)` in search.hl importTitle and people.hl
  14. // addMinimalTitle (the only places the app creates shows) and people.hl castPersonId (mission 062: the only place
  15. // the app creates persons — the cast/crew of #26/#28: completion, credits job, daily sync + tools/sync-tmdb.hl,
  16. // search import; and a guest star opened for the first time, people.hl guestPersonId).
  17. // THE BACKFILL: the records without one (at first every row: 9,453 shows + 15,157 persons) are given theirs in the
  18. // background, a time-boxed batch per clock tick (jobs.hl `shortIdTick` → `shortIdStep`), so pages are served
  19. // between two batches; after a restart it goes on with what is still missing. Real data: STATUS.md mission 060.
  20. //
  21. // ONE PROCESS PER STORAGE (hybriel#21): the map lives in the app's process; the tables are shows.hl's.
  22. import { now } from 'hl:time'
  23. import { env } from 'hl:proc'
  24. import { readFile, exists } from 'hl:fs'
  25. import { randomBytes } from 'hl:crypto'
  26. import { hexDigits } from './util.hl'
  27. import { showsTable, personsTable, titlePath, liveShowOf } from './shows.hl'
  28. static shortIdChars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  29. // short id → { kind ('show' | 'person'), id }
  30. static owners = {}
  31. // the old tracker's ids: oldId → short id, and every one of them → true (reserved)
  32. static oldShortIds = {}
  33. static reserved = {}
  34. // the records still without a short id, [{ kind, id }], worked off from `state.queuePos`. Filled in place (push) and never
  35. // reassigned (a static cannot be) — kept OUT of `state`: reading `state.queue[i]` copied the whole 25k list on every access
  36. // (measured: ~3 ms per record instead of ~0.2)
  37. static queue = []
  38. static state = { built = false queuePos = 0 oldLoaded = 0 scanned = 0 existing = 0 duplicates = 0 ms = 0 assigned = 0 oldKept = 0 }
  39. // the file of old ids: TRACKER_OLD_SHORT_IDS, else data/old-short-ids.json beside project.hl (relative paths resolve against the
  40. // ENTRY script: a tool in tools/ — sync-tmdb.hl creates people since #28, mission 062 — finds it one folder up)
  41. static oldFile = () => {
  42. f = env('TRACKER_OLD_SHORT_IDS')
  43. if (f != null && f.trim() != '') { return f.trim() }
  44. return !exists('./data/old-short-ids.json') && exists('../data/old-short-ids.json') ? '../data/old-short-ids.json' : './data/old-short-ids.json'
  45. }
  46. // is this a short id at all (5 characters, a–z, 0–9)?
  47. static isShortId = (&s) => {
  48. if (s == null || hlTypeName(s) != 'String' || s.length != 5) { return false }
  49. let i = 0
  50. while (i < 5) {
  51. if (!shortIdChars.includes(s[i])) { return false }
  52. i = i + 1
  53. }
  54. return true
  55. }
  56. // 5 random characters a–z0–9, not taken and not an old one. Bytes ≥ 252 are skipped (252 = 7 × 36), so every character
  57. // is equally likely.
  58. static randomShortId = () => {
  59. while (true) {
  60. let hex = randomBytes(16, 'hex')
  61. let out = ''
  62. let i = 0
  63. while (i < hex.length && out.length < 5) {
  64. let b = hexDigits.indexOf(hex[i]) * 16 + hexDigits.indexOf(hex[i + 1])
  65. if (b < 252) { out = out + shortIdChars[b % 36] }
  66. i = i + 2
  67. }
  68. if (out.length == 5 && owners[out] == null && reserved[out] != true) { return out }
  69. }
  70. }
  71. // 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
  72. // one — taken in `owners` at once
  73. static claimShortId = (kind, id, &oldId) => {
  74. ensureShortIds()
  75. let sid = oldId != null ? oldShortIds['' + oldId] : null
  76. if (sid != null && owners[sid] == null) { state.oldKept = state.oldKept + 1 } else { sid = randomShortId() }
  77. owners[sid] = { kind = kind id = id }
  78. return sid
  79. }
  80. // tracker#31 (merge.hl picks the keeper of duplicates): is this record's short id the one the old tracker gave it?
  81. static hasOldShortId = (&r) => {
  82. ensureShortIds()
  83. return r.oldId != null && r.shortId != null && oldShortIds['' + r.oldId] == r.shortId
  84. }
  85. // does this record own its short id? (null / malformed / held by another record → no)
  86. static ownsShortId = (&kind, &r) => {
  87. if (!isShortId(r.shortId)) { return false }
  88. o = owners[r.shortId]
  89. return o != null && o.kind == kind && o.id == r.id
  90. }
  91. // one table's rows into `owners`; the rows without a (valid, own) short id into the queue
  92. static scanTable = (kind, &table) => {
  93. for (r of table.find(null, null)) {
  94. state.scanned = state.scanned + 1
  95. if (isShortId(r.shortId) && owners[r.shortId] == null) {
  96. owners[r.shortId] = { kind = kind id = r.id }
  97. state.existing = state.existing + 1
  98. } else {
  99. if (r.shortId != null) {
  100. state.duplicates = state.duplicates + 1
  101. console.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')
  102. }
  103. queue.push({ kind = kind id = r.id })
  104. }
  105. }
  106. return true
  107. }
  108. // at start (project.hl): the old ids, the map of every short id in use, the queue of records without one
  109. static ensureShortIds = () => {
  110. if (state.built) { return true }
  111. state.built = true
  112. t0 = now()
  113. f = oldFile()
  114. if (exists(f)) {
  115. m = JSON.parse(readFile(f))
  116. let n = 0
  117. for (k of m.keys()) {
  118. let sid = m[k]
  119. if (isShortId(sid)) { oldShortIds[k] = sid reserved[sid] = true n = n + 1 }
  120. }
  121. state.oldLoaded = n
  122. } else { console.log('short ids: no old ids (' + f + ' missing)') }
  123. scanTable('show', showsTable)
  124. scanTable('person', personsTable)
  125. state.ms = now() - t0
  126. console.log('short ids: ' + state.scanned + ' records, ' + state.existing + ' with a short id, ' + queue.length + ' without, ' + state.oldLoaded + ' old ids, ' + state.ms + ' ms')
  127. return true
  128. }
  129. static tableOf = (&kind) => { return kind == 'person' ? personsTable : showsTable }
  130. // the backfill, one batch: records from the queue until `budgetMs` is used up → { done, assigned, left }
  131. static shortIdStep = (&budgetMs) => {
  132. ensureShortIds()
  133. t0 = now()
  134. let n = 0
  135. while (state.queuePos < queue.length && now() - t0 < budgetMs) {
  136. let item = queue[state.queuePos]
  137. state.queuePos = state.queuePos + 1
  138. let table = tableOf(item.kind)
  139. let r = table.fetch(item.id)
  140. if (r != null && !ownsShortId(item.kind, r)) {
  141. let x = r
  142. x.shortId = claimShortId(item.kind, x.id, x.oldId)
  143. if (table.update(x.id, x) == null) { console.log('short ids: ' + item.kind + ' ' + x.id + ' not stored: ' + table.lastError()) } else { n = n + 1 }
  144. }
  145. }
  146. state.assigned = state.assigned + n
  147. done = state.queuePos >= queue.length
  148. return { done = done assigned = n left = queue.length - state.queuePos }
  149. }
  150. static shortIdStats = () => { return state }
  151. static persistShortIds = () => {
  152. showsTable.persist()
  153. personsTable.persist()
  154. return true
  155. }
  156. static shortIdsLeft = () => { return queue.length - state.queuePos }
  157. // `/<shortId>` (project.hl): the page's path, or null
  158. static shortIdPath = (&sid) => {
  159. if (!isShortId(sid)) { return null }
  160. ensureShortIds()
  161. o = owners[sid]
  162. if (o == null) { return null }
  163. // tracker#31: a merged tombstone's short id leads to its keeper
  164. r = o.kind == 'person' ? personsTable.fetch(o.id) : liveShowOf(showsTable.fetch(o.id))
  165. if (r == null || r.urlSegment == null) { return null }
  166. // a title's own page (/movies/, /series/, /shows/<slug>, tracker.worldapi.org#21)
  167. return o.kind == 'person' ? '/person/' + r.urlSegment : titlePath(r)
  168. }

Branches

Latest commits

  • b638e99dMerge t38 (tracker#38 pagination, #35 Returning/Airing label) into main: LOG/STATUS keep both sides; pager gate follows #37's /people (everyone, last updated first: seed updatedAt); gates pager 229/0, browser 374/0mre
  • f8ffa4dbtracker: report 032 + The Remaining + #39mre
  • 7565a863tracker: LOG timemre
  • b10f00c8tracker#39: double episodes — migrated episodes whose TMDB id TMDB replaced are adopted by their number in the sync (old id -> migratedTmdbId); merge.hl step 3 merges each season's doubles at start (keeper: most watches > synced > first; watches moved/parked; tombstones into mergedEpisodes, nothing deleted); tools/count-duplicate-episodes.hl; gate fixture + paths-m039; live copy 850 -> 0 in 64 s; gates 373/0, 32/0, 52/0mre
  • 9448d643tracker#35 follow-up (mission 033): TVmaze 'Running' is labelled 'Returning', or 'Airing' while a non-special episode of the two newest seasons is released within today +-7 days (data unchanged); gate fixtures Running/Airing/Aired + a special; browser 366/0, kinds 32/0, franchises 52/0, pager 229/0, check-theme 0mre
  • 8751adb8tracker: report 032mre
  • 9bce1f65tracker mission 032: STATUS gate files + the hour-boundary flakemre
  • 718bfb89tracker#37 (mission 032): /people = everyone, last updated first (updatedAt stamped by the person fill; view built at boot, touched people first at once), photo + name tiles (person colour) with the /movies pagination, /people/<letter> removed; photo = our file, tmdbProfile, a cast/crew entry's profile (in-memory map at boot), else the new 'no photo' placeholder; new cast/crew/created_by people keep tmdbProfile; search people rows with the photo; /settings = the heading only; util.hl sortDesc starts from sorted runs (same result, 105k: 1.6 s -> 0.15 s); gates 369/0, 32/0, 52/0, check-theme 0; README/STATUS/LOGmre
  • 03ec792ftracker#38 (mission 033): pagination goes exactly to the clicked page — tilelist read the clicked button's text after pagination.hl's own handler had rebuilt the buttons (real clicks only); now li.current, else the button's own text; new gate tests/pager.mjs (5 lists x 11 pages, 390/1280, real + script clicks, Back/Forward) 229/0; browser 365/0, kinds 32/0, franchises 52/0, check-theme 0mre
  • 96ba683adeploy.sh: a gate without a 'passed,' line (check-theme) no longer ends the scriptmre
  • eb3b9205tracker: report 031mre
  • 9b5d2e89tracker mission 031: README (What it does, Test: four gates + the #32 checks, Files: theme/, new pages), STATUS (real copy, A/B load, how to repeat, open points), LOGmre
  • 39950e4ctracker#32 (mission 031): the WorldAPI theme (theme/ vendored verbatim from layouts.worldapi.org 85b5654; styles.hl inherits it: accent green-dark, type colours 1-6; own base/header rules, row lines, genre-pill and inverted-button frames removed, the season foldable keeps its line; check-theme 21 -> 0, 4th deploy gate; main actions class primary) and the #32 header (theme AppHeader/MainMenu/UserMenu/Sidebar/ContentFirst: desktop brand, search, Series|Shows|Movies|Genres|People, user icon with Unwatched..Settings, Logout; signed out the ident selector, phone the iD icon dropdown; phone menu in the sidebar overlay; marked entry by :has); /find -> /search/<q>, /genres, /people(/<letter>), /settings; main { ContentFirst { slot } } works around the hl:web one-line slot bug; gates 365/0, 32/0, 52/0, check-theme 0mre
  • 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