Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Making an SDK

A plugin backend can be written in any language: mochid starts a program and talks JSON lines with it over a socket. A backend can speak the plugin protocol directly, as the sh one on the Writing plugins page does, but a small library makes plugins in a language pleasant to write. This page is a guide to writing that library: what it must do, what it should do, and a complete one in Python to start from.

The Python SDK below is examples/python/hello/mochi_plugin.py in the repository, with an example plugin next to it. Mochi’s test suite runs that plugin in a real mochid, so the code on this page works.

What an SDK does

1. Connect

mochid starts the backend with these:

File descriptor 3One end of a Unix stream socket to mochid. MOCHI_PLUGIN_FD holds the number, 3; read it rather than assume it.
MOCHI_PLUGIN_DIRThe plugin’s directory, which is also the working directory.
stdout, stderrRead by mochid line by line into its log, tagged with the plugin’s id.
stdinEmpty.

Wrap the descriptor in the language’s socket type: socket.socket(fileno=3) in Python, net.FileConn(os.NewFile(3, "")) in Go, new net.Socket({ fd: 3 }) in Node. When MOCHI_PLUGIN_FD isn’t set, the program was run by hand: exit with a message saying mochid starts it, rather than wait forever.

2. Read and write lines

Every message is one JSON object on one line, ended by \n, at most 1 MiB. Keep a buffer and split it at newlines: a read can return half a line or several. Write each message whole; when several threads or tasks send, write under a lock so lines don’t interleave.

3. Say hello

mochid speaks first:

{"type":"hello","api":1,"version":"0.4.7","module":"hello","settings":{},"data_dir":"…","session_dir":"…","compositor":{…}}

Check api: an SDK for API 1 should refuse anything else with a clear message. Keep module, settings, data_dir, session_dir and compositor for the plugin. Then answer within 5 seconds, or mochid stops the backend:

{"type":"hello","api":1}

4. Number activities and bubbles

The backend picks the ids of its activities and bubbles: count up from 1 and return the number from present and show_bubble, so the plugin can update or remove what it showed. Events about them, like ended or bubble_clicked, carry the same numbers. Activities and bubbles may share one counter.

5. Match answers to questions

call, activate_workspace, windows and pointer_output carry an id, and their answer, call_result or compositor_result, repeats it. Use a second counter for these. Other messages can come before the answer: keep them for later rather than drop them. An async SDK keeps a table of pending ids with a future or callback each; a blocking SDK can read until the answer comes and queue the rest, as the Python one does.

6. Answer every command

A command carries an id, the action and its args as an object, already checked against the manifest. The caller waits until the backend sends a reply with that id: with nothing for success, error for a failure, or output for mochi ipc to print. Make it hard to forget: Rust’s SDK fails a command dropped unanswered, and an SDK with destructors or context managers can do the same.

7. Keep the compositor’s state

compositor messages replace the whole state. Keep the latest for the plugin to read, and let it wait for changes if the language has a way.

8. Stop when mochid closes

When the socket reaches its end, mochid is stopping the plugin: end the event loop, let the plugin finish, and exit. 1.5 seconds later the backend is killed. Fail pending questions then, so nothing waits forever.

9. Let unknown messages through

The protocol only grows: a newer mochid may send message types or fields the SDK doesn’t know. Ignore unknown fields, and pass unknown messages on to the plugin or drop them, but don’t fail on them.

What an SDK should have

  • One call per message the backend sends, named like the protocol: publish_state, present, update, withdraw, show_bubble, update_bubble, hide_bubble, call, reply, activate_workspace, windows, pointer_output. The Rust SDK’s names are the same, which helps people move between them. call returns the output its call_result carries, for actions that answer with something, like a launcher provider’s search.
  • Settings with defaults. settings holds only what the user wrote, so the plugin fills in the rest.
  • A way to wait for events and a timer at once, because most plugins also do something every second or minute: a timeout on the event wait, an async stream, or a callback API on an event loop.
  • Activity and bubble specs that need only the view: in the protocol, only compact and view are required, and everything else has a default.

A Python SDK

The whole library, about 200 lines with only the standard library:

"""A small Mochi plugin SDK for Python, in one file and the standard library.

It speaks the plugin protocol: JSON lines over the socket mochid passes as
file descriptor 3. Copy this file next to your backend and import it.

    from mochi_plugin import Plugin

    plugin = Plugin()
    for event in plugin.events():
        if event["type"] == "command":
            plugin.present("Hello", payload={"text": "Hi"}, timeout_ms=3000)
            plugin.reply(event)
"""

import json
import os
import select
import socket
import sys

API = 1


class CallError(Exception):
    """Another module's action failed: `kind` is `not_enabled`, `itself`,
    `unknown_action`, `invalid_args` or `failed`."""

    def __init__(self, error):
        self.kind = error.get("kind", "failed")
        self.detail = error.get("detail")
        super().__init__(f"{self.kind}: {self.detail}")


class Plugin:
    """The connection to mochid. Creating it says hello."""

    def __init__(self):
        fd = os.environ.get("MOCHI_PLUGIN_FD")
        if fd is None:
            sys.exit("MOCHI_PLUGIN_FD isn't set: mochid starts plugin backends")
        self._socket = socket.socket(fileno=int(fd))
        self._buffer = b""
        self._backlog = []  # messages read while waiting for an answer
        self._next_id = 0  # activities and bubbles
        self._next_request = 0  # calls and compositor questions
        self.closed = False

        hello = self._read()
        if hello is None or hello.get("type") != "hello":
            sys.exit("mochid didn't start with hello")
        if hello["api"] != API:
            sys.exit(f"mochid speaks api {hello['api']}, this plugin speaks {API}")
        self.module = hello["module"]
        self.version = hello["version"]
        self.settings = hello.get("settings") or {}
        self.data_dir = hello["data_dir"]
        self.session_dir = hello["session_dir"]
        self.compositor = hello["compositor"]
        self._send({"type": "hello", "api": API})

    # Events

    def events(self, timeout=None):
        """Yields mochid's events as dicts, until it closes the connection.

        With `timeout` in seconds, yields None when nothing came for that
        long, for work on a timer. Answers and compositor changes are taken
        care of here: `self.compositor` is always the latest state."""
        while True:
            message = self._next(timeout)
            if message is None:
                if self.closed:
                    return
                yield None
                continue
            if message["type"] == "compositor":
                self.compositor = message["state"]
                continue
            yield message

    def reply(self, command, error=None, output=None):
        """Answers a `command` event: with `error` for a failure, with
        `output` for `mochi ipc` to print, or with neither."""
        message = {"type": "reply", "id": command["id"]}
        if error is not None:
            message["error"] = error
        if output is not None:
            message["output"] = output
        self._send(message)

    # Requests that need no answer

    def publish_state(self, state):
        """Replaces the plugin's state, which its views and other modules read."""
        self._send({"type": "publish_state", "state": state})

    def present(self, compact, **spec):
        """Submits an activity showing the view `compact`. `spec` takes the
        protocol's fields: payload, timeout_ms, priority, expanded, key...
        Returns its id."""
        number = self._number()
        self._send({"type": "present", "id": number, "spec": {"compact": compact, **spec}})
        return number

    def update(self, activity, payload):
        self._send({"type": "update", "id": activity, "payload": payload})

    def withdraw(self, activity):
        self._send({"type": "withdraw", "id": activity})

    def show_bubble(self, view, **spec):
        """Shows a bubble with the view `view`. `spec` takes payload, area,
        group, order, priority, news, key, wide. Returns its id."""
        number = self._number()
        self._send({"type": "show_bubble", "id": number, "spec": {"view": view, **spec}})
        return number

    def update_bubble(self, bubble, payload):
        self._send({"type": "update_bubble", "id": bubble, "payload": payload})

    def hide_bubble(self, bubble):
        self._send({"type": "hide_bubble", "id": bubble})

    # Requests with an answer. They wait for it; events that come meanwhile
    # wait in the backlog for `events`.

    def call(self, module, action, *args):
        """Runs another module's action and returns what it answered with,
        or None. Raises CallError when it fails."""
        answer = self._ask({"type": "call", "module": module, "action": action, "args": list(args)})
        if answer.get("error"):
            raise CallError(answer["error"])
        return answer.get("output")

    def activate_workspace(self, workspace):
        self._compositor({"type": "activate_workspace", "workspace": workspace})

    def windows(self):
        return self._compositor({"type": "windows"})

    def pointer_output(self):
        return self._compositor({"type": "pointer_output"})

    def _compositor(self, request):
        answer = self._ask(request)
        if answer.get("error"):
            raise RuntimeError(answer["error"])
        return answer.get("value")

    def _ask(self, request):
        self._next_request += 1
        request["id"] = self._next_request
        self._send(request)
        while True:
            message = self._read()
            if message is None:
                raise ConnectionError("mochid closed the connection")
            if message["type"] in ("call_result", "compositor_result") and message["id"] == request["id"]:
                return message
            self._backlog.append(message)

    # The wire

    def _number(self):
        self._next_id += 1
        return self._next_id

    def _send(self, message):
        try:
            self._socket.sendall(json.dumps(message).encode() + b"\n")
        except OSError:
            self.closed = True

    def _next(self, timeout):
        if self._backlog:
            return self._backlog.pop(0)
        if b"\n" not in self._buffer and not self.closed:
            ready, _, _ = select.select([self._socket], [], [], timeout)
            if not ready:
                return None
        return self._read()

    def _read(self):
        """The next message, or None once mochid closed the connection."""
        while b"\n" not in self._buffer:
            chunk = self._socket.recv(65536)
            if not chunk:
                self.closed = True
                return None
            self._buffer += chunk
        line, self._buffer = self._buffer.split(b"\n", 1)
        try:
            return json.loads(line)
        except ValueError:
            return self._read()

How it does each part:

PartIn the code
Connectsocket.socket(fileno=int(fd))
Lines_read splits a byte buffer at \n; _send writes json.dumps(message) + "\n"
HelloThe constructor reads mochid’s hello, checks api and answers
Numbers_number counts activities and bubbles; _next_request counts questions
Answers_ask reads until its answer comes, keeping other messages in _backlog
Commandsreply(event, error=…, output=…)
Compositorevents keeps self.compositor up to date and doesn’t yield those messages
Stopevents returns when the socket ends
Unknown messagesevents yields every message it doesn’t handle itself; the plugin skips what it doesn’t know
Timersevents(timeout=1.0) yields None when nothing came for a second

A plugin with it:

#!/usr/bin/env python3
"""An example plugin backend in Python, with the SDK in mochi_plugin.py.

`mochi ipc hello say [text...]` shows the text on the island and counts it
in a bubble. A click on the bubble opens the control center, when it's enabled.
"""

from mochi_plugin import CallError, Plugin

plugin = Plugin()
greeting = plugin.settings.get("greeting", "Hello from Python")
said = 0
bubble = None

plugin.publish_state({"said": said})

for event in plugin.events():
    kind = event["type"]
    if kind == "command" and event["action"] == "say":
        text = event["args"].get("text") or greeting
        plugin.present("Hello", payload={"text": text}, timeout_ms=3000)
        said += 1
        plugin.publish_state({"said": said})
        if bubble is None:
            bubble = plugin.show_bubble("Bubble", payload={"said": said}, area="right", news=True)
        else:
            plugin.update_bubble(bubble, {"said": said})
        plugin.reply(event, output=f"said {text!r}")
    elif kind == "command" and event["action"] == "count":
        plugin.reply(event, output=str(said))
    elif kind == "command":
        plugin.reply(event, error=f"no action {event['action']}")
    elif kind == "bubble_clicked":
        try:
            plugin.call("control-center", "open")
        except CallError as error:
            # Without the control center there's nothing to open: fine.
            if error.kind != "not_enabled":
                print(f"opening the control center failed: {error}", flush=True)

and its manifest:

# An example plugin with a backend in Python, and a tiny Python SDK in
# mochi_plugin.py. `needs` asks for Python 3.

[plugin]
id = "hello"
name = "Hello"
version = "0.1.0"
description = "Says hello on the island, from Python"
authors = ["Mochi"]
api = 1

[backend]
exec = "hello.py"
needs = ["python3"]

[[actions]]
name = "say"
description = "Show some text on the island"
args = [{ name = "text", description = "What to say, instead of the greeting", optional = true, rest = true }]

[[actions]]
name = "count"
description = "Print how many times it said something"

# Where its bubble goes unless the user moves it, as hello.py shows it.
[bubbles]
area = "right"

The backend is the script itself, so Python must be installed where the plugin runs. A plugin can ship its SDK file next to its code, as this one does, or depend on a package.

Testing an SDK

Test the SDK the way mochid uses it: make a socket pair, give one end to the SDK, and play mochid on the other, sending hello first. Check that it answers hello, numbers what it shows, matches answers to questions with other messages in between, answers commands, and ends when you close your end. Rust’s SDK does this in crates/mochi-sdk/tests/talk.rs, and the Rust SDK page shows it.

Then run a plugin built with it in a real mochid: list it in plugins.toml with a path: source, enable it, and drive it with mochi ipc. mochi status says whether it runs, and mochid’s log has what it printed. crates/mochid/tests/plugins.rs does the same automatically for the Python example and for a backend in sh.