gitoria
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
- fdfb4b1bgitoria: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, mpackdb 2cb7ae5e, http1 773de63e); gates 200/0, 46/0, 44/0mre
- 5b46ac84antcolony#40: LOG.md — missions 069/072 are antcolony missions (report paths on Byrodin)mre
- 5602ff41gitoria: Hybriel master 190aa11d (fc838894 GC correctness, #127 mountKids by reference, #126, #48) — tracker README flat; gates 200/0, 46/0, 44/0mre
- e85eaf01gitoria: 069 round 2 — hybriel 1a096ad3 not adopted (Markdown SSR still grows); browser gate waits for the server-side logout before restartmre
- 09ce4f3fgitoria: mission 069 re-vendor hybriel 8efba065 stopped (big SSR pages grow + slow down); lambda audit clean; old vendor keptmre
- 3dc43108antcolony#40: mission references point to the moved missionsmre
- 8d9450fdantcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
- 205d5fe4gitoria: Hybriel master ff51cf46; ssh keys/tokens no double rows (session sync); gates follow #20mre
- 9b27cb26gitoria#21: installable app (manifest, service worker, offline start page), own iconmre
- 68dcb603deploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
- e2deed6dgitoria#20: "Add code" only on the Code page of an empty repository, no collapsiblemre
- 8bb97ffddeploy.sh: never send .git or .gitignore to Byrodinmre
- fd981932State of 2026-09-27; bin/ no longer tracked (Hybriel commit is in README)mre
- 4a2d7125initial commitmre