gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitb9c7c3c8b9c7c3c8Merge branch 'records-dp74' into mainTrackerb9c7c3c8/lib/shortids.hl

9.9 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 packed lookup `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 PackedOwners from './shortid-owners.hl'
  23. import { now } from 'hl:time'
  24. import { warm } from './warm.hl'
  25. import { env } from 'hl:proc'
  26. import { readFile, exists } from 'hl:fs'
  27. import { randomBytes } from 'hl:crypto'
  28. import { hexDigits } from './util.hl'
  29. import { showsTable, personsTable, titlePath, liveShowOf } from './shows.hl'
  30. import { warmBlocked, startingUpText } from './warm.hl'
  31. import { movedResponse, notFoundText } from './util.hl'
  32. static shortIdChars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  33. // HM60: the hash slots and prefixed owner text live in Bytes (shortid-owners.hl).
  34. // A lookup decodes just its owner: 's<id>' for a show or 'p<id>' for a person.
  35. static owners = new PackedOwners()
  36. static ownerValue = (&kind, &id) => { return (kind == 'person' ? 'p' : 's') + id }
  37. static ownerKind = (&v) => { return v.slice(0, 1) == 'p' ? 'person' : 'show' }
  38. static ownerId = (&v) => { return v.slice(1) }
  39. // the old tracker's ids: oldId → short id, and every one of them → true (reserved)
  40. static oldShortIds = {}
  41. static reserved = {}
  42. // the records still without a short id, [{ kind, id }], worked off from `state.queuePos`. Filled in place (push) and never
  43. // reassigned (a static cannot be) — kept OUT of `state`: reading `state.queue[i]` copied the whole 25k list on every access
  44. // (measured: ~3 ms per record instead of ~0.2)
  45. static queue = []
  46. static state = { built = false queuePos = 0 oldLoaded = 0 scanned = 0 existing = 0 duplicates = 0 ms = 0 assigned = 0 oldKept = 0 }
  47. // the file of old ids: TRACKER_OLD_SHORT_IDS, else data/old-short-ids.json beside project.hl (relative paths resolve against the
  48. // ENTRY script: a tool in tools/ — sync-tmdb.hl creates people since #28, mission 062 — finds it one folder up)
  49. static oldFile = () => {
  50. f = env('TRACKER_OLD_SHORT_IDS')
  51. if (f != null && f.trim() != '') { return f.trim() }
  52. return !exists('./data/old-short-ids.json') && exists('../data/old-short-ids.json') ? '../data/old-short-ids.json' : './data/old-short-ids.json'
  53. }
  54. // is this a short id at all (5 characters, a–z, 0–9)?
  55. static isShortId = (&s) => {
  56. if (s == null || hlTypeName(s) != 'String' || s.length != 5) { return false }
  57. let i = 0
  58. while (i < 5) {
  59. if (!shortIdChars.includes(s[i])) { return false }
  60. i = i + 1
  61. }
  62. return true
  63. }
  64. // 5 random characters a–z0–9, not taken and not an old one. Bytes ≥ 252 are skipped (252 = 7 × 36), so every character
  65. // is equally likely.
  66. static randomShortId = () => {
  67. while (true) {
  68. hex = randomBytes(16, 'hex')
  69. let out = ''
  70. let i = 0
  71. while (i < hex.length && out.length < 5) {
  72. b = hexDigits.indexOf(hex[i]) * 16 + hexDigits.indexOf(hex[i + 1])
  73. if (b < 252) { out = out + shortIdChars[b % 36] }
  74. i = i + 2
  75. }
  76. if (out.length == 5 && owners.fetch(out) == null && reserved[out] != true) { return out }
  77. }
  78. }
  79. // 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
  80. // one — taken in `owners` at once
  81. static claimShortId = (kind, id, &oldId) => {
  82. ensureShortIds()
  83. let sid = oldId != null ? oldShortIds['' + oldId] : null
  84. if (sid != null && owners.fetch(sid) == null) { state.oldKept = state.oldKept + 1 } else { sid = randomShortId() }
  85. owners.put(sid, ownerValue(&kind, &id))
  86. return sid
  87. }
  88. // tracker#31 (merge.hl picks the keeper of duplicates): is this record's short id the one the old tracker gave it?
  89. static hasOldShortId = (&r) => {
  90. ensureShortIds()
  91. return r.oldId != null && r.shortId != null && oldShortIds['' + r.oldId] == r.shortId
  92. }
  93. // does this record own its short id? (null / malformed / held by another record → no)
  94. static ownsShortId = (&kind, &r) => {
  95. if (!isShortId(&r.shortId)) { return false }
  96. o = owners.fetch(r.shortId)
  97. return o != null && o == ownerValue(&kind, &r.id)
  98. }
  99. // one record into `owners`; a record without a (valid, own) short id into the queue
  100. static noteShortIdRow = (kind, &r) => {
  101. state.scanned = state.scanned + 1
  102. if (isShortId(&r.shortId) && owners.fetch(r.shortId) == null) {
  103. owners.put(r.shortId, ownerValue(&kind, &r.id))
  104. state.existing = state.existing + 1
  105. } else {
  106. if (r.shortId != null) {
  107. state.duplicates = state.duplicates + 1
  108. console.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')
  109. }
  110. queue.push({ kind = kind id = r.id })
  111. }
  112. return true
  113. }
  114. // one table's rows into `owners` (streamed, mission 043)
  115. static scanTable = (kind, &table) => {
  116. for (r of table.iterate(null, null)) { noteShortIdRow(kind, &r) }
  117. return true
  118. }
  119. // the old tracker's ids (data/old-short-ids.json) into oldShortIds + reserved
  120. static loadOldShortIds = () => {
  121. f = oldFile()
  122. if (exists(f)) {
  123. m = JSON.parse(readFile(f))
  124. let n = 0
  125. for (k of m.keys()) {
  126. sid = m[k]
  127. if (isShortId(&sid)) { oldShortIds[k] = sid reserved[sid] = true n = n + 1 }
  128. }
  129. state.oldLoaded = n
  130. } else { console.log('short ids: no old ids (' + f + ' missing)') }
  131. return true
  132. }
  133. // the scan is done (bootscan.hl streams the tables itself): the log line
  134. static finishShortIds = (&t0) => {
  135. state.built = true
  136. state.ms = now() - t0
  137. console.log('short ids: ' + state.scanned + ' records, ' + state.existing + ' with a short id, ' + queue.length + ' without, ' + state.oldLoaded + ' old ids, ' + state.ms + ' ms')
  138. return true
  139. }
  140. // 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
  141. // queue of records without one
  142. static ensureShortIds = () => {
  143. if (state.built) { return true }
  144. // mission T17: the progressive start is filling `owners` (bootscan.hl); nothing hands out an id before it is done (warm.hl warmBlocked)
  145. if (warm.running) { return false }
  146. state.built = true
  147. t0 = now()
  148. loadOldShortIds()
  149. scanTable('show', &showsTable)
  150. scanTable('person', &personsTable)
  151. finishShortIds(&t0)
  152. return true
  153. }
  154. static tableOf = (&kind) => { return kind == 'person' ? personsTable : showsTable }
  155. // the backfill, one batch: records from the queue until `budgetMs` is used up → { done, assigned, left }
  156. static shortIdStep = (&budgetMs) => {
  157. ensureShortIds()
  158. t0 = now()
  159. let n = 0
  160. while (state.queuePos < queue.length && now() - t0 < budgetMs) {
  161. item = queue[state.queuePos]
  162. state.queuePos = state.queuePos + 1
  163. table = tableOf(&item.kind)
  164. r = table.fetch(item.id)
  165. if (r != null && !ownsShortId(&item.kind, &r)) {
  166. x = r
  167. x.shortId = claimShortId(item.kind, x.id, &x.oldId)
  168. if (table.update(x.id, x) == null) { console.log('short ids: ' + item.kind + ' ' + x.id + ' not stored: ' + table.lastError()) } else { n = n + 1 }
  169. }
  170. }
  171. state.assigned = state.assigned + n
  172. done = state.queuePos >= queue.length
  173. return { done = done assigned = n left = queue.length - state.queuePos }
  174. }
  175. static shortIdStats = () => { return state }
  176. static persistShortIds = () => {
  177. showsTable.persist()
  178. personsTable.persist()
  179. return true
  180. }
  181. static shortIdsLeft = () => { return queue.length - state.queuePos }
  182. // `/<shortId>` (project.hl): the page's path, or null
  183. static shortIdPath = (&sid) => {
  184. if (!isShortId(&sid)) { return null }
  185. ensureShortIds()
  186. o = owners.fetch(sid)
  187. if (o == null) { return null }
  188. // tracker#31: a merged tombstone's short id leads to its keeper
  189. oKind = ownerKind(&o)
  190. oId = ownerId(&o)
  191. r = oKind == 'person' ? personsTable.fetch(oId) : liveShowOf(showsTable.fetch(oId))
  192. if (r == null || r.urlSegment == null) { return null }
  193. // a title's own page (/movies/, /series/, /shows/<slug>, tracker.worldapi.org#21)
  194. return oKind == 'person' ? '/person/' + r.urlSegment : titlePath(&r)
  195. }
  196. static shortIdRoute = (&route, &req) => {
  197. sid = route.params != null ? route.params.sid : null
  198. path = sid != null && hlTypeName(sid) == 'String' ? shortIdPath(sid.toLowerCase()) : null
  199. if (path == null) { return warmBlocked() ? startingUpText() : notFoundText('not found') }
  200. return movedResponse(&path)
  201. }

Branches

Latest commits

  • b9c7c3c8Merge branch 'records-dp74' into mainTracker
  • 85cfb4ae|||PR records: AP61 day61, DP74 liveTracker
  • b1496147Merge branch 'ap61' into mainTracker
  • 2047955bMerge branch 'u12-gateports' into mainTracker
  • c8da40f3|||PR AP61: re-vendor Hybriel set day61 (source a05af47c, bin a11042e5)Tracker
  • 4e018678|||PR deploy.sh: gates use Tracker's ports 8716-8719 and LC_ALL=C; README: 2 backups keptTracker
  • 0b86324aMerge branch 'records-dp73' into mainTracker
  • 9ce5f59b|||PR records: DP73 live 613ae0e; deploy.sh keeps 2 backupsTracker
  • 613ae0ecMerge branch 'bs3' into mainTracker
  • 1383264b|||PR BS3: keep shared synchronous sorting fastTracker
  • 63e5ba1a|||PR BS3: guard boot imports and share resumable sort buffersTracker
  • 310613f1Merge branch 'records-dp72' into mainTracker
  • 6f7b61ba|||PR records: deploy-swap fix live, Kunibert findingsTracker
  • c41587d2Merge branch 'bs2' into mainTracker
  • 0dd538a6|||PR BS2: finish the boot index in slices so a booting instance keeps answeringTracker
  • 019d5cedMerge branch 'records-1110' into mainTracker
  • f88ae8b9|||PR records: day56 toggle live, reviewTracker
  • b6b3bb4dMerge branch 'ap56e' into mainTracker
  • 29a26da9|||PR AP56e: guard hidden show helpers during session syncTracker
  • 7c9ec236|||PR AP56e: re-vendor Hybriel set day56 (source 36ae83a8, bin c1f595a2)Tracker