Hosted services from plugins for the Moon-Lander framework: one contract for each plugin kind
host start hook --> describe, start(settings) next step: wake after 1 s
1 s later --> tick(time since start) next step: wake after 1 s
application event --> handle("heartbeat.count") reply "1"
host stop hook --> stop(reason), then the release| Package | Targets | Contents |
|---|---|---|
| moonrockz/moon-lander-plugins | wasm, wasm-gc, js, native | The contract types, the message encoding, the pure session, Service, and the Plugin and Transport traits |
| moonrockz/moon-lander-plugins/hosting | native, js, wasm | plugin_service: a plugin as a service of a host |
| moonrockz/moon-lander-plugins/wasm | native, js | WasmPlugin: a plugin in a WebAssembly module, with limits and no authority by default |
| moonrockz/moon-lander-plugins/guest | wasm | Guest: a MoonBit Service as a wasm plugin |
| moonrockz/moon-lander-plugins/abi | native | NativePlugin: a linked plugin in Zig, C or another language with a C ABI, the C header and the Zig build package |
| moonrockz/moon-lander-plugins/process | native | WorkerPlugin: a plugin of any kind in its own worker process, with an enforced call limit |
| moonrockz/moon-lander-plugins/worker | native | serve: the serve loop of a worker program |
///|
fn heartbeat() -> @plugins.Service raise {
let count_event = @plugins.EventName::parse("heartbeat.count")
let description = @plugins.Description::new(
@plugins.PluginName::parse("heartbeat"),
@plugins.PluginVersion::parse("0.1.0"),
[count_event],
)
@plugins.Service::new(description, (settings, log) => {
// The application chose the bytes of the settings: here, text such as "1s".
let interval = @lander_core.TimeLimit::parse(@utf8.decode(settings)) catch {
_ => raise @plugins.ServiceFailed("no interval")
}
let mut beats = 0
@plugins.RunningService::new(
Wake(interval),
tick=_ => {
beats += 1
Wake(interval)
},
handle=(_, payload) => {
guard payload.length() == 0 else {
raise @plugins.EventRejected("bad payload")
}
(Wake(interval), @utf8.encode(beats.to_string()))
},
stop=_ => log.write(Information, "stopped after \{beats} beats"),
)
})
}| Operation | When | The plugin gets | The plugin gives |
|---|---|---|---|
| describe | First, one time | Nothing | Contract version, name, version and the names of its events |
| start | After a valid description | The settings bytes of the application | The next step |
| tick | At the wake time | The time since the start | The next step |
| handle | When the application sends an event | The event name and the payload bytes | The next step and the reply bytes |
| stop | When the host stops | The stop reason | Nothing |
| Next step | Meaning |
|---|---|
| Idle | No tick. The plugin only waits for events |
| Wake(time) | One tick, this long after the end of the call |
| Finished | No more calls. The host releases the plugin and continues to run |
| What happens | Result |
|---|---|
| The application sends an event that the description does not have | The sender gets UnknownEvent. The plugin gets no call |
| handle raises EventRejected | The sender gets RejectedEvent with the message. The plugin continues, and its planned tick stays |
| Another error, a trap, a lost connection or a message that breaks the contract | The plugin failed. The sender and the waiting senders get PluginFailed |
| describe or start fails | The host does not start |
///|
test "the plugin counts its ticks" {
let plugin = heartbeat().instance(@plugins.PluginLog::new((_, _) => ()))
let call = (request : @plugins.Request) => {
let operation = request.operation()
@plugins.Reply::decode(
operation,
plugin.respond(operation, request.encode()),
)
}
let wake = @plugins.NextStep::Wake(@lander_core.TimeLimit::seconds(1))
let count = @plugins.EventName::parse("heartbeat.count")
assert_eq(call(Start(b"1s")), Next(wake))
assert_eq(call(Tick(@plugins.Uptime::millis(1000))), Next(wake))
assert_eq(call(Handle(count, b"")), Handled(wake, b"1"))
assert_eq(call(Handle(count, b"x")), Rejected("bad payload"))
}///|
test "the host makes one tick after one second" {
let at = millis => @plugins.Instant::millis(millis)
let limit : @plugins.CallLimit = {
limit: @lander_core.TimeLimit::seconds(5),
enforcement: NotEnforced,
}
let (launch, _) = @plugins.Launch::new(at(0), limit, b"1s")
let plugin = heartbeat().instance(@plugins.PluginLog::new((_, _) => ()))
guard launch.answered(at(0), plugin.respond(Describe, b""))
is Call(launch, start, _) else {
fail("expected the start call")
}
guard launch.answered(at(0), plugin.respond(Start, start.encode()))
is Started(session, _) else {
fail("expected a session")
}
assert_eq(session.next_time(), Some(at(1000)))
assert_eq(session.next_call(at(999)).1, None)
assert_eq(
session.next_call(at(1000)).1,
Some(Tick(@plugins.Uptime::millis(1000))),
)
}| Operation | Request | Response with status 0 |
|---|---|---|
| describe | Empty | JSON in UTF-8: contract, name, version, events |
| start | The settings bytes | Next step |
| handle | u32 length of the name, the name in UTF-8, the payload | Next step, then the reply bytes |
| tick | u64 milliseconds since the start | Next step |
| stop | u32 reason: 0 completed, 1 requested, 2 signal, 3 embedder, 4 start failed, 5 failed | Empty |
pub(open) trait Transport {
async fn call(Self, Operation, Bytes) -> Response
fn enforcement(Self) -> Enforcement
fn wake_flag(Self) -> WakeFlag? = _
}pub suberror FrameError {
InvalidLimit(Int)
WrongHeaderLength(Int)
WrongMark(UInt)
UnsupportedVersion(found~ : UInt, supported~ : UInt)
UnknownKind(UInt)
TooLong(length~ : UInt, limit~ : Int)
UnknownCode(FrameKind, UInt)
WrongBodyLength(expected~ : Int, actual~ : Int)
InvalidLogText
} derive(Eq, Debug)impl Show for FrameErrorpub suberror MessageError {
InvalidText(MessagePart)
InvalidDescription(String)
UnsupportedContract(plugin~ : String?, found~ : Int)
InvalidName(NameError)
DuplicateEvent(EventName)
WrongLength(expected~ : Int, actual~ : Int)
NameBeyondEnd(UInt)
UnknownCode(MessagePart, UInt)
InvalidWakeTime(UInt)
} derive(Eq, Debug)pub suberror PluginFailure {
Reported(operation~ : Operation, message~ : String)
BrokenContract(operation~ : Operation, error~ : MessageError)
NoResponse(operation~ : Operation?, fault~ : TransportFault)
} derive(Eq, Debug)impl Show for PluginFailurepub suberror SendError {
UnknownEvent(EventName)
RejectedEvent(event~ : EventName, message~ : String)
PluginFinished
PluginStopped
PluginFailed(PluginFailure)
} derive(Eq, Debug)pub(all) suberror ServiceError {
EventRejected(String)
ServiceFailed(String)
}fn Description::new(name : PluginName, version : PluginVersion, events : ArrayView[EventName]) -> Description raise MessageErrorpub struct Launch {
// private fields
}pub struct PluginLog {
// private fields
}impl Show for PluginNameimpl Show for PluginVersionpub(all) enum Reply {
Described(Description)
Next(NextStep)
Handled(NextStep, Bytes)
Stopped
Rejected(String)
Failed(String)
} derive(Eq, Debug)pub(all) enum Request {
Describe
Start(Bytes)
Handle(EventName, Bytes)
Tick(Uptime)
Stop(StopReason)
} derive(Eq, Debug)pub struct RunningService {
// private fields
}fn RunningService::new(next : NextStep, handle? : (EventName, Bytes) -> (NextStep, Bytes) raise, tick? : (Uptime) -> NextStep raise, stop? : (StopReason) -> Unit raise) -> RunningServicepub struct Service {
// private fields
}fn Service::new(description : Description, start : (Bytes, PluginLog) -> RunningService raise) -> Servicepub struct ServiceInstance {
// private fields
}fn ServiceInstance::respond(self : ServiceInstance, operation : Operation, request : Bytes) -> Responsepub struct Session {
// private fields
}pub struct WakeFlag {
// private fields
}let FRAME_VERSION : UIntInstall
Download zipHosted services from plugins for the Moon-Lander framework: one contract for each plugin kind