Compare commits
16 Commits
bc30c9cc89
...
main
Author | SHA1 | Date | |
---|---|---|---|
|
38709e06f3
|
||
|
08de312cd9
|
||
|
4d1cd3d910
|
||
|
c1c1ae3bd1
|
||
|
ec339c5cbe
|
||
|
2aa6277385
|
||
|
9c47eaaf93
|
||
|
fce0ccb2d8
|
||
|
e5a6228448
|
||
|
052539409b
|
||
|
1551b4707b
|
||
|
4b597cc445
|
||
|
cf06c7fa36
|
||
|
6f7fded175
|
||
|
fde456fd5e
|
||
|
a8227eb808
|
914
Cargo.lock
generated
914
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
16
Cargo.toml
16
Cargo.toml
@@ -14,12 +14,12 @@ redis = { version = "0.32.5", features = [
|
||||
"connection-manager",
|
||||
"aio",
|
||||
] }
|
||||
jsonrpsee = { version = "0.26.0", features = [
|
||||
"server",
|
||||
"macros",
|
||||
"client",
|
||||
"http-client",
|
||||
"ws-client",
|
||||
] }
|
||||
http = "1.3.1"
|
||||
jsonrpsee = { version = "0.26.0", features = ["server", "macros"] }
|
||||
async-trait = "0.1.83"
|
||||
# HTTP client to call Mycelium JSON-RPC
|
||||
reqwest = { version = "0.12.7", features = ["json", "rustls-tls"] }
|
||||
# Base64 encoding for message payloads
|
||||
base64 = "0.22.1"
|
||||
# Error derive for clean error types
|
||||
thiserror = "2.0.16"
|
||||
tracing-subscriber = { version = "0.3.18", features = ["env-filter", "fmt"] }
|
||||
|
120
README.md
120
README.md
@@ -1,122 +1,2 @@
|
||||
# herocoordinator
|
||||
|
||||
Supervisor JSON-RPC client
|
||||
|
||||
This crate now includes a typed client to communicate with an external "supervisor" component via JSON-RPC 2.0 over HTTP and WebSocket, generated from the OpenAPI spec in `specs/supervisor.yaml`.
|
||||
|
||||
Highlights
|
||||
- Transports: HTTP and WebSocket (jsonrpsee).
|
||||
- Session: optional bearer token support (Authorization header).
|
||||
- Methods implemented: fetch_nonce, authenticate, whoami, play, create_job, start_job, run_job, get_job_status, get_job_output, get_job_logs, list_jobs, stop_job, delete_job, clear_all_jobs.
|
||||
- Types mirror the spec exactly (enum casing etc.).
|
||||
|
||||
Enable features
|
||||
|
||||
jsonrpsee client features are enabled in Cargo.toml:
|
||||
- server, macros, client, http-client, ws-client.
|
||||
|
||||
Usage
|
||||
|
||||
Add to your crate imports:
|
||||
```rust
|
||||
use herocoordinator::supervisor::{
|
||||
SupervisorClient,
|
||||
ScriptType,
|
||||
JobParams,
|
||||
};
|
||||
```
|
||||
|
||||
Create an HTTP client (default http://127.0.0.1:9944/)
|
||||
```rust
|
||||
# #[tokio::main]
|
||||
# async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut client = SupervisorClient::new_http("http://127.0.0.1:9944/").await?;
|
||||
|
||||
// Optional: obtain a token (out-of-band) and set it
|
||||
// client.set_bearer_token("your-token").await?;
|
||||
|
||||
let pk = "abcdef1234deadbeef";
|
||||
let nonce = client.fetch_nonce(pk).await?;
|
||||
let ok = client.authenticate(pk, "signature-here", &nonce).await?;
|
||||
assert!(ok, "authentication should succeed");
|
||||
|
||||
// whoami
|
||||
let who = client.whoami().await?;
|
||||
println!("whoami: {who}");
|
||||
|
||||
// play
|
||||
let res = client.play(r#"echo "hello""#).await?;
|
||||
println!("play.output: {}", res.output);
|
||||
|
||||
// create a job
|
||||
let job_id = client
|
||||
.create_job(JobParams {
|
||||
script: r#"print("hi")"#.into(),
|
||||
script_type: ScriptType::Python,
|
||||
caller_id: "cli".into(),
|
||||
context_id: "demo".into(),
|
||||
timeout: Some(30),
|
||||
prerequisites: Some(vec![]),
|
||||
})
|
||||
.await?;
|
||||
println!("created job: {job_id}");
|
||||
|
||||
// start a job
|
||||
let started = client.start_job(&job_id).await?;
|
||||
println!("job started: {}", started.success);
|
||||
|
||||
// get status / output / logs
|
||||
let status = client.get_job_status(&job_id).await?;
|
||||
println!("job status: {:?}", status);
|
||||
|
||||
let output = client.get_job_output(&job_id).await?;
|
||||
println!("job output: {output}");
|
||||
|
||||
let logs = client.get_job_logs(&job_id).await?;
|
||||
println!("job logs: {:?}", logs.logs);
|
||||
|
||||
// list / stop / delete / clear
|
||||
let jobs = client.list_jobs().await?;
|
||||
println!("jobs: {:?}", jobs);
|
||||
|
||||
// stop and delete are noop if job is already finished (server-defined behavior)
|
||||
let _ = client.stop_job(&job_id).await?;
|
||||
let _ = client.delete_job(&job_id).await?;
|
||||
|
||||
// clear all jobs (use with care)
|
||||
let _ = client.clear_all_jobs().await?;
|
||||
# Ok(())
|
||||
# }
|
||||
```
|
||||
|
||||
Create a WebSocket client (default ws://127.0.0.1:9944/)
|
||||
```rust
|
||||
# #[tokio::main]
|
||||
# async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let client = SupervisorClient::new_ws("ws://127.0.0.1:9944/").await?;
|
||||
// Use the same methods as the HTTP client
|
||||
let who = client.whoami().await?;
|
||||
println!("whoami: {who}");
|
||||
# Ok(())
|
||||
# }
|
||||
```
|
||||
|
||||
Notes on authenticate and tokens
|
||||
- The OpenAPI spec defines authenticate returning a boolean. If your deployment provides a token via a header or another method, capture it externally and set it on the client using:
|
||||
- `client.set_bearer_token("...").await?`
|
||||
- To remove: `client.clear_bearer_token().await?`
|
||||
|
||||
Types
|
||||
- Enums and DTOs mirror the OpenAPI casing:
|
||||
- ScriptType: "OSIS" | "SAL" | "V" | "Python"
|
||||
- JobStatus: "Dispatched" | "WaitingForPrerequisites" | "Started" | "Error" | "Finished"
|
||||
- JobParams include: script, script_type, caller_id, context_id, timeout?, prerequisites?.
|
||||
|
||||
Testing
|
||||
- Unit tests verify enum casing and request param shapes. No live server needed. Run: `cargo test`.
|
||||
|
||||
Files
|
||||
- src/supervisor/mod.rs
|
||||
- src/supervisor/types.rs
|
||||
- src/supervisor/error.rs
|
||||
- src/supervisor/client.rs
|
||||
|
361
scripts/jsonrpc_demo.py
Normal file
361
scripts/jsonrpc_demo.py
Normal file
@@ -0,0 +1,361 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Demo script for HeroCoordinator JSON-RPC API.
|
||||
- Creates an actor
|
||||
- Verifies by loading the actor
|
||||
- Creates a context with the actor as admin/reader/executor
|
||||
- Creates three jobs with dependencies
|
||||
- Creates a flow referencing those jobs
|
||||
- Fetches and prints the flow DAG
|
||||
|
||||
Usage:
|
||||
COORDINATOR_URL=http://127.0.0.1:9652 python3 scripts/jsonrpc_demo.py
|
||||
Defaults to http://127.0.0.1:9652 if COORDINATOR_URL is not set.
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import sys
|
||||
from urllib import request, error
|
||||
from typing import Any, Dict, List, Tuple
|
||||
|
||||
JSONRPC_VERSION = "2.0"
|
||||
|
||||
class JsonRpcClient:
|
||||
def __init__(self, url: str):
|
||||
self.url = url.rstrip("/")
|
||||
self._id = 0
|
||||
|
||||
def call(self, method: str, params: Dict[str, Any]) -> Any:
|
||||
self._id += 1
|
||||
payload = {
|
||||
"jsonrpc": JSONRPC_VERSION,
|
||||
"id": self._id,
|
||||
"method": method,
|
||||
"params": params,
|
||||
}
|
||||
data = json.dumps(payload).encode("utf-8")
|
||||
req = request.Request(self.url, data=data, headers={"Content-Type": "application/json"})
|
||||
try:
|
||||
with request.urlopen(req) as resp:
|
||||
body = resp.read()
|
||||
except error.HTTPError as e:
|
||||
try:
|
||||
details = e.read().decode("utf-8", "ignore")
|
||||
except Exception:
|
||||
details = ""
|
||||
raise RuntimeError(f"HTTP error {e.code}: {details}") from e
|
||||
except error.URLError as e:
|
||||
raise RuntimeError(f"URL error: {e.reason}") from e
|
||||
|
||||
try:
|
||||
obj = json.loads(body.decode("utf-8"))
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Invalid JSON response: {body!r}") from e
|
||||
|
||||
# JSON-RPC single response expected
|
||||
if isinstance(obj, list):
|
||||
raise RuntimeError("Batch responses are not supported in this demo")
|
||||
|
||||
if obj.get("error"):
|
||||
raise RuntimeError(f"RPC error: {json.dumps(obj['error'])}")
|
||||
|
||||
return obj.get("result")
|
||||
|
||||
def print_header(title: str):
|
||||
print("\n" + "=" * 80)
|
||||
print(title)
|
||||
print("=" * 80)
|
||||
|
||||
def pretty_print(obj: Any):
|
||||
print(json.dumps(obj, indent=2, sort_keys=True))
|
||||
|
||||
def summarize_dag(dag: Dict[str, Any]):
|
||||
print_header("Flow DAG Summary")
|
||||
flow_id = dag.get("flow_id")
|
||||
caller_id = dag.get("caller_id")
|
||||
context_id = dag.get("context_id")
|
||||
print(f"flow_id={flow_id} caller_id={caller_id} context_id={context_id}")
|
||||
edges: List[Tuple[int, int]] = dag.get("edges", [])
|
||||
roots: List[int] = dag.get("roots", [])
|
||||
leaves: List[int] = dag.get("leaves", [])
|
||||
levels: List[List[int]] = dag.get("levels", [])
|
||||
nodes: Dict[str, Any] = dag.get("nodes", {})
|
||||
|
||||
print("Edges:")
|
||||
for a, b in edges:
|
||||
print(f" {a} -> {b}")
|
||||
|
||||
print(f"Roots: {roots}")
|
||||
print(f"Leaves: {leaves}")
|
||||
print("Levels:")
|
||||
for i, lvl in enumerate(levels):
|
||||
print(f" L{i}: {lvl}")
|
||||
|
||||
# Show nodes and their dependencies (from JobSummary)
|
||||
print("Nodes:")
|
||||
for k, v in nodes.items():
|
||||
depends = v.get("depends", [])
|
||||
prerequisites = v.get("prerequisites", [])
|
||||
stype = v.get("script_type")
|
||||
print(f" Job {k}: depends={depends} prerequisites={prerequisites} script_type={stype}")
|
||||
|
||||
def assert_edges(edges: List[Tuple[int, int]], required: List[Tuple[int, int]]):
|
||||
edge_set = {(int(a), int(b)) for a, b in edges}
|
||||
missing = [e for e in required if e not in edge_set]
|
||||
if missing:
|
||||
raise AssertionError(f"Missing expected edges in DAG: {missing}; got={sorted(edge_set)}")
|
||||
|
||||
def main():
|
||||
url = os.getenv("COORDINATOR_URL", "http://127.0.0.1:9652")
|
||||
client = JsonRpcClient(url)
|
||||
|
||||
# Deterministic demo IDs; change if collisions happen
|
||||
actor_id = 1001
|
||||
context_id = 1 # Redis DB indices are 0-15; keep <= 15
|
||||
job_a = 3001
|
||||
job_b = 3002
|
||||
job_c = 3003
|
||||
job_d = 3004
|
||||
job_e = 3005
|
||||
job_f = 3006
|
||||
job_g = 3007
|
||||
job_h = 3008
|
||||
job_i = 3009
|
||||
flow_id = 4001
|
||||
|
||||
print_header("actor.create")
|
||||
actor = client.call("actor.create", {
|
||||
"actor": {
|
||||
"id": actor_id,
|
||||
"pubkey": "demo-pubkey",
|
||||
"address": ["127.0.0.1"]
|
||||
}
|
||||
})
|
||||
pretty_print(actor)
|
||||
|
||||
print_header("actor.load")
|
||||
actor_loaded = client.call("actor.load", {"id": actor_id})
|
||||
pretty_print(actor_loaded)
|
||||
|
||||
print_header("context.create")
|
||||
context = client.call("context.create", {
|
||||
"context": {
|
||||
"id": context_id,
|
||||
"admins": [actor_id],
|
||||
"readers": [actor_id],
|
||||
"executors": [actor_id]
|
||||
}
|
||||
})
|
||||
pretty_print(context)
|
||||
|
||||
print_header("job.create - A (root)")
|
||||
jobA = client.call("job.create", {
|
||||
"context_id": context_id,
|
||||
"job": {
|
||||
"id": job_a,
|
||||
"caller_id": actor_id,
|
||||
"context_id": context_id,
|
||||
"script": "print('A')",
|
||||
"script_type": "Python",
|
||||
"timeout": 30,
|
||||
"retries": 0,
|
||||
"env_vars": {},
|
||||
"prerequisites": [],
|
||||
"depends": []
|
||||
}
|
||||
})
|
||||
pretty_print(jobA)
|
||||
|
||||
print_header("job.create - B (root)")
|
||||
jobB = client.call("job.create", {
|
||||
"context_id": context_id,
|
||||
"job": {
|
||||
"id": job_b,
|
||||
"caller_id": actor_id,
|
||||
"context_id": context_id,
|
||||
"script": "print('B')",
|
||||
"script_type": "Python",
|
||||
"timeout": 30,
|
||||
"retries": 0,
|
||||
"env_vars": {},
|
||||
"prerequisites": [],
|
||||
"depends": []
|
||||
}
|
||||
})
|
||||
pretty_print(jobB)
|
||||
|
||||
print_header("job.create - C (depends on A and B)")
|
||||
jobC = client.call("job.create", {
|
||||
"context_id": context_id,
|
||||
"job": {
|
||||
"id": job_c,
|
||||
"caller_id": actor_id,
|
||||
"context_id": context_id,
|
||||
"script": "print('C')",
|
||||
"script_type": "Python",
|
||||
"timeout": 30,
|
||||
"retries": 0,
|
||||
"env_vars": {},
|
||||
"prerequisites": [],
|
||||
"depends": [job_a, job_b]
|
||||
}
|
||||
})
|
||||
pretty_print(jobC)
|
||||
|
||||
print_header("job.create - D (depends on A)")
|
||||
jobD = client.call("job.create", {
|
||||
"context_id": context_id,
|
||||
"job": {
|
||||
"id": job_d,
|
||||
"caller_id": actor_id,
|
||||
"context_id": context_id,
|
||||
"script": "print('D')",
|
||||
"script_type": "Python",
|
||||
"timeout": 30,
|
||||
"retries": 0,
|
||||
"env_vars": {},
|
||||
"prerequisites": [],
|
||||
"depends": [job_a]
|
||||
}
|
||||
})
|
||||
pretty_print(jobD)
|
||||
|
||||
print_header("job.create - E (depends on B)")
|
||||
jobE = client.call("job.create", {
|
||||
"context_id": context_id,
|
||||
"job": {
|
||||
"id": job_e,
|
||||
"caller_id": actor_id,
|
||||
"context_id": context_id,
|
||||
"script": "print('E')",
|
||||
"script_type": "Python",
|
||||
"timeout": 30,
|
||||
"retries": 0,
|
||||
"env_vars": {},
|
||||
"prerequisites": [],
|
||||
"depends": [job_b]
|
||||
}
|
||||
})
|
||||
pretty_print(jobE)
|
||||
|
||||
print_header("job.create - F (depends on C and D)")
|
||||
jobF = client.call("job.create", {
|
||||
"context_id": context_id,
|
||||
"job": {
|
||||
"id": job_f,
|
||||
"caller_id": actor_id,
|
||||
"context_id": context_id,
|
||||
"script": "print('F')",
|
||||
"script_type": "Python",
|
||||
"timeout": 30,
|
||||
"retries": 0,
|
||||
"env_vars": {},
|
||||
"prerequisites": [],
|
||||
"depends": [job_c, job_d]
|
||||
}
|
||||
})
|
||||
pretty_print(jobF)
|
||||
|
||||
print_header("job.create - G (depends on C and E)")
|
||||
jobG = client.call("job.create", {
|
||||
"context_id": context_id,
|
||||
"job": {
|
||||
"id": job_g,
|
||||
"caller_id": actor_id,
|
||||
"context_id": context_id,
|
||||
"script": "print('G')",
|
||||
"script_type": "Python",
|
||||
"timeout": 30,
|
||||
"retries": 0,
|
||||
"env_vars": {},
|
||||
"prerequisites": [],
|
||||
"depends": [job_c, job_e]
|
||||
}
|
||||
})
|
||||
pretty_print(jobG)
|
||||
|
||||
print_header("job.create - H (leaf; depends on F and G)")
|
||||
jobH = client.call("job.create", {
|
||||
"context_id": context_id,
|
||||
"job": {
|
||||
"id": job_h,
|
||||
"caller_id": actor_id,
|
||||
"context_id": context_id,
|
||||
"script": "print('H')",
|
||||
"script_type": "Python",
|
||||
"timeout": 30,
|
||||
"retries": 0,
|
||||
"env_vars": {},
|
||||
"prerequisites": [],
|
||||
"depends": [job_f, job_g]
|
||||
}
|
||||
})
|
||||
pretty_print(jobH)
|
||||
|
||||
print_header("job.create - I (leaf; depends on F and G)")
|
||||
jobI = client.call("job.create", {
|
||||
"context_id": context_id,
|
||||
"job": {
|
||||
"id": job_i,
|
||||
"caller_id": actor_id,
|
||||
"context_id": context_id,
|
||||
"script": "print('I')",
|
||||
"script_type": "Python",
|
||||
"timeout": 30,
|
||||
"retries": 0,
|
||||
"env_vars": {},
|
||||
"prerequisites": [],
|
||||
"depends": [job_f, job_g]
|
||||
}
|
||||
})
|
||||
pretty_print(jobI)
|
||||
|
||||
print_header("flow.create")
|
||||
flow = client.call("flow.create", {
|
||||
"context_id": context_id,
|
||||
"flow": {
|
||||
"id": flow_id,
|
||||
"caller_id": actor_id,
|
||||
"context_id": context_id,
|
||||
"jobs": [job_a, job_b, job_c, job_d, job_e, job_f, job_g, job_h, job_i],
|
||||
"env_vars": {}
|
||||
}
|
||||
})
|
||||
pretty_print(flow)
|
||||
|
||||
print_header("flow.dag")
|
||||
dag = client.call("flow.dag", {"context_id": context_id, "id": flow_id})
|
||||
summarize_dag(dag)
|
||||
|
||||
# Validate roots and leaves
|
||||
got_roots = list(map(int, dag.get("roots", [])))
|
||||
if got_roots != sorted([job_a, job_b]):
|
||||
print("WARNING: Unexpected roots:", got_roots, file=sys.stderr)
|
||||
|
||||
got_leaves = {int(x) for x in dag.get("leaves", [])}
|
||||
expected_leaves = {job_h, job_i}
|
||||
if got_leaves != expected_leaves:
|
||||
print("WARNING: Unexpected leaves:", got_leaves, "expected:", expected_leaves, file=sys.stderr)
|
||||
|
||||
# Check edges reflect the expanded DAG
|
||||
expected_edges = [
|
||||
(job_a, job_c), (job_b, job_c),
|
||||
(job_a, job_d), (job_b, job_e),
|
||||
(job_c, job_f), (job_d, job_f),
|
||||
(job_c, job_g), (job_e, job_g),
|
||||
(job_f, job_h), (job_g, job_h),
|
||||
(job_f, job_i), (job_g, job_i),
|
||||
]
|
||||
try:
|
||||
assert_edges(dag.get("edges", []), expected_edges)
|
||||
print("DAG edges contain expected dependencies:", expected_edges)
|
||||
except AssertionError as e:
|
||||
print("WARNING:", e, file=sys.stderr)
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception as e:
|
||||
print_header("Error")
|
||||
print(str(e))
|
||||
sys.exit(1)
|
@@ -20,7 +20,7 @@
|
||||
"methods": [
|
||||
{
|
||||
"name": "actor.create",
|
||||
"summary": "Create/Upsert Actor in a context",
|
||||
"summary": "Create/Upsert Actor",
|
||||
"params": [
|
||||
{
|
||||
"name": "params",
|
||||
@@ -49,7 +49,7 @@
|
||||
},
|
||||
{
|
||||
"name": "actor.load",
|
||||
"summary": "Load an Actor by id from a context",
|
||||
"summary": "Load an Actor by id",
|
||||
"params": [
|
||||
{
|
||||
"name": "params",
|
||||
@@ -438,6 +438,16 @@
|
||||
"Processed"
|
||||
]
|
||||
},
|
||||
"TransportStatus": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Queued",
|
||||
"Sent",
|
||||
"Delivered",
|
||||
"Read",
|
||||
"Failed"
|
||||
]
|
||||
},
|
||||
"MessageType": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
@@ -779,6 +789,12 @@
|
||||
},
|
||||
"status": {
|
||||
"$ref": "#/components/schemas/MessageStatus"
|
||||
},
|
||||
"transport_id": {
|
||||
"type": "string"
|
||||
},
|
||||
"transport_status": {
|
||||
"$ref": "#/components/schemas/TransportStatus"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1165,14 +1181,9 @@
|
||||
"ActorCreateParams": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"context_id",
|
||||
"actor"
|
||||
],
|
||||
"properties": {
|
||||
"context_id": {
|
||||
"type": "integer",
|
||||
"format": "uint32"
|
||||
},
|
||||
"actor": {
|
||||
"$ref": "#/components/schemas/ActorCreate"
|
||||
}
|
||||
@@ -1181,14 +1192,9 @@
|
||||
"ActorLoadParams": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"context_id",
|
||||
"id"
|
||||
],
|
||||
"properties": {
|
||||
"context_id": {
|
||||
"type": "integer",
|
||||
"format": "uint32"
|
||||
},
|
||||
"id": {
|
||||
"type": "integer",
|
||||
"format": "uint32"
|
||||
|
@@ -10,7 +10,7 @@
|
||||
| **Runner** | Public key, Mycelium address, topic name, type (`v\|python\|osis\|rust`), local flag, timestamps | `runner:<id>` (hash) | The *worker* that actually executes **RunnerJob** scripts. It subscribes to a Mycelium topic (normally `runner<id>`). If `local == true` the runner also consumes jobs directly from a Redis queue that is named after the script‑type suffix (`v`, `python`, …). |
|
||||
| **RunnerJob**| Script source, type (`osis\|sal\|v\|python`), env‑vars, prerequisites, dependencies, status, timestamps, result map | `job:<caller_id>:<id>` (hash) | A single executable unit. It lives inside a **Context**, belongs to a **Runner**, and is queued according to its `script_type` (e.g. `queue:python`). Its status moves through the lifecycle `dispatched → waiting_for_prerequisites → started → finished|error`. |
|
||||
|
||||
> **Key idea:** All objects are persisted as *hashes* in a **Redis** database that is dedicated to a *Context*. The system is completely **decentralised** – each actor owns its own context and can spin up as many runners as needed. Communication between actors, runners and the rest of the system happens over **Mycelium**, a message‑bus that uses Redis lists as queues.
|
||||
> **Key idea:** All objects are persisted as *hashes*. Context‑scoped objects (**Context**, **Flow**, **Message**, **Runner**, **RunnerJob**) live in a **Redis** database dedicated to that context. **Actors are global** and are stored in Redis DB 0 under `actor:<id>`. The system is completely **decentralised** – each actor owns its own context and can spin up as many runners as needed. Communication between actors, runners and the rest of the system happens over **Mycelium**, a message‑bus that uses Redis lists as queues.
|
||||
|
||||
---
|
||||
|
||||
|
7
src/clients/mod.rs
Normal file
7
src/clients/mod.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
pub mod mycelium_client;
|
||||
pub mod supervisor_client;
|
||||
pub mod types;
|
||||
|
||||
pub use mycelium_client::{MyceliumClient, MyceliumClientError};
|
||||
pub use supervisor_client::{SupervisorClient, SupervisorClientError};
|
||||
pub use types::Destination;
|
238
src/clients/mycelium_client.rs
Normal file
238
src/clients/mycelium_client.rs
Normal file
@@ -0,0 +1,238 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use reqwest::Client as HttpClient;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::clients::Destination;
|
||||
use crate::models::TransportStatus;
|
||||
|
||||
/// Lightweight client for Mycelium JSON-RPC (send + query status)
|
||||
#[derive(Clone)]
|
||||
pub struct MyceliumClient {
|
||||
base_url: String, // e.g. http://127.0.0.1:8990
|
||||
http: HttpClient,
|
||||
id_counter: Arc<AtomicU64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum MyceliumClientError {
|
||||
#[error("HTTP error: {0}")]
|
||||
Http(#[from] reqwest::Error),
|
||||
#[error("JSON error: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error("Transport timed out waiting for a reply (408)")]
|
||||
TransportTimeout,
|
||||
#[error("JSON-RPC error: {0}")]
|
||||
RpcError(String),
|
||||
#[error("Invalid response: {0}")]
|
||||
InvalidResponse(String),
|
||||
}
|
||||
|
||||
impl MyceliumClient {
|
||||
pub fn new(base_url: impl Into<String>) -> Result<Self, MyceliumClientError> {
|
||||
let url = base_url.into();
|
||||
let http = HttpClient::builder().build()?;
|
||||
Ok(Self {
|
||||
base_url: url,
|
||||
http,
|
||||
id_counter: Arc::new(AtomicU64::new(1)),
|
||||
})
|
||||
}
|
||||
|
||||
fn next_id(&self) -> u64 {
|
||||
self.id_counter.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
async fn jsonrpc(&self, method: &str, params: Value) -> Result<Value, MyceliumClientError> {
|
||||
let req = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": self.next_id(),
|
||||
"method": method,
|
||||
"params": [ params ]
|
||||
});
|
||||
let resp = self.http.post(&self.base_url).json(&req).send().await?;
|
||||
let status = resp.status();
|
||||
let body: Value = resp.json().await?;
|
||||
if let Some(err) = body.get("error") {
|
||||
let code = err.get("code").and_then(|v| v.as_i64()).unwrap_or(0);
|
||||
let msg = err
|
||||
.get("message")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("unknown error");
|
||||
if code == 408 {
|
||||
return Err(MyceliumClientError::TransportTimeout);
|
||||
}
|
||||
return Err(MyceliumClientError::RpcError(format!(
|
||||
"code={code} msg={msg}"
|
||||
)));
|
||||
}
|
||||
if !status.is_success() {
|
||||
return Err(MyceliumClientError::RpcError(format!(
|
||||
"HTTP {status}, body {body}"
|
||||
)));
|
||||
}
|
||||
Ok(body)
|
||||
}
|
||||
|
||||
/// Call messageStatus with an outbound message id (hex string)
|
||||
pub async fn message_status(
|
||||
&self,
|
||||
id_hex: &str,
|
||||
) -> Result<TransportStatus, MyceliumClientError> {
|
||||
let params = json!({ "id": id_hex });
|
||||
let body = self.jsonrpc("messageStatus", params).await?;
|
||||
let result = body.get("result").ok_or_else(|| {
|
||||
MyceliumClientError::InvalidResponse(format!("missing result in response: {body}"))
|
||||
})?;
|
||||
// Accept both { status: "..."} and bare "..."
|
||||
let status_str = if let Some(s) = result.get("status").and_then(|v| v.as_str()) {
|
||||
s.to_string()
|
||||
} else if let Some(s) = result.as_str() {
|
||||
s.to_string()
|
||||
} else {
|
||||
return Err(MyceliumClientError::InvalidResponse(format!(
|
||||
"unexpected result shape: {result}"
|
||||
)));
|
||||
};
|
||||
Self::map_status(&status_str).ok_or_else(|| {
|
||||
MyceliumClientError::InvalidResponse(format!("unknown status: {status_str}"))
|
||||
})
|
||||
}
|
||||
|
||||
fn map_status(s: &str) -> Option<TransportStatus> {
|
||||
match s {
|
||||
"queued" => Some(TransportStatus::Queued),
|
||||
"sent" => Some(TransportStatus::Sent),
|
||||
"delivered" => Some(TransportStatus::Delivered),
|
||||
"read" => Some(TransportStatus::Read),
|
||||
"failed" => Some(TransportStatus::Failed),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build params object for pushMessage without performing any network call.
|
||||
/// Exposed for serializer-only tests and reuse.
|
||||
pub(crate) fn build_push_params(
|
||||
dst: &Destination,
|
||||
topic: &str,
|
||||
payload_b64: &str,
|
||||
reply_timeout: Option<u64>,
|
||||
) -> Value {
|
||||
let dst_v = match dst {
|
||||
Destination::Ip(ip) => json!({ "ip": ip.to_string() }),
|
||||
Destination::Pk(pk) => json!({ "pk": pk }),
|
||||
};
|
||||
let message = json!({
|
||||
"dst": dst_v,
|
||||
"topic": topic,
|
||||
"payload": payload_b64,
|
||||
});
|
||||
let mut params = json!({ "message": message });
|
||||
if let Some(rt) = reply_timeout {
|
||||
params["reply_timeout"] = json!(rt);
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
/// pushMessage: send a message with dst/topic/payload. Optional reply_timeout for sync replies.
|
||||
pub async fn push_message(
|
||||
&self,
|
||||
dst: &Destination,
|
||||
topic: &str,
|
||||
payload_b64: &str,
|
||||
reply_timeout: Option<u64>,
|
||||
) -> Result<Value, MyceliumClientError> {
|
||||
let params = Self::build_push_params(dst, topic, payload_b64, reply_timeout);
|
||||
let body = self.jsonrpc("pushMessage", params).await?;
|
||||
let result = body.get("result").ok_or_else(|| {
|
||||
MyceliumClientError::InvalidResponse(format!("missing result in response: {body}"))
|
||||
})?;
|
||||
Ok(result.clone())
|
||||
}
|
||||
|
||||
/// Helper to extract outbound message id from pushMessage result (InboundMessage or PushMessageResponseId)
|
||||
pub fn extract_message_id_from_result(result: &Value) -> Option<String> {
|
||||
result
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::clients::Destination;
|
||||
|
||||
#[test]
|
||||
fn build_push_params_shapes_ip_pk_and_timeout() {
|
||||
// IP destination
|
||||
let p1 = MyceliumClient::build_push_params(
|
||||
&Destination::Ip("2001:db8::1".parse().unwrap()),
|
||||
"supervisor.rpc",
|
||||
"Zm9vYmFy", // "foobar"
|
||||
Some(10),
|
||||
);
|
||||
let msg1 = p1.get("message").unwrap();
|
||||
assert_eq!(
|
||||
msg1.get("topic").unwrap().as_str().unwrap(),
|
||||
"supervisor.rpc"
|
||||
);
|
||||
assert_eq!(msg1.get("payload").unwrap().as_str().unwrap(), "Zm9vYmFy");
|
||||
assert_eq!(
|
||||
msg1.get("dst")
|
||||
.unwrap()
|
||||
.get("ip")
|
||||
.unwrap()
|
||||
.as_str()
|
||||
.unwrap(),
|
||||
"2001:db8::1"
|
||||
);
|
||||
assert_eq!(p1.get("reply_timeout").unwrap().as_u64().unwrap(), 10);
|
||||
|
||||
// PK destination without timeout
|
||||
let p2 = MyceliumClient::build_push_params(
|
||||
&Destination::Pk(
|
||||
"bb39b4a3a4efd70f3e05e37887677e02efbda14681d0acd3882bc0f754792c32".into(),
|
||||
),
|
||||
"supervisor.rpc",
|
||||
"YmF6", // "baz"
|
||||
None,
|
||||
);
|
||||
let msg2 = p2.get("message").unwrap();
|
||||
assert_eq!(
|
||||
msg2.get("dst")
|
||||
.unwrap()
|
||||
.get("pk")
|
||||
.unwrap()
|
||||
.as_str()
|
||||
.unwrap(),
|
||||
"bb39b4a3a4efd70f3e05e37887677e02efbda14681d0acd3882bc0f754792c32"
|
||||
);
|
||||
assert!(p2.get("reply_timeout").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_message_id_variants() {
|
||||
// PushMessageResponseId
|
||||
let r1 = json!({"id":"0123456789abcdef"});
|
||||
assert_eq!(
|
||||
MyceliumClient::extract_message_id_from_result(&r1).unwrap(),
|
||||
"0123456789abcdef"
|
||||
);
|
||||
|
||||
// InboundMessage-like
|
||||
let r2 = json!({
|
||||
"id":"fedcba9876543210",
|
||||
"srcIp":"449:abcd:0123:defa::1",
|
||||
"payload":"hpV+"
|
||||
});
|
||||
assert_eq!(
|
||||
MyceliumClient::extract_message_id_from_result(&r2).unwrap(),
|
||||
"fedcba9876543210"
|
||||
);
|
||||
}
|
||||
}
|
497
src/clients/supervisor_client.rs
Normal file
497
src/clients/supervisor_client.rs
Normal file
@@ -0,0 +1,497 @@
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
|
||||
use serde_json::{Value, json};
|
||||
use thiserror::Error;
|
||||
|
||||
use crate::clients::{Destination, MyceliumClient, MyceliumClientError};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct SupervisorClient {
|
||||
mycelium: Arc<MyceliumClient>, // Delegated Mycelium transport
|
||||
destination: Destination, // ip or pk
|
||||
topic: String, // e.g. "supervisor.rpc"
|
||||
secret: Option<String>, // optional, required by several supervisor methods
|
||||
id_counter: Arc<AtomicU64>, // JSON-RPC id generator (for inner supervisor requests)
|
||||
}
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum SupervisorClientError {
|
||||
#[error("HTTP error: {0}")]
|
||||
Http(#[from] reqwest::Error),
|
||||
#[error("JSON error: {0}")]
|
||||
Json(#[from] serde_json::Error),
|
||||
#[error("Transport timed out waiting for a reply (408)")]
|
||||
TransportTimeout,
|
||||
#[error("JSON-RPC error: {0}")]
|
||||
RpcError(String),
|
||||
#[error("Invalid response: {0}")]
|
||||
InvalidResponse(String),
|
||||
#[error("Missing secret for method requiring authentication")]
|
||||
MissingSecret,
|
||||
}
|
||||
|
||||
impl From<MyceliumClientError> for SupervisorClientError {
|
||||
fn from(e: MyceliumClientError) -> Self {
|
||||
match e {
|
||||
MyceliumClientError::TransportTimeout => SupervisorClientError::TransportTimeout,
|
||||
MyceliumClientError::RpcError(m) => SupervisorClientError::RpcError(m),
|
||||
MyceliumClientError::InvalidResponse(m) => SupervisorClientError::InvalidResponse(m),
|
||||
MyceliumClientError::Http(err) => SupervisorClientError::Http(err),
|
||||
MyceliumClientError::Json(err) => SupervisorClientError::Json(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SupervisorClient {
|
||||
/// Preferred constructor: provide a shared Mycelium client.
|
||||
pub fn new_with_client(
|
||||
mycelium: Arc<MyceliumClient>,
|
||||
destination: Destination,
|
||||
topic: impl Into<String>,
|
||||
secret: Option<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
mycelium,
|
||||
destination,
|
||||
topic: topic.into(),
|
||||
secret,
|
||||
id_counter: Arc::new(AtomicU64::new(1)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Backward-compatible constructor that builds a Mycelium client from base_url.
|
||||
/// base_url defaults to Mycelium spec "http://127.0.0.1:8990" if empty.
|
||||
pub fn new(
|
||||
base_url: impl Into<String>,
|
||||
destination: Destination,
|
||||
topic: impl Into<String>,
|
||||
secret: Option<String>,
|
||||
) -> Result<Self, SupervisorClientError> {
|
||||
let mut url = base_url.into();
|
||||
if url.is_empty() {
|
||||
url = "http://127.0.0.1:8990".to_string();
|
||||
}
|
||||
let mycelium = Arc::new(MyceliumClient::new(url)?);
|
||||
Ok(Self::new_with_client(mycelium, destination, topic, secret))
|
||||
}
|
||||
|
||||
fn next_id(&self) -> u64 {
|
||||
self.id_counter.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Internal helper used by tests to inspect dst JSON shape.
|
||||
fn build_dst(&self) -> Value {
|
||||
match &self.destination {
|
||||
Destination::Ip(ip) => json!({ "ip": ip.to_string() }),
|
||||
Destination::Pk(pk) => json!({ "pk": pk }),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_supervisor_payload(&self, method: &str, params: Value) -> Value {
|
||||
json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": self.next_id(),
|
||||
"method": method,
|
||||
"params": params,
|
||||
})
|
||||
}
|
||||
|
||||
fn encode_payload(payload: &Value) -> Result<String, SupervisorClientError> {
|
||||
let s = serde_json::to_string(payload)?;
|
||||
Ok(BASE64_STANDARD.encode(s.as_bytes()))
|
||||
}
|
||||
|
||||
fn extract_message_id_from_result(result: &Value) -> Option<String> {
|
||||
// Two possibilities per Mycelium spec oneOf:
|
||||
// - PushMessageResponseId: { "id": "0123456789abcdef" }
|
||||
// - InboundMessage: object containing "id" plus srcIp, ...; we still return id.
|
||||
result
|
||||
.get("id")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string())
|
||||
}
|
||||
|
||||
/// Generic call: build supervisor JSON-RPC message, send via Mycelium pushMessage, return outbound message id (hex).
|
||||
pub async fn call(&self, method: &str, params: Value) -> Result<String, SupervisorClientError> {
|
||||
let inner = self.build_supervisor_payload(method, params);
|
||||
let payload_b64 = Self::encode_payload(&inner)?;
|
||||
let result = self
|
||||
.mycelium
|
||||
.push_message(&self.destination, &self.topic, &payload_b64, None)
|
||||
.await?;
|
||||
|
||||
if let Some(id) = MyceliumClient::extract_message_id_from_result(&result) {
|
||||
return Ok(id);
|
||||
}
|
||||
// Some servers might return the oneOf wrapped, handle len==1 array defensively (not in spec but resilient)
|
||||
if let Some(arr) = result.as_array()
|
||||
&& arr.len() == 1
|
||||
&& let Some(id) = MyceliumClient::extract_message_id_from_result(&arr[0])
|
||||
{
|
||||
return Ok(id);
|
||||
}
|
||||
Err(SupervisorClientError::InvalidResponse(format!(
|
||||
"result did not contain message id: {result}"
|
||||
)))
|
||||
}
|
||||
|
||||
/// Synchronous variant: wait for a JSON-RPC reply via Mycelium reply_timeout, and return the inner JSON-RPC "result".
|
||||
/// If the supervisor returns an error object, map to RpcError.
|
||||
pub async fn call_sync(
|
||||
&self,
|
||||
method: &str,
|
||||
params: Value,
|
||||
reply_timeout_secs: u64,
|
||||
) -> Result<Value, SupervisorClientError> {
|
||||
let inner = self.build_supervisor_payload(method, params);
|
||||
let payload_b64 = Self::encode_payload(&inner)?;
|
||||
|
||||
let result = self
|
||||
.mycelium
|
||||
.push_message(
|
||||
&self.destination,
|
||||
&self.topic,
|
||||
&payload_b64,
|
||||
Some(reply_timeout_secs),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Expect an InboundMessage-like with a base64 payload containing the supervisor JSON-RPC response
|
||||
let payload_field = if let Some(p) = result.get("payload").and_then(|v| v.as_str()) {
|
||||
p.to_string()
|
||||
} else if let Some(arr) = result.as_array() {
|
||||
// Defensive: handle single-element array shape
|
||||
if let Some(one) = arr.get(0) {
|
||||
one.get("payload")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string())
|
||||
.ok_or_else(|| {
|
||||
SupervisorClientError::InvalidResponse(format!(
|
||||
"missing payload in result: {result}"
|
||||
))
|
||||
})?
|
||||
} else {
|
||||
return Err(SupervisorClientError::TransportTimeout);
|
||||
}
|
||||
} else {
|
||||
// No payload => no reply received within timeout (Mycelium would have returned just an id)
|
||||
return Err(SupervisorClientError::TransportTimeout);
|
||||
};
|
||||
|
||||
let raw = BASE64_STANDARD
|
||||
.decode(payload_field.as_bytes())
|
||||
.map_err(|e| {
|
||||
SupervisorClientError::InvalidResponse(format!("invalid base64 payload: {e}"))
|
||||
})?;
|
||||
let rpc_resp: Value = serde_json::from_slice(&raw)?;
|
||||
|
||||
if let Some(err) = rpc_resp.get("error") {
|
||||
return Err(SupervisorClientError::RpcError(err.to_string()));
|
||||
}
|
||||
let res = rpc_resp.get("result").ok_or_else(|| {
|
||||
SupervisorClientError::InvalidResponse(format!(
|
||||
"missing result in supervisor reply: {rpc_resp}"
|
||||
))
|
||||
})?;
|
||||
Ok(res.clone())
|
||||
}
|
||||
|
||||
fn need_secret(&self) -> Result<&str, SupervisorClientError> {
|
||||
self.secret
|
||||
.as_deref()
|
||||
.ok_or(SupervisorClientError::MissingSecret)
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Typed wrappers for Supervisor API
|
||||
// Asynchronous-only: returns outbound message id
|
||||
// -----------------------------
|
||||
|
||||
// Runners
|
||||
pub async fn list_runners(&self) -> Result<String, SupervisorClientError> {
|
||||
self.call("list_runners", json!([])).await
|
||||
}
|
||||
|
||||
pub async fn register_runner(
|
||||
&self,
|
||||
name: impl Into<String>,
|
||||
queue: impl Into<String>,
|
||||
) -> Result<String, SupervisorClientError> {
|
||||
let secret = self.need_secret()?;
|
||||
let params = json!([{
|
||||
"secret": secret,
|
||||
"name": name.into(),
|
||||
"queue": queue.into()
|
||||
}]);
|
||||
self.call("register_runner", params).await
|
||||
}
|
||||
|
||||
pub async fn remove_runner(
|
||||
&self,
|
||||
actor_id: impl Into<String>,
|
||||
) -> Result<String, SupervisorClientError> {
|
||||
self.call("remove_runner", json!([actor_id.into()])).await
|
||||
}
|
||||
|
||||
pub async fn start_runner(
|
||||
&self,
|
||||
actor_id: impl Into<String>,
|
||||
) -> Result<String, SupervisorClientError> {
|
||||
self.call("start_runner", json!([actor_id.into()])).await
|
||||
}
|
||||
|
||||
pub async fn stop_runner(
|
||||
&self,
|
||||
actor_id: impl Into<String>,
|
||||
force: bool,
|
||||
) -> Result<String, SupervisorClientError> {
|
||||
self.call("stop_runner", json!([actor_id.into(), force]))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_runner_status(
|
||||
&self,
|
||||
actor_id: impl Into<String>,
|
||||
) -> Result<String, SupervisorClientError> {
|
||||
self.call("get_runner_status", json!([actor_id.into()]))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn get_all_runner_status(&self) -> Result<String, SupervisorClientError> {
|
||||
self.call("get_all_runner_status", json!([])).await
|
||||
}
|
||||
|
||||
pub async fn start_all(&self) -> Result<String, SupervisorClientError> {
|
||||
self.call("start_all", json!([])).await
|
||||
}
|
||||
|
||||
pub async fn stop_all(&self, force: bool) -> Result<String, SupervisorClientError> {
|
||||
self.call("stop_all", json!([force])).await
|
||||
}
|
||||
|
||||
pub async fn get_all_status(&self) -> Result<String, SupervisorClientError> {
|
||||
self.call("get_all_status", json!([])).await
|
||||
}
|
||||
|
||||
// Jobs
|
||||
pub async fn jobs_create(&self, job: Value) -> Result<String, SupervisorClientError> {
|
||||
let secret = self.need_secret()?;
|
||||
let params = json!([{
|
||||
"secret": secret,
|
||||
"job": job
|
||||
}]);
|
||||
self.call("jobs.create", params).await
|
||||
}
|
||||
|
||||
pub async fn jobs_list(&self) -> Result<String, SupervisorClientError> {
|
||||
self.call("jobs.list", json!([])).await
|
||||
}
|
||||
|
||||
pub async fn job_run(&self, job: Value) -> Result<String, SupervisorClientError> {
|
||||
let secret = self.need_secret()?;
|
||||
let params = json!([{
|
||||
"secret": secret,
|
||||
"job": job
|
||||
}]);
|
||||
self.call("job.run", params).await
|
||||
}
|
||||
|
||||
pub async fn job_start(
|
||||
&self,
|
||||
job_id: impl Into<String>,
|
||||
) -> Result<String, SupervisorClientError> {
|
||||
let secret = self.need_secret()?;
|
||||
let params = json!([{
|
||||
"secret": secret,
|
||||
"job_id": job_id.into()
|
||||
}]);
|
||||
self.call("job.start", params).await
|
||||
}
|
||||
|
||||
pub async fn job_status(
|
||||
&self,
|
||||
job_id: impl Into<String>,
|
||||
) -> Result<String, SupervisorClientError> {
|
||||
self.call("job.status", json!([job_id.into()])).await
|
||||
}
|
||||
|
||||
/// Synchronous job.status: waits for the supervisor to reply and returns the status string.
|
||||
/// The supervisor result may be an object with { status: "..." } or a bare string.
|
||||
pub async fn job_status_sync(
|
||||
&self,
|
||||
job_id: impl Into<String>,
|
||||
reply_timeout_secs: u64,
|
||||
) -> Result<String, SupervisorClientError> {
|
||||
let res = self
|
||||
.call_sync("job.status", json!([job_id.into()]), reply_timeout_secs)
|
||||
.await?;
|
||||
let status = if let Some(s) = res.get("status").and_then(|v| v.as_str()) {
|
||||
s.to_string()
|
||||
} else if let Some(s) = res.as_str() {
|
||||
s.to_string()
|
||||
} else {
|
||||
return Err(SupervisorClientError::InvalidResponse(format!(
|
||||
"unexpected job.status result shape: {res}"
|
||||
)));
|
||||
};
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
pub async fn job_result(
|
||||
&self,
|
||||
job_id: impl Into<String>,
|
||||
) -> Result<String, SupervisorClientError> {
|
||||
self.call("job.result", json!([job_id.into()])).await
|
||||
}
|
||||
|
||||
/// Synchronous job.result: waits for the supervisor to reply and returns a map
|
||||
/// containing exactly one of:
|
||||
/// - {"success": "..."} on success
|
||||
/// - {"error": "..."} on error reported by the runner
|
||||
/// Some servers may return a bare string; we treat that as {"success": "<string>"}.
|
||||
pub async fn job_result_sync(
|
||||
&self,
|
||||
job_id: impl Into<String>,
|
||||
reply_timeout_secs: u64,
|
||||
) -> Result<std::collections::HashMap<String, String>, SupervisorClientError> {
|
||||
let res = self
|
||||
.call_sync("job.result", json!([job_id.into()]), reply_timeout_secs)
|
||||
.await?;
|
||||
|
||||
use std::collections::HashMap;
|
||||
let mut out: HashMap<String, String> = HashMap::new();
|
||||
|
||||
if let Some(obj) = res.as_object() {
|
||||
if let Some(s) = obj.get("success").and_then(|v| v.as_str()) {
|
||||
out.insert("success".to_string(), s.to_string());
|
||||
return Ok(out);
|
||||
}
|
||||
if let Some(s) = obj.get("error").and_then(|v| v.as_str()) {
|
||||
out.insert("error".to_string(), s.to_string());
|
||||
return Ok(out);
|
||||
}
|
||||
return Err(SupervisorClientError::InvalidResponse(format!(
|
||||
"unexpected job.result result shape: {res}"
|
||||
)));
|
||||
} else if let Some(s) = res.as_str() {
|
||||
out.insert("success".to_string(), s.to_string());
|
||||
return Ok(out);
|
||||
}
|
||||
|
||||
Err(SupervisorClientError::InvalidResponse(format!(
|
||||
"unexpected job.result result shape: {res}"
|
||||
)))
|
||||
}
|
||||
|
||||
pub async fn job_stop(
|
||||
&self,
|
||||
job_id: impl Into<String>,
|
||||
) -> Result<String, SupervisorClientError> {
|
||||
let secret = self.need_secret()?;
|
||||
let params = json!([{
|
||||
"secret": secret,
|
||||
"job_id": job_id.into()
|
||||
}]);
|
||||
self.call("job.stop", params).await
|
||||
}
|
||||
|
||||
pub async fn job_delete(
|
||||
&self,
|
||||
job_id: impl Into<String>,
|
||||
) -> Result<String, SupervisorClientError> {
|
||||
let secret = self.need_secret()?;
|
||||
let params = json!([{
|
||||
"secret": secret,
|
||||
"job_id": job_id.into()
|
||||
}]);
|
||||
self.call("job.delete", params).await
|
||||
}
|
||||
|
||||
// Discovery
|
||||
pub async fn rpc_discover(&self) -> Result<String, SupervisorClientError> {
|
||||
self.call("rpc.discover", json!([])).await
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Tests (serialization-only)
|
||||
// -----------------------------
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::net::IpAddr;
|
||||
|
||||
fn mk_client() -> SupervisorClient {
|
||||
// Uses the legacy constructor but will not issue real network calls in these tests.
|
||||
SupervisorClient::new(
|
||||
"http://127.0.0.1:8990",
|
||||
Destination::Pk(
|
||||
"bb39b4a3a4efd70f3e05e37887677e02efbda14681d0acd3882bc0f754792c32".to_string(),
|
||||
),
|
||||
"supervisor.rpc",
|
||||
Some("secret".to_string()),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn builds_dst_ip_and_pk() {
|
||||
let c_ip = SupervisorClient::new(
|
||||
"http://127.0.0.1:8990",
|
||||
Destination::Ip("2001:db8::1".parse().unwrap()),
|
||||
"supervisor.rpc",
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let v_ip = c_ip.build_dst();
|
||||
assert_eq!(v_ip.get("ip").unwrap().as_str().unwrap(), "2001:db8::1");
|
||||
|
||||
let c_pk = mk_client();
|
||||
let v_pk = c_pk.build_dst();
|
||||
assert_eq!(
|
||||
v_pk.get("pk").unwrap().as_str().unwrap(),
|
||||
"bb39b4a3a4efd70f3e05e37887677e02efbda14681d0acd3882bc0f754792c32"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encodes_supervisor_payload_b64() {
|
||||
let c = mk_client();
|
||||
let payload = c.build_supervisor_payload("list_runners", json!([]));
|
||||
let b64 = SupervisorClient::encode_payload(&payload).unwrap();
|
||||
|
||||
// decode and compare round-trip JSON
|
||||
let raw = base64::engine::general_purpose::STANDARD
|
||||
.decode(b64.as_bytes())
|
||||
.unwrap();
|
||||
let decoded: Value = serde_json::from_slice(&raw).unwrap();
|
||||
assert_eq!(
|
||||
decoded.get("method").unwrap().as_str().unwrap(),
|
||||
"list_runners"
|
||||
);
|
||||
assert_eq!(decoded.get("jsonrpc").unwrap().as_str().unwrap(), "2.0");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_message_id_works_for_both_variants() {
|
||||
// PushMessageResponseId
|
||||
let r1 = json!({"id":"0123456789abcdef"});
|
||||
assert_eq!(
|
||||
SupervisorClient::extract_message_id_from_result(&r1).unwrap(),
|
||||
"0123456789abcdef"
|
||||
);
|
||||
// InboundMessage-like
|
||||
let r2 = json!({
|
||||
"id":"fedcba9876543210",
|
||||
"srcIp":"449:abcd:0123:defa::1",
|
||||
"payload":"hpV+"
|
||||
});
|
||||
assert_eq!(
|
||||
SupervisorClient::extract_message_id_from_result(&r2).unwrap(),
|
||||
"fedcba9876543210"
|
||||
);
|
||||
}
|
||||
}
|
9
src/clients/types.rs
Normal file
9
src/clients/types.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
use std::net::IpAddr;
|
||||
|
||||
/// Destination for Mycelium messages (shared by clients)
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Destination {
|
||||
Ip(IpAddr),
|
||||
/// 64-hex public key of the receiver node
|
||||
Pk(String),
|
||||
}
|
11
src/lib.rs
11
src/lib.rs
@@ -1,7 +1,8 @@
|
||||
pub mod models;
|
||||
pub mod storage;
|
||||
pub mod service;
|
||||
mod time;
|
||||
pub mod clients;
|
||||
pub mod dag;
|
||||
pub mod models;
|
||||
pub mod router;
|
||||
pub mod rpc;
|
||||
pub mod supervisor;
|
||||
pub mod service;
|
||||
pub mod storage;
|
||||
mod time;
|
||||
|
34
src/main.rs
34
src/main.rs
@@ -2,6 +2,8 @@ use clap::Parser;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
|
||||
use tracing::{error, info, warn};
|
||||
use tracing_subscriber::{EnvFilter, fmt};
|
||||
#[derive(Debug, Clone, Parser)]
|
||||
#[command(
|
||||
name = "herocoordinator",
|
||||
@@ -73,6 +75,14 @@ struct Cli {
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
let cli = Cli::parse();
|
||||
// Initialize tracing subscriber (pretty formatter; controlled by RUST_LOG)
|
||||
let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));
|
||||
tracing_subscriber::fmt()
|
||||
.with_env_filter(filter)
|
||||
.pretty()
|
||||
.with_target(true)
|
||||
.with_level(true)
|
||||
.init();
|
||||
|
||||
let http_addr = SocketAddr::new(cli.api_http_ip, cli.api_http_port);
|
||||
let ws_addr = SocketAddr::new(cli.api_ws_ip, cli.api_ws_port);
|
||||
@@ -84,18 +94,30 @@ async fn main() {
|
||||
|
||||
// Initialize Service
|
||||
let service = herocoordinator::service::AppService::new(redis);
|
||||
let service_for_router = service.clone();
|
||||
|
||||
// Shared application state
|
||||
let state = Arc::new(herocoordinator::rpc::AppState::new(service));
|
||||
|
||||
// Start router workers (auto-discovered contexts)
|
||||
{
|
||||
let base_url = format!("http://{}:{}", cli.mycelium_ip, cli.mycelium_port);
|
||||
let cfg = herocoordinator::router::RouterConfig {
|
||||
context_ids: Vec::new(), // ignored by start_router_auto
|
||||
concurrency: 32,
|
||||
base_url,
|
||||
topic: "supervisor.rpc".to_string(),
|
||||
transport_poll_interval_secs: 2,
|
||||
transport_poll_timeout_secs: 300,
|
||||
};
|
||||
let _auto_handle = herocoordinator::router::start_router_auto(service_for_router, cfg);
|
||||
}
|
||||
|
||||
// Build RPC modules for both servers
|
||||
let http_module = herocoordinator::rpc::build_module(state.clone());
|
||||
let ws_module = herocoordinator::rpc::build_module(state.clone());
|
||||
|
||||
println!(
|
||||
"Starting JSON-RPC servers: HTTP http://{} | WS ws://{} | redis_addr={}",
|
||||
http_addr, ws_addr, cli.redis_addr
|
||||
);
|
||||
info!(%http_addr, %ws_addr, redis_addr=%cli.redis_addr, "Starting JSON-RPC servers");
|
||||
|
||||
// Start servers
|
||||
let _http_handle = herocoordinator::rpc::start_http(http_addr, http_module)
|
||||
@@ -107,7 +129,7 @@ async fn main() {
|
||||
|
||||
// Wait for Ctrl+C to terminate
|
||||
if let Err(e) = tokio::signal::ctrl_c().await {
|
||||
eprintln!("Failed to listen for shutdown signal: {e}");
|
||||
error!(error=%e, "Failed to listen for shutdown signal");
|
||||
}
|
||||
println!("Shutdown signal received, exiting.");
|
||||
info!("Shutdown signal received, exiting.");
|
||||
}
|
||||
|
@@ -10,6 +10,6 @@ pub use actor::Actor;
|
||||
pub use context::Context;
|
||||
pub use flow::{Flow, FlowStatus};
|
||||
pub use job::{Job, JobStatus};
|
||||
pub use message::{Message, MessageFormatType, MessageStatus, MessageType};
|
||||
pub use message::{Message, MessageFormatType, MessageStatus, MessageType, TransportStatus};
|
||||
pub use runner::Runner;
|
||||
pub use script_type::ScriptType;
|
||||
|
@@ -22,6 +22,12 @@ pub struct Message {
|
||||
pub timeout_ack: u32,
|
||||
/// Seconds for the receiver to send us a reply
|
||||
pub timeout_result: u32,
|
||||
|
||||
/// Outbound transport id returned by Mycelium on push
|
||||
pub transport_id: Option<String>,
|
||||
/// Latest transport status as reported by Mycelium
|
||||
pub transport_status: Option<TransportStatus>,
|
||||
|
||||
pub job: Vec<Job>,
|
||||
pub logs: Vec<Log>,
|
||||
pub created_at: Timestamp,
|
||||
@@ -44,6 +50,15 @@ pub enum MessageStatus {
|
||||
Processed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum TransportStatus {
|
||||
Queued,
|
||||
Sent,
|
||||
Delivered,
|
||||
Read,
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub enum MessageFormatType {
|
||||
Html,
|
||||
|
@@ -2,6 +2,7 @@ use std::net::IpAddr;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::models::ScriptType;
|
||||
use crate::time::Timestamp;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone)]
|
||||
@@ -13,6 +14,8 @@ pub struct Runner {
|
||||
pub address: IpAddr,
|
||||
/// Needs to be set by the runner, usually `runner<runnerid`
|
||||
pub topic: String,
|
||||
/// The script type this runner can execute; used for routing
|
||||
pub script_type: ScriptType,
|
||||
/// If this is true, the runner also listens on a local redis queue
|
||||
pub local: bool,
|
||||
pub created_at: Timestamp,
|
||||
|
@@ -1,6 +1,6 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
|
||||
pub enum ScriptType {
|
||||
Osis,
|
||||
Sal,
|
||||
|
475
src/router.rs
Normal file
475
src/router.rs
Normal file
@@ -0,0 +1,475 @@
|
||||
use std::{collections::HashSet, sync::Arc};
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use tokio::sync::Semaphore;
|
||||
|
||||
use crate::{
|
||||
clients::{Destination, MyceliumClient, SupervisorClient},
|
||||
models::{Job, JobStatus, Message, MessageStatus, ScriptType, TransportStatus},
|
||||
service::AppService,
|
||||
};
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RouterConfig {
|
||||
pub context_ids: Vec<u32>,
|
||||
pub concurrency: usize,
|
||||
pub base_url: String, // e.g. http://127.0.0.1:8990
|
||||
pub topic: String, // e.g. "supervisor.rpc"
|
||||
// Transport status polling configuration
|
||||
pub transport_poll_interval_secs: u64, // e.g. 2
|
||||
pub transport_poll_timeout_secs: u64, // e.g. 300 (5 minutes)
|
||||
}
|
||||
|
||||
/// Start background router loops, one per context.
|
||||
/// Each loop:
|
||||
/// - BRPOP msg_out with 1s timeout
|
||||
/// - Loads the Message by key, selects a Runner by script_type
|
||||
/// - Sends supervisor JSON-RPC via Mycelium
|
||||
/// - On success: Message.status = Acknowledged
|
||||
/// - On error: Message.status = Error and append a log
|
||||
pub fn start_router(service: AppService, cfg: RouterConfig) -> Vec<tokio::task::JoinHandle<()>> {
|
||||
let mut handles = Vec::new();
|
||||
for ctx_id in cfg.context_ids.clone() {
|
||||
let service_cloned = service.clone();
|
||||
let cfg_cloned = cfg.clone();
|
||||
let handle = tokio::spawn(async move {
|
||||
let sem = Arc::new(Semaphore::new(cfg_cloned.concurrency));
|
||||
|
||||
// Create a shared Mycelium client for this context loop (retry until available)
|
||||
let mycelium = loop {
|
||||
match MyceliumClient::new(cfg_cloned.base_url.clone()) {
|
||||
Ok(c) => break Arc::new(c),
|
||||
Err(e) => {
|
||||
error!(context_id=ctx_id, error=%e, "MyceliumClient init error");
|
||||
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
loop {
|
||||
// Pop next message key (blocking with timeout)
|
||||
match service_cloned.brpop_msg_out(ctx_id, 1).await {
|
||||
Ok(Some(key)) => {
|
||||
let permit = {
|
||||
// acquire a concurrency permit (non-fair is fine)
|
||||
let sem = sem.clone();
|
||||
// if semaphore is exhausted, await until a slot becomes available
|
||||
match sem.acquire_owned().await {
|
||||
Ok(p) => p,
|
||||
Err(_) => {
|
||||
// Semaphore closed; exit loop
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
let service_task = service_cloned.clone();
|
||||
let cfg_task = cfg_cloned.clone();
|
||||
tokio::spawn({
|
||||
let mycelium = mycelium.clone();
|
||||
async move {
|
||||
// Ensure permit is dropped at end of task
|
||||
let _permit = permit;
|
||||
if let Err(e) =
|
||||
deliver_one(&service_task, &cfg_task, ctx_id, &key, mycelium)
|
||||
.await
|
||||
{
|
||||
error!(context_id=ctx_id, key=%key, error=%e, "Delivery error");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(None) => {
|
||||
// timeout: just tick
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
error!(context_id=ctx_id, error=%e, "BRPOP error");
|
||||
// small backoff to avoid busy-loop on persistent errors
|
||||
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
handles.push(handle);
|
||||
}
|
||||
handles
|
||||
}
|
||||
|
||||
async fn deliver_one(
|
||||
service: &AppService,
|
||||
cfg: &RouterConfig,
|
||||
context_id: u32,
|
||||
msg_key: &str,
|
||||
mycelium: Arc<MyceliumClient>,
|
||||
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
|
||||
// Parse "message:{caller_id}:{id}"
|
||||
let (caller_id, id) = parse_message_key(msg_key)
|
||||
.ok_or_else(|| format!("invalid message key format: {}", msg_key))?;
|
||||
|
||||
// Load message
|
||||
let msg: Message = service.load_message(context_id, caller_id, id).await?;
|
||||
// Embedded job id (if any)
|
||||
let job_id_opt: Option<u32> = msg.job.first().map(|j| j.id);
|
||||
|
||||
// Determine routing script_type
|
||||
let desired: ScriptType = determine_script_type(&msg);
|
||||
|
||||
// Discover runners and select a matching one
|
||||
let runners = service.scan_runners(context_id).await?;
|
||||
let Some(runner) = runners.into_iter().find(|r| r.script_type == desired) else {
|
||||
let log = format!(
|
||||
"No runner with script_type {:?} available in context {} for message {}",
|
||||
desired, context_id, msg_key
|
||||
);
|
||||
let _ = service
|
||||
.append_message_logs(context_id, caller_id, id, vec![log.clone()])
|
||||
.await;
|
||||
let _ = service
|
||||
.update_message_status(context_id, caller_id, id, MessageStatus::Error)
|
||||
.await;
|
||||
return Err(log.into());
|
||||
};
|
||||
|
||||
// Build SupervisorClient
|
||||
let dest = if !runner.pubkey.trim().is_empty() {
|
||||
Destination::Pk(runner.pubkey.clone())
|
||||
} else {
|
||||
Destination::Ip(runner.address)
|
||||
};
|
||||
// Keep clones for poller usage
|
||||
let dest_for_poller = dest.clone();
|
||||
let topic_for_poller = cfg.topic.clone();
|
||||
let client = SupervisorClient::new_with_client(
|
||||
mycelium.clone(),
|
||||
dest.clone(),
|
||||
cfg.topic.clone(),
|
||||
None, // secret
|
||||
);
|
||||
|
||||
// Build supervisor method and params from Message
|
||||
let method = msg.message.clone();
|
||||
let params = build_params(&msg)?;
|
||||
|
||||
// Send
|
||||
let out_id = client.call(&method, params).await?;
|
||||
|
||||
// Store transport id and initial Sent status
|
||||
let _ = service
|
||||
.update_message_transport(
|
||||
context_id,
|
||||
caller_id,
|
||||
id,
|
||||
Some(out_id.clone()),
|
||||
Some(TransportStatus::Sent),
|
||||
)
|
||||
.await;
|
||||
|
||||
// Mark as acknowledged on success
|
||||
service
|
||||
.update_message_status(context_id, caller_id, id, MessageStatus::Acknowledged)
|
||||
.await?;
|
||||
|
||||
// Spawn transport-status poller
|
||||
{
|
||||
let service_poll = service.clone();
|
||||
let poll_interval = std::time::Duration::from_secs(cfg.transport_poll_interval_secs);
|
||||
let poll_timeout = std::time::Duration::from_secs(cfg.transport_poll_timeout_secs);
|
||||
let out_id_cloned = out_id.clone();
|
||||
let mycelium = mycelium.clone();
|
||||
// Determine reply timeout for supervisor job.result: prefer message.timeout_result, fallback to router config timeout
|
||||
let job_result_reply_timeout: u64 = if msg.timeout_result > 0 {
|
||||
msg.timeout_result as u64
|
||||
} else {
|
||||
cfg.transport_poll_timeout_secs
|
||||
};
|
||||
|
||||
tokio::spawn(async move {
|
||||
let start = std::time::Instant::now();
|
||||
let client = mycelium;
|
||||
|
||||
// Supervisor call context captured for sync status checks
|
||||
let sup_dest = dest_for_poller;
|
||||
let sup_topic = topic_for_poller;
|
||||
let job_id_opt = job_id_opt;
|
||||
|
||||
let mut last_status: Option<TransportStatus> = Some(TransportStatus::Sent);
|
||||
|
||||
loop {
|
||||
if start.elapsed() >= poll_timeout {
|
||||
let _ = service_poll
|
||||
.append_message_logs(
|
||||
context_id,
|
||||
caller_id,
|
||||
id,
|
||||
vec!["Transport-status polling timed out".to_string()],
|
||||
)
|
||||
.await;
|
||||
// leave last known status; do not override
|
||||
break;
|
||||
}
|
||||
|
||||
match client.message_status(&out_id_cloned).await {
|
||||
Ok(s) => {
|
||||
if last_status.as_ref() != Some(&s) {
|
||||
let _ = service_poll
|
||||
.update_message_transport(
|
||||
context_id,
|
||||
caller_id,
|
||||
id,
|
||||
None,
|
||||
Some(s.clone()),
|
||||
)
|
||||
.await;
|
||||
last_status = Some(s.clone());
|
||||
}
|
||||
|
||||
// Stop on terminal states
|
||||
if matches!(s, TransportStatus::Delivered | TransportStatus::Read) {
|
||||
// On Read, fetch supervisor job.status and update local job/message if terminal
|
||||
if matches!(s, TransportStatus::Read) {
|
||||
if let Some(job_id) = job_id_opt {
|
||||
let sup = SupervisorClient::new_with_client(
|
||||
client.clone(),
|
||||
sup_dest.clone(),
|
||||
sup_topic.clone(),
|
||||
None,
|
||||
);
|
||||
match sup.job_status_sync(job_id.to_string(), 10).await {
|
||||
Ok(remote_status) => {
|
||||
if let Some((mapped, terminal)) =
|
||||
map_supervisor_job_status(&remote_status)
|
||||
{
|
||||
if terminal {
|
||||
let _ = service_poll
|
||||
.update_job_status_unchecked(
|
||||
context_id,
|
||||
caller_id,
|
||||
job_id,
|
||||
mapped.clone(),
|
||||
)
|
||||
.await;
|
||||
|
||||
// After terminal status, fetch supervisor job.result and store into Job.result
|
||||
let sup = SupervisorClient::new_with_client(
|
||||
client.clone(),
|
||||
sup_dest.clone(),
|
||||
sup_topic.clone(),
|
||||
None,
|
||||
);
|
||||
match sup
|
||||
.job_result_sync(
|
||||
job_id.to_string(),
|
||||
job_result_reply_timeout,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(result_map) => {
|
||||
// Persist the result into the Job.result map (merge)
|
||||
let _ = service_poll
|
||||
.update_job_result_merge_unchecked(
|
||||
context_id,
|
||||
caller_id,
|
||||
job_id,
|
||||
result_map.clone(),
|
||||
)
|
||||
.await;
|
||||
// Log which key was stored (success or error)
|
||||
let key = result_map
|
||||
.keys()
|
||||
.next()
|
||||
.cloned()
|
||||
.unwrap_or_else(|| {
|
||||
"unknown".to_string()
|
||||
});
|
||||
let _ = service_poll
|
||||
.append_message_logs(
|
||||
context_id,
|
||||
caller_id,
|
||||
id,
|
||||
vec![format!(
|
||||
"Stored supervisor job.result for job {} ({})",
|
||||
job_id, key
|
||||
)],
|
||||
)
|
||||
.await;
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = service_poll
|
||||
.append_message_logs(
|
||||
context_id,
|
||||
caller_id,
|
||||
id,
|
||||
vec![format!(
|
||||
"job.result fetch error for job {}: {}",
|
||||
job_id, e
|
||||
)],
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
// Mark message as processed
|
||||
let _ = service_poll
|
||||
.update_message_status(
|
||||
context_id,
|
||||
caller_id,
|
||||
id,
|
||||
MessageStatus::Processed,
|
||||
)
|
||||
.await;
|
||||
let _ = service_poll
|
||||
.append_message_logs(
|
||||
context_id,
|
||||
caller_id,
|
||||
id,
|
||||
vec![format!(
|
||||
"Supervisor job.status for job {} -> {} (mapped to {:?})",
|
||||
job_id, remote_status, mapped
|
||||
)],
|
||||
)
|
||||
.await;
|
||||
}
|
||||
} else {
|
||||
let _ = service_poll
|
||||
.append_message_logs(
|
||||
context_id,
|
||||
caller_id,
|
||||
id,
|
||||
vec![format!(
|
||||
"Unknown supervisor status '{}' for job {}",
|
||||
remote_status, job_id
|
||||
)],
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
let _ = service_poll
|
||||
.append_message_logs(
|
||||
context_id,
|
||||
caller_id,
|
||||
id,
|
||||
vec![format!("job.status sync error: {}", e)],
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
if matches!(s, TransportStatus::Failed) {
|
||||
let _ = service_poll
|
||||
.append_message_logs(
|
||||
context_id,
|
||||
caller_id,
|
||||
id,
|
||||
vec![format!(
|
||||
"Transport failed for outbound id {out_id_cloned}"
|
||||
)],
|
||||
)
|
||||
.await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
// Log and continue polling
|
||||
let _ = service_poll
|
||||
.append_message_logs(
|
||||
context_id,
|
||||
caller_id,
|
||||
id,
|
||||
vec![format!("messageStatus query error: {e}")],
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
tokio::time::sleep(poll_interval).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn determine_script_type(msg: &Message) -> ScriptType {
|
||||
// Prefer embedded job's script_type if available, else fallback to message.message_type
|
||||
match msg.job.first() {
|
||||
Some(j) => j.script_type.clone(),
|
||||
None => msg.message_type.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn build_params(msg: &Message) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
|
||||
// Minimal mapping:
|
||||
// - "job.run" with exactly one embedded job: [{ "job": <job> }]
|
||||
// - otherwise: []
|
||||
if msg.message == "job.run"
|
||||
&& let Some(j) = msg.job.first()
|
||||
{
|
||||
let jv = job_to_json(j)?;
|
||||
return Ok(json!([ { "job": jv } ]));
|
||||
}
|
||||
|
||||
Ok(json!([]))
|
||||
}
|
||||
|
||||
fn job_to_json(job: &Job) -> Result<Value, Box<dyn std::error::Error + Send + Sync>> {
|
||||
Ok(serde_json::to_value(job)?)
|
||||
}
|
||||
|
||||
fn parse_message_key(s: &str) -> Option<(u32, u32)> {
|
||||
// Expect "message:{caller_id}:{id}"
|
||||
let mut it = s.split(':');
|
||||
match (it.next(), it.next(), it.next(), it.next()) {
|
||||
(Some("message"), Some(caller), Some(id), None) => {
|
||||
let caller_id = caller.parse::<u32>().ok()?;
|
||||
let msg_id = id.parse::<u32>().ok()?;
|
||||
Some((caller_id, msg_id))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Map supervisor job.status -> (local JobStatus, terminal)
|
||||
fn map_supervisor_job_status(s: &str) -> Option<(JobStatus, bool)> {
|
||||
match s {
|
||||
"created" | "queued" => Some((JobStatus::Dispatched, false)),
|
||||
"running" => Some((JobStatus::Started, false)),
|
||||
"completed" => Some((JobStatus::Finished, true)),
|
||||
"failed" | "timeout" => Some((JobStatus::Error, true)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Auto-discover contexts periodically and ensure a router loop exists for each.
|
||||
/// Returns a JoinHandle of the discovery task (router loops are detached).
|
||||
pub fn start_router_auto(service: AppService, cfg: RouterConfig) -> tokio::task::JoinHandle<()> {
|
||||
tokio::spawn(async move {
|
||||
let mut active: HashSet<u32> = HashSet::new();
|
||||
loop {
|
||||
match service.list_context_ids().await {
|
||||
Ok(ids) => {
|
||||
for ctx_id in ids {
|
||||
if !active.contains(&ctx_id) {
|
||||
// Spawn a loop for this new context
|
||||
let cfg_ctx = RouterConfig {
|
||||
context_ids: vec![ctx_id],
|
||||
..cfg.clone()
|
||||
};
|
||||
let _ = start_router(service.clone(), cfg_ctx);
|
||||
active.insert(ctx_id);
|
||||
info!(context_id = ctx_id, "Started loop for context");
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
error!(error=%e, "list_context_ids error");
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
|
||||
}
|
||||
})
|
||||
}
|
45
src/rpc.rs
45
src/rpc.rs
@@ -22,6 +22,9 @@ use crate::{
|
||||
time::current_timestamp,
|
||||
};
|
||||
|
||||
/// The OpenRPC specification for the HeroCoordinator JSON-RPC API
|
||||
const OPENRPC_SPEC: &str = include_str!("../specs/openrpc.json");
|
||||
|
||||
pub struct AppState {
|
||||
pub service: AppService,
|
||||
}
|
||||
@@ -144,6 +147,8 @@ pub struct RunnerCreate {
|
||||
pub pubkey: String,
|
||||
pub address: IpAddr,
|
||||
pub topic: String,
|
||||
/// The script type this runner executes (used for routing)
|
||||
pub script_type: ScriptType,
|
||||
pub local: bool,
|
||||
}
|
||||
impl RunnerCreate {
|
||||
@@ -155,6 +160,7 @@ impl RunnerCreate {
|
||||
pubkey,
|
||||
address,
|
||||
topic,
|
||||
script_type,
|
||||
local,
|
||||
} = self;
|
||||
|
||||
@@ -163,6 +169,7 @@ impl RunnerCreate {
|
||||
pubkey,
|
||||
address,
|
||||
topic,
|
||||
script_type,
|
||||
local,
|
||||
created_at: ts,
|
||||
updated_at: ts,
|
||||
@@ -295,6 +302,8 @@ impl MessageCreate {
|
||||
timeout,
|
||||
timeout_ack,
|
||||
timeout_result,
|
||||
transport_id: None,
|
||||
transport_status: None,
|
||||
job: job.into_iter().map(JobCreate::into_domain).collect(),
|
||||
logs: Vec::new(),
|
||||
created_at: ts,
|
||||
@@ -306,12 +315,10 @@ impl MessageCreate {
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ActorCreateParams {
|
||||
pub context_id: u32,
|
||||
pub actor: ActorCreate,
|
||||
}
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct ActorLoadParams {
|
||||
pub context_id: u32,
|
||||
pub id: u32,
|
||||
}
|
||||
|
||||
@@ -388,7 +395,7 @@ pub fn build_module(state: Arc<AppState>) -> RpcModule<()> {
|
||||
let actor = p.actor.into_domain().map_err(invalid_params_err)?;
|
||||
let actor = state
|
||||
.service
|
||||
.create_actor(p.context_id, actor)
|
||||
.create_actor(actor)
|
||||
.await
|
||||
.map_err(storage_err)?;
|
||||
Ok::<_, ErrorObjectOwned>(actor)
|
||||
@@ -403,11 +410,7 @@ pub fn build_module(state: Arc<AppState>) -> RpcModule<()> {
|
||||
let state = state.clone();
|
||||
async move {
|
||||
let p: ActorLoadParams = params.parse().map_err(invalid_params_err)?;
|
||||
let actor = state
|
||||
.service
|
||||
.load_actor(p.context_id, p.id)
|
||||
.await
|
||||
.map_err(storage_err)?;
|
||||
let actor = state.service.load_actor(p.id).await.map_err(storage_err)?;
|
||||
Ok::<_, ErrorObjectOwned>(actor)
|
||||
}
|
||||
})
|
||||
@@ -541,6 +544,23 @@ pub fn build_module(state: Arc<AppState>) -> RpcModule<()> {
|
||||
})
|
||||
.expect("register flow.dag");
|
||||
}
|
||||
{
|
||||
let state = state.clone();
|
||||
module
|
||||
.register_async_method("flow.start", move |params, _caller, _ctx| {
|
||||
let state = state.clone();
|
||||
async move {
|
||||
let p: FlowLoadParams = params.parse().map_err(invalid_params_err)?;
|
||||
let started: bool = state
|
||||
.service
|
||||
.flow_start(p.context_id, p.id)
|
||||
.await
|
||||
.map_err(storage_err)?;
|
||||
Ok::<_, ErrorObjectOwned>(started)
|
||||
}
|
||||
})
|
||||
.expect("register flow.start");
|
||||
}
|
||||
|
||||
// Job
|
||||
{
|
||||
@@ -615,6 +635,15 @@ pub fn build_module(state: Arc<AppState>) -> RpcModule<()> {
|
||||
})
|
||||
.expect("register message.load");
|
||||
}
|
||||
{
|
||||
module
|
||||
.register_async_method("rpc.discover", move |_params, _caller, _ctx| async move {
|
||||
let spec = serde_json::from_str::<serde_json::Value>(OPENRPC_SPEC)
|
||||
.expect("Failed to parse OpenRPC spec");
|
||||
Ok::<_, ErrorObjectOwned>(spec)
|
||||
})
|
||||
.expect("register rpc.discover");
|
||||
}
|
||||
|
||||
module
|
||||
}
|
||||
|
357
src/service.rs
357
src/service.rs
@@ -1,12 +1,16 @@
|
||||
use crate::dag::{DagResult, FlowDag, build_flow_dag};
|
||||
use crate::dag::{DagError, DagResult, FlowDag, build_flow_dag};
|
||||
use crate::models::{
|
||||
Actor, Context, Flow, FlowStatus, Job, JobStatus, Message, MessageStatus, Runner,
|
||||
Actor, Context, Flow, FlowStatus, Job, JobStatus, Message, MessageFormatType, MessageStatus,
|
||||
Runner, TransportStatus,
|
||||
};
|
||||
use crate::storage::RedisDriver;
|
||||
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::time::{Duration, sleep};
|
||||
|
||||
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
|
||||
|
||||
@@ -112,10 +116,10 @@ fn contains_key_not_found(e: &BoxError) -> bool {
|
||||
fn has_duplicate_u32s(list: &Vec<Value>) -> bool {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for it in list {
|
||||
if let Some(x) = it.as_u64()
|
||||
&& !seen.insert(x)
|
||||
{
|
||||
return true;
|
||||
if let Some(x) = it.as_u64() {
|
||||
if !seen.insert(x) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
@@ -153,7 +157,7 @@ fn validate_context(ctx: &Context) -> Result<(), BoxError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_actor(_context_id: u32, actor: &Actor) -> Result<(), BoxError> {
|
||||
fn validate_actor(actor: &Actor) -> Result<(), BoxError> {
|
||||
let v = as_json(actor)?;
|
||||
let id = json_get_u32(&v, "id")?;
|
||||
if id == 0 {
|
||||
@@ -305,13 +309,18 @@ fn validate_message(context_id: u32, msg: &Message) -> Result<(), BoxError> {
|
||||
// Service API
|
||||
// -----------------------------
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppService {
|
||||
redis: RedisDriver,
|
||||
redis: Arc<RedisDriver>,
|
||||
schedulers: Arc<Mutex<HashSet<(u32, u32)>>>,
|
||||
}
|
||||
|
||||
impl AppService {
|
||||
pub fn new(redis: RedisDriver) -> Self {
|
||||
Self { redis }
|
||||
Self {
|
||||
redis: Arc::new(redis),
|
||||
schedulers: Arc::new(Mutex::new(HashSet::new())),
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
@@ -335,17 +344,17 @@ impl AppService {
|
||||
// -----------------------------
|
||||
// Actor
|
||||
// -----------------------------
|
||||
pub async fn create_actor(&self, context_id: u32, actor: Actor) -> Result<Actor, BoxError> {
|
||||
validate_actor(context_id, &actor)?;
|
||||
pub async fn create_actor(&self, actor: Actor) -> Result<Actor, BoxError> {
|
||||
validate_actor(&actor)?;
|
||||
let v = as_json(&actor)?;
|
||||
let id = json_get_u32(&v, "id")?;
|
||||
self.ensure_actor_not_exists(context_id, id).await?;
|
||||
self.redis.save_actor(context_id, &actor).await?;
|
||||
self.ensure_actor_not_exists_global(id).await?;
|
||||
self.redis.save_actor_global(&actor).await?;
|
||||
Ok(actor)
|
||||
}
|
||||
|
||||
pub async fn load_actor(&self, context_id: u32, id: u32) -> Result<Actor, BoxError> {
|
||||
let actor = self.redis.load_actor(context_id, id).await?;
|
||||
pub async fn load_actor(&self, id: u32) -> Result<Actor, BoxError> {
|
||||
let actor = self.redis.load_actor_global(id).await?;
|
||||
Ok(actor)
|
||||
}
|
||||
|
||||
@@ -395,6 +404,220 @@ impl AppService {
|
||||
build_flow_dag(&self.redis, context_id, flow_id).await
|
||||
}
|
||||
|
||||
/// Start a background scheduler for a flow.
|
||||
/// - Ticks every 1 second.
|
||||
/// - Sets Flow status to Started immediately.
|
||||
/// - Dispatches jobs whose dependencies are Finished: creates a Message and LPUSHes its key into msg_out,
|
||||
/// and marks the job status to Dispatched.
|
||||
/// - When all jobs are Finished sets Flow to Finished; if any job is Error sets Flow to Error.
|
||||
/// Returns:
|
||||
/// - Ok(true) if a scheduler was started
|
||||
/// - Ok(false) if a scheduler was already running for this (context_id, flow_id)
|
||||
pub async fn flow_start(&self, context_id: u32, flow_id: u32) -> Result<bool, BoxError> {
|
||||
// Ensure flow exists (and load caller_id)
|
||||
let flow = self.redis.load_flow(context_id, flow_id).await?;
|
||||
let caller_id = flow.caller_id();
|
||||
|
||||
// Try to register this flow in the active scheduler set
|
||||
{
|
||||
let mut guard = self.schedulers.lock().await;
|
||||
if !guard.insert((context_id, flow_id)) {
|
||||
// Already running
|
||||
return Ok(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Clone resources for background task
|
||||
let redis = self.redis.clone();
|
||||
let schedulers = self.schedulers.clone();
|
||||
|
||||
// Set Flow status to Started
|
||||
let _ = redis
|
||||
.update_flow_status(context_id, flow_id, FlowStatus::Started)
|
||||
.await;
|
||||
|
||||
tokio::spawn(async move {
|
||||
// Background loop
|
||||
loop {
|
||||
// Load current flow; stop if missing
|
||||
let flow = match redis.load_flow(context_id, flow_id).await {
|
||||
Ok(f) => f,
|
||||
Err(_) => break,
|
||||
};
|
||||
|
||||
// Track aggregate state
|
||||
let mut all_finished = true;
|
||||
let mut any_error = false;
|
||||
|
||||
// Iterate jobs declared in the flow
|
||||
for jid in flow.jobs() {
|
||||
// Load job
|
||||
let job = match redis.load_job(context_id, caller_id, *jid).await {
|
||||
Ok(j) => j,
|
||||
Err(_) => {
|
||||
// If job is missing treat as error state for the flow and stop
|
||||
any_error = true;
|
||||
all_finished = false;
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
match job.status() {
|
||||
JobStatus::Finished => {
|
||||
// done
|
||||
}
|
||||
JobStatus::Error => {
|
||||
any_error = true;
|
||||
all_finished = false;
|
||||
}
|
||||
JobStatus::Dispatched | JobStatus::Started => {
|
||||
all_finished = false;
|
||||
}
|
||||
JobStatus::WaitingForPrerequisites => {
|
||||
all_finished = false;
|
||||
|
||||
// Check dependencies complete
|
||||
let mut deps_ok = true;
|
||||
for dep in job.depends() {
|
||||
match redis.load_job(context_id, caller_id, *dep).await {
|
||||
Ok(dj) => {
|
||||
if dj.status() != JobStatus::Finished {
|
||||
deps_ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
deps_ok = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if deps_ok {
|
||||
// Build Message embedding this job
|
||||
let ts = crate::time::current_timestamp();
|
||||
let msg_id: u32 = job.id(); // deterministic message id per job for now
|
||||
|
||||
let message = Message {
|
||||
id: msg_id,
|
||||
caller_id: job.caller_id(),
|
||||
context_id,
|
||||
message: "job.run".to_string(),
|
||||
message_type: job.script_type(),
|
||||
message_format_type: MessageFormatType::Text,
|
||||
timeout: job.timeout,
|
||||
timeout_ack: 10,
|
||||
timeout_result: job.timeout,
|
||||
transport_id: None,
|
||||
transport_status: None,
|
||||
job: vec![job.clone()],
|
||||
logs: Vec::new(),
|
||||
created_at: ts,
|
||||
updated_at: ts,
|
||||
status: MessageStatus::Dispatched,
|
||||
};
|
||||
|
||||
// Persist the message and enqueue it
|
||||
if redis.save_message(context_id, &message).await.is_ok() {
|
||||
let _ = redis
|
||||
.enqueue_msg_out(context_id, job.caller_id(), msg_id)
|
||||
.await;
|
||||
// Mark job as Dispatched
|
||||
let _ = redis
|
||||
.update_job_status(
|
||||
context_id,
|
||||
job.caller_id(),
|
||||
job.id(),
|
||||
JobStatus::Dispatched,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if any_error {
|
||||
let _ = redis
|
||||
.update_flow_status(context_id, flow_id, FlowStatus::Error)
|
||||
.await;
|
||||
break;
|
||||
}
|
||||
if all_finished {
|
||||
let _ = redis
|
||||
.update_flow_status(context_id, flow_id, FlowStatus::Finished)
|
||||
.await;
|
||||
break;
|
||||
}
|
||||
|
||||
sleep(Duration::from_secs(1)).await;
|
||||
}
|
||||
|
||||
// Remove from active schedulers set
|
||||
let mut guard = schedulers.lock().await;
|
||||
guard.remove(&(context_id, flow_id));
|
||||
});
|
||||
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Execute a flow: compute DAG, create Message entries for ready jobs, and enqueue their keys to msg_out.
|
||||
/// Returns the list of enqueued message keys ("message:{caller_id}:{id}") in deterministic order (by job id).
|
||||
pub async fn flow_execute(&self, context_id: u32, flow_id: u32) -> DagResult<Vec<String>> {
|
||||
let dag = build_flow_dag(&self.redis, context_id, flow_id).await?;
|
||||
let mut ready = dag.ready_jobs()?;
|
||||
ready.sort_unstable();
|
||||
|
||||
let mut queued: Vec<String> = Vec::with_capacity(ready.len());
|
||||
for jid in ready {
|
||||
// Load the concrete Job
|
||||
let job = self
|
||||
.redis
|
||||
.load_job(context_id, dag.caller_id, jid)
|
||||
.await
|
||||
.map_err(DagError::from)?;
|
||||
|
||||
// Build a Message that embeds this job
|
||||
let ts = crate::time::current_timestamp();
|
||||
let msg_id: u32 = job.id(); // deterministic; adjust strategy later if needed
|
||||
|
||||
let message = Message {
|
||||
id: msg_id,
|
||||
caller_id: job.caller_id(),
|
||||
context_id,
|
||||
message: "job.run".to_string(),
|
||||
message_type: job.script_type(), // uses ScriptType (matches model)
|
||||
message_format_type: MessageFormatType::Text,
|
||||
timeout: job.timeout,
|
||||
timeout_ack: 10,
|
||||
timeout_result: job.timeout,
|
||||
transport_id: None,
|
||||
transport_status: None,
|
||||
job: vec![job.clone()],
|
||||
logs: Vec::new(),
|
||||
created_at: ts,
|
||||
updated_at: ts,
|
||||
status: MessageStatus::Dispatched,
|
||||
};
|
||||
|
||||
// Persist the Message and enqueue its key to the outbound queue
|
||||
let _ = self
|
||||
.create_message(context_id, message)
|
||||
.await
|
||||
.map_err(DagError::from)?;
|
||||
|
||||
self.redis
|
||||
.enqueue_msg_out(context_id, job.caller_id(), msg_id)
|
||||
.await
|
||||
.map_err(DagError::from)?;
|
||||
|
||||
let key = format!("message:{}:{}", job.caller_id(), msg_id);
|
||||
queued.push(key);
|
||||
}
|
||||
|
||||
Ok(queued)
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Job
|
||||
// -----------------------------
|
||||
@@ -471,6 +694,48 @@ impl AppService {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
/// Bypass-permission variant to update a job status with transition validation.
|
||||
/// This skips the executor permission check but enforces the same state transition rules.
|
||||
pub async fn update_job_status_unchecked(
|
||||
&self,
|
||||
context_id: u32,
|
||||
caller_id: u32,
|
||||
id: u32,
|
||||
new_status: JobStatus,
|
||||
) -> Result<(), BoxError> {
|
||||
let job = self.redis.load_job(context_id, caller_id, id).await?;
|
||||
let current = job.status();
|
||||
|
||||
if new_status == current {
|
||||
// Idempotent: don't touch storage if no change
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let allowed = match current {
|
||||
JobStatus::Dispatched => matches!(
|
||||
new_status,
|
||||
JobStatus::WaitingForPrerequisites | JobStatus::Started | JobStatus::Error
|
||||
),
|
||||
JobStatus::WaitingForPrerequisites => {
|
||||
matches!(new_status, JobStatus::Started | JobStatus::Error)
|
||||
}
|
||||
JobStatus::Started => matches!(new_status, JobStatus::Finished | JobStatus::Error),
|
||||
JobStatus::Finished | JobStatus::Error => false,
|
||||
};
|
||||
|
||||
if !allowed {
|
||||
return Err(Box::new(InvalidJobStatusTransition {
|
||||
from: current,
|
||||
to: new_status,
|
||||
}));
|
||||
}
|
||||
|
||||
self.redis
|
||||
.update_job_status(context_id, caller_id, id, new_status)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Message
|
||||
@@ -598,6 +863,21 @@ impl AppService {
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn update_message_transport(
|
||||
&self,
|
||||
context_id: u32,
|
||||
caller_id: u32,
|
||||
id: u32,
|
||||
transport_id: Option<String>,
|
||||
transport_status: Option<TransportStatus>,
|
||||
) -> Result<(), BoxError> {
|
||||
// Ensure message exists (provides clearer error)
|
||||
let _ = self.redis.load_message(context_id, caller_id, id).await?;
|
||||
self.redis
|
||||
.update_message_transport(context_id, caller_id, id, transport_id, transport_status)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn update_flow_env_vars_merge(
|
||||
&self,
|
||||
context_id: u32,
|
||||
@@ -694,6 +974,22 @@ impl AppService {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Bypass-permission variant to merge into a job's result field.
|
||||
/// Intended for internal router/scheduler use where no actor identity is present.
|
||||
pub async fn update_job_result_merge_unchecked(
|
||||
&self,
|
||||
context_id: u32,
|
||||
caller_id: u32,
|
||||
job_id: u32,
|
||||
patch: HashMap<String, String>,
|
||||
) -> Result<(), BoxError> {
|
||||
// Ensure job exists, then write directly
|
||||
let _ = self.redis.load_job(context_id, caller_id, job_id).await?;
|
||||
self.redis
|
||||
.update_job_result_merge(context_id, caller_id, job_id, patch)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn append_message_logs(
|
||||
&self,
|
||||
context_id: u32,
|
||||
@@ -727,8 +1023,8 @@ impl AppService {
|
||||
}
|
||||
}
|
||||
|
||||
async fn ensure_actor_not_exists(&self, db: u32, id: u32) -> Result<(), BoxError> {
|
||||
match self.redis.load_actor(db, id).await {
|
||||
async fn ensure_actor_not_exists_global(&self, id: u32) -> Result<(), BoxError> {
|
||||
match self.redis.load_actor_global(id).await {
|
||||
Ok(_) => Err(Box::new(AlreadyExistsError {
|
||||
key: format!("actor:{}", id),
|
||||
})),
|
||||
@@ -848,3 +1144,28 @@ impl AppService {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Router/helper wrappers exposed on AppService so background tasks don't need direct Redis access.
|
||||
impl AppService {
|
||||
/// Block-pop from the per-context msg_out queue with a timeout (seconds).
|
||||
/// Returns Some(message_key) like "message:{caller_id}:{id}" or None on timeout.
|
||||
pub async fn brpop_msg_out(
|
||||
&self,
|
||||
context_id: u32,
|
||||
timeout_secs: usize,
|
||||
) -> Result<Option<String>, BoxError> {
|
||||
self.redis.brpop_msg_out(context_id, timeout_secs).await
|
||||
}
|
||||
|
||||
/// Scan all runner:* in the given context and return deserialized Runner entries.
|
||||
pub async fn scan_runners(&self, context_id: u32) -> Result<Vec<Runner>, BoxError> {
|
||||
self.redis.scan_runners(context_id).await
|
||||
}
|
||||
}
|
||||
|
||||
/// Auto-discovery helpers for contexts (wrappers over RedisDriver)
|
||||
impl AppService {
|
||||
pub async fn list_context_ids(&self) -> Result<Vec<u32>, BoxError> {
|
||||
self.redis.list_context_ids().await
|
||||
}
|
||||
}
|
||||
|
@@ -1,4 +1,3 @@
|
||||
|
||||
pub mod redis;
|
||||
|
||||
pub use redis::RedisDriver;
|
||||
|
@@ -8,7 +8,9 @@ use tokio::sync::Mutex;
|
||||
|
||||
use crate::models::{
|
||||
Actor, Context, Flow, FlowStatus, Job, JobStatus, Message, MessageStatus, Runner,
|
||||
TransportStatus,
|
||||
};
|
||||
use tracing::{debug, error, info, trace, warn};
|
||||
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
|
||||
|
||||
@@ -52,8 +54,14 @@ impl RedisDriver {
|
||||
|
||||
// Slow path: create a new manager and cache it
|
||||
let url = format!("{}/{}", self.base_addr.trim_end_matches('/'), db);
|
||||
let client = redis::Client::open(url.as_str())?;
|
||||
let cm = client.get_connection_manager().await?;
|
||||
let client = redis::Client::open(url.as_str()).map_err(|e| {
|
||||
error!(%url, db=%db, error=%e, "Redis client open failed");
|
||||
e
|
||||
})?;
|
||||
let cm = client.get_connection_manager().await.map_err(|e| {
|
||||
error!(%url, db=%db, error=%e, "Redis connection manager init failed");
|
||||
e
|
||||
})?;
|
||||
|
||||
let mut guard = self.managers.lock().await;
|
||||
let entry = guard.entry(db).or_insert(cm);
|
||||
@@ -104,21 +112,37 @@ impl RedisDriver {
|
||||
|
||||
async fn hset_model<T: Serialize>(&self, db: u32, key: &str, model: &T) -> Result<()> {
|
||||
let mut cm = self.manager_for_db(db).await?;
|
||||
let pairs = Self::struct_to_hset_pairs(model)?;
|
||||
let pairs = Self::struct_to_hset_pairs(model).map_err(|e| {
|
||||
error!(db=%db, key=%key, error=%e, "Serialize model to HSET pairs failed");
|
||||
e
|
||||
})?;
|
||||
// Ensure no stale fields
|
||||
let _: u64 = cm.del(key).await.unwrap_or(0);
|
||||
let del_res: redis::RedisResult<u64> = cm.del(key).await;
|
||||
if let Err(e) = del_res {
|
||||
warn!(db=%db, key=%key, error=%e, "DEL before HSET failed");
|
||||
}
|
||||
// Write all fields
|
||||
let _: usize = cm.hset_multiple(key, &pairs).await?;
|
||||
let _: () = cm.hset_multiple(key, &pairs).await.map_err(|e| {
|
||||
error!(db=%db, key=%key, error=%e, "HSET multiple failed");
|
||||
e
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn hget_model<T: DeserializeOwned>(&self, db: u32, key: &str) -> Result<T> {
|
||||
let mut cm = self.manager_for_db(db).await?;
|
||||
let map: StdHashMap<String, String> = cm.hgetall(key).await?;
|
||||
let map: StdHashMap<String, String> = cm.hgetall(key).await.map_err(|e| {
|
||||
error!(db=%db, key=%key, error=%e, "HGETALL failed");
|
||||
e
|
||||
})?;
|
||||
if map.is_empty() {
|
||||
// NotFound is expected in some flows; don't log as error
|
||||
return Err(format!("Key not found: {}", key).into());
|
||||
}
|
||||
Self::hmap_to_struct(map)
|
||||
Self::hmap_to_struct(map).map_err(|e| {
|
||||
error!(db=%db, key=%key, error=%e, "Deserialize model from HGETALL failed");
|
||||
e
|
||||
})
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
@@ -163,7 +187,11 @@ impl RedisDriver {
|
||||
.and_then(|v| v.as_u64())
|
||||
.ok_or("Context.id missing or not a number")? as u32;
|
||||
let key = Self::context_key(id);
|
||||
self.hset_model(id, &key, ctx).await
|
||||
// Write the context hash in its own DB
|
||||
self.hset_model(id, &key, ctx).await?;
|
||||
// Register this context id in the global registry (DB 0)
|
||||
let _ = self.register_context_id(id).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Load a Context from its own DB (db index = id)
|
||||
@@ -192,6 +220,22 @@ impl RedisDriver {
|
||||
let key = Self::actor_key(id);
|
||||
self.hget_model(db, &key).await
|
||||
}
|
||||
/// Save an Actor globally in DB 0 (Actor is context-independent)
|
||||
pub async fn save_actor_global(&self, actor: &Actor) -> Result<()> {
|
||||
let json = serde_json::to_value(actor)?;
|
||||
let id = json
|
||||
.get("id")
|
||||
.and_then(|v| v.as_u64())
|
||||
.ok_or("Actor.id missing or not a number")? as u32;
|
||||
let key = Self::actor_key(id);
|
||||
self.hset_model(0, &key, actor).await
|
||||
}
|
||||
|
||||
/// Load an Actor globally from DB 0 by id
|
||||
pub async fn load_actor_global(&self, id: u32) -> Result<Actor> {
|
||||
let key = Self::actor_key(id);
|
||||
self.hget_model(0, &key).await
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Runner
|
||||
@@ -279,7 +323,10 @@ impl RedisDriver {
|
||||
("status".to_string(), status_str),
|
||||
("updated_at".to_string(), ts.to_string()),
|
||||
];
|
||||
let _: usize = cm.hset_multiple(key, &pairs).await?;
|
||||
let _: usize = cm.hset_multiple(&key, &pairs).await.map_err(|e| {
|
||||
error!(db=%db, key=%key, error=%e, "HSET update_job_status failed");
|
||||
e
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -325,7 +372,10 @@ impl RedisDriver {
|
||||
("status".to_string(), status_str),
|
||||
("updated_at".to_string(), ts.to_string()),
|
||||
];
|
||||
let _: usize = cm.hset_multiple(key, &pairs).await?;
|
||||
let _: usize = cm.hset_multiple(&key, &pairs).await.map_err(|e| {
|
||||
error!(db=%db, key=%key, error=%e, "HSET update_flow_status failed");
|
||||
e
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -350,7 +400,47 @@ impl RedisDriver {
|
||||
("status".to_string(), status_str),
|
||||
("updated_at".to_string(), ts.to_string()),
|
||||
];
|
||||
let _: usize = cm.hset_multiple(key, &pairs).await?;
|
||||
let _: usize = cm.hset_multiple(&key, &pairs).await.map_err(|e| {
|
||||
error!(db=%db, key=%key, error=%e, "HSET update_message_status failed");
|
||||
e
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Message: update transport_id / transport_status (optionally) and bump updated_at
|
||||
pub async fn update_message_transport(
|
||||
&self,
|
||||
db: u32,
|
||||
caller_id: u32,
|
||||
id: u32,
|
||||
transport_id: Option<String>,
|
||||
transport_status: Option<TransportStatus>,
|
||||
) -> Result<()> {
|
||||
let mut cm = self.manager_for_db(db).await?;
|
||||
let key = Self::message_key(caller_id, id);
|
||||
|
||||
let mut pairs: Vec<(String, String)> = Vec::new();
|
||||
|
||||
if let Some(tid) = transport_id {
|
||||
pairs.push(("transport_id".to_string(), tid));
|
||||
}
|
||||
|
||||
if let Some(ts_status) = transport_status {
|
||||
let status_str = match serde_json::to_value(&ts_status)? {
|
||||
Value::String(s) => s,
|
||||
v => v.to_string(),
|
||||
};
|
||||
pairs.push(("transport_status".to_string(), status_str));
|
||||
}
|
||||
|
||||
// Always bump updated_at
|
||||
let ts = crate::time::current_timestamp();
|
||||
pairs.push(("updated_at".to_string(), ts.to_string()));
|
||||
|
||||
let _: usize = cm.hset_multiple(&key, &pairs).await.map_err(|e| {
|
||||
error!(db=%db, key=%key, error=%e, "HSET update_message_transport failed");
|
||||
e
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -383,7 +473,10 @@ impl RedisDriver {
|
||||
("env_vars".to_string(), env_vars_str),
|
||||
("updated_at".to_string(), ts.to_string()),
|
||||
];
|
||||
let _: usize = cm.hset_multiple(key, &pairs).await?;
|
||||
let _: usize = cm.hset_multiple(&key, &pairs).await.map_err(|e| {
|
||||
error!(db=%db, key=%key, error=%e, "HSET update_flow_env_vars_merge failed");
|
||||
e
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -416,7 +509,10 @@ impl RedisDriver {
|
||||
("result".to_string(), result_str),
|
||||
("updated_at".to_string(), ts.to_string()),
|
||||
];
|
||||
let _: usize = cm.hset_multiple(key, &pairs).await?;
|
||||
let _: usize = cm.hset_multiple(&key, &pairs).await.map_err(|e| {
|
||||
error!(db=%db, key=%key, error=%e, "HSET update_flow_result_merge failed");
|
||||
e
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -450,7 +546,10 @@ impl RedisDriver {
|
||||
("env_vars".to_string(), env_vars_str),
|
||||
("updated_at".to_string(), ts.to_string()),
|
||||
];
|
||||
let _: usize = cm.hset_multiple(key, &pairs).await?;
|
||||
let _: usize = cm.hset_multiple(&key, &pairs).await.map_err(|e| {
|
||||
error!(db=%db, key=%key, error=%e, "HSET update_job_env_vars_merge failed");
|
||||
e
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -484,7 +583,10 @@ impl RedisDriver {
|
||||
("result".to_string(), result_str),
|
||||
("updated_at".to_string(), ts.to_string()),
|
||||
];
|
||||
let _: usize = cm.hset_multiple(key, &pairs).await?;
|
||||
let _: usize = cm.hset_multiple(&key, &pairs).await.map_err(|e| {
|
||||
error!(db=%db, key=%key, error=%e, "HSET update_job_result_merge failed");
|
||||
e
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -499,7 +601,10 @@ impl RedisDriver {
|
||||
("jobs".to_string(), jobs_str),
|
||||
("updated_at".to_string(), ts.to_string()),
|
||||
];
|
||||
let _: usize = cm.hset_multiple(key, &pairs).await?;
|
||||
let _: usize = cm.hset_multiple(&key, &pairs).await.map_err(|e| {
|
||||
error!(db=%db, key=%key, error=%e, "HSET update_flow_jobs_set failed");
|
||||
e
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -530,7 +635,120 @@ impl RedisDriver {
|
||||
("logs".to_string(), logs_str),
|
||||
("updated_at".to_string(), ts.to_string()),
|
||||
];
|
||||
let _: usize = cm.hset_multiple(key, &pairs).await?;
|
||||
let _: usize = cm.hset_multiple(&key, &pairs).await.map_err(|e| {
|
||||
error!(db=%db, key=%key, error=%e, "HSET append_message_logs failed");
|
||||
e
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Queues (lists)
|
||||
// -----------------------------
|
||||
|
||||
/// Push a value onto a Redis list using LPUSH in the given DB.
|
||||
pub async fn lpush_list(&self, db: u32, list: &str, value: &str) -> Result<()> {
|
||||
let mut cm = self.manager_for_db(db).await?;
|
||||
let _: i64 = cm.lpush(list, value).await.map_err(|e| {
|
||||
error!(db=%db, list=%list, value=%value, error=%e, "LPUSH failed");
|
||||
e
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Enqueue a message key onto the outbound queue (msg_out).
|
||||
/// The value is the canonical message key "message:{caller_id}:{id}".
|
||||
pub async fn enqueue_msg_out(&self, db: u32, caller_id: u32, id: u32) -> Result<()> {
|
||||
let key = Self::message_key(caller_id, id);
|
||||
self.lpush_list(db, "msg_out", &key).await
|
||||
}
|
||||
|
||||
/// Block-pop from msg_out with timeout (seconds). Returns the message key if present.
|
||||
/// Uses BRPOP so that the queue behaves FIFO with LPUSH producer.
|
||||
pub async fn brpop_msg_out(&self, db: u32, timeout_secs: usize) -> Result<Option<String>> {
|
||||
let mut cm = self.manager_for_db(db).await?;
|
||||
// BRPOP returns (list, element) on success
|
||||
let res: Option<(String, String)> = redis::cmd("BRPOP")
|
||||
.arg("msg_out")
|
||||
.arg(timeout_secs)
|
||||
.query_async(&mut cm)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!(db=%db, timeout_secs=%timeout_secs, error=%e, "BRPOP failed");
|
||||
e
|
||||
})?;
|
||||
Ok(res.map(|(_, v)| v))
|
||||
}
|
||||
|
||||
/// Scan all runner:* keys in this DB and return the deserialized Runner entries.
|
||||
pub async fn scan_runners(&self, db: u32) -> Result<Vec<Runner>> {
|
||||
let mut cm = self.manager_for_db(db).await?;
|
||||
let mut out: Vec<Runner> = Vec::new();
|
||||
let mut cursor: u64 = 0;
|
||||
loop {
|
||||
let (next, keys): (u64, Vec<String>) = redis::cmd("SCAN")
|
||||
.arg(cursor)
|
||||
.arg("MATCH")
|
||||
.arg("runner:*")
|
||||
.arg("COUNT")
|
||||
.arg(100)
|
||||
.query_async(&mut cm)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!(db=%db, cursor=%cursor, error=%e, "SCAN failed");
|
||||
e
|
||||
})?;
|
||||
for k in keys {
|
||||
if let Ok(r) = self.hget_model::<Runner>(db, &k).await {
|
||||
out.push(r);
|
||||
}
|
||||
}
|
||||
if next == 0 {
|
||||
break;
|
||||
}
|
||||
cursor = next;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Global registry (DB 0) for Context IDs
|
||||
// -----------------------------
|
||||
|
||||
/// Register a context id in the global set "contexts" stored in DB 0.
|
||||
pub async fn register_context_id(&self, id: u32) -> Result<()> {
|
||||
let mut cm = self.manager_for_db(0).await?;
|
||||
let _: i64 = redis::cmd("SADD")
|
||||
.arg("contexts")
|
||||
.arg(id)
|
||||
.query_async(&mut cm)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!(db=0, context_id=%id, error=%e, "SADD contexts failed");
|
||||
e
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// List all registered context ids from the global set in DB 0.
|
||||
pub async fn list_context_ids(&self) -> Result<Vec<u32>> {
|
||||
let mut cm = self.manager_for_db(0).await?;
|
||||
// Using SMEMBERS and parsing into u32
|
||||
let vals: Vec<String> = redis::cmd("SMEMBERS")
|
||||
.arg("contexts")
|
||||
.query_async(&mut cm)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
error!(db=0, error=%e, "SMEMBERS contexts failed");
|
||||
e
|
||||
})?;
|
||||
let mut out = Vec::with_capacity(vals.len());
|
||||
for v in vals {
|
||||
if let Ok(n) = v.parse::<u32>() {
|
||||
out.push(n);
|
||||
}
|
||||
}
|
||||
out.sort_unstable();
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
|
@@ -1,18 +0,0 @@
|
||||
// Public Supervisor client module entrypoint.
|
||||
//
|
||||
// Exposes:
|
||||
// - SupervisorClient: high-level JSON-RPC client (HTTP/WS)
|
||||
// - SupervisorError: typed error for transport and JSON-RPC envelopes
|
||||
// - types::*: external DTOs and enums matching specs/supervisor.yaml
|
||||
//
|
||||
// Default endpoints (configurable at construction):
|
||||
// - HTTP: http://127.0.0.1:9944/
|
||||
// - WS: ws://127.0.0.1:9944/
|
||||
|
||||
pub mod types;
|
||||
pub mod error;
|
||||
pub mod client;
|
||||
|
||||
pub use client::SupervisorClient;
|
||||
pub use error::SupervisorError;
|
||||
pub use types::*;
|
@@ -1,388 +0,0 @@
|
||||
use crate::supervisor::error::SupervisorError;
|
||||
use crate::supervisor::types::*;
|
||||
use http::header::{AUTHORIZATION, CONTENT_TYPE};
|
||||
use http::{HeaderMap, HeaderValue};
|
||||
use jsonrpsee::core::client::ClientT;
|
||||
use jsonrpsee::core::params::{ArrayParams, ObjectParams};
|
||||
use jsonrpsee::http_client::{HttpClient, HttpClientBuilder};
|
||||
use jsonrpsee::ws_client::{WsClient, WsClientBuilder};
|
||||
use serde::de::DeserializeOwned;
|
||||
use serde::Serialize;
|
||||
use serde_json::Value;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum TransportClient {
|
||||
Http(HttpClient),
|
||||
Ws(WsClient),
|
||||
}
|
||||
|
||||
/// High-level JSON-RPC client for the Supervisor (HTTP/WS).
|
||||
///
|
||||
/// Defaults:
|
||||
/// - HTTP: http://127.0.0.1:9944/
|
||||
/// - WS: ws://127.0.0.1:9944/
|
||||
pub struct SupervisorClient {
|
||||
base_url: String,
|
||||
bearer_token: Option<String>,
|
||||
inner: TransportClient,
|
||||
}
|
||||
|
||||
impl SupervisorClient {
|
||||
// -----------------------------
|
||||
// Constructors
|
||||
// -----------------------------
|
||||
|
||||
pub async fn new_http(base_url: impl Into<String>) -> Result<Self, SupervisorError> {
|
||||
let base_url = base_url.into();
|
||||
let inner = Self::build_http(&base_url, None).await?;
|
||||
Ok(Self {
|
||||
base_url,
|
||||
bearer_token: None,
|
||||
inner: TransportClient::Http(inner),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn new_ws(base_url: impl Into<String>) -> Result<Self, SupervisorError> {
|
||||
let base_url = base_url.into();
|
||||
let inner = Self::build_ws(&base_url, None).await?;
|
||||
Ok(Self {
|
||||
base_url,
|
||||
bearer_token: None,
|
||||
inner: TransportClient::Ws(inner),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn new_http_with_token(
|
||||
base_url: impl Into<String>,
|
||||
token: impl Into<String>,
|
||||
) -> Result<Self, SupervisorError> {
|
||||
let base_url = base_url.into();
|
||||
let token = Some(token.into());
|
||||
let inner = Self::build_http(&base_url, token.clone()).await?;
|
||||
Ok(Self {
|
||||
base_url,
|
||||
bearer_token: token,
|
||||
inner: TransportClient::Http(inner),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn new_ws_with_token(
|
||||
base_url: impl Into<String>,
|
||||
token: impl Into<String>,
|
||||
) -> Result<Self, SupervisorError> {
|
||||
let base_url = base_url.into();
|
||||
let token = Some(token.into());
|
||||
let inner = Self::build_ws(&base_url, token.clone()).await?;
|
||||
Ok(Self {
|
||||
base_url,
|
||||
bearer_token: token,
|
||||
inner: TransportClient::Ws(inner),
|
||||
})
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Session management
|
||||
// -----------------------------
|
||||
|
||||
/// Set or replace the bearer token and rebuild the underlying client with auth header.
|
||||
pub async fn set_bearer_token(&mut self, token: impl Into<String>) -> Result<(), SupervisorError> {
|
||||
let token = token.into();
|
||||
self.bearer_token = Some(token);
|
||||
self.rebuild().await
|
||||
}
|
||||
|
||||
/// Remove the bearer token and rebuild the client without auth header.
|
||||
pub async fn clear_bearer_token(&mut self) -> Result<(), SupervisorError> {
|
||||
self.bearer_token = None;
|
||||
self.rebuild().await
|
||||
}
|
||||
|
||||
async fn rebuild(&mut self) -> Result<(), SupervisorError> {
|
||||
let token = self.bearer_token.clone();
|
||||
self.inner = match self.inner {
|
||||
TransportClient::Http(_) => TransportClient::Http(Self::build_http(&self.base_url, token).await?),
|
||||
TransportClient::Ws(_) => TransportClient::Ws(Self::build_ws(&self.base_url, token).await?),
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Internal builders
|
||||
// -----------------------------
|
||||
|
||||
async fn build_http(base_url: &str, bearer: Option<String>) -> Result<HttpClient, SupervisorError> {
|
||||
let mut headers = HeaderMap::new();
|
||||
// jsonrpsee sets JSON content by default; being explicit doesn't hurt.
|
||||
headers.insert(
|
||||
CONTENT_TYPE,
|
||||
HeaderValue::from_static("application/json; charset=utf-8"),
|
||||
);
|
||||
if let Some(token) = bearer {
|
||||
let val = format!("Bearer {token}");
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&val).map_err(|e| SupervisorError::Transport(e.to_string()))?,
|
||||
);
|
||||
}
|
||||
let client = HttpClientBuilder::default()
|
||||
.set_headers(headers)
|
||||
.build(base_url)
|
||||
.map_err(|e| SupervisorError::Transport(e.to_string()))?;
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
async fn build_ws(base_url: &str, bearer: Option<String>) -> Result<WsClient, SupervisorError> {
|
||||
let mut headers = HeaderMap::new();
|
||||
if let Some(token) = bearer {
|
||||
let val = format!("Bearer {token}");
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&val).map_err(|e| SupervisorError::Transport(e.to_string()))?,
|
||||
);
|
||||
}
|
||||
let client = WsClientBuilder::default()
|
||||
.set_headers(headers)
|
||||
.build(base_url)
|
||||
.await
|
||||
.map_err(|e| SupervisorError::Transport(e.to_string()))?;
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// Request helper (named-object params)
|
||||
// -----------------------------
|
||||
|
||||
async fn request<R, P>(&self, method: &str, params: P) -> Result<R, SupervisorError>
|
||||
where
|
||||
R: DeserializeOwned,
|
||||
P: Serialize,
|
||||
{
|
||||
let value = serde_json::to_value(params).map_err(SupervisorError::from)?;
|
||||
match &self.inner {
|
||||
TransportClient::Http(c) => {
|
||||
match value {
|
||||
Value::Object(map) => {
|
||||
let mut obj = ObjectParams::new();
|
||||
for (k, v) in map {
|
||||
obj.insert(k.as_str(), v).map_err(|e| SupervisorError::Transport(e.to_string()))?;
|
||||
}
|
||||
c.request(method, obj).await.map_err(|e| SupervisorError::Transport(e.to_string()))
|
||||
}
|
||||
Value::Array(arr) => {
|
||||
let mut ap = ArrayParams::new();
|
||||
for v in arr {
|
||||
ap.insert(v).map_err(|e| SupervisorError::Transport(e.to_string()))?;
|
||||
}
|
||||
c.request(method, ap).await.map_err(|e| SupervisorError::Transport(e.to_string()))
|
||||
}
|
||||
other => {
|
||||
let mut ap = ArrayParams::new();
|
||||
ap.insert(other).map_err(|e| SupervisorError::Transport(e.to_string()))?;
|
||||
c.request(method, ap).await.map_err(|e| SupervisorError::Transport(e.to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
TransportClient::Ws(c) => {
|
||||
match value {
|
||||
Value::Object(map) => {
|
||||
let mut obj = ObjectParams::new();
|
||||
for (k, v) in map {
|
||||
obj.insert(k.as_str(), v).map_err(|e| SupervisorError::Transport(e.to_string()))?;
|
||||
}
|
||||
c.request(method, obj).await.map_err(|e| SupervisorError::Transport(e.to_string()))
|
||||
}
|
||||
Value::Array(arr) => {
|
||||
let mut ap = ArrayParams::new();
|
||||
for v in arr {
|
||||
ap.insert(v).map_err(|e| SupervisorError::Transport(e.to_string()))?;
|
||||
}
|
||||
c.request(method, ap).await.map_err(|e| SupervisorError::Transport(e.to_string()))
|
||||
}
|
||||
other => {
|
||||
let mut ap = ArrayParams::new();
|
||||
ap.insert(other).map_err(|e| SupervisorError::Transport(e.to_string()))?;
|
||||
c.request(method, ap).await.map_err(|e| SupervisorError::Transport(e.to_string()))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------
|
||||
// API methods (specs/supervisor.yaml)
|
||||
// -----------------------------
|
||||
|
||||
/// fetch_nonce(public_key) -> String
|
||||
pub async fn fetch_nonce(&self, public_key: &str) -> Result<String, SupervisorError> {
|
||||
let params = FetchNonceParams {
|
||||
public_key: public_key.to_owned(),
|
||||
};
|
||||
self.request("fetch_nonce", params).await
|
||||
}
|
||||
|
||||
/// authenticate(public_key, signature, nonce) -> bool
|
||||
///
|
||||
/// Note: If your deployment provides a token out-of-band (e.g. header or subsequent call),
|
||||
/// use set_bearer_token after obtaining it.
|
||||
pub async fn authenticate(
|
||||
&self,
|
||||
public_key: &str,
|
||||
signature: &str,
|
||||
nonce: &str,
|
||||
) -> Result<bool, SupervisorError> {
|
||||
let params = AuthenticateParams {
|
||||
public_key: public_key.to_owned(),
|
||||
signature: signature.to_owned(),
|
||||
nonce: nonce.to_owned(),
|
||||
};
|
||||
self.request("authenticate", params).await
|
||||
}
|
||||
|
||||
/// whoami() -> String (JSON string with auth info)
|
||||
pub async fn whoami(&self) -> Result<String, SupervisorError> {
|
||||
let params = WhoAmIParams {};
|
||||
self.request("whoami", params).await
|
||||
}
|
||||
|
||||
/// play(script) -> PlayResult
|
||||
pub async fn play(&self, script: &str) -> Result<PlayResult, SupervisorError> {
|
||||
let params = PlayParams {
|
||||
script: script.to_owned(),
|
||||
};
|
||||
self.request("play", params).await
|
||||
}
|
||||
|
||||
/// create_job(job_params) -> String (job id)
|
||||
pub async fn create_job(&self, job_params: JobParams) -> Result<String, SupervisorError> {
|
||||
let params = CreateJobParams { job_params };
|
||||
self.request("create_job", params).await
|
||||
}
|
||||
|
||||
/// start_job(job_id) -> StartJobResult
|
||||
pub async fn start_job(&self, job_id: &str) -> Result<StartJobResult, SupervisorError> {
|
||||
let params = StartJobParams {
|
||||
job_id: job_id.to_owned(),
|
||||
};
|
||||
self.request("start_job", params).await
|
||||
}
|
||||
|
||||
/// run_job(script, script_type, prerequisites?) -> String (output)
|
||||
pub async fn run_job(
|
||||
&self,
|
||||
script: String,
|
||||
script_type: ScriptType,
|
||||
prerequisites: Option<Vec<String>>,
|
||||
) -> Result<String, SupervisorError> {
|
||||
let params = RunJobParams {
|
||||
script,
|
||||
script_type,
|
||||
prerequisites,
|
||||
};
|
||||
self.request("run_job", params).await
|
||||
}
|
||||
|
||||
/// get_job_status(job_id) -> JobStatus
|
||||
pub async fn get_job_status(&self, job_id: &str) -> Result<JobStatus, SupervisorError> {
|
||||
let params = GetJobIdParams {
|
||||
job_id: job_id.to_owned(),
|
||||
};
|
||||
self.request("get_job_status", params).await
|
||||
}
|
||||
|
||||
/// get_job_output(job_id) -> String
|
||||
pub async fn get_job_output(&self, job_id: &str) -> Result<String, SupervisorError> {
|
||||
let params = GetJobIdParams {
|
||||
job_id: job_id.to_owned(),
|
||||
};
|
||||
self.request("get_job_output", params).await
|
||||
}
|
||||
|
||||
/// get_job_logs(job_id) -> JobLogsResult
|
||||
pub async fn get_job_logs(&self, job_id: &str) -> Result<JobLogsResult, SupervisorError> {
|
||||
let params = GetJobIdParams {
|
||||
job_id: job_id.to_owned(),
|
||||
};
|
||||
self.request("get_job_logs", params).await
|
||||
}
|
||||
|
||||
/// list_jobs() -> Vec<String>
|
||||
pub async fn list_jobs(&self) -> Result<Vec<String>, SupervisorError> {
|
||||
let params = ListJobsParams {};
|
||||
self.request("list_jobs", params).await
|
||||
}
|
||||
|
||||
/// stop_job(job_id) -> null (maps to ())
|
||||
pub async fn stop_job(&self, job_id: &str) -> Result<(), SupervisorError> {
|
||||
let params = GetJobIdParams {
|
||||
job_id: job_id.to_owned(),
|
||||
};
|
||||
// jsonrpsee will deserialize JSON null into unit type when expected.
|
||||
self.request("stop_job", params).await
|
||||
}
|
||||
|
||||
/// delete_job(job_id) -> null (maps to ())
|
||||
pub async fn delete_job(&self, job_id: &str) -> Result<(), SupervisorError> {
|
||||
let params = GetJobIdParams {
|
||||
job_id: job_id.to_owned(),
|
||||
};
|
||||
self.request("delete_job", params).await
|
||||
}
|
||||
|
||||
/// clear_all_jobs() -> null (maps to ())
|
||||
pub async fn clear_all_jobs(&self) -> Result<(), SupervisorError> {
|
||||
let params = ClearAllJobsParams {};
|
||||
self.request("clear_all_jobs", params).await
|
||||
}
|
||||
}
|
||||
|
||||
// Basic compilation-only tests for method signatures and param serialization.
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::to_value;
|
||||
|
||||
#[test]
|
||||
fn params_shapes() {
|
||||
let _ = to_value(FetchNonceParams {
|
||||
public_key: "abc".into(),
|
||||
})
|
||||
.unwrap();
|
||||
let _ = to_value(AuthenticateParams {
|
||||
public_key: "abc".into(),
|
||||
signature: "sig".into(),
|
||||
nonce: "nonce".into(),
|
||||
})
|
||||
.unwrap();
|
||||
let _ = to_value(PlayParams {
|
||||
script: "echo hi".into(),
|
||||
})
|
||||
.unwrap();
|
||||
let _ = to_value(CreateJobParams {
|
||||
job_params: JobParams {
|
||||
script: "echo hi".into(),
|
||||
script_type: ScriptType::SAL,
|
||||
caller_id: "cli".into(),
|
||||
context_id: "demo".into(),
|
||||
timeout: Some(30),
|
||||
prerequisites: Some(vec![]),
|
||||
},
|
||||
})
|
||||
.unwrap();
|
||||
let _ = to_value(StartJobParams {
|
||||
job_id: "jid".into(),
|
||||
})
|
||||
.unwrap();
|
||||
let _ = to_value(RunJobParams {
|
||||
script: "print(1)".into(),
|
||||
script_type: ScriptType::Python,
|
||||
prerequisites: None,
|
||||
})
|
||||
.unwrap();
|
||||
let _ = to_value(GetJobIdParams {
|
||||
job_id: "jid".into(),
|
||||
})
|
||||
.unwrap();
|
||||
let _ = to_value(ListJobsParams {}).unwrap();
|
||||
let _ = to_value(ClearAllJobsParams {}).unwrap();
|
||||
}
|
||||
}
|
@@ -1,37 +0,0 @@
|
||||
use serde_json::Value;
|
||||
use std::fmt::{Display, Formatter};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum SupervisorError {
|
||||
Transport(String),
|
||||
Rpc { code: i32, message: String, data: Option<Value> },
|
||||
Serde(serde_json::Error),
|
||||
}
|
||||
|
||||
impl Display for SupervisorError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
SupervisorError::Transport(e) => write!(f, "transport error: {e}"),
|
||||
SupervisorError::Rpc { code, message, .. } => write!(f, "rpc error {code}: {message}"),
|
||||
SupervisorError::Serde(e) => write!(f, "serde error: {e}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for SupervisorError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
match self {
|
||||
SupervisorError::Serde(e) => Some(e),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<serde_json::Error> for SupervisorError {
|
||||
fn from(e: serde_json::Error) -> Self {
|
||||
SupervisorError::Serde(e)
|
||||
}
|
||||
}
|
||||
|
||||
// Note: jsonrpsee error types differ across transports/versions; we avoid a blanket `From` impl.
|
||||
// Callers map transport errors to SupervisorError::Transport at the callsite to reduce coupling.
|
@@ -1,190 +0,0 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// Types mirroring specs/supervisor.yaml exactly (wire format)
|
||||
|
||||
// Enums
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ScriptType {
|
||||
#[serde(rename = "OSIS")]
|
||||
OSIS,
|
||||
#[serde(rename = "SAL")]
|
||||
SAL,
|
||||
#[serde(rename = "V")]
|
||||
V,
|
||||
#[serde(rename = "Python")]
|
||||
Python,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum JobStatus {
|
||||
#[serde(rename = "Dispatched")]
|
||||
Dispatched,
|
||||
#[serde(rename = "WaitingForPrerequisites")]
|
||||
WaitingForPrerequisites,
|
||||
#[serde(rename = "Started")]
|
||||
Started,
|
||||
#[serde(rename = "Error")]
|
||||
Error,
|
||||
#[serde(rename = "Finished")]
|
||||
Finished,
|
||||
}
|
||||
|
||||
// DTOs
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct JobParams {
|
||||
pub script: String,
|
||||
pub script_type: ScriptType,
|
||||
pub caller_id: String,
|
||||
pub context_id: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
pub timeout: Option<i64>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
pub prerequisites: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PlayResult {
|
||||
pub output: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StartJobResult {
|
||||
pub success: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct JobLogsResult {
|
||||
pub logs: Option<String>,
|
||||
}
|
||||
|
||||
// Params (named-object) per method
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct FetchNonceParams {
|
||||
pub public_key: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AuthenticateParams {
|
||||
pub public_key: String,
|
||||
pub signature: String,
|
||||
pub nonce: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct WhoAmIParams {}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PlayParams {
|
||||
pub script: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CreateJobParams {
|
||||
pub job_params: JobParams,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct StartJobParams {
|
||||
pub job_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RunJobParams {
|
||||
pub script: String,
|
||||
pub script_type: ScriptType,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
#[serde(default)]
|
||||
pub prerequisites: Option<Vec<String>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct GetJobIdParams {
|
||||
pub job_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct ListJobsParams {}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
|
||||
pub struct ClearAllJobsParams {}
|
||||
|
||||
// Conversions to/from internal models when convenient
|
||||
|
||||
impl From<crate::models::ScriptType> for ScriptType {
|
||||
fn from(v: crate::models::ScriptType) -> Self {
|
||||
match v {
|
||||
crate::models::ScriptType::Osis => ScriptType::OSIS,
|
||||
crate::models::ScriptType::Sal => ScriptType::SAL,
|
||||
crate::models::ScriptType::V => ScriptType::V,
|
||||
crate::models::ScriptType::Python => ScriptType::Python,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ScriptType> for crate::models::ScriptType {
|
||||
fn from(v: ScriptType) -> Self {
|
||||
match v {
|
||||
ScriptType::OSIS => crate::models::ScriptType::Osis,
|
||||
ScriptType::SAL => crate::models::ScriptType::Sal,
|
||||
ScriptType::V => crate::models::ScriptType::V,
|
||||
ScriptType::Python => crate::models::ScriptType::Python,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<crate::models::JobStatus> for JobStatus {
|
||||
fn from(v: crate::models::JobStatus) -> Self {
|
||||
match v {
|
||||
crate::models::JobStatus::Dispatched => JobStatus::Dispatched,
|
||||
crate::models::JobStatus::WaitingForPrerequisites => JobStatus::WaitingForPrerequisites,
|
||||
crate::models::JobStatus::Started => JobStatus::Started,
|
||||
crate::models::JobStatus::Error => JobStatus::Error,
|
||||
crate::models::JobStatus::Finished => JobStatus::Finished,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<JobStatus> for crate::models::JobStatus {
|
||||
fn from(v: JobStatus) -> Self {
|
||||
match v {
|
||||
JobStatus::Dispatched => crate::models::JobStatus::Dispatched,
|
||||
JobStatus::WaitingForPrerequisites => crate::models::JobStatus::WaitingForPrerequisites,
|
||||
JobStatus::Started => crate::models::JobStatus::Started,
|
||||
JobStatus::Error => crate::models::JobStatus::Error,
|
||||
JobStatus::Finished => crate::models::JobStatus::Finished,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Basic serialization tests (casing)
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::{json, to_value};
|
||||
|
||||
#[test]
|
||||
fn script_type_casing() {
|
||||
assert_eq!(to_value(&ScriptType::OSIS).unwrap(), json!("OSIS"));
|
||||
assert_eq!(to_value(&ScriptType::SAL).unwrap(), json!("SAL"));
|
||||
assert_eq!(to_value(&ScriptType::V).unwrap(), json!("V"));
|
||||
assert_eq!(to_value(&ScriptType::Python).unwrap(), json!("Python"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn job_status_casing() {
|
||||
assert_eq!(to_value(&JobStatus::Dispatched).unwrap(), json!("Dispatched"));
|
||||
assert_eq!(
|
||||
to_value(&JobStatus::WaitingForPrerequisites).unwrap(),
|
||||
json!("WaitingForPrerequisites")
|
||||
);
|
||||
assert_eq!(to_value(&JobStatus::Started).unwrap(), json!("Started"));
|
||||
assert_eq!(to_value(&JobStatus::Error).unwrap(), json!("Error"));
|
||||
assert_eq!(to_value(&JobStatus::Finished).unwrap(), json!("Finished"));
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user