Socket Passing for Auto-Reloading ServersPermalink

Armin Ronacher:

But what about the socket? The solution to this problem I picked comes from systemd. Systemd has a “protocol” that standardizes passing file descriptors from one process to another through environment variables. In systemd parlance this is called “socket activation,” as it allows systemd to only launch a program if someone started making a request to the socket. This concept was originally introduced by Apple as part of launchd.

To make this work with Rust, I created two crates:

  • systemfd is the command line tool that opens sockets and passes them on to other programs.
  • listenfd is a Rust crate that accepts file descriptors from systemd or systemfd.

It’s worth noting that systemfd is not exclusively useful to Rust. The systemd protocol can be implemented in other languages as well, meaning that if you have a socket server written in Go or Python, you can also use systemfd.

For projects like Linked List I currently use something like

watchexec -w src -r 'cargo run --bin linkedlistd'

to restart the server when the source changes. As Armin points out in this post there is a window in which there server is down, so if you hit F5 to reload the page during that window you get a connection error. With the presented solution the systemfd tool always has the socket open and socket passing will hand it to the server when its back up—neat. I’ll have to incorporate this into the Linked List code.