#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 and Authentication Sequence
Step-by-step protocol sequence from initial socket connection to active D-Bus session.
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_ADDRESSenvironment variable (typically something likeunix:path=/run/user/1000/bus). - System Bus: Connects to the standard well-known path
/var/run/dbus/system_bus_socketor readsDBUS_SYSTEM_BUS_ADDRESS. - Accessibility Bus: Reads
AT_SPI_BUS_ADDRESSor queries the X11 root window.
#2. The SASL `EXTERNAL` Handshake
D-Bus requires authentication before switching to binary protocol framing:
- The Null Byte: Goose transmits a single
\0byte right after connecting. In Linux, sending this byte allows the kernel to verify peer credentials on Unix domain sockets viaSO_PEERCRED. - User Identity: Goose sends
AUTH EXTERNAL <hex-encoded UID>\r\n. For example, if your UID is1000, it sends ASCII hex31303030. The bus daemon replies withOK <guid>. - Unix File Descriptor Negotiation: Goose asks
NEGOTIATE_UNIX_FD\r\n. The daemon acknowledges withAGREE_UNIX_FD. This tells both sides that file descriptors can be passed out-of-band usingSCM_RIGHTS. - Binary Protocol Switch: Goose sends
BEGIN\r\nand immediately switches the socket to binary D-Bus message framing. - The
HelloGreeting: Goose callsHelloonorg.freedesktop.DBusto 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:
/// 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 Backend Architecture
Toggle between Goose's two execution modes to see how messages are processed.
recvmsg()Wakes the waiting caller thread immediately using an atomic futex.
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.
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
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:
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 (likecom.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:
- Method Calls (
MethodResult): When you call a method, the returnedMethodResultholds an arena allocator tied to that reply. Callingexpect(T)borrows strings and slices directly from the reply buffer without duplicating them. - Long-Lived Data (
expectAlloc): If you need the decoded data to live longer than theMethodResult, callexpectAlloc(T). This deep-copies all slices into your connection allocator so you can safely callresult.deinit(). - Descriptors: Any file descriptor passed over the wire that your code does not explicitly take or duplicate is automatically closed when
freeMessage()runs.