gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit529dd741529dd741Merge sl1-slices: slice details repair and person fill (SL1)mre529dd741/lib/search.hl

16.6 KB

  1. // lib/search.hl — THE SEARCH (tracker.worldapi.org#14): our own database first, then "Fetch from web" (TMDB) for titles
  2. // we don't have yet, and the import of the one picked. Used by components/search.hl (`/search/<text>`).
  3. //
  4. // dbSearch(text) our shows, movies and people — from an IN-MEMORY INDEX built once at boot (no table scan per
  5. // keystroke): every title/name split into words; each word's first 2 and first 3 characters are
  6. // a bucket key → the entries holding such a word. A query looks at ONE bucket (its longest word's
  7. // first 3 characters, or 2 for a 2-letter word) and keeps the entries where EVERY query word is
  8. // the start of one of the entry's words. A title's year is one of its words ("doctor who 2005").
  9. // webSearch(text) GET <TMDB_BASE_URL>/search/multi?query=… (one request; TV + movies only, people dropped) —
  10. // the titles we already have (same TMDB id and kind) are left out
  11. // importTitle(kind, id) a new show record from GET /tv/<id>?append_to_response=external_ids,aggregate_credits (a movie:
  12. // /movie/<id>?…,credits), then sync.hl `syncShowWith` fills it from that same answer exactly like
  13. // the daily sync does (seasons, episodes, poster, external ids); added to the index. The answer goes
  14. // back as `details`: the caller (components/search.hl) stores its cast + crew (credits.hl applyCredits,
  15. // tracker#28 — details.hl imports this file, so it cannot be called from here)
  16. //
  17. // ADULT TITLES (mission 054): our database lists only titles with `adult == false` (shows.hl isPublicTitle; unknown is
  18. // hidden) — `titleOk` holds that per show id, set by indexShow and by `searchTitleChanged` (the adult backfill and the daily
  19. // sync call it per title). The web list asks TMDB with include_adult=false AND keeps only results with `adult` false.
  20. //
  21. // ONE PROCESS PER STORAGE (hybriel#21): the index lives in the app's process and is kept up to date by importTitle; the
  22. // daily sync never changes a title. New rows get self-assigned 16-hex ids (hybriel#113), like sync.hl.
  23. import { now } from 'hl:time'
  24. import { warm } from './warm.hl'
  25. import { textOr, newId } from './util.hl'
  26. import { showsTable, personsTable, genresTable, isPublicTitle, kindOfTitle, titlePath, liveShowOf } from './shows.hl'
  27. import { tmdbGet, tmdbImageBase, adultOf } from './tmdb.hl'
  28. import { syncShowWith, persistSync } from './sync.hl'
  29. import { refreshCatalogShow } from './catalog.hl'
  30. import { claimShortId } from './shortids.hl'
  31. import { wordsOf, bucketKeys, tmdbKeyOf, yearWordOf, scoreOf, matchesText, entryWords, insertTop, yearOfDate, slugBaseOf } from './search-helpers.hl'
  32. // ---- the index --------------------------------------------------------------------------------------
  33. // entry i = { kind ('title' | 'person'), id, words, text (the words joined by one space, without the year), tie }, kept as PARALLEL
  34. // ARRAYS (mission T17, boot time): an object per entry with its words array and strings was ~11 live objects per person (7.9 M for
  35. // 680 K people — every collection marks them all). Now: kind 0 title / 1 person, id, text and tie — about two objects per person; the
  36. // entry's words are rebuilt from `text` for the few candidates a query looks at (entryWords). `text` is what it always was: the name's
  37. // words joined by one space, a title's year word as the last one (the comment above says "without the year" — it never was). The
  38. // index i is the same as before: the order of insertion.
  39. static entKind = []
  40. static entId = []
  41. static entText = []
  42. static entTie = []
  43. static buckets = {}
  44. // what we have, by TMDB id: 'series:<id>' / 'movie:<id>' → our show id (the web list leaves these out)
  45. static haveTmdb = {}
  46. // tracker#18 (the daily sync's TVmaze change list, dailysync.hl): TVmaze id → our show id (kept by indexShow and
  47. // searchTitleChanged — the sync fills TVmaze ids)
  48. static haveTvmz = {}
  49. // every show slug in use (an imported title gets a free one)
  50. static slugTaken = {}
  51. // show id → true when the title may be listed (not adult, mission 054)
  52. static titleOk = {}
  53. // tracker#18 (a title renamed by the daily sync): show id → its entry's index; an entry replaced by a newer one is `stale`
  54. // (skipped by dbSearch — the buckets only ever grow)
  55. static titleEntry = {}
  56. static staleEntry = {}
  57. static indexStats = { built = false titles = 0 people = 0 keys = 0 ms = 0 }
  58. // `tie` orders equally good matches: lower first (a title: series before movies, then the newer one)
  59. static addEntry = (kind, id, &name, &extra, tie) => {
  60. words = wordsOf(&name)
  61. if (words.length == 0) { return false }
  62. i = entId.length
  63. all = []
  64. for (w of words) { all.push(w) }
  65. if (extra != null && extra != '') { all.push(extra) }
  66. entKind.push(kind == 'title' ? 0 : 1)
  67. entId.push(id)
  68. entText.push(all.join(' '))
  69. entTie.push(tie)
  70. if (kind == 'title') { titleEntry[id] = i }
  71. for (k of bucketKeys(&all)) {
  72. if (buckets[k] == null) { buckets[k] = [i] indexStats.keys = indexStats.keys + 1 } else { buckets[k].push(i) }
  73. }
  74. return true
  75. }
  76. static indexShow = (&s) => {
  77. if (s.urlSegment != null) { slugTaken[s.urlSegment] = true }
  78. // tracker#31: a merged tombstone keeps its slug taken, nothing else (its keeper is the title)
  79. if (s.mergedInto != null) {
  80. titleOk[s.id] = false
  81. return null
  82. }
  83. if (s.tmdbId != null) { haveTmdb[tmdbKeyOf(&s.type, &s.tmdbId)] = s.id }
  84. if (s.tvmzId != null) { haveTvmz['' + s.tvmzId] = s.id }
  85. titleOk[s.id] = isPublicTitle(&s)
  86. y = toNumber(yearWordOf(&s))
  87. if (addEntry('title', s.id, &s.title, yearWordOf(&s), (s.type == 'movie' ? 10000 : 0) + (y != null ? 3000 - y : 2999))) { indexStats.titles = indexStats.titles + 1 }
  88. return null
  89. }
  90. // tracker#26 (details.hl): a person added from a title's cast — findable by the search at once
  91. static indexPerson = (&p) => {
  92. ensureIndex()
  93. if (addEntry('person', p.id, &p.name, '', 0)) { indexStats.people = indexStats.people + 1 }
  94. return null
  95. }
  96. // a title's adult flag changed (the backfill / the daily sync): listed from now on, or not
  97. static searchTitleChanged = (&showId) => {
  98. s = showsTable.fetch(showId)
  99. if (s != null) { titleOk[s.id] = isPublicTitle(&s) }
  100. if (s != null && s.tvmzId != null) { haveTvmz['' + s.tvmzId] = s.id }
  101. return null
  102. }
  103. // tracker#31 (merge.hl): a duplicate became a tombstone of `keeperId` — its entry goes stale, its TMDB id (and TVmaze id) now
  104. // answer the keeper, so no import or filmography adds the title again
  105. static searchTitleMerged = (&tombId, &keeperId, &type, &tmdbId) => {
  106. ensureIndex()
  107. old = titleEntry[tombId]
  108. if (old != null) { staleEntry['' + old] = true }
  109. titleOk[tombId] = false
  110. if (tmdbId != null) { haveTmdb[tmdbKeyOf(&type, &tmdbId)] = keeperId }
  111. k = showsTable.fetch(keeperId)
  112. if (k != null) {
  113. if (k.urlSegment != null) { slugTaken[k.urlSegment] = true }
  114. if (k.tvmzId != null) { haveTvmz['' + k.tvmzId] = k.id }
  115. titleOk[k.id] = isPublicTitle(&k)
  116. }
  117. return null
  118. }
  119. // a title's name changed (the daily sync, tracker#18): its old entry goes stale, a new one is added — found by the new name at once
  120. static searchTitleRenamed = (&showId) => {
  121. if (!indexStats.built) { return null }
  122. s = showsTable.fetch(showId)
  123. if (s == null) { return null }
  124. old = titleEntry[s.id]
  125. if (old != null && entText[old] == wordsOf(&s.title).join(' ')) { return null }
  126. if (old != null) { staleEntry['' + old] = true }
  127. indexShow(&s)
  128. return null
  129. }
  130. // one person into the index (the scan below and bootscan.hl's person pass)
  131. static noteIndexPerson = (&p) => {
  132. if (addEntry('person', p.id, &p.name, '', 0)) { indexStats.people = indexStats.people + 1 }
  133. return null
  134. }
  135. // the scan is done (bootscan.hl streams the tables itself): the log line
  136. static finishSearchIndex = (&t0) => {
  137. indexStats.built = true
  138. indexStats.ms = now() - t0
  139. console.log('search index: ' + indexStats.titles + ' titles, ' + indexStats.people + ' people, ' + indexStats.keys + ' keys, ' + indexStats.ms + ' ms')
  140. return true
  141. }
  142. // built once: at boot (bootscan.hl does it inside its passes; this is the lazy fallback), else by the first search
  143. // mission T17: false while the progressive start is still filling the index (bootscan.hl) — the caller answers "starting up"
  144. static ensureIndex = () => {
  145. if (indexStats.built) { return true }
  146. if (warm.running) { return false }
  147. indexStats.built = true
  148. t0 = now()
  149. // mission 043: streamed, one record decoded at a time
  150. for (s of showsTable.iterate(null, null)) { indexShow(&s) }
  151. for (p of personsTable.iterate(null, null)) { noteIndexPerson(&p) }
  152. finishSearchIndex(&t0)
  153. return true
  154. }
  155. // tracker.worldapi.org#16 (people.hl): our show id for a TMDB title — `type` 'series' | 'movie' — or null
  156. static titleIdByTmdb = (&type, &tmdbId) => {
  157. ensureIndex()
  158. return haveTmdb[tmdbKeyOf(&type, &tmdbId)]
  159. }
  160. // tracker#18: our show id for a TVmaze id, or null
  161. static titleIdByTvmaze = (&tvmzId) => {
  162. ensureIndex()
  163. return haveTvmz['' + tvmzId]
  164. }
  165. // ---- our database ------------------------------------------------------------------------------------
  166. static titleLimit = 30
  167. static peopleLimit = 10
  168. // { text, words, titles: [{ id }], people: [{ id }], titleCount, peopleCount, tooShort }
  169. static dbSearch = (text) => {
  170. out = { text = text titles = [] people = [] titleCount = 0 peopleCount = 0 tooShort = false ms = 0 warming = false }
  171. if (!ensureIndex()) { out.warming = true return out }
  172. t0 = now()
  173. qw = wordsOf(&text)
  174. let longest = ''
  175. for (w of qw) { if (w.length > longest.length) { longest = w } }
  176. if (longest.length < 2) { out.tooShort = true return out }
  177. key = longest.slice(0, longest.length >= 3 ? 3 : 2)
  178. cand = buckets[key]
  179. if (cand == null) { return out }
  180. qtext = qw.join(' ')
  181. let titles = []
  182. let people = []
  183. for (i of cand) {
  184. let isTitle = entKind[i] == 0
  185. if ((!isTitle || (titleOk[entId[i]] == true && staleEntry['' + i] != true)) && matchesText(&entText[i], &qw)) {
  186. let e = { text = entText[i] words = entryWords(&entText[i]) }
  187. let item = { score = scoreOf(&e, &qw, &qtext) len = e.text.length tie = entTie[i] i = i }
  188. if (isTitle) {
  189. out.titleCount = out.titleCount + 1
  190. titles = insertTop(&titles, &item, &titleLimit)
  191. } else {
  192. out.peopleCount = out.peopleCount + 1
  193. people = insertTop(&people, &item, &peopleLimit)
  194. }
  195. }
  196. }
  197. for (t of titles) { out.titles.push({ id = entId[t.i] }) }
  198. for (p of people) { out.people.push({ id = entId[p.i] }) }
  199. out.ms = now() - t0
  200. return out
  201. }
  202. // ---- the web (TMDB) -----------------------------------------------------------------------------------
  203. // TMDB's search: [{ kind ('tv' | 'movie'), tmdbId, title, year, overview, posterUrl }] of what we DON'T have, or
  204. // { failed }. One request (search/multi, page 1 = up to 20 results); people and titles we have are left out.
  205. static webSearch = (&text) => {
  206. if (!ensureIndex()) { return { rows = [] left = 0 failed = 'tracker is starting up, try again in a minute' } }
  207. qw = wordsOf(&text)
  208. if (text == null || text.trim().length < 2 || qw.length == 0) { return { rows = [] left = 0 failed = null } }
  209. j = tmdbGet('/search/multi?query=' + encodeURIComponent(text.trim()) + '&include_adult=false&page=1')
  210. if (j.failed != null) { return { rows = [] left = 0 failed = j.failed } }
  211. rows = []
  212. let left = 0
  213. if (j.results != null) {
  214. for (r of j.results) {
  215. let kind = r.media_type
  216. // mission 054: only what TMDB says is not adult (include_adult=false already, and the result's own flag)
  217. if ((kind == 'tv' || kind == 'movie') && r.id != null && hlTypeName(r.id) == 'Number' && adultOf(&r) == false) {
  218. if (haveTmdb[tmdbKeyOf(kind == 'tv' ? 'series' : 'movie', &r.id)] != null) {
  219. left = left + 1
  220. } else {
  221. let title = kind == 'tv' ? textOr(&r.name) : textOr(&r.title)
  222. let year = yearOfDate(kind == 'tv' ? r.first_air_date : r.release_date)
  223. if (title != null) {
  224. rows.push({ kind = kind tmdbId = r.id title = title year = year
  225. overview = textOr(&r.overview) != null ? r.overview : ''
  226. posterUrl = textOr(&r.poster_path) != null ? tmdbImageBase + '/w92' + r.poster_path : '/posters/none' })
  227. }
  228. }
  229. }
  230. }
  231. }
  232. return { rows = rows left = left failed = null }
  233. }
  234. // ---- the import ------------------------------------------------------------------------------------
  235. // "Doctor Who" → "Doctor-Who" (the migrated urlSegment form: letters and digits, everything else one '-'); a slug in use
  236. // gets "-2", "-3", … like the migrated ones ("Raised-by-Wolves-2"); a title with no Latin letter at all → "title-<tmdbId>"
  237. static slugOf = (&title, &tmdbId) => {
  238. out = slugBaseOf(&title, 'title-' + tmdbId)
  239. if (slugTaken[out] != true) { return out }
  240. let n = 2
  241. while (slugTaken[out + '-' + n] == true) { n = n + 1 }
  242. return out + '-' + n
  243. }
  244. // our genres by lower-case name (TMDB's "Drama" → ours); TMDB-only names ("Sci-Fi & Fantasy") are left out
  245. static genreIdsOf = (&tmdbGenres) => {
  246. out = []
  247. if (tmdbGenres == null) { return out }
  248. byName = {}
  249. for (g of genresTable.find(null, null)) { if (g.name != null) { byName[('' + g.name).toLowerCase()] = g.id } }
  250. for (tg of tmdbGenres) {
  251. let id = tg.name != null ? byName[('' + tg.name).toLowerCase()] : null
  252. if (id != null && !out.includes(id)) { out.push(id) }
  253. }
  254. return out
  255. }
  256. // `kind` 'tv' | 'movie', `tmdbId` a number → { slug, path (its page, shows.hl titlePath), show, created, sync, details } or { error }. A title we already have (same
  257. // TMDB id and kind) is not added again: its slug is answered.
  258. static importTitle = (&kind, tmdbId) => {
  259. if (kind != 'tv' && kind != 'movie') { return { error = 'unknown kind' } }
  260. // `tid`, not `id`: inside the record literal below an entry named `id` would shadow it for every later entry
  261. tid = toNumber('' + tmdbId)
  262. if (tid == null || tid <= 0 || tid % 1 != 0) { return { error = 'bad TMDB id' } }
  263. if (!ensureIndex()) { return { error = 'tracker is starting up, try again in a minute' } }
  264. type = kind == 'tv' ? 'series' : 'movie'
  265. have = haveTmdb[tmdbKeyOf(&type, &tid)]
  266. if (have != null) {
  267. // tracker#31: a merged tombstone answers its keeper
  268. let s = liveShowOf(showsTable.fetch(have))
  269. if (s != null) { return { slug = s.urlSegment path = titlePath(&s) show = s.id created = false } }
  270. }
  271. d = tmdbGet('/' + kind + '/' + tid + '?append_to_response=external_ids,' + (kind == 'tv' ? 'aggregate_credits' : 'credits'))
  272. if (d.failed != null) { return { error = 'TMDB: ' + d.failed } }
  273. let title = kind == 'tv' ? textOr(&d.name) : textOr(&d.title)
  274. if (title == null) { return { error = 'TMDB has no title for ' + kind + ' ' + tid } }
  275. release = textOr(kind == 'tv' ? d.first_air_date : d.release_date)
  276. year = release != null && release.length >= 4 ? toNumber(release.slice(0, 4)) : null
  277. // tracker#18: `summary` is the creator's own text — TMDB's goes to tmdbSummary only
  278. record = {
  279. id = newId() title = title summary = null tmdbSummary = textOr(&d.overview) tmdbId = tid
  280. language = textOr(&d.original_language) type = type release = release year = year image = null
  281. urlSegment = slugOf(&title, &tid) episodesCount = null homepage = textOr(&d.homepage) imdbId = null seasonsCount = null
  282. status = textOr(&d.status) tagline = textOr(&d.tagline) tvdbId = null tvmzId = null genres = genreIdsOf(&d.genres)
  283. cast = [] seasons = [] oldId = 'tmdb-' + kind + '-' + tid imported = now() adult = adultOf(&d)
  284. }
  285. // tracker.worldapi.org#21: a TV title's TMDB type and kind (set after the literal: an entry named `kind` would shadow the
  286. // parameter for the entries after it)
  287. if (kind == 'tv') {
  288. record.tmdbType = textOr(&d.type)
  289. record.kind = kindOfTitle(&record.tmdbType, &record.genres, &record.tvmazeType)
  290. }
  291. // tracker#31: looked up again right before the put — the TMDB request above may have taken a while
  292. again = titleIdByTmdb(&type, &tid)
  293. if (again != null) {
  294. let s = liveShowOf(showsTable.fetch(again))
  295. if (s != null) { return { slug = s.urlSegment path = titlePath(&s) show = s.id created = false } }
  296. }
  297. // mission 060: its short id (shortids.hl — unique across shows and persons)
  298. record.shortId = claimShortId('show', record.id, &record.oldId)
  299. if (showsTable.put(record) == null) { return { error = 'could not store the title: ' + showsTable.lastError() } }
  300. indexShow(&record)
  301. r = syncShowWith(&record.id, &d)
  302. persistSync()
  303. // the public lists (catalog.hl, #13) get it at once, like a show the daily sync touched (merge of #13 + #14)
  304. refreshCatalogShow(&record.id)
  305. console.log('search import: ' + kind + ' ' + tid + ' "' + title + '" → ' + titlePath(&record) + ' (newSeasons=' + r.newSeasons + ' newEpisodes=' + r.newEpisodes + ' posters=' + r.posters + ' ids=' + r.ids + ' requests=' + r.requests + ' errors=' + r.errors + (r.error != '' ? ' ' + r.error : '') + ')')
  306. return { slug = record.urlSegment path = titlePath(&record) show = record.id created = true sync = r details = d }
  307. }

Branches

Latest commits

  • 529dd741Merge sl1-slices: slice details repair and person fill (SL1)mre
  • 8a83316blog: SL1 result, session drain slowermre
  • 35e93e8dSL1: slice the details repair and person fill: catalog lists changed in place, 40 ms fill steps, people created in steps, writes one table per tickmre
  • 72c9119flog+status: SL1 startedmre
  • d74620fcmission SL1: slice repair and person fillmre
  • 5d542d73log+status: ST1 resultmre
  • 3945eb81ST1: stall diagnosis reportmre
  • 404733aclog: ST1 startedmre
  • 3e3d5a55mission ST1: stall diagnosismre
  • 9c3180eblog+status: RV28d measured after deploymre
  • fdf10b1alog: RV28d deployed on day38bmre
  • 320005e9log: RV28d merged, deploy runningmre
  • a8fef27dRV28d: reportmre
  • 2bae8373RV28d: re-vendor Hybriel set day38b (source 1e554d75, bin 5ff2a46d)mre
  • 16b3354aMerge branch 'main' into rv28cmre
  • 6f4f27d8log: RV28d started (day38b)mre
  • e6cf03ffmission RV28d: rv28c onto day38bmre
  • 3ccaee19status: live sweep freeze, waiting for Apollomre
  • 49f76ecblog: watch toggle slowness = session sweep freeze (tracker#50)mre
  • 3daf6eddlog: day37 live, still waiting for day39mre