diff --git a/priv/ready-modules.txt b/priv/ready-modules.txt index fc686161d..a037088ee 100644 --- a/priv/ready-modules.txt +++ b/priv/ready-modules.txt @@ -90,7 +90,7 @@ albedo@shared albedo@startup albedo_account_migration albedo_acp -albedo_active_output +albedo@daemon@active_output_store albedo_agents albedo_capabilities albedo_clock diff --git a/robot-docs/contributing.md b/robot-docs/contributing.md index b033b5761..d8126e255 100644 --- a/robot-docs/contributing.md +++ b/robot-docs/contributing.md @@ -36,8 +36,8 @@ parse it again to add fields. See [`command.StateOp`](../src/albedo/harness/sdk/command.gleam). Keep unfinished-output projection policy in -[`active_output.gleam`](../src/albedo/daemon/active_output.gleam). Its -[native helper](../src/albedo/daemon/albedo_active_output.erl) owns spill-file +[`active_output.gleam`](../src/albedo/daemon/active_output.gleam). Its spill +[store](../src/albedo/daemon/active_output_store.gleam) owns file operations. Do not reconstruct output by replaying events when a typed projection is available. diff --git a/src/albedo/daemon/active_output.gleam b/src/albedo/daemon/active_output.gleam index 2661a38e3..a7858fe3e 100644 --- a/src/albedo/daemon/active_output.gleam +++ b/src/albedo/daemon/active_output.gleam @@ -1,5 +1,6 @@ //// Session-owned provisional output, with bounded memory and leased spill files. +import albedo/daemon/active_output_store import gleam/int import gleam/json import gleam/list @@ -218,13 +219,20 @@ fn append_segment( ), )) False -> { - use content_id <- result.try(create( + use content_id <- result.try(active_output_store.create( projection.home, projection.session, )) - case append(projection.home, content_id, 0, segment.text <> text) { + case + active_output_store.append( + projection.home, + content_id, + 0, + segment.text <> text, + ) + { Error(reason) -> { - release(projection.home, content_id) + active_output_store.release(projection.home, content_id) Error(reason) } Ok(_) -> @@ -254,7 +262,7 @@ fn flush(projection: Projection) -> Result(Projection, String) { case segment.content_id { None -> Ok(segment) Some(content_id) -> { - use _ <- result.try(append( + use _ <- result.try(active_output_store.append( projection.home, content_id, segment.bytes - string.byte_size(segment.pending), @@ -283,7 +291,12 @@ fn capture_segments(projection: Projection) -> Result(List(Snapshot), String) { list.try_map(flushed.segments, fn(segment) { use _ <- result.try(case segment.content_id { None -> Ok(Nil) - Some(content_id) -> lease(projection.home, projection.session, content_id) + Some(content_id) -> + active_output_store.lease( + projection.home, + projection.session, + content_id, + ) }) Ok(Snapshot( segment.message_id, @@ -327,7 +340,7 @@ fn read_whole( case offset < cutoff { False -> Ok(string_tree.to_string(read_so_far)) True -> { - use #(text, next, done) <- result.try(read( + use #(text, next, done) <- result.try(active_output_store.read( projection.home, projection.session, content_id, @@ -348,7 +361,8 @@ pub fn retire(projection: Projection) -> Projection { list.each(projection.segments, fn(segment) { case segment.content_id { None -> Nil - Some(content_id) -> release(projection.home, content_id) + Some(content_id) -> + active_output_store.release(projection.home, content_id) } }) Projection( @@ -364,40 +378,3 @@ pub fn retire(projection: Projection) -> Projection { pub fn retry(projection: Projection) -> Projection { Projection(..retire(projection), attempt: projection.attempt + 1) } - -@external(erlang, "albedo_active_output", "create") -fn create(home: String, session: String) -> Result(String, String) - -@external(erlang, "albedo_active_output", "append") -fn append( - home: String, - content_id: String, - offset: Int, - text: String, -) -> Result(Nil, String) - -@external(erlang, "albedo_active_output", "lease") -fn lease( - home: String, - session: String, - content_id: String, -) -> Result(Nil, String) - -@external(erlang, "albedo_active_output", "release") -fn release(home: String, content_id: String) -> Nil - -@external(erlang, "albedo_active_output", "read") -pub fn read( - home: String, - session: String, - content_id: String, - offset: Int, - limit: Int, - cutoff: Int, -) -> Result(#(String, Int, Bool), String) - -@external(erlang, "albedo_active_output", "maintenance") -pub fn maintenance(home: String) -> Nil - -@external(erlang, "albedo_active_output", "revoke") -pub fn revoke(home: String, session: String) -> Nil diff --git a/src/albedo/daemon/active_output_store.gleam b/src/albedo/daemon/active_output_store.gleam new file mode 100644 index 000000000..8128e092a --- /dev/null +++ b/src/albedo/daemon/active_output_store.gleam @@ -0,0 +1,670 @@ +//// Spill files for unfinished output under `/active-output`: one +//// append-only `.data` file and one `.meta` lease per content id, and a +//// `usage.etf` total held under a 1 GiB disk budget. +//// +//// `.meta` files and `usage.etf` are Erlang external terms. A `.meta` holds +//// the map `#{session, owner, instance, expires}`, so files written by an +//// earlier daemon stay readable. Writers serialize on a global lock per home. +//// +//// Each step asserts what it needs. A failed step fails the whole call, +//// which answers the storage error, as a crash inside the lock would. + +import albedo/clock +import albedo/harness/sdk/digest +import albedo/harness/sdk/http_api +import albedo/harness/sdk/protect +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/process.{type Pid} +import gleam/int +import gleam/list +import gleam/result +import gleam/string + +const disk = 1_073_741_824 + +const lease_ms = 900_000 + +const read_limit = 262_144 + +const meta_limit = 4096 + +const unavailable = "active output storage is unavailable" + +/// Make a new content id for `session`, owned by the calling process. +pub fn create(home: String, session: String) -> Result(String, String) { + guarded(fn() { + locked(home, fn() { + let directory = directory(home) + let made = make_dir(directory) + case made == ok(), error_reason(made) == atom.to_dynamic(atom("eexist")) { + True, _ -> { + let assert True = change_mode(directory, 0o700) == ok() + Nil + } + False, True -> { + let assert True = is_dir(directory) + Nil + } + False, False -> panic as "active output directory not made" + } + case meta_count(home) < meta_limit { + True -> Nil + False -> { + cleanup(home) + let assert True = meta_count(home) < meta_limit + Nil + } + } + let id = digest.hex(crypto.strong_random_bytes(16)) + save( + meta_path(home, id), + new_meta(session, process.self(), instance(), 0), + ) + case + write_file_modes(data_path(home, id), <<>>, [atom("exclusive")]) == ok() + { + True -> { + let assert True = change_mode(data_path(home, id), 0o600) == ok() + Ok(id) + } + False -> { + let _ = delete(meta_path(home, id)) + panic as "active output data not made" + } + } + }) + }) +} + +fn meta_count(home: String) -> Int { + let assert Ok(names) = list_dir(directory(home)) + list.count(names, fn(name) { extension(name) == ".meta" }) +} + +/// Store the bytes of `text` beyond what is already stored at `offset`. A +/// capture can flush its pending buffer without returning replacement actor +/// state, so a repeated prefix is skipped. +pub fn append( + home: String, + id: String, + offset: Int, + text: String, +) -> Result(Nil, String) { + let text = bit_array.from_string(text) + case text { + <<>> -> Ok(Nil) + _ -> + guarded(fn() { + locked(home, fn() { + let assert True = valid_id(id) + let existing = file_size(data_path(home, id)) + let assert True = existing >= offset + let skip = int.max(0, existing - offset) + let length = bit_array.byte_size(text) + case skip >= length { + True -> Ok(Nil) + False -> { + let assert Ok(suffix) = bit_array.slice(text, skip, length - skip) + let size = bit_array.byte_size(suffix) + let current = usage(home) + let base = case current + size <= disk { + True -> current + False -> { + cleanup(home) + usage(home) + } + } + let reserved = base + size + let assert True = reserved <= disk + save(usage_path(home), reserved) + case + write_file_modes(data_path(home, id), suffix, [ + atom("append"), + atom("binary"), + ]) + == ok() + { + True -> Ok(Nil) + False -> { + let after = file_size(data_path(home, id)) + save(usage_path(home), base + after - existing) + panic as "active output not appended" + } + } + } + } + }) + }) + } +} + +/// Keep `id` readable for `session` for the lease period. +pub fn lease(home: String, session: String, id: String) -> Result(Nil, String) { + guarded(fn() { + locked(home, fn() { + let meta = metadata(home, id) + let assert True = meta_session(meta) == session + save( + meta_path(home, id), + map_put(atom("expires"), clock.system_ms() + lease_ms, meta), + ) + Ok(Nil) + }) + }) +} + +/// The owner is done with `id`. A leased content stays until its lease ends. +/// Otherwise it goes now. +pub fn release(home: String, id: String) -> Nil { + let _ = + protect.attempt(fn() { + locked(home, fn() { + let meta = metadata(home, id) + case meta_expires(meta) > clock.system_ms() { + True -> + save( + meta_path(home, id), + map_put(atom("owner"), atom.to_dynamic(atom("none")), meta), + ) + False -> delete_content(home, id) + } + }) + }) + Nil +} + +type ReadFailure { + Expired + Unreadable +} + +/// At most `limit` bytes of `id` from `offset`, ending on a UTF-8 boundary +/// and not past `cutoff`: the text, where it ends, and whether that is the +/// cutoff. +pub fn read( + home: String, + session: String, + id: String, + offset: Int, + limit: Int, + cutoff: Int, +) -> Result(#(String, Int, Bool), String) { + let outcome = + protect.attempt(fn() { + let assert True = valid_id(id) + let assert True = offset >= 0 && offset <= cutoff + let assert True = limit > 0 && limit <= read_limit + let opened = + locked(home, fn() { + use meta <- result.try(read_metadata(home, id)) + case + meta_session(meta) == session + && meta_expires(meta) > clock.system_ms() + { + False -> Error(Expired) + True -> { + let assert True = cutoff <= file_size(data_path(home, id)) + let assert Ok(file) = + open(data_path(home, id), [Read, Binary, Raw]) + Ok(file) + } + } + }) + use file <- result.try(opened) + let answer = pread(file, offset, int.min(limit + 4, cutoff - offset)) + let _ = close(file) + let bytes = case answer == atom.to_dynamic(atom("eof")) { + True -> "" + False -> { + let assert Ok(bytes) = + decode.run(answer, decode.at([1], text_bytes())) + bytes + } + } + let assert Ok(#(text, next, _)) = + http_api.content_slice( + bytes, + 0, + int.min(limit, string.byte_size(bytes)), + ) + Ok(#(text, offset + next, offset + next == cutoff)) + }) + case outcome { + Ok(Ok(slice)) -> Ok(slice) + Ok(Error(Expired)) -> Error("active_output_expired") + Ok(Error(Unreadable)) | Error(_) -> + Error("active output content is unavailable") + } +} + +/// The first sweep after start removes everything no live owner holds and +/// recounts usage. Later sweeps find candidates outside the writer lock and +/// recheck each while deleting, so a renewed lease wins the race. +pub fn maintenance(home: String) -> Nil { + let recovered = #(atom("albedo_active_output"), atom("recovered"), home) + let _ = + protect.attempt(fn() { + case get_recovered(recovered, False) { + False -> + locked(home, fn() { + cleanup(home) + case is_dir(directory(home)) { + True -> save(usage_path(home), disk_bytes(home)) + False -> Nil + } + let _ = put_recovered(recovered, True) + Nil + }) + True -> + case list_dir(directory(home)) { + Ok(names) -> + list.each(names, fn(name) { + let _ = + protect.attempt(fn() { + case removable(home, name) { + True -> locked(home, fn() { cleanup_file(home, name) }) + False -> Nil + } + }) + Nil + }) + Error(_) -> Nil + } + } + }) + Nil +} + +/// Remove every content of `session`. +pub fn revoke(home: String, session: String) -> Nil { + let _ = + protect.attempt(fn() { + locked(home, fn() { + let assert Ok(names) = list_dir(directory(home)) + list.each(names, fn(name) { + case extension(name) == ".meta" { + True -> { + let id = rootname(name) + case meta_session(metadata(home, id)) == session { + True -> delete_content(home, id) + False -> Nil + } + } + False -> Nil + } + }) + }) + }) + Nil +} + +// ---- cleanup -------------------------------------------------------------------- + +fn cleanup(home: String) -> Nil { + case list_dir(directory(home)) { + Ok(names) -> + list.each(names, fn(name) { + let _ = protect.attempt(fn() { cleanup_file(home, name) }) + Nil + }) + Error(_) -> Nil + } +} + +/// Whether nothing holds `name`: a `.meta` whose owner is gone and whose lease +/// has ended, a `.data` without its `.meta`, or a temporary file. +fn removable(home: String, name: String) -> Bool { + case extension(name) { + ".meta" -> { + let meta = metadata(home, rootname(name)) + let owner = map_get_strict(atom("owner"), meta) + let alive = + map_get(atom("instance"), meta, atom.to_dynamic(atom("none"))) + == instance() + && is_pid(owner) + && process.is_alive(unsafe_pid(owner)) + !alive && meta_expires(meta) <= clock.system_ms() + } + ".data" -> { + let id = rootname(name) + let assert True = valid_id(id) + !is_file(meta_path(home, id)) + } + ".tmp" -> True + _ -> False + } +} + +fn cleanup_file(home: String, name: String) -> Nil { + case removable(home, name) { + False -> Nil + True -> + case extension(name) { + ".tmp" -> { + let _ = delete(join(directory(home), name)) + Nil + } + _ -> delete_content(home, rootname(name)) + } + } +} + +fn delete_content(home: String, id: String) -> Nil { + let bytes = case read_file_info(data_path(home, id)) { + Ok(info) -> info_size(info) + Error(_) -> 0 + } + let total = usage(home) + let deleted = delete(data_path(home, id)) + case + deleted == ok(), + error_reason(deleted) == atom.to_dynamic(atom("enoent")) + { + True, _ -> save(usage_path(home), int.max(0, total - bytes)) + False, True -> Nil + False, False -> panic as "active output data not deleted" + } + let deleted = delete(meta_path(home, id)) + case + deleted == ok() || error_reason(deleted) == atom.to_dynamic(atom("enoent")) + { + True -> Nil + False -> panic as "active output lease not deleted" + } +} + +fn disk_bytes(home: String) -> Int { + case list_dir(directory(home)) { + Ok(names) -> + names + |> list.filter(fn(name) { extension(name) == ".data" }) + |> list.map(fn(name) { + case read_file_info(join(directory(home), name)) { + Ok(info) -> info_size(info) + Error(_) -> 0 + } + }) + |> int.sum + Error(reason) -> { + let assert True = reason == atom.to_dynamic(atom("enoent")) + 0 + } + } +} + +fn usage(home: String) -> Int { + case read_file(usage_path(home)) { + Ok(bytes) -> { + let assert Ok(total) = + decode.run(binary_to_term(bytes, [atom("safe")]), decode.int) + total + } + Error(reason) -> { + let assert True = reason == atom.to_dynamic(atom("enoent")) + disk_bytes(home) + } + } +} + +// ---- metadata ------------------------------------------------------------------- + +fn new_meta( + session: String, + owner: Pid, + instance: Dynamic, + expires: Int, +) -> Dynamic { + empty_map() + |> map_put(atom("session"), session, _) + |> map_put(atom("owner"), owner, _) + |> map_put(atom("instance"), instance, _) + |> map_put(atom("expires"), expires, _) +} + +fn metadata(home: String, id: String) -> Dynamic { + let assert True = valid_id(id) + let assert Ok(bytes) = read_file(meta_path(home, id)) + binary_to_term(bytes, [atom("safe")]) +} + +fn read_metadata(home: String, id: String) -> Result(Dynamic, ReadFailure) { + case read_file(meta_path(home, id)) { + Ok(bytes) -> Ok(binary_to_term(bytes, [atom("safe")])) + Error(reason) -> + case reason == atom.to_dynamic(atom("enoent")) { + True -> Error(Expired) + False -> Error(Unreadable) + } + } +} + +fn meta_session(meta: Dynamic) -> String { + let assert Ok(session) = + decode.run(map_get_strict(atom("session"), meta), decode.string) + session +} + +fn meta_expires(meta: Dynamic) -> Int { + let assert Ok(expires) = + decode.run(map_get_strict(atom("expires"), meta), decode.int) + expires +} + +/// Write `value` as an external term through a private temporary file. +fn save(path: String, value: a) -> Nil { + let temporary = path <> ".tmp" + let assert True = write_file(temporary, <<>>) == ok() + let assert True = change_mode(temporary, 0o600) == ok() + let assert True = write_file(temporary, term_to_binary(value)) == ok() + let assert True = rename(temporary, path) == ok() + Nil +} + +/// One rarely installed immutable token distinguishes owner pids across VMs. +fn instance() -> Dynamic { + let key = #(atom("albedo_active_output"), atom("instance")) + let none = atom.to_dynamic(atom("none")) + case get_instance(key, none) { + found if found == none -> + trans(#(key, process.self()), fn() { + case get_instance(key, none) { + found if found == none -> { + let id = to_dynamic(crypto.strong_random_bytes(16)) + let _ = put_instance(key, id) + id + } + found -> found + } + }) + found -> found + } +} + +// ---- helpers -------------------------------------------------------------------- + +// Keys are plain tuples, so the lock ids and persistent terms keep the names +// the native module used: `{{albedo_active_output, Home}, Pid}`, +// `{albedo_active_output, instance}` and +// `{albedo_active_output, recovered, Home}`. +type InstanceKey = + #(Atom, Atom) + +type Recovered = + #(Atom, Atom, String) + +fn locked(home: String, run: fn() -> a) -> a { + trans(#(#(atom("albedo_active_output"), home), process.self()), run) +} + +fn guarded(run: fn() -> Result(a, String)) -> Result(a, String) { + case protect.attempt(run) { + Ok(result) -> result + Error(_) -> Error(unavailable) + } +} + +fn directory(home: String) -> String { + join(home, "active-output") +} + +fn data_path(home: String, id: String) -> String { + join(directory(home), id <> ".data") +} + +fn meta_path(home: String, id: String) -> String { + join(directory(home), id <> ".meta") +} + +fn usage_path(home: String) -> String { + join(directory(home), "usage.etf") +} + +fn valid_id(id: String) -> Bool { + string.byte_size(id) == 32 + && list.all(string.to_graphemes(id), fn(character) { + string.contains("0123456789abcdef", character) + }) +} + +fn file_size(path: String) -> Int { + let assert Ok(info) = read_file_info(path) + info_size(info) +} + +/// 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)) + size +} + +fn text_bytes() -> decode.Decoder(String) { + decode.bit_array |> decode.map(unsafe_text) +} + +fn ok() -> Dynamic { + atom.to_dynamic(atom("ok")) +} + +fn atom(name: String) -> Atom { + atom.create(name) +} + +/// `Reason` of `{error, Reason}`, or the answer itself. +fn error_reason(answer: Dynamic) -> Dynamic { + decode.run(answer, decode.at([1], decode.dynamic)) |> result.unwrap(answer) +} + +type File + +type Mode { + Read + Binary + Raw +} + +@external(erlang, "global", "trans") +fn trans(id: #(key, Pid), run: fn() -> a) -> a + +@external(erlang, "filename", "join") +fn join(directory: String, name: String) -> String + +@external(erlang, "filename", "extension") +fn extension(name: String) -> String + +@external(erlang, "filename", "rootname") +fn rootname(name: String) -> String + +@external(erlang, "file", "list_dir") +fn list_dir_raw(directory: String) -> Result(List(Dynamic), Dynamic) + +fn list_dir(directory: String) -> Result(List(String), Dynamic) { + list_dir_raw(directory) |> result.map(list.map(_, characters_to_binary)) +} + +@external(erlang, "unicode", "characters_to_binary") +fn characters_to_binary(name: Dynamic) -> String + +@external(erlang, "file", "make_dir") +fn make_dir(path: String) -> Dynamic + +@external(erlang, "filelib", "is_dir") +fn is_dir(path: String) -> Bool + +@external(erlang, "filelib", "is_file") +fn is_file(path: String) -> Bool + +@external(erlang, "file", "change_mode") +fn change_mode(path: String, mode: Int) -> Dynamic + +@external(erlang, "file", "write_file") +fn write_file(path: String, bytes: BitArray) -> Dynamic + +@external(erlang, "file", "write_file") +fn write_file_modes(path: String, bytes: BitArray, modes: List(Atom)) -> Dynamic + +@external(erlang, "file", "read_file") +fn read_file(path: String) -> Result(BitArray, Dynamic) + +@external(erlang, "file", "read_file_info") +fn read_file_info(path: String) -> Result(Dynamic, Dynamic) + +@external(erlang, "file", "rename") +fn rename(from: String, to: String) -> Dynamic + +@external(erlang, "file", "delete") +fn delete(path: String) -> Dynamic + +@external(erlang, "file", "open") +fn open(path: String, modes: List(Mode)) -> Result(File, Dynamic) + +@external(erlang, "file", "pread") +fn pread(file: File, offset: Int, size: Int) -> Dynamic + +@external(erlang, "file", "close") +fn close(file: File) -> Dynamic + +@external(erlang, "erlang", "term_to_binary") +fn term_to_binary(value: a) -> BitArray + +@external(erlang, "erlang", "binary_to_term") +fn binary_to_term(bytes: BitArray, options: List(Atom)) -> Dynamic + +@external(erlang, "maps", "new") +fn empty_map() -> Dynamic + +@external(erlang, "maps", "put") +fn map_put(key: Atom, value: a, map: Dynamic) -> Dynamic + +@external(erlang, "maps", "get") +fn map_get(key: Atom, map: Dynamic, default: Dynamic) -> Dynamic + +@external(erlang, "maps", "get") +fn map_get_strict(key: Atom, map: Dynamic) -> Dynamic + +@external(erlang, "erlang", "is_pid") +fn is_pid(value: Dynamic) -> Bool + +@external(erlang, "gleam_stdlib", "identity") +fn unsafe_pid(value: Dynamic) -> Pid + +@external(erlang, "gleam_stdlib", "identity") +fn unsafe_text(bytes: BitArray) -> String + +@external(erlang, "gleam_stdlib", "identity") +fn to_dynamic(value: a) -> Dynamic + +@external(erlang, "persistent_term", "get") +fn get_recovered(key: Recovered, default: Bool) -> Bool + +@external(erlang, "persistent_term", "put") +fn put_recovered(key: Recovered, value: Bool) -> Dynamic + +@external(erlang, "persistent_term", "get") +fn get_instance(key: InstanceKey, default: Dynamic) -> Dynamic + +@external(erlang, "persistent_term", "put") +fn put_instance(key: InstanceKey, value: Dynamic) -> Dynamic diff --git a/src/albedo/daemon/albedo_active_output.erl b/src/albedo/daemon/albedo_active_output.erl deleted file mode 100644 index f753a69e5..000000000 --- a/src/albedo/daemon/albedo_active_output.erl +++ /dev/null @@ -1,347 +0,0 @@ --module(albedo_active_output). --export([create/2, append/4, lease/3, release/2, read/6, maintenance/1, revoke/2]). --include_lib("kernel/include/file.hrl"). - --define(DISK, 1073741824). --define(LEASE, 900000). - -create(Home, Session) -> - guarded(fun() -> - locked(Home, fun() -> - case file:make_dir(directory(Home)) of - ok -> ok = file:change_mode(directory(Home), 8#700); - {error, eexist} -> true = filelib:is_dir(directory(Home)); - Error0 -> error(Error0) - end, - {ok, Files} = file:list_dir(directory(Home)), - Count = length([Name || Name <- Files, filename:extension(Name) =:= ".meta"]), - case Count < 4096 of - true -> - ok; - false -> - cleanup(Home), - {ok, AfterCleanup} = file:list_dir(directory(Home)), - true = - length([Name || Name <- AfterCleanup, filename:extension(Name) =:= ".meta"]) < - 4096 - end, - ID = binary:encode_hex(crypto:strong_rand_bytes(16), lowercase), - save(meta_path(Home, ID), #{ - session => Session, owner => self(), instance => instance(), expires => 0 - }), - case file:write_file(data_path(Home, ID), <<>>, [exclusive]) of - ok -> - ok = file:change_mode(data_path(Home, ID), 8#600); - Error -> - file:delete(meta_path(Home, ID)), - error(Error) - end, - {ok, ID} - end) - end). - -%% Only append bytes beyond the already stored immutable prefix. A capture can -%% flush its pending buffer without returning replacement actor state. -append(_, _, _, <<>>) -> - {ok, nil}; -append(Home, ID, Offset, Text) -> - guarded(fun() -> - locked(Home, fun() -> - true = valid_id(ID), - {ok, Info} = file:read_file_info(data_path(Home, ID)), - Existing = Info#file_info.size, - true = Existing >= Offset, - Skip = erlang:max(0, Existing - Offset), - case Skip >= byte_size(Text) of - true -> - {ok, nil}; - false -> - Suffix = binary:part(Text, Skip, byte_size(Text) - Skip), - Current = usage(Home), - Usage = - case Current + byte_size(Suffix) =< ?DISK of - true -> - Current; - false -> - cleanup(Home), - usage(Home) - end, - Reserved = Usage + byte_size(Suffix), - true = Reserved =< ?DISK, - save(usage_path(Home), Reserved), - case file:write_file(data_path(Home, ID), Suffix, [append, binary]) of - ok -> - {ok, nil}; - Error -> - {ok, After} = file:read_file_info(data_path(Home, ID)), - save(usage_path(Home), Usage + After#file_info.size - Existing), - error(Error) - end - end - end) - end). - -lease(Home, Session, ID) -> - guarded(fun() -> - locked(Home, fun() -> - Meta = metadata(Home, ID), - true = maps:get(session, Meta) =:= Session, - save(meta_path(Home, ID), Meta#{expires => now_ms() + ?LEASE}), - {ok, nil} - end) - end). - -release(Home, ID) -> - try - locked(Home, fun() -> - Meta = metadata(Home, ID), - case maps:get(expires, Meta) > now_ms() of - true -> save(meta_path(Home, ID), Meta#{owner => none}); - false -> delete_content(Home, ID) - end - end) - catch - _:_ -> ok - end, - nil. - -read(Home, Session, ID, Offset, Limit, Cutoff) -> - try - true = valid_id(ID), - true = Offset >= 0 andalso Offset =< Cutoff, - true = Limit > 0 andalso Limit =< 262144, - File = locked(Home, fun() -> - Meta = read_metadata(Home, ID), - case maps:get(session, Meta) =:= Session andalso maps:get(expires, Meta) > now_ms() of - true -> ok; - false -> throw(active_output_expired) - end, - {ok, Info} = file:read_file_info(data_path(Home, ID)), - true = Cutoff =< Info#file_info.size, - {ok, Handle} = file:open(data_path(Home, ID), [read, binary, raw]), - Handle - end), - try - Amount = erlang:min(Limit + 4, Cutoff - Offset), - Bytes = - case file:pread(File, Offset, Amount) of - eof -> <<>>; - {ok, Data} -> Data - end, - {ok, Result} = 'albedo@harness@sdk@http_api':content_slice( - Bytes, 0, erlang:min(Limit, byte_size(Bytes)) - ), - %% content_slice's native tuple is returned inside Gleam Result. - {Text, Next, _} = Result, - {ok, {Text, Offset + Next, Offset + Next =:= Cutoff}} - after - file:close(File) - end - catch - throw:active_output_expired -> {error, <<"active_output_expired">>}; - _:_ -> {error, <<"active output content is unavailable">>} - end. - -maintenance(Home) -> - try - case persistent_term:get({?MODULE, recovered, Home}, false) of - false -> - locked(Home, fun() -> - cleanup(Home), - case filelib:is_dir(directory(Home)) of - true -> save(usage_path(Home), disk_bytes(Home)); - false -> ok - end, - persistent_term:put({?MODULE, recovered, Home}, true) - end); - true -> - %% Discovery is outside the writer mutex. Every candidate is - %% rechecked while deleting, so a renewed lease wins the race. - case file:list_dir(directory(Home)) of - {ok, Files} -> - lists:foreach( - fun(Name) -> - try - case removable(Home, Name) of - true -> locked(Home, fun() -> cleanup_file(Home, Name) end); - false -> ok - end - catch - _:_ -> ok - end - end, - Files - ); - _ -> - ok - end - end - catch - _:_ -> ok - end, - nil. - -cleanup(Home) -> - case file:list_dir(directory(Home)) of - {ok, Files} -> - lists:foreach( - fun(Name) -> - try - cleanup_file(Home, Name) - catch - _:_ -> ok - end - end, - Files - ); - _ -> - ok - end. - -removable(Home, Name) -> - case filename:extension(Name) of - ".meta" -> - ID = list_to_binary(filename:rootname(Name)), - Meta = metadata(Home, ID), - Owner = maps:get(owner, Meta), - Alive = - maps:get(instance, Meta, none) =:= instance() andalso - is_pid(Owner) andalso is_process_alive(Owner), - not Alive andalso maps:get(expires, Meta) =< now_ms(); - ".data" -> - ID = list_to_binary(filename:rootname(Name)), - true = valid_id(ID), - not filelib:is_file(meta_path(Home, ID)); - ".tmp" -> - true; - _ -> - false - end. - -cleanup_file(Home, Name) -> - case removable(Home, Name) of - false -> - ok; - true -> - case filename:extension(Name) of - ".meta" -> delete_content(Home, list_to_binary(filename:rootname(Name))); - ".data" -> delete_content(Home, list_to_binary(filename:rootname(Name))); - ".tmp" -> file:delete(filename:join(directory(Home), Name)) - end - end. - -revoke(Home, Session) -> - try - locked(Home, fun() -> - {ok, Files} = file:list_dir(directory(Home)), - lists:foreach( - fun(Name) -> - case filename:extension(Name) of - ".meta" -> - ID = list_to_binary(filename:rootname(Name)), - case maps:get(session, metadata(Home, ID)) =:= Session of - true -> delete_content(Home, ID); - false -> ok - end; - _ -> - ok - end - end, - Files - ) - end) - catch - _:_ -> ok - end, - nil. - -read_metadata(Home, ID) -> - case file:read_file(meta_path(Home, ID)) of - {ok, Bytes} -> binary_to_term(Bytes, [safe]); - {error, enoent} -> throw(active_output_expired); - _ -> error(content_unavailable) - end. - -usage(Home) -> - case file:read_file(usage_path(Home)) of - {ok, Bytes} -> binary_to_term(Bytes, [safe]); - {error, enoent} -> disk_bytes(Home) - end. -metadata(Home, ID) -> - true = valid_id(ID), - {ok, Bytes} = file:read_file(meta_path(Home, ID)), - binary_to_term(Bytes, [safe]). -save(Path, Value) -> - Temporary = <>, - ok = file:write_file(Temporary, <<>>), - ok = file:change_mode(Temporary, 8#600), - ok = file:write_file(Temporary, term_to_binary(Value)), - ok = file:rename(Temporary, Path). -locked(Home, Run) -> global:trans({{?MODULE, Home}, self()}, Run). -directory(Home) -> filename:join(Home, <<"active-output">>). -data_path(Home, ID) -> filename:join(directory(Home), <>). -meta_path(Home, ID) -> filename:join(directory(Home), <>). -usage_path(Home) -> filename:join(directory(Home), <<"usage.etf">>). -now_ms() -> erlang:system_time(millisecond). -valid_id(ID) -> - is_binary(ID) andalso byte_size(ID) =:= 32 andalso - lists:all( - fun(C) -> C >= $0 andalso C =< $9 orelse C >= $a andalso C =< $f end, binary_to_list(ID) - ). - -guarded(Run) -> - try - Run() - catch - _:_ -> {error, <<"active output storage is unavailable">>} - end. - -delete_content(Home, ID) -> - Bytes = - case file:read_file_info(data_path(Home, ID)) of - {ok, Info} -> Info#file_info.size; - _ -> 0 - end, - Total = usage(Home), - case file:delete(data_path(Home, ID)) of - ok -> save(usage_path(Home), erlang:max(0, Total - Bytes)); - {error, enoent} -> ok; - Error -> error(Error) - end, - case file:delete(meta_path(Home, ID)) of - ok -> ok; - {error, enoent} -> ok; - Error2 -> error(Error2) - end. - -disk_bytes(Home) -> - case file:list_dir(directory(Home)) of - {ok, Files} -> - lists:sum([ - case file:read_file_info(filename:join(directory(Home), Name)) of - {ok, Info} -> Info#file_info.size; - _ -> 0 - end - || Name <- Files, filename:extension(Name) =:= ".data" - ]); - {error, enoent} -> - 0 - end. - -%% One rarely installed immutable token distinguishes owner PIDs across VMs. -instance() -> - case persistent_term:get({?MODULE, instance}, none) of - none -> - global:trans({{?MODULE, instance}, self()}, fun() -> - case persistent_term:get({?MODULE, instance}, none) of - none -> - ID = crypto:strong_rand_bytes(16), - persistent_term:put({?MODULE, instance}, ID), - ID; - ID -> - ID - end - end); - ID -> - ID - end. diff --git a/src/albedo/daemon/http_active_output.gleam b/src/albedo/daemon/http_active_output.gleam index a9e6a17c7..58a95777f 100644 --- a/src/albedo/daemon/http_active_output.gleam +++ b/src/albedo/daemon/http_active_output.gleam @@ -1,6 +1,7 @@ //// Cursor-bound reads of unfinished model output. The session owns writes. import albedo/daemon/active_output +import albedo/daemon/active_output_store import albedo/daemon/http_api import albedo/daemon/registry import albedo/harness/sdk/history @@ -169,7 +170,7 @@ pub fn content( )) }) use read <- result.try( - active_output.read( + active_output_store.read( config.home, session_id, content_id, diff --git a/src/albedo/daemon/maintenance.gleam b/src/albedo/daemon/maintenance.gleam index 6d0ddbdb1..2167546ef 100644 --- a/src/albedo/daemon/maintenance.gleam +++ b/src/albedo/daemon/maintenance.gleam @@ -4,7 +4,7 @@ import albedo/daemon/host_memory import albedo/harness/sdk/session_info import albedo/actor_call -import albedo/daemon/active_output +import albedo/daemon/active_output_store import albedo/daemon/conversation import albedo/daemon/images import albedo/daemon/pastes @@ -52,7 +52,7 @@ pub fn run(sweep: Sweep) -> Nil { Error(error) -> io.println_error("unused ACP session cleanup failed: " <> error) } - active_output.maintenance(sweep.home) + active_output_store.maintenance(sweep.home) let reports = list.filter_map(sweep.workers, fn(entry) { actor_call.try_call(entry.1, waiting: 5000, sending: session.Idle) diff --git a/src/albedo/daemon/server.gleam b/src/albedo/daemon/server.gleam index 8110d6e17..5128c2661 100644 --- a/src/albedo/daemon/server.gleam +++ b/src/albedo/daemon/server.gleam @@ -1,6 +1,6 @@ import albedo/clock import albedo/daemon/acp_attachments -import albedo/daemon/active_output +import albedo/daemon/active_output_store import albedo/daemon/api_digest import albedo/daemon/boot_code import albedo/daemon/build_identity @@ -101,7 +101,7 @@ pub fn start( ) io.println("startup: starting services") let services_began = clock.monotonic_ms() - active_output.maintenance(config.home) + active_output_store.maintenance(config.home) let name = process.new_name("albedo_registry") use _ <- result.try( supervisor.new(supervisor.OneForOne) diff --git a/src/albedo/daemon/session.gleam b/src/albedo/daemon/session.gleam index 86cdd2561..fa326c256 100644 --- a/src/albedo/daemon/session.gleam +++ b/src/albedo/daemon/session.gleam @@ -14,6 +14,7 @@ import albedo/daemon/acp import albedo/daemon/acp_attachments import albedo/daemon/acp_session import albedo/daemon/active_output +import albedo/daemon/active_output_store import albedo/daemon/bus import albedo/daemon/child_failure import albedo/daemon/command_state @@ -3164,7 +3165,7 @@ fn handle( Error(error), ) Ok(_) -> { - active_output.revoke(state.home, state.info.id) + active_output_store.revoke(state.home, state.info.id) cleanup_registrations(state.info.id) wake_watchers(state) process.send(reply, Ok(Nil)) diff --git a/test/e2e/albedo_active_output_probe.erl b/test/e2e/albedo_active_output_probe.erl index 961e98004..b53d9cb0c 100644 --- a/test/e2e/albedo_active_output_probe.erl +++ b/test/e2e/albedo_active_output_probe.erl @@ -22,5 +22,5 @@ expire(Home, Id) -> <<"true">>. sweep(Home) -> - albedo_active_output:maintenance(Home), + 'albedo@daemon@active_output_store':maintenance(Home), <<"true">>.