tracker
All repositories: gitoria
16.1 KB
// hl:time — the clock AND time as an event source. JS twin of// plugins/time/time.zig, and the one file BOTH other realms run: the JavaScript// transpiler target copies it into `hl-modules/time.js`, and hl:web serves it to// the BROWSER as `hl-time.js` (hl:time declares no `"realm": "server"`, so a// client handler may reach it — plugins/web/web_framework.hl `packagePaths`).//// Parity contract with the native plugin:// now() → epoch milliseconds, integer-valued// timestamp(ms?) → "YYYY-MM-DDTHH:MM:SS.mmmZ", exactly 24 chars, UTC.// No argument (or a non-number) means "now"; an epoch-ms// argument renders THAT instant, which is what makes the// call testable — timestamp(0) is always the epoch.// monotonic() → nanoseconds off a monotonic counter. Origin arbitrary;// only differences are meaningful.// every(s) → a repeating Timer; `on t.tick()` until `t.stop()`// after(s) → a one-shot Timer, `s` seconds from now// until(epochMs) → a one-shot Timer at that instant// sleep(s) → BLOCKING. Yes, in a browser too — see below.// offset / local / fromLocal / localTimestamp / isZone → time zones, ticket #5// (the section below says how Intl stands in for TZif)export function now() { return Date.now(); }export function timestamp(ms) {// Date#toISOString already emits exactly the native format for in-range// instants. Pre-epoch values are clamped the same way the native plugin// clamps them (std.time.epoch is u64-only, so 1970 is the floor on both// sides and the two targets must agree on what happens below it).let t = typeof ms === 'number' && Number.isFinite(ms) ? Math.trunc(ms) : Date.now();if (t < 0) t = 0;return new Date(t).toISOString();}export function monotonic() {// process.hrtime.bigint() is Node's CLOCK_MONOTONIC. Converted to a plain// Number because Hybriel has no bigint; same f64 caveat as the native side// (exact for the first ~104 days of counter uptime).if (typeof process !== 'undefined' && process.hrtime && process.hrtime.bigint) {return Number(process.hrtime.bigint());}// Browser/other host fallback: performance.now() is ms with sub-ms// resolution off a monotonic origin.return Math.round(performance.now() * 1e6);}// ═══════════════════════════════════════════════════════════════════════════// TIME ZONES (ticket #5) — the twin of the TIME ZONES half of time.zig// ═══════════════════════════════════════════════════════════════════════════//// The native plugin reads the system's TZif files; this half asks Intl, which// every browser and Node carry. The ONLY question put to Intl is the offset in// force at an instant; `local`, `fromLocal` and `localTimestamp` are the same// arithmetic time.zig runs, step for step, so the two realms cannot drift on// anything but the zone data itself.//// THE OFFSET FROM INTL. `formatToParts` hands back the wall clock; the offset is// that reading minus UTC. Only the DAY and the time of day are read, never the// year: Intl's `en-US` calendar is Julian before 1582 and prints an era-less// |year| before year 1, and an offset is always under a day, so "same day of// the month, next, or previous" is all the date there is to know.const MAX_MS = 8.64e15;const BAD_INSTANT = 'hl:time: pass the instant in epoch milliseconds (what now() returns)';const zoneFormats = new Map();function floorDiv(a, b) { return Math.floor(a / b); }function mod(a, b) { return a - Math.floor(a / b) * b; }function daysFromCivil(y0, m, d) {const y = m <= 2 ? y0 - 1 : y0;const era = floorDiv(y, 400);const yoe = y - era * 400;const mp = mod(m + 9, 12);const doy = floorDiv(153 * mp + 2, 5);const doe = yoe * 365 + floorDiv(yoe, 4) - floorDiv(yoe, 100) + doy;return era * 146097 + doe - 719468 + (d - 1);}function civilFromDays(z0) {const z = z0 + 719468;const era = floorDiv(z, 146097);const doe = z - era * 146097;const yoe = floorDiv(doe - floorDiv(doe, 1460) + floorDiv(doe, 36524) - floorDiv(doe, 146096), 365);const doy = doe - (365 * yoe + floorDiv(yoe, 4) - floorDiv(yoe, 100));const mp = floorDiv(5 * doy + 2, 153);const d = doy - floorDiv(153 * mp + 2, 5) + 1;const m = mp < 10 ? mp + 3 : mp - 9;return { y: m <= 2 ? yoe + era * 400 + 1 : yoe + era * 400, m, d };}/** The same shape rule as time.zig's `plausibleName`: Intl also takes offsets* ('+01:00') and is case-blind, and the system database is neither. */function plausibleName(name) {if (typeof name !== 'string' || name.length === 0 || name.length > 64) return false;if (!/^[A-Za-z][A-Za-z0-9/_+-]*$/.test(name)) return false;if (name.includes('//') || name.endsWith('/')) return false;if (name.startsWith('posix/') || name.startsWith('right/')) return false;return name !== 'posixrules' && name !== 'localtime' && name !== 'Factory';}function zoneFormat(name) {if (zoneFormats.has(name)) return zoneFormats.get(name);let f = null;if (plausibleName(name)) {try {f = new Intl.DateTimeFormat('en-US', {timeZone: name, hourCycle: 'h23',day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric',});// a case variant of a real name ('europe/vienna') is accepted by Intl// and unknown to the file system — refuse it on this side as wellconst resolved = f.resolvedOptions().timeZone;if (resolved !== name && resolved.toLowerCase() === name.toLowerCase()) f = null;} catch { f = null; }}if (zoneFormats.size < 4096) zoneFormats.set(name, f);return f;}function zoneArg(zone) {if (typeof zone !== 'string') throw new Error("hl:time: pass the time zone as an IANA name, e.g. 'Europe/Vienna'");const f = zoneFormat(zone);if (!f) throw new Error(`hl:time: unknown time zone '${zone.length > 64 ? zone.slice(0, 64) : zone}'`);return f;}function instantArg(ms) {if (typeof ms !== 'number' || !(ms <= MAX_MS && ms >= -MAX_MS)) throw new Error(BAD_INSTANT);return Math.floor(ms);}function offsetAtMs(f, ms) {const secs = floorDiv(ms, 1000);let day = 0, wall = 0;for (const p of f.formatToParts(secs * 1000)) {const v = Number(p.value);if (p.type === 'day') day = v;else if (p.type === 'hour') wall += v * 3600;else if (p.type === 'minute') wall += v * 60;else if (p.type === 'second') wall += v;}const utcDays = floorDiv(secs, 86400);let off = wall - (secs - utcDays * 86400);if (day !== civilFromDays(utcDays).d) off += off < 0 ? 86400 : -86400;return off;}/** Seconds east of UTC in force in `zone` at the instant `ms`. */export function offset(ms, zone) {const t = instantArg(ms);return offsetAtMs(zoneArg(zone), t);}/** The wall-clock reading in `zone` at `ms` — time.zig `hl_time_local`. */export function local(ms, zone) {const t = instantArg(ms);const off = offsetAtMs(zoneArg(zone), t);const lt = t + off * 1000;const days = floorDiv(lt, 86400000);const inDay = lt - days * 86400000;const c = civilFromDays(days);return {year: c.y, month: c.m, day: c.d,hour: floorDiv(inDay, 3600000), minute: mod(floorDiv(inDay, 60000), 60), second: mod(floorDiv(inDay, 1000), 60),millisecond: mod(inDay, 1000), weekday: mod(days + 3, 7) + 1,offset: off,};}const BAD_FIELDS = 'hl:time fromLocal: every field must be a Number (year is required)';function fieldNumber(o, key, dflt) {const v = o[key];if (v === undefined || v === null) return dflt;if (typeof v !== 'number' || !(Math.abs(v) < 1e12)) throw new Error(BAD_FIELDS);return Math.floor(v);}/** The instant a wall-clock reading in `zone` names — time.zig `fromWall`:* a FOLD answers the earlier instant, a GAP moves forward by its length. */export function fromLocal(fields, zone) {if (fields === null || typeof fields !== 'object') {throw new Error('hl:time fromLocal: pass the fields as { year, month, day, hour, minute, second, millisecond }');}const f = zoneArg(zone);const y = fieldNumber(fields, 'year', NaN);if (Number.isNaN(y)) throw new Error(BAD_FIELDS);const mo = fieldNumber(fields, 'month', 1), d = fieldNumber(fields, 'day', 1);const h = fieldNumber(fields, 'hour', 0), mi = fieldNumber(fields, 'minute', 0);const s = fieldNumber(fields, 'second', 0), milli = fieldNumber(fields, 'millisecond', 0);const m0 = mo - 1;const wall = daysFromCivil(y + floorDiv(m0, 12), mod(m0, 12) + 1, d) * 86400000 +h * 3600000 + mi * 60000 + s * 1000 + milli;if (Math.abs(wall) > MAX_MS + 86400000) throw new Error(BAD_INSTANT);const before = offsetAtMs(f, wall - 86400000);const after = offsetAtMs(f, wall + 86400000);const a = wall - before * 1000, b = wall - after * 1000;const aOk = offsetAtMs(f, a) === before, bOk = offsetAtMs(f, b) === after;const ms = aOk && bOk ? Math.min(a, b) : aOk ? a : bOk ? b : a;if (Math.abs(ms) > MAX_MS) throw new Error(BAD_INSTANT);return ms;}const pad = (n, w) => String(n).padStart(w, '0');/** ISO-8601 in `zone`: "YYYY-MM-DDTHH:MM:SS.mmm+HH:MM" (":SS" on the offset only* when it has seconds, i.e. local mean time). */export function localTimestamp(ms, zone) {const t = instantArg(ms);const off = offsetAtMs(zoneArg(zone), t);const lt = t + off * 1000;const days = floorDiv(lt, 86400000);const inDay = lt - days * 86400000;const c = civilFromDays(days);const year = c.y >= 0 && c.y <= 9999 ? pad(c.y, 4) : (c.y < 0 ? '-' : '+') + pad(Math.abs(c.y), 6);const a = Math.abs(off);return year + '-' + pad(c.m, 2) + '-' + pad(c.d, 2) + 'T' +pad(floorDiv(inDay, 3600000), 2) + ':' + pad(floorDiv(inDay, 60000) % 60, 2) + ':' +pad(floorDiv(inDay, 1000) % 60, 2) + '.' + pad(inDay % 1000, 3) +(off < 0 ? '-' : '+') + pad(floorDiv(a, 3600), 2) + ':' + pad(floorDiv(a, 60) % 60, 2) +(a % 60 !== 0 ? ':' + pad(a % 60, 2) : '');}/** True when this realm's zone database (Intl) knows the name. */export function isZone(name) {return typeof name === 'string' && zoneFormat(name) !== null;}// ═══════════════════════════════════════════════════════════════════════════// TIME AS AN EVENT SOURCE (mission 254)// ═══════════════════════════════════════════════════════════════════════════//// THE FLOOR IS THE SAME NUMBER AS THE NATIVE PLUGIN'S, and this is the realm// that sets it. Server-side a timerfd carries nanoseconds and the event loop// blocks on it, so there is no floor there at all; the browser has one, and it// was MEASURED rather than quoted from the spec — tests/browser/tests/66-timers.mjs// drives a real page and prints the number it measured on every run. HTML's// timer nesting rule clamps a chained `setTimeout(…, 0)` to 4ms from the fifth// nesting level, and a `setInterval` asked for 1ms delivers ~4ms periods.//// The same `on t.tick()` handler is meant to run in both realms, so `every(0.001)`// must not mean two different things depending on where it ran: both sides raise// anything below the floor to it. (plugins/time/time.zig FLOOR_NS = 4_000_000.)export const TIMER_FLOOR_SECONDS = 0.004;/** Monotonic milliseconds, fractional. `performance` is a global in Node ≥16 and* in every browser; `Date.now()` is the last-resort fallback and is not* monotonic, which only costs accuracy across a clock adjustment. */function monoMs() {if (typeof performance !== 'undefined' && performance.now) return performance.now();return Date.now();}/** ONE ARMED TIMER — the twin of plugins/time/Timer.hl.** `on t.tick()` reaches this through `__hlOn`, which is the ONE registration* protocol both JS realms use: the transpiler target's `hlScopedBus`* (js/src/runtime/runtime.js) and hl:web's client runtime (hl-core.js* `__hlBindSources`) each end up calling it with the event name and a handler.* A plugin object is not an hl class instance and has no `constructor.__events__`,* so it could not otherwise be the target of an instance-scoped handler.** SCHEDULED FROM THE ORIGIN, like the native half: each round's delay is* computed against `origin + n × period`, never `period` from where the last* handler finished, so the handler's own runtime does not accumulate. A round* the host was too busy to deliver is SKIPPED rather than queued — a periodic* timer that owes you a backlog is a stampede.** A CHAINED `setTimeout` RATHER THAN `setInterval`, for the same reason: the* chain lets each delay be recomputed from the origin, and `setInterval`'s* behaviour when a callback overruns its period differs between hosts. */class HlTimer {constructor(seconds, repeating) {this.seconds = Math.max(TIMER_FLOOR_SECONDS, Number(seconds) || 0);this.repeating = !!repeating;this.running = true;this.count = 0;this.__handlers = new Map();this.__origin = monoMs();this.__n = 0;this.__h = null;this.__arm();}__arm() {const period = this.seconds * 1000;this.__n += 1;const due = this.__origin + this.__n * period;this.__h = setTimeout(() => this.__fire(), Math.max(0, due - monoMs()));}__fire() {this.__h = null;if (!this.running) return;this.count += 1;const ev = { count: this.count, at: Date.now() };if (this.repeating) {// skip whatever the host was too busy to deliver, keeping the phaseconst period = this.seconds * 1000;const now = monoMs();while (this.__origin + this.__n * period <= now) this.__n += 1;this.__n -= 1;this.__arm();} else {// A SPENT ONE-SHOT RETIRES ITSELF before the tick is delivered — the// same rule as the native half (mission 249: a source that will never// speak again must not keep the program alive; in Node that is// literally true, an un-cleared timer keeps the process running).this.running = false;}const list = this.__handlers.get('tick');if (list) for (const fn of list.slice()) fn(ev);}/** The registration protocol — see the class comment. */__hlOn(event, fn) {let list = this.__handlers.get(event);if (!list) { list = []; this.__handlers.set(event, list); }list.push(fn);return this;}/** Stop an interval. True when this call was the one that stopped it. */stop() {if (!this.running) return false;this.running = false;if (this.__h !== null) { clearTimeout(this.__h); this.__h = null; }return true;}}/** A REPEATING timer: `on t.tick()` fires every `seconds` until `t.stop()`. */export function every(seconds) { return new HlTimer(seconds, true); }/** A ONE-SHOT: `on t.tick()` fires once, `seconds` from now, and retires. */export function after(seconds) { return new HlTimer(seconds, false); }/** A ONE-SHOT AT AN INSTANT. `epochMs` is what `now()` answers; an instant* already past fires immediately (at the floor). */export function until(epochMs) {const delay = (Number(epochMs) - Date.now()) / 1000;return new HlTimer(delay > 0 ? delay : 0, false);}/** BLOCK for `seconds`. The creator's ruling: a basic tool for tests and* debugging, and it blocks — inside a server, `after()` is the thing to use.** `Atomics.wait` is the only real block JavaScript has, and it is FORBIDDEN on* a browser's main thread (it throws TypeError). So the browser gets a spin on* the monotonic clock instead, which is the same observable behaviour — the tab* is frozen for the duration — reached a different way. That is what a blocking* sleep IS; the docs say so beside it rather than pretending otherwise. */export function sleep(seconds) {const ms = Number(seconds) * 1000;if (!(ms > 0)) return false;try {if (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') {Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);return true;}} catch { /* main thread — fall through to the spin */ }const until_ = monoMs() + ms;while (monoMs() < until_) { /* the block */ }return true;}
Branches
- mainmain branch
Latest commits
- 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
- c1fa2f2etracker (mission 071): Hybriel master 190aa11d measured on the real copy vs the live binary 8590df63 — NOT adopted (after the first-start jobs /my/series 2.4x slower, /series 1.6x, RSS swings 7.4-12.2 GB; fresh it is flat at 1.7-2.2 GB and /my/unwatched faster), vendor stays 8efba065, candidate kept in .scratch/w071/vendor-190aa11d; tests/kinds.mjs: collection seed off (its TMDB request broke check 1 in 1 of 4 runs); tests/realdata-071.sh + realdata-071-bench.mjs + tools/realdata-071-table.py; README + STATUS (numbers, how to repeat); gates 325/0, 32/0, 50/0mre
- 8081350atracker docs (mission 070): README (summary, Config HL_GC_BYTES — kept at Hybriel's default, the 256 MiB setting is taken out of docker-compose.yml again: the jobs grew to 12+ GB with it too, see STATUS), Test (three gates), Deploy (first start ~50 min: kinds then seed, restart once after collections done, memory numbers), Vendored Hybriel 8efba065 + #48 audit, Files; STATUS mission 070 entry (merges, migrated counts, lambda audit, gates, RSS old vs new, how to repeat, open points); docs/kinds.md + docs/franchises.md job order; tests/realdata-070-*.sh, tools/count-migrated.hl, tools/ref-params.py, tools/lambda-audit.pymre
- 1ad19c8ctracker: re-vendor Hybriel master 8efba065 (#126 GC by bytes, #48 lambda parameters copy) (mission 070): bin/hybriel sha256 50361e95…, plugins core crypto data fetch fs http http1 mpackdb proc smtp time web; lambda audit: 13 lambdas change a passed record/list (11 through a local alias), no caller relies on it — unchanged; 319 read-only lambda parameters get & (no copy per call: /my/schedule 2.35 → 0.46 s, /my/unwatched 13.7 → 5.7 s on the real copy); /my/unwatched one merge sort instead of n² inserts; docker-compose HL_GC_BYTES=268435456; deploy.sh runs kinds.mjs + franchises.mjs too (default ports 8700–8710); tests/realdata-070.mjs; gates browser 325/0, kinds 32/0, franchises 50/0mre
- 46b21389tracker (mission 070, conductor): the sync never destroys migrated data — the one-time summary step MOVES a copied summary to migratedSummary (marker summaries-moved.txt) instead of clearing it; a migrated record's first title/genres/homepage/tagline TMDB replaces → migratedTitle/migratedGenres/migratedHomepage/migratedTagline, a migrated season's/episode's title/summary → migratedTitle/migratedSummary (set once); tests/peek-shows.hl prints them; gate 325/0mre
- 749019b0Merge t19 (tracker#19 franchises + timelines) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/browser.mjs/faketmdb.mjs, both sides kept; franchise/timeline pages get #20's typed heading (Franchise | …, Timeline | …), their title links via titlePath (/movies|/series|/shows); the collection seed waits for repair, kinds and credits too; franchises.mjs URLs + 2 new checks; gates browser 323/0, kinds 32/0, franchises 50/0mre
- daf49feaMerge t20 (tracker#20 typed headings + #21 series/shows split) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/search.hl/components/search.hl/browser.mjs/faketmdb.mjs, both sides kept; clock order backfill → repair → kinds → credits; withDetailsFields stores tmdbType + kind; gates: browser.mjs URLs → /series|/movies, typed h1 selectors; kinds.mjs repair/credits off, fixture name = seed name; browser 323/0, kinds 32/0mre
- 20e09d89Merge t18 (tracker#18 delta sync) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/browser.mjs, both sides kept; pageShowOf summary = summaryOfmre
- f83571c3tracker#18 (mission 067): daily sync by change lists — TMDB /tv|movie/changes (since the stored day, paged) + TVmaze /updates/shows → only our changed titles (followed: full step, unfollowed: light step — changed seasons, no TVmaze), full walk on first run / gap > 14 days / failed list; show record refreshed (title, tmdbSummary, tagline, status, genres …; renamed titles re-indexed); summary = the creator's own text (page: summary > tmdbSummary > tvmazeSummary), one-time clear of copied summaries (9,647 on the live copy); gate 261, tests/realdata-018*.mjs, README + STATUSmre
- 1ed5457etracker#20 + #21 (mission 068): typed headings "<Type> | <name>" in type colours; TV titles split into Series (/series) and Shows (/shows) by TMDB type + Reality/Talk/News genres — kind stored by sync/import/adult backfill + new kind backfill (resumes), /movies/<slug>, /shows/<slug> of a series/movie → 301, /my/series + /my/shows, home 5 tiles + 3 rows, search/filmography labels; gates kinds 32 + browser 266, tests/realdata-068.mjs, tools/count-kinds.hl, docs/kinds.md, README + STATUSmre
- f2b00674Merge t26 (tracker#26 + #28) into main (mission 062): short ids for every new person (castPersonId, guest route), guest stars stored on the title and created as people only when opened (/person/tmdb/<id>?show=<id> → 302), lean watch/follow clicks (showRow a small object, cast/crew from the slug, watches cached per user, face rows only after a season toggle); gate 311, tests/realdata-062.mjs, README + STATUSmre
- 0553b51ftracker#19 (mission 066): franchises and timelines — tables, /franchises, /franchises/<slug>, /timelines/<slug> (Timeline | Release sort, series by last episode), the Prequel | Timeline | Sequel widget with the franchise above, the creator's editor, TMDB collection seed in the app (resumes, paced); gate tests/franchises.mjs 48/0 + browser.mjs 266/0, tests/realdata-066.mjs, docs/franchises.md, README + STATUSmre
- fa1f9dfatracker#29 (mission 063): unwatched check muted grey outline + check (accent only on hover), watched stays solid — no code regression, the accent outline read as ticked; gate checks real checks visibly (computed style + screenshot pixel) on /my/unwatched, show, movie, /my/movies; gate 266, tests/realdata-063.mjs, README + STATUSmre
- 10bb3f93tracker#28 (mission 061): full cast (all seasons, main cast by episodes, guest stars) + crew (created by, directed by, written by, screenplay, story, music) — stored by the details completion, the daily sync, the search import (one details request) and a background credits job (resumes, RSS limit); show page collapsed after 20 with client-side Show all; showBySlug via a slug map; gate 249, tests/realdata-028.mjs, README + STATUSmre
- d8b12d67tracker#27 (mission 060): short ids for movies, series and persons — old 702 kept (data/old-short-ids.json), new random [a-z0-9]{5} unique across both, claimed at creation, background backfill (resumes), shown under poster/photo, /<shortId> → 301; gate 259, tests/realdata-060*, README + STATUSmre
- 25a50bc4tracker#26 (mission 059): titles from a filmography are completed — on open (skeleton, step-wise face showComplete, no reload) and by the in-app details repair (resumes, TMDB-paced, series in parts); cast from TMDB credits; gate 231, tests/realdata-026.mjs, README + STATUSmre