ocre-cli 0.2.0

Command-line tool for Ocre: create, generate, migrate, run and deploy apps.
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! `ocre g job`, `ocre g schedule` and the queues `ocre deploy` creates, run
//! through the real binary.

#[path = "../support/mod.rs"]
mod support;

use std::fs;

use serde_json::json;
use support::{Sandbox, text};

fn read(root: &std::path::Path, path: &str) -> String {
    fs::read_to_string(root.join(path)).unwrap()
}

const CONFIG: &str = "cloudflare.config.ts";

/// Writes `entry` into cloudflare.config.ts on the line before `marker` (as
/// if written by hand); returns the new text.
fn hand_write(root: &std::path::Path, marker: &str, entry: &str) -> String {
    let text = read(root, CONFIG).replacen(marker, &format!("{entry}\n\t\t\t{marker}"), 1);
    fs::write(root.join(CONFIG), &text).unwrap();
    text
}

/// cloudflare.config.ts with `from` replaced (once), written; returns the new text.
fn rewrite(root: &std::path::Path, from: &str, to: &str) -> String {
    let text = read(root, CONFIG);
    assert!(text.contains(from), "{from} in {text}");
    let text = text.replacen(from, to, 1);
    fs::write(root.join(CONFIG), &text).unwrap();
    text
}

#[test]
fn first_job_wires_the_queue_and_later_jobs_extend_the_registry() {
    let sandbox = Sandbox::new();
    let root = sandbox.new_app("shop", &[]);
    let (report, ok) = sandbox.json(&["g", "job", "SendWelcomeJob", "user_id:integer", "note:text?"], &root);
    assert!(ok, "{report}");
    assert_eq!(report["created"], json!(["src/jobs/send_welcome.rs", "src/jobs/mod.rs"]));
    assert_eq!(report["updated"], json!(["src/lib.rs", "cloudflare.config.ts"]));
    assert_eq!(
        report["next"],
        json!([
            "enqueue it from a handler: jobs::SendWelcome { user_id, note }.perform_later(&ctx).await?",
            "ocre dev (jobs run locally; look for `[ocre jobs]` lines in the output)",
            "ocre deploy creates the queue shop-jobs and its dead-letter queue",
        ])
    );
    let job = read(&root, "src/jobs/send_welcome.rs");
    assert!(
        job.starts_with("//! Send welcome job. Generated by `ocre g job SendWelcomeJob user_id:integer note:text?`.")
    );
    assert!(
        job.contains(
            "pub struct SendWelcome {\n    pub user_id: i64,\n    pub note: Option<String>,\n}\n\nimpl SendWelcome {"
        ),
        "{job}"
    );
    assert!(job.contains("pub async fn perform(self, _ctx: &Ctx) -> Result<()> {\n        Ok(())\n    }"), "{job}");
    let registry = read(&root, "src/jobs/mod.rs");
    assert!(
        registry.contains("// ocre:jobs\npub mod send_welcome;\npub use send_welcome::SendWelcome;\n"),
        "{registry}"
    );
    assert!(registry.contains("    // ocre:job-variants\n    SendWelcome(SendWelcome),\n}"), "{registry}");
    assert!(
        registry.contains("        // ocre:job-dispatch\n        Job::SendWelcome(job) => job.perform(&ctx).await,\n"),
        "{registry}"
    );
    let lib = read(&root, "src/lib.rs");
    assert!(lib.contains("// ocre:modules\nmod jobs;\n"), "{lib}");
    assert!(
        lib.ends_with(
            "#[worker::event(queue)]\nasync fn queue(batch: worker::MessageBatch<String>, env: worker::Env, _ctx: \
             worker::Context) -> worker::Result<()> {\n    ocre::jobs::consume(batch, env, jobs::perform).await\n}\n"
        ),
        "{lib}"
    );
    let config = read(&root, CONFIG);
    assert!(config.contains("\t\t\tJOBS: bindings.queue({ name: \"shop-jobs\" }),\n"), "{config}");
    assert!(
        config.contains(
            "\t\t\ttriggers.queue({ name: \"shop-jobs\", deadLetterQueue: \"shop-jobs-failed\", maxBatchSize: 10, \
             maxBatchTimeout: 5, maxRetries: 5 }),\n"
        ),
        "{config}"
    );

    // A second job, without arguments: only the registry changes.
    let output = sandbox.ocre(&["g", "job", "cleanup"], &root);
    assert!(output.status.success());
    let (stdout, _) = text(&output);
    assert!(stdout.starts_with("  create  src/jobs/cleanup.rs\n  update  src/jobs/mod.rs\n"), "{stdout}");
    assert!(stdout.contains("jobs::Cleanup {}.perform_later(&ctx)"), "{stdout}");
    assert!(!stdout.contains("ocre deploy creates"), "{stdout}");
    assert!(read(&root, "src/jobs/cleanup.rs").contains("pub struct Cleanup {}\n\nimpl Cleanup {"));
    let registry = read(&root, "src/jobs/mod.rs");
    assert!(registry.contains("    Cleanup(Cleanup),\n    SendWelcome(SendWelcome),\n"), "{registry}");
    assert_eq!(read(&root, "src/lib.rs").matches("event(queue)").count(), 1);
    assert_eq!(read(&root, CONFIG).matches("bindings.queue(").count(), 1);
}

#[test]
fn a_named_queue_gets_its_own_cloudflare_queue_once() {
    let sandbox = Sandbox::new();
    let root = sandbox.new_app("shop", &[]);
    let (report, ok) = sandbox.json(&["g", "job", "SendCode", "user_id:integer", "--queue", "urgent"], &root);
    assert!(ok, "{report}");
    assert_eq!(
        report["next"],
        json!([
            "enqueue it from a handler: jobs::SendCode { user_id }.perform_later(&ctx).await?",
            "ocre dev (jobs run locally; look for `[ocre jobs]` lines in the output)",
            "ocre deploy creates the queue shop-jobs and its dead-letter queue",
            "ocre deploy creates the queue shop-jobs-urgent and its dead-letter queue",
        ])
    );
    let job = read(&root, "src/jobs/send_code.rs");
    assert!(job.contains("Generated by `ocre g job SendCode user_id:integer --queue urgent`"), "{job}");
    assert!(
        job.contains(
            "pub fn perform_later(self, ctx: &Ctx) -> impl Future<Output = Result<()>> + Send + use<> {\n        \
             ocre::jobs::queue(ctx, \"urgent\").enqueue(&super::Job::SendCode(self))\n    }"
        ),
        "{job}"
    );
    let config = read(&root, CONFIG);
    assert!(config.contains("JOBS_URGENT: bindings.queue({ name: \"shop-jobs-urgent\" }),\n"), "{config}");
    assert!(
        config.contains(
            "triggers.queue({ name: \"shop-jobs-urgent\", deadLetterQueue: \"shop-jobs-urgent-failed\", \
             maxBatchSize: 10, maxBatchTimeout: 1, maxRetries: 5 }),\n"
        ),
        "{config}"
    );

    // The same queue again: only the job; the default queue: `enqueue`.
    let (report, ok) = sandbox.json(&["g", "job", "SendSms", "--queue", "urgent"], &root);
    assert!(ok, "{report}");
    assert_eq!(report["updated"], json!(["src/jobs/mod.rs"]));
    let (report, ok) = sandbox.json(&["g", "job", "Cleanup", "--queue", "default"], &root);
    assert!(ok, "{report}");
    assert!(read(&root, "src/jobs/cleanup.rs").contains("ocre::jobs::enqueue(ctx, &super::Job::Cleanup(self))"));
    assert_eq!(read(&root, CONFIG).matches("bindings.queue(").count(), 2);
    assert_eq!(read(&root, CONFIG).matches("triggers.queue(").count(), 2);

    for bad in ["Urgent", "-x", "x-", "a_b", ""] {
        let (report, ok) = sandbox.json(&["g", "job", "Other", &format!("--queue={bad}")], &root);
        assert!(!ok);
        assert_eq!(report["error"], format!("invalid queue name `{bad}`"));
    }
    rewrite(&root, "name: \"shop\",", "name: app,");
    let (report, _) = sandbox.json(&["g", "job", "Other", "--queue", "low"], &root);
    assert_eq!(report["error"], "cloudflare.config.ts has no `worker.name` Ocre can read");
    assert!(!root.join("src/jobs/other.rs").exists());
    rewrite(&root, "name: app,", "name: \"shop\",");
    rewrite(&root, "// ocre:triggers", "");
    let before = read(&root, CONFIG);
    let (report, _) = sandbox.json(&["g", "job", "Other", "--queue", "low"], &root);
    assert_eq!(report["error"], "cloudflare.config.ts is missing the `// ocre:triggers` marker");
    assert_eq!(read(&root, CONFIG), before);
    assert!(!root.join("src/jobs/other.rs").exists());
}

#[test]
fn schedules_are_listed_and_fired_on_ocre_dev() {
    let sandbox = Sandbox::new();
    let root = sandbox.new_app("shop", &[]);
    let output = sandbox.ocre(&["schedules"], &root);
    assert!(text(&output).0.starts_with("No schedules."), "{}", text(&output).0);
    let (report, _) = sandbox.json(&["schedules", "run", "nightly"], &root);
    assert_eq!(report["error"], "no scheduled task `nightly`");
    assert!(report["hint"].as_str().unwrap().contains("ocre g schedule"), "{report}");

    sandbox.json(&["g", "schedule", "nightly", "every day at 3am"], &root);
    let nightly = "triggers.scheduled({ schedule: \"0 3 * * *\" }),";
    rewrite(&root, nightly, &format!("{nightly}\n\t\t\ttriggers.scheduled({{ schedule: \"*/5 * * * *\" }}),"));
    let (report, ok) = sandbox.json(&["schedules"], &root);
    assert!(ok, "{report}");
    assert_eq!(
        report["schedules"],
        json!([{"cron": "0 3 * * *", "task": "nightly"}, {"cron": "*/5 * * * *", "task": null}])
    );
    assert!(report["next"][0].as_str().unwrap().starts_with("a cron without a task fails"), "{report}");
    let output = sandbox.ocre(&["schedules"], &root);
    assert_eq!(
        text(&output).0.lines().take(3).collect::<Vec<_>>(),
        ["CRON (UTC)   TASK", "0 3 * * *    src/schedules/nightly.rs", "*/5 * * * *  (no task: fails when it fires)"]
    );

    let (report, _) = sandbox.json(&["schedules", "run", "weekly"], &root);
    assert_eq!(report["hint"], "tasks: nightly");

    let (port, request) = stand_in(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok");
    let (report, ok) = sandbox.json(&["schedules", "run", "nightly", "--port", &port.to_string()], &root);
    assert!(ok, "{report}");
    assert!(request.join().unwrap().starts_with("GET /cdn-cgi/local/scheduled?cron=0+3+*+*+* HTTP/1.1\r\n"));
    assert_eq!(report["ran"][0], "fired nightly (0 3 * * *); its `[ocre cron]` line is in the `ocre dev` output");

    let (port, request) = stand_in(b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n");
    let (report, ok) = sandbox.json(&["schedules", "run", "nightly", "--port", &port.to_string()], &root);
    request.join().unwrap();
    assert!(!ok);
    assert_eq!(report["error"], "the scheduled task answered HTTP 500");

    // Not HTTP.
    let (port, request) = stand_in(b"hello");
    let (report, _) = sandbox.json(&["schedules", "run", "nightly", "--port", &port.to_string()], &root);
    request.join().unwrap();
    assert!(report["error"].as_str().unwrap().ends_with("not an HTTP answer"), "{report}");

    // Nothing listening.
    let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
    let (report, _) = sandbox.json(&["schedules", "run", "nightly", "--port", &port.to_string()], &root);
    assert!(report["error"].as_str().unwrap().starts_with(&format!("cannot reach `ocre dev` on port {port}:")));

    // A cron Ocre cannot read.
    rewrite(&root, "{ schedule: \"*/5 * * * *\" }", "{ schedule: every5 }");
    let (report, ok) = sandbox.json(&["schedules"], &root);
    assert!(!ok);
    assert_eq!(report["error"], "cloudflare.config.ts has a scheduled trigger Ocre cannot read");
    assert_eq!(report["hint"], "write it as `triggers.scheduled({ schedule: \"0 3 * * *\" }),`");
}

/// A stand-in for `ocre dev`: reads one whole request, answers `response`,
/// and returns the request.
fn stand_in(response: &'static [u8]) -> (u16, std::thread::JoinHandle<String>) {
    use std::io::{Read, Write};
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    let handle = std::thread::spawn(move || {
        let (mut stream, _) = listener.accept().unwrap();
        let mut request = Vec::new();
        let mut chunk = [0u8; 256];
        while !request.ends_with(b"\r\n\r\n") {
            let read = stream.read(&mut chunk).unwrap();
            assert!(read > 0, "the request ends with an empty line");
            request.extend_from_slice(&chunk[..read]);
        }
        stream.write_all(response).unwrap();
        String::from_utf8(request).unwrap()
    });
    (port, handle)
}

#[test]
fn a_hand_written_jobs_producer_is_reused() {
    let sandbox = Sandbox::new();
    let root = sandbox.new_app("shop", &[]);
    let config = hand_write(&root, "// ocre:env", "JOBS: bindings.queue({ name: \"custom\" }),");
    let (report, ok) = sandbox.json(&["g", "job", "Ping"], &root);
    assert!(ok, "{report}");
    assert_eq!(report["updated"], json!(["src/lib.rs"]));
    assert_eq!(report["next"][2], "ocre deploy creates the queue custom and its dead-letter queue");
    assert_eq!(read(&root, CONFIG), config);
}

#[test]
fn job_errors_name_the_fix_and_write_nothing() {
    let sandbox = Sandbox::new();
    let root = sandbox.new_app("shop", &[]);
    let pristine = |root: &std::path::Path| !root.join("src/jobs").exists();
    let cases: &[(&[&str], &str)] = &[
        (&["g", "job", "2Fast"], "invalid job name `2Fast`"),
        (&["g", "job", "Type"], "invalid job name `Type`"),
        (&["g", "job", "Job"], "invalid job name `Job`"),
        (&["g", "job", "Import", "path"], "field `path` has no type"),
        (&["g", "job", "Import", "path:string^"], "job field `path` cannot be unique"),
        (&["g", "job", "Import", "csv:attachment"], "job field `csv` cannot be an attachment"),
    ];
    for (args, error) in cases {
        let (report, ok) = sandbox.json(args, &root);
        assert!(!ok);
        assert_eq!(report["error"], *error, "{args:?}");
        assert!(report["hint"].is_string(), "{report}");
    }
    assert!(pristine(&root));

    // A queue handler written by hand is not duplicated.
    let lib = read(&root, "src/lib.rs");
    fs::write(root.join("src/lib.rs"), format!("{lib}\n// #[worker::event(queue)]\n")).unwrap();
    let (report, _) = sandbox.json(&["g", "job", "Ping"], &root);
    assert_eq!(report["error"], "src/lib.rs already handles the `queue` event");
    fs::write(root.join("src/lib.rs"), "fn main() {}\n").unwrap();
    let (report, _) = sandbox.json(&["g", "job", "Ping"], &root);
    assert_eq!(report["error"], "src/lib.rs is missing the `// ocre:modules` marker");
    fs::write(root.join("src/lib.rs"), lib.replace("// ocre:routes", "")).unwrap();
    let (report, _) = sandbox.json(&["g", "job", "Ping"], &root);
    assert_eq!(report["error"], "src/lib.rs is missing the `// ocre:routes` marker");
    fs::write(root.join("src/lib.rs"), &lib).unwrap();

    // cloudflare.config.ts problems: named, nothing written.
    let config = read(&root, CONFIG);
    rewrite(&root, "name: \"shop\",", "name: `${prefix}shop`,");
    let (report, _) = sandbox.json(&["g", "job", "Ping"], &root);
    // Without a readable `name`, Project::find still works (it reads the D1 binding).
    assert_eq!(report["error"], "cloudflare.config.ts has no `worker.name` Ocre can read");
    fs::write(root.join(CONFIG), &config).unwrap();
    hand_write(&root, "// ocre:env", "JOBS: bindings.queue({ name: queueName }),");
    let (report, _) = sandbox.json(&["g", "job", "Ping"], &root);
    assert_eq!(report["error"], "cloudflare.config.ts defines `JOBS` in a form Ocre cannot read");
    assert_eq!(report["hint"], "write it as a literal: `JOBS: bindings.queue({ name: \"<app-name>-jobs\" }),`");
    for marker in ["// ocre:env", "// ocre:triggers"] {
        let without = config.replace(marker, "");
        fs::write(root.join(CONFIG), &without).unwrap();
        let (report, _) = sandbox.json(&["g", "job", "Ping"], &root);
        assert_eq!(report["error"], format!("cloudflare.config.ts is missing the `{marker}` marker"));
        assert!(report["hint"].as_str().unwrap().starts_with(&format!("put `{marker}` on its own line")));
        assert_eq!(read(&root, CONFIG), without);
    }
    fs::write(root.join(CONFIG), &config).unwrap();
    assert!(pristine(&root));
    assert_eq!(read(&root, "src/lib.rs"), lib);

    // A registry without its markers.
    let (report, ok) = sandbox.json(&["g", "job", "Ping"], &root);
    assert!(ok, "{report}");
    let registry = read(&root, "src/jobs/mod.rs");
    for marker in ["// ocre:jobs", "// ocre:job-variants", "// ocre:job-dispatch"] {
        fs::write(root.join("src/jobs/mod.rs"), registry.replace(marker, "")).unwrap();
        let (report, _) = sandbox.json(&["g", "job", "Pong"], &root);
        assert_eq!(report["error"], format!("src/jobs/mod.rs is missing the `{marker}` marker"));
        assert!(!root.join("src/jobs/pong.rs").exists());
    }
    fs::write(root.join("src/jobs/mod.rs"), &registry).unwrap();
    let (report, _) = sandbox.json(&["g", "job", "Ping"], &root);
    assert_eq!(report["error"], "src/jobs/ping.rs already exists");
}

#[test]
fn schedules_add_crons_and_dispatch_by_expression() {
    let sandbox = Sandbox::new();
    let root = sandbox.new_app("shop", &[]);
    let (report, ok) = sandbox.json(&["g", "schedule", "NightlyCleanup", " 0  3 * * * "], &root);
    assert!(ok, "{report}");
    assert_eq!(report["created"], json!(["src/schedules/nightly_cleanup.rs", "src/schedules/mod.rs"]));
    assert_eq!(report["updated"], json!(["cloudflare.config.ts", "src/lib.rs"]));
    assert_eq!(report["next"][0], "ocre dev, then: ocre schedules run nightly_cleanup");
    let task = read(&root, "src/schedules/nightly_cleanup.rs");
    assert!(task.starts_with(
        "//! Nightly cleanup: scheduled task. Generated by `ocre g schedule NightlyCleanup \"0 3 * * *\"`.\n//!\n\
         //! Runs at `0 3 * * *`, UTC,"
    ));
    assert!(task.contains("`curl 'http://localhost:8787/cdn-cgi/local/scheduled?cron=0+3+*+*+*'`"), "{task}");
    assert!(task.contains("pub async fn run(_ctx: &Ctx) -> Result<()> {\n    Ok(())\n}"), "{task}");
    let registry = read(&root, "src/schedules/mod.rs");
    assert!(registry.contains("// ocre:schedules\npub mod nightly_cleanup;\n"), "{registry}");
    assert!(
        registry.contains("// ocre:schedule-dispatch\n        \"0 3 * * *\" => nightly_cleanup::run(&ctx).await,\n")
    );
    let lib = read(&root, "src/lib.rs");
    assert!(lib.contains("// ocre:modules\nmod schedules;\n"), "{lib}");
    assert!(
        lib.ends_with(
            "#[worker::event(scheduled)]\nasync fn scheduled(event: worker::ScheduledEvent, env: worker::Env, _ctx: \
             worker::ScheduleContext) {\n    ocre::jobs::cron(event, env, schedules::run).await\n}\n"
        ),
        "{lib}"
    );
    assert!(read(&root, CONFIG).contains("\t\t\ttriggers.scheduled({ schedule: \"0 3 * * *\" }),\n"));

    // Weekday with `#` is escaped in the local URL; each cron is its own trigger.
    let (report, ok) = sandbox.json(&["g", "schedule", "monthly_report", "0 9 * * MON#1"], &root);
    assert!(ok, "{report}");
    assert_eq!(report["updated"], json!(["cloudflare.config.ts", "src/schedules/mod.rs"]));
    assert!(read(&root, "src/schedules/monthly_report.rs").contains("?cron=0+9+*+*+MON%231'"));
    // Plain English, converted to cron; the phrase stays in the task's comment.
    let (report, ok) = sandbox.json(&["g", "schedule", "digest", "every monday at 9:30am"], &root);
    assert!(ok, "{report}");
    assert_eq!(
        report["next"][1],
        "ocre deploy (Cron Triggers only fire on the deployed Worker; this one runs at `30 9 * * MON`, UTC)"
    );
    assert!(read(&root, "src/schedules/digest.rs").contains("Runs at `30 9 * * MON` (every monday at 9:30am), UTC"));
    assert!(read(&root, "src/schedules/mod.rs").contains("\"30 9 * * MON\" => digest::run(&ctx).await,"));
    assert_eq!(crons(&sandbox, &root), ["30 9 * * MON", "0 9 * * MON#1", "0 3 * * *"], "newest first, at the marker");
    assert_eq!(read(&root, "src/lib.rs").matches("event(scheduled)").count(), 1);

    // Duplicates and bad input.
    let cases: &[(&[&str], &str)] = &[
        (&["g", "schedule", "again", "0 3 * * *"], "cron `0 3 * * *` is already scheduled in cloudflare.config.ts"),
        (&["g", "schedule", "hourly", "0 * * *"], "invalid schedule `0 * * *`"),
        (&["g", "schedule", "hourly", "0 * * * ?"], "invalid schedule `0 * * * ?`"),
        (&["g", "schedule", "often", "every 30 seconds"], "invalid schedule `every 30 seconds`"),
        (&["g", "schedule", "9lives", "0 * * * *"], "invalid schedule name `9lives`"),
        (&["g", "schedule", "match", "0 * * * *"], "invalid schedule name `match`"),
        (&["g", "schedule", "nightly_cleanup", "5 * * * *"], "src/schedules/nightly_cleanup.rs already exists"),
    ];
    for (args, error) in cases {
        let (report, ok) = sandbox.json(args, &root);
        assert!(!ok);
        assert_eq!(report["error"], *error, "{args:?}");
        assert!(report["hint"].is_string(), "{report}");
    }
    assert!(!root.join("src/schedules/again.rs").exists() && !root.join("src/schedules/hourly.rs").exists());
}

/// The crons `ocre schedules` reads, in file order.
fn crons(sandbox: &Sandbox, root: &std::path::Path) -> Vec<String> {
    let (report, ok) = sandbox.json(&["schedules"], root);
    assert!(ok, "{report}");
    report["schedules"].as_array().unwrap().iter().map(|s| s["cron"].as_str().unwrap().to_owned()).collect()
}

#[test]
fn crons_are_added_at_the_triggers_marker() {
    let sandbox = Sandbox::new();
    let root = sandbox.new_app("shop", &[]);
    let pristine = read(&root, CONFIG);

    // Hand-written triggers: crons count toward the free plan, queue consumers do not.
    hand_write(
        &root,
        "// ocre:triggers",
        "triggers.scheduled({ schedule: \"0 1 * * *\" }),\n\t\t\ttriggers.scheduled({ schedule: \"0 2 * * *\" }),\n\t\t\t\
         triggers.queue({ name: \"shop-jobs\" }),\n\t\t\ttriggers.scheduled({ schedule: \"0 3 * * *\" }),",
    );
    for (name, cron) in [("a", "0 4 * * *"), ("b", "0 5 * * *")] {
        let (report, ok) = sandbox.json(&["g", "schedule", name, cron], &root);
        assert!(ok, "{report}");
        assert_eq!(report["next"].as_array().unwrap().len(), 2, "{report}");
    }
    let (report, ok) = sandbox.json(&["g", "schedule", "c", "0 6 * * *"], &root);
    assert!(ok, "{report}");
    assert_eq!(
        report["next"][2],
        "this app now has 6 crons; the free plan allows 5 per account: run several tasks from one cron"
    );
    // Hand-written entries sit above the marker; Ocre's go right below it, newest first.
    assert_eq!(crons(&sandbox, &root), ["0 1 * * *", "0 2 * * *", "0 3 * * *", "0 6 * * *", "0 5 * * *", "0 4 * * *"]);
    let (report, _) = sandbox.json(&["g", "schedule", "d", "0 2 * * *"], &root);
    assert_eq!(report["error"], "cron `0 2 * * *` is already scheduled in cloudflare.config.ts", "hand-written too");

    // Forms Ocre does not edit: named, nothing written.
    fs::remove_dir_all(root.join("src/schedules")).unwrap();
    let lib = read(&root, "src/lib.rs").replace("event(scheduled)", "");
    fs::write(root.join("src/lib.rs"), &lib).unwrap();
    let without = pristine.replace("// ocre:triggers", "");
    fs::write(root.join(CONFIG), &without).unwrap();
    let (report, _) = sandbox.json(&["g", "schedule", "a", "0 3 * * *"], &root);
    assert_eq!(report["error"], "cloudflare.config.ts is missing the `// ocre:triggers` marker");
    assert!(report["hint"].as_str().unwrap().contains("inside `worker.triggers: [ ... ]`"), "{report}");
    assert_eq!(read(&root, CONFIG), without);
    fs::write(root.join(CONFIG), &pristine).unwrap();
    let unreadable = hand_write(&root, "// ocre:triggers", "triggers.scheduled({ schedule: nightly }),");
    let (report, _) = sandbox.json(&["g", "schedule", "a", "0 3 * * *"], &root);
    assert_eq!(report["error"], "cloudflare.config.ts has a scheduled trigger Ocre cannot read");
    assert_eq!(read(&root, CONFIG), unreadable);
    assert!(!root.join("src/schedules").exists());
    assert_eq!(read(&root, "src/lib.rs"), lib);

    // lib.rs problems.
    fs::write(root.join(CONFIG), &pristine).unwrap();
    fs::write(root.join("src/lib.rs"), format!("{lib}\n// #[worker::event(scheduled)]\n")).unwrap();
    let (report, _) = sandbox.json(&["g", "schedule", "a", "0 3 * * *"], &root);
    assert_eq!(report["error"], "src/lib.rs already handles the `scheduled` event");
    fs::write(root.join("src/lib.rs"), "fn main() {}\n").unwrap();
    let (report, _) = sandbox.json(&["g", "schedule", "a", "0 3 * * *"], &root);
    assert_eq!(report["error"], "src/lib.rs is missing the `// ocre:modules` marker");
    fs::write(root.join("src/lib.rs"), &lib).unwrap();
    assert_eq!(read(&root, CONFIG), pristine);

    // A registry without its markers.
    let (report, ok) = sandbox.json(&["g", "schedule", "a", "0 3 * * *"], &root);
    assert!(ok, "{report}");
    let registry = read(&root, "src/schedules/mod.rs");
    for marker in ["// ocre:schedules", "// ocre:schedule-dispatch"] {
        fs::write(root.join("src/schedules/mod.rs"), registry.replace(marker, "")).unwrap();
        let (report, _) = sandbox.json(&["g", "schedule", "b", "0 4 * * *"], &root);
        assert_eq!(report["error"], format!("src/schedules/mod.rs is missing the `{marker}` marker"));
    }
    assert_eq!(crons(&sandbox, &root), ["0 3 * * *"]);
}

#[test]
fn deploy_creates_missing_queues_once() {
    let sandbox = Sandbox::new();
    let root = sandbox.new_app("shop", &[]);
    sandbox.set("has_secret");
    sandbox.remote_database("shop");
    let (report, ok) = sandbox.json(&["g", "job", "Ping"], &root);
    assert!(ok, "{report}");
    sandbox.set("queue_shop-jobs");
    sandbox.clear_calls();

    let output = sandbox.ocre(&["deploy"], &root);
    let (stdout, _) = text(&output);
    assert!(output.status.success(), "{stdout}");
    assert!(stdout.contains("Created queue shop-jobs-failed on Cloudflare\n"), "{stdout}");
    assert_eq!(
        sandbox.calls(),
        [
            "cf d1 list --name shop",
            "cf queues list",
            "cf queues create --queue-name shop-jobs-failed",
            "cf workers secrets list --worker shop",
            "cf d1 migrations apply uuid-shop",
            "cf deploy --secrets-file .wrangler/ocre-secrets.json",
            "secrets file ok",
            "build --release",
        ]
    );

    // Everything exists now: nothing to create.
    sandbox.clear_calls();
    let (report, ok) = sandbox.json(&["deploy"], &root);
    assert!(ok, "{report}");
    assert!(report.get("provisioned").is_none(), "{report}");
    assert!(!sandbox.calls().iter().any(|call| call.starts_with("cf queues create")), "{:?}", sandbox.calls());

    // A named queue: producer and dead-letter queue, from one list.
    fs::remove_file(sandbox.work.join("../state/queue_shop-jobs")).unwrap();
    let (report, ok) = sandbox.json(&["g", "job", "SendCode", "--queue", "urgent"], &root);
    assert!(ok, "{report}");
    sandbox.clear_calls();
    let (report, ok) = sandbox.json(&["deploy"], &root);
    assert!(ok, "{report}");
    assert_eq!(
        report["provisioned"],
        json!(["queue shop-jobs-urgent", "queue shop-jobs", "queue shop-jobs-urgent-failed"])
    );
    assert_eq!(sandbox.calls().iter().filter(|call| *call == "cf queues list").count(), 1);

    // Any other failure stops the deploy before it starts.
    let unset = |marker: &str| fs::remove_file(sandbox.work.join("../state").join(marker)).unwrap();
    sandbox.set("queues_list_fails");
    let (report, ok) = sandbox.json(&["deploy"], &root);
    assert!(!ok);
    assert_eq!(report["error"], "`cf queues list` failed: ┌ Error\n│ queues_list_fails\n└");
    assert!(report["hint"].as_str().unwrap().contains("ocre login"), "{report}");
    unset("queues_list_fails");
    unset("queue_shop-jobs");
    sandbox.set("queues_create_fails");
    let (report, ok) = sandbox.json(&["deploy"], &root);
    assert!(!ok);
    // The transient 500 recorded once on the real API.
    let error = report["error"].as_str().unwrap();
    assert!(error.starts_with("`cf queues create --queue-name shop-jobs` failed: ┌ APIError\n│ [10013] "), "{error}");
    assert_eq!(
        sandbox.calls().last().unwrap(),
        "cf queues create --queue-name shop-jobs",
        "never deployed without its queues"
    );
    unset("queues_create_fails");

    // Queue names Ocre cannot read: the canonical form, nothing created.
    let config = read(&root, CONFIG);
    rewrite(&root, "{ name: \"shop-jobs-urgent\" }", "{ name: urgent }");
    sandbox.clear_calls();
    let (report, _) = sandbox.json(&["deploy"], &root);
    assert_eq!(report["error"], "cloudflare.config.ts defines `JOBS_URGENT` in a form Ocre cannot read");
    assert_eq!(report["hint"], "write it as a literal: `JOBS_URGENT: bindings.queue({ name: \"<queue>\" }),`");
    fs::write(root.join(CONFIG), &config).unwrap();
    rewrite(&root, "triggers.queue({ name: \"shop-jobs\",", "triggers.queue({ name: jobs,");
    let (report, _) = sandbox.json(&["deploy"], &root);
    assert_eq!(report["error"], "cloudflare.config.ts has a queue trigger Ocre cannot read");
    assert!(!sandbox.calls().iter().any(|call| call.starts_with("cf queues") || call.starts_with("cf deploy")));
}