1// Stores that persist: small sets of JSON values by key that a program2// keeps across its runs, such as its settings, a basket or recent3// searches. A store is read whole when opened and kept in memory, so4// reading never waits; it is meant for up to about a megabyte, and5// larger data goes into files of its own.6//7// ```alloy8// import std::json;9// import std::option;10//11// var store = Store::open(&"alloy-example", &"settings");12// store.set(&"theme", Json::text(&"dark"));13// expect(store.keys().length() == 1);14// if (store.get(&"theme") is ::Some |&theme|) {15// expect_equal(&theme.to_json().view(), &"\"dark\"");16// }17// expect(store.flush());18// store.dispose(); // flushes too19// ```20//21// - **Natively** a store is one file, `<data directory>/<app>/<name>.json`22// (std::fs's `data_directory`), one object of keys to values, a member a23// line. `flush` writes it whole to `<name>.json.tmp`, syncs it to the24// disk and renames it over the old file, so a crash leaves the old file25// or the new, never half of one. A file that does not parse is moved26// aside to `<name>.json.bad` and the store starts empty.27// - **On the web** each key is a `localStorage` item, `<app>/<name>/<key>`,28// holding the value's JSON text: `set` writes through at once, and29// opening reads every item with the prefix, in the keys' byte order. A30// write the browser refuses (its quota, about 5 MB an origin, or private31// browsing) keeps the value in memory and makes `saved` false. The32// first store opened asks the browser to keep the site's data33// (`navigator.storage.persist()`), which Safari otherwise deletes after34// seven days unvisited.35// - **Nowhere to keep it:** a store whose directory is not known (WASI36// without the variables or the directory preopened), whose file cannot37// be read, or of the app "", is kept in memory, and `saved` says so.38//39// Stores are not for secrets: the file is one the user's other programs40// can read, and on the web any script of the origin can. Two processes of41// one app writing one store: the last flush wins; other tabs' changes on42// the web are not followed.4344import std::option;45import std::vector;46import std::string;47import std::io;48import std::fs;49import std::json;50import std::sort;51import std::dispose;52import std::process;53import std::ffi;5455// A store of the app, written back when flushed or disposed.56exp type Store : Disposable = struct {57 kept: KeptStore,58};5960// The app's store of the name: what was saved, or nothing. It never61// fails: one it cannot read or write is kept in memory, and `saved` says62// so.63exp fn Store::open(app: &[u8], name: &[u8]) -> Store {64 return Store { .kept = KeptStore::open(&app, &name) };65}6667// The value saved under the key.68exp fn get(self store: &Store, key: &[u8]) -> Option<&Json> => store.kept.get(&key);6970// Sets the key's value, written at the next flush (natively) or at once71// (on the web).72exp fn set(self store: &var Store, key: &[u8], value: Json) {73 store.kept.set(&key, move value);74}7576exp fn remove(self store: &var Store, key: &[u8]) {77 store.kept.remove(&key);78}7980// The keys in the order they were first set.81exp fn keys(self store: &Store) -> Vector<String> => store.kept.keys();8283// Writes the store through now: false when it could not be.84exp fn flush(self store: &var Store) -> bool => store.kept.flush();8586// Whether everything set has reached the disk or the browser.87exp fn saved(self store: &Store) -> bool => store.kept.saved();8889// The store's file, natively; None on the web and in memory.90exp fn path(self store: &Store) -> Option<&[u8]> => store.kept.path();9192// Flushes the store.93exp fn dispose(self store: &var Store) {94 store.kept.flush();95}9697/* --- A store kept by a holder --- */9899// A store a holder keeps open for the whole program and writes back100// itself, as pkg::alloy::ui's Ui does for `ui.store()`: the same store101// as a `Store` without being disposable, for a holder that cannot be102// disposed. It may be written off the holder's thread: `unsaved` gives103// what to write, `write` writes it anywhere, and `wrote` says how it went.104exp type KeptStore = struct {105 members: Vector<JsonMember>,106 place: Place,107 changes: u64, // the sets and removes made108 written: u64, // how many of them the file holds109 refused: Vector<String>, // on the web: the keys the browser last refused110};111112// Where a store is kept.113type Place = enum {114 File: String, // natively: its path115 Page: String, // on the web: its items' prefix, "<app>/<name>/"116 Memory117};118119// As `Store::open`.120exp fn KeptStore::open(app: &[u8], name: &[u8]) -> KeptStore {121 var store = KeptStore {122 .members = Vector<JsonMember>::empty(),123 .place = ::Memory,124 .changes = 0,125 .written = 0,126 .refused = Vector<String>::empty()127 };128 if (app.length() == 0) {129 return move store;130 }131 if (target() == "web-wasm32") {132 var prefix = f"{app}/{name}/";133 store.members = read_page(&prefix.view());134 store.place = ::Page(move prefix);135 return move store;136 }137 const directory = if (data_directory(&app) is ::Some |move d|) move d else {138 return move store;139 };140 var path = join(&directory.view(), &f"{name}.json".view());141 if (exists(&path.view())) {142 const text = if (read_file(&path.view()) is ::Some |move t|) move t else {143 return move store; // there, but not to be read144 };145 if (parse_json(&text) is ::Some |move json| && json is ::Object |move members|) {146 store.members = move members;147 } else {148 rename(&path.view(), &f"{path}.bad".view());149 }150 }151 store.place = ::File(move path);152 return move store;153}154155exp fn get(self store: &KeptStore, key: &[u8]) -> Option<&Json> {156 if (store.find(&key) is ::Some |k|) {157 return ::Some(&store.members.get(k).value);158 }159 return ::None;160}161162exp fn set(self store: &var KeptStore, key: &[u8], value: Json) {163 const found = store.find(&key);164 if (found is ::Some |k| && store.members.get(k).value == value) {165 return;166 }167 if (store.place is ::Page |&prefix|) {168 const stored = page_set(&f"{prefix}{key}".view(), &value.to_json().view());169 store.mark_refused(&key, !stored);170 }171 if (found is ::Some |k|) {172 store.members.get_var(k).value = move value;173 } else {174 store.members.push(JsonMember { .key = String::from(&key), .value = move value });175 }176 store.changes += 1;177}178179exp fn remove(self store: &var KeptStore, key: &[u8]) {180 const k = if (store.find(&key) is ::Some |k|) k else {181 return;182 };183 store.members.remove(k);184 if (store.place is ::Page |&prefix|) {185 page_remove(&f"{prefix}{key}".view());186 store.mark_refused(&key, false);187 }188 store.changes += 1;189}190191exp fn keys(self store: &KeptStore) -> Vector<String> {192 var keys = Vector<String>::with_capacity(store.members.length());193 for (store.members.view()) |&member| {194 keys.push(copy member.key);195 }196 return move keys;197}198199exp fn saved(self store: &KeptStore) -> bool => match (store.place) {200 ::File store.written == store.changes;201 ::Page store.refused.length() == 0;202 ::Memory false;203};204205exp fn path(self store: &KeptStore) -> Option<&[u8]> {206 if (store.place is ::File |&path|) {207 return ::Some(&path.view());208 }209 return ::None;210}211212// Writes the store through now, on the web the items the browser refused213// asked again: false when it could not be.214exp fn flush(self store: &var KeptStore) -> bool {215 if (store.place is ::Page |&prefix|) {216 var refused = move store.refused;217 store.refused = Vector<String>::empty();218 for (refused.view()) |&key| {219 if (store.find(&key.view()) is ::Some |k|) {220 const text = store.members.get(k).value.to_json();221 const stored = page_set(&f"{prefix}{key}".view(), &text.view());222 store.mark_refused(&key.view(), !stored);223 }224 }225 return store.refused.length() == 0;226 }227 if (store.unsaved() is ::Some |&w|) {228 const ok = w.write();229 store.wrote(&w, ok);230 return ok;231 }232 return store.saved();233}234235// What a store's file is to be written with.236exp type StoreWrite = struct {237 path: String,238 text: String,239 changes: u64, // as many as the store had made240};241242// What to write for the store's file to hold everything set, or None243// when it holds it already or the store has no file.244exp fn unsaved(self store: &KeptStore) -> Option<StoreWrite> {245 if (store.place is ::File |&path| && store.written != store.changes) {246 return ::Some(StoreWrite {247 .path = copy path,248 .text = file_text(&store.members.view()),249 .changes = store.changes250 });251 }252 return ::None;253}254255// How many sets and removes of the store the write holds.256exp fn changes(self w: &StoreWrite) -> u64 => w.changes;257258// Writes the file whole, atomically: to the path with `.tmp` after it,259// synced, then renamed over the old one, the directories made first.260exp fn write(self w: &StoreWrite) -> bool {261 make_directories(&parent(&w.path.view()));262 const temporary = f"{w.path}.tmp";263 var file = if (File::create(&temporary.view()) is ::Some |move f|) move f else {264 return false;265 };266 const ok = file.write(&w.text.view()) && file.sync();267 file.dispose();268 if (!ok || !rename(&temporary.view(), &w.path.view())) {269 remove_file(&temporary.view());270 return false;271 }272 return true;273}274275// Takes how a write `unsaved` gave went: what it held is saved when it276// was written.277exp fn wrote(self store: &var KeptStore, w: &StoreWrite, ok: bool) {278 if (ok && w.changes > store.written) {279 store.written = w.changes;280 }281}282283/* --- Inside --- */284285fn find(self store: &KeptStore, key: &[u8]) -> Option<u64> {286 for (store.members.view(), [..store.members.length()]) |&member, k| {287 if (member.key.view() == key) {288 return ::Some(k);289 }290 }291 return ::None;292}293294fn mark_refused(self store: &var KeptStore, key: &[u8], refused: bool) {295 for ([..store.refused.length()]) |k| {296 if (store.refused.get(k).view() == key) {297 if (!refused) {298 store.refused.remove(k);299 }300 return;301 }302 }303 if (refused) {304 store.refused.push(String::from(&key));305 }306}307308// The members as an object, one a line, so the file reads well.309fn file_text(members: &[JsonMember]) -> String {310 if (members.length() == 0) {311 return String::from(&"{}\n");312 }313 var out = String::from(&"{\n");314 for (members, [..members.length()]) |&member, k| {315 out.append(&" ");316 write_text(&member.key.view(), &var out);317 out.append(&": ");318 write_json(&member.value, &var out);319 out.append(if (k + 1 < members.length()) &",\n" else &"\n");320 }321 out.append(&"}\n");322 return move out;323}324325/* --- The page's localStorage (storage.web.js) --- */326327extern al_storage_read(prefix: c_pointer, length: u32) -> u32;328extern al_storage_take(at: c_pointer, capacity: u32);329extern al_storage_set(key: c_pointer, key_length: u32, value: c_pointer, value_length: u32) -> u32;330extern al_storage_remove(key: c_pointer, key_length: u32);331332// Whether the browser stored the item; nothing elsewhere.333fn page_set(item: &[u8], text: &[u8]) -> bool {334 if (target() == "web-wasm32") {335 const stored = al_storage_set(336 c_pointer::of(&item),337 item.length() to u32,338 c_pointer::of(&text),339 text.length() to u32340 );341 return stored != 0;342 }343 return false;344}345346fn page_remove(item: &[u8]) {347 if (target() == "web-wasm32") {348 al_storage_remove(c_pointer::of(&item), item.length() to u32);349 }350}351352// The items under the prefix, in their keys' byte order; one whose text353// is not JSON is left out.354fn read_page(prefix: &[u8]) -> Vector<JsonMember> {355 const length = al_storage_read(c_pointer::of(&prefix), prefix.length() to u32);356 var bytes: *var [u8] = new [0 to u8 : length to u64];357 al_storage_take(c_pointer::of(&bytes[..]), length);358 var members = Vector<JsonMember>::empty();359 var at: u64 = 4;360 for ([..number_at(&bytes[..], 0) to u64]) {361 const key_length = number_at(&bytes[..], at) to u64;362 const key = &bytes[at + 4..at + 4 + key_length];363 at += 4 + key_length;364 const value_length = number_at(&bytes[..], at) to u64;365 const value = &bytes[at + 4..at + 4 + value_length];366 at += 4 + value_length;367 if (parse_json(&value) is ::Some |move json|) {368 members.push(JsonMember { .key = String::from(&key), .value = move json });369 }370 }371 sort_by(&var members.items(), (a, b) => before(&a.key.view(), &b.key.view()));372 return move members;373}374375// The little-endian u32 at the offset; 0 past the end.376fn number_at(bytes: &[u8], at: u64) -> u32 {377 if (at + 4 > bytes.length()) {378 return 0;379 }380 return bytes[at] to u32381 | (bytes[at + 1] to u32) << 8382 | (bytes[at + 2] to u32) << 16383 | (bytes[at + 3] to u32) << 24;384}385386fn before(a: &[u8], b: &[u8]) -> bool {387 const shorter = if (a.length() < b.length()) a.length() else b.length();388 for ([..shorter]) |k| {389 if (a[k] != b[k]) {390 return a[k] < b[k];391 }392 }393 return a.length() < b.length();394}395396/* --- F12d as built --- */397398// **F12d as built** (2026-10-16; alloy-ui's decisions/F12.md, "Storage",399// question 9A):400// - `Store` as designed, over `KeptStore`, the same store for a holder401// that cannot be disposed (pkg::alloy::ui's Ui, question 21), whose402// writes may go off its thread: `unsaved` gives a `StoreWrite` (the403// path, the text, how many changes it holds), `write` writes it404// anywhere, `wrote` takes how it went. `path` gives the file. A value405// set equal to the one kept changes nothing. Keys keep the order they406// were first set in; the page's come in byte order.407// - The file: an object, a member a line, written to `<name>.json.tmp`,408// synced and renamed over the old, the directories made first; one409// that does not parse, or is no object, renamed to `<name>.json.bad`;410// one there but not to be read keeps the store in memory, as does a411// directory not known and the app "".412// - std::io's `File::sync` (`al_sys_sync`: fflush and fsync, `_commit`413// on Windows); std::fs's `data_directory` and `cache_directory`414// (`al_sys_user_directory`: an absolute `$XDG_DATA_HOME` or415// `$XDG_CACHE_HOME`, else under `$HOME`; `~/Library/Application416// Support` and `~/Library/Caches` on macOS, built and not yet run there;417// `SHGetKnownFolderPath` for the roaming and local app data on418// Windows, Shell32 and Ole32 loaded when asked so a program not asking419// imports neither; under WASI Linux's when the directory is there,420// that is preopened), the interpreter calling the same. Windows'421// `rename` writes through (`MOVEFILE_WRITE_THROUGH`).422// - The web: `storage.web.js` reads the items under `<app>/<name>/`423// packed, sets and removes them, a throw being a refusal; `flush` asks424// again for the items refused. The first store opened calls425// `navigator.storage.persist()`.426// - Tests: `tests/driver/storage.sh` runs `storage/stores.alloy` under427// alloyc test, interpreted and natively (round trips, a corrupt file428// moved aside, a `.tmp` left by a crash, a store that cannot be429// written, one in memory, a kept store's writes off its thread), and430// `storage/dirs.alloy` across runs natively, interpreted under each431// variable's case, under wasmtime with the directory preopened and432// without, and in node over a localStorage kept in a file, refusing433// past a quota; it is built for Windows and macOS. Windows runs by434// hand, the Known Folders not being redirected by a variable.435// - Sizes, release builds: hello world 145,288 bytes natively and 12,266436// of wasm, unchanged; one opening a store, setting a value and437// disposing it 244,728 and 106,993 (std::fs, std::json with its floats438// read and written exactly, the file's text).