Durable state graphs for MoonBit: nodes, merging, checkpoints, interrupts and resume. No model in sight.
let graph = @moonstate.Builder::new(merge=merge, initial={ n: 0, log: [] })
.entry("seed")
.node("seed", (_state, _run) => [@moonstate.Write({ n: Some(1), log: Some(["seed"]) })])
.node("double", (state, _run) => [@moonstate.Write({ n: Some(state.n * 2), log: None })])
.edge("seed", "double")
.compile("hello")
let out = graph.run({ n: None, log: None })
// out.n == 2[dependencies]
"moonbitstack/moonstate" = "0.1.0"import { "moonbitstack/moonstate" }struct Counter { n : Int; log : Array[String] }
struct Patch { n : Int?; log : Array[String]? }
fn merge(state : Counter, patch : Patch) -> Counter {
{ n: patch.n.unwrap_or(state.n), log: state.log + patch.log.unwrap_or([]) }
}.node("fan", (_state, _run) => {
let steps : Array[@moonstate.Step[Report, Part]] = []
for index = 0; index < 3; index = index + 1 {
steps.push(@moonstate.Send("shard", { parts: [], total: index }))
}
steps
})
.node("shard", (state, _run) => [@moonstate.Write({ parts: Some([...]), total: None })])
.routed("shard") // entered by Send, not by an edgelet saver = @moonstate.MemorySaver::new()
let graph = build(saver) // compile(..., saver=saver)
let _ = graph.run(input, thread="job") // dies halfway
let out = graph.run(input, thread="job") // continues from the last superstep.node("approve", (_state, run) => match run.answer() {
Some(answer) => [@moonstate.Write({ approved: Some(@json.from_json(answer)) , text: None })],
None => [@moonstate.Interrupt({ "ask": "approve?" })],
})let out = graph.resume_with("review", Json(true))pub(open) trait Executor {
async each(Self, Array[Work]) -> Array[Done] raise
}let fetch = @moonstate.task("fetch", async fn(url : String) -> String { ... })
let score = @moonstate.task("score", async fn(text : String) -> Int { ... })
let workflow = @moonstate.entrypoint("rank", async fn(url : String, ctx : @moonstate.Context) -> Int {
let text = fetch.call(ctx, url)
score.call(ctx, text)
}, saver=saver)| Item | Purpose |
|---|---|
| Builder::new(merge~, initial~) | The empty state, and how an update folds into it. |
| Builder::node(name, run, retry?) | A node: state and Run in, steps out. |
| Builder::edge(from, to) | Run to after from. |
| Builder::join(from, to) | Run to once every node in from ran in the same superstep. |
| Builder::branch(from, route) | route picks the next nodes from the merged state. |
| Builder::subgraph(name, graph, enter~, leave~) | A whole graph as one node. |
| Builder::routed(name) | name is entered by Send, Goto or a route. |
| Builder::entry(name) | The node a run starts at. |
| Builder::compile(name, saver?, store?, executor?, limit?) | Check the graph and freeze it. |
| Step | Write, Goto, Send, Interrupt: what a node returns. |
| Graph::run(input, thread?) | Run to the end, or continue a crashed thread. |
| Graph::stream(input, on, thread?) | The same, reporting events. |
| Graph::resume_with(thread, answer) | Continue a thread that is waiting. |
| Graph::resume_stream(thread, answer, on) | The same, reporting events. |
| Graph::state(thread) / Graph::history(thread) | The thread now, and every checkpoint it took. |
| Graph::update(thread, patch, as_node?) | Rewrite the latest state, then continue after a node. |
| Saver / MemorySaver | Where checkpoints live. |
| Store / MemoryStore | Long-term memory: namespaced JSON with a search. |
| Executor / inline | Where a superstep's tasks run. |
| Run | Thread, step, checkpoint, store, emit, cancel. |
| task / entrypoint / Task / Context | The functional form. |
pub(open) trait Saver {
async fn get(Self, thread : String, id? : String) -> Checkpoint?
async fn put(Self, Checkpoint) -> Unit
async fn put_writes(Self, thread : String, id : String, task : String, values : Array[Json]) -> Unit
async fn list(Self, thread : String, limit? : Int, before? : String) -> Array[Checkpoint]
async fn delete(Self, thread : String) -> Unit
}pub(open) trait Store {
async fn get(Self, space : Array[String], key : String) -> Item?
async fn put(Self, space : Array[String], key : String, value : Json) -> Unit
async fn delete(Self, space : Array[String], key : String) -> Unit
async fn search(Self, space : Array[String], query? : String, filter? : Map[String, Json], limit? : Int) -> Array[Item]
}pub(all) suberror GraphError {
StepLimit(limit~ : Int)
NodeFailed(node~ : String, message~ : String)
Interrupted(thread~ : String, value~ : Json)
NotInterrupted(thread~ : String)
MissingThread(thread~ : String)
MissingNode(node~ : String)
Unreadable(reason~ : String)
Cancelled(thread~ : String)
Backend(reason~ : String)
}pub(all) suberror Refused {
NoNodes
NoEntry
UnknownEntry(node~ : String)
DuplicateNode(node~ : String)
DanglingEdge(from~ : String, to~ : String)
Unreachable(node~ : String)
NoExit
}async fn[I, O] Entrypoint::run(self : Entrypoint[I, O], input : I, thread? : String) -> O raise GraphErrorpub struct Graph[S, U] {
name : String
merge : (S, U) -> S
initial : S
entry : String
nodes : Map[String, NodeSpec[S, U]]
edges : Map[String, Array[String]]
joins : Array[(Array[String], String)]
branches : Map[String, Array[async (S) -> Array[String]]]
saver : &Saver?
store : &Store?
executor : &Executor
limit : Int
}async fn[S : FromJson, U] Graph::state(self : Graph[S, U], thread : String) -> Snapshot[S]? raise GraphErrorasync fn[S : ToJson + FromJson, U] Graph::update(self : Graph[S, U], thread : String, update : U, as_node? : String) -> Unit raise GraphErrorimpl Saver for MemorySaverasync fn list(self : MemorySaver, thread : String, limit? : Int, before? : String) -> Array[Checkpoint]async fn put_writes(self : MemorySaver, thread : String, id : String, task : String, values : Array[Json]) -> Unitasync fn MemorySaver::list(self : MemorySaver, thread : String, limit? : Int, before? : String) -> Array[Checkpoint]async fn MemorySaver::put_writes(self : MemorySaver, thread : String, id : String, task : String, values : Array[Json]) -> Unitimpl Store for MemoryStoreasync fn MemoryStore::put(self : MemoryStore, space : Array[String], key : String, value : Json) -> Unitasync fn MemoryStore::search(self : MemoryStore, space : Array[String], query? : String, filter? : Map[String, Json], limit? : Int) -> Array[Item]type NodeSpec[S, U]pub(all) struct Retry {
attempts : Int
delay : Int
}let default_limit : IntInstall
Download zipDurable state graphs for MoonBit: nodes, merging, checkpoints, interrupts and resume. No model in sight.