From 2f8ca2c542726bba034176c465f8e13324ef6cd3 Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Wed, 11 Nov 2026 21:48:50 -0500 Subject: [PATCH] feat(settings): add typed atomic section updates --- robot-docs/plugins.md | 11 + robot-docs/settings.md | 35 +++ .../harness/albedo_extension_settings.erl | 110 ++++----- src/albedo/harness/extension/selection.gleam | 69 +++--- .../web_search/albedo_web_search_settings.erl | 38 --- .../harness/extensions/web_search/order.gleam | 62 ++++- src/albedo/harness/settings.gleam | 55 +++++ test/e2e/web_search_test.py | 12 +- .../albedo_settings_update_test_support.erl | 116 ++++++++++ test/harness/settings_update_test.gleam | 217 ++++++++++++++++++ 10 files changed, 572 insertions(+), 153 deletions(-) delete mode 100644 src/albedo/harness/extensions/web_search/albedo_web_search_settings.erl create mode 100644 test/harness/albedo_settings_update_test_support.erl create mode 100644 test/harness/settings_update_test.gleam diff --git a/robot-docs/plugins.md b/robot-docs/plugins.md index 9749ffbb0..bfd5dce27 100644 --- a/robot-docs/plugins.md +++ b/robot-docs/plugins.md @@ -78,6 +78,16 @@ Startup callbacks run after the schema transaction commits. The host does not roll back an earlier successful startup if a later startup or dependency check fails. Extensions own the lifetime of long-lived startup resources. +## Persisted extension settings + +Use [`settings.Section`](../src/albedo/harness/settings.gleam) for a typed +section decoder and validation. `settings.update(section, encode, change)` +performs a locked read-modify-write of that section without extension-owned +native code. Follow the +[typed update contract](settings.md#typed-extension-updates) for encoder +overlays, pure callbacks, defaults, and failure behavior. Credentials and +multi-document mutations retain specialized owners. + ## HTTP services `ServicePlugin` serves routes below `/extensions//` while the extension is @@ -139,3 +149,4 @@ not authorize requests or validate submitted domain values. - [Change guidance](contributing.md) - [Extensions](extensions.md) - [Commands](commands.md) +- [Settings](settings.md) diff --git a/robot-docs/settings.md b/robot-docs/settings.md index a69273901..06dd37d37 100644 --- a/robot-docs/settings.md +++ b/robot-docs/settings.md @@ -24,6 +24,40 @@ declared extension settings. Provider validation belongs to every provider setting is a secret or that a presence indicator returns the credential value. +## Typed extension updates + +[`settings.update`](../src/albedo/harness/settings.gleam) changes one +`extensions.json` section using its existing `Section(a)`, an encoder +`fn(a) -> List(settings.Edit)`, and a callback `fn(a) -> Result(a, String)`. Use +`load_section` to read the same declaration. A missing document or section uses +the section's empty-object defaults. List-valued settings can use a section with +no declared UI fields. + +The settings lock covers recovery, a fresh read, field validation, decoding, the +section check, the change callback, encoding, final validation, and publication. +The encoder returns `Set(key, value)` and `Remove(key)` edits. Omitted keys, +including unknown keys, and other sections survive. Setting and removing the +same key in one update is refused; use `Set(key, json.null())` to store null +rather than delete a key. Invalid existing data or a callback or validation +error causes no update write. Success returns the final decoded and checked +value after publication. + +Keep the callback, encoder, and section check pure and bounded. Do not call +settings I/O from them or perform external effects. Keep secrets out of errors. +This is a caller contract; the function types do not enforce purity. Use this +API for single-section extension settings. Credentials and changes spanning +documents keep their specialized owners and validation. See +[persistence and recovery](#persistence-and-recovery) for the publication +boundary and recovery limits. + +[`web_search/order.gleam`](../src/albedo/harness/extensions/web_search/order.gleam) +uses a pure update to save provider order and exclusions. It merges a caller's +visible selection into the fresh saved values, retaining hidden provider slots +and exclusions. +[`selection.gleam`](../src/albedo/harness/extension/selection.gleam) also uses +this API for global enablement, compaction strategy replacement, and raised +context caps. + ## Session configuration and catalog [`session_configuration`](../src/albedo/daemon/session_configuration.gleam) owns @@ -55,5 +89,6 @@ merges native files under a different procedure. - [All topics](README.md) - [Change guidance](contributing.md) +- [Plugins](plugins.md) - [Extensions](extensions.md) - [Commands](commands.md) diff --git a/src/albedo/harness/albedo_extension_settings.erl b/src/albedo/harness/albedo_extension_settings.erl index a39a6aca1..09d86ed8e 100644 --- a/src/albedo/harness/albedo_extension_settings.erl +++ b/src/albedo/harness/albedo_extension_settings.erl @@ -3,15 +3,50 @@ -export([ home/0, read/1, - set_enabled/3, - set_enabled_many/2, - set_entry/4, - remove_entry/3, + update_section/4, rename_key/4 ]). -define(MAX_BYTES, 1048576). +%% Typed callbacks stay in Gleam. Only the encoded owned fields cross back +%% into the document, so keys unknown to the section's decoder survive. +update_section(Home, Name, Prepare, Validate) -> + albedo_settings_store:with_lock(Home, fun() -> + albedo_settings_store:guarded(fun() -> + Read = read_locked(Home), + albedo_settings_store:check(Read), + {ok, Bytes} = Read, + Sections = json:decode(Bytes), + true = is_map(Sections), + Saved = albedo_settings_store:object(Name, Sections), + case Prepare(Saved) of + {error, _} = PrepareError -> + PrepareError; + {ok, {Encoded, Removed}} -> + Fields = json:decode(Encoded), + true = is_map(Fields), + true = lists:all(fun(Key) -> not maps:is_key(Key, Fields) end, Removed), + Candidate = maps:merge(maps:without(Removed, Saved), Fields), + case Validate(Candidate) of + {error, _} = ValidateError -> + ValidateError; + {ok, Value} -> + Updated = Sections#{Name => Candidate}, + case iolist_size(json:encode(Updated)) =< ?MAX_BYTES of + false -> + {error, <<"extensions.json exceeds 1 MiB">>}; + true -> + ok = albedo_settings_store:commit_group( + Home, #{<<"extensions.json">> => Updated} + ), + {ok, Value} + end + end + end + end) + end). + home() -> unicode:characters_to_binary( case os:getenv("ALBEDO_HOME") of @@ -49,73 +84,6 @@ read_locked(Home) -> {error, <<"extensions.json is not a readable regular file">>} end. -%% Records a global extension default in the `enabled` section. -set_enabled(Home, Name, Enabled) -> - set_entry(Home, <<"enabled">>, Name, Enabled). - -%% A strategy selection changes all siblings in one locked rename. -set_enabled_many(Home, Choices) -> - albedo_settings_lock:with_lock( - Home, - fun() -> - try - {ok, Bytes} = read_locked(Home), - Sections = json:decode(Bytes), - Enabled = maps:get(<<"enabled">>, Sections, #{}), - Updated = Sections#{<<"enabled">> => maps:merge(Enabled, maps:from_list(Choices))}, - case - albedo_credentials:write(filename:join(Home, <<"extensions.json">>), Updated) - of - ok -> {ok, nil}; - _ -> {error, <<"could not save extensions.json">>} - end - catch - _:_ -> {error, <<"extensions.json is not a valid settings object">>} - end - end, - fun() -> {error, <<"settings store is busy">>} end - ). - -remove_entry(Home, Section, Key) -> - set_entry(Home, Section, Key, null). - -%% Sets one key of one section, keeping every other section and key as -%% written; `null` removes the key. The rename is the commit, so readers never -%% see a partly written file. -set_entry(Home, Section, Key, Value) -> - albedo_settings_lock:with_lock( - Home, - fun() -> set_entry_locked(Home, Section, Key, Value) end, - fun() -> {error, <<"settings store is busy">>} end - ). - -set_entry_locked(Home, Section, Key, Value) -> - try - {ok, Bytes} = read(Home), - Sections = - case Bytes of - <<>> -> #{}; - _ -> json:decode(Bytes) - end, - true = is_map(Sections), - Entries = - case maps:get(Section, Sections, #{}) of - Map when is_map(Map) -> Map; - _ -> erlang:error(invalid_section) - end, - Updated = - case Value of - null -> Sections#{Section => maps:remove(Key, Entries)}; - _ -> Sections#{Section => Entries#{Key => Value}} - end, - case albedo_credentials:write(filename:join(Home, <<"extensions.json">>), Updated) of - ok -> {ok, nil}; - _ -> {error, <<"could not save extensions.json">>} - end - catch - _:_ -> {error, <<"extensions.json is not a valid settings object">>} - end. - %% Moves `Old` to `New` in the top-level object (`root`) or in one section %% (`{section, Name}`), when `Old` is there and `New` is not, so a renamed %% extension keeps its settings and its global default. Answers whether it diff --git a/src/albedo/harness/extension/selection.gleam b/src/albedo/harness/extension/selection.gleam index 0ebd8ea05..eb9ea224a 100644 --- a/src/albedo/harness/extension/selection.gleam +++ b/src/albedo/harness/extension/selection.gleam @@ -14,6 +14,7 @@ import albedo/harness/settings import gleam/dict import gleam/dynamic/decode import gleam/int +import gleam/json import gleam/list import gleam/option.{type Option, None, Some} import gleam/result @@ -151,10 +152,12 @@ pub fn raised_caps() -> List(String) { /// Raises or restores a model's context cap for every session. pub fn raise_cap(model: String, raised: Bool) -> Result(Nil, String) { - case raised { - True -> set_entry(settings.home(), "raisedCaps", model, True) - False -> remove_entry(settings.home(), "raisedCaps", model) - } + save_choices("raisedCaps", [ + #(model, case raised { + True -> Some(True) + False -> None + }), + ]) } /// The window the user saved for a model to compact against, from the @@ -192,21 +195,6 @@ pub fn window(info: extension.ModelInfo) -> Option(Int) { } } -@external(erlang, "albedo_extension_settings", "set_entry") -fn set_entry( - home: String, - section: String, - key: String, - value: Bool, -) -> Result(Nil, String) - -@external(erlang, "albedo_extension_settings", "remove_entry") -fn remove_entry( - home: String, - section: String, - key: String, -) -> Result(Nil, String) - /// How a user changes which extensions a session runs. `SetSession` records a /// choice for one session; `SetGlobal` changes the default every session /// without its own choice follows; `Inherit` drops the session's choice. @@ -312,7 +300,7 @@ pub fn record( ) -> Result(Nil, String) { case change { SetSession(name, value) -> set_enabled(ledger, session, name, value) - SetGlobal(name, value) -> set_global(settings.home(), name, value) + SetGlobal(name, value) -> save_choices("enabled", [#(name, Some(value))]) Inherit(name) -> store.write( ledger, @@ -322,9 +310,6 @@ pub fn record( } } -@external(erlang, "albedo_extension_settings", "set_enabled") -fn set_global(home: String, name: String, enabled: Bool) -> Result(Nil, String) - pub fn is_compaction(ext: extension.Extension) -> Bool { list.any(ext.plugins, fn(plugin) { case plugin { @@ -374,21 +359,43 @@ pub fn record_selected( SetSession(..), True -> set_selection_with(ledger, session, previous, selected, #(name, True)) SetGlobal(..), True -> - set_globals( - settings.home(), + save_choices( + "enabled", installed |> list.filter(is_compaction) - |> list.map(fn(other) { #(other.name, other.name == name) }), + |> list.map(fn(other) { #(other.name, Some(other.name == name)) }), ) _, _ -> record(ledger, session, change) } } -@external(erlang, "albedo_extension_settings", "set_enabled_many") -fn set_globals( - home: String, - choices: List(#(String, Bool)), -) -> Result(Nil, String) +fn save_choices( + name: String, + changes: List(#(String, Option(Bool))), +) -> Result(Nil, String) { + let section = + settings.section( + name, + name, + settings.Tools, + [], + decode.dict(decode.string, decode.bool), + Ok, + ) + settings.update( + section, + fn(_) { + list.map(changes, fn(change) { + case change.1 { + Some(value) -> settings.Set(change.0, json.bool(value)) + None -> settings.Remove(change.0) + } + }) + }, + Ok, + ) + |> result.replace(Nil) +} fn set_selection_with( ledger: store.Store, diff --git a/src/albedo/harness/extensions/web_search/albedo_web_search_settings.erl b/src/albedo/harness/extensions/web_search/albedo_web_search_settings.erl deleted file mode 100644 index acd17e634..000000000 --- a/src/albedo/harness/extensions/web_search/albedo_web_search_settings.erl +++ /dev/null @@ -1,38 +0,0 @@ --module(albedo_web_search_settings). --export([save/2]). - -%% Replace visible positions while retaining hidden providers' positions and -%% exclusions. Read and publish both fields under the same settings lock. -save(Home, Selected) -> - albedo_settings_store:with_lock(Home, fun() -> - albedo_settings_store:guarded(fun() -> - Documents = albedo_settings_store:read(Home, <<"extensions.json">>), - Search = albedo_settings_store:object(<<"web-search">>, Documents), - Prior = maps:get(<<"order">>, Search, []), - Names = [Name || {Name, _} <- Selected], - Order = replace_visible(Prior, Names, Names), - Off = - [Name || Name <- maps:get(<<"off">>, Search, []), not lists:member(Name, Names)] ++ - [Name || {Name, false} <- Selected], - Updated = Documents#{ - <<"web-search">> => Search#{<<"order">> => Order, <<"off">> => Off} - }, - case albedo_credentials:write(filename:join(Home, <<"extensions.json">>), Updated) of - ok -> {ok, nil}; - _ -> {error, <<"could not save web search preferences">>} - end - end) - end). - -replace_visible([], Remaining, _) -> - Remaining; -replace_visible([Name | Rest], Remaining, Visible) -> - case lists:member(Name, Visible) of - false -> - [Name | replace_visible(Rest, Remaining, Visible)]; - true -> - case Remaining of - [Next | Tail] -> [Next | replace_visible(Rest, Tail, Visible)]; - [] -> replace_visible(Rest, [], Visible) - end - end. diff --git a/src/albedo/harness/extensions/web_search/order.gleam b/src/albedo/harness/extensions/web_search/order.gleam index f25a3fafc..76da18e13 100644 --- a/src/albedo/harness/extensions/web_search/order.gleam +++ b/src/albedo/harness/extensions/web_search/order.gleam @@ -6,6 +6,7 @@ import albedo/harness/settings import albedo/harness/web_search import gleam/dynamic/decode +import gleam/json import gleam/list import gleam/result @@ -29,9 +30,12 @@ pub type Change { Toggle } -pub fn load() -> Result(Preference, String) { - settings.load( +fn section() -> settings.Section(Preference) { + settings.section( "web-search", + "Web search provider order", + settings.WebSearch, + [], { use order <- decode.optional_field( "order", @@ -41,10 +45,14 @@ pub fn load() -> Result(Preference, String) { use off <- decode.optional_field("off", [], decode.list(decode.string)) decode.success(Preference(order, off)) }, - Preference([], []), + Ok, ) } +pub fn load() -> Result(Preference, String) { + settings.load_section(section()) +} + pub fn ranked( providers: List(web_search.Provider), preference: Preference, @@ -106,14 +114,44 @@ fn swap(ranked: List(Ranked), index: Int) -> List(Ranked) { } fn save(ranked: List(Ranked)) -> Result(Nil, String) { - save_selection( - settings.home(), - list.map(ranked, fn(entry) { #(entry.provider.name, entry.on) }), - ) + let names = list.map(ranked, fn(entry) { entry.provider.name }) + settings.update(section(), encode, fn(prior) { + let order = replace_visible(prior.order, names, names) + let hidden_off = + list.filter(prior.off, fn(name) { !list.contains(names, name) }) + let selected_off = + ranked + |> list.filter(fn(entry) { !entry.on }) + |> list.map(fn(entry) { entry.provider.name }) + Ok(Preference(order, list.append(hidden_off, selected_off))) + }) + |> result.replace(Nil) +} + +fn encode(preference: Preference) -> List(settings.Edit) { + [ + settings.Set("order", json.array(preference.order, json.string)), + settings.Set("off", json.array(preference.off, json.string)), + ] } -@external(erlang, "albedo_web_search_settings", "save") -fn save_selection( - home: String, - selected: List(#(String, Bool)), -) -> Result(Nil, String) +// Replace only visible slots in the fresh saved order. The caller's ranked +// selection can be stale; hidden providers keep their positions and exclusions. +fn replace_visible( + prior: List(String), + remaining: List(String), + visible: List(String), +) -> List(String) { + case prior { + [] -> remaining + [name, ..rest] -> + case list.contains(visible, name) { + False -> [name, ..replace_visible(rest, remaining, visible)] + True -> + case remaining { + [next, ..tail] -> [next, ..replace_visible(rest, tail, visible)] + [] -> replace_visible(rest, [], visible) + } + } + } +} diff --git a/src/albedo/harness/settings.gleam b/src/albedo/harness/settings.gleam index b01110242..46364d927 100644 --- a/src/albedo/harness/settings.gleam +++ b/src/albedo/harness/settings.gleam @@ -252,6 +252,61 @@ pub fn load_section(section: Section(a)) -> Result(a, String) { ) } +/// An explicit edit to one saved section. Omitted keys remain untouched. +pub type Edit { + Set(key: String, value: json.Json) + Remove(key: String) +} + +/// Atomically read, change, validate and save one extensions.json section. +/// Missing settings use the section's defaults. Invalid existing settings or +/// callback errors leave the document unchanged. Encoded fields overlay the +/// saved section; Remove deletes a key. Omitted fields, including unknown keys, +/// survive. Setting and removing the same key in one update is refused. +/// +/// Both callbacks run under the settings lock. They must be pure and bounded, +/// must not perform settings I/O, and must not include secrets in errors. +/// The returned value is decoded and checked from the final saved candidate. +pub fn update( + section: Section(a), + encode: fn(a) -> List(Edit), + change: fn(a) -> Result(a, String), +) -> Result(a, String) { + update_section( + home(), + section.name, + fn(saved) { + use current <- result.try(parse(section, saved)) + use changed <- result.try(change(current)) + let edits = encode(changed) + let fields = + list.filter_map(edits, fn(edit) { + case edit { + Set(key, value) -> Ok(#(key, value)) + Remove(_) -> Error(Nil) + } + }) + let removed = + list.filter_map(edits, fn(edit) { + case edit { + Remove(key) -> Ok(key) + Set(_, _) -> Error(Nil) + } + }) + Ok(#(fields |> json.object |> json.to_string, removed)) + }, + fn(candidate) { parse(section, candidate) }, + ) +} + +@external(erlang, "albedo_extension_settings", "update_section") +fn update_section( + home: String, + name: String, + prepare: fn(Dynamic) -> Result(#(String, List(String)), String), + validate: fn(Dynamic) -> Result(a, String), +) -> Result(a, String) + fn parse(section: Section(a), value: Dynamic) -> Result(a, String) { use values <- result.try( decode.run(value, decode.dict(decode.string, decode.dynamic)) diff --git a/test/e2e/web_search_test.py b/test/e2e/web_search_test.py index 5f355c5be..69717df4b 100644 --- a/test/e2e/web_search_test.py +++ b/test/e2e/web_search_test.py @@ -171,13 +171,23 @@ class WebSearchTests(unittest.TestCase): app = self.start([]) self.change(app, "exa", "up") self.change(app, "exa", "toggle") - before = json.loads((app.home / "extensions.json").read_text())["web-search"] + path = app.home / "extensions.json" + document = json.loads(path.read_text()) + document["web-search"]["future-preference"] = {"keep": [True, "value"]} + document["unrelated-extension"] = {"nested": {"keep": 42}} + path.write_text(json.dumps(document)) + before = document["web-search"] self.patch(app, "/settings?group=extensions", {"defaults": {"exa": False}}) self.assertNotIn("exa", [entry["name"] for entry in self.providers(app)[0]]) self.change(app, "codex", "toggle") saved = json.loads((app.home / "extensions.json").read_text())["web-search"] self.assertEqual(saved["order"], before["order"]) self.assertIn("exa", saved["off"]) + self.assertEqual(saved["future-preference"], before["future-preference"]) + self.assertEqual( + json.loads(path.read_text())["unrelated-extension"], + document["unrelated-extension"], + ) self.patch(app, "/settings?group=extensions", {"defaults": {"exa": True}}) exa = next(entry for entry in self.providers(app)[0] if entry["name"] == "exa") self.assertFalse(exa["enabled"]) diff --git a/test/harness/albedo_settings_update_test_support.erl b/test/harness/albedo_settings_update_test_support.erl new file mode 100644 index 000000000..f16d78593 --- /dev/null +++ b/test/harness/albedo_settings_update_test_support.erl @@ -0,0 +1,116 @@ +%% Environment-sensitive SDK fixtures run in a disposable VM, as do the +%% Bedrock catalog fixtures. No daemon, global environment edits, or lock mocks. +-module(albedo_settings_update_test_support). +-export([fixtures/0, isolated/0, write/1, read/0, concurrent/1]). + +fixtures() -> + Args = + ["+S", "2:2", "+SDcpu", "1", "+SDio", "1", "+A", "1", "-pa"] ++ + code:get_path() ++ + [ + "-noshell", + "-eval", + "albedo_settings_update_test_support:isolated(), halt(0)." + ], + Port = open_port( + {spawn_executable, os:find_executable("erl")}, + [binary, exit_status, use_stdio, stderr_to_stdout, {args, Args}] + ), + await(Port, <<>>). + +await(Port, Output) -> + receive + {Port, {data, Bytes}} -> await(Port, <>); + {Port, {exit_status, 0}} -> true; + {Port, {exit_status, Status}} -> error({settings_fixture_failed, Status, Output}) + after 30000 -> + port_close(Port), + error({settings_fixture_timeout, Output}) + end. + +isolated() -> + Dir = filename:join( + os:getenv("TMPDIR", "/tmp"), + "settings-update-" ++ os:getpid() + ), + ok = file:make_dir(Dir), + try + true = os:putenv("ALBEDO_HOME", Dir), + nil = 'harness@settings_update_test':verify() + after + file:del_dir_r(Dir) + end. + +write(Bytes) -> + ok = file:write_file(path(), Bytes), + nil. + +read() -> + {ok, Bytes} = file:read_file(path()), + Bytes. + +path() -> filename:join(albedo_extension_settings:home(), <<"extensions.json">>). + +%% Hold the first update until the mutex owner has queued the second writer. +%% Only this disposable VM traces the lock's queue boundary. +concurrent(Update) -> + Parent = self(), + First = spawn_link(fun() -> + Result = Update(fun(Count) -> + Parent ! {self(), entered}, + receive + release -> {ok, Count + 1} + after 10000 -> error(no_release) + end + end), + Parent ! {self(), Result} + end), + receive + {First, entered} -> ok + after 5000 -> error(first_not_entered) + end, + Second = spawn_link(fun() -> + receive + go -> ok + end, + Parent ! {self(), Update(fun(Count) -> {ok, Count + 1} end)} + end), + Lock = whereis(albedo_lock), + erlang:trace_pattern({albedo_lock, loop, 1}, true, [local]), + erlang:trace(Lock, true, [call, {tracer, Parent}]), + try + Second ! go, + await_queued(Lock, Second), + First ! release, + receive + {First, {ok, 1}} -> ok + after 5000 -> error(first_failed) + end, + receive + {Second, {ok, 2}} -> nil + after 5000 -> error(second_lost_update) + end + after + erlang:trace(Lock, false, [call]), + erlang:trace_pattern({albedo_lock, loop, 1}, false, [local]), + unlink(First), + unlink(Second), + exit(First, kill), + exit(Second, kill) + end. + +await_queued(Lock, Writer) -> + receive + {trace, Lock, call, {albedo_lock, loop, [Locks]}} -> + Queued = lists:any( + fun({_Key, {_Holder, Waiting}}) -> + lists:keymember(Writer, 1, queue:to_list(Waiting)) + end, + maps:to_list(Locks) + ), + case Queued of + true -> ok; + false -> await_queued(Lock, Writer) + end + after 5000 -> error(second_not_waiting) + end. diff --git a/test/harness/settings_update_test.gleam b/test/harness/settings_update_test.gleam new file mode 100644 index 000000000..10b37c42c --- /dev/null +++ b/test/harness/settings_update_test.gleam @@ -0,0 +1,217 @@ +//// Callback and encoder rejection are SDK boundaries no HTTP route exposes. +//// A disposable VM isolates ALBEDO_HOME while exercising the real store/lock. + +import albedo/daemon/store +import albedo/harness/extension/selection +import albedo/harness/extensions/rolling/extension as rolling +import albedo/harness/extensions/snapcompact/extension as snapcompact +import albedo/harness/settings +import gleam/dict +import gleam/dynamic/decode +import gleam/erlang/process +import gleam/json +import gleam/list +import gleeunit/should + +pub fn rejected_updates_leave_saved_bytes_untouched_test() -> Nil { + assert fixtures() +} + +fn section() -> settings.Section(Int) { + let count = settings.whole("count", "Count", "Fixture count", 0, 0, 10) + let decoder = { + use count <- settings.value(count) + decode.success(count) + } + settings.section( + "update-fixture", + "Update fixture", + settings.Tools, + [settings.field(count)], + decoder, + fn(count) { + case count <= 5 { + True -> Ok(count) + False -> Error("fixture cross-field constraint") + } + }, + ) +} + +fn encode(count: Int) -> List(settings.Edit) { + [settings.Set("count", json.int(count))] +} + +pub fn verify() -> Nil { + let section = section() + // Missing sections must feed their defaults to the callback. + write("{\"unrelated\":{\"keep\":true}}") + settings.update(section, encode, fn(count) { Ok(count + 1) }) + |> should.equal(Ok(1)) + settings.load_section(section) |> should.equal(Ok(1)) + let before = read() + + settings.update( + section, + fn(_) { panic as "rejected callback was encoded" }, + fn(_) { Error("refused") }, + ) + |> should.equal(Error("refused")) + read() |> should.equal(before) + + // A valid typed value can still violate declared field or section rules. + settings.update(section, encode, fn(_) { Ok(11) }) |> should.be_error + read() |> should.equal(before) + settings.update(section, encode, fn(_) { Ok(7) }) |> should.be_error + read() |> should.equal(before) + settings.update( + section, + fn(_) { [settings.Set("count", json.string("wrong type"))] }, + Ok, + ) + |> should.be_error + read() |> should.equal(before) + + write( + "{\"unrelated\":{\"keep\":true},\"update-fixture\":{\"count\":2,\"keep\":true}}", + ) + settings.update(section, fn(_) { [settings.Remove("count")] }, Ok) + |> should.equal(Ok(0)) + json.parse(read(), decode.at(["update-fixture", "keep"], decode.bool)) + |> should.equal(Ok(True)) + json.parse(read(), decode.at(["unrelated", "keep"], decode.bool)) + |> should.equal(Ok(True)) + let deleted = read() + settings.update(section, fn(_) { [settings.Remove("count")] }, Ok) + |> should.equal(Ok(0)) + read() |> should.equal(deleted) + settings.update( + section, + fn(_) { [settings.Remove("keep"), settings.Set("count", json.int(11))] }, + Ok, + ) + |> should.be_error + read() |> should.equal(deleted) + settings.update( + section, + fn(_) { [settings.Remove("count"), settings.Set("count", json.int(1))] }, + Ok, + ) + |> should.be_error + read() |> should.equal(deleted) + + write("{\"raisedCaps\":{\"other\":true},\"unrelated\":{\"keep\":true}}") + selection.raise_cap("model", True) |> should.equal(Ok(Nil)) + selection.raised_caps() |> list.contains("model") |> should.be_true + selection.raise_cap("model", False) |> should.equal(Ok(Nil)) + json.parse( + read(), + decode.at(["raisedCaps"], decode.dict(decode.string, decode.bool)), + ) + |> should.equal(Ok(dict.from_list([#("other", True)]))) + json.parse(read(), decode.at(["unrelated", "keep"], decode.bool)) + |> should.equal(Ok(True)) + + verify_global_choices() + + write("{}") + concurrent(fn(change) { settings.update(section, encode, change) }) + settings.load_section(section) |> should.equal(Ok(2)) + + // Malformed existing data must never be repaired by invoking the callback. + [ + "{", + "[]", + "{\"update-fixture\":[]}", + "{\"update-fixture\":{\"count\":\"wrong type\"}}", + "{\"update-fixture\":{\"count\":7}}", + ] + |> each_invalid(section) +} + +// HTTP settings writes have a different owner and never construct SetGlobal. +fn verify_global_choices() -> Nil { + let assert Ok(ledger) = store.start(":memory:", "") + write("{\"enabled\":{\"other\":true},\"unrelated\":{\"keep\":true}}") + selection.record(ledger, "unused", selection.SetGlobal("skills", True)) + |> should.equal(Ok(Nil)) + selection.record(ledger, "unused", selection.SetGlobal("skills", False)) + |> should.equal(Ok(Nil)) + json.parse( + read(), + decode.at(["enabled"], decode.dict(decode.string, decode.bool)), + ) + |> should.equal(Ok(dict.from_list([#("other", True), #("skills", False)]))) + + let installed = [rolling.extension(), snapcompact.extension()] + selection.record_selected( + ledger, + "unused", + selection.SetGlobal("rolling", True), + [], + [], + installed, + ) + |> should.equal(Ok(Nil)) + selection.record_selected( + ledger, + "unused", + selection.SetGlobal("snapcompact", True), + [], + [], + installed, + ) + |> should.equal(Ok(Nil)) + json.parse( + read(), + decode.at(["enabled"], decode.dict(decode.string, decode.bool)), + ) + |> should.equal( + Ok( + dict.from_list([ + #("other", True), + #("skills", False), + #("rolling", False), + #("snapcompact", True), + ]), + ), + ) + json.parse(read(), decode.at(["unrelated", "keep"], decode.bool)) + |> should.equal(Ok(True)) + store.close(ledger) +} + +fn each_invalid( + documents: List(String), + section: settings.Section(Int), +) -> Nil { + case documents { + [] -> Nil + [document, ..rest] -> { + write(document) + let called = process.new_subject() + settings.update(section, encode, fn(_) { + process.send(called, Nil) + Ok(1) + }) + |> should.be_error + process.receive(called, 0) |> should.be_error + read() |> should.equal(document) + each_invalid(rest, section) + } + } +} + +@external(erlang, "albedo_settings_update_test_support", "fixtures") +fn fixtures() -> Bool + +@external(erlang, "albedo_settings_update_test_support", "write") +fn write(document: String) -> Nil + +@external(erlang, "albedo_settings_update_test_support", "read") +fn read() -> String + +@external(erlang, "albedo_settings_update_test_support", "concurrent") +fn concurrent( + update: fn(fn(Int) -> Result(Int, String)) -> Result(Int, String), +) -> Nil -- knotmirror 0.0.1