Dever v0.0.2
This commit is contained in:
commit
e6e175ebcf
816 files changed
+120349
No files matched your search
@@ -0,0 +1,315 @@
|
||||
use super::*;
|
||||
|
||||
fn executable(domain: &Path) {
|
||||
let bin = domain.join("bin");
|
||||
fs::create_dir_all(&bin).unwrap();
|
||||
let source = bin.join("tool.rs");
|
||||
fs::write(
|
||||
&source,
|
||||
r#"use std::io::{Read,Write};
|
||||
fn main() {
|
||||
let mut bytes = Vec::new(); std::io::stdin().read_to_end(&mut bytes).unwrap();
|
||||
let argument = std::env::args().nth(1).unwrap();
|
||||
std::io::stdout().write_all(argument.as_bytes()).unwrap();
|
||||
std::io::stdout().write_all(&bytes).unwrap();
|
||||
std::io::stderr().write_all(b"diagnostic").unwrap();
|
||||
std::process::exit(7);
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
success(
|
||||
Command::new("rustc")
|
||||
.args(["+1.95.0", "-C", "target-feature=+crt-static"])
|
||||
.arg(&source)
|
||||
.arg("-o")
|
||||
.arg(bin.join("tool"))
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_command_runs_without_shell_and_is_embedded_in_published_binary() {
|
||||
let root = project(
|
||||
"external-command",
|
||||
"execute(args: List<Text>, stdin: Bytes?) (output: dever.process.Output) fails dever.process.Error",
|
||||
"external command \"bin/tool\" {}",
|
||||
r#"flow start() (code: Int, stdout: Text, stderr: Text)
|
||||
| step | kind | do |
|
||||
| output | port | port.execute(["$(printf wrong) 中文"], dever.bytes.fromText("input")) |
|
||||
| code | calc | output.code |
|
||||
| stdout | calc | dever.bytes.toText(output.stdout) |
|
||||
| stderr | calc | dever.bytes.toText(output.stderr) |
|
||||
"#,
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
executable(&domain);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let target = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| function.signature.name.ends_with("adapter.port.execute"))
|
||||
.unwrap();
|
||||
assert!(target.effects.process && target.effects.suspends && target.effects.scope());
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let output = root.join("published");
|
||||
artifact.publish(&output).unwrap();
|
||||
fs::remove_file(domain.join("bin/tool")).unwrap();
|
||||
let text = run(&output);
|
||||
assert!(text.contains("7"), "{text}");
|
||||
assert!(text.contains("diagnostic"), "{text}");
|
||||
assert!(text.contains("$(printf wrong) 中文input"), "{text}");
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["fmt", root.to_str().unwrap(), "--check"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_command_requires_adapter_matching_port_and_explicit_failures() {
|
||||
for (name, port, adapter) in [
|
||||
(
|
||||
"missing-fails",
|
||||
"execute(args: List<Text>, stdin: Bytes?) (output: dever.process.Output)",
|
||||
"external command \"bin/tool\" {}",
|
||||
),
|
||||
(
|
||||
"signature",
|
||||
"execute(args: List<Text>) (output: dever.process.Output) fails dever.process.Error",
|
||||
"external command \"bin/tool\" {}",
|
||||
),
|
||||
(
|
||||
"escape",
|
||||
"execute(args: List<Text>, stdin: Bytes?) (output: dever.process.Output) fails dever.process.Error",
|
||||
"external command \"../tool\" {}",
|
||||
),
|
||||
(
|
||||
"limit",
|
||||
"execute(args: List<Text>, stdin: Bytes?) (output: dever.process.Output) fails dever.process.Error",
|
||||
"external command \"bin/tool\" { timeout_ms = 0 }",
|
||||
),
|
||||
] {
|
||||
let root = project(
|
||||
&format!("external-{name}"),
|
||||
port,
|
||||
adapter,
|
||||
"flow start() (out: dever.process.Output)\n| step | kind | do |\n| out | port | port.execute([], null) |",
|
||||
);
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
!project.diagnostics.is_empty()
|
||||
|| program::check(&project.declarations, &project.modules).is_err(),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_command_failure_can_be_captured_but_not_discarded() {
|
||||
let root = project(
|
||||
"external-capture",
|
||||
"execute(args: List<Text>, stdin: Bytes?) (output: dever.process.Output) fails dever.process.Error",
|
||||
"external command \"bin/tool\" { output_limit = 1 }",
|
||||
r#"type Attempt { Done(output: dever.process.Output), error Failed(error: dever.process.Error) }
|
||||
flow start() (out: Attempt)
|
||||
| step | kind | do |
|
||||
| out | port | result(port.execute(["overflow"], null)) |
|
||||
"#,
|
||||
);
|
||||
executable(&root.join("module/demo/service"));
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let text = run(&artifact.binary);
|
||||
assert!(text.contains("output exceeds combined limit"), "{text}");
|
||||
write_source(
|
||||
root.join("module/demo/service/app/main.dever"),
|
||||
r#"type Attempt { Done(output: dever.process.Output), error Failed(error: dever.process.Error) }
|
||||
flow capture() (out: Attempt)
|
||||
| step | kind | do |
|
||||
| out | port | result(port.execute(["overflow"], null)) |
|
||||
|
||||
flow start() (out: Int)
|
||||
| step | kind | do |
|
||||
| ignored | flow | capture() |
|
||||
| out | calc | 1 |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(program::check(&project.declarations, &project.modules).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn command_build_rejects_non_elf_and_assets_outside_domain() {
|
||||
let root = project(
|
||||
"external-assets",
|
||||
"execute(args: List<Text>, stdin: Bytes?) (output: dever.process.Output) fails dever.process.Error",
|
||||
"external command \"bin/tool\" {}",
|
||||
"flow start() (out: dever.process.Output)\n| step | kind | do |\n| out | port | port.execute([], null) |",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
executable(&domain);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let binary = domain.join("bin/tool");
|
||||
let other = match build::Target::host().unwrap() {
|
||||
build::Target::LinuxX86_64 => build::Target::LinuxAarch64,
|
||||
build::Target::LinuxAarch64 => build::Target::LinuxX86_64,
|
||||
};
|
||||
let error = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
Some(other),
|
||||
)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert!(
|
||||
error.contains(&format!("not an executable for {}", other.arch())),
|
||||
"{error}"
|
||||
);
|
||||
fs::write(&binary, b"#!/bin/sh\nexit 0\n").unwrap();
|
||||
assert!(
|
||||
build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
fs::remove_file(&binary).unwrap();
|
||||
std::os::unix::fs::symlink("/bin/true", &binary).unwrap();
|
||||
assert!(
|
||||
build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_command_carries_transitive_libraries_and_cleans_its_private_directory() {
|
||||
let root = project(
|
||||
"dynamic-command",
|
||||
"execute(args: List<Text>, stdin: Bytes?) (output: dever.process.Output) fails dever.process.Error",
|
||||
"external command \"bin/tool\" {}",
|
||||
r#"flow start() (first: Text, second: Text)
|
||||
| step | kind | do |
|
||||
| one | port | port.execute([], null) |
|
||||
| two | port | port.execute([], null) |
|
||||
| first | calc | dever.bytes.toText(one.stdout) |
|
||||
| second | calc | dever.bytes.toText(two.stdout) |
|
||||
"#,
|
||||
);
|
||||
let bin = root.join("module/demo/service/bin");
|
||||
fs::create_dir_all(&bin).unwrap();
|
||||
fs::write(bin.join("leaf.c"), "int leaf(void) { return 37; }").unwrap();
|
||||
fs::write(
|
||||
bin.join("answer.c"),
|
||||
"extern int leaf(void); int answer(void) { return leaf()+5; }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
bin.join("tool.c"),
|
||||
r#"#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
extern int answer(void);
|
||||
int main(void) {
|
||||
char path[4096]; ssize_t size=readlink("/proc/self/exe",path,sizeof(path)-1);
|
||||
if(size<0) return 1;
|
||||
path[size]=0; printf("%d:%s",answer(),path); return 0;
|
||||
}"#,
|
||||
)
|
||||
.unwrap();
|
||||
for args in [
|
||||
vec![
|
||||
"-shared",
|
||||
"-fPIC",
|
||||
"leaf.c",
|
||||
"-Wl,-soname,libdever_leaf.so",
|
||||
"-o",
|
||||
"libdever_leaf.so",
|
||||
],
|
||||
vec![
|
||||
"-shared",
|
||||
"-fPIC",
|
||||
"answer.c",
|
||||
"-L.",
|
||||
"-ldever_leaf",
|
||||
"-Wl,-rpath,$ORIGIN",
|
||||
"-Wl,-soname,libdever_answer.so",
|
||||
"-o",
|
||||
"libdever_answer.so",
|
||||
],
|
||||
vec![
|
||||
"tool.c",
|
||||
"-L.",
|
||||
"-ldever_answer",
|
||||
"-Wl,-rpath,$ORIGIN",
|
||||
"-o",
|
||||
"tool",
|
||||
],
|
||||
] {
|
||||
success(
|
||||
Command::new("cc")
|
||||
.current_dir(&bin)
|
||||
.args(args)
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
fs::write(
|
||||
root.join("module/demo/service/api.dever"),
|
||||
"cmd start = app.start",
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let published = root.join("relocated");
|
||||
artifact.publish(&published).unwrap();
|
||||
fs::remove_dir_all(&bin).unwrap();
|
||||
let output = success(
|
||||
Command::new(&published)
|
||||
.args(["demo.service.start", "{}"])
|
||||
.env("LD_LIBRARY_PATH", "/does-not-exist")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let values: serde_json::Value = serde_json::from_str(&output).unwrap();
|
||||
let first = values["data"]["first"].as_str().unwrap();
|
||||
assert!(first.starts_with("42:"), "{output}");
|
||||
assert_eq!(first, values["data"]["second"].as_str().unwrap());
|
||||
assert_eq!(
|
||||
Path::new(first.strip_prefix("42:").unwrap())
|
||||
.file_name()
|
||||
.unwrap(),
|
||||
"program"
|
||||
);
|
||||
let directory = Path::new(first.strip_prefix("42:").unwrap())
|
||||
.parent()
|
||||
.unwrap();
|
||||
assert!(
|
||||
!directory.exists(),
|
||||
"resource directory leaked: {}",
|
||||
directory.display()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
use super::*;
|
||||
mod command;
|
||||
mod native;
|
||||
mod native_package;
|
||||
mod selection;
|
||||
pub(crate) mod worker;
|
||||
|
||||
fn project(name: &str, port: &str, adapter: &str, app: &str) -> PathBuf {
|
||||
let root = directory(name);
|
||||
let domain = root.join("module/demo/service");
|
||||
for (file, source) in [
|
||||
("port.dever", port),
|
||||
("adapter.dever", adapter),
|
||||
("app/main.dever", app),
|
||||
] {
|
||||
write_source(domain.join(file), source).unwrap();
|
||||
}
|
||||
root
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn port_binds_directly_and_keeps_table_kind_in_inspect() {
|
||||
let root = project(
|
||||
"port-native",
|
||||
"add(value: Int) (out: Int)",
|
||||
"port.add(value: Int) (out: Int) { out = value + 1 }",
|
||||
"flow start() (out: Int)\n| step | kind | do |\n| out | port | port.add(41) |",
|
||||
);
|
||||
let (project, program) = analyze(&root);
|
||||
assert_eq!(program.functions.len(), 2, "no forwarding implementation");
|
||||
let files = emit::emit(&program, &ownership::analyze(&program), &project.sources);
|
||||
let app = &files["module/d_4_demo_7_service_3_app.rs"].text;
|
||||
assert!(
|
||||
app.contains("d_4_demo_7_service_7_adapter_4_port_3_add(41i64)"),
|
||||
"{app}"
|
||||
);
|
||||
let artifact = build::build(
|
||||
&project,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(run(&artifact.binary), "42");
|
||||
let path = root.to_str().unwrap();
|
||||
success(cli(&["fmt", path]));
|
||||
success(cli(&["fmt", path, "--check"]));
|
||||
let index: serde_json::Value =
|
||||
serde_json::from_str(&success(cli(&["inspect", path, "--json"]))).unwrap();
|
||||
let contract = index["symbols"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|symbol| symbol["kind"] == "port")
|
||||
.unwrap();
|
||||
assert_eq!(contract["name"], "demo.service.port.add");
|
||||
assert!(
|
||||
index["calls"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|edge| edge["caller"] == contract["id"] && edge["kind"] == "implementation")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effectful_adapter_is_awaited_directly_and_cannot_be_called_around_its_port() {
|
||||
let root = project(
|
||||
"port-async",
|
||||
"pause() () fails dever.time.SleepResult",
|
||||
"flow port.pause() ()\n| step | kind | do |\n| - | flow | dever.time.sleep(0) |",
|
||||
"flow start() (out: Int)\n| step | kind | do |\n| - | port | port.pause() |\n| out | calc | 42 |",
|
||||
);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let target = program
|
||||
.functions
|
||||
.iter()
|
||||
.find(|function| function.signature.name == "demo.service.app.start")
|
||||
.unwrap();
|
||||
assert!(target.effects.suspends && target.effects.clock);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(run(&artifact.binary), "42");
|
||||
write_source(
|
||||
root.join("module/demo/service/app/main.dever"),
|
||||
"flow start() ()\n| step | kind | do |\n| - | - | demo.service.adapter.port.pause() |",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(program::check(&loaded.declarations, &loaded.modules).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapter_contract_rejects_mismatch_hidden_effects_and_undeclared_failures() {
|
||||
let app = "flow start() (out: Int)\n| step | kind | do |\n| out | port | port.read(1) |";
|
||||
for (name, contract, implementation, message) in [
|
||||
(
|
||||
"signature",
|
||||
"read(value: Int) (out: Int)",
|
||||
"port.read(value: Bool) (out: Int) { out = 1 }",
|
||||
"signature",
|
||||
),
|
||||
(
|
||||
"failure",
|
||||
"read(value: Int) (out: Int)",
|
||||
"port.read(value: Int) (out: Int) { check value > 0 else Invalid\nout = value }",
|
||||
"failures",
|
||||
),
|
||||
(
|
||||
"effect",
|
||||
"read(value: Int) (out: Int)",
|
||||
"port.read(value: Int) (out: Int) { time = dever.time.now()\nout = value }",
|
||||
"effectful",
|
||||
),
|
||||
(
|
||||
"missing",
|
||||
"read(value: Int) (out: Int)",
|
||||
"helper() () {}",
|
||||
"requires an Adapter",
|
||||
),
|
||||
] {
|
||||
let root = project(&format!("port-{name}"), contract, implementation, app);
|
||||
let project = Project::load(&root).unwrap();
|
||||
assert!(project.diagnostics.is_empty(), "{:?}", project.diagnostics);
|
||||
let error = program::check(&project.declarations, &project.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains(message), "{name}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapter_propagates_declared_error_through_a_rule_without_wrapping() {
|
||||
let root = project(
|
||||
"port-fails",
|
||||
"type Error { error Rejected }\nread(value: Int) (out: Int) fails Error",
|
||||
"rule port.read(value: Int) (out: Int)\n| value | out |\n| < 0 | fail(port.Error.Rejected) |\n| >= 0 | value |",
|
||||
"flow start() (out: Int)\n| step | kind | do |\n| out | port | port.read(-1) |",
|
||||
);
|
||||
let (project, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&project,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let output = Command::new(&artifact.binary).output().unwrap();
|
||||
assert!(!output.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&output.stderr).contains("Rejected"),
|
||||
"{:?}",
|
||||
output
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapter_private_settings_load_once_from_their_own_namespace() {
|
||||
let root = project(
|
||||
"port-private-setting",
|
||||
"read() (out: Text)",
|
||||
"setting { prefix: Text\nlimit: Int >= 1 and <= 100\nkey: Secret }\nport.read() (out: Text) { out = setting.prefix }",
|
||||
"setting prefix: Text\nflow start() (out: Text)\n| step | kind | do |\n| out | port | port.read() |",
|
||||
);
|
||||
fs::create_dir_all(root.join("config")).unwrap();
|
||||
let configuration = root.join("config/setting.json");
|
||||
fs::write(&configuration,r#"{"module":{"demo":{"service":{"prefix":"domain"}}},"adapter":{"demo.service":{"setting":{"prefix":"adapter","limit":10,"key":"private-value"}}}}"#).unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let run = || {
|
||||
Command::new(&artifact.binary)
|
||||
.arg("--config")
|
||||
.arg(&configuration)
|
||||
.output()
|
||||
.unwrap()
|
||||
};
|
||||
let result = run();
|
||||
assert!(
|
||||
result.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&result.stderr)
|
||||
);
|
||||
assert_eq!(
|
||||
String::from_utf8_lossy(&result.stdout).trim(),
|
||||
"\"adapter\""
|
||||
);
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["fmt", root.to_str().unwrap(), "--check"]));
|
||||
assert!(
|
||||
fs::read_to_string(root.join("module/demo/service/adapter.dever"))
|
||||
.unwrap()
|
||||
.starts_with("setting {")
|
||||
);
|
||||
success(cli(&["inspect", root.to_str().unwrap(), "--json"]));
|
||||
for bad in [
|
||||
r#"{"module":{"demo":{"service":{"prefix":"domain"}}},"adapter":{"demo.service":{"setting":{"prefix":"adapter","limit":0,"key":"private-value"}}}}"#,
|
||||
r#"{"module":{"demo":{"service":{"prefix":"domain"}}},"adapter":{"demo.service":{"setting":{"prefix":"adapter","limit":10}}}}"#,
|
||||
r#"{"module":{"demo":{"service":{"prefix":"domain"}}}}"#,
|
||||
] {
|
||||
fs::write(&configuration, bad).unwrap();
|
||||
let result = run();
|
||||
assert!(!result.status.success());
|
||||
assert!(!String::from_utf8_lossy(&result.stderr).contains("private-value"));
|
||||
}
|
||||
write_source(
|
||||
root.join("module/demo/service/app/main.dever"),
|
||||
"start() (out: Text) { out = adapter.setting.prefix }",
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(program::check(&loaded.declarations, &loaded.modules).is_err());
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn native_install_rejects_shared_source_and_directory_conflicts_before_preparation() {
|
||||
for same_entry in [true, false] {
|
||||
let root = project(
|
||||
&format!("native-conflict-{same_entry}"),
|
||||
"render(source: Text) (html: Text)",
|
||||
"external npm \"javascript/render.mjs\" { lib \"marked@15.0.12\" }",
|
||||
"flow start() (out: Text)\n| step | kind | do |\n| out | port | port.render(\"hello\") |",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
fs::create_dir(domain.join("javascript")).unwrap();
|
||||
fs::create_dir(domain.join("adapter")).unwrap();
|
||||
fs::rename(
|
||||
domain.join("adapter.dever"),
|
||||
domain.join("adapter/first.dever"),
|
||||
)
|
||||
.unwrap();
|
||||
let second = if same_entry {
|
||||
"render.mjs"
|
||||
} else {
|
||||
"second.mjs"
|
||||
};
|
||||
fs::write(
|
||||
domain.join("adapter/second.dever"),
|
||||
format!("external npm \"javascript/{second}\" {{ lib \"marked@14.0.0\" }}"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(domain.join("javascript/render.mjs"), "").unwrap();
|
||||
fs::write(domain.join("javascript").join(second), "").unwrap();
|
||||
let output = cli(&["lib", "install", root.to_str().unwrap()]);
|
||||
assert!(!output.status.success());
|
||||
assert!(
|
||||
String::from_utf8_lossy(&output.stderr).contains("different dependencies"),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert!(!root.join("dever.lock").exists());
|
||||
assert!(!domain.join("javascript/package.json").exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_go_keeps_port_contracts_and_formats_dependencies_without_preparing_tools() {
|
||||
let root = project(
|
||||
"go-contract",
|
||||
"render(source: Text) (html: Text)",
|
||||
"external go \"go/render.go\" { lib \"github.com/yuin/goldmark@v1.7.8\"
|
||||
allow file }",
|
||||
"flow start() (out: Text)\n| step | kind | do |\n| out | port | port.render(\"hello\") |",
|
||||
);
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["check", root.to_str().unwrap()]));
|
||||
let text = fs::read_to_string(root.join("module/demo/service/adapter.dever")).unwrap();
|
||||
assert!(
|
||||
text.contains("external go") && text.contains("lib \"github.com/yuin/goldmark@v1.7.8\"")
|
||||
);
|
||||
assert!(!root.join("dever.lock").exists());
|
||||
let index: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
root.to_str().unwrap(),
|
||||
"--json",
|
||||
])))
|
||||
.unwrap();
|
||||
assert_eq!(index["worker_contracts"][0]["ecosystem"], "go");
|
||||
let adapter = root.join("module/demo/service/adapter.dever");
|
||||
for body in [
|
||||
"file \"../private\"",
|
||||
"file \"/private\"",
|
||||
"file \"helper.go\"\nfile \"helper.go\"",
|
||||
] {
|
||||
fs::write(
|
||||
&adapter,
|
||||
format!("external go \"go/render.go\" {{ {body} }}"),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(!cli(&["check", root.to_str().unwrap()]).status.success());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "downloads checksum-pinned official Node/npm and a real package through lib install"]
|
||||
fn npm_native_lock_bundles_node_and_packages_and_cleans_runtime_files() {
|
||||
let root = project(
|
||||
"npm-native",
|
||||
"render(source: Text) (html: Text)",
|
||||
"external npm \"javascript/render.mjs\" { lib \"marked@15.0.12\"\nfile \"helper.mjs\"\nfile \"message.txt\"\nallow process }",
|
||||
"flow start() (html: Text)\n| step | kind | do |\n| html | port | port.render(\"# Hello\") |",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
let source = domain.join("javascript");
|
||||
fs::create_dir(&source).unwrap();
|
||||
fs::write(source.join("render.mjs"), "import {renderText} from './helper.mjs'; import {spawnSync} from 'node:child_process'; export async function render(payload) { const child=spawnSync(process.execPath,['-e','process.stdout.write(String(21*2))']); if(child.status!==0 || String(child.stdout)!=='42') throw new Error(String(child.stderr)); return {html:renderText(payload.source)}; }").unwrap();
|
||||
fs::write(source.join("helper.mjs"), "import {marked} from 'marked'; import {readFileSync,existsSync} from 'node:fs'; export function renderText(value) { if(existsSync(new URL('./.env',import.meta.url))) throw new Error('undeclared secret copied'); return marked(value+readFileSync(new URL('./message.txt',import.meta.url),'utf8')); }").unwrap();
|
||||
fs::write(source.join("message.txt"), "").unwrap();
|
||||
fs::write(source.join(".env"), "not a runtime resource").unwrap();
|
||||
fs::write(domain.join("api.dever"), "cmd start = app.start").unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["check", root.to_str().unwrap()]));
|
||||
success(cli(&["lib", "install", root.to_str().unwrap()]));
|
||||
let lock = fs::read(source.join("package-lock.json")).unwrap();
|
||||
assert!(String::from_utf8_lossy(&lock).contains("sha512-"));
|
||||
success(cli(&["lib", "install", root.to_str().unwrap()]));
|
||||
assert_eq!(fs::read(source.join("package-lock.json")).unwrap(), lock);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let output = root.join("published");
|
||||
artifact.publish(&output).unwrap();
|
||||
fs::remove_dir_all(&source).unwrap();
|
||||
let resources = root.join("runtime-resources");
|
||||
fs::create_dir(&resources).unwrap();
|
||||
let result = success(
|
||||
Command::new(output)
|
||||
.args(["demo.service.start", "{}"])
|
||||
.env("PATH", "")
|
||||
.env("TMPDIR", &resources)
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let value: serde_json::Value = serde_json::from_str(&result).unwrap();
|
||||
assert_eq!(value["data"], "<h1>Hello</h1>\n");
|
||||
assert_eq!(fs::read_dir(&resources).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "downloads checksum-pinned uv, managed Python and real packages through lib install"]
|
||||
fn python_native_lock_bundles_python_standard_library_extensions_and_packages() {
|
||||
let root = project(
|
||||
"pip-native",
|
||||
"render(source: Text) (html: Text)",
|
||||
"external pip \"python/render.py\" { lib \"Markdown@3.8.2\"\nfile \"helper.py\"\nfile \"message.txt\"\nallow process }",
|
||||
"flow start() (html: Text)\n| step | kind | do |\n| html | port | port.render(\"# Hello\") |",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
let source = domain.join("python");
|
||||
fs::create_dir(&source).unwrap();
|
||||
fs::write(source.join("render.py"), "import ssl, sqlite3, subprocess, sys\nfrom helper import render_text\nasync def render(payload, setting):\n child=subprocess.run([sys.executable,'-c','import ssl,sqlite3;print(21*2)'],check=True,capture_output=True,text=True)\n assert child.stdout.strip()=='42'\n return {'html':render_text(payload['source'])}\n").unwrap();
|
||||
fs::write(source.join("helper.py"), "from pathlib import Path\nimport markdown\ndef render_text(value):\n assert not Path(__file__).with_name('.env').exists()\n return markdown.markdown(value + Path(__file__).with_name('message.txt').read_text())\n").unwrap();
|
||||
fs::write(source.join("message.txt"), "").unwrap();
|
||||
fs::write(source.join(".env"), "not a runtime resource").unwrap();
|
||||
fs::write(domain.join("api.dever"), "cmd start = app.start").unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["check", root.to_str().unwrap()]));
|
||||
success(cli(&["lib", "install", root.to_str().unwrap()]));
|
||||
let lock = fs::read(source.join("uv.lock")).unwrap();
|
||||
assert!(String::from_utf8_lossy(&lock).contains("sha256:"));
|
||||
success(cli(&["lib", "install", root.to_str().unwrap()]));
|
||||
assert_eq!(fs::read(source.join("uv.lock")).unwrap(), lock);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let output = root.join("published");
|
||||
artifact.publish(&output).unwrap();
|
||||
fs::remove_dir_all(&source).unwrap();
|
||||
let resources = root.join("runtime-resources");
|
||||
fs::create_dir(&resources).unwrap();
|
||||
let result = success(
|
||||
Command::new(&output)
|
||||
.args(["demo.service.start", "{}"])
|
||||
.env("PATH", "")
|
||||
.env("PYTHONPATH", "/does-not-exist")
|
||||
.env("TMPDIR", &resources)
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let value: serde_json::Value = serde_json::from_str(&result).unwrap();
|
||||
assert_eq!(value["data"], "<h1>Hello</h1>");
|
||||
assert_eq!(fs::read_dir(&resources).unwrap().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "downloads checksum-pinned official Go and a real module through lib install"]
|
||||
fn go_native_lock_offline_build_and_generated_worker_run_without_source_or_system_go() {
|
||||
let root = project(
|
||||
"go-native",
|
||||
"render(source: Text) (html: Text)",
|
||||
"external go \"go/render.go\" { lib \"github.com/yuin/goldmark@v1.7.8\"\nfile \"helper.go\"\nfile \"message.txt\" }",
|
||||
"flow start() (html: Text)\n| step | kind | do |\n| html | port | port.render(\"# Hello\") |",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
let source = domain.join("go");
|
||||
fs::create_dir(&source).unwrap();
|
||||
fs::write(source.join("render.go"), r#"package main
|
||||
import ("context"; "bytes"; "github.com/yuin/goldmark")
|
||||
func Render(ctx context.Context, payload any, setting any) (any,error) {
|
||||
var out bytes.Buffer
|
||||
if err:=goldmark.Convert([]byte(payload.(map[string]any)["source"].(string)+suffix), &out); err!=nil { return nil,err }
|
||||
return map[string]any{"html":out.String()},nil
|
||||
}
|
||||
"#).unwrap();
|
||||
fs::write(
|
||||
source.join("helper.go"),
|
||||
"package main\nimport _ \"embed\"\n//go:embed message.txt\nvar suffix string\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(source.join("message.txt"), "").unwrap();
|
||||
fs::write(domain.join("api.dever"), "cmd start = app.start").unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let (loaded, program) = analyze(&root);
|
||||
assert!(
|
||||
build::build(&loaded, &program, "main", Profile::Dev, None)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("not locked")
|
||||
);
|
||||
success(cli(&["lib", "install", root.to_str().unwrap()]));
|
||||
let lock = fs::read(root.join("dever.lock")).unwrap();
|
||||
let native_mod = fs::read(source.join("go.mod")).unwrap();
|
||||
let native_sum = fs::read(source.join("go.sum")).unwrap();
|
||||
assert!(String::from_utf8_lossy(&native_sum).contains("github.com/yuin/goldmark v1.7.8 h1:"));
|
||||
assert!(!String::from_utf8_lossy(&native_mod).contains("dever/component"));
|
||||
success(cli(&["lib", "install", root.to_str().unwrap()]));
|
||||
assert_eq!(fs::read(root.join("dever.lock")).unwrap(), lock);
|
||||
let (loaded, program) = analyze(&root);
|
||||
fs::write(source.join("go.sum"), b"tampered").unwrap();
|
||||
assert!(
|
||||
build::build(&loaded, &program, "main", Profile::Dev, None)
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("digest mismatch")
|
||||
);
|
||||
fs::write(source.join("go.sum"), &native_sum).unwrap();
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
assert_eq!(fs::read(source.join("go.mod")).unwrap(), native_mod);
|
||||
assert_eq!(fs::read(source.join("go.sum")).unwrap(), native_sum);
|
||||
let output = root.join("published");
|
||||
artifact.publish(&output).unwrap();
|
||||
fs::remove_dir_all(&source).unwrap();
|
||||
let value: serde_json::Value = serde_json::from_str(&success(
|
||||
Command::new(&output)
|
||||
.args(["demo.service.start", "{}"])
|
||||
.env("PATH", "")
|
||||
.output()
|
||||
.unwrap(),
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(value["data"], "<h1>Hello</h1>\n");
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[ignore = "uses the checksum-pinned official Go toolchain prepared by lib install"]
|
||||
fn package_native_lock_is_restored_without_mutating_cached_sources() {
|
||||
let author = project(
|
||||
"native-package-author",
|
||||
"render(source: Text) (html: Text)",
|
||||
"external go \"go/render.go\" {}",
|
||||
"flow start() (html: Text)\n| step | kind | do |\n| html | port | port.render(\"packaged\") |",
|
||||
);
|
||||
let directory = author.join("module/demo/service/go");
|
||||
fs::create_dir(&directory).unwrap();
|
||||
fs::write(
|
||||
directory.join("render.go"),
|
||||
r#"package main
|
||||
import "context"
|
||||
func Render(ctx context.Context, payload any, setting any) (any,error) {
|
||||
return map[string]any{"html":payload.(map[string]any)["source"]},nil
|
||||
}
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["lib", "install", author.to_str().unwrap()]));
|
||||
let consumer = super::super::directory("native-package-consumer");
|
||||
let home = std::env::var_os("DEVER_HOME").expect("native tests require DEVER_HOME");
|
||||
let output = Command::new("python3").args(["-c", r#"
|
||||
import hashlib, io, json, pathlib, sys, zipfile
|
||||
author, root, home = map(pathlib.Path, sys.argv[1:])
|
||||
manifest = json.dumps(dict(format='dever-package-v1', name='demo', version='1.0.0', dependencies={}))
|
||||
archive = io.BytesIO()
|
||||
with zipfile.ZipFile(archive, 'w', compression=zipfile.ZIP_DEFLATED) as z:
|
||||
z.writestr('dever-package.json', manifest)
|
||||
for path in sorted((author/'module').rglob('*')):
|
||||
if path.is_file(): z.write(path, path.relative_to(author))
|
||||
raw = archive.getvalue()
|
||||
digest = hashlib.sha256(raw).hexdigest()
|
||||
(home/'packages').mkdir(exist_ok=True)
|
||||
(home/'packages'/digest).write_bytes(raw)
|
||||
(root/'module/client/start/app').mkdir(parents=True)
|
||||
(root/'module/client/start/app/main.dever').write_text('flow start() (out: Text)\n| step | kind | do |\n| out | flow | demo.service.start() |')
|
||||
(root/'config').mkdir()
|
||||
registry = 'https://registry.invalid'
|
||||
(root/'config/setting.json').write_text(json.dumps({'package':{'registry':registry,'use':['demo@1.0.0']}}))
|
||||
(root/'dever.lock').write_text(json.dumps(dict(format='dever-lock-1',registry=registry,roots={'demo':'1.0.0'},packages=[dict(name='demo',version='1.0.0',sha256=digest,bytes=len(raw),manifest_sha256=hashlib.sha256(manifest.encode()).hexdigest(),dependencies={})])))
|
||||
print(digest)
|
||||
"#]).arg(&author).arg(&consumer).arg(&home).output().unwrap();
|
||||
let digest = success(output).trim().to_owned();
|
||||
success(cli(&["fmt", consumer.to_str().unwrap()]));
|
||||
let cached = PathBuf::from(home)
|
||||
.join("packages")
|
||||
.join(format!("{digest}.unpacked"));
|
||||
success(cli(&["lib", "install", consumer.to_str().unwrap()]));
|
||||
let lock = fs::read(consumer.join("dever.lock")).unwrap();
|
||||
let manifest = fs::read(cached.join("module/demo/service/go/go.mod")).unwrap();
|
||||
assert_eq!(manifest, fs::read(directory.join("go.mod")).unwrap());
|
||||
assert_eq!(
|
||||
success(cli(&[
|
||||
"run",
|
||||
consumer.to_str().unwrap(),
|
||||
"--entry",
|
||||
"client.start.app.start"
|
||||
]))
|
||||
.trim(),
|
||||
"\"packaged\""
|
||||
);
|
||||
success(cli(&["lib", "install", consumer.to_str().unwrap()]));
|
||||
assert_eq!(fs::read(consumer.join("dever.lock")).unwrap(), lock);
|
||||
assert_eq!(
|
||||
fs::read(cached.join("module/demo/service/go/go.mod")).unwrap(),
|
||||
manifest
|
||||
);
|
||||
success(cli(&["package", "doctor", consumer.to_str().unwrap()]));
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
use super::*;
|
||||
|
||||
fn multi(name: &str, port: &str, first: &str, second: &str, app: &str) -> PathBuf {
|
||||
let root = project(name, port, first, app);
|
||||
let domain = root.join("module/demo/service");
|
||||
fs::create_dir(domain.join("adapter")).unwrap();
|
||||
fs::rename(
|
||||
domain.join("adapter.dever"),
|
||||
domain.join("adapter/first.dever"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(domain.join("adapter/second.dever"), second).unwrap();
|
||||
fs::create_dir(root.join("config")).unwrap();
|
||||
root
|
||||
}
|
||||
fn selected(binary: &Path, root: &Path, configuration: &str) -> std::process::Output {
|
||||
let path = root.join("config/setting.json");
|
||||
fs::write(&path, configuration).unwrap();
|
||||
Command::new(binary)
|
||||
.arg("--config")
|
||||
.arg(path)
|
||||
.output()
|
||||
.unwrap()
|
||||
}
|
||||
#[test]
|
||||
fn multi_adapter_selects_at_startup_and_decodes_only_selected_settings() {
|
||||
let root = multi(
|
||||
"port-selection",
|
||||
"read(value: Text) (out: Text)",
|
||||
"setting { prefix: Text }\nport.read(value: Text) (out: Text) { out = prefix() + value }\nprefix() (out: Text) { out = setting.prefix }",
|
||||
"setting { count: Int >= 1 and <= 3\nkey: Secret }\nport.read(value: Text) (out: Text) { out = value + value }",
|
||||
"flow start() (out: Text)\n| step | kind | do |\n| out | port | port.read(\"x\") |",
|
||||
);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
for (config, expected) in [
|
||||
(
|
||||
r#"{"adapter":{"demo.service":{"use":"first","setting":{"prefix":"A"}}}}"#,
|
||||
"\"Ax\"",
|
||||
),
|
||||
(
|
||||
r#"{"adapter":{"demo.service":{"setting":{"count":2,"key":"private-value"},"use":"second"}}}"#,
|
||||
"\"xx\"",
|
||||
),
|
||||
] {
|
||||
let output = selected(&artifact.binary, &root, config);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), expected);
|
||||
}
|
||||
for config in [
|
||||
r#"{"adapter":{"demo.service":{"setting":{"prefix":"A"}}}}"#,
|
||||
r#"{"adapter":{"demo.service":{"use":"unknown"}}}"#,
|
||||
r#"{"adapter":{"demo.service":{"use":"first","use":"second","setting":{"prefix":"A"}}}}"#,
|
||||
r#"{"adapter":{"demo.service":{"use":"second","setting":{"count":0,"key":"private-value"}}}}"#,
|
||||
r#"{"adapter":{"demo.service":{"use":"first","setting":{"prefix":"A","prefix":"B"}}}}"#,
|
||||
r#"{"adapter":{"demo.service":{"setting":{"prefix":"A","prefix":"B"},"use":"first"}}}"#,
|
||||
r#"{"adapter":{"demo.service":{"use":"first","setting":{"prefix":"A"},"other":1}}}"#,
|
||||
] {
|
||||
let output = selected(&artifact.binary, &root, config);
|
||||
assert!(!output.status.success(), "accepted {config}");
|
||||
assert!(!String::from_utf8_lossy(&output.stderr).contains("private-value"));
|
||||
}
|
||||
let index: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
root.to_str().unwrap(),
|
||||
"--json",
|
||||
])))
|
||||
.unwrap();
|
||||
let ports = index["symbols"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|s| s["name"] == "demo.service.port.read")
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(ports.len(), 1);
|
||||
assert_eq!(
|
||||
index["calls"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.filter(|edge| edge["caller"] == ports[0]["id"] && edge["kind"] == "implementation")
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_adapter_returns_multiple_fields_with_one_call_per_branch() {
|
||||
let root = multi(
|
||||
"port-selection-outputs",
|
||||
"read(value: Text) (first: Text, second: Int)",
|
||||
"port.read(value: Text) (first: Text, second: Int) { first = value\nsecond = 1 }",
|
||||
"port.read(value: Text) (first: Text, second: Int) { first = value\nsecond = 2 }",
|
||||
"flow start() (out: Int)\n| step | kind | do |\n| answer | port | port.read(\"hello\") |\n| out | calc | answer.second |",
|
||||
);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
for (name, expected) in [("first", "1"), ("second", "2")] {
|
||||
let output = selected(
|
||||
&artifact.binary,
|
||||
&root,
|
||||
&format!(r#"{{"adapter":{{"demo.service":{{"use":"{name}"}}}}}}"#),
|
||||
);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_adapter_must_implement_the_whole_port_and_obey_its_contract() {
|
||||
for (name, second, message) in [
|
||||
(
|
||||
"incomplete",
|
||||
"port.read(value: Int) (out: Int) { out = value }",
|
||||
"requires an Adapter",
|
||||
),
|
||||
(
|
||||
"signature",
|
||||
"port.read(value: Bool) (out: Int) { out = 1 }\nport.write() () {}",
|
||||
"signature",
|
||||
),
|
||||
(
|
||||
"failure",
|
||||
"port.read(value: Int) (out: Int) { check value > 0 else Invalid\nout = value }\nport.write() () {}",
|
||||
"failures",
|
||||
),
|
||||
(
|
||||
"cycle",
|
||||
"port.read(value: Int) (out: Int) { out = helper(value) }\nhelper(value: Int) (out: Int) { out = helper(value) }\nport.write() () {}",
|
||||
"recursive",
|
||||
),
|
||||
] {
|
||||
let root = multi(
|
||||
&format!("port-selection-{name}"),
|
||||
"read(value: Int) (out: Int)\nwrite() ()",
|
||||
"port.read(value: Int) (out: Int) { out = value }\nport.write() () {}",
|
||||
second,
|
||||
"flow start() (out: Int)\n| step | kind | do |\n| out | port | port.read(1) |",
|
||||
);
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains(message), "{name}: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_adapter_keeps_async_failures_and_private_settings_in_child_tasks() {
|
||||
let root = multi(
|
||||
"port-selection-task",
|
||||
"read() (out: Text) fails dever.time.SleepResult",
|
||||
"setting { message: Text }\nflow port.read() (out: Text)\n| step | kind | do |\n| work | calc | run(pause()) |\n| out | calc | wait(work) |\nflow pause() (out: Text)\n| step | kind | do |\n| - | flow | dever.time.sleep(0) |\n| out | calc | setting.message |",
|
||||
"port.read() (out: Text) { out = \"immediate\" }",
|
||||
"flow start() (out: Text)\n| step | kind | do |\n| work | calc | run(port.read()) |\n| out | calc | wait(work) |",
|
||||
);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
for (config, expected) in [
|
||||
(
|
||||
r#"{"adapter":{"demo.service":{"use":"first","setting":{"message":"async"}}}}"#,
|
||||
"\"async\"",
|
||||
),
|
||||
(
|
||||
r#"{"adapter":{"demo.service":{"use":"second"}}}"#,
|
||||
"\"immediate\"",
|
||||
),
|
||||
] {
|
||||
let output = selected(&artifact.binary, &root, config);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_adapter_propagates_selected_failure_without_fallback() {
|
||||
let root = multi(
|
||||
"port-selection-propagate",
|
||||
"type Error { error Rejected }\nread() (out: Int) fails Error",
|
||||
"port.read() (out: Int) { out = 1 }",
|
||||
"port.read() (out: Int) { out = fail(port.Error.Rejected) }",
|
||||
"flow start() (out: Int)\n| step | kind | do |\n| out | port | port.read() |",
|
||||
);
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let output = selected(
|
||||
&artifact.binary,
|
||||
&root,
|
||||
r#"{"adapter":{"demo.service":{"use":"second"}}}"#,
|
||||
);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("Rejected"));
|
||||
let output = selected(
|
||||
&artifact.binary,
|
||||
&root,
|
||||
r#"{"adapter":{"demo.service":{"use":"first"}}}"#,
|
||||
);
|
||||
assert_eq!(success(output).trim(), "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_adapter_test_fake_replaces_all_production_choices() {
|
||||
let root = multi(
|
||||
"port-selection-fake",
|
||||
"read() (out: Int)",
|
||||
"setting { value: Int }\nport.read() (out: Int) { out = setting.value }",
|
||||
"setting { label: Text }\nport.read() (out: Int) { out = 2 }",
|
||||
"start() (out: Int) { out = port.read() }",
|
||||
);
|
||||
let tests = root.join("test/demo/service");
|
||||
fs::create_dir_all(&tests).unwrap();
|
||||
fs::write(
|
||||
tests.join("fake.dever"),
|
||||
"fake() () { assertEq(app.start(), 42) }\nport.read() (out: Int) { out = 42 }",
|
||||
)
|
||||
.unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
let result = success(cli(&["test", root.to_str().unwrap()]));
|
||||
assert!(result.contains("PASS demo.service.fake"), "{result}");
|
||||
assert!(!root.join("config/setting.json").exists());
|
||||
|
||||
write_source(
|
||||
root.join("module/demo/service/app/main.dever"),
|
||||
"setting base:Int\nstart() (out:Int) { out=port.read()+base }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
tests.join("fake.dever"),
|
||||
"fake() () { assertEq(app.start(),44) }\nport.read() (out:Int) { out=42 }",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(root.join("test/setting.json"), r#"{"module":{"demo":{"service":{"base":2}}},"adapter":{"demo.service":{"use":"first","setting":{"value":7}}}}"#).unwrap();
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
assert!(success(cli(&["test", root.to_str().unwrap()])).contains("PASS demo.service.fake"));
|
||||
fs::write(root.join("test/setting.json"), r#"{"module":{"demo":{"service":{"base":2}}},"adapter":{"demo.service":{},"demo.service":{}}}"#).unwrap();
|
||||
let output = cli(&["test", root.to_str().unwrap()]);
|
||||
assert!(!output.status.success());
|
||||
assert!(String::from_utf8_lossy(&output.stderr).contains("duplicate adapter configuration"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_adapter_does_not_erase_returned_error_obligations_or_effects() {
|
||||
for (name, contract, first, second, app, message) in [
|
||||
(
|
||||
"port-body",
|
||||
"read() (out: Int) { out = 1 }",
|
||||
"port.read() (out: Int) { out = 1 }",
|
||||
"port.read() (out: Int) { out = 2 }",
|
||||
"start() (out: Int) { out = port.read() }",
|
||||
"does not allow function bodies",
|
||||
),
|
||||
(
|
||||
"error-value",
|
||||
"type Outcome { Good\nerror Rejected }\nread() (out: Outcome)",
|
||||
"port.read() (out: port.Outcome) { out = port.Outcome.Good }",
|
||||
"port.read() (out: port.Outcome) { out = port.Outcome.Rejected }",
|
||||
"start() () { ignored = port.read() }",
|
||||
"failure is not handled",
|
||||
),
|
||||
(
|
||||
"effect-union",
|
||||
"read() () fails dever.time.SleepResult",
|
||||
"port.read() () {}",
|
||||
"flow port.read() ()\n| step | kind | do |\n| - | flow | dever.time.sleep(0) |",
|
||||
"start() () { port.read() }",
|
||||
"effectful",
|
||||
),
|
||||
] {
|
||||
let root = multi(
|
||||
&format!("port-selection-{name}"),
|
||||
contract,
|
||||
first,
|
||||
second,
|
||||
app,
|
||||
);
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
let error = program::check(&loaded.declarations, &loaded.modules)
|
||||
.err()
|
||||
.unwrap();
|
||||
assert!(error.message.contains(message), "{name}: {error}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
use super::*;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
pub(crate) fn executable(domain: &Path) {
|
||||
static BINARY: OnceLock<PathBuf> = OnceLock::new();
|
||||
let binary=BINARY.get_or_init(|| {
|
||||
let root=directory("worker-fixture");
|
||||
fs::write(root.join("Cargo.toml"),"[package]\nname=\"worker-fixture\"\nversion=\"0.0.1\"\nedition=\"2024\"\n[workspace]\n[[bin]]\nname=\"worker-fixture\"\npath=\"main.rs\"\n[dependencies]\nserde_json=\"=1.0.145\"\n").unwrap();
|
||||
fs::write(root.join("main.rs"),include_str!("worker_fixture.rs.txt")).unwrap();
|
||||
success(Command::new("cargo").args(["+1.95.0","build","--offline","--release"]).env("CARGO_TARGET_DIR",root.join("target")).current_dir(&root).output().unwrap());
|
||||
root.join("target/release/worker-fixture")
|
||||
});
|
||||
fs::create_dir_all(domain.join("bin")).unwrap();
|
||||
fs::copy(binary, domain.join("bin/worker")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_worker_reuses_typed_session_settings_and_embedded_image() {
|
||||
let root = project(
|
||||
"worker-native",
|
||||
"add(value: Int) (out: Int, calls: Int)\necho(value: Text) (out: Text)\nunit() ()",
|
||||
"setting { offset: Int, token: Secret }\nexternal exec \"bin/worker\" {}",
|
||||
"flow start() (out: Int, calls: Int, text: Text)\n| step | kind | do |\n| first | port | port.add(30) |\n| next | port | port.add(first.out) |\n| out | calc | next.out |\n| calls | calc | next.calls |\n| text | port | port.echo(\"中文\") |\n| - | port | port.unit() |",
|
||||
);
|
||||
let domain = root.join("module/demo/service");
|
||||
executable(&domain);
|
||||
fs::create_dir(root.join("config")).unwrap();
|
||||
fs::write(
|
||||
root.join("config/setting.json"),
|
||||
r#"{"adapter":{"demo.service":{"setting":{"offset":6,"token":"private setting"}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let resources = fs::read_to_string(artifact.directory.join("external.rs")).unwrap();
|
||||
assert_eq!(resources.matches("static IMAGE_").count(), 1);
|
||||
let output = root.join("published");
|
||||
artifact.publish(&output).unwrap();
|
||||
fs::remove_file(domain.join("bin/worker")).unwrap();
|
||||
let text = run(&output);
|
||||
assert!(
|
||||
text.contains("42") && text.contains("2") && text.contains("中文"),
|
||||
"{text}"
|
||||
);
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["fmt", root.to_str().unwrap(), "--check"]));
|
||||
let index: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
root.to_str().unwrap(),
|
||||
"--json",
|
||||
])))
|
||||
.unwrap();
|
||||
assert_eq!(index["worker_contracts"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(
|
||||
index["worker_contracts"][0]["operations"],
|
||||
serde_json::json!(["add", "echo", "unit"])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_worker_decodes_declared_errors_and_rejects_range_violations() {
|
||||
for (name, port, call, expected) in [
|
||||
(
|
||||
"error",
|
||||
"type Error { error Rejected(message: Text) }\nfail() (out: Int) fails Error",
|
||||
"fail",
|
||||
"demo.service.port.Error.Rejected",
|
||||
),
|
||||
(
|
||||
"range",
|
||||
"invalid() (out: Int >= 0 and <= 100)",
|
||||
"invalid",
|
||||
"out is outside its declared range",
|
||||
),
|
||||
] {
|
||||
let root = project(
|
||||
&format!("worker-{name}"),
|
||||
port,
|
||||
"external exec \"bin/worker\" {}",
|
||||
&format!(
|
||||
"flow start() (out: Int)\n| step | kind | do |\n| out | port | port.{call}() |"
|
||||
),
|
||||
);
|
||||
executable(&root.join("module/demo/service"));
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let resources = root.join("runtime-resources");
|
||||
fs::create_dir(&resources).unwrap();
|
||||
let output = Command::new(&artifact.binary)
|
||||
.env("TMPDIR", &resources)
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(!output.status.success());
|
||||
let error = String::from_utf8(output.stderr).unwrap();
|
||||
assert!(error.contains(expected), "{error}");
|
||||
assert_eq!(
|
||||
fs::read_dir(&resources).unwrap().count(),
|
||||
0,
|
||||
"failed Worker left runtime resources"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_worker_rejects_nonportable_ports_and_mixed_implementation() {
|
||||
for (name, port, adapter) in [
|
||||
(
|
||||
"payload-choice",
|
||||
"type State { Value(value: Text) }\nread(value: State) (out: Text)",
|
||||
"external exec \"bin/worker\" {}",
|
||||
),
|
||||
(
|
||||
"error-choice",
|
||||
"type State { Ready, error Failed }\nread(value: State) (out: Text)",
|
||||
"external exec \"bin/worker\" {}",
|
||||
),
|
||||
(
|
||||
"secret",
|
||||
"read(value: Secret) (out: Text)",
|
||||
"external exec \"bin/worker\" {}",
|
||||
),
|
||||
(
|
||||
"resource",
|
||||
"read(value: Bytes) (out: Text)",
|
||||
"external exec \"bin/worker\" {}",
|
||||
),
|
||||
(
|
||||
"mixed",
|
||||
"read() (out: Text)",
|
||||
"external exec \"bin/worker\" {}\nhelper() (out: Int) { out = 1 }",
|
||||
),
|
||||
(
|
||||
"duplicate",
|
||||
"read() (out: Text)",
|
||||
"external exec \"bin/worker\" {}\nexternal exec \"bin/other\" {}",
|
||||
),
|
||||
] {
|
||||
let root = project(
|
||||
&format!("worker-reject-{name}"),
|
||||
port,
|
||||
adapter,
|
||||
"start() (out: Int) { out = 1 }",
|
||||
);
|
||||
let loaded = Project::load(&root).unwrap();
|
||||
assert!(
|
||||
!loaded.diagnostics.is_empty()
|
||||
|| program::check(&loaded.declarations, &loaded.modules).is_err(),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn external_worker_captures_business_payload_without_losing_error_obligation() {
|
||||
let root = project(
|
||||
"worker-capture",
|
||||
"type Error { error Rejected(message: Text) }\nfail() (out: Int) fails Error",
|
||||
r#"external exec "bin/worker" {}"#,
|
||||
r#"type Attempt { Done(out: Int), error Failed(error: port.Error) }
|
||||
flow start() (out: Attempt)
|
||||
| step | kind | do |
|
||||
| out | port | result(port.fail()) |
|
||||
"#,
|
||||
);
|
||||
executable(&root.join("module/demo/service"));
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
assert!(run(&artifact.binary).contains("business rejection"));
|
||||
}
|
||||
|
||||
fn sdk_contract(name: &str) -> (PathBuf, PathBuf) {
|
||||
let root = project(
|
||||
name,
|
||||
r#"
|
||||
type Error { error Rejected(message: Text) }
|
||||
type ToolName { Add, Multiply }
|
||||
tool(value: ToolName, maybe: ToolName?, items: List<ToolName>) (out: ToolName)
|
||||
echo(value: Int, label: Text?, items: List<Int>) (out: Int, name: Text?)
|
||||
fail() (out: Int) fails Error
|
||||
hang() ()
|
||||
invalid() (out: Int >= 0 and <= 100)
|
||||
raw(value: Json) (out: Json)
|
||||
floating(value: Float) (out: Float)
|
||||
"#,
|
||||
r#"setting { marker: Text }
|
||||
external exec "bin/worker" {}"#,
|
||||
"start() (out: Int) { out = 1 }",
|
||||
);
|
||||
success(cli(&["fmt", root.to_str().unwrap()]));
|
||||
success(cli(&["check", root.to_str().unwrap()]));
|
||||
let index: serde_json::Value = serde_json::from_str(&success(cli(&[
|
||||
"inspect",
|
||||
root.to_str().unwrap(),
|
||||
"--json",
|
||||
])))
|
||||
.unwrap();
|
||||
let manifest = root.join("manifest.json");
|
||||
fs::write(
|
||||
&manifest,
|
||||
serde_json::to_vec(&index["worker_contracts"][0]).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
(root, manifest)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_sdks_use_the_compilers_exact_port_manifest() {
|
||||
let (root, manifest) = sdk_contract("worker-sdks");
|
||||
let repository = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap();
|
||||
let go = root.join("go");
|
||||
fs::create_dir(&go).unwrap();
|
||||
fs::write(go.join("go.mod"),format!("module sdkfixture\ngo 1.25.0\nrequire dever/component v0.0.1\nreplace dever/component => {}\n",repository.join("sdk/go").display())).unwrap();
|
||||
fs::write(
|
||||
go.join("main.go"),
|
||||
include_str!("../../../external-sdk/go_worker.go.txt"),
|
||||
)
|
||||
.unwrap();
|
||||
fs::copy(&manifest, go.join("manifest.json")).unwrap();
|
||||
let go_binary = go.join("worker");
|
||||
success(
|
||||
Command::new("go")
|
||||
.args(["build", "-buildvcs=false", "-o"])
|
||||
.arg(&go_binary)
|
||||
.arg(".")
|
||||
.current_dir(&go)
|
||||
.env("GOTOOLCHAIN", "local")
|
||||
.env("GOWORK", "off")
|
||||
.env("CGO_ENABLED", "0")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
for language in ["python", "javascript", "go"] {
|
||||
let sdk = if language == "go" {
|
||||
go_binary.clone()
|
||||
} else {
|
||||
repository.join("sdk").join(language)
|
||||
};
|
||||
success(
|
||||
Command::new(std::env::var_os("DEVER_SDK_PYTHON").unwrap_or_else(|| "python3".into()))
|
||||
.arg("-B")
|
||||
.arg(repository.join("test/external-sdk/check.py"))
|
||||
.arg(&manifest)
|
||||
.arg(sdk)
|
||||
.arg(language)
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
let domain = root.join("module/demo/service");
|
||||
fs::create_dir(domain.join("bin")).unwrap();
|
||||
fs::copy(&go_binary, domain.join("bin/worker")).unwrap();
|
||||
write_source(
|
||||
domain.join("app/main.dever"),
|
||||
r#"type Attempt { Done(out: Int), error Failed(error: port.Error) }
|
||||
flow start() (out: Int, name: Text?, tool: port.ToolName, rejected: Attempt)
|
||||
| step | kind | do |
|
||||
| reply | port | port.echo(42, "中文", []) |
|
||||
| out | calc | reply.out |
|
||||
| name | calc | reply.name |
|
||||
| tool | port | port.tool(port.ToolName.Multiply, null, [port.ToolName.Add]) |
|
||||
| rejected | port | result(port.fail()) |
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::create_dir(root.join("config")).unwrap();
|
||||
fs::write(
|
||||
root.join("config/setting.json"),
|
||||
r#"{"adapter":{"demo.service":{"setting":{"marker":"unused"}}}}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(
|
||||
&loaded,
|
||||
&program,
|
||||
"demo.service.app.start",
|
||||
Profile::Dev,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let binary = root.join("published");
|
||||
artifact.publish(&binary).unwrap();
|
||||
fs::remove_file(domain.join("bin/worker")).unwrap();
|
||||
fs::remove_file(go_binary).unwrap();
|
||||
let output = run(&binary);
|
||||
assert!(
|
||||
output.contains("42")
|
||||
&& output.contains("中文")
|
||||
&& output.contains("Multiply")
|
||||
&& output.contains("business rejection"),
|
||||
"{output}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires YYJSON_ROOT pointing to yyjson 0.12.0 sources"]
|
||||
fn c_and_cpp_sdks_use_the_compilers_exact_port_manifest() {
|
||||
let (root, manifest) = sdk_contract("worker-c-sdk");
|
||||
let repository = Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap();
|
||||
let library = PathBuf::from(std::env::var("YYJSON_ROOT").expect("YYJSON_ROOT"));
|
||||
let source = root.join("native");
|
||||
fs::create_dir(&source).unwrap();
|
||||
let contract = fs::read_to_string(&manifest).unwrap();
|
||||
fs::write(
|
||||
source.join("manifest.h"),
|
||||
serde_json::to_string(&contract).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
fs::copy(
|
||||
repository.join("test/external-sdk/c_worker.c"),
|
||||
source.join("main.c"),
|
||||
)
|
||||
.unwrap();
|
||||
let mut objects = Vec::new();
|
||||
for (name, path) in [
|
||||
("yyjson", library.join("src/yyjson.c")),
|
||||
("wire", repository.join("sdk/c/wire.c")),
|
||||
("ffi", repository.join("sdk/c/dever_ffi.c")),
|
||||
] {
|
||||
let object = source.join(format!("{name}.o"));
|
||||
success(
|
||||
Command::new("cc")
|
||||
.args(["-std=c11", "-Wall", "-Wextra", "-Werror", "-c"])
|
||||
.arg(path)
|
||||
.arg("-I")
|
||||
.arg(library.join("src"))
|
||||
.arg("-I")
|
||||
.arg(repository.join("sdk/c"))
|
||||
.arg("-o")
|
||||
.arg(&object)
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
objects.push(object);
|
||||
}
|
||||
for (compiler, standard) in [("cc", "-std=c11"), ("c++", "-std=c++17")] {
|
||||
let binary = source.join(compiler);
|
||||
success(
|
||||
Command::new(compiler)
|
||||
.args([standard, "-Wall", "-Wextra", "-Werror"])
|
||||
.arg(source.join("main.c"))
|
||||
.args(&objects)
|
||||
.arg("-I")
|
||||
.arg(library.join("src"))
|
||||
.arg("-I")
|
||||
.arg(repository.join("sdk/c"))
|
||||
.arg("-o")
|
||||
.arg(&binary)
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
success(
|
||||
Command::new(std::env::var_os("DEVER_SDK_PYTHON").unwrap_or_else(|| "python3".into()))
|
||||
.arg("-B")
|
||||
.arg(repository.join("test/external-sdk/c_check.py"))
|
||||
.arg(&manifest)
|
||||
.arg(&binary)
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_gpu_capability_passes_device_selection_without_inheriting_application_secrets() {
|
||||
for gpu in [false, true] {
|
||||
let root = project(
|
||||
&format!("worker-gpu-{gpu}"),
|
||||
"device() (out: Text?, secret: Text?)",
|
||||
if gpu {
|
||||
r#"external exec "bin/worker" {allow gpu}"#
|
||||
} else {
|
||||
r#"external exec "bin/worker" {}"#
|
||||
},
|
||||
"flow start() (out: Text?, secret: Text?)\n| step | kind | do |\n| device | port | port.device() |\n| out | calc | device.out |\n| secret | calc | device.secret |",
|
||||
);
|
||||
executable(&root.join("module/demo/service"));
|
||||
fs::write(
|
||||
root.join("module/demo/service/api.dever"),
|
||||
"cmd start = app.start",
|
||||
)
|
||||
.unwrap();
|
||||
let (loaded, program) = analyze(&root);
|
||||
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
||||
let text = success(
|
||||
Command::new(&artifact.binary)
|
||||
.args(["demo.service.start", "{}"])
|
||||
.env("CUDA_VISIBLE_DEVICES", "7")
|
||||
.env("DEVER_TEST_SECRET", "private")
|
||||
.output()
|
||||
.unwrap(),
|
||||
);
|
||||
let value: serde_json::Value = serde_json::from_str(&text).unwrap();
|
||||
assert_eq!(
|
||||
value["data"]["out"],
|
||||
if gpu {
|
||||
serde_json::json!("7")
|
||||
} else {
|
||||
serde_json::Value::Null
|
||||
}
|
||||
);
|
||||
assert!(value["data"]["secret"].is_null());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
use serde_json::{Value,json};
|
||||
use std::io::{Read,Write};
|
||||
fn receive() -> Value {
|
||||
let mut prefix=[0u8;4];std::io::stdin().read_exact(&mut prefix).unwrap();
|
||||
let mut body=vec![0;u32::from_be_bytes(prefix) as usize];std::io::stdin().read_exact(&mut body).unwrap();
|
||||
serde_json::from_slice(&body).unwrap()
|
||||
}
|
||||
fn send(value:Value){let bytes=serde_json::to_vec(&value).unwrap();let mut out=std::io::stdout().lock();out.write_all(&(bytes.len() as u32).to_be_bytes()).unwrap();out.write_all(&bytes).unwrap();out.flush().unwrap();}
|
||||
fn main(){
|
||||
let mut hello=receive();let setting=hello.as_object_mut().unwrap().remove("setting").unwrap();hello["kind"]="ready".into();send(hello);
|
||||
let mut calls=0;
|
||||
loop {let message=receive();match message["kind"].as_str().unwrap(){
|
||||
"health"=>send(message),
|
||||
"shutdown"=>{send(message);return},
|
||||
"cancel"=>send(json!({"kind":"error","id":message["id"],"error":"dever.cancelled","payload":null})),
|
||||
"call"=>{calls+=1;let operation=message["operation"].as_str().unwrap();let payload=match operation{
|
||||
"add"=>json!({"out":message["payload"]["value"].as_i64().unwrap()+setting["offset"].as_i64().unwrap(),"calls":calls}),
|
||||
"echo"=>json!({"out":message["payload"]["value"]}),
|
||||
"fail"=>{send(json!({"kind":"error","id":message["id"],"error":"demo.service.port.Error.Rejected","payload":{"message":"business rejection"}}));continue},
|
||||
"invalid"=>json!({"out":200}),
|
||||
"hang"=>continue,
|
||||
"unit"=>json!({}),
|
||||
"device"=>json!({"out":std::env::var("CUDA_VISIBLE_DEVICES").ok(),"secret":std::env::var("DEVER_TEST_SECRET").ok()}),
|
||||
_=>panic!("unknown test operation"),
|
||||
};send(json!({"kind":"result","id":message["id"],"payload":payload}));},
|
||||
_=>panic!("unknown protocol message"),
|
||||
}}
|
||||
}
|
||||
Reference in new issue
Block a user