|
| 1 | +"""The universe's clock as a site reads it: ``clock/v1``'s ``sync_time`` hands the server the gateway's ``/clock/time`` |
| 2 | +URL, as it hands it to MCP servers, and the site's time then follows that clock's ``{"virtual_time": <RFC3339>}``, |
| 3 | +read at most once a second and extrapolated between reads. The rate it extrapolates at is one two successive intervals |
| 4 | +between reads agreed on, so a clock set or advanced between two reads is taken for a jump, not a speed; until two agree |
| 5 | +it is real time's. An unsynced site reads wall time. Every answer of a site carries the time it answered at as ``X-Universe-Now``, |
| 6 | +RFC3339 in UTC. ``sync_time`` may also name the universe's time zone, an IANA name, which the clock keeps for the site |
| 7 | +to show local times in; the time itself stays UTC.""" |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import asyncio |
| 11 | +import datetime |
| 12 | +import json |
| 13 | +import logging |
| 14 | +import time |
| 15 | + |
| 16 | +import httpx |
| 17 | + |
| 18 | +logger = logging.getLogger(__name__) |
| 19 | + |
| 20 | +CLOCK_EXTENSION_URI = "urn:agentenv:clock/v1" |
| 21 | +UNIVERSE_NOW_HEADER = "X-Universe-Now" |
| 22 | +REFRESH_S = 1.0 |
| 23 | +READ_TIMEOUT_S = 5.0 |
| 24 | +RATE_AGREEMENT = 0.1 |
| 25 | + |
| 26 | + |
| 27 | +def iso(moment: datetime.datetime) -> str: |
| 28 | + return moment.astimezone(datetime.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") |
| 29 | + |
| 30 | + |
| 31 | +def parse_time(value: str) -> datetime.datetime: |
| 32 | + moment = datetime.datetime.fromisoformat(value.replace("Z", "+00:00")) |
| 33 | + return moment if moment.tzinfo else moment.replace(tzinfo=datetime.timezone.utc) |
| 34 | + |
| 35 | + |
| 36 | +class UniverseClock: |
| 37 | + """The time a site answers with: wall time until ``sync`` names a gateway clock, that clock's after.""" |
| 38 | + |
| 39 | + def __init__(self) -> None: |
| 40 | + self.url: str | None = None |
| 41 | + self.timezone: str | None = None |
| 42 | + self._virtual: datetime.datetime | None = None |
| 43 | + self._read_at = 0.0 |
| 44 | + self._tried_at = 0.0 |
| 45 | + self._rate = 1.0 |
| 46 | + self._measured: float | None = None |
| 47 | + self._lock: asyncio.Lock | None = None |
| 48 | + |
| 49 | + @property |
| 50 | + def synced(self) -> bool: |
| 51 | + return self._virtual is not None |
| 52 | + |
| 53 | + def now(self) -> datetime.datetime: |
| 54 | + if self._virtual is None: |
| 55 | + return datetime.datetime.now(datetime.timezone.utc) |
| 56 | + return self._virtual + datetime.timedelta(seconds=(time.monotonic() - self._read_at) * self._rate) |
| 57 | + |
| 58 | + async def sync(self, url: str, timezone: str | None = None) -> datetime.datetime: |
| 59 | + """Follow the clock at ``url`` from now on, in ``timezone`` (none when the sync names none); raises when it |
| 60 | + can't be read, keeping the clock and zone it followed. It waits for a refresh reading the clock it followed, |
| 61 | + so that read never lands on the new clock.""" |
| 62 | + async with self._reading(): |
| 63 | + virtual = await _read(url) |
| 64 | + self.url, self._virtual, self._rate, self._measured = url, virtual, 1.0, None |
| 65 | + self.timezone = timezone |
| 66 | + self._read_at = self._tried_at = time.monotonic() |
| 67 | + return virtual |
| 68 | + |
| 69 | + async def refresh(self) -> None: |
| 70 | + """Read the synced clock again when the last read is a second old; a failed read keeps extrapolating.""" |
| 71 | + if self.url is None or time.monotonic() - self._tried_at < REFRESH_S: |
| 72 | + return |
| 73 | + async with self._reading(): |
| 74 | + started = time.monotonic() |
| 75 | + if started - self._tried_at < REFRESH_S: |
| 76 | + return |
| 77 | + self._tried_at = started |
| 78 | + try: |
| 79 | + virtual = await _read(self.url) |
| 80 | + except Exception as e: |
| 81 | + logger.debug("reading the universe's clock at %s failed: %r", self.url, e) |
| 82 | + return |
| 83 | + read_at = time.monotonic() |
| 84 | + if self._virtual is not None and read_at > self._read_at: |
| 85 | + measured = max(0.0, (virtual - self._virtual).total_seconds() / (read_at - self._read_at)) |
| 86 | + if self._measured is not None and abs(measured - self._measured) <= RATE_AGREEMENT * max(measured, self._measured, 1.0): |
| 87 | + self._rate = measured |
| 88 | + self._measured = measured |
| 89 | + self._virtual, self._read_at = virtual, read_at |
| 90 | + |
| 91 | + def _reading(self) -> asyncio.Lock: |
| 92 | + """The lock a sync and a refresh each read the clock under.""" |
| 93 | + self._lock = self._lock or asyncio.Lock() |
| 94 | + return self._lock |
| 95 | + |
| 96 | + |
| 97 | +async def _read(url: str) -> datetime.datetime: |
| 98 | + async with httpx.AsyncClient() as client: |
| 99 | + response = await client.get(url, timeout=READ_TIMEOUT_S) |
| 100 | + response.raise_for_status() |
| 101 | + return parse_time(response.json()["virtual_time"]) |
| 102 | + |
| 103 | + |
| 104 | +def clock_patch_script(now: datetime.datetime) -> bytes: |
| 105 | + """An inline script that shifts the page's ``Date`` to the universe's time ``now``, and follows the |
| 106 | + ``X-Universe-Now`` header of every ``fetch`` the page makes after. The ``Date`` it puts in place answers called, |
| 107 | + with the time's string, as constructed, and keeps ``Date.parse``, ``Date.UTC`` and ``instanceof Date``.""" |
| 108 | + return ("<script>(function(){var D=Date,o=%s-D.now();function n(){return D.now()+o}" |
| 109 | + "function U(){if(!new.target)return new D(n()).toString();" |
| 110 | + "return Reflect.construct(D,arguments.length?[].slice.call(arguments):[n()],new.target)}" |
| 111 | + "Object.setPrototypeOf(U,D);U.prototype=D.prototype;D.prototype.constructor=U;U.now=n;U.parse=D.parse;" |
| 112 | + "U.UTC=D.UTC;window.Date=U;var f=window.fetch;if(f)window.fetch=function(){return f.apply(this,arguments)" |
| 113 | + ".then(function(r){var t=D.parse(r.headers.get(%s)||'');if(!isNaN(t))o=t-D.now();return r})}})();" |
| 114 | + "</script>" % (int(now.timestamp() * 1000), json.dumps(UNIVERSE_NOW_HEADER))).encode() |
0 commit comments