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

Network – POSIX Sockets with Phantom State

Lean: Hale.Network | Haskell: network

POSIX socket API with phantom type parameters encoding lifecycle states. A Socket (state : SocketState) tracks state transitions (fresh → bound → listening → connected → closed) at compile time, making it a type error to send on an unconnected socket or close an already-closed one.

Socket State Machine

  Fresh ──bind──► Bound ──listen──► Listening ──accept──► Connected
    │                                                         │
    └──────────────────── close ◄─────────────────────────────┘

Key Types

TypeDescription
Socket (state : SocketState)Phantom-typed socket
SocketState.fresh | .bound | .listening | .connected | .closed
SockAddrSocket address
AcceptOutcome / RecvOutcome / SendOutcomeNon-blocking I/O outcomes
RecvBufferBuffered reader with CRLF scanning (C FFI)
EventDispatcherGreen thread suspension bridge (kqueue/epoll)

API

FunctionState TransitionSignature
socket.freshIO (Socket .fresh)
bind.fresh.boundSocket .fresh → SockAddr → IO (Socket .bound)
listen.bound.listeningSocket .bound → Nat → IO (Socket .listening)
accept.listening.connectedSocket .listening → IO (Socket .connected × SockAddr)
connect.fresh.connectedSocket .fresh → SockAddr → IO (Socket .connected)
sendrequires .connectedSocket .connected → ByteArray → IO Nat
recvrequires .connectedSocket .connected → Nat → IO ByteArray
closeany → .closedSocket s → IO Unit

Files

  • Hale/Network/Network/Socket/Types.lean – SocketState, SockAddr, phantom socket type
  • Hale/Network/Network/Socket/FFI.lean – C FFI declarations
  • Hale/Network/Network/Socket.lean – High-level API with state transitions
  • Hale/Network/Network/Socket/ByteString.lean – ByteArray send/recv
  • Hale/Network/Network/Socket/Blocking.lean – Blocking wrappers
  • Hale/Network/Network/Socket/EventDispatcher.lean – kqueue/epoll dispatcher