@fireemu/darwin-arm64 0.68.0 → 0.69.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @fireemu/darwin-arm64
2
2
 
3
3
  The [fireemu](https://www.npmjs.com/package/fireemu) daemon built for `darwin-arm64`
4
- (Rust target `aarch64-apple-darwin`), version 0.68.0.
4
+ (Rust target `aarch64-apple-darwin`), version 0.69.0.
5
5
 
6
6
  macOS 13 or newer on Apple silicon.
7
7
 
package/bin/fireemu CHANGED
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/bin/fireemu
3
- size: 38718112 bytes
4
- sha256: 8092674293e0e0151aac68f94528ef0108491b3e7db1fb968149e175b3725a3c
3
+ size: 38900032 bytes
4
+ sha256: a72576b1028860d4f415659386dc9fabf20b9ea38b215ce14e3a747cd4206282
@@ -0,0 +1,154 @@
1
+ """Opt-in virtual application clock for the fireemu Python Functions runner.
2
+
3
+ Follows the same `FIREEMU_CLOCK_JSON` and `clock:set` frame protocol as `tools/runner-node/clock.mjs`.
4
+ When `date == "virtual"`, patches `time.time`, `time.time_ns`, `datetime.datetime.now`,
5
+ `datetime.datetime.utcnow`, and `datetime.date.today` so Python functions observe deterministic
6
+ emulator time while keeping monotonic timers and runner lifecycle timeouts on real time.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import datetime as _datetime_mod
12
+ import json
13
+ import threading
14
+ import time as _time_mod
15
+ from typing import Any
16
+
17
+ _NANOS_PER_SEC = 1_000_000_000
18
+ _REAL_TIME = _time_mod.time
19
+ _REAL_TIME_NS = _time_mod.time_ns
20
+ _REAL_MONOTONIC_NS = _time_mod.monotonic_ns
21
+ _REAL_DATETIME = _datetime_mod.datetime
22
+ _REAL_DATE = _datetime_mod.date
23
+
24
+
25
+ def _parse_nanos(value: Any, name: str) -> int:
26
+ if isinstance(value, int) and not isinstance(value, bool):
27
+ return value
28
+ if isinstance(value, str):
29
+ stripped = value.strip()
30
+ if stripped and (stripped.isdigit() or (stripped.startswith("-") and stripped[1:].isdigit())):
31
+ return int(stripped)
32
+ raise ValueError(f"invalid clock {name}: {value!r}")
33
+
34
+
35
+ class RuntimeClock:
36
+ """Thread-safe virtual clock state synchronized with the fireemu daemon."""
37
+
38
+ def __init__(self, options: dict[str, Any] | None = None) -> None:
39
+ opts = options or {}
40
+ date_policy = opts.get("date", "real")
41
+ if date_policy not in ("real", "virtual"):
42
+ raise ValueError(f"invalid runtime clock date policy: {date_policy!r}")
43
+ self._lock = threading.Lock()
44
+ self.date_virtual = date_policy == "virtual"
45
+ self._instant_nanos = _parse_nanos(opts.get("instantNanos", "0"), "instantNanos")
46
+ self._elapsed_nanos = _parse_nanos(opts.get("elapsedNanos", "0"), "elapsedNanos")
47
+ if self._elapsed_nanos < 0:
48
+ raise ValueError("negative timer elapsed time")
49
+ self._following = bool(opts.get("following", False))
50
+ self._anchor_monotonic = _REAL_MONOTONIC_NS()
51
+ self._revision = _parse_nanos(opts.get("revision", "0"), "revision")
52
+ self._installed = False
53
+
54
+ def current_instant_nanos(self) -> int:
55
+ with self._lock:
56
+ return self._instant_unlocked()
57
+
58
+ def _instant_unlocked(self) -> int:
59
+ if not self._following:
60
+ return self._instant_nanos
61
+ delta = max(0, _REAL_MONOTONIC_NS() - self._anchor_monotonic)
62
+ return self._instant_nanos + delta
63
+
64
+ def _elapsed_unlocked(self) -> int:
65
+ if not self._following:
66
+ return self._elapsed_nanos
67
+ delta = max(0, _REAL_MONOTONIC_NS() - self._anchor_monotonic)
68
+ return self._elapsed_nanos + delta
69
+
70
+ def update(self, frame: dict[str, Any]) -> dict[str, Any]:
71
+ revision = _parse_nanos(frame.get("revision"), "revision")
72
+ instant = _parse_nanos(frame.get("instantNanos"), "instantNanos")
73
+ elapsed = _parse_nanos(frame.get("elapsedNanos", "0"), "elapsedNanos")
74
+ if elapsed < 0:
75
+ raise ValueError("negative timer elapsed time")
76
+ following = bool(frame.get("following", False))
77
+ with self._lock:
78
+ if revision < self._revision:
79
+ raise ValueError("stale clock revision")
80
+ self._instant_nanos = instant
81
+ self._elapsed_nanos = elapsed
82
+ self._following = following
83
+ self._anchor_monotonic = _REAL_MONOTONIC_NS()
84
+ self._revision = revision
85
+ return self._status_unlocked()
86
+
87
+ def status(self) -> dict[str, Any]:
88
+ with self._lock:
89
+ return self._status_unlocked()
90
+
91
+ def _status_unlocked(self) -> dict[str, Any]:
92
+ return {
93
+ "executed": 0,
94
+ "pending": 0,
95
+ "due": 0,
96
+ "instantNanos": str(self._instant_unlocked()),
97
+ "elapsedNanos": str(self._elapsed_unlocked()),
98
+ }
99
+
100
+ def install(self) -> None:
101
+ if not self.date_virtual or self._installed:
102
+ return
103
+ self._installed = True
104
+ clock = self
105
+
106
+ def _virtual_time_ns() -> int:
107
+ return clock.current_instant_nanos()
108
+
109
+ def _virtual_time() -> float:
110
+ return clock.current_instant_nanos() / _NANOS_PER_SEC
111
+
112
+ class _VirtualDatetime(_REAL_DATETIME):
113
+ @classmethod
114
+ def now(cls, tz=None):
115
+ seconds, nanos = divmod(clock.current_instant_nanos(), _NANOS_PER_SEC)
116
+ return cls.fromtimestamp(seconds, tz=tz).replace(microsecond=nanos // 1_000)
117
+
118
+ @classmethod
119
+ def utcnow(cls):
120
+ return cls.now(_datetime_mod.timezone.utc).replace(tzinfo=None)
121
+
122
+ @classmethod
123
+ def today(cls):
124
+ return cls.now()
125
+
126
+ class _VirtualDate(_REAL_DATE):
127
+ @classmethod
128
+ def today(cls):
129
+ dt = _VirtualDatetime.now()
130
+ return cls(dt.year, dt.month, dt.day)
131
+
132
+ _time_mod.time_ns = _virtual_time_ns
133
+ _time_mod.time = _virtual_time
134
+ _datetime_mod.datetime = _VirtualDatetime # type: ignore[misc]
135
+ _datetime_mod.date = _VirtualDate # type: ignore[misc]
136
+
137
+ def uninstall(self) -> None:
138
+ if not self._installed:
139
+ return
140
+ self._installed = False
141
+ _time_mod.time_ns = _REAL_TIME_NS
142
+ _time_mod.time = _REAL_TIME
143
+ _datetime_mod.datetime = _REAL_DATETIME # type: ignore[misc]
144
+ _datetime_mod.date = _REAL_DATE # type: ignore[misc]
145
+
146
+
147
+ def from_environment(env: dict[str, str] | Any) -> RuntimeClock:
148
+ raw = env.get("FIREEMU_CLOCK_JSON")
149
+ if not raw:
150
+ return RuntimeClock({})
151
+ parsed = json.loads(raw)
152
+ if not isinstance(parsed, dict):
153
+ raise ValueError("FIREEMU_CLOCK_JSON must be a JSON object")
154
+ return RuntimeClock(parsed)
@@ -110,6 +110,13 @@ def _decode_message(payload: bytes) -> dict:
110
110
  raise ProtocolError("message object")
111
111
  if message.get("type") == "shutdown":
112
112
  return message
113
+ if message.get("type") == "clock:set":
114
+ if (
115
+ not all(_text(message.get(key)) for key in ("invocationId", "instantNanos", "elapsedNanos", "revision"))
116
+ or not isinstance(message.get("following"), bool)
117
+ ):
118
+ raise ProtocolError("message fields")
119
+ return message
113
120
  if (
114
121
  message.get("type") != "invoke"
115
122
  or not _text(message.get("invocationId"))
@@ -7,6 +7,7 @@ import sys
7
7
  import traceback
8
8
 
9
9
  from . import appcheck, blocking
10
+ from .clock import RuntimeClock, from_environment as clock_from_environment
10
11
  from .dispatch import Dispatcher
11
12
  from .environment import EnvironmentGate, load_local_secrets
12
13
  from .framing import FrameWriter, ProtocolError, read_frame
@@ -32,6 +33,28 @@ def load_codebase(source: str) -> dict:
32
33
  return serving.get_functions()
33
34
 
34
35
 
36
+ def _start_debugpy_from_environment(env) -> int | None:
37
+ raw = env.get("FIREEMU_PYTHON_INSPECT_PORT")
38
+ if not raw:
39
+ return None
40
+ try:
41
+ requested_port = int(raw)
42
+ except ValueError:
43
+ sys.stderr.write(f"[functions] invalid FIREEMU_PYTHON_INSPECT_PORT value: {raw!r}\n")
44
+ return None
45
+ try:
46
+ import debugpy # type: ignore[import-not-found]
47
+ except ImportError:
48
+ sys.stderr.write(
49
+ "[functions] debugpy is not installed in the Python codebase venv; "
50
+ "install debugpy to attach a Python debugger\n"
51
+ )
52
+ return None
53
+ _host, bound_port = debugpy.listen(("127.0.0.1", requested_port))
54
+ sys.stderr.write(f"[functions] debugpy listening on 127.0.0.1:{bound_port}\n")
55
+ return int(bound_port)
56
+
57
+
35
58
  def serve(
36
59
  functions: dict,
37
60
  codebase: str,
@@ -42,11 +65,14 @@ def serve(
42
65
  app_check_verified: bool = False,
43
66
  blocking_verified: bool = False,
44
67
  function: str | None = None,
68
+ runtime_clock: RuntimeClock | None = None,
69
+ inspector_port: int | None = None,
45
70
  ) -> int:
46
71
  """Says hello, then serves frames from `stdin` until `shutdown` or the end of the stream.
47
72
 
48
73
  With `function`, the runner is that function's instance: only it is announced and served.
49
74
  """
75
+ clock = runtime_clock if runtime_clock is not None else RuntimeClock({})
50
76
  manifest = build_manifest(functions, app_check_verified)
51
77
  if function is not None:
52
78
  if not any(spec["name"] == function for spec in manifest["functions"]):
@@ -59,22 +85,45 @@ def serve(
59
85
  port = None
60
86
  if any(spec["trigger"]["type"] in HTTP_TRIGGERS for spec in manifest["functions"]):
61
87
  server, port = start_server(functions, manifest, secret, gate, function is not None)
62
- writer.write(
63
- {
64
- "type": "hello",
65
- "runner": "python",
66
- "codebase": codebase,
67
- "version": platform.python_version(),
68
- "httpPort": port,
69
- "manifest": manifest,
70
- }
71
- )
88
+ hello = {
89
+ "type": "hello",
90
+ "runner": "python",
91
+ "clock": {"version": 1, "date": True, "timers": False},
92
+ "codebase": codebase,
93
+ "version": platform.python_version(),
94
+ "httpPort": port,
95
+ "manifest": manifest,
96
+ }
97
+ if inspector_port is not None:
98
+ hello["inspectorPort"] = inspector_port
99
+ writer.write(hello)
72
100
  dispatcher = Dispatcher(functions, manifest, writer, gate, fixed_identity=function is not None)
73
101
  try:
74
102
  while True:
75
103
  message = read_frame(stdin)
76
104
  if message is None or message["type"] == "shutdown":
77
105
  return 0
106
+ if message["type"] == "clock:set":
107
+ try:
108
+ status = clock.update(message)
109
+ writer.write(
110
+ {
111
+ "type": "result",
112
+ "invocationId": message.get("invocationId"),
113
+ "ok": True,
114
+ "timers": status,
115
+ }
116
+ )
117
+ except Exception as error:
118
+ writer.write(
119
+ {
120
+ "type": "result",
121
+ "invocationId": message.get("invocationId"),
122
+ "ok": False,
123
+ "error": str(error),
124
+ }
125
+ )
126
+ continue
78
127
  if not dispatcher.reserve():
79
128
  sys.stderr.write("[functions] too many active invocations\n")
80
129
  return 2
@@ -103,6 +152,15 @@ def run(argv) -> int:
103
152
  except ValueError as error:
104
153
  sys.stderr.write(f"[functions] {error}\n")
105
154
  return 1
155
+ # Install virtual application clock (if requested via FIREEMU_CLOCK_JSON) and optional
156
+ # debugpy listener before importing user code.
157
+ try:
158
+ runtime_clock = clock_from_environment(os.environ)
159
+ runtime_clock.install()
160
+ except (ValueError, TypeError) as error:
161
+ sys.stderr.write(f"[functions] {error}\n")
162
+ return 1
163
+ inspector_port = _start_debugpy_from_environment(os.environ)
106
164
  # Before any user code runs, so the Admin SDK's App Check service is built against the emulator's keys.
107
165
  app_check_verified = appcheck.install_from_environment(os.environ)
108
166
  try:
@@ -116,7 +174,9 @@ def run(argv) -> int:
116
174
  traceback.print_exc()
117
175
  return 1
118
176
  # A dedicated runner (`--function`) names its function; otherwise the call is the one the daemon has always seen.
119
- options = {} if args.function is None else {"function": args.function}
177
+ options: dict = {"runtime_clock": runtime_clock, "inspector_port": inspector_port}
178
+ if args.function is not None:
179
+ options["function"] = args.function
120
180
  if blocking_verified:
121
181
  return serve(functions, args.codebase, secret, sys.stdin.buffer, writer, gate, app_check_verified, blocking_verified=True, **options)
122
182
  return serve(functions, args.codebase, secret, sys.stdin.buffer, writer, gate, app_check_verified, **options)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fireemu/darwin-arm64",
3
- "version": "0.68.0",
3
+ "version": "0.69.0",
4
4
  "description": "The fireemu daemon for darwin-arm64",
5
5
  "homepage": "https://fireemu.github.io/fireemu/",
6
6
  "repository": {