@pulse-compute/provider-fastly 0.0.0 → 1.0.0-beta.10

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.
Files changed (103) hide show
  1. package/README.md +53 -1
  2. package/dist/config-schema.json +103 -0
  3. package/dist/index.d.ts +77 -0
  4. package/dist/index.d.ts.map +1 -0
  5. package/dist/index.js +67 -0
  6. package/dist/index.js.map +1 -0
  7. package/package.json +88 -5
  8. package/src/build/canonical-target.js +469 -0
  9. package/src/build/digest-native.js +25 -0
  10. package/src/build/effect-invocations.js +49 -0
  11. package/src/build/embedded-assets.as.ts +32 -0
  12. package/src/build/entities-native.js +559 -0
  13. package/src/build/fixed-memory-runtime.as.ts +148 -0
  14. package/src/build/kv-native.as.ts +331 -0
  15. package/src/build/kv-native.js +27 -0
  16. package/src/build/native-application-errors.js +159 -0
  17. package/src/build/native-binary-resources.js +30 -0
  18. package/src/build/native-body-forwarding.as.ts +341 -0
  19. package/src/build/native-body-forwarding.js +69 -0
  20. package/src/build/native-dynamic-backends.as.ts +115 -0
  21. package/src/build/native-dynamic-backends.js +52 -0
  22. package/src/build/native-fetch-deadlines.as.ts +164 -0
  23. package/src/build/native-fetch-deadlines.js +27 -0
  24. package/src/build/native-fetch-errors.js +38 -0
  25. package/src/build/native-handle-ownership.js +127 -0
  26. package/src/build/native-header-lookup.js +50 -0
  27. package/src/build/native-http-effects.js +994 -0
  28. package/src/build/native-http-shell.js +703 -0
  29. package/src/build/native-platform-capabilities.js +2654 -0
  30. package/src/build/native-request-body.js +44 -0
  31. package/src/build/native-request-headers.js +93 -0
  32. package/src/build/native-send-error-detail.as.ts +12 -0
  33. package/src/build/native-stdio.js +45 -0
  34. package/src/build/native-string-values.js +143 -0
  35. package/src/build/native-transport-details.as.ts +84 -0
  36. package/src/build/native-value-budget.js +90 -0
  37. package/src/build/package-native-application.js +114 -0
  38. package/src/build/request-budget.as.ts +50 -0
  39. package/src/build/request-budget.js +47 -0
  40. package/src/build/s3-body.as.ts +97 -0
  41. package/src/build/s3-native.as.ts +228 -0
  42. package/src/build/s3-native.js +30 -0
  43. package/src/build/schema-admission.js +83 -0
  44. package/src/build/schema-nested-json.js +93 -0
  45. package/src/build/schema-scalar-record.js +41 -0
  46. package/src/build/time-native.js +49 -0
  47. package/src/build/wasm-budget.js +28 -0
  48. package/src/compiler/assets-package-out-parity-proof.js +338 -0
  49. package/src/compiler/assets-provider-proof.js +499 -0
  50. package/src/compiler/config-provider-resolution.js +573 -0
  51. package/src/compiler/fastly-adapter.js +564 -0
  52. package/src/compiler/fastly-command-entry.js +390 -0
  53. package/src/compiler/fastly-config-secret-serve.js +323 -0
  54. package/src/compiler/fastly-hostcall-binding.js +598 -0
  55. package/src/compiler/fastly-readiness.js +477 -0
  56. package/src/compiler/index.js +40 -0
  57. package/src/compiler/lifecycle-parity-contract.js +70 -0
  58. package/src/compiler/lifecycle-parity-proof.js +260 -0
  59. package/src/compiler/route-handler-effect-proof.js +255 -0
  60. package/src/compiler/runtime-provider-kv.js +237 -0
  61. package/src/compiler/runtime-provider-shape.js +109 -0
  62. package/src/config-api.js +69 -0
  63. package/src/config-schema.d.ts +13 -0
  64. package/src/config-schema.js +27 -0
  65. package/src/config-schema.json +103 -0
  66. package/src/index.js +3 -0
  67. package/src/index.ts +143 -0
  68. package/src/javascript/assets-adapter.js +122 -0
  69. package/src/javascript/bindings-adapter.js +237 -0
  70. package/src/javascript/errors.js +26 -0
  71. package/src/javascript/fetch-adapter.js +93 -0
  72. package/src/javascript/grip-broadcast.js +261 -0
  73. package/src/javascript/jwt-verifier.js +147 -0
  74. package/src/javascript/lifecycle.js +55 -0
  75. package/src/javascript/local-loader.js +138 -0
  76. package/src/javascript/logging.js +35 -0
  77. package/src/javascript/package-effects.js +71 -0
  78. package/src/javascript/runtime-host.js +112 -0
  79. package/src/javascript/sha256.js +128 -0
  80. package/src/javascript/source-package.js +778 -0
  81. package/src/javascript/support.js +142 -0
  82. package/src/javascript/target-support-policy.js +277 -0
  83. package/src/javascript/target.js +89 -0
  84. package/src/javascript/test-runtime.js +408 -0
  85. package/src/provider-contract.js +88 -0
  86. package/src/runtime/assets-provider.js +464 -0
  87. package/src/runtime/canonical-api-runtime.js +603 -0
  88. package/src/runtime/index.js +28 -0
  89. package/src/runtime/provider-primitives-contract.js +272 -0
  90. package/src/runtime/provider-primitives.js +82 -0
  91. package/src/runtime/route-handler-effects.js +507 -0
  92. package/src/testing/conditional-kv-host.js +155 -0
  93. package/src/testing/fastly-cli.js +538 -0
  94. package/src/testing/native-dynamic-backends-host.js +39 -0
  95. package/src/testing/native-http-effects-host.js +398 -0
  96. package/src/testing/native-http-shell-host.js +190 -0
  97. package/src/testing/native-platform-capabilities-host.js +924 -0
  98. package/src/toolchain/body-forwarding.js +25 -0
  99. package/src/toolchain/config.js +144 -0
  100. package/src/toolchain/index.js +386 -0
  101. package/src/toolchain/logging.js +18 -0
  102. package/src/toolchain/native-execution.js +78 -0
  103. package/src/toolchain/s3.js +26 -0
@@ -0,0 +1,148 @@
1
+ /*
2
+ * Fixed-memory AssemblyScript runtime for guest-linked Fastly Native modules.
3
+ *
4
+ * The ES256 guest contract reserves [0, 262144) for Rust, [262144, 524288)
5
+ * for primary static data, and [524288, 540928) for the private invocation
6
+ * frame. Dynamic primary allocations use [540928, 2097152). The allocator
7
+ * reclaims and coalesces blocks and asks the mark/sweep runtime to collect
8
+ * before reporting exhaustion. It contains no memory.grow instruction.
9
+ */
10
+
11
+ import {
12
+ AL_MASK,
13
+ BLOCK_MAXSIZE,
14
+ BLOCK_OVERHEAD,
15
+ } from "~lib/rt/common"
16
+ import "~lib/rt/itcms"
17
+
18
+ const PRIMARY_HEAP_START: usize = 540928
19
+ const PRIMARY_HEAP_END: usize = 2097152
20
+ const FREE: usize = 1
21
+ const MIN_PAYLOAD: usize =
22
+ ((1 + BLOCK_OVERHEAD + AL_MASK) & ~AL_MASK) - BLOCK_OVERHEAD
23
+
24
+ @lazy let startOffset: usize =
25
+ ((PRIMARY_HEAP_START + BLOCK_OVERHEAD + AL_MASK) & ~AL_MASK) - BLOCK_OVERHEAD
26
+ @lazy let endOffset: usize = startOffset
27
+ @lazy let collecting: bool = false
28
+
29
+ @inline function computeSize(size: usize): usize {
30
+ return ((size + BLOCK_OVERHEAD + AL_MASK) & ~AL_MASK) - BLOCK_OVERHEAD
31
+ }
32
+
33
+ @inline function blockSize(block: usize): usize {
34
+ return load<usize>(block) & ~FREE
35
+ }
36
+
37
+ @inline function blockIsFree(block: usize): bool {
38
+ return (load<usize>(block) & FREE) != 0
39
+ }
40
+
41
+ function allocateFromFree(block: usize, actualSize: usize, size: usize): usize {
42
+ const remaining = actualSize - size
43
+ if (remaining >= BLOCK_OVERHEAD + MIN_PAYLOAD) {
44
+ const next = block + BLOCK_OVERHEAD + size
45
+ store<usize>(next, (remaining - BLOCK_OVERHEAD) | FREE)
46
+ store<usize>(block, size)
47
+ } else {
48
+ store<usize>(block, actualSize)
49
+ }
50
+ return block + BLOCK_OVERHEAD
51
+ }
52
+
53
+ function tryAllocate(size: usize): usize {
54
+ let cursor = startOffset
55
+ while (cursor < endOffset) {
56
+ const actualSize = blockSize(cursor)
57
+ if (blockIsFree(cursor) && actualSize >= size) {
58
+ return allocateFromFree(cursor, actualSize, size)
59
+ }
60
+ cursor += BLOCK_OVERHEAD + actualSize
61
+ }
62
+ const nextEnd = endOffset + BLOCK_OVERHEAD + size
63
+ if (nextEnd > PRIMARY_HEAP_END) return 0
64
+ const block = endOffset
65
+ endOffset = nextEnd
66
+ store<usize>(block, size)
67
+ return block + BLOCK_OVERHEAD
68
+ }
69
+
70
+ function coalesce(): void {
71
+ let cursor = startOffset
72
+ while (cursor < endOffset) {
73
+ let actualSize = blockSize(cursor)
74
+ let next = cursor + BLOCK_OVERHEAD + actualSize
75
+ if (blockIsFree(cursor)) {
76
+ while (next < endOffset && blockIsFree(next)) {
77
+ actualSize += BLOCK_OVERHEAD + blockSize(next)
78
+ store<usize>(cursor, actualSize | FREE)
79
+ next = cursor + BLOCK_OVERHEAD + actualSize
80
+ }
81
+ if (next == endOffset) {
82
+ endOffset = cursor
83
+ return
84
+ }
85
+ }
86
+ cursor = next
87
+ }
88
+ }
89
+
90
+ @unsafe @global
91
+ export function __alloc(size: usize): usize {
92
+ if (size > BLOCK_MAXSIZE) unreachable()
93
+ const payloadSize = computeSize(size)
94
+ let pointer = tryAllocate(payloadSize)
95
+ if (pointer == 0 && !collecting) {
96
+ collecting = true
97
+ __collect()
98
+ collecting = false
99
+ coalesce()
100
+ pointer = tryAllocate(payloadSize)
101
+ }
102
+ if (pointer == 0) unreachable()
103
+ return pointer
104
+ }
105
+
106
+ @unsafe @global
107
+ export function __realloc(pointer: usize, size: usize): usize {
108
+ if (pointer == 0 || (pointer & AL_MASK) != 0) unreachable()
109
+ const block = pointer - BLOCK_OVERHEAD
110
+ const actualSize = blockSize(block)
111
+ const payloadSize = computeSize(size)
112
+ if (payloadSize <= actualSize) {
113
+ const remaining = actualSize - payloadSize
114
+ if (remaining >= BLOCK_OVERHEAD + MIN_PAYLOAD) {
115
+ const next = block + BLOCK_OVERHEAD + payloadSize
116
+ store<usize>(block, payloadSize)
117
+ store<usize>(next, (remaining - BLOCK_OVERHEAD) | FREE)
118
+ coalesce()
119
+ }
120
+ return pointer
121
+ }
122
+ const right = block + BLOCK_OVERHEAD + actualSize
123
+ if (right < endOffset && blockIsFree(right)) {
124
+ const combined = actualSize + BLOCK_OVERHEAD + blockSize(right)
125
+ if (combined >= payloadSize) {
126
+ return allocateFromFree(block, combined, payloadSize)
127
+ }
128
+ }
129
+ const newPointer = __alloc(max<usize>(payloadSize, actualSize << 1))
130
+ for (let index: usize = 0; index < actualSize; index += 1) {
131
+ store<u8>(newPointer + index, load<u8>(pointer + index))
132
+ }
133
+ __free(pointer)
134
+ return newPointer
135
+ }
136
+
137
+ @unsafe @global
138
+ export function __free(pointer: usize): void {
139
+ if (pointer == 0 || (pointer & AL_MASK) != 0) unreachable()
140
+ const block = pointer - BLOCK_OVERHEAD
141
+ store<usize>(block, blockSize(block) | FREE)
142
+ coalesce()
143
+ }
144
+
145
+ @unsafe @global
146
+ export function __reset(): void {
147
+ endOffset = startOffset
148
+ }
@@ -0,0 +1,331 @@
1
+ // Fastly Native realization of the runtime-owned K1/K2 conditional KV contract.
2
+ // Limits are generated from runtime/host. No SDK or unconditional CAS fallback.
3
+ @external('fastly_async_io', 'select') declare function __kv_select(handles: usize, count: i32, timeout: i32, ready: usize): i32
4
+ @external('fastly_http_body', 'close') declare function __kv_close(body: i32): i32
5
+
6
+ @lazy const __kv_deadline = new StaticArray<i64>(PULSE_FASTLY_EFFECT_COUNT)
7
+ @lazy const __kv_dispatched = new StaticArray<bool>(PULSE_FASTLY_EFFECT_COUNT)
8
+ @lazy const __kv_list_limits = new StaticArray<i32>(PULSE_FASTLY_EFFECT_COUNT)
9
+ @lazy const __kv_list_prefixes = new Array<string>(PULSE_FASTLY_EFFECT_COUNT).fill('')
10
+ let __kv_request_deadline: i64 = -1;
11
+ // Host embedding seam, in monotonic nanoseconds; never exposed through ctx.
12
+ export function pulse_fastly_kv_request_deadline(deadline: i64): void { __kv_request_deadline = deadline; }
13
+ function __kv_clock(): i64 {
14
+ const out = new StaticArray<i64>(1);
15
+ return wasi_snapshot_preview1_clock_time_get(1, 1, changetype<usize>(out)) == 0 ? out[0] : -1;
16
+ }
17
+ function __kv_remaining(index: i32): i32 {
18
+ const now = __kv_clock();
19
+ if (now < 0) return -1;
20
+ const remaining = __kv_deadline[index] - now;
21
+ return remaining <= 0 ? 0 : i32((remaining + 999999) / 1000000);
22
+ }
23
+ function __kv_set(result: i32, key: string, value: i32): void { host_value_object_set(result, __pulse_fastly_string_value(key), value); }
24
+ function __kv_result(status: string, reason: string = ''): i32 {
25
+ const result = host_value_object(); __kv_set(result, 'status', __pulse_fastly_string_value(status));
26
+ if (reason.length) __kv_set(result, 'reason', __pulse_fastly_string_value(reason));
27
+ return result;
28
+ }
29
+ function __kv_failure(index: i32, reason: string): i32 {
30
+ const kind = __pulse_fastly_effect_kind(index);
31
+ return __kv_result(kind == 15 || kind == 23 ? 'failed' : __kv_dispatched[index] ? 'unknown' : kind == 22 ? 'not-deleted' : 'not-stored', reason);
32
+ }
33
+ function __kv_fail(index: i32, reason: string): void { __pulse_fastly_ready_effect(index, __kv_failure(index, reason)); }
34
+ function __kv_expired(index: i32): bool {
35
+ const remaining = __kv_remaining(index);
36
+ if (remaining > 0) return false;
37
+ __kv_fail(index, remaining == 0 ? 'timeout' : 'unavailable'); return true;
38
+ }
39
+ // select readiness guarantees the corresponding I/O action will not block.
40
+ // Zero timeout means infinity in this ABI, so it must never be passed.
41
+ function __kv_ready(index: i32, handle: i32): i32 {
42
+ const remaining = __kv_remaining(index); if (remaining <= 0) return remaining;
43
+ const handles = new StaticArray<i32>(1), out = new StaticArray<i32>(1);
44
+ handles[0] = handle; out[0] = -1;
45
+ if (__kv_select(changetype<usize>(handles), 1, remaining, changetype<usize>(out)) != 0) return -1;
46
+ const after = __kv_remaining(index); if (after <= 0) return after;
47
+ return out[0] == 0 ? 1 : out[0] == -1 ? 0 : -2;
48
+ }
49
+ function __kv_ready_failure(index: i32, ready: i32): i32 { return __kv_failure(index, ready == 0 ? 'timeout' : ready == -2 ? 'protocol' : 'transport'); }
50
+ function __kv_key(text: string): bool {
51
+ if (text == ' ' || text == '\ufffe' || text == '\uffff') return false;
52
+ if (!text.length || text.length > __KV_keyBytes || String.UTF8.byteLength(text) > __KV_keyBytes) return false;
53
+ for (let i = 0; i < text.length; i++) {
54
+ const c = text.charCodeAt(i);
55
+ if (c < 32 || (c >= 127 && c <= 159)) return false;
56
+ if (c >= 0xd800 && c <= 0xdbff) { if (++i >= text.length) return false; const next = text.charCodeAt(i); if (next < 0xdc00 || next > 0xdfff) return false; }
57
+ else if (c >= 0xdc00 && c <= 0xdfff) return false;
58
+ }
59
+ // Fastly's exact-key restrictions; never normalize an application key.
60
+ return text != '.' && text != '..' && !text.startsWith('.well-known/acme-challenge')
61
+ && text.indexOf('./') < 0 && !text.endsWith('/.') && !text.endsWith('/..')
62
+ && text.indexOf('#') < 0 && text.indexOf('?') < 0 && text.indexOf('^') < 0
63
+ && text.indexOf('|') < 0 && text.indexOf(';') < 0 && text.indexOf('\n') < 0 && text.indexOf('\r') < 0;
64
+ }
65
+ function __kv_list_text(text: string, max: i32, empty: bool = false): bool {
66
+ if ((!empty && !text.length) || text.length > max || String.UTF8.byteLength(text) > max) return false;
67
+ for (let i = 0; i < text.length; i++) {
68
+ const c = text.charCodeAt(i);
69
+ if (c < 32 || (c >= 127 && c <= 159)) return false;
70
+ if (c >= 0xd800 && c <= 0xdbff) { if (++i >= text.length) return false; const next = text.charCodeAt(i); if (next < 0xdc00 || next > 0xdfff) return false; }
71
+ else if (c >= 0xdc00 && c <= 0xdfff) return false;
72
+ }
73
+ return true;
74
+ }
75
+ // ABI config: mode:u32, cursor:ptr/len, limit:u32, prefix:ptr/len.
76
+ // Strong is the explicit provider mode; it does not establish a page snapshot.
77
+ function __kv_list_config(index: i32, payload: __PulseFastlyValue, config: StaticArray<i32>): i32 {
78
+ const options = __pulse_fastly_value(__pulse_fastly_payload_field(payload, 'options'));
79
+ if (options.kind != PULSE_VALUE_OBJECT) return -1;
80
+ for (let i = 0; i < options.keys.length; i++) if (options.keys[i] != 'limit' && options.keys[i] != 'prefix' && options.keys[i] != 'cursor') return -1;
81
+ const limit = __pulse_fastly_value(__pulse_fastly_payload_field(options, 'limit'));
82
+ if (limit.kind != PULSE_VALUE_NUMBER || !isFinite(limit.number) || limit.number < 1 || limit.number > __KV_listLimit || Math.floor(limit.number) != limit.number) return -1;
83
+ config[3] = i32(limit.number); __kv_list_limits[index] = config[3]; __kv_list_prefixes[index] = '';
84
+ let mask = 4;
85
+ const prefix = __pulse_fastly_value(__pulse_fastly_payload_field(options, 'prefix'));
86
+ if (prefix.kind != PULSE_VALUE_UNDEFINED) {
87
+ if (prefix.kind != PULSE_VALUE_STRING || !__kv_list_text(prefix.text, __KV_keyBytes, true)) return -1;
88
+ __kv_private(prefix.text); __kv_list_prefixes[index] = prefix.text;
89
+ if (prefix.text.length) mask |= 8;
90
+ }
91
+ const cursor = __pulse_fastly_value(__pulse_fastly_payload_field(options, 'cursor'));
92
+ if (cursor.kind != PULSE_VALUE_UNDEFINED) {
93
+ if (cursor.kind != PULSE_VALUE_STRING || !__kv_list_text(cursor.text, __KV_cursorBytes)) return -2;
94
+ __kv_private(cursor.text);
95
+ mask |= 2;
96
+ }
97
+ return mask;
98
+ }
99
+ function __kv_token_valid(token: string): bool {
100
+ if (token.length != 29 || !token.startsWith('fastly-kv-v1:')) return false;
101
+ for (let i = 13; i < 29; i++) { const c = token.charCodeAt(i); if (!(c >= 48 && c <= 57) && !(c >= 97 && c <= 102)) return false; }
102
+ return true;
103
+ }
104
+ function __kv_generation(token: string): u64 {
105
+ let value: u64 = 0;
106
+ for (let i = 13; i < 29; i++) { const c = token.charCodeAt(i); value = (value << 4) | u64(c <= 57 ? c - 48 : c - 87); }
107
+ return value;
108
+ }
109
+ function __kv_token(value: u64): string {
110
+ let text = 'fastly-kv-v1:';
111
+ for (let i = 15; i >= 0; i--) text += '0123456789abcdef'.charAt(i32((value >> (i * 4)) & 15));
112
+ return text;
113
+ }
114
+ function __kv_number(value: f64): string {
115
+ const text = __pulse_fastly_number_string(value);
116
+ // AS prints a trailing .0 for large integral f64s; JSON.stringify does not.
117
+ // Count the portable serialized value budget, including this boundary case.
118
+ return text.endsWith('.0') ? text.substring(0, text.length - 2) : text;
119
+ }
120
+ // Object field names are complete quoted tokens, not substring secrets: a field
121
+ // named "id" must not corrupt "considered", "invalidAcks", or numeric metrics.
122
+ // Values, lookup keys and generations retain raw and JSON-escaped protection.
123
+ function __kv_private(text: string, field: bool = false): string {
124
+ const encoded = __pulse_fastly_quote(text);
125
+ if (field) __pulse_fastly_remember_secret(encoded, true);
126
+ else {
127
+ __pulse_fastly_remember_secret(text);
128
+ __pulse_fastly_remember_secret(encoded.substring(1, encoded.length - 1));
129
+ }
130
+ return encoded;
131
+ }
132
+ class __KvEncoder {
133
+ reason: string = ''; entries: i32 = 0; bytes: i32 = 0;
134
+ seen: Set<i32> = new Set<i32>(); parts: Array<string> | null;
135
+ // Reads need the same validation and redaction walk, but no serialized output.
136
+ constructor(materialize: bool = true) { this.parts = materialize ? new Array<string>() : null; }
137
+ add(text: string): void { this.bytes += String.UTF8.byteLength(text); if (this.bytes > __KV_valueBytes) this.reason = 'too-large'; else if (this.parts !== null) this.parts!.push(text); }
138
+ visit(handle: i32, depth: i32 = 0): void {
139
+ if (this.reason.length) return;
140
+ if (++this.entries > __KV_entries || depth > __KV_depth) { this.reason = 'too-large'; return; }
141
+ const value = __pulse_fastly_value(handle);
142
+ if (value.kind == PULSE_VALUE_NULL) this.add('null');
143
+ else if (value.kind == PULSE_VALUE_BOOLEAN) this.add(value.boolean ? 'true' : 'false');
144
+ else if (value.kind == PULSE_VALUE_STRING) this.add(__kv_private(value.text));
145
+ else if (value.kind == PULSE_VALUE_NUMBER) { if (!isFinite(value.number)) this.reason = 'invalid-value'; else this.add(value.number == 0 ? '0' : __kv_number(value.number)); }
146
+ else if (value.kind == PULSE_VALUE_ARRAY || value.kind == PULSE_VALUE_OBJECT) {
147
+ if (this.seen.has(handle)) { this.reason = 'invalid-value'; return; } this.seen.add(handle);
148
+ const object = value.kind == PULSE_VALUE_OBJECT; this.add(object ? '{' : '[');
149
+ for (let i = 0; i < value.values.length && !this.reason.length; i++) {
150
+ if (i) this.add(',');
151
+ if (object) this.add(__kv_private(value.keys[i], true) + ':');
152
+ this.visit(value.values[i], depth + 1);
153
+ }
154
+ this.add(object ? '}' : ']');
155
+ } else this.reason = 'invalid-value';
156
+ }
157
+ encode(handle: i32): string { this.visit(handle); return this.reason.length ? '' : this.parts!.join(''); }
158
+ }
159
+ function __pulse_fastly_kv_conditional_begin(index: i32, payload: __PulseFastlyValue): void {
160
+ __kv_dispatched[index] = false;
161
+ const start = __kv_clock(); if (start < 0) { __kv_fail(index, 'unavailable'); return; }
162
+ __kv_deadline[index] = start + i64(__KV_timeoutMs) * 1000000;
163
+ if (__kv_request_deadline >= 0 && __kv_request_deadline < __kv_deadline[index]) __kv_deadline[index] = __kv_request_deadline;
164
+ const kind = __pulse_fastly_effect_kind(index), key = __pulse_fastly_value(__pulse_fastly_payload_field(payload, 'key'));
165
+ let listConfig: StaticArray<i32> | null = null;
166
+ let listMask = 0;
167
+ if (__KV_HAS_LIST && kind == 23) {
168
+ listConfig = new StaticArray<i32>(6);
169
+ listMask = __kv_list_config(index, payload, listConfig!);
170
+ if (listMask < 0) { __kv_fail(index, listMask == -2 ? 'invalid-cursor' : 'invalid-options'); return; }
171
+ } else {
172
+ if (key.kind != PULSE_VALUE_STRING || !__kv_key(key.text)) { __kv_fail(index, 'invalid-key'); return; }
173
+ __kv_private(key.text);
174
+ }
175
+ let generation: u64 = 0;
176
+ if (kind == 17) {
177
+ const token = __pulse_fastly_value(__pulse_fastly_payload_field(payload, 'generation'));
178
+ if (token.kind != PULSE_VALUE_STRING || !__kv_token_valid(token.text)) { __kv_fail(index, 'invalid-generation'); return; }
179
+ __kv_private(token.text); generation = __kv_generation(token.text);
180
+ }
181
+ let wire = '';
182
+ if (__KV_HAS_WRITE && (kind == 16 || kind == 17)) {
183
+ const encoder = new __KvEncoder(); const json = encoder.encode(__pulse_fastly_payload_field(payload, 'value'));
184
+ if (encoder.reason.length) { __kv_fail(index, encoder.reason); return; }
185
+ // Immutable string snapshot exists before any binding/body/dispatch hostcall.
186
+ wire = '{"__pulseKv":1,"value":' + json + '}';
187
+ if (String.UTF8.byteLength(wire) > __KV_wireBytes) { __kv_fail(index, 'too-large'); return; }
188
+ }
189
+ if (__kv_expired(index)) return;
190
+ const name = __pulse_fastly_utf8(__pulse_fastly_kv_store(index)), storeHandle = new StaticArray<i32>(1);
191
+ if (fastly_kv_store_open(changetype<usize>(name), name.byteLength, changetype<usize>(storeHandle)) != 0) { __kv_fail(index, 'configuration'); return; }
192
+ if (__kv_expired(index)) return;
193
+ const keyBytes = __pulse_fastly_utf8(key.text), pending = new StaticArray<i32>(1); let status: i32;
194
+ if (__KV_HAS_LIST && kind == 23) {
195
+ const options = __pulse_fastly_value(__pulse_fastly_payload_field(payload, 'options'));
196
+ const prefixBytes = __pulse_fastly_utf8(__kv_list_prefixes[index]);
197
+ const cursor = __pulse_fastly_value(__pulse_fastly_payload_field(options, 'cursor'));
198
+ const cursorBytes = __pulse_fastly_utf8(cursor.kind == PULSE_VALUE_STRING ? cursor.text : '');
199
+ listConfig![1] = i32(changetype<usize>(cursorBytes)); listConfig![2] = cursorBytes.byteLength;
200
+ listConfig![4] = i32(changetype<usize>(prefixBytes)); listConfig![5] = prefixBytes.byteLength;
201
+ status = fastly_kv_store_list(storeHandle[0], listMask, changetype<usize>(listConfig!), changetype<usize>(pending));
202
+ } else if (__KV_HAS_DELETE && kind == 22) {
203
+ const config = new StaticArray<i32>(1);
204
+ __kv_dispatched[index] = true;
205
+ status = fastly_kv_store_delete(storeHandle[0], changetype<usize>(keyBytes), keyBytes.byteLength, 0, changetype<usize>(config), changetype<usize>(pending));
206
+ } else if (__KV_HAS_READ && kind == 15) {
207
+ const config = new StaticArray<i32>(1);
208
+ status = fastly_kv_store_lookup(storeHandle[0], changetype<usize>(keyBytes), keyBytes.byteLength, 0, changetype<usize>(config), changetype<usize>(pending));
209
+ } else if (__KV_HAS_WRITE) {
210
+ const body = new StaticArray<i32>(1), written = new StaticArray<i32>(1);
211
+ if (fastly_http_body_new(changetype<usize>(body)) != 0) { __kv_fail(index, 'transport'); return; }
212
+ if (__kv_expired(index)) { __kv_close(body[0]); return; }
213
+ const bytes = __pulse_fastly_utf8(wire);
214
+ status = fastly_http_body_write(body[0], changetype<usize>(bytes), bytes.byteLength, 0, changetype<usize>(written));
215
+ if (status != 0 || written[0] != bytes.byteLength) { __kv_close(body[0]); __kv_fail(index, status != 0 ? 'transport' : 'protocol'); return; }
216
+ if (__kv_expired(index)) { __kv_close(body[0]); return; }
217
+ const config = new StaticArray<u64>(4); // 32 zeroed bytes, including padding.
218
+ if (kind == 16) store<u32>(changetype<usize>(config), 1);
219
+ else store<u64>(changetype<usize>(config) + 24, generation);
220
+ __kv_dispatched[index] = true; // Entry is the conservative mutation boundary.
221
+ status = fastly_kv_store_insert(storeHandle[0], changetype<usize>(keyBytes), keyBytes.byteLength, body[0], kind == 17 ? 32 : 0, changetype<usize>(config), changetype<usize>(pending));
222
+ // Insert takes ownership on success. On error the body may already be consumed;
223
+ // best-effort close cannot turn uncertain acceptance into rejection.
224
+ if (status != 0) __kv_close(body[0]);
225
+ } else { __kv_fail(index, 'protocol'); return; }
226
+ if (status != 0) { __kv_fail(index, kind == 23 && status == 2 && (listMask & 2) != 0 ? 'invalid-cursor' : 'transport'); return; }
227
+ __pulse_fastly_pending[index] = pending[0]; __pulse_fastly_pending_mode[index] = PULSE_FASTLY_PENDING_ASYNC;
228
+ }
229
+ function __kv_utf8(data: Uint8Array, length: i32): bool {
230
+ for (let i = 0; i < length;) {
231
+ const c = data[i++]; if (c <= 127) continue;
232
+ const count = c >= 194 && c <= 223 ? 1 : c >= 224 && c <= 239 ? 2 : c >= 240 && c <= 244 ? 3 : -1;
233
+ if (count < 0 || i + count > length) return false;
234
+ const second = data[i];
235
+ if ((c == 224 && second < 160) || (c == 237 && second > 159) || (c == 240 && second < 144) || (c == 244 && second > 143)) return false;
236
+ for (let j = 0; j < count; j++) { const next = data[i++]; if (next < 128 || next > 191) return false; }
237
+ }
238
+ return true;
239
+ }
240
+ // Each read is synchronous through owned-string decoding and parsing. Parallel
241
+ // effects enter their waits serially; no result or pending hostcall owns this
242
+ // scratch buffer. Only the written prefix is inspected, including after errors.
243
+ @lazy let __kv_read_buffer: Uint8Array | null = null;
244
+ function __kv_read(index: i32, body: i32, generation: u64): i32 {
245
+ const isList = __KV_HAS_LIST && __pulse_fastly_effect_kind(index) == 23, max = isList ? __KV_envelopeBytes : __KV_wireBytes;
246
+ if (__kv_read_buffer === null || __kv_read_buffer!.length < max + 1) __kv_read_buffer = new Uint8Array(max + 1);
247
+ const buffer = __kv_read_buffer!, written = new StaticArray<i32>(1); let count = 0;
248
+ while (true) {
249
+ const ready = __kv_ready(index, body); if (ready <= 0) return __kv_ready_failure(index, ready);
250
+ written[0] = 0;
251
+ if (fastly_http_body_read(body, buffer.dataStart + count, max + 1 - count, changetype<usize>(written)) != 0) return __kv_failure(index, 'transport');
252
+ if (written[0] < 0 || written[0] > max + 1 - count) return __kv_failure(index, 'protocol');
253
+ if (!written[0]) break;
254
+ count += written[0]; if (count > max) return __kv_failure(index, 'too-large');
255
+ }
256
+ if (!__kv_utf8(buffer, count)) return __kv_failure(index, 'protocol');
257
+ const parser = new __PulseJsonParser(String.UTF8.decodeUnsafe(buffer.dataStart, count, false), true), parsed = parser.parse();
258
+ if (parser.failed || parsed <= 0) return __kv_failure(index, parser.tooLarge ? 'too-large' : 'protocol');
259
+ const outer = __pulse_fastly_value(parsed);
260
+ if (isList) return __kv_list_result(index, outer);
261
+ if (outer.kind != PULSE_VALUE_OBJECT || outer.keys.length != 2 || __pulse_fastly_find(outer, '__pulseKv') < 0 || __pulse_fastly_find(outer, 'value') < 0) return __kv_failure(index, 'protocol');
262
+ const marker = __pulse_fastly_value(__pulse_fastly_payload_field(outer, '__pulseKv'));
263
+ if (marker.kind != PULSE_VALUE_NUMBER || marker.number != 1) return __kv_failure(index, 'protocol');
264
+ const value = __pulse_fastly_payload_field(outer, 'value'), encoder = new __KvEncoder(false); encoder.visit(value);
265
+ if (encoder.reason.length) return __kv_failure(index, encoder.reason);
266
+ const remaining = __kv_remaining(index); if (remaining <= 0) return __kv_failure(index, remaining == 0 ? 'timeout' : 'unavailable');
267
+ const result = __kv_result('found'), token = __kv_token(generation); __kv_private(token);
268
+ __kv_set(result, 'generation', __pulse_fastly_string_value(token)); __kv_set(result, 'value', value);
269
+ __pulse_fastly_deep_freeze(result); return result;
270
+ }
271
+ function __kv_list_result(index: i32, outer: __PulseFastlyValue): i32 {
272
+ if (outer.kind != PULSE_VALUE_OBJECT || outer.keys.length != 2 || __pulse_fastly_find(outer, 'data') < 0 || __pulse_fastly_find(outer, 'meta') < 0) return __kv_failure(index, 'protocol');
273
+ const data = __pulse_fastly_value(__pulse_fastly_payload_field(outer, 'data')), meta = __pulse_fastly_value(__pulse_fastly_payload_field(outer, 'meta'));
274
+ if (data.kind != PULSE_VALUE_ARRAY || data.values.length > __kv_list_limits[index] || meta.kind != PULSE_VALUE_OBJECT) return __kv_failure(index, 'protocol');
275
+ for (let i = 0; i < meta.keys.length; i++) if (meta.keys[i] != 'limit' && meta.keys[i] != 'prefix' && meta.keys[i] != 'next_cursor' && meta.keys[i] != 'consistency') return __kv_failure(index, 'protocol');
276
+ const limit = __pulse_fastly_value(__pulse_fastly_payload_field(meta, 'limit'));
277
+ if (limit.kind != PULSE_VALUE_NUMBER || limit.number != __kv_list_limits[index]) return __kv_failure(index, 'protocol');
278
+ const prefix = __pulse_fastly_value(__pulse_fastly_payload_field(meta, 'prefix'));
279
+ if (prefix.kind != PULSE_VALUE_UNDEFINED && prefix.kind != PULSE_VALUE_NULL && (prefix.kind != PULSE_VALUE_STRING || prefix.text != __kv_list_prefixes[index])) return __kv_failure(index, 'protocol');
280
+ const consistency = __pulse_fastly_value(__pulse_fastly_payload_field(meta, 'consistency'));
281
+ if (consistency.kind != PULSE_VALUE_UNDEFINED && consistency.kind != PULSE_VALUE_NULL && (consistency.kind != PULSE_VALUE_STRING || consistency.text != 'strong')) return __kv_failure(index, 'protocol');
282
+ const keys = host_value_array(), seen = new Set<string>();
283
+ for (let i = 0; i < data.values.length; i++) {
284
+ const key = __pulse_fastly_value(data.values[i]);
285
+ if (key.kind != PULSE_VALUE_STRING || !__kv_list_text(key.text, __KV_keyBytes) || !key.text.startsWith(__kv_list_prefixes[index]) || seen.has(key.text)) return __kv_failure(index, 'protocol');
286
+ seen.add(key.text); __kv_private(key.text); host_value_array_push(keys, data.values[i]);
287
+ }
288
+ const cursor = __pulse_fastly_value(__pulse_fastly_payload_field(meta, 'next_cursor'));
289
+ if (cursor.kind != PULSE_VALUE_UNDEFINED && cursor.kind != PULSE_VALUE_NULL && (cursor.kind != PULSE_VALUE_STRING || !__kv_list_text(cursor.text, __KV_cursorBytes))) return __kv_failure(index, 'protocol');
290
+ if (cursor.kind == PULSE_VALUE_STRING) __kv_private(cursor.text);
291
+ const remaining = __kv_remaining(index); if (remaining <= 0) return __kv_failure(index, remaining == 0 ? 'timeout' : 'unavailable');
292
+ const result = __kv_result('listed'); __kv_set(result, 'keys', keys);
293
+ __kv_set(result, 'cursor', cursor.kind == PULSE_VALUE_STRING ? __pulse_fastly_string_value(cursor.text) : host_value_null());
294
+ return result;
295
+ }
296
+ function __kv_wait(index: i32): i32 {
297
+ if (__pulse_fastly_pending_mode[index] == PULSE_FASTLY_PENDING_READY) return __pulse_fastly_wait_ready(index);
298
+ const pending = __pulse_fastly_pending[index];
299
+ __pulse_fastly_pending_mode[index] = PULSE_FASTLY_PENDING_NONE; __pulse_fastly_pending[index] = 0; __pulse_fastly_payloads[index] = 0;
300
+ // No KV cancel hostcall exists. An expired pending handle is left to invocation
301
+ // teardown; never call an unready wait just to drain it, and never retry.
302
+ const ready = __kv_ready(index, pending); if (ready <= 0) return __kv_ready_failure(index, ready);
303
+ const error = new StaticArray<i32>(1), kind = __pulse_fastly_effect_kind(index);
304
+ if ((__KV_HAS_WRITE || __KV_HAS_DELETE) && kind != 15 && kind != 23) {
305
+ const status = __KV_HAS_DELETE && kind == 22 ? fastly_kv_store_delete_wait(pending, changetype<usize>(error)) : __KV_HAS_WRITE ? fastly_kv_store_insert_wait(pending, changetype<usize>(error)) : 1;
306
+ if (status != 0) return __kv_failure(index, 'transport');
307
+ const remaining = __kv_remaining(index); if (remaining <= 0) return __kv_failure(index, remaining == 0 ? 'timeout' : 'unavailable');
308
+ if (kind == 22 && (error[0] == 1 || error[0] == 3)) return __kv_result(error[0] == 1 ? 'deleted' : 'not-found');
309
+ if (error[0] == 1) return __kv_result('stored');
310
+ if (kind != 22 && (error[0] == 4 || (error[0] == 3 && kind == 17))) return __kv_result('conflict');
311
+ if (error[0] == 2 || error[0] == 5 || error[0] == 7) return __kv_result(kind == 22 ? 'not-deleted' : 'not-stored', error[0] == 2 ? 'rejected' : error[0] == 5 ? 'too-large' : 'throttled');
312
+ return __kv_failure(index, error[0] == 6 ? 'unavailable' : 'protocol');
313
+ }
314
+ const body = new StaticArray<i32>(1), metadata = new Uint8Array(2000), written = new StaticArray<i32>(1), generation = new StaticArray<u64>(1);
315
+ const status = __KV_HAS_LIST && kind == 23 ? fastly_kv_store_list_wait(pending, changetype<usize>(body), changetype<usize>(error)) : __KV_HAS_READ ? fastly_kv_store_lookup_wait_v2(pending, changetype<usize>(body), metadata.dataStart, metadata.length, changetype<usize>(written), changetype<usize>(generation), changetype<usize>(error)) : 1;
316
+ if (status != 0) return __kv_failure(index, 'transport');
317
+ if (error[0] != 1) {
318
+ const remaining = __kv_remaining(index); if (remaining <= 0) return __kv_failure(index, remaining == 0 ? 'timeout' : 'unavailable');
319
+ if (error[0] == 3 && kind == 15) return __kv_result('not-found');
320
+ if (error[0] == 2 && kind == 23) return __kv_failure(index, 'invalid-cursor');
321
+ return __kv_failure(index, error[0] == 5 ? 'too-large' : error[0] == 6 ? 'unavailable' : error[0] == 7 ? 'throttled' : 'protocol');
322
+ }
323
+ const result = written[0] < 0 || written[0] > metadata.length ? __kv_failure(index, 'protocol') : __kv_read(index, body[0], generation[0]);
324
+ __kv_close(body[0]); return result;
325
+ }
326
+
327
+ function __pulse_fastly_kv_conditional_wait(index: i32): i32 {
328
+ const result = __kv_wait(index);
329
+ if (__KV_HAS_LIST) { __kv_list_prefixes[index] = ''; __kv_list_limits[index] = 0; }
330
+ __pulse_fastly_deep_freeze(result); return result;
331
+ }
@@ -0,0 +1,27 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const { KV_CONDITIONAL_KINDS, KV_CONDITIONAL_LIMITS } = require('@pulse-compute/runtime/host');
5
+
6
+ const KV_IMPORTS = Object.freeze([
7
+ 'fastly_async_io:select', 'fastly_http_body:close', 'wasi_snapshot_preview1:clock_time_get',
8
+ 'fastly_kv_store:open'
9
+ ]);
10
+ function kvImports(kind) {
11
+ if (kind === 'kv.list') return [...KV_IMPORTS, 'fastly_kv_store:list', 'fastly_kv_store:list_wait', 'fastly_http_body:read'];
12
+ if (kind === 'kv.delete') return [...KV_IMPORTS.filter(key => key !== 'fastly_http_body:close'), 'fastly_kv_store:delete', 'fastly_kv_store:delete_wait'];
13
+ return [...KV_IMPORTS, ...(kind === 'kv.getVersioned'
14
+ ? ['fastly_kv_store:lookup', 'fastly_kv_store:lookup_wait_v2', 'fastly_http_body:read']
15
+ : ['fastly_kv_store:insert', 'fastly_kv_store:insert_wait', 'fastly_http_body:new', 'fastly_http_body:write'])];
16
+ }
17
+ function kvNativeSource(plan) {
18
+ if (!plan.effects.some(effect => KV_CONDITIONAL_KINDS.includes(effect.kind))) return '';
19
+ const limits = Object.entries(KV_CONDITIONAL_LIMITS).map(([key, value]) => `const __KV_${key}: i32 = ${value};`).join('\n');
20
+ const kinds = new Set(plan.effects.map(effect => effect.kind));
21
+ const selection = `const __KV_HAS_READ: bool = ${kinds.has('kv.getVersioned')};
22
+ const __KV_HAS_WRITE: bool = ${kinds.has('kv.insertIfAbsent') || kinds.has('kv.compareAndSwap')};
23
+ const __KV_HAS_LIST: bool = ${kinds.has('kv.list')};
24
+ const __KV_HAS_DELETE: bool = ${kinds.has('kv.delete')};`;
25
+ return limits + '\n' + selection + '\n' + fs.readFileSync(path.join(__dirname, 'kv-native.as.ts'), 'utf8');
26
+ }
27
+ module.exports = { KV_CONDITIONAL_KINDS, KV_CONDITIONAL_LIMITS, KV_IMPORTS, kvImports, kvNativeSource };