#Architecture and Concurrency

When you connect to D-Bus in Goose, you are talking directly to a Unix domain socket. There is no middleman library or hidden C runtime. This guide explains what happens across that socket from the moment you connect to when requests are dispatched.


#How a Connection is Established

When you instantiate a Connection, Goose walks through five clear steps:

Connection Flow

Connection and Authentication Sequence

Step-by-step protocol sequence from initial socket connection to active D-Bus session.

Your Application
Goose Core
Unix Socket / D-Bus Daemon
1
Connection.init()
2
connect(path)
3
\0AUTH EXTERNAL <hex_uid>
4
OK <guid>
5
NEGOTIATE_UNIX_FD
6
AGREE_UNIX_FD
7
BEGIN
8
Hello() [MethodCall]
9
Return: ":1.42"
Step 1 of 9 Connection.init()

Application requests connection to session, system, or accessibility bus.

#1. Locating the Socket

Goose inspects your environment based on the BusType:

  • Session Bus: Reads the DBUS_SESSION_BUS_ADDRESS environment variable (typically something like unix:path=/run/user/1000/bus).
  • System Bus: Connects to the standard well-known path /var/run/dbus/system_bus_socket or reads DBUS_SYSTEM_BUS_ADDRESS.
  • Accessibility Bus: Reads AT_SPI_BUS_ADDRESS or queries the X11 root window.

#2. The SASL `EXTERNAL` Handshake

D-Bus requires authentication before switching to binary protocol framing:

  1. The Null Byte: Goose transmits a single \0 byte right after connecting. In Linux, sending this byte allows the kernel to verify peer credentials on Unix domain sockets via SO_PEERCRED.
  2. User Identity: Goose sends AUTH EXTERNAL <hex-encoded UID>\r\n. For example, if your UID is 1000, it sends ASCII hex 31303030. The bus daemon replies with OK <guid>.
  3. Unix File Descriptor Negotiation: Goose asks NEGOTIATE_UNIX_FD\r\n. The daemon acknowledges with AGREE_UNIX_FD. This tells both sides that file descriptors can be passed out-of-band using SCM_RIGHTS.
  4. Binary Protocol Switch: Goose sends BEGIN\r\n and immediately switches the socket to binary D-Bus message framing.
  5. The Hello Greeting: Goose calls Hello on org.freedesktop.DBus to claim its unique bus address (like :1.84).

#Two Concurrency Models

Applications have different threading needs. A GUI or a game loop usually wants a single thread driving everything, while a backend daemon or CLI tool might prefer worker threads handling work concurrently.

Goose provides both options via the Backend enum:

Backend Enum (Live Extract) ~/goose/src/connection.zig
zig
/// Defines the concurrency/event-loop model for the connection.
pub const Backend = enum {
    threaded,
    poll,
};

#Backend 1: `.threaded` (Default)

In .threaded mode, Goose manages background tasks so your main code stays simple:

Concurrency Engine

Concurrency Backend Architecture

Toggle between Goose's two execution modes to see how messages are processed.

Unix Domain Socket
/run/user/1000/bus
▼ recvmsg()
Background Thread
SocketReader
Reads bytes, extracts SCM_RIGHTS file descriptors
Method Replies (Serial Match)
PendingCalls Map

Wakes the waiting caller thread immediately using an atomic futex.

Signals & Incoming Calls
MessageQueue Pool

Condition-signaled worker threads pull and execute registered handlers.

  • SocketReader Thread: Reads raw bytes from the Unix socket, reconstructs message boundaries, and pulls any file descriptors from the ancillary socket buffer.
  • Synchronous Method Calls: When you call p.call(), Goose adds an entry to an internal map keyed by message serial. When the reply packet arrives, Goose matches the serial and immediately wakes your thread using a futex.
  • Worker Queue: Signals and incoming calls from other processes are pushed into a thread-safe queue where worker threads pick them up and run your registered handlers.
  • Shutdown: Calling conn.close() terminates the reader, drains the queue, and cleanly wakes all threads.
zig
var conn = try goose.Connection.init(allocator, .Session, io, environ_map);
defer conn.close();

// Serves incoming requests on the bus
try conn.serve();

#Backend 2: `.poll` (Zero Background Threads)

Sometimes you do not want background threads at all. If you are writing a Wayland compositor, a game with a custom main loop, or an embedded service, spawning threads introduces mutex overhead, race conditions, and signal-handling headaches.

The .poll backend guarantees that zero background threads are ever spawned.

Instead of background worker threads, you poll conn.getFd() directly in your event loop, and call while (try conn.dispatch()) {} whenever the socket is ready to read.

#Event Loop Integration Example

zig
const std = @import("std");
const goose = @import("goose");

pub fn runEventLoop(init: std.process.Init) !void {
    const allocator = init.gpa;
    const io = init.io;

    // Connect using .poll mode
    var conn = try goose.Connection.initWithBackend(
        allocator,
        .Session,
        io,
        init.environ_map,
        .poll,
    );
    defer conn.close();

    // Get the socket file descriptor
    const socket_fd = conn.getFd();

    var pfd = [1]std.posix.pollfd{.{
        .fd = socket_fd,
        .events = std.posix.POLL.IN,
        .revents = 0,
    }};

    std.debug.print("Single-threaded poll loop running on FD {d}...\n", .{socket_fd});

    while (true) {
        // Wait up to 500ms for incoming data
        const ready = try std.posix.poll(&pfd, 500);
        if (ready == 0) continue;

        // Drain any incoming messages
        if ((pfd[0].revents & std.posix.POLL.IN) != 0 or conn.hasDataToRead()) {
            while (try conn.dispatch()) {
                // Returns true as long as buffered messages remain
            }
        }
    }
}

#Dispatch Tables and Interface Wrappers

When you export a Zig struct as a D-Bus object, Goose creates an internal InterfaceWrapper table:

InterfaceWrapper Dispatch Definition ~/goose/src/common.zig
zig
pub const InterfaceWrapper = struct {
    pub const DispatchResult = enum { unhandled, dispatched };

    instance: *anyopaque,
    dispatch: *const fn (wrapper: *const InterfaceWrapper, conn: *Connection, msg: core.Message) anyerror!DispatchResult,
    destroy: *const fn (wrapper: *const InterfaceWrapper, allocator: std.mem.Allocator) void,
    interface_name: [:0]const u8,
    path: [:0]const u8,
    intro_xml: []const u8,
};

This wrapper connects:

  • path: The object path (like /com/example/MyService).
  • interface_name: The interface namespace (like com.example.MyService).
  • instance: A pointer to your struct instance.
  • dispatch_fn: An auto-generated function that decodes arguments, injects context parameters, executes your method, and packages the return value into a reply message.

#Memory Ownership and Lifetimes

Memory management in IPC libraries is usually a minefield. Goose keeps lifetimes predictable:

  1. Method Calls (MethodResult): When you call a method, the returned MethodResult holds an arena allocator tied to that reply. Calling expect(T) borrows strings and slices directly from the reply buffer without duplicating them.
  2. Long-Lived Data (expectAlloc): If you need the decoded data to live longer than the MethodResult, call expectAlloc(T). This deep-copies all slices into your connection allocator so you can safely call result.deinit().
  3. Descriptors: Any file descriptor passed over the wire that your code does not explicitly take or duplicate is automatically closed when freeMessage() runs.