fraiseql-cli 2.19.1

CLI tools for FraiseQL v2 - Schema compilation and development utilities
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
#![allow(clippy::unwrap_used, clippy::panic)] // Reason: test code — fail-loud.
//! Integration tests for `fraiseql functions invoke` (phase 08).
//!
//! Each test spawns the compiled CLI binary, which runs the guest in its own V8
//! isolate in a child process — so the harness's one-isolate-per-process constraint
//! is satisfied structurally and these tests are safe under plain `cargo test` (the
//! test process never creates an isolate).
//!
//! **Execution engine:** V8 (in the spawned CLI child)
//! **Infrastructure:** none (no database, no network — host ops are mocked)
//! **Parallelism:** safe (each test forks its own binary + temp dir)

use std::{path::PathBuf, process::Command};

use tempfile::TempDir;

/// The directory holding the fixture `.ts` modules (`module_dir`).
fn fixture_module_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/functions")
}

/// A fresh invocation of the compiled CLI binary.
fn cli() -> Command {
    Command::new(env!("CARGO_BIN_EXE_fraiseql-cli"))
}

/// Author a project declaring `notify_approved`
/// (`after:mutation:Order:update`, gated `status` → `approved`), **compile it with the
/// real compiler**, and return the path to the compiled artifact.
///
/// This used to hand-build the compiled JSON, because until #1325 nothing could produce
/// one — `IntermediateSchema` had no `functions` field, so the only writer of a compiled
/// `functions` section in the tree was this function. A harness fixture that constructs
/// its own input proves only that it agrees with itself; every question about whether
/// the compiler and the harness read the same section was invisible to it. Now the
/// producer is the producer.
fn write_schema(dir: &TempDir) -> PathBuf {
    write_schema_declaring(
        dir,
        &serde_json::json!([{
            "name": "notify_approved",
            "trigger": "after:mutation:Order:update",
            "runtime": "Deno",
            "when": [{"field": "status", "changed_to": "approved"}]
        }]),
    )
}

/// [`write_schema`]'s project, declaring `functions` instead of `notify_approved`.
fn write_schema_declaring(dir: &TempDir, functions: &serde_json::Value) -> PathBuf {
    let module_dir = fixture_module_dir();
    let types = serde_json::json!({
        "version": "2.0.0",
        "types": [{
            "name": "Order",
            "sql_source": "v_order",
            "is_input": false,
            "fields": [
                {"name": "id", "type": "ID", "nullable": false},
                {"name": "status", "type": "String", "nullable": false}
            ]
        }],
        "mutations": [{
            "name": "updateOrder",
            "return_type": "Order",
            "sql_source": "fn_update_order",
            "operation": "update",
            "invalidates_views": ["v_order"],
            "arguments": []
        }],
        "functions": functions
    });
    let types_path = dir.path().join("types.json");
    std::fs::write(&types_path, serde_json::to_string_pretty(&types).unwrap()).unwrap();

    // `module_dir` is the deployment half of the surface, owned by `[functions]` — it
    // is not something the schema can set, which is what the split is for.
    let toml_path = dir.path().join("fraiseql.toml");
    std::fs::write(
        &toml_path,
        format!(
            "[schema]\nname = \"invoke\"\nversion = \"1.0.0\"\n\
             database_target = \"postgresql\"\n\n\
             [functions]\nmodule_dir = \"{}\"\n",
            module_dir.display()
        ),
    )
    .unwrap();

    let path = dir.path().join("schema.compiled.json");
    let output = cli()
        .arg("compile")
        .arg(&toml_path)
        .arg("--types")
        .arg(&types_path)
        .arg("--output")
        .arg(&path)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "the fixture project must compile:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
    path
}

/// Write a JSON fixture file and return its path.
fn write_json(dir: &TempDir, name: &str, value: &serde_json::Value) -> PathBuf {
    let path = dir.path().join(name);
    std::fs::write(&path, serde_json::to_string(value).unwrap()).unwrap();
    path
}

// ── Exit code 0: a matching payload runs, host ops are recorded ──────────────

#[test]
fn matching_payload_runs_and_reports_result_and_host_ops() {
    let dir = TempDir::new().unwrap();
    let schema = write_schema(&dir);
    // status pending → approved satisfies the `changed_to` predicate.
    let payload = write_json(
        &dir,
        "payload.json",
        &serde_json::json!({
            "event_kind": "update",
            "old": { "id": "o-1", "status": "pending" },
            "new": { "id": "o-1", "status": "approved" }
        }),
    );
    // A query mock matching any query text (no `query_contains`) bound to the order's id
    // as a variable returns a canned row.
    let mock_query = write_json(
        &dir,
        "query.json",
        &serde_json::json!([ {
            "variables": { "id": "o-1" },
            "response": { "data": { "markNotified": { "id": "o-1" } } }
        } ]),
    );

    let out = cli()
        .args(["functions", "invoke", "notify_approved"])
        .arg("--payload")
        .arg(&payload)
        .arg("--schema")
        .arg(&schema)
        .arg("--mock-query")
        .arg(&mock_query)
        .args(["--idempotency-token", "tok-123"])
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&out.stdout);
    let code = out.status.code().unwrap_or(-1);
    assert_eq!(code, 0, "a matching payload runs (exit 0); stdout:\n{stdout}");
    assert!(stdout.contains("notified"), "the guest's result is printed:\n{stdout}");
    // The injected idempotency token reached the guest and came back in the result.
    assert!(stdout.contains("tok-123"), "the injected token is visible:\n{stdout}");
    // The recorded host-op calls are printed (the query the guest issued).
    assert!(stdout.contains("host ops"), "host-op calls are reported:\n{stdout}");
    assert!(stdout.contains("query"), "the guest's query op is recorded:\n{stdout}");
}

// ── Exit code 3: the `when` predicate does not match — no isolate spins ──────

#[test]
fn non_matching_predicate_exits_predicate_no_match() {
    let dir = TempDir::new().unwrap();
    let schema = write_schema(&dir);
    // Already approved → the `changed_to approved` transition did NOT happen.
    let payload = write_json(
        &dir,
        "payload.json",
        &serde_json::json!({
            "event_kind": "update",
            "old": { "id": "o-2", "status": "approved" },
            "new": { "id": "o-2", "status": "approved" }
        }),
    );

    let out = cli()
        .args(["functions", "invoke", "notify_approved"])
        .arg("--payload")
        .arg(&payload)
        .arg("--schema")
        .arg(&schema)
        .arg("--explain")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&out.stdout);
    let code = out.status.code().unwrap_or(-1);
    assert_eq!(code, 3, "a non-matching predicate exits 3 (no isolate); stdout:\n{stdout}");
    assert!(stdout.contains("NO MATCH"), "--explain shows why it did not fire:\n{stdout}");
}

// ── Exit code 4: a mock miss fails the op loud → the guest errors ────────────

#[test]
fn mock_query_miss_fails_loud_and_the_guest_errors() {
    let dir = TempDir::new().unwrap();
    let schema = write_schema(&dir);
    let payload = write_json(
        &dir,
        "payload.json",
        &serde_json::json!({
            "event_kind": "update",
            "old": { "id": "o-3", "status": "pending" },
            "new": { "id": "o-3", "status": "approved" }
        }),
    );
    // A mock that matches a DIFFERENT query — the guest's query matches none.
    let mock_query = write_json(
        &dir,
        "query.json",
        &serde_json::json!([ { "query_contains": "somethingElse", "response": {} } ]),
    );

    let out = cli()
        .args(["functions", "invoke", "notify_approved"])
        .arg("--payload")
        .arg(&payload)
        .arg("--schema")
        .arg(&schema)
        .arg("--mock-query")
        .arg(&mock_query)
        .output()
        .unwrap();

    let code = out.status.code().unwrap_or(-1);
    assert_eq!(code, 4, "an unmatched mock fails the op loud → guest error (exit 4)");
}

// ── Exit code 4: a guest past its declared `timeout_ms` is cut off (#1627) ───

/// The harness runs a guest under the limits the server would: its declared
/// `timeout_ms`, not the 5 s default. A guest that never returns is stopped at 100 ms.
#[test]
fn a_declared_timeout_cuts_the_guest_off() {
    let dir = TempDir::new().unwrap();
    let schema = write_schema_declaring(
        &dir,
        &serde_json::json!([{
            "name": "spin_forever",
            "trigger": "after:mutation:Order:update",
            "runtime": "Deno",
            "timeout_ms": 100
        }]),
    );
    let payload = write_json(
        &dir,
        "payload.json",
        &serde_json::json!({ "event_kind": "update", "old": {}, "new": { "id": "o-9" } }),
    );

    let started = std::time::Instant::now();
    let out = cli()
        .args(["functions", "invoke", "spin_forever"])
        .arg("--payload")
        .arg(&payload)
        .arg("--schema")
        .arg(&schema)
        .output()
        .unwrap();
    let elapsed = started.elapsed();

    let code = out.status.code().unwrap_or(-1);
    assert_eq!(code, 4, "a guest cut off by its timeout is a guest error (exit 4)");
    // Generous for the process spawn and the isolate start, and well under the 5 s
    // default the harness used to apply whatever the function declared.
    assert!(
        elapsed < std::time::Duration::from_secs(3),
        "the guest ran for {elapsed:?}, so its 100 ms timeout was not applied"
    );
}

// ── Exit code 1: an unknown function is a config error ───────────────────────

#[test]
fn unknown_function_is_a_config_error() {
    let dir = TempDir::new().unwrap();
    let schema = write_schema(&dir);
    let payload = write_json(&dir, "payload.json", &serde_json::json!({ "id": "x" }));

    let out = cli()
        .args(["functions", "invoke", "does_not_exist"])
        .arg("--payload")
        .arg(&payload)
        .arg("--schema")
        .arg(&schema)
        .output()
        .unwrap();

    let code = out.status.code().unwrap_or(-1);
    assert_eq!(code, 1, "an unknown function name is a config error (exit 1)");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("does_not_exist") || stderr.to_lowercase().contains("no function"),
        "the error names the missing function:\n{stderr}"
    );
}

// ── before:mutation — a data-dependent rule (#1328) ──────────────────────────

/// Author a project declaring `credit_limit` (`before:mutation:placeOrder`), compile
/// it with the real compiler, and return the compiled artifact's path.
fn write_before_mutation_schema(dir: &TempDir) -> PathBuf {
    let module_dir = fixture_module_dir();
    let types = serde_json::json!({
        "version": "2.0.0",
        "types": [{
            "name": "Order",
            "sql_source": "v_order",
            "is_input": false,
            "fields": [
                {"name": "id", "type": "ID", "nullable": false},
                {"name": "amount", "type": "Int", "nullable": false}
            ]
        }],
        "mutations": [{
            "name": "placeOrder",
            "return_type": "Order",
            "sql_source": "fn_place_order",
            "operation": "insert",
            "invalidates_views": ["v_order"],
            "arguments": []
        }],
        "functions": [{
            "name": "credit_limit",
            "trigger": "before:mutation:placeOrder",
            "runtime": "Deno"
        }]
    });
    let types_path = dir.path().join("types.json");
    std::fs::write(&types_path, serde_json::to_string_pretty(&types).unwrap()).unwrap();

    let toml_path = dir.path().join("fraiseql.toml");
    std::fs::write(
        &toml_path,
        format!(
            "[schema]\nname = \"invoke\"\nversion = \"1.0.0\"\n\
             database_target = \"postgresql\"\n\n\
             [functions]\nmodule_dir = \"{}\"\n",
            module_dir.display()
        ),
    )
    .unwrap();

    let path = dir.path().join("schema.compiled.json");
    let output = cli()
        .arg("compile")
        .arg(&toml_path)
        .arg("--types")
        .arg(&types_path)
        .arg("--output")
        .arg(&path)
        .output()
        .unwrap();
    assert!(
        output.status.success(),
        "the fixture project must compile:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );
    path
}

/// The read is mocked with a customer whose remaining credit is `limit - outstanding`.
/// It answers only the read bound to `c-1` as a variable: a fixture that writes the id
/// into the query text instead misses it.
fn credit_mock(dir: &TempDir, limit: i64, outstanding: i64) -> PathBuf {
    write_json(
        dir,
        "query.json",
        &serde_json::json!([{
            "query_contains": "customer",
            "variables": { "id": "c-1" },
            "response": { "data": { "customer": {
                "creditLimit": limit, "outstanding": outstanding,
            } } }
        }]),
    )
}

/// A rule that *needs* a read runs in the harness, and the harness reports the
/// decision the server would reach — not just the guest's raw JSON.
///
/// This is the fixture #1328 asks for: without the read bridge the guest's
/// `fraiseql_query` fails loud and this function cannot decide anything.
#[test]
fn a_data_dependent_rule_aborts_when_the_read_says_so() {
    let dir = TempDir::new().unwrap();
    let schema = write_before_mutation_schema(&dir);
    // The fixture is the mutation's resolved arguments — there are no row images.
    let payload = write_json(
        &dir,
        "payload.json",
        &serde_json::json!({ "input": { "customer_id": "c-1", "amount": 900 } }),
    );
    let mock_query = credit_mock(&dir, 1000, 400); // 600 remaining < 900

    let out = cli()
        .args(["functions", "invoke", "credit_limit"])
        .arg("--payload")
        .arg(&payload)
        .arg("--schema")
        .arg(&schema)
        .arg("--mock-query")
        .arg(&mock_query)
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&out.stdout);
    assert_eq!(out.status.code().unwrap_or(-1), 0, "the guest ran; stdout:\n{stdout}");
    assert!(
        stdout.contains("decision: ABORT `placeOrder`"),
        "the harness must report the decision the chain would reach:\n{stdout}"
    );
    assert!(
        stdout.contains("exceeds the remaining credit of 600"),
        "the rule's own message must be shown:\n{stdout}"
    );
}

/// The other side of the same rule: the counterweight that proves the abort above
/// is a verdict about the data and not a fixture that refuses everything. It also
/// pins the rewrite path — a hook that returns `{input}` replaces the arguments the
/// write binds from.
#[test]
fn the_same_rule_proceeds_and_rewrites_when_the_read_allows_it() {
    let dir = TempDir::new().unwrap();
    let schema = write_before_mutation_schema(&dir);
    let payload = write_json(
        &dir,
        "payload.json",
        &serde_json::json!({ "input": { "customer_id": "c-1", "amount": 100 } }),
    );
    let mock_query = credit_mock(&dir, 1000, 400); // 600 remaining > 100

    let out = cli()
        .args(["functions", "invoke", "credit_limit"])
        .arg("--payload")
        .arg(&payload)
        .arg("--schema")
        .arg(&schema)
        .arg("--mock-query")
        .arg(&mock_query)
        .arg("--json")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&out.stdout);
    assert_eq!(out.status.code().unwrap_or(-1), 0, "the guest ran; stdout:\n{stdout}");
    let decision: serde_json::Value = stdout
        .lines()
        .filter_map(|line| serde_json::from_str::<serde_json::Value>(line).ok())
        .find(|value| value.get("decision").is_some())
        .expect("--json must emit the decision object");
    assert_eq!(decision["decision"], "proceed");
    assert_eq!(decision["rewritten"], true, "the hook stamped the input: {decision}");
    assert_eq!(decision["arguments_or_reason"]["credit_checked"], true);
}

/// A query mock that names `variables` answers only a call bound with exactly those
/// variables: the same query text, bound for another customer, is a miss, not a read of
/// the customer the mock describes.
#[test]
fn a_query_mock_for_other_variables_is_a_miss() {
    let dir = TempDir::new().unwrap();
    let schema = write_before_mutation_schema(&dir);
    let payload = write_json(
        &dir,
        "payload.json",
        &serde_json::json!({ "input": { "customer_id": "c-1", "amount": 100 } }),
    );
    let mock_query = write_json(
        &dir,
        "query.json",
        &serde_json::json!([{
            "query_contains": "customer",
            "variables": { "id": "c-2" },
            "response": { "data": { "customer": { "creditLimit": 1000, "outstanding": 0 } } }
        }]),
    );

    let out = cli()
        .args(["functions", "invoke", "credit_limit"])
        .arg("--payload")
        .arg(&payload)
        .arg("--schema")
        .arg(&schema)
        .arg("--mock-query")
        .arg(&mock_query)
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&out.stdout);
    assert_eq!(
        out.status.code().unwrap_or(-1),
        4,
        "a mock for other variables must miss and fail the op loud; stdout:\n{stdout}"
    );
}

/// A `before:mutation` fixture is the arguments object. A bare array or scalar is a
/// config error naming what the shape should be, not a payload the guest is handed.
#[test]
fn a_non_object_before_mutation_fixture_is_a_config_error() {
    let dir = TempDir::new().unwrap();
    let schema = write_before_mutation_schema(&dir);
    let payload = write_json(&dir, "payload.json", &serde_json::json!([1, 2, 3]));

    let out = cli()
        .args(["functions", "invoke", "credit_limit"])
        .arg("--payload")
        .arg(&payload)
        .arg("--schema")
        .arg(&schema)
        .output()
        .unwrap();

    assert_eq!(out.status.code().unwrap_or(-1), 1, "a bad fixture is a config error");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("arguments object") && stderr.contains("an array"),
        "the error must say what was expected and what was found:\n{stderr}"
    );
}