@fireemu/darwin-arm64 0.68.0 → 0.70.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 +1 -1
- package/bin/fireemu +2 -2
- package/bin/runner-node/clock.mjs +93 -27
- package/bin/runner-node/index.mjs +56 -15
- package/bin/runner-python/fireemu_runner/clock.py +154 -0
- package/bin/runner-python/fireemu_runner/framing.py +7 -0
- package/bin/runner-python/fireemu_runner/main.py +71 -11
- package/package.json +1 -1
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.
|
|
4
|
+
(Rust target `aarch64-apple-darwin`), version 0.70.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:
|
|
4
|
-
sha256:
|
|
3
|
+
size: 38916576 bytes
|
|
4
|
+
sha256: 6e5911ba57b52c00880cd8160e4cb7c20532945b2d36545f8f8d4a67a5ff8d47
|
|
@@ -114,14 +114,70 @@ export function createRuntimeClock({date = 'real', timers: timerPolicy = 'real',
|
|
|
114
114
|
}
|
|
115
115
|
|
|
116
116
|
function cancel(value) {
|
|
117
|
-
|
|
118
|
-
|
|
117
|
+
if (value instanceof Timer) {
|
|
118
|
+
value.cancelled = true;
|
|
119
|
+
queue.delete(value.id);
|
|
120
|
+
handles.delete(value.id);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
if (typeof value === 'object' && value !== null) {
|
|
124
|
+
native.clearTimeout(value);
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
const handle = handles.get(Number(value));
|
|
128
|
+
if (!handle) {
|
|
129
|
+
native.clearTimeout(value);
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
handle.cancelled = true;
|
|
133
|
+
queue.delete(handle.id);
|
|
134
|
+
handles.delete(handle.id);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function cancelInterval(value) {
|
|
138
|
+
if (value instanceof Timer) {
|
|
139
|
+
value.cancelled = true;
|
|
140
|
+
queue.delete(value.id);
|
|
141
|
+
handles.delete(value.id);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (typeof value === 'object' && value !== null) {
|
|
145
|
+
native.clearInterval(value);
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const handle = handles.get(Number(value));
|
|
149
|
+
if (!handle) {
|
|
150
|
+
native.clearInterval(value);
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
119
153
|
handle.cancelled = true;
|
|
120
154
|
queue.delete(handle.id);
|
|
121
155
|
handles.delete(handle.id);
|
|
122
156
|
}
|
|
123
157
|
|
|
158
|
+
// Internal gRPC transport timers (BackoffTimeout, ResolvingCall deadlines, subchannel
|
|
159
|
+
// keepalive/cleanup) live inside `@grpc/grpc-js`. Freezing them under a non-following
|
|
160
|
+
// virtual clock deadlocks Admin SDK calls inside Functions triggers. Exempt only when
|
|
161
|
+
// the immediate caller frame outside `clock.mjs` belongs to `@grpc/grpc-js`.
|
|
162
|
+
function isTransportTimerCaller() {
|
|
163
|
+
const stack = new Error().stack;
|
|
164
|
+
if (typeof stack !== 'string') return false;
|
|
165
|
+
const lines = stack.split('\n');
|
|
166
|
+
for (let i = 1; i < lines.length; i++) {
|
|
167
|
+
const normalized = lines[i].replace(/\\/g, '/');
|
|
168
|
+
if (normalized.includes('/runner-node/clock.mjs')) continue;
|
|
169
|
+
return (
|
|
170
|
+
normalized.includes('node_modules/') &&
|
|
171
|
+
/(?:@grpc[+/]grpc-js|google-gax|@google-cloud[+/](?:firestore|storage)|gaxios|google-auth-library)\//.test(
|
|
172
|
+
normalized,
|
|
173
|
+
)
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
|
|
124
179
|
function promiseTimeout(duration, value, config = {}) {
|
|
180
|
+
if (isTransportTimerCaller()) return nativePromises.setTimeout(duration, value, config);
|
|
125
181
|
try { options(config); } catch (error) { return Promise.reject(error); }
|
|
126
182
|
if (config.signal?.aborted) return Promise.reject(abortError(config.signal.reason));
|
|
127
183
|
return new Promise((resolve, reject) => {
|
|
@@ -140,29 +196,32 @@ export function createRuntimeClock({date = 'real', timers: timerPolicy = 'real',
|
|
|
140
196
|
});
|
|
141
197
|
}
|
|
142
198
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
199
|
+
function promiseInterval(duration, value, config = {}) {
|
|
200
|
+
if (isTransportTimerCaller()) return nativePromises.setInterval(duration, value, config);
|
|
201
|
+
return (async function* () {
|
|
202
|
+
options(config);
|
|
203
|
+
if (config.signal?.aborted) throw abortError(config.signal.reason);
|
|
204
|
+
let count = 0;
|
|
205
|
+
let wake;
|
|
206
|
+
let aborted = false;
|
|
207
|
+
const handle = schedule(() => { count++; wake?.(); }, duration, [], true);
|
|
208
|
+
if (config.ref === false) handle.unref();
|
|
209
|
+
const abort = () => { aborted = true; cancel(handle); wake?.(); };
|
|
210
|
+
config.signal?.addEventListener('abort', abort, {once:true});
|
|
211
|
+
try {
|
|
212
|
+
while (!aborted) {
|
|
213
|
+
if (count === 0) await new Promise(resolve => {wake = resolve;});
|
|
214
|
+
wake = undefined;
|
|
215
|
+
if (aborted) break;
|
|
216
|
+
count--;
|
|
217
|
+
yield value;
|
|
218
|
+
}
|
|
219
|
+
throw abortError(config.signal.reason);
|
|
220
|
+
} finally {
|
|
221
|
+
cancel(handle);
|
|
222
|
+
config.signal?.removeEventListener('abort', abort);
|
|
160
223
|
}
|
|
161
|
-
|
|
162
|
-
} finally {
|
|
163
|
-
cancel(handle);
|
|
164
|
-
config.signal?.removeEventListener('abort', abort);
|
|
165
|
-
}
|
|
224
|
+
})();
|
|
166
225
|
}
|
|
167
226
|
|
|
168
227
|
function now() {
|
|
@@ -199,9 +258,16 @@ export function createRuntimeClock({date = 'real', timers: timerPolicy = 'real',
|
|
|
199
258
|
},
|
|
200
259
|
});
|
|
201
260
|
const virtual = {
|
|
202
|
-
setTimeout: (callback, duration, ...args) =>
|
|
203
|
-
|
|
204
|
-
|
|
261
|
+
setTimeout: (callback, duration, ...args) =>
|
|
262
|
+
isTransportTimerCaller()
|
|
263
|
+
? native.setTimeout(callback, duration, ...args)
|
|
264
|
+
: schedule(callback, duration, args, false),
|
|
265
|
+
setInterval: (callback, duration, ...args) =>
|
|
266
|
+
isTransportTimerCaller()
|
|
267
|
+
? native.setInterval(callback, duration, ...args)
|
|
268
|
+
: schedule(callback, duration, args, true),
|
|
269
|
+
clearTimeout: cancel,
|
|
270
|
+
clearInterval: cancelInterval,
|
|
205
271
|
};
|
|
206
272
|
Object.defineProperty(virtual.setTimeout, promisify.custom, {value:promiseTimeout});
|
|
207
273
|
|
|
@@ -518,13 +518,27 @@ function rejectAsyncOption(value, field) {
|
|
|
518
518
|
return value;
|
|
519
519
|
}
|
|
520
520
|
|
|
521
|
+
function isResetValue(value) {
|
|
522
|
+
if (value == null || typeof value !== "object") return false;
|
|
523
|
+
if (value[Symbol.for("firebase-functions:ResetValue:Tag")] === true) return true;
|
|
524
|
+
// firebase-functions 6.x ResetValue predates the symbol tag: `constructor.name === "ResetValue"`
|
|
525
|
+
// and `toJSON() === null`. Never read `.value` here so single-read Expression accessors stay intact.
|
|
526
|
+
if (
|
|
527
|
+
value.constructor?.name === "ResetValue" &&
|
|
528
|
+
typeof value.toJSON === "function" &&
|
|
529
|
+
value.toJSON() === null
|
|
530
|
+
) {
|
|
531
|
+
return true;
|
|
532
|
+
}
|
|
533
|
+
return false;
|
|
534
|
+
}
|
|
535
|
+
|
|
521
536
|
// SDK endpoint options keep Expression objects until the local runtime resolves
|
|
522
537
|
// them. JSON/toString encode a deployment expression, not its runtime value.
|
|
523
538
|
// Match the existing numeric-option `.value()` protocol, but never read its
|
|
524
539
|
// accessor twice or coerce an unresolved value into false/true/default.
|
|
525
540
|
function resolvedOption(value, field) {
|
|
526
|
-
if (value == null) return undefined;
|
|
527
|
-
if (value?.[Symbol.for("firebase-functions:ResetValue:Tag")] === true) return undefined;
|
|
541
|
+
if (value == null || isResetValue(value)) return undefined;
|
|
528
542
|
if (typeof value === "object") {
|
|
529
543
|
const evaluate = value.value;
|
|
530
544
|
if (typeof evaluate === "function") {
|
|
@@ -573,7 +587,7 @@ function resolvedNonNegativeInteger(value, field) {
|
|
|
573
587
|
// Do not stringify an Expression (that emits its deployment representation),
|
|
574
588
|
// coerce malformed values, or retain a caller-owned map with a later toJSON.
|
|
575
589
|
function triggerRecord(value, field) {
|
|
576
|
-
if (value == null || value
|
|
590
|
+
if (value == null || isResetValue(value)) {
|
|
577
591
|
return Object.create(null);
|
|
578
592
|
}
|
|
579
593
|
rejectAsyncOption(value, field);
|
|
@@ -690,10 +704,14 @@ function describeSchedule(base, value) {
|
|
|
690
704
|
function platformOptions(ep) {
|
|
691
705
|
if (!ep) return undefined;
|
|
692
706
|
const options = {};
|
|
693
|
-
const
|
|
707
|
+
const rawPreserveExternalChanges =
|
|
694
708
|
ep.preserveExternalChanges ??
|
|
695
709
|
(ep.platform === "gcfv2" ? discoveredGlobalOptions.preserveExternalChanges : undefined);
|
|
696
|
-
|
|
710
|
+
const preserveExternalChanges = resolvedOption(
|
|
711
|
+
rawPreserveExternalChanges,
|
|
712
|
+
"preserveExternalChanges",
|
|
713
|
+
);
|
|
714
|
+
if (preserveExternalChanges !== undefined)
|
|
697
715
|
options.preserveExternalChanges = Boolean(preserveExternalChanges);
|
|
698
716
|
const availableMemoryMb = resolvedNonNegativeInteger(ep.availableMemoryMb, "availableMemoryMb");
|
|
699
717
|
if (availableMemoryMb !== undefined) options.availableMemoryMb = availableMemoryMb;
|
|
@@ -701,16 +719,26 @@ function platformOptions(ep) {
|
|
|
701
719
|
if (minInstances !== undefined) options.minInstances = minInstances;
|
|
702
720
|
const maxInstances = resolvedNonNegativeInteger(ep.maxInstances, "maxInstances");
|
|
703
721
|
if (maxInstances !== undefined) options.maxInstances = maxInstances;
|
|
704
|
-
|
|
722
|
+
const ingressSettings = resolvedOption(ep.ingressSettings, "ingressSettings");
|
|
723
|
+
if (ingressSettings !== undefined) options.ingressSettings = ingressSettings;
|
|
705
724
|
if (ep.httpsTrigger?.invoker?.length) options.invoker = ep.httpsTrigger.invoker;
|
|
706
|
-
|
|
707
|
-
if (
|
|
708
|
-
|
|
709
|
-
if (
|
|
725
|
+
const serviceAccountEmail = resolvedOption(ep.serviceAccountEmail, "serviceAccountEmail");
|
|
726
|
+
if (serviceAccountEmail !== undefined) options.serviceAccountEmail = serviceAccountEmail;
|
|
727
|
+
const vpc = resolvedOption(ep.vpc, "vpc");
|
|
728
|
+
if (vpc && typeof vpc === "object") {
|
|
729
|
+
const vpcConnector = resolvedOption(vpc.connector, "vpc.connector");
|
|
730
|
+
if (vpcConnector !== undefined) options.vpcConnector = vpcConnector;
|
|
731
|
+
const vpcEgressSettings = resolvedOption(vpc.egressSettings, "vpc.egressSettings");
|
|
732
|
+
if (vpcEgressSettings !== undefined) options.vpcEgressSettings = vpcEgressSettings;
|
|
733
|
+
}
|
|
734
|
+
if (ep.labels && !isResetValue(ep.labels) && Object.keys(ep.labels).length > 0) {
|
|
735
|
+
options.labels = ep.labels;
|
|
736
|
+
}
|
|
710
737
|
if (ep.platform === "gcfv2") {
|
|
711
|
-
|
|
712
|
-
if (
|
|
713
|
-
|
|
738
|
+
const cpu = resolvedOption(ep.cpu, "cpu");
|
|
739
|
+
if (cpu !== undefined) options.cpu = String(cpu);
|
|
740
|
+
if (vpc && typeof vpc === "object" && Array.isArray(vpc.networkInterfaces))
|
|
741
|
+
options.networkInterfaces = vpc.networkInterfaces;
|
|
714
742
|
}
|
|
715
743
|
if (Array.isArray(ep.secretEnvironmentVariables)) {
|
|
716
744
|
options.secrets = ep.secretEnvironmentVariables.map((secret) => secret.key).filter(Boolean);
|
|
@@ -1438,8 +1466,21 @@ async function makeHttpServer(functions, manifest) {
|
|
|
1438
1466
|
? blockingFailure(error, HttpsErrors)
|
|
1439
1467
|
: invocationFailure(error);
|
|
1440
1468
|
try {
|
|
1441
|
-
const
|
|
1442
|
-
|
|
1469
|
+
const expectedHttpsError =
|
|
1470
|
+
blocking &&
|
|
1471
|
+
Array.isArray(HttpsErrors) &&
|
|
1472
|
+
HttpsErrors.some((Ctor) => typeof Ctor === "function" && error instanceof Ctor) &&
|
|
1473
|
+
!(
|
|
1474
|
+
failure.canonicalName === "UNAVAILABLE" &&
|
|
1475
|
+
failure.status === 503 &&
|
|
1476
|
+
failure.message === "An unexpected error occurred."
|
|
1477
|
+
);
|
|
1478
|
+
if (expectedHttpsError) {
|
|
1479
|
+
log("warn", `${spec.name}: ${failure.canonicalName}: ${failure.message}`, undefined, spec.name);
|
|
1480
|
+
} else {
|
|
1481
|
+
const diagnostic = blocking ? invocationFailure(error).diagnostic : failure.diagnostic;
|
|
1482
|
+
log("error", `${spec.name}: ${diagnostic}`, undefined, spec.name);
|
|
1483
|
+
}
|
|
1443
1484
|
} catch {
|
|
1444
1485
|
// Diagnostics cannot suppress the already classified response.
|
|
1445
1486
|
}
|
|
@@ -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
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
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 = {
|
|
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)
|