# moonrockz/moon-lander-plugins/abi

A service plugin in native code that the application links into its program. The plugin
can come from Zig, C, Rust or another language with a C ABI. The contract, the order and
the failures are the same as for each other plugin kind: see
[the module guide](../README.mbt.md). This package builds for native only.

## Before you link a native plugin

- A native plugin runs in the host process. A crash of the plugin ends the host, and the
  stop hooks of the other services do not run.
- The host cannot stop a call of a native plugin. A call blocks the event loop until it
  returns, and the call limit is not enforced: `RunningPlugin::enforcement` is
  `NotEnforced`.
- For code that can crash or not return, use a worker process. A worker process is not a
  sandbox: it has the file and network access of the user.

So link only native code that you trust as you trust the code of the application.

## The ABI

The C header `moonlander_plugin.h` in this directory holds the ABI. It comes from the Zig
source `abi.zig`, and a Zig author imports that source directly. The layout is for
64-bit targets, and the header makes the C compiler check each size and offset.

A plugin gives one entry function with a name that it selects, for example
`acme_heartbeat`. The function returns a pointer to its service table. The table is valid
for the whole program:

| Field | Content |
| --- | --- |
| `abi_version` | `MOONLANDER_ABI_VERSION`, now 1 |
| `struct_size` | `sizeof(moonlander_service)`, now 64 |
| `create` | Makes the state of one instance; returns 0, or another value when it fails |
| `describe`, `start`, `handle`, `tick`, `stop` | One function for each operation |
| `destroy` | Releases the state of `create` |

The host checks the table one time, in `NativePlugin::load`, before it calls a function
of the plugin. Each start of a service then makes an instance with `create`:

| `NativePluginError` | When | Cause |
| --- | --- | --- |
| `NullTable` | Load | The entry function returns no table |
| `UnsupportedVersion(found~, supported~)` | Load | Another ABI version than 1 |
| `TableTooSmall(size~, minimum~)` | Load | A size below 64 bytes |
| `MissingFunction(function)` | Load | A function pointer that is null, such as `handle` |
| `CreateFailed(status~)` | Start | `create` returns another value than 0; the host writes its log entries and does not call `destroy` |
| `NoMemory` | Start | The host has no memory for the instance, so `create` does not run |

A later version adds fields at the end of a table and keeps the meaning of the earlier
fields. A version 1 table that is larger than 64 bytes runs, and the host uses the fields
that it knows. Version 1 is a preview: until a later change adds run-time loading of
native libraries, a release can still change it, and the release notes say so.

Each operation gets the state of `create`, the request bytes with a `u64` length, and a
response buffer. It returns the status: 0 success, 1 a rejected event, 2 a failure. The
bytes are [the message encoding](../README.mbt.md#the-message-encoding) of the contract.
The host gives an unknown status to the application as a failure.

## Memory and threads

- The request bytes belong to the host, and they are valid only during the call.
- A response uses memory from `alloc` of the host table. After the call, the response
  belongs to the host, and the host releases it. A response of length 0 can have no data.
  Give memory of `alloc` that is no response back with `free`.
- The host table is valid from `create` until `destroy` returns, or until a failed
  `create` returns. No MoonBit object crosses to the plugin.
- Call `alloc`, `free` and `log` only during `create` or a call, on the thread of that
  call. The host drops the log entries of `destroy`.
- Call `wake` from any thread to ask for a tick. When no call runs, the host calls `tick`
  within 100 ms. Requests before that tick give one tick.
- End each thread of the plugin before `destroy` returns, and before a failed `create`
  returns.
- After the release of an instance, a call through its transport fails with
  `TransportFault::Lost`, and no code of the plugin runs.

## A plugin in Zig

The Zig package in this directory gives the module `moonlander_plugin` and the build
helper `addPlugin`. It needs Zig 0.17.1 or newer, and an older Zig fails with a message
that names that version. Name the package as a dependency in `build.zig.zon`. After
`moon update`, an application has the package in
`.mooncakes/moonrockz/moon-lander-plugins/abi`:

```zig
.{
    .name = .acme_plugins,
    .version = "0.1.0",
    .fingerprint = 0xce16957fd8ef69aa,
    .minimum_zig_version = "0.17.1",
    .dependencies = .{
        // An application outside this repository names the published module path instead.
        .moonlander_plugin = .{ .path = "../../../pkgs/plugins/abi" },
    },
    .paths = .{
        "build.zig",
        "build.zig.zon",
        "heartbeat.zig",
        "pulse.zig",
    },
}
```

`addPlugin` makes a static library that links into a MoonBit native program on Linux,
macOS and Windows. It adds the runtime functions of the compiler and position-independent
code, uses libc on Linux and macOS, gives the MSVC ABI on Windows and the deployment
target 14.0 on macOS, and builds with `ReleaseSafe`. The author gives no other option:

```zig
const std = @import("std");
const moonlander_plugin = @import("moonlander_plugin");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const heartbeat = moonlander_plugin.addPlugin(b, .{
        .name = "heartbeat",
        .root = b.path("heartbeat.zig"),
        .target = target.query,
    });
    b.installArtifact(heartbeat);
    const pulse = moonlander_plugin.addPlugin(b, .{
        .name = "pulse",
        .root = b.path("pulse.zig"),
        .target = target.query,
    });
    b.installArtifact(pulse);
}
```

This is the heartbeat service of the conformance suite in Zig
([`tests/plugins-native/zig`](https://github.com/moonrockz/moon-lander/tree/main/tests/plugins-native/zig)).
`zig build` writes `zig-out/lib/libheartbeat.a`, or `zig-out/lib/heartbeat.lib` on
Windows:

```zig
//! The heartbeat service as a native plugin in Zig. It counts one beat at each tick, and the
//! event `heartbeat.count` gives the count as decimal text.

const std = @import("std");
const abi = @import("moonlander_plugin");

const Heartbeat = struct {
    host: *const abi.Host,
    interval: u32 = 0,
    count: u32 = 0,
};

/// Give `bytes` as the response, in memory of the host.
fn respond(host: *const abi.Host, response: *abi.Buffer, status: abi.Status, bytes: []const u8) u32 {
    response.* = .{ .data = null, .length = 0 };
    if (bytes.len > 0) {
        const data = host.alloc(host.context, bytes.len) orelse return @intFromEnum(abi.Status.failure);
        @memcpy(data[0..bytes.len], bytes);
        response.* = .{ .data = data, .length = bytes.len };
    }
    return @intFromEnum(status);
}

/// The next step "wake after the interval", then `reply`.
fn wakeAfter(self: *Heartbeat, response: *abi.Buffer, reply: []const u8) u32 {
    var bytes: [32]u8 = undefined;
    std.mem.writeInt(u32, bytes[0..4], 1, .little);
    std.mem.writeInt(u32, bytes[4..8], self.interval, .little);
    @memcpy(bytes[8..][0..reply.len], reply);
    return respond(self.host, response, .success, bytes[0 .. 8 + reply.len]);
}

fn create(host: *const abi.Host, state: *?*anyopaque) callconv(.c) u32 {
    const self = std.heap.smp_allocator.create(Heartbeat) catch return 1;
    self.* = .{ .host = host };
    state.* = self;
    return 0;
}

fn describe(state: ?*anyopaque, _: [*]const u8, _: u64, response: *abi.Buffer) callconv(.c) u32 {
    const self: *Heartbeat = @ptrCast(@alignCast(state));
    return respond(self.host, response, .success,
        \\{"contract":1,"name":"heartbeat","version":"0.1.0","events":["heartbeat.count"]}
    );
}

fn start(state: ?*anyopaque, request: [*]const u8, length: u64, response: *abi.Buffer) callconv(.c) u32 {
    const self: *Heartbeat = @ptrCast(@alignCast(state));
    const interval = if (length == 4) std.mem.readInt(u32, request[0..4], .little) else 0;
    if (interval == 0 or interval > std.math.maxInt(i32)) {
        return respond(self.host, response, .failure, "no interval");
    }
    self.interval = interval;
    return wakeAfter(self, response, "");
}

fn tick(state: ?*anyopaque, _: [*]const u8, _: u64, response: *abi.Buffer) callconv(.c) u32 {
    const self: *Heartbeat = @ptrCast(@alignCast(state));
    self.count += 1;
    return wakeAfter(self, response, "");
}

fn handle(state: ?*anyopaque, request: [*]const u8, length: u64, response: *abi.Buffer) callconv(.c) u32 {
    const self: *Heartbeat = @ptrCast(@alignCast(state));
    const bytes = request[0..length];
    const name_length = std.mem.readInt(u32, bytes[0..4], .little);
    const payload = bytes[4 + name_length ..];
    if (payload.len != 0) {
        const text = "bad payload";
        self.host.log(self.host.context, @intFromEnum(abi.LogLevel.warn), text, text.len);
        return respond(self.host, response, .rejected, text);
    }
    var digits: [16]u8 = undefined;
    return wakeAfter(self, response, std.fmt.bufPrint(&digits, "{d}", .{self.count}) catch unreachable);
}

fn stop(state: ?*anyopaque, _: [*]const u8, _: u64, response: *abi.Buffer) callconv(.c) u32 {
    const self: *Heartbeat = @ptrCast(@alignCast(state));
    var text: [64]u8 = undefined;
    const line = std.fmt.bufPrint(&text, "stopped after {d} beats", .{self.count}) catch unreachable;
    self.host.log(self.host.context, @intFromEnum(abi.LogLevel.info), line.ptr, line.len);
    return respond(self.host, response, .success, "");
}

fn destroy(state: ?*anyopaque) callconv(.c) void {
    const self: *Heartbeat = @ptrCast(@alignCast(state));
    std.heap.smp_allocator.destroy(self);
}

const service: abi.Service = .{
    .abi_version = abi.abi_version,
    .struct_size = @sizeOf(abi.Service),
    .create = create,
    .describe = describe,
    .start = start,
    .handle = handle,
    .tick = tick,
    .stop = stop,
    .destroy = destroy,
};

/// The entry function. The application declares it with the same name.
export fn zig_heartbeat() *const abi.Service {
    return &service;
}
```

A plugin with a thread asks for a tick with `wake`, and joins the thread in `destroy`:

```zig
/// The thread: `wake` is the one host function that any thread can call.
fn askForTick(host: *const abi.Host) void {
    host.wake(host.context);
}
```

```zig
fn start(state: ?*anyopaque, _: [*]const u8, _: u64, response: *abi.Buffer) callconv(.c) u32 {
    const self: *Pulse = @ptrCast(@alignCast(state));
    self.thread = std.Thread.spawn(.{}, askForTick, .{self.host}) catch null;
    return idle(self, response, "");
}
```

```zig
fn destroy(state: ?*anyopaque) callconv(.c) void {
    const self: *Pulse = @ptrCast(@alignCast(state));
    if (self.thread) |thread| thread.join();
    std.heap.smp_allocator.destroy(self);
}
```

## A plugin in C

A C author includes `moonlander_plugin.h` and needs no other Moon-Lander source and no
Zig. The response comes from `alloc` of the host:

```c
static uint32_t
respond(const moonlander_host *host, moonlander_buffer *response, uint32_t status, const void *data, uint64_t length)
{
  if (length == 0) {
    response->data = NULL;
    response->length = 0;
    return status;
  }
  uint8_t *bytes = host->alloc(host->context, length);
  if (bytes == NULL) {
    return MOONLANDER_STATUS_FAILURE;
  }
  memcpy(bytes, data, (size_t)length);
  response->data = bytes;
  response->length = length;
  return status;
}
```

This is the heartbeat service in C, from the fixture plugins of the repository
([`tests/plugins-native/fixtures.c`](https://github.com/moonrockz/moon-lander/tree/main/tests/plugins-native/fixtures.c),
with its other helpers):

```c

typedef struct {
  const moonlander_host *host;
  uint32_t interval;
  uint32_t count;
} Heartbeat;

static uint32_t
heartbeat_create(const moonlander_host *host, void **state)
{
  function_calls += 1;
  Heartbeat *heartbeat = (Heartbeat *)calloc(1, sizeof(Heartbeat));
  if (heartbeat == NULL) {
    return 1;
  }
  heartbeat->host = host;
  *state = heartbeat;
  return 0;
}

static uint32_t
heartbeat_describe(void *state, const uint8_t *request, uint64_t length, moonlander_buffer *response)
{
  (void)request;
  (void)length;
  Heartbeat *heartbeat = (Heartbeat *)state;
  return respond_text(heartbeat->host, response, MOONLANDER_STATUS_SUCCESS,
                      "{\"contract\":1,\"name\":\"heartbeat\",\"version\":\"0.1.0\",\"events\":[\"heartbeat.count\"]}");
}

static uint32_t
heartbeat_next(Heartbeat *heartbeat, moonlander_buffer *response)
{
  uint8_t next[8];
  put_next(next, 1, heartbeat->interval);
  return respond(heartbeat->host, response, MOONLANDER_STATUS_SUCCESS, next, sizeof next);
}

static uint32_t
heartbeat_start(void *state, const uint8_t *request, uint64_t length, moonlander_buffer *response)
{
  Heartbeat *heartbeat = (Heartbeat *)state;
  if (length != 4 || get_u32(request) == 0 || get_u32(request) > INT32_MAX) {
    return respond_text(heartbeat->host, response, MOONLANDER_STATUS_FAILURE, "no interval");
  }
  heartbeat->interval = get_u32(request);
  return heartbeat_next(heartbeat, response);
}

static uint32_t
heartbeat_tick(void *state, const uint8_t *request, uint64_t length, moonlander_buffer *response)
{
  (void)request;
  (void)length;
  Heartbeat *heartbeat = (Heartbeat *)state;
  heartbeat->count += 1;
  return heartbeat_next(heartbeat, response);
}

static uint32_t
heartbeat_handle(void *state, const uint8_t *request, uint64_t length, moonlander_buffer *response)
{
  Heartbeat *heartbeat = (Heartbeat *)state;
  const uint8_t *name, *payload;
  uint32_t name_length;
  uint64_t payload_length;
  if (!event_of(request, length, &name, &name_length, &payload, &payload_length) ||
      !event_is(name, name_length, "heartbeat.count")) {
    return respond_text(heartbeat->host, response, MOONLANDER_STATUS_FAILURE, "unknown event");
  }
  if (payload_length != 0) {
    log_text(heartbeat->host, MOONLANDER_LOG_WARN, "bad payload");
    return respond_text(heartbeat->host, response, MOONLANDER_STATUS_REJECTED, "bad payload");
  }
  uint8_t reply[32];
  put_next(reply, 1, heartbeat->interval);
  int digits = snprintf((char *)reply + 8, sizeof reply - 8, "%u", heartbeat->count);
  return respond(heartbeat->host, response, MOONLANDER_STATUS_SUCCESS, reply, 8 + (uint64_t)digits);
}

static uint32_t
heartbeat_stop(void *state, const uint8_t *request, uint64_t length, moonlander_buffer *response)
{
  (void)request;
  (void)length;
  Heartbeat *heartbeat = (Heartbeat *)state;
  char text[64];
  snprintf(text, sizeof text, "stopped after %u beats", heartbeat->count);
  log_text(heartbeat->host, MOONLANDER_LOG_INFO, text);
  /* An empty response with no data pointer. */
  return respond(heartbeat->host, response, MOONLANDER_STATUS_SUCCESS, NULL, 0);
}

static void
heartbeat_destroy(void *state)
{
  free(state);
}

static const moonlander_service heartbeat_service = {
  MOONLANDER_ABI_VERSION, sizeof(moonlander_service), heartbeat_create, heartbeat_describe,
  heartbeat_start,        heartbeat_handle,           heartbeat_tick,   heartbeat_stop,
  heartbeat_destroy,
};

const moonlander_service *
acme_heartbeat(void)
{
  return &heartbeat_service;
}
```

A plugin in C can also be a `native-stub` of a MoonBit package, so the MoonBit build
compiles it with the C compiler of MoonBit. The tests of the repository do that.

## Link the plugin

Give the archive in the link flags of the program package in `moon.pkg`. A relative path
starts at the directory where `moon` runs, so give an absolute path, or run `moon` from
the root of the module:

| System | `cc-link-flags` |
| --- | --- |
| Linux and macOS | `/path/to/zig-out/lib/libheartbeat.a` |
| Windows | `C:/path/to/zig-out/lib/heartbeat.lib ntdll.lib` |

```text
options(
  link: { "native": { "cc-link-flags": "/path/to/zig-out/lib/libheartbeat.a" } },
)
```

On Windows, MoonBit uses the Microsoft linker, and a Zig library needs `ntdll.lib`. A Zig
library for a MoonBit program on Windows has the target `x86_64-windows`, also on an Arm
machine, because the MoonBit toolchain is x86-64 there.

Declare each entry function with the result type `ServiceTable`. Each plugin has its own
entry name, so one program can link more than one plugin:

```moonbit notest
///|
extern "C" fn acme_heartbeat() -> @plugins_abi.ServiceTable = "acme_heartbeat"

///|
extern "C" fn acme_audit() -> @plugins_abi.ServiceTable = "acme_audit"
```

`NativePlugin::load` checks the table, and the result is a plugin for `plugin_service` of
[the hosting package](../hosting/README.mbt.md). Each start of the service makes a new
instance with `create`, and its release calls `destroy`:

```moonbit notest
let heartbeat = @plugins_abi.NativePlugin::load(acme_heartbeat())
let audit = @plugins_abi.NativePlugin::load(acme_audit())
let running : Map[String, @plugins_hosting.RunningPlugin] = Map([])
let outcome = @plugins_hosting.with_plugins(plugins => {
  let host = builder()
    |> @plugins_hosting.plugin_service(
      plugins,
      "heartbeat",
      heartbeat,
      settings=_ => @conformance.settings(seconds(60)),
      started=plugin => running["heartbeat"] = plugin,
    )
    |> @plugins_hosting.plugin_service(plugins, "audit", audit, started=plugin => {
      running["audit"] = plugin
    })
    |> @hosting.build(_ => ())
  @hosting.run(host, _ => {
    let record = @plugins.EventName::parse("audit.record")
    assert_eq(running["audit"].send(record, b""), b"1")
    assert_eq(running["audit"].send(record, b""), b"2")
    assert_eq(
      running["heartbeat"].send(@conformance.count_event(), b""),
      b"0",
    )
  })
})
assert_eq(outcome.exit_code(), @hosting.ExitCode::success())
assert_eq(running["heartbeat"].description().name().to_string(), "heartbeat")
assert_eq(running["audit"].description().name().to_string(), "audit")
```

A program for js, wasm or wasm-gc that imports this package does not build, and the error
names the backend.
