@fireemu/darwin-arm64 0.49.0 → 0.51.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/callable-app-check-loader.mjs +1 -1
- package/bin/runner-node/callable-app-check.mjs +9 -5
- package/bin/runner-node/index.mjs +32 -1
- package/bin/runner-node/nested-callable.mjs +92 -0
- package/bin/runner-node/task-auth.mjs +53 -0
- package/bin/runner-python/fireemu_runner/dispatch.py +16 -6
- package/bin/runner-python/fireemu_runner/main.py +27 -6
- package/bin/runner-python/fireemu_runner/serve.py +19 -8
- 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.51.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: 38369776 bytes
|
|
4
|
+
sha256: 52aec9a4febfabab0a1f65229c629e1ddfac507b7b9af878be91778327b1079f
|
|
@@ -28,7 +28,7 @@ function transform(source, name) {
|
|
|
28
28
|
next = replaceOnce(
|
|
29
29
|
next,
|
|
30
30
|
"function encodeSSE(data) {",
|
|
31
|
-
`function onCallHandler(options, handler, version) {\n\tconst fn = fireemuOriginalOnCallHandler(options, handler, version);\n\
|
|
31
|
+
`function onCallHandler(options, handler, version) {\n\tconst fn = fireemuOriginalOnCallHandler(options, handler, version);\n\treturn ${REGISTRY}.observe(fn, options);\n}\nfunction encodeSSE(data) {`,
|
|
32
32
|
"encodeSSE",
|
|
33
33
|
);
|
|
34
34
|
return next;
|
|
@@ -28,6 +28,8 @@ import { createRequire, register } from "node:module";
|
|
|
28
28
|
import { dirname, join, parse as parsePath } from "node:path";
|
|
29
29
|
import { pathToFileURL } from "node:url";
|
|
30
30
|
|
|
31
|
+
import { guardCallableWrapper } from "./nested-callable.mjs";
|
|
32
|
+
|
|
31
33
|
/// `firebase-functions` majors whose callable internals this instrumentation is written for.
|
|
32
34
|
const SUPPORTED_MAJORS = [6, 7];
|
|
33
35
|
|
|
@@ -187,15 +189,19 @@ export function instrumentCallables(sourceDir) {
|
|
|
187
189
|
].map((v) => String(v ?? "").toLowerCase());
|
|
188
190
|
|
|
189
191
|
const options = new WeakMap();
|
|
192
|
+
// Returns the callable wrapper to use: the guarded wrapper, which refuses a credential the daemon
|
|
193
|
+
// did not verify when it runs inside a non-callable endpoint (nested-callable.mjs).
|
|
190
194
|
const observe = (fn, opts) => {
|
|
191
|
-
if (typeof fn !== "function" || options.has(fn)) return;
|
|
195
|
+
if (typeof fn !== "function" || options.has(fn)) return fn;
|
|
196
|
+
const guarded = guardCallableWrapper(fn);
|
|
192
197
|
options.set(
|
|
193
|
-
|
|
198
|
+
guarded,
|
|
194
199
|
Object.freeze({
|
|
195
200
|
enforceAppCheck: (opts ?? {}).enforceAppCheck === true,
|
|
196
201
|
consumeAppCheckToken: consumeState((opts ?? {}).consumeAppCheckToken),
|
|
197
202
|
}),
|
|
198
203
|
);
|
|
204
|
+
return guarded;
|
|
199
205
|
};
|
|
200
206
|
const carry = (from, to) => {
|
|
201
207
|
if (typeof to === "function" && !options.has(to) && options.has(from)) {
|
|
@@ -205,9 +211,7 @@ export function instrumentCallables(sourceDir) {
|
|
|
205
211
|
|
|
206
212
|
const originalOnCallHandler = loaded.commonHttps.onCallHandler;
|
|
207
213
|
loaded.commonHttps.onCallHandler = function onCallHandler(opts, handler, version_) {
|
|
208
|
-
|
|
209
|
-
observe(fn, opts);
|
|
210
|
-
return fn;
|
|
214
|
+
return observe(originalOnCallHandler.call(this, opts, handler, version_), opts);
|
|
211
215
|
};
|
|
212
216
|
|
|
213
217
|
const originalWrapTrace = loaded.trace.wrapTraceContext;
|
|
@@ -22,10 +22,12 @@ import { createRuntimeClock } from "./clock.mjs";
|
|
|
22
22
|
import { instrumentCallables } from "./callable-app-check.mjs";
|
|
23
23
|
import { createAdminChannel, instrumentAdminAppCheck } from "./admin-app-check.mjs";
|
|
24
24
|
import { removeAppCheckToken, withholdsAppCheckToken } from "./app-check-token.mjs";
|
|
25
|
+
import { markNonCallableRequest } from "./nested-callable.mjs";
|
|
25
26
|
import { blockingFailure } from "./blocking-error.mjs";
|
|
26
27
|
import { blockingEvent, loadIdentityParsers, portedIdentityParsers } from "./blocking-event.mjs";
|
|
27
28
|
import { blockingResult } from "./blocking-response.mjs";
|
|
28
29
|
import { boundLogMessage, createInvocationLogger } from "./log-context.mjs";
|
|
30
|
+
import { installTaskAuthEnvironment, runWithTaskAuth, takeTaskIdentityMarker } from "./task-auth.mjs";
|
|
29
31
|
import { invocationFailure } from "./invocation-error.mjs";
|
|
30
32
|
import { InvocationBudget, readFrames } from "./protocol.mjs";
|
|
31
33
|
import { deliverSchedule, v1ScheduleContext } from "./schedule-delivery.mjs";
|
|
@@ -342,10 +344,11 @@ const invocationLogger = createInvocationLogger((entry) =>
|
|
|
342
344
|
invocationLogger.install();
|
|
343
345
|
|
|
344
346
|
function parseArgs(argv) {
|
|
345
|
-
const out = { source: process.cwd(), codebase: "default" };
|
|
347
|
+
const out = { source: process.cwd(), codebase: "default", function: undefined };
|
|
346
348
|
for (let i = 0; i < argv.length; i++) {
|
|
347
349
|
if (argv[i] === "--source" && argv[i + 1]) out.source = argv[++i];
|
|
348
350
|
else if (argv[i] === "--codebase" && argv[i + 1]) out.codebase = argv[++i];
|
|
351
|
+
else if (argv[i] === "--function" && argv[i + 1]) out.function = argv[++i];
|
|
349
352
|
}
|
|
350
353
|
return out;
|
|
351
354
|
}
|
|
@@ -355,6 +358,7 @@ startupTrace('argv parsed');
|
|
|
355
358
|
const sourceDir = resolve(args.source);
|
|
356
359
|
startupTrace('source resolved');
|
|
357
360
|
process.env.FUNCTIONS_EMULATOR = process.env.FUNCTIONS_EMULATOR || "true";
|
|
361
|
+
installTaskAuthEnvironment();
|
|
358
362
|
process.env.FUNCTION_TARGET = process.env.FUNCTION_TARGET || "";
|
|
359
363
|
process.env.FUNCTION_SIGNATURE_TYPE = process.env.FUNCTION_SIGNATURE_TYPE || "";
|
|
360
364
|
process.env.K_SERVICE = process.env.K_SERVICE || "";
|
|
@@ -382,7 +386,16 @@ function setFunctionIdentity(spec) {
|
|
|
382
386
|
process.env.K_SERVICE = spec?.name ?? "";
|
|
383
387
|
}
|
|
384
388
|
|
|
389
|
+
// A runner started with `--function <name>` (`functions.isolation = "function"`) is one function's instance,
|
|
390
|
+
// as a production instance is: the daemon put FUNCTION_TARGET, FUNCTION_SIGNATURE_TYPE, K_SERVICE and the
|
|
391
|
+
// function's own secrets into its environment at spawn, before any user code loaded, so nothing is rewritten,
|
|
392
|
+
// hidden or queued per call.
|
|
393
|
+
const dedicatedFunction = () => args.function !== undefined;
|
|
394
|
+
|
|
385
395
|
function withFunctionEnvironment(spec, task, invocationId) {
|
|
396
|
+
if (dedicatedFunction()) {
|
|
397
|
+
return invocationLogger.run({ functionName: spec?.name, invocationId }, task);
|
|
398
|
+
}
|
|
386
399
|
const shared = localSecrets.size > 0 && activeInspectorPort === undefined &&
|
|
387
400
|
!(spec?.platformOptions?.secrets || []).some(name => localSecrets.has(name));
|
|
388
401
|
const run = async () => {
|
|
@@ -1395,6 +1408,12 @@ async function makeHttpServer(functions, manifest) {
|
|
|
1395
1408
|
.send(`no HTTP function ${req.params.project}/${req.params.region}/${req.params.name}`);
|
|
1396
1409
|
return;
|
|
1397
1410
|
}
|
|
1411
|
+
// Guard nested callable wrappers for every non-callable entry, including task queues.
|
|
1412
|
+
markNonCallableRequest(req, {
|
|
1413
|
+
strict: strictProfile(),
|
|
1414
|
+
nonCallableHttp: spec.trigger?.type !== "http" || spec.trigger.callable !== true,
|
|
1415
|
+
});
|
|
1416
|
+
const taskIdentity = takeTaskIdentityMarker(req);
|
|
1398
1417
|
// Without App Check a callable that could consume a token never sees one, whichever path
|
|
1399
1418
|
// the request took here (spec 13.4; app-check-token.mjs).
|
|
1400
1419
|
if (withholdsAppCheckToken(spec, process.env)) removeAppCheckToken(req);
|
|
@@ -1461,6 +1480,9 @@ async function makeHttpServer(functions, manifest) {
|
|
|
1461
1480
|
const payload = blockingResult(value, spec.trigger.eventType, HttpsErrors[0]);
|
|
1462
1481
|
if (lifetime.canStart()) res.status(200).json(payload);
|
|
1463
1482
|
}
|
|
1483
|
+
} else if (taskIdentity && strictProfile() && spec.trigger?.type === "tasks") {
|
|
1484
|
+
// In the strict profile, the daemon marker hides only the SDK's request.auth read.
|
|
1485
|
+
await runWithTaskAuth(() => fn(req, res));
|
|
1464
1486
|
} else {
|
|
1465
1487
|
await fn(req, res);
|
|
1466
1488
|
}
|
|
@@ -1826,6 +1848,15 @@ async function main() {
|
|
|
1826
1848
|
reason: d.ignored.reason,
|
|
1827
1849
|
})),
|
|
1828
1850
|
};
|
|
1851
|
+
if (dedicatedFunction()) {
|
|
1852
|
+
// One function's instance serves one function. Another export stays in the module graph, as in a
|
|
1853
|
+
// production instance, but is neither announced nor routable here.
|
|
1854
|
+
if (!manifest.functions.some((f) => f.name === args.function)) {
|
|
1855
|
+
process.stderr.write(`the function ${args.function} is not exported by the codebase at ${sourceDir}\n`);
|
|
1856
|
+
process.exit(1);
|
|
1857
|
+
}
|
|
1858
|
+
manifest = { ...manifest, functions: manifest.functions.filter((f) => f.name === args.function) };
|
|
1859
|
+
}
|
|
1829
1860
|
startupTrace('function discovery complete');
|
|
1830
1861
|
let httpPort;
|
|
1831
1862
|
if (
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// A callable's wrapper that runs inside an endpoint the daemon serves as something else.
|
|
2
|
+
//
|
|
3
|
+
// `onRequest(opts, onCall(opts, handler))` deploys the callable's code as a plain HTTPS function:
|
|
4
|
+
// discovery sees an `onRequest` endpoint (`httpsTrigger`, no `callableTrigger`), so the daemon does
|
|
5
|
+
// not treat it as a callable and forwards `Authorization` untouched, as it must for application
|
|
6
|
+
// code that verifies credentials itself. The wrapper inside then runs under `skipTokenVerification`
|
|
7
|
+
// (the trusted callable protocol) and decodes any Bearer without checking it, so an unsigned or
|
|
8
|
+
// malformed token became an identity (`uid: "x"`), where production's wrapper verifies the token and
|
|
9
|
+
// refuses it (FUNCTIONS-HTTP-CALLABLE-INGRESS, run 1: 401 for every unverified shape).
|
|
10
|
+
//
|
|
11
|
+
// In the strict profile the daemon therefore tells the runner whether the one `Authorization` field
|
|
12
|
+
// of a request to a non-callable HTTP endpoint is a Bearer of a user of the project it verified
|
|
13
|
+
// (`x-fireemu-credential-verified: 1`; the daemon removes every caller-supplied copy first). The
|
|
14
|
+
// runner marks such a request, and the callable wrapper, the one place that decodes credentials,
|
|
15
|
+
// receives a credential it cannot read as a Bearer when the daemon did not verify it. The wrapper
|
|
16
|
+
// then refuses it itself, with its own envelope and in its own order of checks, exactly as it does
|
|
17
|
+
// for any value that is not `Bearer <token>`. Nothing else changes: a plain `onRequest` function
|
|
18
|
+
// sees the request it always saw (the marker field is removed), and a real callable never carries
|
|
19
|
+
// the mark, because the daemon has already refused or verified its credential.
|
|
20
|
+
|
|
21
|
+
/// The field the daemon sets on a request to a non-callable HTTP endpoint in the strict profile.
|
|
22
|
+
export const VERIFIED_CREDENTIAL_HEADER = "x-fireemu-credential-verified";
|
|
23
|
+
export const VERIFIED_APP_CHECK_HEADER = "x-fireemu-appcheck-verified";
|
|
24
|
+
|
|
25
|
+
const CONTEXT = Symbol.for("fireemu.endpointContext");
|
|
26
|
+
|
|
27
|
+
/// What a callable wrapper receives instead of an unverified credential: not `Bearer <token>`, so
|
|
28
|
+
/// the SDK reads it as an invalid credential without decoding it.
|
|
29
|
+
export const UNVERIFIED_CREDENTIAL = "fireemu-unverified-credential";
|
|
30
|
+
|
|
31
|
+
/// Reads and removes the daemon's markers, then marks requests to non-callable entries.
|
|
32
|
+
/// A missing App Check marker never admits a token. Returns whether the request was marked.
|
|
33
|
+
export function markNonCallableRequest(req, { strict, nonCallableHttp }) {
|
|
34
|
+
const marker = req.headers?.[VERIFIED_CREDENTIAL_HEADER];
|
|
35
|
+
const appCheckMarker = req.headers?.[VERIFIED_APP_CHECK_HEADER];
|
|
36
|
+
if (req.headers) {
|
|
37
|
+
for (const name of Object.keys(req.headers)) {
|
|
38
|
+
if ([VERIFIED_CREDENTIAL_HEADER, VERIFIED_APP_CHECK_HEADER].includes(name.toLowerCase())) delete req.headers[name];
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
if (Array.isArray(req.rawHeaders)) {
|
|
42
|
+
const kept = [];
|
|
43
|
+
for (let i = 0; i + 1 < req.rawHeaders.length; i += 2) {
|
|
44
|
+
if (![VERIFIED_CREDENTIAL_HEADER, VERIFIED_APP_CHECK_HEADER].includes(String(req.rawHeaders[i]).toLowerCase())) {
|
|
45
|
+
kept.push(req.rawHeaders[i], req.rawHeaders[i + 1]);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
req.rawHeaders = kept;
|
|
49
|
+
}
|
|
50
|
+
if (!nonCallableHttp && appCheckMarker === undefined) return false;
|
|
51
|
+
Object.defineProperty(req, CONTEXT, {
|
|
52
|
+
value: Object.freeze({ credentialVerified: !nonCallableHttp || !strict || marker === "1", appCheckVerified: appCheckMarker === "1" }),
|
|
53
|
+
configurable: true,
|
|
54
|
+
});
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/// The request a callable wrapper should see: the request itself, or, when it was served by a
|
|
59
|
+
/// non-callable endpoint and carries a credential the daemon did not verify, a view of it whose
|
|
60
|
+
/// `Authorization` is [`UNVERIFIED_CREDENTIAL`]. The view leaves the caller's own request untouched.
|
|
61
|
+
export function requestForCallableWrapper(req) {
|
|
62
|
+
const context = req?.[CONTEXT];
|
|
63
|
+
if (!context) return req;
|
|
64
|
+
const headers = { ...req.headers };
|
|
65
|
+
let changed = false;
|
|
66
|
+
if (!context.credentialVerified && typeof headers.authorization === "string" && headers.authorization !== "") {
|
|
67
|
+
headers.authorization = UNVERIFIED_CREDENTIAL;
|
|
68
|
+
changed = true;
|
|
69
|
+
}
|
|
70
|
+
if (!context.appCheckVerified && headers["x-firebase-appcheck"] !== undefined) {
|
|
71
|
+
delete headers["x-firebase-appcheck"];
|
|
72
|
+
changed = true;
|
|
73
|
+
}
|
|
74
|
+
if (!changed) return req;
|
|
75
|
+
return Object.create(req, { headers: { value: headers, enumerable: true } });
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/// A callable wrapper that reads its request through [`requestForCallableWrapper`]. The result keeps
|
|
79
|
+
/// the wrapper's own properties, which the SDK reads and extends after the wrapper is built.
|
|
80
|
+
export function guardCallableWrapper(wrapper) {
|
|
81
|
+
if (typeof wrapper !== "function") return wrapper;
|
|
82
|
+
const guarded = function (req, ...rest) {
|
|
83
|
+
return wrapper.call(this, requestForCallableWrapper(req), ...rest);
|
|
84
|
+
};
|
|
85
|
+
for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(wrapper))) {
|
|
86
|
+
Reflect.defineProperty(guarded, key, descriptor);
|
|
87
|
+
}
|
|
88
|
+
for (const symbol of Object.getOwnPropertySymbols(wrapper)) {
|
|
89
|
+
Reflect.defineProperty(guarded, symbol, Object.getOwnPropertyDescriptor(wrapper, symbol));
|
|
90
|
+
}
|
|
91
|
+
return guarded;
|
|
92
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// The daemon sets this marker only for strict-profile dispatches and removes caller-supplied copies.
|
|
2
|
+
// The runner removes it before the function sees the request. Only the SDK's first read is hidden,
|
|
3
|
+
// so the handler and its timers continue to see "true".
|
|
4
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
5
|
+
|
|
6
|
+
export const TASK_IDENTITY_HEADER = "x-fireemu-task-identity";
|
|
7
|
+
const scope = new AsyncLocalStorage();
|
|
8
|
+
const installed = new WeakSet();
|
|
9
|
+
|
|
10
|
+
export function takeTaskIdentityMarker(req) {
|
|
11
|
+
const marker = req.headers?.[TASK_IDENTITY_HEADER];
|
|
12
|
+
if (req.headers) delete req.headers[TASK_IDENTITY_HEADER];
|
|
13
|
+
if (Array.isArray(req.rawHeaders)) {
|
|
14
|
+
const kept = [];
|
|
15
|
+
for (let i = 0; i + 1 < req.rawHeaders.length; i += 2) {
|
|
16
|
+
if (String(req.rawHeaders[i]).toLowerCase() !== TASK_IDENTITY_HEADER) {
|
|
17
|
+
kept.push(req.rawHeaders[i], req.rawHeaders[i + 1]);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
req.rawHeaders = kept;
|
|
21
|
+
}
|
|
22
|
+
return marker === "1";
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function runWithTaskAuth(run) {
|
|
26
|
+
return scope.run({ hideNext: true }, run);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function installTaskAuthEnvironment(target = process) {
|
|
30
|
+
if (installed.has(target)) return;
|
|
31
|
+
const real = target.env;
|
|
32
|
+
target.env = new Proxy(real, {
|
|
33
|
+
get: (env, prop) => {
|
|
34
|
+
const store = scope.getStore();
|
|
35
|
+
if (prop === "FUNCTIONS_EMULATOR" && store?.hideNext) {
|
|
36
|
+
store.hideNext = false;
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
return env[prop];
|
|
40
|
+
},
|
|
41
|
+
// Writes go to the real environment by plain assignment: the real `process.env` refuses a descriptor-based write.
|
|
42
|
+
set: (env, prop, value) => {
|
|
43
|
+
env[prop] = value;
|
|
44
|
+
return true;
|
|
45
|
+
},
|
|
46
|
+
deleteProperty: (env, prop) => delete env[prop],
|
|
47
|
+
defineProperty: (env, prop, descriptor) => {
|
|
48
|
+
if ("value" in descriptor) env[prop] = descriptor.value;
|
|
49
|
+
return true;
|
|
50
|
+
},
|
|
51
|
+
});
|
|
52
|
+
installed.add(target);
|
|
53
|
+
}
|
|
@@ -51,8 +51,16 @@ def _bound(text: str, limit: int) -> str:
|
|
|
51
51
|
class Dispatcher:
|
|
52
52
|
"""Runs `invoke` frames against the functions the manifest serves."""
|
|
53
53
|
|
|
54
|
-
def __init__(
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
functions: dict,
|
|
57
|
+
manifest: dict,
|
|
58
|
+
writer: FrameWriter,
|
|
59
|
+
gate: EnvironmentGate | None = None,
|
|
60
|
+
fixed_identity: bool = False,
|
|
61
|
+
):
|
|
55
62
|
self._gate = gate if gate is not None else EnvironmentGate({})
|
|
63
|
+
self._fixed_identity = fixed_identity
|
|
56
64
|
self._functions = functions
|
|
57
65
|
self._specs = {spec["name"]: spec for spec in manifest["functions"]}
|
|
58
66
|
self._writer = writer
|
|
@@ -98,11 +106,13 @@ class Dispatcher:
|
|
|
98
106
|
return ASYNC_HANDLER, ASYNC_HANDLER
|
|
99
107
|
with self._gate.hold(spec.get("platformOptions", {}).get("secrets")):
|
|
100
108
|
try:
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
109
|
+
if not self._fixed_identity:
|
|
110
|
+
# One process serves the whole codebase, so these name the invocation that started most
|
|
111
|
+
# recently, not a fixed target (the design memo, section 5). A dedicated runner has them from
|
|
112
|
+
# its spawn.
|
|
113
|
+
os.environ["FUNCTION_TARGET"] = spec["entryPoint"]
|
|
114
|
+
os.environ["FUNCTION_SIGNATURE_TYPE"] = _SIGNATURE_TYPES.get(message["trigger"], "cloudevent")
|
|
115
|
+
os.environ["K_SERVICE"] = spec["name"]
|
|
106
116
|
_deliver(message["trigger"], function, message["event"], message.get("rawEventData"))
|
|
107
117
|
except BaseException as error: # a SystemExit in user code must still answer the daemon
|
|
108
118
|
diagnostic, text = describe(error)
|
|
@@ -18,6 +18,9 @@ def _parse(argv):
|
|
|
18
18
|
parser = argparse.ArgumentParser(prog="runner.py")
|
|
19
19
|
parser.add_argument("--source", required=True)
|
|
20
20
|
parser.add_argument("--codebase", default="default")
|
|
21
|
+
# One function's instance (`functions.isolation = "function"`): the daemon fixed the function's identity and secrets
|
|
22
|
+
# in the environment at spawn, so this runner serves that function only and rewrites nothing per call.
|
|
23
|
+
parser.add_argument("--function", default=None)
|
|
21
24
|
return parser.parse_args(argv)
|
|
22
25
|
|
|
23
26
|
|
|
@@ -30,16 +33,32 @@ def load_codebase(source: str) -> dict:
|
|
|
30
33
|
|
|
31
34
|
|
|
32
35
|
def serve(
|
|
33
|
-
functions: dict,
|
|
36
|
+
functions: dict,
|
|
37
|
+
codebase: str,
|
|
38
|
+
secret: str,
|
|
39
|
+
stdin,
|
|
40
|
+
writer: FrameWriter,
|
|
41
|
+
gate: EnvironmentGate | None = None,
|
|
42
|
+
app_check_verified: bool = False,
|
|
43
|
+
blocking_verified: bool = False,
|
|
44
|
+
function: str | None = None,
|
|
34
45
|
) -> int:
|
|
35
|
-
"""Says hello, then serves frames from `stdin` until `shutdown` or the end of the stream.
|
|
46
|
+
"""Says hello, then serves frames from `stdin` until `shutdown` or the end of the stream.
|
|
47
|
+
|
|
48
|
+
With `function`, the runner is that function's instance: only it is announced and served.
|
|
49
|
+
"""
|
|
36
50
|
manifest = build_manifest(functions, app_check_verified)
|
|
51
|
+
if function is not None:
|
|
52
|
+
if not any(spec["name"] == function for spec in manifest["functions"]):
|
|
53
|
+
sys.stderr.write(f"[functions] the function {function} is not exported by the codebase\n")
|
|
54
|
+
return 1
|
|
55
|
+
manifest = {**manifest, "functions": [spec for spec in manifest["functions"] if spec["name"] == function]}
|
|
37
56
|
if not blocking_verified and any(spec["trigger"]["type"] == "blockingAuth" for spec in manifest["functions"]):
|
|
38
57
|
blocking.announce_default_note(sys.stderr)
|
|
39
58
|
server = None
|
|
40
59
|
port = None
|
|
41
60
|
if any(spec["trigger"]["type"] in HTTP_TRIGGERS for spec in manifest["functions"]):
|
|
42
|
-
server, port = start_server(functions, manifest, secret, gate)
|
|
61
|
+
server, port = start_server(functions, manifest, secret, gate, function is not None)
|
|
43
62
|
writer.write(
|
|
44
63
|
{
|
|
45
64
|
"type": "hello",
|
|
@@ -50,7 +69,7 @@ def serve(
|
|
|
50
69
|
"manifest": manifest,
|
|
51
70
|
}
|
|
52
71
|
)
|
|
53
|
-
dispatcher = Dispatcher(functions, manifest, writer, gate)
|
|
72
|
+
dispatcher = Dispatcher(functions, manifest, writer, gate, fixed_identity=function is not None)
|
|
54
73
|
try:
|
|
55
74
|
while True:
|
|
56
75
|
message = read_frame(stdin)
|
|
@@ -96,6 +115,8 @@ def run(argv) -> int:
|
|
|
96
115
|
except BaseException: # a failing import in user code is reported with its traceback
|
|
97
116
|
traceback.print_exc()
|
|
98
117
|
return 1
|
|
118
|
+
# 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}
|
|
99
120
|
if blocking_verified:
|
|
100
|
-
return serve(functions, args.codebase, secret, sys.stdin.buffer, writer, gate, app_check_verified, blocking_verified=True)
|
|
101
|
-
return serve(functions, args.codebase, secret, sys.stdin.buffer, writer, gate, app_check_verified)
|
|
121
|
+
return serve(functions, args.codebase, secret, sys.stdin.buffer, writer, gate, app_check_verified, blocking_verified=True, **options)
|
|
122
|
+
return serve(functions, args.codebase, secret, sys.stdin.buffer, writer, gate, app_check_verified, **options)
|
|
@@ -88,8 +88,17 @@ class _HeldBody:
|
|
|
88
88
|
class RunnerRouter:
|
|
89
89
|
"""Admission and routing in front of the Flask app."""
|
|
90
90
|
|
|
91
|
-
def __init__(
|
|
91
|
+
def __init__(
|
|
92
|
+
self,
|
|
93
|
+
functions: dict,
|
|
94
|
+
manifest: dict,
|
|
95
|
+
project: str,
|
|
96
|
+
secret: str,
|
|
97
|
+
gate: EnvironmentGate | None = None,
|
|
98
|
+
fixed_identity: bool = False,
|
|
99
|
+
):
|
|
92
100
|
self._app = _flask_app()
|
|
101
|
+
self._fixed_identity = fixed_identity
|
|
93
102
|
self._gate = gate if gate is not None else EnvironmentGate({})
|
|
94
103
|
self._project = project
|
|
95
104
|
self._secret = secret.encode()
|
|
@@ -137,11 +146,13 @@ class RunnerRouter:
|
|
|
137
146
|
held = contextlib.ExitStack()
|
|
138
147
|
held.enter_context(self._gate.hold(route[3]))
|
|
139
148
|
try:
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
149
|
+
if not self._fixed_identity:
|
|
150
|
+
# The variables a production instance has from its start name the function it serves. One process
|
|
151
|
+
# serves the whole codebase here, so they name the call that started most recently, as for events.
|
|
152
|
+
# A dedicated runner has them from its spawn.
|
|
153
|
+
os.environ["FUNCTION_TARGET"] = route[2]
|
|
154
|
+
os.environ["FUNCTION_SIGNATURE_TYPE"] = "http"
|
|
155
|
+
os.environ["K_SERVICE"] = name
|
|
145
156
|
body = self._app(environ, start_response)
|
|
146
157
|
except BaseException as error:
|
|
147
158
|
_log_failure(name, error)
|
|
@@ -155,9 +166,9 @@ class _QuietHandler(WSGIRequestHandler):
|
|
|
155
166
|
pass
|
|
156
167
|
|
|
157
168
|
|
|
158
|
-
def start_server(functions: dict, manifest: dict, secret: str, gate: EnvironmentGate | None = None):
|
|
169
|
+
def start_server(functions: dict, manifest: dict, secret: str, gate: EnvironmentGate | None = None, fixed_identity: bool = False):
|
|
159
170
|
"""Starts the server on a free loopback port; returns `(server, port)`."""
|
|
160
|
-
router = RunnerRouter(functions, manifest, os.environ.get("GCLOUD_PROJECT", ""), secret, gate)
|
|
171
|
+
router = RunnerRouter(functions, manifest, os.environ.get("GCLOUD_PROJECT", ""), secret, gate, fixed_identity)
|
|
161
172
|
server = make_server("127.0.0.1", 0, router, threaded=True, request_handler=_QuietHandler)
|
|
162
173
|
import threading
|
|
163
174
|
|