moon-lander-plugins

    Hosted services from plugins for the Moon-Lander framework: one contract for each plugin kind

    Download zip
    Author
    Version
    0.18.0
    License
    Apache-2.0
    Last updated
    10 hours ago
    Downloads
    9

    #moonrockz/moon-lander-plugins

    Service plugins for Moon-Lander. A plugin is a hosted service with one fixed contract, so the application does not depend on how the plugin is made. This release has plugins in MoonBit code, in WebAssembly modules and in linked native libraries, and a native host can run a plugin of each kind in a worker process.

    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

    PackageTargetsContents
    moonrockz/moon-lander-pluginswasm, wasm-gc, js, nativeThe contract types, the message encoding, the pure session, Service, and the Plugin and Transport traits
    moonrockz/moon-lander-plugins/hostingnative, js, wasmplugin_service: a plugin as a service of a host
    moonrockz/moon-lander-plugins/wasmnative, jsWasmPlugin: a plugin in a WebAssembly module, with limits and no authority by default
    moonrockz/moon-lander-plugins/guestwasmGuest: a MoonBit Service as a wasm plugin
    moonrockz/moon-lander-plugins/abinativeNativePlugin: 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/processnativeWorkerPlugin: a plugin of any kind in its own worker process, with an enforced call limit
    moonrockz/moon-lander-plugins/workernativeserve: the serve loop of a worker program

    #Write a plugin

    The host drives the plugin with short calls. The plugin has no loop and no task. This plugin counts one beat at each tick and gives the count for an event:

    ///|
    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"),
    )
    })
    }

    The function of Service::new runs at start. The state is in its local variables, so each start has its own state.

    A call runs on the event loop of the host. While it runs, the host does no other work, and nothing can end it. Keep each call short.

    #The contract

    OperationWhenThe plugin getsThe plugin gives
    describeFirst, one timeNothingContract version, name, version and the names of its events
    startAfter a valid descriptionThe settings bytes of the applicationThe next step
    tickAt the wake timeThe time since the startThe next step
    handleWhen the application sends an eventThe event name and the payload bytesThe next step and the reply bytes
    stopWhen the host stopsThe stop reasonNothing

    The next step says what the host does next:

    Next stepMeaning
    IdleNo tick. The plugin only waits for events
    Wake(time)One tick, this long after the end of the call
    FinishedNo more calls. The host releases the plugin and continues to run

    The latest next step replaces the earlier one. In the example, an event moves the next tick to one interval after that event. A plugin that must keep its rhythm calculates the time that remains.

    #Order

    • The plugin gets one call at a time.
    • Events and ticks that arrive during a call wait, and run in the order of arrival.
    • A sender that is cancelled while it waits does not reach the plugin.
    • When the host stops, the waiting events fail with PluginStopped, the call in progress ends, and then the plugin gets stop.

    #Failures

    What happensResult
    The application sends an event that the description does not haveThe sender gets UnknownEvent. The plugin gets no call
    handle raises EventRejectedThe 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 contractThe plugin failed. The sender and the waiting senders get PluginFailed
    describe or start failsThe host does not start

    A failed plugin gets no more calls, also no stop. The host stops with the exit code 1. There is no automatic restart. In a MoonBit plugin, panic and abort are not errors: they end the program.

    #Test a plugin

    Service::instance answers calls with no host, no event loop and no clock:

    ///|
    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"))
    }

    Launch and Session hold the rules of the host side as values. They have no clock and no I/O, so a test gives the time:

    ///|
    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))),
    )
    }

    #The message encoding

    A transport carries an operation and request bytes to the plugin, and a status and response bytes back. Request and Reply encode and decode the bytes. Integers are little-endian, with no padding.

    OperationRequestResponse with status 0
    describeEmptyJSON in UTF-8: contract, name, version, events
    startThe settings bytesNext step
    handleu32 length of the name, the name in UTF-8, the payloadNext step, then the reply bytes
    ticku64 milliseconds since the startNext step
    stopu32 reason: 0 completed, 1 requested, 2 signal, 3 embedder, 4 start failed, 5 failedEmpty

    The next step is two u32 values: the kind (0 idle, 1 wake, 2 finished), and the wake time in milliseconds, which is 0 for idle and finished. Status 1 is a rejected event, and status 2 is a failure. Then the response is a message in UTF-8.

    A name of a plugin or an event starts with an ASCII letter, has only ASCII letters, digits, ., - and _, and has at most 128 characters. A plugin version has 1 to 64 printable ASCII characters and no space.

    Plugin

    pub(open) trait Plugin {
    async fn connect(Self, PluginLog,
    TimeLimit
    , async (&Transport) -> Unit) -> Unit
    }

    A plugin that a host can connect to: a MoonBit Service, or a value of one of the other packages of this module.

    Transport

    pub(open) trait Transport {
    async fn call(Self, Operation, Bytes) -> Response
    fn enforcement(Self) -> Enforcement
    fn wake_flag(Self) -> WakeFlag? = _
    }

    A connection to one plugin instance. It carries an operation and the request bytes to the plugin, and gives the status and the response bytes back. It does not know the contract rules; Launch and Session hold them.

    FrameError

    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
    )

    Why a frame or a frame limit is not valid.
    impl Show for FrameError

    FrameError::equal

    fn FrameError::equal(FrameError, FrameError) -> Bool
    automatically derived

    FrameError::message

    fn FrameError::message(self : FrameError) -> String

    Text for people that describes the error.

    FrameError::not_equal

    fn FrameError::not_equal(x : FrameError, y : FrameError) -> Bool
    automatically derived

    FrameError::output

    fn FrameError::output(self : FrameError, logger : &Logger) -> Unit

    FrameError::to_repr

    automatically derived

    FrameError::to_string

    fn FrameError::to_string(self : FrameError) -> String

    Default implementation for Show::to_string, uses a StringBuilder

    MessageError

    pub 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
    )

    A message that breaks the plugin contract. Callers can match the cases, but only the functions of this package make them.

    MessageError::equal

    automatically derived

    MessageError::message

    fn MessageError::message(self : MessageError) -> String

    Text for people that describes the fault.

    MessageError::not_equal

    fn MessageError::not_equal(x : MessageError, y : MessageError) -> Bool
    automatically derived

    MessageError::to_repr

    automatically derived

    NameError

    pub suberror NameError {
    InvalidPluginName(text~ : String, rule~ : NameRule)
    InvalidPluginVersion(text~ : String, rule~ : NameRule)
    InvalidEventName(text~ : String, rule~ : NameRule)
    } derive(Eq,
    Debug
    )

    A text that is not a valid name or version of the plugin contract. Callers can match the cases, but only the parse functions make them.

    NameError::equal

    fn NameError::equal(NameError, NameError) -> Bool
    automatically derived

    NameError::message

    fn NameError::message(self : NameError) -> String

    Text for people that describes the fault.

    NameError::not_equal

    fn NameError::not_equal(x : NameError, y : NameError) -> Bool
    automatically derived

    NameError::to_repr

    automatically derived

    PluginFailure

    pub suberror PluginFailure {
    Reported(operation~ : Operation, message~ : String)
    BrokenContract(operation~ : Operation, error~ : MessageError)
    NoResponse(operation~ : Operation?, fault~ : TransportFault)
    } derive(Eq,
    Debug
    )

    Why a plugin failed. The host makes no more calls to the plugin.

    PluginFailure::equal

    automatically derived

    PluginFailure::message

    fn PluginFailure::message(self : PluginFailure) -> String

    Text for people that describes the fault.

    PluginFailure::not_equal

    fn PluginFailure::not_equal(x : PluginFailure, y : PluginFailure) -> Bool
    automatically derived

    PluginFailure::output

    fn PluginFailure::output(self : PluginFailure, logger : &Logger) -> Unit

    PluginFailure::to_repr

    automatically derived

    PluginFailure::to_string

    fn PluginFailure::to_string(self : PluginFailure) -> String

    Default implementation for Show::to_string, uses a StringBuilder

    SendError

    pub suberror SendError {
    UnknownEvent(EventName)
    RejectedEvent(event~ : EventName, message~ : String)
    PluginFinished
    PluginStopped
    PluginFailed(PluginFailure)
    } derive(Eq,
    Debug
    )

    Why a sender gets no reply for its event.
    impl Show for SendError

    SendError::equal

    fn SendError::equal(SendError, SendError) -> Bool
    automatically derived

    SendError::message

    fn SendError::message(self : SendError) -> String

    Text for people that describes the fault.

    SendError::not_equal

    fn SendError::not_equal(x : SendError, y : SendError) -> Bool
    automatically derived

    SendError::output

    fn SendError::output(self : SendError, logger : &Logger) -> Unit

    SendError::to_repr

    automatically derived

    SendError::to_string

    fn SendError::to_string(self : SendError) -> String

    Default implementation for Show::to_string, uses a StringBuilder

    ServiceError

    pub(all) suberror ServiceError {
    EventRejected(String)
    ServiceFailed(String)
    }

    The two ways in which a MoonBit service refuses a call. Each other error of a service function is a failure with the text of that error.

    TransportFault

    pub(all) suberror TransportFault {
    Trapped(String)
    LimitReached(
    TimeLimit
    )
    MemoryLimitReached
    Denied(function~ : String)
    Lost(String)
    } derive(Eq,
    Debug
    )

    A call that gave no response. The plugin is unusable after it.

    TransportFault::equal

    automatically derived

    TransportFault::message

    fn TransportFault::message(self : TransportFault) -> String

    Text for people that describes the fault.

    TransportFault::not_equal

    fn TransportFault::not_equal(x : TransportFault, y : TransportFault) -> Bool
    automatically derived

    TransportFault::to_repr

    automatically derived

    Action

    pub(all) enum Action {
    Answer(Ticket, Bytes)
    Refuse(Ticket, SendError)
    Warn(LateCall)
    Fail(PluginFailure)
    } derive(Eq,
    Debug
    )

    What the host must do, in the order of the array.

    Action::equal

    fn Action::equal(Action, Action) -> Bool
    automatically derived

    Action::not_equal

    fn Action::not_equal(x : Action, y : Action) -> Bool
    automatically derived

    Action::to_repr

    automatically derived

    CallLimit

    pub(all) struct CallLimit {
    limit :
    TimeLimit

    enforcement : Enforcement
    } derive(Eq,
    Debug
    )

    The time limit of each call, and whether the transport enforces it.

    CallLimit::equal

    fn CallLimit::equal(CallLimit, CallLimit) -> Bool
    automatically derived

    CallLimit::not_equal

    fn CallLimit::not_equal(x : CallLimit, y : CallLimit) -> Bool
    automatically derived

    CallLimit::to_repr

    automatically derived

    ContractVersion

    pub(all) enum ContractVersion {
    V1
    } derive(Eq,
    Debug
    )

    A version of the plugin contract that this library supports.

    ContractVersion::equal

    automatically derived

    ContractVersion::from_number

    fn ContractVersion::from_number(number : Int) -> ContractVersion?

    The version with the number number, or None when this library does not support it.

    ContractVersion::not_equal

    fn ContractVersion::not_equal(x : ContractVersion, y : ContractVersion) -> Bool
    automatically derived

    ContractVersion::number

    fn ContractVersion::number(self : ContractVersion) -> Int

    The number of the version in a description.

    ContractVersion::to_repr

    automatically derived

    Description

    pub struct Description {
    // private fields
    } derive(Eq,
    Debug
    )

    What a plugin says about itself before it starts: the contract version, the name, the version and the events that it accepts. No event name occurs two times.

    Description::accepts

    fn Description::accepts(self : Description, event : EventName) -> Bool

    True when the plugin accepts the event event.

    Description::contract

    fn Description::contract(self : Description) -> ContractVersion

    The contract version that the plugin uses.

    Description::decode

    fn Description::decode(bytes : Bytes) -> Description raise MessageError

    Read the response bytes of describe. The decoder ignores fields that it does not know.

    Description::encode

    fn Description::encode(self : Description) -> Bytes

    The description as the response bytes of describe.

    Description::equal

    fn Description::equal(Description, Description) -> Bool
    automatically derived

    Description::events

    fn Description::events(self : Description) -> ReadOnlyArray[EventName]

    The events that the plugin accepts, in the order of the description.

    Description::name

    fn Description::name(self : Description) -> PluginName

    The name of the plugin.

    Description::new

    fn Description::new(name : PluginName, version : PluginVersion, events : ArrayView[EventName]) -> Description raise MessageError

    Make a description of contract version 1.

    Description::not_equal

    fn Description::not_equal(x : Description, y : Description) -> Bool
    automatically derived

    Description::to_repr

    automatically derived

    Description::version

    fn Description::version(self : Description) -> PluginVersion

    The version of the plugin.

    End

    pub enum End {
    Finished
    Stopped
    Failed(PluginFailure)
    } derive(Eq,
    Debug
    )

    How a session ended.

    End::equal

    fn End::equal(End, End) -> Bool
    automatically derived

    End::not_equal

    fn End::not_equal(x : End, y : End) -> Bool
    automatically derived

    End::to_repr

    automatically derived

    Enforcement

    pub(all) enum Enforcement {
    Enforced
    NotEnforced
    } derive(Eq,
    Debug
    )

    Whether a transport can stop a call at its time limit.

    Enforcement::equal

    fn Enforcement::equal(Enforcement, Enforcement) -> Bool
    automatically derived

    Enforcement::not_equal

    fn Enforcement::not_equal(x : Enforcement, y : Enforcement) -> Bool
    automatically derived

    Enforcement::to_repr

    automatically derived

    EventName

    pub struct EventName {
    // private fields
    } derive(Eq, Hash,
    Debug
    )

    The name of an event that a plugin accepts, for example heartbeat.count. It has the same rules as PluginName.
    impl Show for EventName

    EventName::equal

    fn EventName::equal(EventName, EventName) -> Bool
    automatically derived

    EventName::hash

    fn EventName::hash(self : EventName) -> Int
    automatically derived

    EventName::hash_combine

    fn EventName::hash_combine(EventName, Hasher) -> Unit
    automatically derived

    EventName::not_equal

    fn EventName::not_equal(x : EventName, y : EventName) -> Bool
    automatically derived

    EventName::output

    fn EventName::output(self : EventName, logger : &Logger) -> Unit

    EventName::parse

    fn EventName::parse(text : String) -> EventName raise NameError

    Parse an event name.

    EventName::to_repr

    automatically derived

    EventName::to_string

    fn EventName::to_string(self : EventName) -> String

    Default implementation for Show::to_string, uses a StringBuilder

    Frame

    pub(all) enum Frame {
    Call(Operation, Bytes)
    Reply(Status, Bytes)
    Log(
    Level
    , String)
    Wake
    } derive(Eq,
    Debug
    )

    One message between a host and a worker process (WRK-2). There is one call at a time, so a frame has no identifier. The log frames of a call come before its reply.

    Frame::encode

    fn Frame::encode(self : Frame) -> Bytes

    The frame as bytes: the header, then the body.

    Frame::equal

    fn Frame::equal(Frame, Frame) -> Bool
    automatically derived

    Frame::kind

    fn Frame::kind(self : Frame) -> FrameKind

    The kind of the frame.

    Frame::not_equal

    fn Frame::not_equal(x : Frame, y : Frame) -> Bool
    automatically derived

    Frame::to_repr

    automatically derived

    FrameHeader

    pub struct FrameHeader {
    // private fields
    } derive(Eq,
    Debug
    )

    The header of a frame, after its checks. The body has length() bytes.

    FrameHeader::decode

    fn FrameHeader::decode(bytes : BytesView, limit : FrameLimit) -> FrameHeader raise FrameError

    Read a header of FRAME_HEADER_LENGTH bytes. It checks the mark, the version, the kind and the length, so a reader allocates no body over limit.

    FrameHeader::decode_body

    fn FrameHeader::decode_body(self : FrameHeader, body : Bytes) -> Frame raise FrameError

    Read the frame from its header and its body of length() bytes.

    FrameHeader::equal

    fn FrameHeader::equal(FrameHeader, FrameHeader) -> Bool
    automatically derived

    FrameHeader::kind

    fn FrameHeader::kind(self : FrameHeader) -> FrameKind

    The kind of the frame.

    FrameHeader::length

    fn FrameHeader::length(self : FrameHeader) -> Int

    The number of bytes of the body.

    FrameHeader::not_equal

    fn FrameHeader::not_equal(x : FrameHeader, y : FrameHeader) -> Bool
    automatically derived

    FrameHeader::to_repr

    automatically derived

    FrameKind

    pub(all) enum FrameKind {
    Call
    Reply
    Log
    Wake
    } derive(Eq,
    Debug
    )

    The kind of a frame, as its header gives it.

    FrameKind::equal

    fn FrameKind::equal(FrameKind, FrameKind) -> Bool
    automatically derived

    FrameKind::name

    fn FrameKind::name(self : FrameKind) -> String

    The name of the kind: call, reply, log or wake.

    FrameKind::not_equal

    fn FrameKind::not_equal(x : FrameKind, y : FrameKind) -> Bool
    automatically derived

    FrameKind::to_repr

    automatically derived

    FrameLimit

    pub struct FrameLimit {
    // private fields
    } derive(Eq,
    Debug
    )

    The largest body of a frame that a reader accepts. A reader checks the length in the header against the limit before it reads the body.

    FrameLimit::bytes

    fn FrameLimit::bytes(count : Int) -> FrameLimit raise FrameError

    A limit of count bytes, from 1 byte to 1 GiB.

    FrameLimit::default

    fn FrameLimit::default() -> FrameLimit

    The default limit: 16 MiB.

    FrameLimit::equal

    fn FrameLimit::equal(FrameLimit, FrameLimit) -> Bool
    automatically derived

    FrameLimit::not_equal

    fn FrameLimit::not_equal(x : FrameLimit, y : FrameLimit) -> Bool
    automatically derived

    FrameLimit::to_bytes

    fn FrameLimit::to_bytes(self : FrameLimit) -> Int

    The number of bytes.

    FrameLimit::to_repr

    automatically derived

    Instant

    pub struct Instant {
    // private fields
    } derive(Compare, Eq,
    Debug
    )

    A point in time, as whole milliseconds of a clock that does not go back. Only the difference of two points of one clock has a meaning.

    Instant::equal

    fn Instant::equal(Instant, Instant) -> Bool
    automatically derived

    Instant::millis

    fn Instant::millis(count : Int64) -> Instant

    Make a point in time from the milliseconds of a clock.

    Instant::not_equal

    fn Instant::not_equal(x : Instant, y : Instant) -> Bool
    automatically derived

    Instant::to_millis

    fn Instant::to_millis(self : Instant) -> Int64

    The milliseconds of the clock.

    Instant::to_repr

    automatically derived

    LateCall

    pub struct LateCall {
    operation : Operation
    limit :
    TimeLimit

    elapsed : Uptime
    } derive(Eq,
    Debug
    )

    A call that gave its response after the limit, because nothing can end it.

    LateCall::equal

    fn LateCall::equal(LateCall, LateCall) -> Bool
    automatically derived

    LateCall::not_equal

    fn LateCall::not_equal(x : LateCall, y : LateCall) -> Bool
    automatically derived

    LateCall::to_repr

    automatically derived

    Launch

    pub struct Launch {
    // private fields
    }

    The start of a plugin: describe, and then start with the settings.

    Launch::answered

    fn Launch::answered(self : Launch, now : Instant, response : Response) -> LaunchStep

    Take the response of the call in progress.

    Launch::broken

    fn Launch::broken(self : Launch, fault : TransportFault) -> PluginFailure

    The failure of the plugin when the call in progress gave no response.

    Launch::new

    fn Launch::new(now : Instant, limit : CallLimit, settings : Bytes) -> (Launch, Request)

    Begin the start of a plugin. Make the call that this function gives at once, and pass its response to Launch::answered.

    LaunchStep

    pub enum LaunchStep {
    Call(Launch, Request, LateCall?)
    Started(Session, LateCall?)
    Refused(PluginFailure, LateCall?)
    }

    The step that follows a response during the start. The last part is present when the call before it was late.

    MessagePart

    pub enum MessagePart {
    Description
    EventName
    NextStep
    StopReason
    Status
    } derive(Eq,
    Debug
    )

    The part of a message that holds an invalid value.

    MessagePart::equal

    fn MessagePart::equal(MessagePart, MessagePart) -> Bool
    automatically derived

    MessagePart::not_equal

    fn MessagePart::not_equal(x : MessagePart, y : MessagePart) -> Bool
    automatically derived

    MessagePart::to_repr

    automatically derived

    NameRule

    pub enum NameRule {
    Empty
    TooLong(Int)
    FirstNotAsciiLetter
    CharNotAllowed(Char)
    } derive(Eq,
    Debug
    )

    The rule of a plugin name, a plugin version or an event name that a text breaks.

    NameRule::equal

    fn NameRule::equal(NameRule, NameRule) -> Bool
    automatically derived

    NameRule::not_equal

    fn NameRule::not_equal(x : NameRule, y : NameRule) -> Bool
    automatically derived

    NameRule::to_repr

    automatically derived

    NextStep

    pub(all) enum NextStep {
    Idle
    Wake(
    TimeLimit
    )
    Finished
    } derive(Eq,
    Debug
    )

    What a plugin asks for after a successful start, handle or tick. The latest next step replaces the earlier one.

    NextStep::equal

    fn NextStep::equal(NextStep, NextStep) -> Bool
    automatically derived

    NextStep::not_equal

    fn NextStep::not_equal(x : NextStep, y : NextStep) -> Bool
    automatically derived

    NextStep::to_repr

    automatically derived

    Operation

    pub(all) enum Operation {
    Describe
    Start
    Handle
    Tick
    Stop
    } derive(Eq,
    Debug
    )

    An operation of the plugin contract.
    impl Show for Operation

    Operation::equal

    fn Operation::equal(Operation, Operation) -> Bool
    automatically derived

    Operation::not_equal

    fn Operation::not_equal(x : Operation, y : Operation) -> Bool
    automatically derived

    Operation::output

    fn Operation::output(self : Operation, logger : &Logger) -> Unit

    Operation::to_repr

    automatically derived

    Operation::to_string

    fn Operation::to_string(self : Operation) -> String

    Default implementation for Show::to_string, uses a StringBuilder

    PluginLog

    pub struct PluginLog {
    // private fields
    }

    The log of a plugin. The host writes each entry to the logger of the application, with the name of the hosted service.

    PluginLog::new

    Make a log that gives each entry to sink.

    PluginLog::write

    fn PluginLog::write(self : PluginLog, level :
    Level
    , text : String) -> Unit

    Write one entry.

    PluginName

    pub struct PluginName {
    // private fields
    } derive(Eq, Hash,
    Debug
    )

    The name that a plugin gives itself, for example heartbeat. It starts with an ASCII letter, holds only ASCII letters, digits, ., - and _, and has at most 128 characters.
    impl Show for PluginName

    PluginName::equal

    fn PluginName::equal(PluginName, PluginName) -> Bool
    automatically derived

    PluginName::hash

    fn PluginName::hash(self : PluginName) -> Int
    automatically derived

    PluginName::hash_combine

    fn PluginName::hash_combine(PluginName, Hasher) -> Unit
    automatically derived

    PluginName::not_equal

    fn PluginName::not_equal(x : PluginName, y : PluginName) -> Bool
    automatically derived

    PluginName::output

    fn PluginName::output(self : PluginName, logger : &Logger) -> Unit

    PluginName::parse

    fn PluginName::parse(text : String) -> PluginName raise NameError

    Parse a plugin name.

    PluginName::to_repr

    automatically derived

    PluginName::to_string

    fn PluginName::to_string(self : PluginName) -> String

    Default implementation for Show::to_string, uses a StringBuilder

    PluginVersion

    pub struct PluginVersion {
    // private fields
    } derive(Eq, Hash,
    Debug
    )

    The version that a plugin gives itself, for example 0.1.0. The host only shows it. It has 1 to 64 printable ASCII characters and no space.

    PluginVersion::equal

    automatically derived

    PluginVersion::hash

    fn PluginVersion::hash(self : PluginVersion) -> Int
    automatically derived

    PluginVersion::hash_combine

    fn PluginVersion::hash_combine(PluginVersion, Hasher) -> Unit
    automatically derived

    PluginVersion::not_equal

    fn PluginVersion::not_equal(x : PluginVersion, y : PluginVersion) -> Bool
    automatically derived

    PluginVersion::output

    fn PluginVersion::output(self : PluginVersion, logger : &Logger) -> Unit

    PluginVersion::parse

    fn PluginVersion::parse(text : String) -> PluginVersion raise NameError

    Parse a plugin version.

    PluginVersion::to_repr

    automatically derived

    PluginVersion::to_string

    fn PluginVersion::to_string(self : PluginVersion) -> String

    Default implementation for Show::to_string, uses a StringBuilder

    Reply

    pub(all) enum Reply {
    Described(Description)
    Next(NextStep)
    Handled(NextStep, Bytes)
    Stopped
    Rejected(String)
    Failed(String)
    } derive(Eq,
    Debug
    )

    The meaning of a response.

    Reply::decode

    fn Reply::decode(operation : Operation, response : Response) -> Reply raise MessageError

    Read the response of operation. Only handle can reject; for each other operation, the status Rejected is a failure. A message that is not valid UTF-8 gets replacement characters, so the text is not lost.

    Reply::encode

    fn Reply::encode(self : Reply) -> Response

    The reply as a response, on the side of the plugin.

    Reply::equal

    fn Reply::equal(Reply, Reply) -> Bool
    automatically derived

    Reply::not_equal

    fn Reply::not_equal(x : Reply, y : Reply) -> Bool
    automatically derived

    Reply::to_repr

    automatically derived

    Request

    pub(all) enum Request {
    Describe
    Start(Bytes)
    Handle(EventName, Bytes)
    Tick(Uptime)
    Stop(StopReason)
    } derive(Eq,
    Debug
    )

    One call from the host to a plugin.

    Request::decode

    fn Request::decode(operation : Operation, bytes : Bytes) -> Request raise MessageError

    Read the request bytes of operation, on the side of the plugin.

    Request::encode

    fn Request::encode(self : Request) -> Bytes

    The request bytes. A transport sends them together with the operation.

    Request::equal

    fn Request::equal(Request, Request) -> Bool
    automatically derived

    Request::not_equal

    fn Request::not_equal(x : Request, y : Request) -> Bool
    automatically derived

    Request::operation

    fn Request::operation(self : Request) -> Operation

    The operation of the request.

    Request::to_repr

    automatically derived

    Response

    pub(all) struct Response {
    status : Status
    body : Bytes
    } derive(Eq,
    Debug
    )

    What a transport gives back for one call: the status and the response bytes. Reply::decode reads its meaning.

    Response::equal

    fn Response::equal(Response, Response) -> Bool
    automatically derived

    Response::not_equal

    fn Response::not_equal(x : Response, y : Response) -> Bool
    automatically derived

    Response::to_repr

    automatically derived

    RunningService

    pub struct RunningService {
    // private fields
    }

    A service after its start.

    RunningService::new

    fn RunningService::new(next : NextStep, handle? : (EventName, Bytes) -> (NextStep, Bytes) raise, tick? : (Uptime) -> NextStep raise, stop? : (StopReason) -> Unit raise) -> RunningService

    Give the first next step and the functions of a service that started. With no handle, the service rejects each event. With no tick, a tick gives Idle.

    Service

    pub struct Service {
    // private fields
    }

    A plugin in MoonBit code: its description, and a function that starts it. One value can serve a program that links it, a wasm module and a worker.
    impl Plugin for Service

    Service::description

    fn Service::description(self : Service) -> Description

    What the service says about itself.

    Service::instance

    fn Service::instance(self : Service, log : PluginLog) -> ServiceInstance

    Make an instance that did not start. It writes its log entries to log.

    Service::new

    fn Service::new(description : Description, start : (Bytes, PluginLog) -> RunningService raise) -> Service

    Make a service. start gets the settings bytes and the log, and gives the first next step together with the functions for the later calls. Those functions hold the state, so each start has its own state.

    ServiceInstance

    pub struct ServiceInstance {
    // private fields
    }

    One instance of a service, on the side of the plugin. It answers the calls of a transport.

    ServiceInstance::respond

    fn ServiceInstance::respond(self : ServiceInstance, operation : Operation, request : Bytes) -> Response

    Answer one call. An error of a service function and a request that breaks the contract give a response with that status, so this function does not raise.

    Session

    pub struct Session {
    // private fields
    }

    A plugin after its start. The session holds the contract rules: one call at a time, the arrival order, the next step and the failures. It is a value with no clock and no I/O. Each function gives a new session, and some functions also give actions for the host.

    The host makes the calls: it asks next_call for the next one, makes it, and passes the response to answered. When there is no call, it waits until next_time or until the session changes. When end gives a value, the host releases the plugin.

    Session::answered

    fn Session::answered(self : Session, now : Instant, response : Response) -> (Session, Array[Action])

    Take the response of the call in progress. With no call in progress, nothing changes.

    Session::broken

    fn Session::broken(self : Session, fault : TransportFault) -> (Session, Array[Action])

    The transport lost the plugin, during a call or between two calls.

    Session::description

    fn Session::description(self : Session) -> Description

    What the plugin says about itself.

    Session::end

    fn Session::end(self : Session) -> End?

    How the session ended, or None while it is active.

    Session::next_call

    fn Session::next_call(self : Session, now : Instant) -> (Session, Request?)

    Take the next call. The call is in progress from this time, so the host must make it at once and pass its response to answered or its fault to broken. It is None when a call is in progress and when no work waits.

    Session::next_time

    fn Session::next_time(self : Session) -> Instant?

    The time of the next tick, when the host must ask for the next call. It is None while a call is in progress and when the plugin asked for no tick.

    Session::released

    fn Session::released(self : Session) -> (Session, Array[Action])

    The host released the plugin before the session ended, so there are no more calls and no more responses. The sender of the call in progress and the waiting senders get PluginStopped.

    Session::send

    fn Session::send(self : Session, now : Instant, event : EventName, payload : Bytes) -> (Session, Ticket) raise SendError

    Send an event. The ticket names the sender in a later Answer or Refuse. An event that the plugin cannot get raises at once and changes nothing.

    Session::stop

    fn Session::stop(self : Session, reason : StopReason) -> (Session, Array[Action])

    Stop the plugin. The waiting events fail at their senders, the call in progress ends, and then next_call gives stop.

    Session::wake

    fn Session::wake(self : Session, now : Instant) -> Session

    The plugin asked for a tick without a wait. A later next step does not remove this tick.

    Session::withdraw

    fn Session::withdraw(self : Session, ticket : Ticket) -> Session

    Take back an event that still waits, because its sender is gone. When the plugin already has the event, the call continues, and the host ignores the later Answer or Refuse.

    Status

    pub(all) enum Status {
    Success
    Rejected
    Failure
    } derive(Eq,
    Debug
    )

    The status of a response.

    Status::code

    fn Status::code(self : Status) -> UInt

    The number of the status in a transport: 0, 1 or 2.

    Status::equal

    fn Status::equal(Status, Status) -> Bool
    automatically derived

    Status::from_code

    fn Status::from_code(code : UInt) -> Status raise MessageError

    Read the number of a status.

    Status::not_equal

    fn Status::not_equal(x : Status, y : Status) -> Bool
    automatically derived

    Status::to_repr

    automatically derived

    StopReason

    pub(all) enum StopReason {
    Completed
    Requested
    Signal
    Embedder
    StartFailed
    Failed
    } derive(Eq,
    Debug
    )

    Why the host stops a plugin. The cases are the stop reasons of a host.

    StopReason::equal

    fn StopReason::equal(StopReason, StopReason) -> Bool
    automatically derived

    StopReason::not_equal

    fn StopReason::not_equal(x : StopReason, y : StopReason) -> Bool
    automatically derived

    StopReason::to_repr

    automatically derived

    Ticket

    pub struct Ticket {
    // private fields
    } derive(Eq, Hash,
    Debug
    )

    The identity of one event that the application sent.

    Ticket::equal

    fn Ticket::equal(Ticket, Ticket) -> Bool
    automatically derived

    Ticket::hash

    fn Ticket::hash(self : Ticket) -> Int
    automatically derived

    Ticket::hash_combine

    fn Ticket::hash_combine(Ticket, Hasher) -> Unit
    automatically derived

    Ticket::not_equal

    fn Ticket::not_equal(x : Ticket, y : Ticket) -> Bool
    automatically derived

    Ticket::to_repr

    automatically derived

    Uptime

    pub struct Uptime {
    // private fields
    } derive(Compare, Eq,
    Debug
    )

    The time since the plugin started, in whole milliseconds.

    Uptime::equal

    fn Uptime::equal(Uptime, Uptime) -> Bool
    automatically derived

    Uptime::millis

    fn Uptime::millis(count : UInt64) -> Uptime

    Make an uptime from a count of milliseconds. Each count is valid.

    Uptime::not_equal

    fn Uptime::not_equal(x : Uptime, y : Uptime) -> Bool
    automatically derived

    Uptime::to_millis

    fn Uptime::to_millis(self : Uptime) -> UInt64

    The count of milliseconds.

    Uptime::to_repr

    automatically derived

    WakeFlag

    pub struct WakeFlag {
    // private fields
    }

    A flag that a plugin sets from any thread to ask for a tick. Taking it gives whether it was set, and clears it, so the requests before one look give one tick.

    WakeFlag::new

    fn WakeFlag::new(take : () -> Bool) -> WakeFlag

    A flag that take reads and clears.

    WakeFlag::take

    fn WakeFlag::take(self : WakeFlag) -> Bool

    Whether the plugin asked for a tick since the last time. The flag is clear after it.

    FRAME_HEADER_LENGTH

    let FRAME_HEADER_LENGTH : Int

    The number of bytes of a frame header.

    FRAME_VERSION

    let FRAME_VERSION : UInt

    The version of the frame format that this library reads and writes.