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
- 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
- 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
- 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
- 2e89b968tracker mission 028 (code order) 5/5 let: `let` only where a variable is reassigned — 667 never-reassigned lets became plain declarations (project.hl, lib/, components/, tools/, tests/); kept: 264 in loop bodies (a plain declaration there is 'Cannot reassign' on the 2nd pass), 234 reassigned, 27 whose name is also a member/outer/free name (a plain write would rebind it); tools/let-audit.py decides and fixes (README 'Code order'); tests/realdata-m028.{sh,mjs} = the page-output diff on a real copy; gates 342/0, 32/0, 52/0, real-copy pages identicalmre
- 54796ff2tracker mission 028 (code order) 4/5 thin faces + last copies: the show page's check/follow faces call lib/watches.hl toggleWatched / toggleSeasonWatched (seasonAllWatched moved there) and lib/follows.hl toggleFollowed; both logins (header selector face, /login/callback) share lib/users.hl userOfCode; todayStr/listOf copies in components and the export readers copied into tools/migrate.hl + tools/old-short-ids.hl now once (lib/util.hl, lib/export.hl); gates 342/0, 32/0, 52/0; old-short-ids output byte-identical, migrate output identicalmre
- 06b078e3tracker mission 028 (code order) 3/5 project.hl is the map: config, routes, wiring and a feature → file index (914 → 258 lines); the background jobs (daily sync run, backfills, details repair, credits job, merge, short ids, collection seed) moved unchanged into lib/jobs.hl (a class: their state is reassigned every step, a static cannot be; one instance made after the server), the login callback into lib/users.hl, poster/photo serving into lib/images.hl, the /shows/<slug> rule into lib/shows.hl showsMovedPath; route handlers are thin wrappers; gates 342/0, 32/0, 52/0, real-copy pages identicalmre
- 94716fd2tracker mission 028 (code order) 2/5 util + topics: lib/util.hl holds envOr, storageDir, postersDir, profilesDir, newId, hexDigits, todayStr, dateOr, textOr, hasId, listOr, firstOf, sortDesc once (were copied into up to 5 files); tmdbsync.hl split into tmdb.hl (TMDB/TVmaze requests), sync.hl (one title's sync), sync-helpers.hl, backfill.hl; details.hl split into details.hl, credits.hl, credits-helpers.hl (isIncomplete to shows.hl); search-helpers.hl (words, query, ranking, slugs); collections.hl (the TMDB collection seed, out of franchises.hl); deltasync.hl renamed dailysync.hl; no behaviour change: gates 342/0, 32/0, 52/0, real-copy pages identicalmre