Compare commits

3 Commits

Author SHA1 Message Date
Alexander Heldt
a1971693ef TCP echo server 2025-11-14 18:41:29 +01:00
Alexander Heldt
28b29d3dbf Send some messages 2025-11-14 18:39:51 +01:00
Alexander Heldt
77f441dea4 Add tcp module 2025-11-14 18:39:23 +01:00
8 changed files with 488 additions and 6 deletions

View File

@@ -14,6 +14,9 @@ version = "1.0.0"
[dependencies]
gleam_stdlib = ">= 0.44.0 and < 2.0.0"
gleam_otp = ">= 1.2.0 and < 2.0.0"
gleam_erlang = ">= 1.3.0 and < 2.0.0"
simplifile = ">= 2.3.1 and < 3.0.0"
[dev-dependencies]
gleeunit = ">= 1.0.0 and < 2.0.0"

View File

@@ -2,10 +2,17 @@
# You typically do not need to edit this file
packages = [
{ name = "filepath", version = "1.1.2", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "filepath", source = "hex", outer_checksum = "B06A9AF0BF10E51401D64B98E4B627F1D2E48C154967DA7AF4D0914780A6D40A" },
{ name = "gleam_erlang", version = "1.3.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleam_erlang", source = "hex", outer_checksum = "1124AD3AA21143E5AF0FC5CF3D9529F6DB8CA03E43A55711B60B6B7B3874375C" },
{ name = "gleam_otp", version = "1.2.0", build_tools = ["gleam"], requirements = ["gleam_erlang", "gleam_stdlib"], otp_app = "gleam_otp", source = "hex", outer_checksum = "BA6A294E295E428EC1562DC1C11EA7530DCB981E8359134BEABC8493B7B2258E" },
{ name = "gleam_stdlib", version = "0.65.0", build_tools = ["gleam"], requirements = [], otp_app = "gleam_stdlib", source = "hex", outer_checksum = "7C69C71D8C493AE11A5184828A77110EB05A7786EBF8B25B36A72F879C3EE107" },
{ name = "gleeunit", version = "1.9.0", build_tools = ["gleam"], requirements = ["gleam_stdlib"], otp_app = "gleeunit", source = "hex", outer_checksum = "DA9553CE58B67924B3C631F96FE3370C49EB6D6DC6B384EC4862CC4AAA718F3C" },
{ name = "simplifile", version = "2.3.1", build_tools = ["gleam"], requirements = ["filepath", "gleam_stdlib"], otp_app = "simplifile", source = "hex", outer_checksum = "957E0E5B75927659F1D2A1B7B75D7B9BA96FAA8D0C53EA71C4AD9CD0C6B848F6" },
]
[requirements]
gleam_erlang = { version = ">= 1.3.0 and < 2.0.0" }
gleam_otp = { version = ">= 1.2.0 and < 2.0.0" }
gleam_stdlib = { version = ">= 0.44.0 and < 2.0.0" }
gleeunit = { version = ">= 1.0.0 and < 2.0.0" }
simplifile = { version = ">= 2.3.1 and < 3.0.0" }

View File

@@ -1,5 +1,5 @@
import gleam/io
pub fn main() -> Nil {
io.println("Hello from musicplayer!")
io.println("musicplayer")
}

81
src/tcp/echo_server.gleam Normal file
View File

@@ -0,0 +1,81 @@
import gleam/erlang/process.{type Subject}
import gleam/io
import gleam/otp/actor
import gleam/result
import gleam/string
import tcp/reason.{type Reason}
import tcp/tcp
pub type Message {
Shutdown
ReadyToAccept(subject: Subject(Message), listen_socket: tcp.Socket)
}
pub fn new(socket_path: String) -> Result(tcp.Socket, String) {
let server = actor.new(Nil) |> actor.on_message(handle_message) |> actor.start
case tcp.listen(socket_path), server {
Error(r), _ -> Error(reason.to_string(r))
_, Error(start_error) ->
case start_error {
actor.InitExited(_) -> Error("InitExited")
actor.InitFailed(_) -> Error("InitFailed")
actor.InitTimeout -> Error("InitTimeout")
}
Ok(listen_socket), Ok(b) -> {
let subject = b.data
actor.send(subject, ReadyToAccept(subject, listen_socket))
Ok(listen_socket)
}
}
}
fn handle_message(_: Nil, message: Message) -> actor.Next(Nil, Message) {
case message {
Shutdown -> actor.stop()
ReadyToAccept(subject, listen_socket) -> {
case tcp.accept(listen_socket) {
Error(r) ->
actor.stop_abnormal(
"Could not accept connection :" <> reason.to_string(r),
)
Ok(socket) -> {
case receive_from_connection(socket) {
Error(r) ->
io.println_error(
"Failed to receive from connection :" <> reason.to_string(r),
)
Ok(_) -> Nil
}
actor.send(subject, ReadyToAccept(subject, listen_socket))
actor.continue(Nil)
}
}
}
}
}
fn receive_from_connection(socket: tcp.Socket) -> Result(Nil, Reason) {
result.try(receive_until_closed(socket, ""), fn(data) {
let _ = tcp.send(socket, data)
tcp.close(socket)
Ok(Nil)
})
}
fn receive_until_closed(
socket: tcp.Socket,
result: String,
) -> Result(String, Reason) {
case tcp.receive(socket, 10_000) {
Error(reason.Closed) -> Ok(result)
Error(err) -> Error(err)
Ok(data) -> {
let result = data |> string.append(result, _)
receive_until_closed(socket, result)
}
}
}

243
src/tcp/reason.gleam Normal file
View File

@@ -0,0 +1,243 @@
pub type Reason {
/// from `connect`
Timeout
/// from `send`
Closed
Overflow
/// Address already in use
Eaddrinuse
/// Cannot assign requested address
Eaddrnotavail
/// Address family not supported by protocol family
Eafnosupport
/// Operation already in progress
Ealready
/// Software caused connection abort
Econnaborted
/// Connection refused
Econnrefused
/// Connection reset by peer
Econnreset
/// Destination address required
Edestaddrreq
/// Host is down
Ehostdown
/// Host is unreachable
Ehostunreach
/// Operation now in progress
Einprogress
/// Socket is already connected
Eisconn
/// Message too long
Emsgsize
/// Network is down
Enetdown
/// Network is unreachable
Enetunreach
/// Package not installed
Enopkg
/// Bad protocol option
Enoprotoopt
/// Socket is not connected
Enotconn
/// Inappropriate device for ioctl
Enotty
/// Socket operation on non-socket
Enotsock
/// Protocol error
Eproto
/// Protocol not supported
Eprotonosupport
/// Wrong protocol type for socket
Eprototype
/// Socket type not supported
Esocktnosupport
/// Connection timed out
Etimedout
/// Operation would block
Ewouldblock
/// Invalid exchange
Exbadport
/// Invalid sequence number
Exbadseq
/// Permission denied
Eacces
/// Resource temporarily unavailable
Eagain
/// Bad file number
Ebadf
/// Not a data message
Ebadmsg
/// File busy
Ebusy
/// Resource deadlock avoided
Edeadlk
/// Resource deadlock avoided
Edeadlock
/// Disk quota exceeded
Edquot
/// File already exists
Eexist
/// Bad address in system call argument
Efault
/// File too large
Efbig
/// Inappropriate file type or format
Eftype
/// Interrupted system call
Eintr
/// Invalid argument
Einval
/// I/O error
Eio
/// Illegal operation on a directory
Eisdir
/// Too many levels of symbolic links
Eloop
/// Too many open files
Emfile
/// Too many links
Emlink
/// Multihop attempted
Emultihop
/// Filename too long
Enametoolong
/// File table overflow
Enfile
/// No buffer space available
Enobufs
/// No such device
Enodev
/// No locks available
Enolck
/// Link has been severed
Enolink
/// No such file or directory
Enoent
/// Not enough memory
Enomem
/// No space left on device
Enospc
/// Out of stream resources or not a stream device
Enosr
/// Not a stream device
Enostr
/// Function not implemented
Enosys
/// Block device required
Enotblk
/// Not a directory
Enotdir
/// Operation not supported
Enotsup
/// No such device or address
Enxio
/// Operation not supported on socket
Eopnotsupp
/// Value too large for defined data type
Eoverflow
/// Not owner
Eperm
/// Broken pipe
Epipe
/// Math result unrepresentable
Erange
/// Read-only filesystem
Erofs
/// Invalid seek
Espipe
/// No such process
Esrch
/// Stale remote file handle
Estale
/// Text file or pseudo-device busy
Etxtbsy
/// Cross-device link
Exdev
}
pub fn to_string(reason: Reason) -> String {
case reason {
Overflow -> "overflow"
Closed -> "Connection closed (closed)"
Eacces -> "Permission denied (eacces)"
Eaddrinuse -> "Address already in use (eaddrinuse)"
Eaddrnotavail -> "Cannot assign requested address (eaddrnotavail)"
Eafnosupport ->
"Address family not supported by protocol family (eafnosupport)"
Eagain -> "Resource temporarily unavailable (eagain)"
Ealready -> "Operation already in progress (ealready)"
Ebadf -> "Bad file number (ebadf)"
Ebadmsg -> "Not a data message (ebadmsg)"
Ebusy -> "File busy (ebusy)"
Econnaborted -> "Software caused connection abort (econnaborted)"
Econnrefused -> "Connection refused (econnrefused)"
Econnreset -> "Connection reset by peer (econnreset)"
Edeadlk -> "Resource deadlock avoided (edeadlk)"
Edeadlock -> "Resource deadlock avoided (edeadlock)"
Edestaddrreq -> "Destination address required (edestaddrreq)"
Edquot -> "Disk quota exceeded (edquot)"
Eexist -> "File already exists (eexist)"
Efault -> "Bad address in system call argument (efault)"
Efbig -> "File too large (efbig)"
Eftype -> "Inappropriate file type or format (eftype)"
Ehostdown -> "Host is down (ehostdown)"
Ehostunreach -> "Host is unreachable (ehostunreach)"
Einprogress -> "Operation now in progress (einprogress)"
Eintr -> "Interrupted system call (eintr)"
Einval -> "Invalid argument (einval)"
Eio -> "I/O error (eio)"
Eisconn -> "Socket is already connected (eisconn)"
Eisdir -> "Illegal operation on a directory (eisdir)"
Eloop -> "Too many levels of symbolic links (eloop)"
Emfile -> "Too many open files (emfile)"
Emlink -> "Too many links (emlink)"
Emsgsize -> "Message too long (emsgsize)"
Emultihop -> "Multihop attempted (emultihop)"
Enametoolong -> "Filename too long (enametoolong)"
Enetdown -> "Network is down (enetdown)"
Enetunreach -> "Network is unreachable (enetunreach)"
Enfile -> "File table overflow (enfile)"
Enobufs -> "No buffer space available (enobufs)"
Enodev -> "No such device (enodev)"
Enoent -> "No such file or directory (enoent)"
Enolck -> "No locks available (enolck)"
Enolink -> "Link has been severed (enolink)"
Enomem -> "Not enough memory (enomem)"
Enopkg -> "Package not installed (enopkg)"
Enoprotoopt -> "Bad protocol option (enoprotoopt)"
Enospc -> "No space left on device (enospc)"
Enosr -> "Out of stream resources or not a stream device (enosr)"
Enostr -> "Not a stream device (enostr)"
Enosys -> "Function not implemented (enosys)"
Enotblk -> "Block device required (enotblk)"
Enotconn -> "Socket is not connected (enotconn)"
Enotdir -> "Not a directory (enotdir)"
Enotsock -> "Socket operation on non-socket (enotsock)"
Enotsup -> "Operation not supported (enotsup)"
Enotty -> "Inappropriate device for ioctl (enotty)"
Enxio -> "No such device or address (enxio)"
Eopnotsupp -> "Operation not supported on socket (eopnotsupp)"
Eoverflow -> "Value too large for defined data type (eoverflow)"
Eperm -> "Not owner (eperm)"
Epipe -> "Broken pipe (epipe)"
Eproto -> "Protocol error (eproto)"
Eprotonosupport -> "Protocol not supported (eprotonosupport)"
Eprototype -> "Wrong protocol type for socket (eprototype)"
Erange -> "Math result unrepresentable (erange)"
Erofs -> "Read-only filesystem (erofs)"
Esocktnosupport -> "Socket type not supported (esocktnosupport)"
Espipe -> "Invalid seek (espipe)"
Esrch -> "No such process (esrch)"
Estale -> "Stale remote file handle (estale)"
Etimedout -> "Connection timed out (etimedout)"
Etxtbsy -> "Text file or pseudo-device busy (etxtbsy)"
Ewouldblock -> "Operation would block (ewouldblock)"
Exbadport -> "Invalid exchange (exbadport)"
Exbadseq -> "Invalid sequence number (exbadseq)"
Exdev -> "Cross-device link (exdev)"
Timeout -> "Operation timed out (timeout)"
}
}

117
src/tcp/tcp.gleam Normal file
View File

@@ -0,0 +1,117 @@
import gleam/bit_array
import gleam/erlang/atom
import gleam/result
import tcp/reason.{type Reason}
pub type Socket
// https://www.erlang.org/doc/apps/kernel/inet#t:address_family/0
// local socket
type Local {
Local(socket_path: String)
}
type ModeValue {
Binary
}
type TCPOption {
Active(Bool)
Mode(ModeValue)
Reuseaddr(Bool)
Ifaddr(Local)
ExitOnClose(Bool)
}
pub fn listen(socket_path: String) -> Result(Socket, Reason) {
let options = [
Mode(Binary),
Active(False),
Reuseaddr(True),
Ifaddr(Local(socket_path)),
ExitOnClose(False),
]
// port zero with `local` address
let port = 0
gen_tcp_listen(port, options)
}
pub fn accept(listen_socket: Socket) -> Result(Socket, Reason) {
gen_tcp_accept(listen_socket)
}
pub fn receive(socket: Socket, timeout: Int) -> Result(String, Reason) {
// Get all bytes
let length = 0
use bits <- result.try(gen_tcp_recv(socket, length, timeout))
case bits |> bit_array.to_string {
// TODO what error is best?
Error(_) -> Error(reason.Ebadmsg)
Ok(s) -> Ok(s)
}
}
pub fn connect(socket_path: String) -> Result(Socket, Reason) {
let options = [Mode(Binary), Active(False)]
// port zero with `local` address
let port = 0
// timeout in ms
let timeout = 1000
gen_tcp_connect(Local(socket_path), port, options, timeout)
}
pub fn send(socket: Socket, message: String) -> Result(Nil, Reason) {
gen_tcp_send(socket, bit_array.from_string(message))
}
pub fn close(socket: Socket) -> Nil {
gen_tcp_close(socket)
}
pub fn shutdown(socket: Socket) -> Result(Nil, Reason) {
let how = atom.create("write")
gen_tcp_shutdown(socket, how)
}
// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#listen/2
@external(erlang, "gen_tcp", "listen")
fn gen_tcp_listen(port: Int, option: List(TCPOption)) -> Result(Socket, Reason)
// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#accept/1
@external(erlang, "gen_tcp", "accept")
fn gen_tcp_accept(listen_socket: Socket) -> Result(Socket, Reason)
// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#recv/3
@external(erlang, "gen_tcp", "recv")
fn gen_tcp_recv(
socket: Socket,
length: Int,
timeout: Int,
) -> Result(BitArray, Reason)
// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#connect/4
@external(erlang, "gen_tcp", "connect")
fn gen_tcp_connect(
address: Local,
port: Int,
options: List(TCPOption),
timeout: Int,
) -> Result(Socket, Reason)
// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#send/2
@external(erlang, "tcp_ffi", "send")
fn gen_tcp_send(socket: Socket, packet: BitArray) -> Result(Nil, Reason)
// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#close/1
@external(erlang, "gen_tcp", "close")
fn gen_tcp_close(socket: Socket) -> Nil
// https://www.erlang.org/doc/apps/kernel/gen_tcp.html#shutdown/2
@external(erlang, "tcp_ffi", "shutdown")
fn gen_tcp_shutdown(socket: Socket, how: atom.Atom) -> Result(Nil, Reason)

14
src/tcp/tcp_ffi.erl Normal file
View File

@@ -0,0 +1,14 @@
-module(tcp_ffi).
-export([send/2, shutdown/2]).
send(Socket, Packet) ->
case gen_tcp:send(Socket, Packet) of
ok -> {ok, nil};
Res -> Res
end.
shutdown(Socket, How) ->
case gen_tcp:shutdown(Socket, How) of
ok -> {ok, nil};
Res -> Res
end.

View File

@@ -1,13 +1,30 @@
import gleam/list
import gleeunit
import simplifile
import tcp/echo_server
import tcp/tcp
pub fn main() -> Nil {
gleeunit.main()
}
// gleeunit test functions end in `_test`
pub fn hello_world_test() {
let name = "Joe"
let greeting = "Hello, " <> name <> "!"
pub fn tcp_send_shutdown_receive_test() {
let socket_path = "/tmp/musicplayer-test.sock"
assert greeting == "Hello, Joe!"
let assert Ok(_) = echo_server.new(socket_path)
let assert Ok(socket) = tcp.connect(socket_path)
let messages = ["hello, ", "world!\n"]
list.each(messages, fn(message) {
let assert Ok(_) = tcp.send(socket, message)
})
let assert Ok(_) = tcp.shutdown(socket)
let timeout_ms = 100
assert Ok("hello, world!\n") == tcp.receive(socket, timeout_ms)
// TODO find better way to always do cleanup
simplifile.delete(socket_path)
}