@apifuse/provider-sdk 2.2.0-beta.67 → 2.2.0-beta.68
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/AUTHORING.md +28 -1
- package/CHANGELOG.md +4 -0
- package/README.md +8 -4
- package/bin/apifuse-record.ts +81 -21
- package/bin/apifuse-submit-check.ts +170 -28
- package/dist/cli/templates/provider/.agents/skills/health-checks-and-fail-closed/SKILL.md.tpl +138 -23
- package/dist/cli/templates/provider/README.md.tpl +17 -9
- package/dist/config/loader.d.ts +16 -0
- package/dist/config/loader.js +25 -8
- package/dist/error-resolution.d.ts +13 -0
- package/dist/error-resolution.js +72 -35
- package/dist/lint.d.ts +2 -0
- package/dist/lint.js +493 -2
- package/dist/runtime/executor.js +3 -0
- package/dist/runtime/http.d.ts +2 -0
- package/dist/runtime/http.js +2 -1
- package/dist/runtime/provider.d.ts +7 -0
- package/dist/runtime/provider.js +14 -0
- package/dist/server/index.d.ts +1 -0
- package/dist/server/serve-implementation.d.ts +2 -1
- package/dist/server/serve-implementation.js +43 -29
- package/dist/server/state-backend-report.d.ts +70 -0
- package/dist/server/state-backend-report.js +113 -0
- package/package.json +1 -1
- package/src/cli/templates/provider/.agents/skills/health-checks-and-fail-closed/SKILL.md.tpl +138 -23
- package/src/cli/templates/provider/README.md.tpl +17 -9
- package/src/config/loader.ts +49 -12
- package/src/error-resolution.ts +89 -35
- package/src/lint.ts +541 -1
- package/src/runtime/executor.ts +3 -0
- package/src/runtime/http.ts +2 -1
- package/src/runtime/provider.ts +15 -0
- package/src/server/index.ts +4 -0
- package/src/server/serve-implementation.ts +56 -30
- package/src/server/state-backend-report.ts +185 -0
package/src/lint.ts
CHANGED
|
@@ -29,12 +29,12 @@ import {
|
|
|
29
29
|
} from "./runtime/stealth-owned-headers.js";
|
|
30
30
|
import {
|
|
31
31
|
lintRuntimeBoundary,
|
|
32
|
-
scriptKindForSourceFile,
|
|
33
32
|
// This module already has a narrower TEST_SOURCE_FILE_PATTERN of its own,
|
|
34
33
|
// used by the older source rules; it does not cover a plain `tests/`
|
|
35
34
|
// directory. Aliased rather than merged because consolidating the two would
|
|
36
35
|
// silently change what those rules scan.
|
|
37
36
|
TEST_SOURCE_FILE_PATTERN as SHARED_TEST_SOURCE_FILE_PATTERN,
|
|
37
|
+
scriptKindForSourceFile,
|
|
38
38
|
} from "./runtime-boundary-lint.js";
|
|
39
39
|
import { APIFUSE_DESCRIPTION_KEY_META_KEY, APIFUSE_SENSITIVE_META_KEY } from "./schema.js";
|
|
40
40
|
import type { AuthMode, OperationApprovalPolicy, OperationRiskClass } from "./types.js";
|
|
@@ -2836,6 +2836,543 @@ function lintProviderMetaNarrowing(provider: ProviderSourceLike): LintDiagnostic
|
|
|
2836
2836
|
return diagnostics;
|
|
2837
2837
|
}
|
|
2838
2838
|
|
|
2839
|
+
const STALE_IF_ERROR_OPTION = "staleIfErrorMs";
|
|
2840
|
+
const STALE_IF_ERROR_PATTERN = /\bstaleIfErrorMs\b/;
|
|
2841
|
+
|
|
2842
|
+
/**
|
|
2843
|
+
* Whether a property assignment's initializer leaves no stale window.
|
|
2844
|
+
* `staleIfErrorMs: 0` makes `staleUntil` equal `freshUntil` in
|
|
2845
|
+
* `runtime/cache.ts`, so a loader failure propagates instead of being answered
|
|
2846
|
+
* from cache — a provider deliberately turning stale serving OFF must not be
|
|
2847
|
+
* told its probes conceal outages.
|
|
2848
|
+
*/
|
|
2849
|
+
function disablesStaleWindow(
|
|
2850
|
+
ts: typeof import("typescript"),
|
|
2851
|
+
initializer: import("typescript").Expression,
|
|
2852
|
+
): boolean {
|
|
2853
|
+
if (ts.isNumericLiteral(initializer)) return Number(initializer.text) === 0;
|
|
2854
|
+
return ts.isIdentifier(initializer) && initializer.text === "undefined";
|
|
2855
|
+
}
|
|
2856
|
+
|
|
2857
|
+
/**
|
|
2858
|
+
* Whether executable source configures a stale-if-error window.
|
|
2859
|
+
*
|
|
2860
|
+
* Parsed, not matched: comments and unrelated string literals must not count,
|
|
2861
|
+
* and a regex cannot tell them apart (an `Accept: "*/*"` header literal opens a
|
|
2862
|
+
* block comment to a stripping regex and swallows the cache call after it).
|
|
2863
|
+
* This is the approach `findLegacyChoiceUsage` already uses here. All three
|
|
2864
|
+
* spellings of the option count — `staleIfErrorMs: n`, the shorthand
|
|
2865
|
+
* `{ ttlMs, staleIfErrorMs }`, and the quoted `"staleIfErrorMs": n` — because
|
|
2866
|
+
* refactoring between them must not change the verdict. Falls back to the raw
|
|
2867
|
+
* identifier match when TypeScript is not installed, which is the fail-closed
|
|
2868
|
+
* direction for this rule: it warns rather than goes quiet.
|
|
2869
|
+
*/
|
|
2870
|
+
function servesStaleIfError(source: string, fileName = "provider.ts"): boolean {
|
|
2871
|
+
if (!source.includes(STALE_IF_ERROR_OPTION)) return false;
|
|
2872
|
+
let ts: typeof import("typescript");
|
|
2873
|
+
try {
|
|
2874
|
+
ts = getTypeScript();
|
|
2875
|
+
} catch {
|
|
2876
|
+
return STALE_IF_ERROR_PATTERN.test(source);
|
|
2877
|
+
}
|
|
2878
|
+
const file = ts.createSourceFile(
|
|
2879
|
+
fileName,
|
|
2880
|
+
source,
|
|
2881
|
+
ts.ScriptTarget.Latest,
|
|
2882
|
+
false,
|
|
2883
|
+
scriptKindForSourceFile(ts, fileName),
|
|
2884
|
+
);
|
|
2885
|
+
/** The statically known name of a property, however it is written. */
|
|
2886
|
+
const propertyName = (name: import("typescript").PropertyName): string | undefined => {
|
|
2887
|
+
if (ts.isIdentifier(name) || ts.isStringLiteral(name)) return name.text;
|
|
2888
|
+
if (ts.isComputedPropertyName(name) && ts.isStringLiteral(name.expression)) {
|
|
2889
|
+
return name.expression.text;
|
|
2890
|
+
}
|
|
2891
|
+
return undefined;
|
|
2892
|
+
};
|
|
2893
|
+
/**
|
|
2894
|
+
* A type declaring the option is not a cache call setting it. Skipping these
|
|
2895
|
+
* whole subtrees also stops a `CachePolicy` interface from overriding the
|
|
2896
|
+
* disabled-window exemption for a provider whose only real call passes 0.
|
|
2897
|
+
*/
|
|
2898
|
+
const isTypeOnly = (node: import("typescript").Node): boolean =>
|
|
2899
|
+
ts.isInterfaceDeclaration(node) ||
|
|
2900
|
+
ts.isTypeAliasDeclaration(node) ||
|
|
2901
|
+
ts.isTypeLiteralNode(node) ||
|
|
2902
|
+
ts.isPropertySignature(node) ||
|
|
2903
|
+
ts.isTypeReferenceNode(node) ||
|
|
2904
|
+
ts.isTypeParameterDeclaration(node);
|
|
2905
|
+
/**
|
|
2906
|
+
* The cache write options that travel with `staleIfErrorMs`
|
|
2907
|
+
* (`ProviderCacheWriteOptions`). An object literal carrying one of these
|
|
2908
|
+
* alongside the option is a cache configuration wherever it is declared.
|
|
2909
|
+
*/
|
|
2910
|
+
const siblingCacheOptions = new Set(["ttlMs", "jitterPct"]);
|
|
2911
|
+
/**
|
|
2912
|
+
* A callee that writes the provider cache: `ctx.cache.getOrSet(...)`,
|
|
2913
|
+
* `ctx.cache.set(...)`, and the `cached*` helpers built on them. An unrelated
|
|
2914
|
+
* call receiving an object that happens to carry the name is not cache
|
|
2915
|
+
* configuration. Every one of these takes its options LAST.
|
|
2916
|
+
*/
|
|
2917
|
+
const isCacheCallee = (expression: import("typescript").Expression): boolean => {
|
|
2918
|
+
if (ts.isIdentifier(expression)) return /^cached[A-Z]/.test(expression.text);
|
|
2919
|
+
if (!ts.isPropertyAccessExpression(expression)) return false;
|
|
2920
|
+
if (expression.name.text === "getOrSet") return true;
|
|
2921
|
+
return (
|
|
2922
|
+
(expression.name.text === "set" || expression.name.text === "write") &&
|
|
2923
|
+
ts.isPropertyAccessExpression(expression.expression) &&
|
|
2924
|
+
expression.expression.name.text === "cache"
|
|
2925
|
+
);
|
|
2926
|
+
};
|
|
2927
|
+
/**
|
|
2928
|
+
* `const POLICY = { ... }` object literals, so `{ ...POLICY }` can be judged.
|
|
2929
|
+
* Keyed by name file-wide: a shadowed name may resolve to the wrong literal,
|
|
2930
|
+
* which at warning level is a mis-nudge rather than a wrong build — but the
|
|
2931
|
+
* expansion below still has to be cycle-safe, because shadowing can make the
|
|
2932
|
+
* resolution circular in valid source.
|
|
2933
|
+
*/
|
|
2934
|
+
const literalsByName = new Map<string, import("typescript").ObjectLiteralExpression>();
|
|
2935
|
+
const collect = (node: import("typescript").Node): void => {
|
|
2936
|
+
if (
|
|
2937
|
+
ts.isVariableDeclaration(node) &&
|
|
2938
|
+
ts.isIdentifier(node.name) &&
|
|
2939
|
+
node.initializer !== undefined &&
|
|
2940
|
+
ts.isObjectLiteralExpression(node.initializer)
|
|
2941
|
+
) {
|
|
2942
|
+
literalsByName.set(node.name.text, node.initializer);
|
|
2943
|
+
}
|
|
2944
|
+
ts.forEachChild(node, collect);
|
|
2945
|
+
};
|
|
2946
|
+
collect(file);
|
|
2947
|
+
|
|
2948
|
+
type OptionReading = { window: "enabled" | "disabled" | undefined; hasSibling: boolean };
|
|
2949
|
+
|
|
2950
|
+
/**
|
|
2951
|
+
* The EFFECTIVE stale-window setting of an object literal, spreads expanded
|
|
2952
|
+
* and later properties overriding earlier ones the way JavaScript does — so
|
|
2953
|
+
* `{ ...policy, staleIfErrorMs: 0 }` reads as disabled even when `policy`
|
|
2954
|
+
* enables it.
|
|
2955
|
+
*/
|
|
2956
|
+
const readOptions = (
|
|
2957
|
+
literal: import("typescript").ObjectLiteralExpression,
|
|
2958
|
+
seen: Set<import("typescript").ObjectLiteralExpression>,
|
|
2959
|
+
): OptionReading => {
|
|
2960
|
+
if (seen.has(literal)) return { window: undefined, hasSibling: false };
|
|
2961
|
+
seen.add(literal);
|
|
2962
|
+
let window: OptionReading["window"];
|
|
2963
|
+
let hasSibling = false;
|
|
2964
|
+
for (const property of literal.properties) {
|
|
2965
|
+
if (ts.isSpreadAssignment(property)) {
|
|
2966
|
+
const target = ts.isIdentifier(property.expression)
|
|
2967
|
+
? literalsByName.get(property.expression.text)
|
|
2968
|
+
: ts.isObjectLiteralExpression(property.expression)
|
|
2969
|
+
? property.expression
|
|
2970
|
+
: undefined;
|
|
2971
|
+
if (target === undefined) continue;
|
|
2972
|
+
const inner = readOptions(target, seen);
|
|
2973
|
+
if (inner.window !== undefined) window = inner.window;
|
|
2974
|
+
hasSibling ||= inner.hasSibling;
|
|
2975
|
+
continue;
|
|
2976
|
+
}
|
|
2977
|
+
if (ts.isShorthandPropertyAssignment(property)) {
|
|
2978
|
+
if (property.name.text === STALE_IF_ERROR_OPTION) window = "enabled";
|
|
2979
|
+
else if (siblingCacheOptions.has(property.name.text)) hasSibling = true;
|
|
2980
|
+
continue;
|
|
2981
|
+
}
|
|
2982
|
+
if (!ts.isPropertyAssignment(property)) continue;
|
|
2983
|
+
const name = propertyName(property.name);
|
|
2984
|
+
if (name === STALE_IF_ERROR_OPTION) {
|
|
2985
|
+
window = disablesStaleWindow(ts, property.initializer) ? "disabled" : "enabled";
|
|
2986
|
+
} else if (name !== undefined && siblingCacheOptions.has(name)) {
|
|
2987
|
+
hasSibling = true;
|
|
2988
|
+
}
|
|
2989
|
+
}
|
|
2990
|
+
seen.delete(literal);
|
|
2991
|
+
return { window, hasSibling };
|
|
2992
|
+
};
|
|
2993
|
+
|
|
2994
|
+
let found = false;
|
|
2995
|
+
/**
|
|
2996
|
+
* `inOptionsArgument` is the second way to recognise a cache configuration:
|
|
2997
|
+
* the literal is the options argument of a cache call. Together with the
|
|
2998
|
+
* sibling-option test this covers the real shapes, while an upstream payload
|
|
2999
|
+
* that merely carries a field of the same name does not count.
|
|
3000
|
+
*/
|
|
3001
|
+
const visit = (node: import("typescript").Node, inOptionsArgument: boolean): void => {
|
|
3002
|
+
if (found || isTypeOnly(node)) return;
|
|
3003
|
+
if (ts.isObjectLiteralExpression(node)) {
|
|
3004
|
+
const { window, hasSibling } = readOptions(node, new Set());
|
|
3005
|
+
if (window === "enabled" && (hasSibling || inOptionsArgument)) {
|
|
3006
|
+
found = true;
|
|
3007
|
+
return;
|
|
3008
|
+
}
|
|
3009
|
+
}
|
|
3010
|
+
if (ts.isCallExpression(node) || ts.isNewExpression(node)) {
|
|
3011
|
+
const argumentList = node.arguments ?? [];
|
|
3012
|
+
// Options come last on every cache API; the earlier arguments are the
|
|
3013
|
+
// key, the loader, or the value being cached.
|
|
3014
|
+
const optionsIndex = isCacheCallee(node.expression) ? argumentList.length - 1 : -1;
|
|
3015
|
+
visit(node.expression, false);
|
|
3016
|
+
for (const [index, argument] of [...argumentList].entries()) {
|
|
3017
|
+
visit(argument, index === optionsIndex);
|
|
3018
|
+
}
|
|
3019
|
+
return;
|
|
3020
|
+
}
|
|
3021
|
+
ts.forEachChild(node, (child) => visit(child, false));
|
|
3022
|
+
};
|
|
3023
|
+
visit(file, false);
|
|
3024
|
+
return found;
|
|
3025
|
+
}
|
|
3026
|
+
|
|
3027
|
+
/** The operation-step field that distinguishes a stale-if-error serve. */
|
|
3028
|
+
const SERVED_STALE_CACHE_OPERAND = "served_stale_cache";
|
|
3029
|
+
|
|
3030
|
+
/**
|
|
3031
|
+
* Sources that describe behaviour rather than serve it. Mirrors the broadest
|
|
3032
|
+
* test-source predicate in the repository (`runtime-boundary-lint.ts:82`, which
|
|
3033
|
+
* covers a plain `tests/` directory and `__mocks__/` as well as `__tests__/`)
|
|
3034
|
+
* and adds recorded-fixture directories, so a mock that mentions
|
|
3035
|
+
* `staleIfErrorMs` cannot raise a warning about code the runtime never serves.
|
|
3036
|
+
*/
|
|
3037
|
+
const NON_SERVING_SOURCE_FILE_PATTERN =
|
|
3038
|
+
/(?:^|\/)(?:__tests__|__mocks__|__fixtures__|tests|fixtures)\/|\.(?:test|spec)\.[cm]?[jt]sx?$/;
|
|
3039
|
+
|
|
3040
|
+
/**
|
|
3041
|
+
* Operator tooling and bootstrap entrypoints, mirroring
|
|
3042
|
+
* `runtime-boundary-lint.ts`: a cache option used by a fixture recorder or a
|
|
3043
|
+
* start script is not the request path a probe reads through.
|
|
3044
|
+
*/
|
|
3045
|
+
const NON_SERVING_TOOLING_DIRECTORY_PATTERN = /^(?:scripts|tools|bin)\//;
|
|
3046
|
+
const NON_SERVING_BOOTSTRAP_FILE_PATTERN = /^(?:dev|start|deploy)\.[cm]?[jt]sx?$/;
|
|
3047
|
+
|
|
3048
|
+
function isServingProviderSourcePath(relativePath: string): boolean {
|
|
3049
|
+
return (
|
|
3050
|
+
JAVASCRIPT_SOURCE_FILE_PATTERN.test(relativePath) &&
|
|
3051
|
+
!NON_SERVING_SOURCE_FILE_PATTERN.test(relativePath) &&
|
|
3052
|
+
!NON_SERVING_TOOLING_DIRECTORY_PATTERN.test(relativePath) &&
|
|
3053
|
+
!NON_SERVING_BOOTSTRAP_FILE_PATTERN.test(relativePath)
|
|
3054
|
+
);
|
|
3055
|
+
}
|
|
3056
|
+
|
|
3057
|
+
function isLintRecord(value: unknown): value is Record<string, unknown> {
|
|
3058
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
3059
|
+
}
|
|
3060
|
+
|
|
3061
|
+
/**
|
|
3062
|
+
* Reads `healthCheck.cases` structurally. The lint input is the loaded provider
|
|
3063
|
+
* declaration, which `defineProvider` has already validated, but this rule must
|
|
3064
|
+
* not throw on a shape it did not expect.
|
|
3065
|
+
*/
|
|
3066
|
+
function readHealthCheckCases(healthCheck: unknown): Record<string, unknown>[] {
|
|
3067
|
+
if (!isLintRecord(healthCheck)) return [];
|
|
3068
|
+
const cases = healthCheck.cases;
|
|
3069
|
+
if (!Array.isArray(cases)) return [];
|
|
3070
|
+
return cases.filter(isLintRecord);
|
|
3071
|
+
}
|
|
3072
|
+
|
|
3073
|
+
/**
|
|
3074
|
+
* The `result` bindings of the `operation` steps that invoke `operationId`.
|
|
3075
|
+
*
|
|
3076
|
+
* Scoped to the probe's own operation on purpose: a scenario may invoke a
|
|
3077
|
+
* preparatory read before the operation the case is about, and a guard on the
|
|
3078
|
+
* preparation's result says nothing about whether the checked operation was
|
|
3079
|
+
* answered from a stale cache.
|
|
3080
|
+
*/
|
|
3081
|
+
function operationStepBindings(steps: readonly unknown[], operationId: string): Set<string> {
|
|
3082
|
+
const bindings = new Set<string>();
|
|
3083
|
+
for (const step of steps) {
|
|
3084
|
+
if (
|
|
3085
|
+
isLintRecord(step) &&
|
|
3086
|
+
step.kind === "operation" &&
|
|
3087
|
+
step.operationId === operationId &&
|
|
3088
|
+
typeof step.result === "string"
|
|
3089
|
+
) {
|
|
3090
|
+
bindings.add(step.result);
|
|
3091
|
+
}
|
|
3092
|
+
}
|
|
3093
|
+
return bindings;
|
|
3094
|
+
}
|
|
3095
|
+
|
|
3096
|
+
/**
|
|
3097
|
+
* Whether an operand is the operand: the runtime's `served_stale_cache`
|
|
3098
|
+
* projection on an operation step result for the probe's own operation.
|
|
3099
|
+
*
|
|
3100
|
+
* Exact on three counts, because each looser form is a way to silence the rule
|
|
3101
|
+
* without checking cache provenance: a literal `"served_stale_cache"` in an
|
|
3102
|
+
* `inputTemplate` or a `reasonKey` is not a reference at all;
|
|
3103
|
+
* `["data", "served_stale_cache"]` is an upstream payload field the provider
|
|
3104
|
+
* happens to have named that way; and a reference bound to an `extract` result
|
|
3105
|
+
* is not the operation step this probe invoked.
|
|
3106
|
+
*/
|
|
3107
|
+
function isStaleCacheOperand(operand: unknown, bindings: ReadonlySet<string>): boolean {
|
|
3108
|
+
if (!isLintRecord(operand)) return false;
|
|
3109
|
+
const reference = operand.ref;
|
|
3110
|
+
return (
|
|
3111
|
+
isLintRecord(reference) &&
|
|
3112
|
+
reference.namespace === "steps" &&
|
|
3113
|
+
typeof reference.binding === "string" &&
|
|
3114
|
+
bindings.has(reference.binding) &&
|
|
3115
|
+
Array.isArray(reference.path) &&
|
|
3116
|
+
reference.path.length === 1 &&
|
|
3117
|
+
reference.path[0] === SERVED_STALE_CACHE_OPERAND
|
|
3118
|
+
);
|
|
3119
|
+
}
|
|
3120
|
+
|
|
3121
|
+
/**
|
|
3122
|
+
* Whether a single predicate over the operand is FALSE for a stale serve, under
|
|
3123
|
+
* `negated` negation depth. `served_stale_cache` is always present and always a
|
|
3124
|
+
* boolean, so `exists` and `type_is: "boolean"` pass for a stale serve too —
|
|
3125
|
+
* reading the operand is not the same as rejecting it.
|
|
3126
|
+
*/
|
|
3127
|
+
function predicateRejectsStaleServe(
|
|
3128
|
+
predicate: Record<string, unknown>,
|
|
3129
|
+
bindings: ReadonlySet<string>,
|
|
3130
|
+
negated: boolean,
|
|
3131
|
+
): boolean {
|
|
3132
|
+
// `equals`/`not_equals` are symmetric and the schema allows a reference on
|
|
3133
|
+
// either side, so `equals(actual: false, expected: <ref>)` is the same check
|
|
3134
|
+
// written the other way round.
|
|
3135
|
+
const onActual = isStaleCacheOperand(predicate.actual, bindings);
|
|
3136
|
+
const onExpected = isStaleCacheOperand(predicate.expected, bindings);
|
|
3137
|
+
if (!onActual && !onExpected) return false;
|
|
3138
|
+
const { operator } = predicate;
|
|
3139
|
+
const literal = onActual ? predicate.expected : predicate.actual;
|
|
3140
|
+
const failsWhenStale =
|
|
3141
|
+
(operator === "not_equals" && literal === true) || (operator === "equals" && literal === false);
|
|
3142
|
+
const holdsWhenStale =
|
|
3143
|
+
(operator === "is_true" && onActual) ||
|
|
3144
|
+
(operator === "equals" && literal === true) ||
|
|
3145
|
+
(operator === "not_equals" && literal === false);
|
|
3146
|
+
return negated ? holdsWhenStale : failsWhenStale;
|
|
3147
|
+
}
|
|
3148
|
+
|
|
3149
|
+
/**
|
|
3150
|
+
* Whether an assertion expression evaluates FALSE when the operation step was
|
|
3151
|
+
* answered from a stale cache — the only thing that makes a guard degrade or an
|
|
3152
|
+
* assert fail. A clause under `any` only counts if every sibling branch also
|
|
3153
|
+
* rejects the stale serve, because `any` is satisfied by the branch that still
|
|
3154
|
+
* passes (`status_2xx` on a stale 200 being the obvious one).
|
|
3155
|
+
*/
|
|
3156
|
+
function rejectsStaleServe(node: unknown, bindings: ReadonlySet<string>, negated = false): boolean {
|
|
3157
|
+
if (!isLintRecord(node)) return false;
|
|
3158
|
+
if (node.kind === "not") return rejectsStaleServe(node.clause, bindings, !negated);
|
|
3159
|
+
if (node.kind === "all" || node.kind === "any") {
|
|
3160
|
+
if (!Array.isArray(node.clauses)) return false;
|
|
3161
|
+
// `all` fails if ANY clause fails; `any` fails only if EVERY clause fails.
|
|
3162
|
+
// Negation swaps which of the two the operator behaves like.
|
|
3163
|
+
const conjunctive = negated ? node.kind === "any" : node.kind === "all";
|
|
3164
|
+
return conjunctive
|
|
3165
|
+
? node.clauses.some((clause) => rejectsStaleServe(clause, bindings, negated))
|
|
3166
|
+
: node.clauses.every((clause) => rejectsStaleServe(clause, bindings, negated));
|
|
3167
|
+
}
|
|
3168
|
+
if (node.kind === "predicate") return predicateRejectsStaleServe(node, bindings, negated);
|
|
3169
|
+
return false;
|
|
3170
|
+
}
|
|
3171
|
+
|
|
3172
|
+
/**
|
|
3173
|
+
* Whether a guard's degrade lands on the operation the case is about. A guard
|
|
3174
|
+
* whose condition reads the checked operation's freshness but attributes the
|
|
3175
|
+
* failure to a different operation leaves the checked one green through the
|
|
3176
|
+
* stale serve — covered on paper, not on the status page.
|
|
3177
|
+
*/
|
|
3178
|
+
/**
|
|
3179
|
+
* Whether an assert records its verdict against the checked operation. Same
|
|
3180
|
+
* concern as `guardAttributesTo`: an assertion that covers only some other
|
|
3181
|
+
* operation fails that one, not this one.
|
|
3182
|
+
*/
|
|
3183
|
+
function assertCoversOperation(coversOperations: unknown, operationId: string): boolean {
|
|
3184
|
+
return Array.isArray(coversOperations) && coversOperations.includes(operationId);
|
|
3185
|
+
}
|
|
3186
|
+
|
|
3187
|
+
function guardAttributesTo(onFail: unknown, operationId: string): boolean {
|
|
3188
|
+
if (!isLintRecord(onFail) || !Array.isArray(onFail.attribute)) return false;
|
|
3189
|
+
return onFail.attribute.some((entry) => isLintRecord(entry) && entry.operationId === operationId);
|
|
3190
|
+
}
|
|
3191
|
+
|
|
3192
|
+
/**
|
|
3193
|
+
* Whether a scenario reaches a verdict on freshness: a `guard` condition
|
|
3194
|
+
* (degraded, the shape this rule recommends) or an `assert` expression (down,
|
|
3195
|
+
* harsher but still real coverage). Any other position — an extract selector,
|
|
3196
|
+
* an operation input — is not a verdict.
|
|
3197
|
+
*
|
|
3198
|
+
* Order matters, and this is the rule the guidance states: the freshness
|
|
3199
|
+
* verdict must come before any OTHER guard. Every guard stops the scenario when
|
|
3200
|
+
* it fires, so a row or emptiness guard placed first answers a stale serve that
|
|
3201
|
+
* happens to be empty with its own reason and the freshness guard never runs —
|
|
3202
|
+
* the probe degrades for the wrong cause and the tenant reads "no rows" during
|
|
3203
|
+
* an upstream outage. Asserts before it are fine; they are the evidence clauses
|
|
3204
|
+
* and only stop the scenario by failing it outright.
|
|
3205
|
+
*/
|
|
3206
|
+
function scenarioChecksFreshness(scenario: unknown, operationId: string): boolean {
|
|
3207
|
+
if (!isLintRecord(scenario) || !Array.isArray(scenario.steps)) return false;
|
|
3208
|
+
const bindings = [...operationStepBindings(scenario.steps, operationId)];
|
|
3209
|
+
if (bindings.length === 0) return false;
|
|
3210
|
+
// EVERY read of the operation must be checked. A scenario that invokes it
|
|
3211
|
+
// twice with different inputs has two chances to serve stale, and one fresh
|
|
3212
|
+
// read must not conceal the other.
|
|
3213
|
+
return bindings.every((binding) =>
|
|
3214
|
+
resultBindingChecksFreshness(
|
|
3215
|
+
scenario.steps as readonly unknown[],
|
|
3216
|
+
binding,
|
|
3217
|
+
operationId,
|
|
3218
|
+
bindings,
|
|
3219
|
+
),
|
|
3220
|
+
);
|
|
3221
|
+
}
|
|
3222
|
+
|
|
3223
|
+
function resultBindingChecksFreshness(
|
|
3224
|
+
steps: readonly unknown[],
|
|
3225
|
+
binding: string,
|
|
3226
|
+
operationId: string,
|
|
3227
|
+
siblingBindings: readonly string[],
|
|
3228
|
+
): boolean {
|
|
3229
|
+
const operand = new Set([binding]);
|
|
3230
|
+
let produced = false;
|
|
3231
|
+
for (const step of steps) {
|
|
3232
|
+
if (!isLintRecord(step)) continue;
|
|
3233
|
+
if (!produced) {
|
|
3234
|
+
// Nothing before the read can have checked its freshness.
|
|
3235
|
+
produced = step.kind === "operation" && step.result === binding;
|
|
3236
|
+
continue;
|
|
3237
|
+
}
|
|
3238
|
+
if (
|
|
3239
|
+
step.kind === "assert" &&
|
|
3240
|
+
rejectsStaleServe(step.expression, operand) &&
|
|
3241
|
+
assertCoversOperation(step.coversOperations, operationId)
|
|
3242
|
+
) {
|
|
3243
|
+
return true;
|
|
3244
|
+
}
|
|
3245
|
+
if (step.kind !== "guard") continue;
|
|
3246
|
+
if (rejectsStaleServe(step.condition, operand)) {
|
|
3247
|
+
return guardAttributesTo(step.onFail, operationId);
|
|
3248
|
+
}
|
|
3249
|
+
// A freshness guard for ANOTHER read of the same operation is not a row or
|
|
3250
|
+
// emptiness guard masking the cause: it degrades on exactly this concern,
|
|
3251
|
+
// so `read A, read B, guard A, guard B` covers both. Anything else stops
|
|
3252
|
+
// the scenario first and shadows a later freshness guard.
|
|
3253
|
+
const coversSibling = siblingBindings.some(
|
|
3254
|
+
(sibling) =>
|
|
3255
|
+
sibling !== binding &&
|
|
3256
|
+
rejectsStaleServe(step.condition, new Set([sibling])) &&
|
|
3257
|
+
guardAttributesTo(step.onFail, operationId),
|
|
3258
|
+
);
|
|
3259
|
+
if (!coversSibling) return false;
|
|
3260
|
+
}
|
|
3261
|
+
return false;
|
|
3262
|
+
}
|
|
3263
|
+
|
|
3264
|
+
/** How many uncovered probes the stale-serve message names before eliding. */
|
|
3265
|
+
const STALE_SERVE_MESSAGE_PROBE_LIMIT = 8;
|
|
3266
|
+
|
|
3267
|
+
/**
|
|
3268
|
+
* Health-check cases the platform monitor cannot execute, and stale-if-error
|
|
3269
|
+
* serves no probe can see.
|
|
3270
|
+
*
|
|
3271
|
+
* The monitor runs a case's SERIALIZED `scenario` and nothing else — a closure
|
|
3272
|
+
* cannot cross the registry's serialization boundary. A case carrying only
|
|
3273
|
+
* `assertions` is still published as a probe, but the registry projects it as
|
|
3274
|
+
* `legacy_function_assertions_not_serializable` and the monitor answers
|
|
3275
|
+
* `unknown` / `monitoring_unavailable` for it forever: the operation reads as
|
|
3276
|
+
* monitored on the status page while nothing is checked.
|
|
3277
|
+
*
|
|
3278
|
+
* A provider that reads its upstream through `ctx.cache.getOrSet(..., {
|
|
3279
|
+
* staleIfErrorMs })` answers an upstream outage with HTTP 200 and a
|
|
3280
|
+
* schema-valid body for the whole stale window, so every clause over
|
|
3281
|
+
* `status_code` and `data` passes and the probe rolls up `ok` through the
|
|
3282
|
+
* outage. `served_stale_cache` on the operation step result is the only operand
|
|
3283
|
+
* that separates that from a live read.
|
|
3284
|
+
*
|
|
3285
|
+
* Both are warnings while the fleet migrates; they become errors once no
|
|
3286
|
+
* repository carries an unmonitored case.
|
|
3287
|
+
*/
|
|
3288
|
+
function lintHealthCheckMonitorability(provider: {
|
|
3289
|
+
id?: string;
|
|
3290
|
+
providerSourceFiles?: Record<string, string>;
|
|
3291
|
+
operations?: Record<string, { handler?: unknown; source?: string; healthCheck?: unknown }>;
|
|
3292
|
+
}): LintDiagnostic[] {
|
|
3293
|
+
const diagnostics: LintDiagnostic[] = [];
|
|
3294
|
+
const providerLabel = provider.id ? `Provider "${provider.id}"` : "Provider";
|
|
3295
|
+
// Freshness is judged per CASE. Operation-level bookkeeping would let one
|
|
3296
|
+
// guarded case silence its unguarded siblings, which still report `ok`
|
|
3297
|
+
// through a stale serve — the same fail-open this rule exists to close.
|
|
3298
|
+
const uncoveredByOperation = new Map<string, string[]>();
|
|
3299
|
+
|
|
3300
|
+
for (const [operationKey, operation] of Object.entries(provider.operations ?? {})) {
|
|
3301
|
+
const cases = readHealthCheckCases(operation.healthCheck);
|
|
3302
|
+
const unmonitored: string[] = [];
|
|
3303
|
+
for (const [caseIndex, healthCase] of cases.entries()) {
|
|
3304
|
+
const caseLabel =
|
|
3305
|
+
typeof healthCase.name === "string" && healthCase.name.length > 0
|
|
3306
|
+
? `"${healthCase.name}"`
|
|
3307
|
+
: `[${caseIndex}]`;
|
|
3308
|
+
if (healthCase.scenario === undefined) {
|
|
3309
|
+
unmonitored.push(caseLabel);
|
|
3310
|
+
}
|
|
3311
|
+
if (!scenarioChecksFreshness(healthCase.scenario, operationKey)) {
|
|
3312
|
+
const uncovered = uncoveredByOperation.get(operationKey) ?? [];
|
|
3313
|
+
uncovered.push(`${operationKey} ${caseLabel}`);
|
|
3314
|
+
uncoveredByOperation.set(operationKey, uncovered);
|
|
3315
|
+
}
|
|
3316
|
+
}
|
|
3317
|
+
if (unmonitored.length > 0) {
|
|
3318
|
+
diagnostics.push({
|
|
3319
|
+
rule: "health-check-assertions-not-monitored",
|
|
3320
|
+
level: "warn",
|
|
3321
|
+
field: `operations.${operationKey}.healthCheck.cases`,
|
|
3322
|
+
message: `${providerLabel} operation "${operationKey}" health-check ${unmonitored.length === 1 ? "case" : "cases"} ${unmonitored.join(", ")} declare assertions without a scenario. The platform health monitor executes only a case's serialized scenario, so this operation publishes a probe whose outcome is permanently unknown/monitoring_unavailable — it reads as monitored while nothing is checked. Express the checks as scenario: defineHealthScenario({ ... }).`,
|
|
3323
|
+
});
|
|
3324
|
+
}
|
|
3325
|
+
}
|
|
3326
|
+
|
|
3327
|
+
if (uncoveredByOperation.size === 0) return diagnostics;
|
|
3328
|
+
|
|
3329
|
+
// Attribution. A handler that carries the cache call in its OWN source names
|
|
3330
|
+
// exactly the operation that serves stale. A file does not: the linter cannot
|
|
3331
|
+
// follow the call graph, and it cannot reliably tell a handler's own file
|
|
3332
|
+
// from a shared helper either — `getOperationSource` returns the runtime's
|
|
3333
|
+
// `handler.toString()`, which type erasure and reformatting make textually
|
|
3334
|
+
// unequal to the TypeScript on disk. So any file-level evidence degrades the
|
|
3335
|
+
// verdict to "somewhere in this provider", and the message says so instead of
|
|
3336
|
+
// implying every listed probe reads through that cache.
|
|
3337
|
+
const sources = new Set<string>();
|
|
3338
|
+
const operationsServingStale = new Set<string>();
|
|
3339
|
+
for (const [operationKey, operation] of Object.entries(provider.operations ?? {})) {
|
|
3340
|
+
if (servesStaleIfError(getOperationSource(operation), `${operationKey}.ts`)) {
|
|
3341
|
+
sources.add(`operations.${operationKey} handler`);
|
|
3342
|
+
operationsServingStale.add(operationKey);
|
|
3343
|
+
}
|
|
3344
|
+
}
|
|
3345
|
+
let unattributed = false;
|
|
3346
|
+
for (const [filePath, source] of Object.entries(provider.providerSourceFiles ?? {})) {
|
|
3347
|
+
if (!isServingProviderSourcePath(filePath) || !servesStaleIfError(source, filePath)) continue;
|
|
3348
|
+
sources.add(filePath);
|
|
3349
|
+
unattributed = true;
|
|
3350
|
+
}
|
|
3351
|
+
if (sources.size === 0) return diagnostics;
|
|
3352
|
+
|
|
3353
|
+
const attributable = !unattributed;
|
|
3354
|
+
const uncovered = [...uncoveredByOperation]
|
|
3355
|
+
.filter(([operationKey]) => !attributable || operationsServingStale.has(operationKey))
|
|
3356
|
+
.flatMap(([, probes]) => probes);
|
|
3357
|
+
if (uncovered.length === 0) return diagnostics;
|
|
3358
|
+
|
|
3359
|
+
const elided = uncovered.length - STALE_SERVE_MESSAGE_PROBE_LIMIT;
|
|
3360
|
+
const named = uncovered
|
|
3361
|
+
.slice(0, STALE_SERVE_MESSAGE_PROBE_LIMIT)
|
|
3362
|
+
.join(", ")
|
|
3363
|
+
.concat(elided > 0 ? `, and ${elided} more` : "");
|
|
3364
|
+
const caveat = attributable
|
|
3365
|
+
? ""
|
|
3366
|
+
: ` The cache call is in provider source the linter cannot attribute to one operation, so every uncovered probe is listed — skip any whose operation does not read through that cache.`;
|
|
3367
|
+
diagnostics.push({
|
|
3368
|
+
rule: "health-check-stale-serve-unguarded",
|
|
3369
|
+
level: "warn",
|
|
3370
|
+
field: "healthCheck",
|
|
3371
|
+
message: `${providerLabel} serves stale-if-error (staleIfErrorMs in ${[...sources].sort().join(", ")}) and these health-check cases never check ${SERVED_STALE_CACHE_OPERAND}: ${named}. During an upstream outage the cache answers HTTP 200 with a schema-valid body, so every clause over status_code and data still passes and those probes report ok for the whole stale window. Add one guard step per affected probe on { ref: { namespace: "steps", binding: "<operation step result>", path: ["${SERVED_STALE_CACHE_OPERAND}"] } } attributing status "degraded" with reasonCode "expected_absence", placed before any row or emptiness guard.${caveat}`,
|
|
3372
|
+
});
|
|
3373
|
+
return diagnostics;
|
|
3374
|
+
}
|
|
3375
|
+
|
|
2839
3376
|
export function lintOperation(op: {
|
|
2840
3377
|
descriptionKey?: string;
|
|
2841
3378
|
whenToUseKeys?: readonly string[];
|
|
@@ -2987,6 +3524,8 @@ export function lintProvider(
|
|
|
2987
3524
|
fixtures?: unknown;
|
|
2988
3525
|
handler?: unknown;
|
|
2989
3526
|
source?: string;
|
|
3527
|
+
/** Read structurally by the health-check monitorability rules. */
|
|
3528
|
+
healthCheck?: unknown;
|
|
2990
3529
|
errorCodes?: ReadonlyArray<{
|
|
2991
3530
|
code: string;
|
|
2992
3531
|
status?: number;
|
|
@@ -3029,6 +3568,7 @@ export function lintProviderWithInformation(
|
|
|
3029
3568
|
...lintLegacyChoiceUsage(provider),
|
|
3030
3569
|
...lintProviderMetaNarrowing(provider),
|
|
3031
3570
|
...lintHandleDeclarations(provider),
|
|
3571
|
+
...lintHealthCheckMonitorability(provider),
|
|
3032
3572
|
];
|
|
3033
3573
|
// Runtime boundary rules (process.env, node:fs/net/child_process, raw
|
|
3034
3574
|
// fetch) also yield information entries for `@apifuse-allow` acknowledgements.
|
package/src/runtime/executor.ts
CHANGED
|
@@ -39,6 +39,9 @@ export async function executeOperation<
|
|
|
39
39
|
if (!operation) {
|
|
40
40
|
throw new ProviderError(`Unknown operation: ${provider.id}/${operationId}`, {
|
|
41
41
|
code: "NOT_FOUND",
|
|
42
|
+
// No upstream was asked: keep the registered NOT_FOUND code from
|
|
43
|
+
// attributing this to one.
|
|
44
|
+
category: "provider_error",
|
|
42
45
|
fix: `Valid operations: ${Object.keys(provider.operations).join(", ")}`,
|
|
43
46
|
});
|
|
44
47
|
}
|
package/src/runtime/http.ts
CHANGED
|
@@ -578,7 +578,8 @@ function normalizeHttpMethod(method: string): Uppercase<HttpMethod> {
|
|
|
578
578
|
}
|
|
579
579
|
}
|
|
580
580
|
|
|
581
|
-
|
|
581
|
+
/** Whether `url` carries its own scheme, so it needs no `upstream.baseUrl` to resolve. */
|
|
582
|
+
export function isAbsoluteUrl(url: string): boolean {
|
|
582
583
|
return /^[a-z][a-z\d+\-.]*:/i.test(url);
|
|
583
584
|
}
|
|
584
585
|
|
package/src/runtime/provider.ts
CHANGED
|
@@ -13,3 +13,18 @@ export function getProviderBaseUrl(provider: ProviderDefinition): string | undef
|
|
|
13
13
|
|
|
14
14
|
return undefined;
|
|
15
15
|
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The base `ctx.stealth` resolves relative request URLs (and seeds its cookie
|
|
19
|
+
* jar's default origin) against: the provider's first declared
|
|
20
|
+
* `upstream.baseUrl`, else `https://<allowedHosts[0]>`. `undefined` means the
|
|
21
|
+
* provider declares neither, and `serve` binds no stealth transport at all.
|
|
22
|
+
*/
|
|
23
|
+
export function getProviderStealthBaseUrl(provider: ProviderDefinition): string | undefined {
|
|
24
|
+
const baseUrl = getProviderBaseUrl(provider);
|
|
25
|
+
if (baseUrl) {
|
|
26
|
+
return baseUrl;
|
|
27
|
+
}
|
|
28
|
+
const firstHost = provider.allowedHosts?.[0];
|
|
29
|
+
return firstHost ? `https://${firstHost}` : undefined;
|
|
30
|
+
}
|
package/src/server/index.ts
CHANGED
|
@@ -115,6 +115,10 @@ export {
|
|
|
115
115
|
type ServeOptions,
|
|
116
116
|
serve,
|
|
117
117
|
} from "./serve.js";
|
|
118
|
+
export type {
|
|
119
|
+
ProviderStateBackendLogEvent,
|
|
120
|
+
ProviderStoreBackendReport,
|
|
121
|
+
} from "./state-backend-report.js";
|
|
118
122
|
export type { ProviderErrorObservability } from "../errors.js";
|
|
119
123
|
export {
|
|
120
124
|
computeSelfTestPlanDigest,
|