From 598da1d0904e1ec5b2efecc633ddd2ec0351d0dc Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Sat, 14 Nov 2026 17:38:41 -0500 Subject: [PATCH] refactor(daemon): rewrite albedo_transfers in Gleam Staging file operations, df's free space, the home identity and the one-worker-per-transfer protocol move to transfer_files.gleam. The worker keeps its global name {albedo_transfer, Key}. port_program.gleam reads a port's own messages for programs the daemon runs. --- src/albedo/daemon/albedo_transfers.erl | 367 ------------- src/albedo/daemon/port_program.gleam | 135 +++++ src/albedo/daemon/transfer.gleam | 20 +- src/albedo/daemon/transfer_files.gleam | 688 +++++++++++++++++++++++++ src/albedo/daemon/transfers.gleam | 129 ++--- test/daemon/albedo_transfers_test.erl | 4 +- 6 files changed, 883 insertions(+), 460 deletions(-) delete mode 100644 src/albedo/daemon/albedo_transfers.erl create mode 100644 src/albedo/daemon/port_program.gleam create mode 100644 src/albedo/daemon/transfer_files.gleam diff --git a/src/albedo/daemon/albedo_transfers.erl b/src/albedo/daemon/albedo_transfers.erl deleted file mode 100644 index 5bb8ee33c..000000000 --- a/src/albedo/daemon/albedo_transfers.erl +++ /dev/null @@ -1,367 +0,0 @@ -%% Transfer staging on disk: bounded copies, digests, resumable appends and free space. --module(albedo_transfers). --export([ - regular_files/1, - is_regular/1, - copy_file/3, - write_file/2, - digest/1, - append_at/4, - file_size/1, - free_bytes/1, - identity/1, - remove_tree/1, - ensure_dir/1, - rename/2, - tree_bytes/1, - private/1, - install_file/2, - run_once/2 -]). --include_lib("kernel/include/file.hrl"). - --define(chunk, 524288). - -regular_files(Dir) -> - case file:list_dir(Dir) of - {ok, Names} -> - {ok, - lists:sort([ - unicode:characters_to_binary(N) - || N <- Names, - is_regular(filename:join(Dir, N)) - ])}; - {error, enoent} -> - {ok, []}; - {error, Reason} -> - {error, reason(Dir, Reason)} - end. - -is_regular(Path) -> - case file:read_link_info(Path) of - {ok, #file_info{type = regular}} -> true; - _ -> false - end. - -%% Copies `Source` to a new file `Target`, hashing as it goes. Answers {Bytes, Digest}. -copy_file(Source, Target, MaxBytes) -> - case file:open(Source, [read, raw, binary]) of - {ok, In} -> - try - case file:open(Target, [write, exclusive, raw, binary]) of - {ok, Out} -> - ok = file:change_mode(Target, 8#600), - Result = - try - copy(In, Out, crypto:hash_init(sha256), 0, MaxBytes) - after - file:close(Out) - end, - case Result of - {ok, _} -> - Result; - _ -> - file:delete(Target), - Result - end; - {error, Reason} -> - {error, reason(Target, Reason)} - end - after - file:close(In) - end; - {error, Reason} -> - {error, reason(Source, Reason)} - end. - -copy(In, Out, Hash, Bytes, Max) -> - case file:read(In, ?chunk) of - eof -> - ok = file:sync(Out), - {ok, {Bytes, hex(crypto:hash_final(Hash))}}; - {ok, Data} when Bytes + byte_size(Data) > Max -> - {error, <<"file is larger than its transfer allows">>}; - {ok, Data} -> - case file:write(Out, Data) of - ok -> copy(In, Out, crypto:hash_update(Hash, Data), Bytes + byte_size(Data), Max); - {error, Reason} -> {error, reason(<<"transfer file">>, Reason)} - end; - {error, Reason} -> - {error, reason(<<"transfer file">>, Reason)} - end. - -write_file(Target, Bytes) -> - case file:open(Target, [write, exclusive, raw, binary]) of - {ok, Out} -> - try - ok = file:change_mode(Target, 8#600), - ok = file:write(Out, Bytes), - ok = file:sync(Out), - {ok, {byte_size(Bytes), hex(crypto:hash(sha256, Bytes))}} - after - file:close(Out) - end; - {error, Reason} -> - {error, reason(Target, Reason)} - end. - -digest(Path) -> - case file:open(Path, [read, raw, binary]) of - {ok, In} -> - try - {ok, hash(In, crypto:hash_init(sha256))} - after - file:close(In) - end; - {error, Reason} -> - {error, reason(Path, Reason)} - end. - -hash(In, Hash) -> - case file:read(In, ?chunk) of - eof -> hex(crypto:hash_final(Hash)); - {ok, Data} -> hash(In, crypto:hash_update(Hash, Data)) - end. - -%% Writes `Bytes` at `Offset` of a partial file no longer than `Limit`. A -%% repeat of bytes already there is accepted; a gap or different bytes are not. -append_at(Path, Offset, Bytes, Limit) -> - Size = - case file:read_file_info(Path) of - {ok, #file_info{size = S}} -> S; - {error, enoent} -> 0 - end, - End = Offset + byte_size(Bytes), - if - Offset < 0 -> - {error, <<"offset is negative">>}; - End > Limit -> - {error, <<"chunk runs past the segment's length">>}; - Offset > Size -> - {error, <<"chunk leaves a gap; resume at ", (integer_to_binary(Size))/binary>>}; - End =< Size -> - {ok, Fd} = file:open(Path, [read, raw, binary]), - Held = - try - file:pread(Fd, Offset, byte_size(Bytes)) - after - file:close(Fd) - end, - case Held of - {ok, Bytes} -> {ok, Size}; - _ when Bytes =:= <<>> -> {ok, Size}; - _ -> {error, <<"chunk differs from bytes already received">>} - end; - true -> - {ok, Fd} = file:open(Path, [read, write, raw, binary]), - Offset =:= 0 andalso file:change_mode(Path, 8#600), - try - ok = file:pwrite(Fd, Offset, Bytes), - ok = file:datasync(Fd), - {ok, End} - after - file:close(Fd) - end - end. - -file_size(Path) -> - case file:read_file_info(Path) of - {ok, #file_info{size = S}} -> S; - _ -> 0 - end. - -tree_bytes(Dir) -> - case file:list_dir(Dir) of - {ok, Names} -> lists:sum([file_size(filename:join(Dir, N)) || N <- Names]); - _ -> 0 - end. - -%% Free bytes on the filesystem holding `Path`, from df's POSIX output. -free_bytes(Path) -> - case os:find_executable("df") of - false -> - {error, <<"df is not on PATH">>}; - Df -> - Port = open_port( - {spawn_executable, Df}, - [{args, ["-Pk", Path]}, exit_status, binary, stderr_to_stdout] - ), - case collect(Port, <<>>) of - {0, Output} -> - case binary:split(Output, <<"\n">>, [global, trim_all]) of - [_, Line | _] -> - case string:lexemes(Line, " ") of - [_, _, _, Available | _] -> - {ok, binary_to_integer(Available) * 1024}; - _ -> - {error, <<"df answered an unexpected line">>} - end; - _ -> - {error, <<"df answered nothing">>} - end; - {_, Output} -> - {error, string:trim(Output)} - end - end. - -collect(Port, Acc) -> - receive - {Port, {data, Data}} -> collect(Port, <>); - {Port, {exit_status, Status}} -> {Status, Acc} - after 10000 -> - try - port_close(Port) - catch - _:_ -> ok - end, - {1, <<"df did not answer">>} - end. - -%% This home's durable identity, made once. Two first callers at once each -%% write their own candidate and link it into place; the one that loses -%% reads the winner's. -identity(Home) -> - Path = filename:join(Home, <<"identity">>), - case file:read_file(Path) of - {ok, Id} -> - {ok, string:trim(Id)}; - {error, enoent} -> - Id = hex(crypto:strong_rand_bytes(16)), - Partial = <>, - ok = file:write_file(Partial, Id, [sync]), - Linked = file:make_link(Partial, Path), - _ = file:delete(Partial), - case Linked of - ok -> {ok, Id}; - {error, eexist} -> identity(Home); - {error, Reason} -> {error, reason(Path, Reason)} - end; - {error, Reason} -> - {error, reason(Path, Reason)} - end. - -remove_tree(Path) -> - case file:del_dir_r(Path) of - ok -> {ok, nil}; - {error, enoent} -> {ok, nil}; - {error, Reason} -> {error, reason(Path, Reason)} - end. - -%% Staging holds session rows and secrets: every directory is the owner's alone. -ensure_dir(Path) -> - case filelib:ensure_path(Path) of - ok -> - private_dirs(Path), - {ok, nil}; - {error, Reason} -> - {error, reason(Path, Reason)} - end. - -private_dirs(Path) -> - Parent = filename:dirname(Path), - ok = file:change_mode(Path, 8#700), - case filename:basename(Path) of - <<"transfers">> -> ok; - _ when Parent =:= Path -> ok; - _ -> private_dirs(Parent) - end. - -private(Path) -> - case file:change_mode(Path, 8#600) of - ok -> {ok, nil}; - {error, Reason} -> {error, reason(Path, Reason)} - end. - -rename(From, To) -> - case file:rename(From, To) of - ok -> {ok, nil}; - {error, Reason} -> {error, reason(From, Reason)} - end. - -hex(Bytes) -> binary:encode_hex(Bytes, lowercase). - -reason(Path, Reason) -> - iolist_to_binary([Path, <<": ">>, atom_to_binary(Reason)]). - -%% Copies `From` to `To` through a temporary name, unless `To` already exists: -%% an install that resumes after a crash repeats nothing it finished. -install_file(From, To) -> - case is_regular(To) of - true -> - {ok, nil}; - false -> - Partial = <>, - _ = file:delete(Partial), - case filelib:ensure_dir(To) of - ok -> - case copy_file(From, Partial, 9223372036854775807) of - {ok, _} -> rename(Partial, To); - {error, _} = Failed -> Failed - end; - {error, Reason} -> - {error, reason(To, Reason)} - end - end. - -%% Runs `Work` in a new process unless one already runs for `Key`. Answers -%% whether this call started it. A call that finds one running wakes it: the -%% worker runs `Work` again once it returns, so a wake that lands after the -%% worker's last read is not lost. The worker leaves the name before it looks -%% for wakes, and a wake it never saw (it exited between the caller's look-up -%% and send) is re-run by the caller's watcher. -run_once(Key, Work) -> - Parent = self(), - Pid = spawn(fun() -> - receive - {Parent, go} -> worker(Key, Work); - {Parent, stop} -> ok - end - end), - case global:register_name({albedo_transfer, Key}, Pid) of - yes -> - Pid ! {Parent, go}, - true; - no -> - Pid ! {Parent, stop}, - wake(Key, Work), - false - end. - -worker(Key, Work) -> - Work(), - global:unregister_name({albedo_transfer, Key}), - case collect_wakes([]) of - [] -> - ok; - Wakers -> - case global:register_name({albedo_transfer, Key}, self()) of - yes -> - [W ! {acked, self()} || W <- Wakers], - worker(Key, Work); - no -> - [W ! {acked, self()} || W <- Wakers], - ok - end - end. - -collect_wakes(Acc) -> - receive - {wake, From} -> collect_wakes([From | Acc]) - after 0 -> Acc - end. - -wake(Key, Work) -> - spawn(fun() -> - case global:whereis_name({albedo_transfer, Key}) of - undefined -> - run_once(Key, Work); - Worker -> - Monitor = erlang:monitor(process, Worker), - Worker ! {wake, self()}, - receive - {acked, Worker} -> erlang:demonitor(Monitor, [flush]); - {'DOWN', Monitor, process, Worker, _} -> run_once(Key, Work) - end - end - end), - ok. diff --git a/src/albedo/daemon/port_program.gleam b/src/albedo/daemon/port_program.gleam new file mode 100644 index 000000000..4d6941c2d --- /dev/null +++ b/src/albedo/daemon/port_program.gleam @@ -0,0 +1,135 @@ +//// Local programs run through Erlang ports, read by the process that opened +//// them. Each receive selects only the port's own messages, so a caller's +//// other mail stays in its mailbox. + +import albedo/harness/sdk/protect +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/erlang/atom +import gleam/erlang/charlist.{type Charlist} +import gleam/erlang/port.{type Port} +import gleam/erlang/process +import gleam/result + +/// `open_port` settings, spelled as the Erlang terms they encode. +pub type Setting { + /// `{args, Args}`. + Args(List(String)) + /// `exit_status`. + ExitStatus + /// `binary`. + Binary + /// `stderr_to_stdout`. + StderrToStdout + /// `hide`. + Hide + /// `use_stdio`. + UseStdio +} + +/// What a port reported. +pub type Event { + /// `{data, Bytes}` from a port opened with `Binary`. + Data(BitArray) + /// `{exit_status, Status}`. + Exited(Int) + /// Any other port message. + Other +} + +type Name { + SpawnExecutable(String) +} + +/// Open `executable` with `settings`. Raises like `erlang:open_port/2`. +pub fn open(executable: String, settings: List(Setting)) -> Port { + open_port(SpawnExecutable(executable), settings) +} + +/// The next message from `port`, or `Error(Nil)` when none arrives within +/// `timeout_ms`. +pub fn next(port: Port, timeout_ms: Int) -> Result(Event, Nil) { + process.new_selector() + |> process.select_record(tag: port, fields: 1, mapping: event) + |> process.selector_receive(timeout_ms) +} + +/// Close `port`, ignoring one that is already closed. +pub fn close(port: Port) -> Nil { + let _ = protect.attempt(fn() { port_close(port) }) + Nil +} + +/// Everything `port` writes until it exits, with its status. Each wait for a +/// message is bounded by `timeout_ms`. A silent port is closed and answers +/// `Error` with the output read so far. +pub fn collect(port: Port, timeout_ms: Int) -> Result(#(Int, BitArray), Nil) { + collect_loop(port, timeout_ms, <<>>) +} + +fn collect_loop( + port: Port, + timeout_ms: Int, + output: BitArray, +) -> Result(#(Int, BitArray), Nil) { + case next(port, timeout_ms) { + Ok(Data(bytes)) -> + collect_loop(port, timeout_ms, <>) + Ok(Exited(status)) -> Ok(#(status, output)) + Ok(Other) -> collect_loop(port, timeout_ms, output) + Error(Nil) -> { + close(port) + Error(Nil) + } + } +} + +/// The path of `name` on `PATH`, as `os:find_executable/1` finds it. +pub fn find_executable(name: String) -> Result(String, Nil) { + let found = find(charlist.from_string(name)) + decode.run(found, decode.list(decode.int)) + |> result.replace(charlist.to_string(unsafe_charlist(found))) + |> result.replace_error(Nil) +} + +/// The OS process id of a port's program. +pub fn os_pid(port: Port) -> Result(Int, Nil) { + let info = port_info(port, atom.create("os_pid")) + decode.run(info, decode.at([1], decode.int)) |> result.replace_error(Nil) +} + +fn event(message: Dynamic) -> Event { + let data = { + use tag <- decode.field(0, atom.decoder()) + use bytes <- decode.field(1, decode.bit_array) + case atom.to_string(tag) { + "data" -> decode.success(Data(bytes)) + _ -> decode.failure(Other, "data") + } + } + let exited = { + use tag <- decode.field(0, atom.decoder()) + use status <- decode.field(1, decode.int) + case atom.to_string(tag) { + "exit_status" -> decode.success(Exited(status)) + _ -> decode.failure(Other, "exit_status") + } + } + decode.run(message, decode.at([1], decode.one_of(data, [exited]))) + |> result.unwrap(Other) +} + +@external(erlang, "erlang", "open_port") +fn open_port(name: Name, settings: List(Setting)) -> Port + +@external(erlang, "erlang", "port_close") +fn port_close(port: Port) -> Bool + +@external(erlang, "erlang", "port_info") +fn port_info(port: Port, item: atom.Atom) -> Dynamic + +@external(erlang, "os", "find_executable") +fn find(name: Charlist) -> Dynamic + +@external(erlang, "gleam_stdlib", "identity") +fn unsafe_charlist(value: Dynamic) -> Charlist diff --git a/src/albedo/daemon/transfer.gleam b/src/albedo/daemon/transfer.gleam index 40782eb7d..97a24c6d4 100644 --- a/src/albedo/daemon/transfer.gleam +++ b/src/albedo/daemon/transfer.gleam @@ -4,6 +4,7 @@ //// transfer carries or as an exclusion with its reason. Extensions declare //// their own tables through `extension.TransferPlugin`. +import albedo/daemon/transfer_files import albedo/harness/runtime import albedo/harness/sdk/extension import albedo/transfer.{RowId, Shift, Transcript} @@ -249,9 +250,9 @@ fn shifts() -> List(transfer.Shift) { fn files(scope: transfer.Scope) -> Result(List(transfer.File), String) { list.try_map(scope.sessions, fn(session) { let captures = scope.home <> "/shell-output/" <> session - use names <- result.try(regular_files(captures)) + use names <- result.try(transfer_files.regular_files(captures)) let state = scope.home <> "/kernels/" <> session <> ".state" - let kernel = case is_regular(state) { + let kernel = case transfer_files.is_regular(state) { True -> [transfer.OnDisk("kernels/" <> session <> ".state", state)] False -> [] } @@ -268,13 +269,6 @@ fn files(scope: transfer.Scope) -> Result(List(transfer.File), String) { |> result.map(list.flatten) } -/// The names of the regular files directly in `directory`; none when it is missing. -@external(erlang, "albedo_transfers", "regular_files") -fn regular_files(directory: String) -> Result(List(String), String) - -@external(erlang, "albedo_transfers", "is_regular") -fn is_regular(path: String) -> Bool - /// Places shell captures and saved kernel state where the target's daemon /// keeps them; a file already there is kept, so a resumed install repeats /// nothing. A kernel state that cannot be placed is reported, not fatal. @@ -291,17 +285,13 @@ fn install( let target = scope.home <> "/" <> file.name case string.starts_with(file.name, "kernels/") { True -> - case install_file(file.path, target) { + case transfer_files.install_file(file.path, target) { Ok(_) -> Ok(lost) Error(_) -> Ok(list.append(lost, ["python namespace"])) } False -> - install_file(file.path, target) + transfer_files.install_file(file.path, target) |> result.replace(lost) } }) } - -/// Copies `from` to `to` through a temporary name, unless `to` exists. -@external(erlang, "albedo_transfers", "install_file") -fn install_file(from: String, to: String) -> Result(Nil, String) diff --git a/src/albedo/daemon/transfer_files.gleam b/src/albedo/daemon/transfer_files.gleam new file mode 100644 index 000000000..96b21282b --- /dev/null +++ b/src/albedo/daemon/transfer_files.gleam @@ -0,0 +1,688 @@ +//// Transfer staging on disk: bounded copies, digests, resumable appends, free +//// space, the home's identity, and one worker per transfer. +//// +//// Errors name the path and the posix reason, as in `"/path: enoent"`. + +import albedo/daemon/port_program +import albedo/harness/sdk/digest +import albedo/harness/sdk/file_status +import albedo/harness/sdk/term +import gleam/bit_array +import gleam/crypto +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/erlang/atom.{type Atom} +import gleam/erlang/charlist.{type Charlist} +import gleam/erlang/process.{type Pid} +import gleam/int +import gleam/list +import gleam/result +import gleam/string + +const chunk = 524_288 + +type Device + +/// `file:open` modes, spelled as the atoms they encode. +type Mode { + Read + Write + Exclusive + Raw + Binary +} + +/// What `file:read` answered. +type Chunk { + Bytes(BitArray) + Eof + Failed(Dynamic) +} + +/// The names of the regular files directly in `directory`, sorted. A missing +/// directory has none. +pub fn regular_files(directory: String) -> Result(List(String), String) { + case list_dir(directory) { + Ok(names) -> + names + |> list.map(characters_to_binary) + |> list.filter(fn(name) { is_regular(join(directory, name)) }) + |> term.sort + |> Ok + Error(reason) -> + case reason == enoent() { + True -> Ok([]) + False -> Error(reason_text(directory, reason)) + } + } +} + +/// Whether `path` itself is a regular file. A symbolic link is not. +pub fn is_regular(path: String) -> Bool { + case file_status.link_status(path) { + Ok(file_status.Status(kind: file_status.Regular, ..)) -> True + _ -> False + } +} + +/// Copy `source` to a new private file `target`, hashing as it goes, and +/// answer its size and SHA-256. A copy past `max_bytes` fails and removes +/// `target`. +pub fn copy_file( + source: String, + target: String, + max_bytes: Int, +) -> Result(#(Int, String), String) { + case open(source, [Read, Raw, Binary]) { + Error(reason) -> Error(reason_text(source, reason)) + Ok(input) -> { + let copied = case open(target, [Write, Exclusive, Raw, Binary]) { + Error(reason) -> Ok(Error(reason_text(target, reason))) + Ok(output) -> { + let copied = case is_ok(change_mode(target, 0o600)) { + True -> + copy( + input, + output, + crypto.new_hasher(crypto.Sha256), + 0, + max_bytes, + ) + False -> Error(Nil) + } + let _ = close(output) + case copied { + Ok(Error(_)) -> { + let _ = delete(target) + copied + } + _ -> copied + } + } + } + let _ = close(input) + // A mode or sync failure raises after both files close. + let assert Ok(result) = copied as "transfer copy failed" + result + } + } +} + +/// The copy's answer, or `Error(Nil)` when the target could not be synced. +fn copy( + input: Device, + output: Device, + hasher: crypto.Hasher, + bytes: Int, + max: Int, +) -> Result(Result(#(Int, String), String), Nil) { + case read(input) { + Eof -> + case is_ok(sync(output)) { + True -> Ok(Ok(#(bytes, digest.hex(crypto.digest(hasher))))) + False -> Error(Nil) + } + Bytes(data) -> + case bytes + bit_array.byte_size(data) > max { + True -> Ok(Error("file is larger than its transfer allows")) + False -> { + let written = write(output, data) + case is_ok(written) { + True -> + copy( + input, + output, + crypto.hash_chunk(hasher, data), + bytes + bit_array.byte_size(data), + max, + ) + False -> + Ok(Error(reason_text("transfer file", error_reason(written)))) + } + } + } + Failed(reason) -> Ok(Error(reason_text("transfer file", reason))) + } +} + +/// Write `bytes` to a new private file `target`, synced, and answer its size +/// and SHA-256. +pub fn write_file( + target: String, + bytes: BitArray, +) -> Result(#(Int, String), String) { + case open(target, [Write, Exclusive, Raw, Binary]) { + Error(reason) -> Error(reason_text(target, reason)) + Ok(output) -> { + let written = + is_ok(change_mode(target, 0o600)) + && is_ok(write(output, bytes)) + && is_ok(sync(output)) + let _ = close(output) + let assert True = written as "transfer file not written" + Ok(#( + bit_array.byte_size(bytes), + digest.hex(crypto.hash(crypto.Sha256, bytes)), + )) + } + } +} + +/// The SHA-256 of the file at `path`, in lowercase hex. +pub fn digest(path: String) -> Result(String, String) { + case open(path, [Read, Raw, Binary]) { + Error(reason) -> Error(reason_text(path, reason)) + Ok(input) -> { + let hashed = hash(input, crypto.new_hasher(crypto.Sha256)) + let _ = close(input) + let assert Ok(digest) = hashed as "transfer file not readable" + Ok(digest) + } + } +} + +fn hash(input: Device, hasher: crypto.Hasher) -> Result(String, Nil) { + case read(input) { + Eof -> Ok(digest.hex(crypto.digest(hasher))) + Bytes(data) -> hash(input, crypto.hash_chunk(hasher, data)) + Failed(_) -> Error(Nil) + } +} + +/// Write `bytes` at `offset` of a partial file no longer than `limit`, and +/// answer the file's new length. A repeat of bytes already there is accepted. +/// A gap or different bytes are not. +pub fn append_at( + path: String, + offset: Int, + bytes: BitArray, + limit: Int, +) -> Result(Int, String) { + let size = case read_file_info(path) { + Ok(info) -> info_size(info) + Error(reason) -> { + let assert True = reason == enoent() as "partial file not readable" + 0 + } + } + let length = bit_array.byte_size(bytes) + let end = offset + length + case offset < 0, end > limit, offset > size, end <= size { + True, _, _, _ -> Error("offset is negative") + _, True, _, _ -> Error("chunk runs past the segment's length") + _, _, True, _ -> + Error("chunk leaves a gap; resume at " <> int.to_string(size)) + _, _, _, True -> { + let assert Ok(input) = open(path, [Read, Raw, Binary]) + as "partial file not readable" + let held = pread(input, offset, length) + let _ = close(input) + case decode.run(held, ok_bytes()) { + Ok(found) if found == bytes -> Ok(size) + _ if length == 0 -> Ok(size) + _ -> Error("chunk differs from bytes already received") + } + } + _, _, _, False -> { + let assert Ok(output) = open(path, [Read, Write, Raw, Binary]) + as "partial file not writable" + case offset == 0 { + True -> { + let _ = change_mode(path, 0o600) + Nil + } + False -> Nil + } + let stored = + is_ok(pwrite(output, offset, bytes)) && is_ok(datasync(output)) + let _ = close(output) + let assert True = stored as "partial file not written" + Ok(end) + } + } +} + +/// The size of the file at `path`, or 0 when it cannot be read. +pub fn file_size(path: String) -> Int { + case read_file_info(path) { + Ok(info) -> info_size(info) + Error(_) -> 0 + } +} + +/// Free bytes on the filesystem holding `path`, from df's POSIX output. +pub fn free_bytes(path: String) -> Result(Int, String) { + case port_program.find_executable("df") { + Error(Nil) -> Error("df is not on PATH") + Ok(df) -> { + let port = + port_program.open(df, [ + port_program.Args(["-Pk", path]), + port_program.ExitStatus, + port_program.Binary, + port_program.StderrToStdout, + ]) + case port_program.collect(port, 10_000) { + Ok(#(0, output)) -> free_line(output) + Ok(#(_, output)) -> Error(string.trim(bytes_text(output))) + Error(Nil) -> Error("df did not answer") + } + } + } +} + +fn free_line(output: BitArray) -> Result(Int, String) { + let lines = + split_bytes(output, <<"\n">>, [ + atom.create("global"), + atom.create("trim_all"), + ]) + case lines { + [_, line, ..] -> + case lexemes(line, charlist.from_string(" ")) { + [_, _, _, available, ..] -> { + let assert Ok(kibibytes) = int.parse(available) + as "df answered a non-numeric size" + Ok(kibibytes * 1024) + } + _ -> Error("df answered an unexpected line") + } + _ -> Error("df answered nothing") + } +} + +/// This home's durable identity, made once. Two first callers at once each +/// write their own candidate and link it into place. The one that loses reads +/// the winner's. +pub fn identity(home: String) -> Result(String, String) { + let path = join(home, "identity") + case read_text(path) { + Ok(id) -> Ok(string.trim(id)) + Error(reason) -> + case reason == enoent() { + False -> Error(reason_text(path, reason)) + True -> { + let id = digest.hex(crypto.strong_random_bytes(16)) + let partial = path <> "." <> id + let assert True = + is_ok(write_synced(partial, id, [atom.create("sync")])) + as "identity candidate not written" + let linked = make_link(partial, path) + let _ = delete(partial) + case is_ok(linked) { + True -> Ok(id) + False -> + case error_reason(linked) == eexist() { + True -> identity(home) + False -> Error(reason_text(path, error_reason(linked))) + } + } + } + } + } +} + +/// Remove `path` and everything below it. A missing path is already removed. +pub fn remove_tree(path: String) -> Result(Nil, String) { + let removed = del_dir_r(path) + case is_ok(removed) || error_reason(removed) == enoent() { + True -> Ok(Nil) + False -> Error(reason_text(path, error_reason(removed))) + } +} + +/// Make `path` and its parents. Staging holds session rows and secrets, so +/// every directory up to `transfers` is made private to the owner. +pub fn ensure_dir(path: String) -> Result(Nil, String) { + let made = ensure_path(path) + case is_ok(made) { + True -> { + private_dirs(path) + Ok(Nil) + } + False -> Error(reason_text(path, error_reason(made))) + } +} + +fn private_dirs(path: String) -> Nil { + let parent = dirname(path) + let assert True = is_ok(change_mode(path, 0o700)) + as "staging directory mode not set" + case basename(path) == "transfers" || parent == path { + True -> Nil + False -> private_dirs(parent) + } +} + +/// Make the file at `path` readable and writable by its owner alone. +pub fn private(path: String) -> Result(Nil, String) { + let changed = change_mode(path, 0o600) + case is_ok(changed) { + True -> Ok(Nil) + False -> Error(reason_text(path, error_reason(changed))) + } +} + +/// Rename `from` to `to`. +pub fn rename(from: String, to: String) -> Result(Nil, String) { + let renamed = rename_file(from, to) + case is_ok(renamed) { + True -> Ok(Nil) + False -> Error(reason_text(from, error_reason(renamed))) + } +} + +/// Copy `from` to `to` through a temporary name, unless `to` already exists. +/// An install that resumes after a crash repeats nothing it finished. +pub fn install_file(from: String, to: String) -> Result(Nil, String) { + case is_regular(to) { + True -> Ok(Nil) + False -> { + let partial = to <> ".part" + let _ = delete(partial) + let parents = ensure_parent(to) + case is_ok(parents) { + True -> + copy_file(from, partial, 9_223_372_036_854_775_807) + |> result.try(fn(_) { rename(partial, to) }) + False -> Error(reason_text(to, error_reason(parents))) + } + } + } +} + +// ---- one worker per transfer ------------------------------------------------- + +/// The global name `{albedo_transfer, Key}` a running worker holds. +type WorkerName { + AlbedoTransfer(key: String) +} + +/// The messages of the worker protocol, as `{Tag, Pid}` records. +type Signal { + Go(Pid) + Stop(Pid) + Wake(Pid) + Acked(Pid) +} + +/// Run `work` in a new process unless one already runs for `key`, and answer +/// whether this call started it. A call that finds one running wakes it, and +/// the worker runs `work` again once it returns, so a wake that lands after +/// the worker's last read is not lost. The worker leaves the name before it +/// looks for wakes. A wake it never saw, because it exited between the +/// caller's look-up and send, is run again by the caller's watcher. +pub fn run_once(key: String, work: fn() -> Nil) -> Bool { + let parent = process.self() + let pid = + process.spawn_unlinked(fn() { + let start = + process.new_selector() + |> process.select_record(atom.create("go"), 1, fn(_) { True }) + |> process.select_record(atom.create("stop"), 1, fn(_) { False }) + case process.selector_receive_forever(start) { + True -> worker(key, work) + False -> Nil + } + }) + case register_name(AlbedoTransfer(key), pid) == atom.create("yes") { + True -> { + send(pid, Go(parent)) + True + } + False -> { + send(pid, Stop(parent)) + wake(key, work) + False + } + } +} + +fn worker(key: String, work: fn() -> Nil) -> Nil { + work() + let _ = unregister_name(AlbedoTransfer(key)) + case collect_wakes([]) { + [] -> Nil + wakers -> { + let again = register_name(AlbedoTransfer(key), process.self()) + list.each(wakers, fn(waker) { send(waker, Acked(process.self())) }) + case again == atom.create("yes") { + True -> worker(key, work) + False -> Nil + } + } + } +} + +fn collect_wakes(wakers: List(Pid)) -> List(Pid) { + let wakes = + process.new_selector() + |> process.select_record(atom.create("wake"), 1, signal_pid) + case process.selector_receive(wakes, 0) { + Ok(Ok(waker)) -> collect_wakes([waker, ..wakers]) + Ok(Error(Nil)) -> collect_wakes(wakers) + Error(Nil) -> wakers + } +} + +fn wake(key: String, work: fn() -> Nil) -> Nil { + process.spawn_unlinked(fn() { + case whereis_name(AlbedoTransfer(key)) |> decode.run(pid_decoder()) { + Error(_) -> { + let _ = run_once(key, work) + Nil + } + Ok(running) -> { + let monitor = process.monitor(running) + send(running, Wake(process.self())) + await_ack(key, work, running, monitor) + } + } + }) + Nil +} + +fn await_ack( + key: String, + work: fn() -> Nil, + running: Pid, + monitor: process.Monitor, +) -> Nil { + let outcome = + process.new_selector() + |> process.select_record(atom.create("acked"), 1, fn(message) { + case signal_pid(message) == Ok(running) { + True -> AckedByWorker + False -> AckedByOther + } + }) + |> process.select_specific_monitor(monitor, fn(_) { WorkerDown }) + case process.selector_receive_forever(outcome) { + AckedByWorker -> process.demonitor_process(monitor) + AckedByOther -> await_ack(key, work, running, monitor) + WorkerDown -> { + let _ = run_once(key, work) + Nil + } + } +} + +type AckOutcome { + AckedByWorker + AckedByOther + WorkerDown +} + +fn signal_pid(message: Dynamic) -> Result(Pid, Nil) { + decode.run(message, decode.at([1], pid_decoder())) + |> result.replace_error(Nil) +} + +fn pid_decoder() -> decode.Decoder(Pid) { + decode.new_primitive_decoder("Pid", fn(value) { + case is_pid(value) { + True -> Ok(unsafe_pid(value)) + False -> Error(process.self()) + } + }) +} + +// ---- helpers ------------------------------------------------------------------- + +fn reason_text(path: String, reason: Dynamic) -> String { + path <> ": " <> atom_to_binary(reason) +} + +fn is_ok(answer: Dynamic) -> Bool { + answer == atom.to_dynamic(atom.create("ok")) +} + +/// `Reason` of `{error, Reason}`. +fn error_reason(answer: Dynamic) -> Dynamic { + decode.run(answer, decode.at([1], decode.dynamic)) + |> result.unwrap(answer) +} + +fn enoent() -> Dynamic { + atom.to_dynamic(atom.create("enoent")) +} + +fn eexist() -> Dynamic { + atom.to_dynamic(atom.create("eexist")) +} + +fn read(device: Device) -> Chunk { + let answer = read_device(device, chunk) + case decode.run(answer, ok_bytes()) { + Ok(bytes) -> Bytes(bytes) + Error(_) -> + case answer == atom.to_dynamic(atom.create("eof")) { + True -> Eof + False -> Failed(error_reason(answer)) + } + } +} + +/// `{ok, Bytes}`. +fn ok_bytes() -> decode.Decoder(BitArray) { + use tag <- decode.field(0, atom.decoder()) + use bytes <- decode.field(1, decode.bit_array) + case atom.to_string(tag) { + "ok" -> decode.success(bytes) + _ -> decode.failure(bytes, "ok") + } +} + +/// Field 1 of OTP's `#file_info{}` record. +fn info_size(info: Dynamic) -> Int { + let assert Ok(size) = decode.run(info, decode.at([1], decode.int)) + as "file_info without a size" + size +} + +fn bytes_text(bytes: BitArray) -> String { + unsafe_text(bytes) +} + +@external(erlang, "file", "list_dir") +fn list_dir(directory: String) -> Result(List(Dynamic), Dynamic) + +@external(erlang, "unicode", "characters_to_binary") +fn characters_to_binary(name: Dynamic) -> String + +@external(erlang, "filename", "join") +fn join(directory: String, name: String) -> String + +@external(erlang, "filename", "dirname") +fn dirname(path: String) -> String + +@external(erlang, "filename", "basename") +fn basename(path: String) -> String + +@external(erlang, "file", "open") +fn open(path: String, modes: List(Mode)) -> Result(Device, Dynamic) + +@external(erlang, "file", "close") +fn close(device: Device) -> Dynamic + +@external(erlang, "file", "read") +fn read_device(device: Device, size: Int) -> Dynamic + +@external(erlang, "file", "write") +fn write(device: Device, bytes: BitArray) -> Dynamic + +@external(erlang, "file", "pread") +fn pread(device: Device, offset: Int, size: Int) -> Dynamic + +@external(erlang, "file", "pwrite") +fn pwrite(device: Device, offset: Int, bytes: BitArray) -> Dynamic + +@external(erlang, "file", "sync") +fn sync(device: Device) -> Dynamic + +@external(erlang, "file", "datasync") +fn datasync(device: Device) -> Dynamic + +@external(erlang, "file", "change_mode") +fn change_mode(path: String, mode: Int) -> Dynamic + +@external(erlang, "file", "delete") +fn delete(path: String) -> Dynamic + +@external(erlang, "file", "read_file_info") +fn read_file_info(path: String) -> Result(Dynamic, Dynamic) + +@external(erlang, "file", "read_file") +fn read_text(path: String) -> Result(String, Dynamic) + +@external(erlang, "file", "write_file") +fn write_synced(path: String, text: String, modes: List(Atom)) -> Dynamic + +@external(erlang, "file", "make_link") +fn make_link(existing: String, new: String) -> Dynamic + +@external(erlang, "file", "del_dir_r") +fn del_dir_r(path: String) -> Dynamic + +@external(erlang, "file", "rename") +fn rename_file(from: String, to: String) -> Dynamic + +@external(erlang, "filelib", "ensure_path") +fn ensure_path(path: String) -> Dynamic + +@external(erlang, "filelib", "ensure_dir") +fn ensure_parent(path: String) -> Dynamic + +@external(erlang, "erlang", "atom_to_binary") +fn atom_to_binary(reason: Dynamic) -> String + +@external(erlang, "gleam_stdlib", "identity") +fn unsafe_text(bytes: BitArray) -> String + +@external(erlang, "binary", "split") +fn split_bytes( + bytes: BitArray, + pattern: BitArray, + options: List(Atom), +) -> List(BitArray) + +@external(erlang, "string", "lexemes") +fn lexemes(line: BitArray, separators: Charlist) -> List(String) + +@external(erlang, "global", "register_name") +fn register_name(name: WorkerName, pid: Pid) -> Atom + +@external(erlang, "global", "unregister_name") +fn unregister_name(name: WorkerName) -> Dynamic + +@external(erlang, "global", "whereis_name") +fn whereis_name(name: WorkerName) -> Dynamic + +@external(erlang, "erlang", "send") +fn send(pid: Pid, message: Signal) -> Signal + +@external(erlang, "erlang", "is_pid") +fn is_pid(value: Dynamic) -> Bool + +@external(erlang, "gleam_stdlib", "identity") +fn unsafe_pid(value: Dynamic) -> Pid diff --git a/src/albedo/daemon/transfers.gleam b/src/albedo/daemon/transfers.gleam index 1200b726a..a1abe5376 100644 --- a/src/albedo/daemon/transfers.gleam +++ b/src/albedo/daemon/transfers.gleam @@ -11,6 +11,7 @@ import albedo/harness/sdk/session_info import albedo/clock import albedo/daemon/conversation import albedo/daemon/migrations/pending_inputs_inbox +import albedo/daemon/transfer_files import albedo/harness/sdk/protect import albedo/harness/sdk/store import albedo/transfer.{type Adapter, type Occurrence, type Segment} @@ -100,7 +101,7 @@ pub fn initialise(ledger: store.Store) -> Result(Nil, String) { /// This home's identity, which a manifest names as its origin. pub fn identity(home: String) -> Result(String, String) { - daemon_identity(home) + transfer_files.identity(home) } fn directory(home: String, id: String, role: String) -> String { @@ -129,10 +130,10 @@ pub fn export( "this transfer id already exported another session", )) None -> { - use origin <- result.try(native(daemon_identity(home))) + use origin <- result.try(native(transfer_files.identity(home))) let dir = directory(home, id, "export") - use _ <- result.try(native(remove_tree(dir))) - use _ <- result.try(native(ensure_dir(dir))) + use _ <- result.try(native(transfer_files.remove_tree(dir))) + use _ <- result.try(native(transfer_files.ensure_dir(dir))) let exported = store.snapshot(ledger, fn(db) { use #(root, workspace, sessions) <- result.try(scope(db, session)) @@ -158,7 +159,7 @@ pub fn export( }) case exported { Error(refusal) -> { - let _ = remove_tree(dir) + let _ = transfer_files.remove_tree(dir) Error(refusal) } Ok(manifest) -> { @@ -302,7 +303,7 @@ fn export_rows( path, unbounded, )) - private(path) |> result.replace(segment) + transfer_files.private(path) |> result.replace(segment) }) |> result.map(Entry(Rows, _)) |> result.map_error(fn(reason) { @@ -335,8 +336,14 @@ fn export_files( let #(index, #(owner, file)) = indexed let target = dir <> "/" <> int.to_string(index) <> ".seg" let #(name, written) = case file { - transfer.OnDisk(name, path) -> #(name, copy_file(path, target, unbounded)) - transfer.Contents(name, bytes) -> #(name, write_file(target, bytes)) + transfer.OnDisk(name, path) -> #( + name, + transfer_files.copy_file(path, target, unbounded), + ) + transfer.Contents(name, bytes) -> #( + name, + transfer_files.write_file(target, bytes), + ) } case written { Ok(#(bytes, digest)) -> @@ -389,8 +396,8 @@ pub fn stage( let bytes = total_bytes(manifest) use _ <- result.try(room(ledger, home, bytes)) let dir = directory(home, id, "import") - use _ <- result.try(native(remove_tree(dir))) - use _ <- result.try(native(ensure_dir(dir))) + use _ <- result.try(native(transfer_files.remove_tree(dir))) + use _ <- result.try(native(transfer_files.ensure_dir(dir))) let now = clock.system_ms() use _ <- result.try( store.write( @@ -529,7 +536,7 @@ fn room(ledger: store.Store, home: String, bytes: Int) -> Result(Nil, Refusal) { <> " byte limit for moves waiting together", )), ) - use free <- result.try(native(free_bytes(home))) + use free <- result.try(native(transfer_files.free_bytes(home))) let needed = bytes * 12 / 10 + free_margin case free >= needed { True -> Ok(Nil) @@ -561,7 +568,7 @@ pub fn receive( ) use entry <- result.try(entry_at(manifest, index)) use _ <- result.try( - append_at( + transfer_files.append_at( segment_path(home, id, "import", index, ".part"), offset, bytes, @@ -613,13 +620,16 @@ fn settle( let segment = entry.segment let named = int.to_string(index) <> " (" <> segment.owner <> "/" <> segment.name <> ")" - use <- bool.guard(is_regular(final), Ok(Nil)) + use <- bool.guard(transfer_files.is_regular(final), Ok(Nil)) // An empty segment has no chunk to send, so nothing created its file. - use _ <- result.try(case segment.bytes == 0 && !is_regular(part) { - True -> write_file(part, <<>>) |> result.replace(Nil) |> native - False -> Ok(Nil) - }) - let have = file_size(part) + use _ <- result.try( + case segment.bytes == 0 && !transfer_files.is_regular(part) { + True -> + transfer_files.write_file(part, <<>>) |> result.replace(Nil) |> native + False -> Ok(Nil) + }, + ) + let have = transfer_files.file_size(part) use <- bool.guard( have != segment.bytes, Error(Refusal( @@ -636,16 +646,16 @@ fn settle( let checked = case entry.kind { Rows -> codec.verify(part, segment) File -> - case digest(part) { + case transfer_files.digest(part) { Ok(found) if found == segment.digest -> Ok(Nil) Ok(_) -> Error("digest mismatch") Error(reason) -> Error(reason) } } case checked { - Ok(_) -> rename(part, final) |> native + Ok(_) -> transfer_files.rename(part, final) |> native Error(reason) -> { - let _ = remove_tree(part) + let _ = transfer_files.remove_tree(part) Error(Refusal( "segment_invalid", "segment " <> named <> ": " <> reason <> "; send it again", @@ -666,10 +676,22 @@ pub fn status( list.index_map(entries, fn(entry, index) { case found.state, - is_regular(segment_path(home, id, "import", index, ".seg")) + transfer_files.is_regular(segment_path( + home, + id, + "import", + index, + ".seg", + )) { "staging", False -> - file_size(segment_path(home, id, "import", index, ".part")) + transfer_files.file_size(segment_path( + home, + id, + "import", + index, + ".part", + )) _, _ -> entry.segment.bytes } }) @@ -920,7 +942,8 @@ pub fn resume( ) list.try_each(rows, fn(row) { case row.1 { - "active" | "cancelled" -> remove_tree(directory(home, row.0, "import")) + "active" | "cancelled" -> + transfer_files.remove_tree(directory(home, row.0, "import")) _ -> Ok(start(ledger, home, adapters, row.0, adopt)) } }) @@ -933,7 +956,8 @@ fn start( id: String, adopt: fn(String) -> Nil, ) -> Nil { - let _ = run_once(id, fn() { work(ledger, home, adapters, id, adopt) }) + let _ = + transfer_files.run_once(id, fn() { work(ledger, home, adapters, id, adopt) }) Nil } @@ -989,7 +1013,7 @@ fn advance( discard_step(db, home, adapters, id, found) }) "active", _ | "cancelled", _ -> - native(remove_tree(directory(home, id, "import"))) + native(transfer_files.remove_tree(directory(home, id, "import"))) |> result.replace(False) _, _ -> Ok(False) } @@ -1707,7 +1731,9 @@ pub fn expire(ledger: store.Store, home: String) -> Result(Nil, String) { ), ) list.try_each(stale, fn(row) { - use _ <- result.try(remove_tree(directory(home, row.0, row.1))) + use _ <- result.try( + transfer_files.remove_tree(directory(home, row.0, row.1)), + ) store.write( ledger, "DELETE FROM transfers WHERE id=? AND role=? AND updated_at Result(Manifest, Refusal) { Error(Refusal("invalid_manifest", "the manifest does not parse")) } } - -@external(erlang, "albedo_transfers", "identity") -fn daemon_identity(home: String) -> Result(String, String) - -@external(erlang, "albedo_transfers", "copy_file") -fn copy_file( - source: String, - target: String, - max_bytes: Int, -) -> Result(#(Int, String), String) - -@external(erlang, "albedo_transfers", "write_file") -fn write_file(target: String, bytes: BitArray) -> Result(#(Int, String), String) - -@external(erlang, "albedo_transfers", "digest") -fn digest(path: String) -> Result(String, String) - -@external(erlang, "albedo_transfers", "append_at") -fn append_at( - path: String, - offset: Int, - bytes: BitArray, - limit: Int, -) -> Result(Int, String) - -@external(erlang, "albedo_transfers", "file_size") -fn file_size(path: String) -> Int - -@external(erlang, "albedo_transfers", "free_bytes") -fn free_bytes(path: String) -> Result(Int, String) - -@external(erlang, "albedo_transfers", "remove_tree") -fn remove_tree(path: String) -> Result(Nil, String) - -@external(erlang, "albedo_transfers", "ensure_dir") -fn ensure_dir(path: String) -> Result(Nil, String) - -@external(erlang, "albedo_transfers", "rename") -fn rename(from: String, to: String) -> Result(Nil, String) - -@external(erlang, "albedo_transfers", "private") -fn private(path: String) -> Result(Nil, String) - -@external(erlang, "albedo_transfers", "is_regular") -fn is_regular(path: String) -> Bool - -/// Runs `work` in a new process unless one already runs for `key`. -@external(erlang, "albedo_transfers", "run_once") -fn run_once(key: String, work: fn() -> Nil) -> Bool diff --git a/test/daemon/albedo_transfers_test.erl b/test/daemon/albedo_transfers_test.erl index 1dc4ef466..68faae648 100644 --- a/test/daemon/albedo_transfers_test.erl +++ b/test/daemon/albedo_transfers_test.erl @@ -12,14 +12,14 @@ a_wake_during_the_last_step_runs_the_work_again_test() -> release -> ok end end, - ?assert(albedo_transfers:run_once(Key, Work)), + ?assert('albedo@daemon@transfer_files':run_once(Key, Work)), First = receive {step, Pid} -> Pid after 5000 -> error(no_first_step) end, %% The state a wake wrote is not read by a step already past its read. - ?assertNot(albedo_transfers:run_once(Key, Work)), + ?assertNot('albedo@daemon@transfer_files':run_once(Key, Work)), Monitor = erlang:monitor(process, First), First ! release, Second = -- knotmirror 0.0.1