@abyss-project/runtime 3.0.0 → 3.2.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.
Files changed (41) hide show
  1. package/README.md +31 -0
  2. package/dist/discord/discord.types.d.ts +135 -0
  3. package/dist/discord/discord.types.js +59 -0
  4. package/dist/discord/discord.types.js.map +1 -0
  5. package/dist/index.d.ts +1 -0
  6. package/dist/index.js +1 -0
  7. package/dist/index.js.map +1 -1
  8. package/dist/runner-protocol/execution-protocol.types.js.map +1 -1
  9. package/package.json +1 -1
  10. package/scripts/build-engine.cjs +70 -70
  11. package/src/__tests__/engine-bundle.test.ts +121 -121
  12. package/src/cost/__tests__/execution-cost.test.ts +196 -196
  13. package/src/cost/execution-cost.ts +186 -186
  14. package/src/definition/__tests__/validate-definition.test.ts +354 -354
  15. package/src/definition/definition.limits.ts +9 -9
  16. package/src/definition/definition.schema.ts +172 -172
  17. package/src/definition/definition.types.ts +171 -171
  18. package/src/discord/discord.types.ts +181 -0
  19. package/src/engine/__tests__/run-in-isolate.test.ts +468 -468
  20. package/src/engine/engine-entry.ts +3 -3
  21. package/src/engine/engine-global.ts +2 -2
  22. package/src/engine/run-in-isolate.ts +404 -404
  23. package/src/errors/runtime-error-code.enum.ts +37 -37
  24. package/src/index.ts +31 -30
  25. package/src/interpreter/__tests__/interpreter.test.ts +854 -854
  26. package/src/interpreter/__tests__/log-respond-resume.test.ts +223 -223
  27. package/src/interpreter/interpreter.ts +461 -461
  28. package/src/interpreter/interpreter.types.ts +192 -192
  29. package/src/interpreter/test-host.ts +85 -85
  30. package/src/runner-protocol/evaluation.types.ts +21 -21
  31. package/src/runner-protocol/execution-protocol.types.ts +231 -225
  32. package/src/server/__tests__/code-runner-session.test.ts +311 -311
  33. package/src/server/code-runner-error.ts +12 -12
  34. package/src/server/code-runner-session.ts +310 -310
  35. package/src/server/index.ts +11 -11
  36. package/src/steps/__tests__/global-references.test.ts +133 -113
  37. package/src/steps/execute-step.ts +186 -186
  38. package/src/steps/global-references.ts +48 -48
  39. package/src/steps/step-access.ts +56 -56
  40. package/src/steps/step-fields.ts +87 -87
  41. package/src/steps/value-source.ts +69 -69
@@ -1,121 +1,121 @@
1
- import * as vm from 'vm';
2
- import { AccessKind } from '../access/access.types';
3
- import {
4
- CURRENT_FORMAT_VERSION,
5
- HttpMethod,
6
- LogLevel,
7
- StepType,
8
- StopStatus,
9
- } from '../definition/definition.types';
10
- import type { RuntimeDefinition } from '../definition/definition.types';
11
- import { ENGINE_GLOBAL_NAME } from '../engine/engine-global';
12
- import { EngineResultKind } from '../engine/run-in-isolate';
13
- import type { EngineHost, EngineRequest, EngineResult } from '../engine/run-in-isolate';
14
- import type { EvaluationItem } from '../runner-protocol/evaluation.types';
15
- import { CoreCapability, ExecutionStatus } from '../runner-protocol/execution-protocol.types';
16
-
17
- // The build script is plain CommonJS, shared with `build`: the test bundles exactly what ships.
18
- // eslint-disable-next-line @typescript-eslint/no-require-imports
19
- const { bundleEngine } = require('../../scripts/build-engine.cjs') as {
20
- bundleEngine: (globalName: string) => string;
21
- };
22
-
23
- type Engine = { runInIsolate: (request: EngineRequest, host: EngineHost) => Promise<EngineResult> };
24
-
25
- const definition: RuntimeDefinition = {
26
- formatVersion: CURRENT_FORMAT_VERSION,
27
- accesses: [{ kind: AccessKind.HTTP, hosts: ['api.example.com'] }],
28
- steps: [
29
- { id: 'double', type: StepType.SET, variable: 'n', value: { $expression: 'input.n * 2' } },
30
- {
31
- id: 'fetch',
32
- type: StepType.HTTP,
33
- method: HttpMethod.GET,
34
- url: 'https://api.example.com/{{ vars.n }}',
35
- },
36
- { id: 'note', type: StepType.LOG, level: LogLevel.INFO, message: 'fetched' },
37
- {
38
- id: 'end',
39
- type: StepType.STOP,
40
- status: StopStatus.SUCCEEDED,
41
- output: { $expression: 'vars.n' },
42
- },
43
- ],
44
- };
45
-
46
- describe('isolate engine bundle', () => {
47
- let source: string;
48
-
49
- beforeAll(() => {
50
- source = bundleEngine(ENGINE_GLOBAL_NAME);
51
- });
52
-
53
- it('carries no module loader and no Joi', () => {
54
- expect(source).not.toMatch(/\brequire\s*\(/);
55
- expect(source).not.toMatch(/joi/i);
56
- });
57
-
58
- it('loads in a bare context and runs a definition with a fake evaluate and callHost', async () => {
59
- // No `require`, `process`, `URL`, timers nor console: only the language built-ins.
60
- const context = vm.createContext({});
61
- vm.runInContext(source, context);
62
- expect(vm.runInContext('typeof require + typeof process + typeof URL', context)).toBe(
63
- 'undefinedundefinedundefined',
64
- );
65
- const engine = (context as Record<string, unknown>)[ENGINE_GLOBAL_NAME] as Engine;
66
- expect(typeof engine.runInIsolate).toBe('function');
67
-
68
- const values: Record<string, unknown> = {
69
- 'input.n * 2': 42,
70
- 'https://api.example.com/{{ vars.n }}': 'https://api.example.com/42',
71
- 'vars.n': 42,
72
- };
73
- const calls: Array<{ stepId: string; capability: string; args: unknown }> = [];
74
- const progress: string[] = [];
75
- const host: EngineHost = {
76
- evaluate: async (items: EvaluationItem[]) =>
77
- items.map((item) => ({ id: item.id, ok: true as const, value: values[item.source] })),
78
- callHost: async (stepId, capability, args) => {
79
- calls.push({ stepId, capability, args });
80
- return {
81
- ok: true,
82
- value:
83
- capability === CoreCapability.HTTP_FETCH
84
- ? { status: 200, headers: {}, body: null }
85
- : null,
86
- };
87
- },
88
- onProgress: (p) => progress.push(`${p.stepId}:${p.phase}`),
89
- now: () => 0,
90
- };
91
-
92
- const result = await engine.runInIsolate(
93
- {
94
- definition,
95
- input: { n: 21 },
96
- capabilities: [CoreCapability.HTTP_FETCH, CoreCapability.LOG_WRITE],
97
- budget: { maxSteps: 10, maxEffects: 10 },
98
- },
99
- host,
100
- );
101
-
102
- // Values built in the other realm: compare their JSON.
103
- expect(JSON.parse(JSON.stringify(result))).toEqual({
104
- kind: EngineResultKind.FINISHED,
105
- outcome: { status: ExecutionStatus.SUCCEEDED, output: 42 },
106
- });
107
- expect(JSON.parse(JSON.stringify(calls))).toEqual([
108
- {
109
- stepId: 'fetch',
110
- capability: CoreCapability.HTTP_FETCH,
111
- args: { method: 'GET', url: 'https://api.example.com/42', headers: {} },
112
- },
113
- {
114
- stepId: 'note',
115
- capability: CoreCapability.LOG_WRITE,
116
- args: { level: LogLevel.INFO, message: 'fetched' },
117
- },
118
- ]);
119
- expect(progress).toHaveLength(8);
120
- });
121
- });
1
+ import * as vm from 'vm';
2
+ import { AccessKind } from '../access/access.types';
3
+ import {
4
+ CURRENT_FORMAT_VERSION,
5
+ HttpMethod,
6
+ LogLevel,
7
+ StepType,
8
+ StopStatus,
9
+ } from '../definition/definition.types';
10
+ import type { RuntimeDefinition } from '../definition/definition.types';
11
+ import { ENGINE_GLOBAL_NAME } from '../engine/engine-global';
12
+ import { EngineResultKind } from '../engine/run-in-isolate';
13
+ import type { EngineHost, EngineRequest, EngineResult } from '../engine/run-in-isolate';
14
+ import type { EvaluationItem } from '../runner-protocol/evaluation.types';
15
+ import { CoreCapability, ExecutionStatus } from '../runner-protocol/execution-protocol.types';
16
+
17
+ // The build script is plain CommonJS, shared with `build`: the test bundles exactly what ships.
18
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
19
+ const { bundleEngine } = require('../../scripts/build-engine.cjs') as {
20
+ bundleEngine: (globalName: string) => string;
21
+ };
22
+
23
+ type Engine = { runInIsolate: (request: EngineRequest, host: EngineHost) => Promise<EngineResult> };
24
+
25
+ const definition: RuntimeDefinition = {
26
+ formatVersion: CURRENT_FORMAT_VERSION,
27
+ accesses: [{ kind: AccessKind.HTTP, hosts: ['api.example.com'] }],
28
+ steps: [
29
+ { id: 'double', type: StepType.SET, variable: 'n', value: { $expression: 'input.n * 2' } },
30
+ {
31
+ id: 'fetch',
32
+ type: StepType.HTTP,
33
+ method: HttpMethod.GET,
34
+ url: 'https://api.example.com/{{ vars.n }}',
35
+ },
36
+ { id: 'note', type: StepType.LOG, level: LogLevel.INFO, message: 'fetched' },
37
+ {
38
+ id: 'end',
39
+ type: StepType.STOP,
40
+ status: StopStatus.SUCCEEDED,
41
+ output: { $expression: 'vars.n' },
42
+ },
43
+ ],
44
+ };
45
+
46
+ describe('isolate engine bundle', () => {
47
+ let source: string;
48
+
49
+ beforeAll(() => {
50
+ source = bundleEngine(ENGINE_GLOBAL_NAME);
51
+ });
52
+
53
+ it('carries no module loader and no Joi', () => {
54
+ expect(source).not.toMatch(/\brequire\s*\(/);
55
+ expect(source).not.toMatch(/joi/i);
56
+ });
57
+
58
+ it('loads in a bare context and runs a definition with a fake evaluate and callHost', async () => {
59
+ // No `require`, `process`, `URL`, timers nor console: only the language built-ins.
60
+ const context = vm.createContext({});
61
+ vm.runInContext(source, context);
62
+ expect(vm.runInContext('typeof require + typeof process + typeof URL', context)).toBe(
63
+ 'undefinedundefinedundefined',
64
+ );
65
+ const engine = (context as Record<string, unknown>)[ENGINE_GLOBAL_NAME] as Engine;
66
+ expect(typeof engine.runInIsolate).toBe('function');
67
+
68
+ const values: Record<string, unknown> = {
69
+ 'input.n * 2': 42,
70
+ 'https://api.example.com/{{ vars.n }}': 'https://api.example.com/42',
71
+ 'vars.n': 42,
72
+ };
73
+ const calls: Array<{ stepId: string; capability: string; args: unknown }> = [];
74
+ const progress: string[] = [];
75
+ const host: EngineHost = {
76
+ evaluate: async (items: EvaluationItem[]) =>
77
+ items.map((item) => ({ id: item.id, ok: true as const, value: values[item.source] })),
78
+ callHost: async (stepId, capability, args) => {
79
+ calls.push({ stepId, capability, args });
80
+ return {
81
+ ok: true,
82
+ value:
83
+ capability === CoreCapability.HTTP_FETCH
84
+ ? { status: 200, headers: {}, body: null }
85
+ : null,
86
+ };
87
+ },
88
+ onProgress: (p) => progress.push(`${p.stepId}:${p.phase}`),
89
+ now: () => 0,
90
+ };
91
+
92
+ const result = await engine.runInIsolate(
93
+ {
94
+ definition,
95
+ input: { n: 21 },
96
+ capabilities: [CoreCapability.HTTP_FETCH, CoreCapability.LOG_WRITE],
97
+ budget: { maxSteps: 10, maxEffects: 10 },
98
+ },
99
+ host,
100
+ );
101
+
102
+ // Values built in the other realm: compare their JSON.
103
+ expect(JSON.parse(JSON.stringify(result))).toEqual({
104
+ kind: EngineResultKind.FINISHED,
105
+ outcome: { status: ExecutionStatus.SUCCEEDED, output: 42 },
106
+ });
107
+ expect(JSON.parse(JSON.stringify(calls))).toEqual([
108
+ {
109
+ stepId: 'fetch',
110
+ capability: CoreCapability.HTTP_FETCH,
111
+ args: { method: 'GET', url: 'https://api.example.com/42', headers: {} },
112
+ },
113
+ {
114
+ stepId: 'note',
115
+ capability: CoreCapability.LOG_WRITE,
116
+ args: { level: LogLevel.INFO, message: 'fetched' },
117
+ },
118
+ ]);
119
+ expect(progress).toHaveLength(8);
120
+ });
121
+ });
@@ -1,196 +1,196 @@
1
- import {
2
- COST_RATES,
3
- CostedExecutionStatus,
4
- RESOURCE_PROFILES,
5
- ResourceProfile,
6
- computeExecutionCost,
7
- computeStepCost,
8
- } from '../execution-cost';
9
- import type { ExecutionCostInput, StepUsage } from '../execution-cost';
10
-
11
- const NO_USAGE: StepUsage = { cpuMs: 0, wallMs: 0, netOutBytes: 0, httpCalls: 0, storeWrites: 0 };
12
-
13
- const execution = (overrides: Partial<ExecutionCostInput> = {}): ExecutionCostInput => ({
14
- ...NO_USAGE,
15
- status: CostedExecutionStatus.RAN,
16
- profile: ResourceProfile.S,
17
- ...overrides,
18
- });
19
-
20
- const usage = (overrides: Partial<StepUsage>): StepUsage => ({ ...NO_USAGE, ...overrides });
21
-
22
- const sum = (values: number[]): number => values.reduce((total, value) => total + value, 0);
23
-
24
- describe('resource profiles and rates', () => {
25
- it('follow ADR-0240', () => {
26
- expect(RESOURCE_PROFILES).toEqual({
27
- S: { memoryMb: 128, cpuCoefficient: 1 },
28
- M: { memoryMb: 256, cpuCoefficient: 1.05 },
29
- L: { memoryMb: 512, cpuCoefficient: 1.1 },
30
- XL: { memoryMb: 1024, cpuCoefficient: 1.2 },
31
- XXL: { memoryMb: 2048, cpuCoefficient: 1.35 },
32
- });
33
- expect(COST_RATES).toEqual({
34
- executionMillicredits: 10,
35
- cpuMillicreditsPerSecond: 500,
36
- memoryMillicreditsPerGbSecond: 100,
37
- networkOutMillicreditsPerMb: 1000,
38
- httpCallMillicredits: 10,
39
- storeWriteMillicredits: 10,
40
- });
41
- });
42
- });
43
-
44
- describe('computeExecutionCost', () => {
45
- it('prices a 3 s wait in profile S at about 0.05 credit', () => {
46
- // 10 + 0.125 GB × 3 s × 100 = 47.5, rounded half-up.
47
- const cost = computeExecutionCost(execution({ wallMs: 3_000 }));
48
- expect(cost).toBe(48);
49
- expect(cost / 1000).toBeCloseTo(0.05, 2);
50
- });
51
-
52
- it('prices 2 s of CPU in profile L at about 1.1 credits for the CPU part', () => {
53
- const computing = computeExecutionCost(
54
- execution({ profile: ResourceProfile.L, cpuMs: 2_000, wallMs: 2_000 }),
55
- );
56
- const waiting = computeExecutionCost(execution({ profile: ResourceProfile.L, wallMs: 2_000 }));
57
- expect(computing - waiting).toBe(1_100);
58
- // 10 + 1100 CPU + 0.5 GB × 2 s × 100 memory.
59
- expect(computing).toBe(1_210);
60
- });
61
-
62
- it('makes a computation cost more than a wait of the same duration', () => {
63
- const wall = { wallMs: 3_000 };
64
- expect(computeExecutionCost(execution({ ...wall, cpuMs: 3_000 }))).toBeGreaterThan(
65
- computeExecutionCost(execution(wall)),
66
- );
67
- });
68
-
69
- it('applies the profile coefficient to the CPU part', () => {
70
- const cpu = { cpuMs: 1_000 };
71
- expect(computeExecutionCost(execution(cpu))).toBe(10 + 500);
72
- expect(computeExecutionCost(execution({ ...cpu, profile: ResourceProfile.M }))).toBe(10 + 525);
73
- expect(computeExecutionCost(execution({ ...cpu, profile: ResourceProfile.XXL }))).toBe(
74
- 10 + 675,
75
- );
76
- // 500 × 1.05 × 0.001 = 0.525: rounded half-up once, at the end.
77
- expect(computeExecutionCost(execution({ cpuMs: 1, profile: ResourceProfile.M }))).toBe(10 + 1);
78
- });
79
-
80
- it('prices the allocated memory, the network out and the effects', () => {
81
- expect(computeExecutionCost(execution({ profile: ResourceProfile.XL, wallMs: 1_000 }))).toBe(
82
- 10 + 100,
83
- );
84
- expect(computeExecutionCost(execution({ netOutBytes: 1024 * 1024 }))).toBe(10 + 1_000);
85
- expect(computeExecutionCost(execution({ httpCalls: 2, storeWrites: 3 }))).toBe(10 + 50);
86
- });
87
-
88
- it('rounds half-up once, at the end', () => {
89
- // 128 MB × 40 ms = 0.5 millicredit.
90
- expect(computeExecutionCost(execution({ wallMs: 40 }))).toBe(11);
91
- // Fractions of a millisecond count.
92
- expect(computeExecutionCost(execution({ cpuMs: 0.999 }))).toBe(10);
93
- expect(computeExecutionCost(execution({ cpuMs: 1 }))).toBe(11);
94
- });
95
-
96
- it('makes an interrupted or refused execution free', () => {
97
- const heavy = { cpuMs: 5_000, wallMs: 9_000, netOutBytes: 10_000_000, httpCalls: 4 };
98
- expect(
99
- computeExecutionCost(execution({ ...heavy, status: CostedExecutionStatus.INTERRUPTED })),
100
- ).toBe(0);
101
- expect(
102
- computeExecutionCost(execution({ ...heavy, status: CostedExecutionStatus.REFUSED })),
103
- ).toBe(0);
104
- });
105
-
106
- it('charges the execution price once: a resumed segment adds only its measure', () => {
107
- expect(computeExecutionCost(execution({ wallMs: 3_000, resumedSegment: true }))).toBe(38);
108
- });
109
-
110
- it('refuses a negative or non-finite measure', () => {
111
- expect(() => computeExecutionCost(execution({ cpuMs: -1 }))).toThrow(RangeError);
112
- expect(() => computeExecutionCost(execution({ wallMs: Number.NaN }))).toThrow(RangeError);
113
- });
114
- });
115
-
116
- describe('computeStepCost', () => {
117
- it('gives each step its share, so that steps plus the execution price equal the total', () => {
118
- const steps = [
119
- usage({ cpuMs: 3.3, wallMs: 12.7 }),
120
- usage({ cpuMs: 120.25, wallMs: 450, httpCalls: 1, netOutBytes: 2_345 }),
121
- usage({ wallMs: 3_000 }),
122
- usage({ cpuMs: 7.77, wallMs: 9.1, storeWrites: 2 }),
123
- ];
124
- const total = execution({
125
- profile: ResourceProfile.M,
126
- // The engine between the steps adds CPU and time measured at the execution level only.
127
- cpuMs: 140,
128
- wallMs: 3_500,
129
- httpCalls: 1,
130
- storeWrites: 2,
131
- netOutBytes: 2_345,
132
- });
133
- const costs = computeStepCost({ execution: total, steps });
134
- expect(costs).toHaveLength(4);
135
- costs.forEach((cost) => expect(Number.isInteger(cost)).toBe(true));
136
- expect(sum(costs) + COST_RATES.executionMillicredits).toBe(computeExecutionCost(total));
137
- expect(costs[2]).toBeGreaterThan(costs[0]);
138
- });
139
-
140
- it('holds the invariant over many shapes', () => {
141
- for (let n = 1; n <= 40; n += 1) {
142
- const steps = Array.from({ length: n }, (_, i) =>
143
- usage({ cpuMs: (i * 7.3) % 11, wallMs: (i * 13.1) % 29, httpCalls: i % 3 === 0 ? 1 : 0 }),
144
- );
145
- const totals = steps.reduce(
146
- (acc, step) => ({
147
- cpuMs: acc.cpuMs + step.cpuMs,
148
- wallMs: acc.wallMs + step.wallMs,
149
- httpCalls: acc.httpCalls + step.httpCalls,
150
- }),
151
- { cpuMs: 0.37 * n, wallMs: 1.9 * n, httpCalls: 0 },
152
- );
153
- for (const profile of Object.values(ResourceProfile)) {
154
- const total = execution({ ...totals, profile });
155
- const costs = computeStepCost({ execution: total, steps });
156
- expect(sum(costs) + COST_RATES.executionMillicredits).toBe(computeExecutionCost(total));
157
- }
158
- }
159
- });
160
-
161
- it('rounds cumulatively instead of rounding each step', () => {
162
- // Three steps of 0.4 millicredit each (128 MB × 32 ms): 1.2 in total.
163
- const step = usage({ wallMs: 32 });
164
- const total = execution({ wallMs: 96 });
165
- expect(computeExecutionCost(total)).toBe(11);
166
- expect(computeStepCost({ execution: total, steps: [step, step, step] })).toEqual([0, 1, 0]);
167
- });
168
-
169
- it('carries no execution price on a resumed segment', () => {
170
- const total = execution({ wallMs: 3_000, resumedSegment: true });
171
- const costs = computeStepCost({ execution: total, steps: [usage({ wallMs: 3_000 })] });
172
- expect(sum(costs)).toBe(computeExecutionCost(total));
173
- });
174
-
175
- it('is zero for every step of an interrupted execution', () => {
176
- const total = execution({
177
- status: CostedExecutionStatus.INTERRUPTED,
178
- cpuMs: 900,
179
- wallMs: 2_000,
180
- });
181
- expect(
182
- computeStepCost({ execution: total, steps: [usage({ cpuMs: 400 }), usage({ cpuMs: 500 })] }),
183
- ).toEqual([0, 0]);
184
- expect(computeExecutionCost(total)).toBe(0);
185
- });
186
-
187
- it('returns nothing for an execution without step', () => {
188
- expect(computeStepCost({ execution: execution({ wallMs: 10 }), steps: [] })).toEqual([]);
189
- });
190
-
191
- it('refuses a negative step measure', () => {
192
- expect(() =>
193
- computeStepCost({ execution: execution(), steps: [usage({ httpCalls: -1 })] }),
194
- ).toThrow(RangeError);
195
- });
196
- });
1
+ import {
2
+ COST_RATES,
3
+ CostedExecutionStatus,
4
+ RESOURCE_PROFILES,
5
+ ResourceProfile,
6
+ computeExecutionCost,
7
+ computeStepCost,
8
+ } from '../execution-cost';
9
+ import type { ExecutionCostInput, StepUsage } from '../execution-cost';
10
+
11
+ const NO_USAGE: StepUsage = { cpuMs: 0, wallMs: 0, netOutBytes: 0, httpCalls: 0, storeWrites: 0 };
12
+
13
+ const execution = (overrides: Partial<ExecutionCostInput> = {}): ExecutionCostInput => ({
14
+ ...NO_USAGE,
15
+ status: CostedExecutionStatus.RAN,
16
+ profile: ResourceProfile.S,
17
+ ...overrides,
18
+ });
19
+
20
+ const usage = (overrides: Partial<StepUsage>): StepUsage => ({ ...NO_USAGE, ...overrides });
21
+
22
+ const sum = (values: number[]): number => values.reduce((total, value) => total + value, 0);
23
+
24
+ describe('resource profiles and rates', () => {
25
+ it('follow ADR-0244', () => {
26
+ expect(RESOURCE_PROFILES).toEqual({
27
+ S: { memoryMb: 128, cpuCoefficient: 1 },
28
+ M: { memoryMb: 256, cpuCoefficient: 1.05 },
29
+ L: { memoryMb: 512, cpuCoefficient: 1.1 },
30
+ XL: { memoryMb: 1024, cpuCoefficient: 1.2 },
31
+ XXL: { memoryMb: 2048, cpuCoefficient: 1.35 },
32
+ });
33
+ expect(COST_RATES).toEqual({
34
+ executionMillicredits: 10,
35
+ cpuMillicreditsPerSecond: 500,
36
+ memoryMillicreditsPerGbSecond: 100,
37
+ networkOutMillicreditsPerMb: 1000,
38
+ httpCallMillicredits: 10,
39
+ storeWriteMillicredits: 10,
40
+ });
41
+ });
42
+ });
43
+
44
+ describe('computeExecutionCost', () => {
45
+ it('prices a 3 s wait in profile S at about 0.05 credit', () => {
46
+ // 10 + 0.125 GB × 3 s × 100 = 47.5, rounded half-up.
47
+ const cost = computeExecutionCost(execution({ wallMs: 3_000 }));
48
+ expect(cost).toBe(48);
49
+ expect(cost / 1000).toBeCloseTo(0.05, 2);
50
+ });
51
+
52
+ it('prices 2 s of CPU in profile L at about 1.1 credits for the CPU part', () => {
53
+ const computing = computeExecutionCost(
54
+ execution({ profile: ResourceProfile.L, cpuMs: 2_000, wallMs: 2_000 }),
55
+ );
56
+ const waiting = computeExecutionCost(execution({ profile: ResourceProfile.L, wallMs: 2_000 }));
57
+ expect(computing - waiting).toBe(1_100);
58
+ // 10 + 1100 CPU + 0.5 GB × 2 s × 100 memory.
59
+ expect(computing).toBe(1_210);
60
+ });
61
+
62
+ it('makes a computation cost more than a wait of the same duration', () => {
63
+ const wall = { wallMs: 3_000 };
64
+ expect(computeExecutionCost(execution({ ...wall, cpuMs: 3_000 }))).toBeGreaterThan(
65
+ computeExecutionCost(execution(wall)),
66
+ );
67
+ });
68
+
69
+ it('applies the profile coefficient to the CPU part', () => {
70
+ const cpu = { cpuMs: 1_000 };
71
+ expect(computeExecutionCost(execution(cpu))).toBe(10 + 500);
72
+ expect(computeExecutionCost(execution({ ...cpu, profile: ResourceProfile.M }))).toBe(10 + 525);
73
+ expect(computeExecutionCost(execution({ ...cpu, profile: ResourceProfile.XXL }))).toBe(
74
+ 10 + 675,
75
+ );
76
+ // 500 × 1.05 × 0.001 = 0.525: rounded half-up once, at the end.
77
+ expect(computeExecutionCost(execution({ cpuMs: 1, profile: ResourceProfile.M }))).toBe(10 + 1);
78
+ });
79
+
80
+ it('prices the allocated memory, the network out and the effects', () => {
81
+ expect(computeExecutionCost(execution({ profile: ResourceProfile.XL, wallMs: 1_000 }))).toBe(
82
+ 10 + 100,
83
+ );
84
+ expect(computeExecutionCost(execution({ netOutBytes: 1024 * 1024 }))).toBe(10 + 1_000);
85
+ expect(computeExecutionCost(execution({ httpCalls: 2, storeWrites: 3 }))).toBe(10 + 50);
86
+ });
87
+
88
+ it('rounds half-up once, at the end', () => {
89
+ // 128 MB × 40 ms = 0.5 millicredit.
90
+ expect(computeExecutionCost(execution({ wallMs: 40 }))).toBe(11);
91
+ // Fractions of a millisecond count.
92
+ expect(computeExecutionCost(execution({ cpuMs: 0.999 }))).toBe(10);
93
+ expect(computeExecutionCost(execution({ cpuMs: 1 }))).toBe(11);
94
+ });
95
+
96
+ it('makes an interrupted or refused execution free', () => {
97
+ const heavy = { cpuMs: 5_000, wallMs: 9_000, netOutBytes: 10_000_000, httpCalls: 4 };
98
+ expect(
99
+ computeExecutionCost(execution({ ...heavy, status: CostedExecutionStatus.INTERRUPTED })),
100
+ ).toBe(0);
101
+ expect(
102
+ computeExecutionCost(execution({ ...heavy, status: CostedExecutionStatus.REFUSED })),
103
+ ).toBe(0);
104
+ });
105
+
106
+ it('charges the execution price once: a resumed segment adds only its measure', () => {
107
+ expect(computeExecutionCost(execution({ wallMs: 3_000, resumedSegment: true }))).toBe(38);
108
+ });
109
+
110
+ it('refuses a negative or non-finite measure', () => {
111
+ expect(() => computeExecutionCost(execution({ cpuMs: -1 }))).toThrow(RangeError);
112
+ expect(() => computeExecutionCost(execution({ wallMs: Number.NaN }))).toThrow(RangeError);
113
+ });
114
+ });
115
+
116
+ describe('computeStepCost', () => {
117
+ it('gives each step its share, so that steps plus the execution price equal the total', () => {
118
+ const steps = [
119
+ usage({ cpuMs: 3.3, wallMs: 12.7 }),
120
+ usage({ cpuMs: 120.25, wallMs: 450, httpCalls: 1, netOutBytes: 2_345 }),
121
+ usage({ wallMs: 3_000 }),
122
+ usage({ cpuMs: 7.77, wallMs: 9.1, storeWrites: 2 }),
123
+ ];
124
+ const total = execution({
125
+ profile: ResourceProfile.M,
126
+ // The engine between the steps adds CPU and time measured at the execution level only.
127
+ cpuMs: 140,
128
+ wallMs: 3_500,
129
+ httpCalls: 1,
130
+ storeWrites: 2,
131
+ netOutBytes: 2_345,
132
+ });
133
+ const costs = computeStepCost({ execution: total, steps });
134
+ expect(costs).toHaveLength(4);
135
+ costs.forEach((cost) => expect(Number.isInteger(cost)).toBe(true));
136
+ expect(sum(costs) + COST_RATES.executionMillicredits).toBe(computeExecutionCost(total));
137
+ expect(costs[2]).toBeGreaterThan(costs[0]);
138
+ });
139
+
140
+ it('holds the invariant over many shapes', () => {
141
+ for (let n = 1; n <= 40; n += 1) {
142
+ const steps = Array.from({ length: n }, (_, i) =>
143
+ usage({ cpuMs: (i * 7.3) % 11, wallMs: (i * 13.1) % 29, httpCalls: i % 3 === 0 ? 1 : 0 }),
144
+ );
145
+ const totals = steps.reduce(
146
+ (acc, step) => ({
147
+ cpuMs: acc.cpuMs + step.cpuMs,
148
+ wallMs: acc.wallMs + step.wallMs,
149
+ httpCalls: acc.httpCalls + step.httpCalls,
150
+ }),
151
+ { cpuMs: 0.37 * n, wallMs: 1.9 * n, httpCalls: 0 },
152
+ );
153
+ for (const profile of Object.values(ResourceProfile)) {
154
+ const total = execution({ ...totals, profile });
155
+ const costs = computeStepCost({ execution: total, steps });
156
+ expect(sum(costs) + COST_RATES.executionMillicredits).toBe(computeExecutionCost(total));
157
+ }
158
+ }
159
+ });
160
+
161
+ it('rounds cumulatively instead of rounding each step', () => {
162
+ // Three steps of 0.4 millicredit each (128 MB × 32 ms): 1.2 in total.
163
+ const step = usage({ wallMs: 32 });
164
+ const total = execution({ wallMs: 96 });
165
+ expect(computeExecutionCost(total)).toBe(11);
166
+ expect(computeStepCost({ execution: total, steps: [step, step, step] })).toEqual([0, 1, 0]);
167
+ });
168
+
169
+ it('carries no execution price on a resumed segment', () => {
170
+ const total = execution({ wallMs: 3_000, resumedSegment: true });
171
+ const costs = computeStepCost({ execution: total, steps: [usage({ wallMs: 3_000 })] });
172
+ expect(sum(costs)).toBe(computeExecutionCost(total));
173
+ });
174
+
175
+ it('is zero for every step of an interrupted execution', () => {
176
+ const total = execution({
177
+ status: CostedExecutionStatus.INTERRUPTED,
178
+ cpuMs: 900,
179
+ wallMs: 2_000,
180
+ });
181
+ expect(
182
+ computeStepCost({ execution: total, steps: [usage({ cpuMs: 400 }), usage({ cpuMs: 500 })] }),
183
+ ).toEqual([0, 0]);
184
+ expect(computeExecutionCost(total)).toBe(0);
185
+ });
186
+
187
+ it('returns nothing for an execution without step', () => {
188
+ expect(computeStepCost({ execution: execution({ wallMs: 10 }), steps: [] })).toEqual([]);
189
+ });
190
+
191
+ it('refuses a negative step measure', () => {
192
+ expect(() =>
193
+ computeStepCost({ execution: execution(), steps: [usage({ httpCalls: -1 })] }),
194
+ ).toThrow(RangeError);
195
+ });
196
+ });