velt/dev
import { joinStop, drained } from "velt/dev". What a program run by velt dev
(hot reload) takes part in: the graceful stop before its next version
starts. A server joins it so that no request in flight is cut off. The
HTTP server package does this for you; use this module for a
server of your own, such as one on velt/net's TCP listener.
joinStop(): AbortSignal | nulljoins the graceful stop. The signal is aborted oncevelt devasks the program to stop for its next version. Then stop taking work (close the listener; the supervisor keeps the listening socket, so new connections wait for the next version), finish what is in flight, and calldrained(). Outsidevelt devit returnsnull, and nothing waits.drained()says that what joined has finished. The program exits once everything that joined has drained, or after a bounded wait (1 s); the supervisor stops a program that is still running 1.5 s after asking.
ts
import { joinStop, drained } from "velt/dev";
import { listen, TcpListener, TcpStream } from "velt/net";
async function closeOnStop(stop: AbortSignal, listener: TcpListener) {
await stop.whenAborted();
listener.close(); // the accept loop below ends
}
async function handle(conn: TcpStream) {
await conn.write("hello\n");
conn.close();
}
const listener = await listen("127.0.0.1:8080");
const stop = joinStop();
if (stop != null) {
// Under `velt dev`: stop accepting when the next version is about to start.
const closing = spawn(closeOnStop(stop, listener));
}
try {
for (;;) {
const conn = await listener.accept();
await handle(conn);
}
} catch (e) {
// the listener was closed
}
if (stop != null) {
drained();
}