Skip to content

Commit 85248a0

Browse files
k2onclaude
andcommitted
Take Seed and the JSON encoder from petros
Both were copies of the engine's, identical byte for byte, and neither was domain code. `Seed` expands one uuid into as many ids as a verb needs — a rule of `fill_auto`'s contract, which is the engine's. `from_json` is the other end of `mutations!`: the macro declares the verbs, petros-codegen emits the TypeScript that calls them, and that TypeScript sends JSON. The id convention was documented by the generator and implemented here separately. They are `petros_schema::Seed` and `petros_schema::author` now, with tests this app never gave them — the expansion pinned against a fixture, because what it produces goes into the log and is replayed forever. The `author` feature is asked for by `storage` rather than on the dependency line. On the line it reached the wasm module: features unify per target, so `default-features = false` in crates/harken-wasm does not withdraw a feature the domain crate asked of a dependency unconditionally, and serde_json and uuid were in the module. `cargo tree -p harken-wasm --target wasm32-unknown-unknown` now counts zero of serde_json, uuid and diesel. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MPvMMuiQGPd6Sw7gx2GqGo
1 parent e1f4387 commit 85248a0

5 files changed

Lines changed: 47 additions & 100 deletions

File tree

‎Cargo.lock‎

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/harken/Cargo.toml‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,11 @@ rust-version.workspace = true
1111
# real SQLite. The wasm build turns this off: it has no SQLite of its own, only
1212
# a channel to the host's, so it wants `domain` and `schema` and nothing else.
1313
default = ["storage"]
14-
storage = ["dep:petros", "dep:serde", "dep:serde_json"]
14+
# `petros-schema/author` belongs here and not on the dependency line: features
15+
# are unified per target, so asking for it there would put serde_json and uuid
16+
# in the wasm module even though `default-features = false` turns this whole
17+
# feature off. Checked with `cargo tree -p harken-wasm`.
18+
storage = ["dep:petros", "dep:serde", "dep:serde_json", "petros-schema/author"]
1519
# A transport, for a client that runs. The domain itself has no opinion about
1620
# sockets and neither does the engine.
1721
ws = ["storage", "petros/ws"]

‎crates/harken/src/domain.rs‎

Lines changed: 2 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -184,8 +184,8 @@ pub fn fill_auto(mutation: &mut Value, uuid: Vec<u8>, now_ms: i64) {
184184
// only thing it can reach is [`Host`]. So the one uuid is expanded here,
185185
// in the single place non-determinism is allowed, and the log freezes it.
186186
Some("AddAlbum") => {
187-
let mut seed = Seed::from(&uuid);
188-
let album = ALBUMS[(seed.next() % ALBUMS.len() as u64) as usize];
187+
let mut seed = petros_schema::Seed::from(&uuid);
188+
let album = ALBUMS[(seed.next_u64() % ALBUMS.len() as u64) as usize];
189189
let tracks = (1..=TRACKS)
190190
.map(|n| {
191191
Value::Map(vec![
@@ -210,41 +210,3 @@ const TRACKS: usize = 5;
210210
/// Artists to attribute a generated album to. Chosen from the seed, so the
211211
/// choice is frozen in the log like every other generated value.
212212
const ALBUMS: [&str; 4] = ["Bicep", "Floating Points", "Jamie xx", "Caribou"];
213-
214-
/// xorshift128+, seeded from the uuid the caller supplied.
215-
///
216-
/// Deliberately not a good random number generator — it is a *deterministic
217-
/// expansion* of one non-deterministic seed, which is the only shape the log
218-
/// can hold. The unpredictability is the uuid; everything after it is a pure
219-
/// function of that, which is why replaying the entry reproduces the rows.
220-
struct Seed(u64, u64);
221-
222-
impl Seed {
223-
fn from(bytes: &[u8]) -> Self {
224-
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
225-
for b in bytes {
226-
h ^= *b as u64;
227-
h = h.wrapping_mul(0x1000_0000_01b3);
228-
}
229-
Seed(h | 1, h.rotate_left(31) | 1)
230-
}
231-
232-
fn next(&mut self) -> u64 {
233-
let mut x = self.0;
234-
let y = self.1;
235-
self.0 = y;
236-
x ^= x << 23;
237-
x ^= x >> 17;
238-
x ^= y ^ (y >> 26);
239-
self.1 = x;
240-
x.wrapping_add(y)
241-
}
242-
243-
fn id(&mut self) -> Vec<u8> {
244-
let (a, b) = (self.next(), self.next());
245-
let mut out = Vec::with_capacity(16);
246-
out.extend_from_slice(&a.to_be_bytes());
247-
out.extend_from_slice(&b.to_be_bytes());
248-
out
249-
}
250-
}

‎crates/harken/src/storage.rs‎

Lines changed: 8 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -143,72 +143,21 @@ pub const SCHEMA: &str = include_str!("../schema.sql");
143143

144144
// ------------------------------------------------------------------ authoring
145145

146-
/// Build a mutation from a verb name and its arguments, without knowing what
147-
/// either means.
146+
/// Author a mutation, as [`petros_schema::author`] does it, wrapped in this
147+
/// app's payload type.
148148
///
149-
/// The payload is just `{ "t": kind, ...args }`. Auto-filled fields are not
150-
/// this function's problem: `fill_auto` appends whatever the verb needs
151-
/// afterwards, so `Add` here is `{"text": "..."}` and the id and the timestamp
152-
/// arrive later, chosen by the domain.
153-
///
154-
/// One convention, and it is protocol rather than domain: a field named `id`
155-
/// holding a canonical uuid becomes the sixteen-byte string the log uses.
149+
/// The conversion is protocol rather than domain — the verb goes in `t`, and a
150+
/// field named `id` or ending `_id` becomes the sixteen bytes the log uses — so
151+
/// it lives in the schema crate, beside the macro that declares the verbs and
152+
/// the generator that emits the TypeScript calling them.
156153
pub fn from_value(kind: &str, args: serde_json::Value) -> Result<Payload, String> {
157-
let serde_json::Value::Object(args) = args else {
158-
return Err("the arguments should be a json object".into());
159-
};
160-
let mut fields = vec![(Value::Text("t".into()), Value::Text(kind.to_string()))];
161-
for (name, value) in args {
162-
let is_id = name == "id" || name.ends_with("_id");
163-
fields.push((Value::Text(name), json_to_cbor(value, is_id)?));
164-
}
165-
Ok(Payload(Value::Map(fields)))
154+
petros_schema::author::from_value(kind, args).map(Payload)
166155
}
167156

168157
/// As [`from_value`], for a caller that has the arguments as JSON text — which
169158
/// is every foreign one, since it has no CBOR encoder.
170159
pub fn from_json(kind: &str, args_json: &str) -> Result<Payload, String> {
171-
let args: serde_json::Value = if args_json.trim().is_empty() {
172-
serde_json::Value::Object(Default::default())
173-
} else {
174-
serde_json::from_str(args_json).map_err(|e| format!("the arguments are not json: {e}"))?
175-
};
176-
from_value(kind, args)
177-
}
178-
179-
fn json_to_cbor(value: serde_json::Value, is_id: bool) -> Result<Value, String> {
180-
use serde_json::Value as J;
181-
Ok(match value {
182-
J::Null => Value::Null,
183-
J::Bool(b) => Value::Bool(b),
184-
J::Number(n) => match n.as_i64() {
185-
Some(i) => Value::Integer(i.into()),
186-
// `docs/decisions.md`: no floats anywhere near the log.
187-
None => return Err(format!("{n} is not an integer")),
188-
},
189-
J::String(s) if is_id => Value::Bytes(
190-
petros::uuid::Uuid::parse_str(&s)
191-
.map_err(|e| format!("not an id: {e}"))?
192-
.as_bytes()
193-
.to_vec(),
194-
),
195-
J::String(s) => Value::Text(s),
196-
J::Array(items) => Value::Array(
197-
items
198-
.into_iter()
199-
.map(|v| json_to_cbor(v, false))
200-
.collect::<Result<_, _>>()?,
201-
),
202-
J::Object(entries) => Value::Map(
203-
entries
204-
.into_iter()
205-
.map(|(k, v)| {
206-
let is_id = k == "id" || k.ends_with("_id");
207-
Ok((Value::Text(k), json_to_cbor(v, is_id)?))
208-
})
209-
.collect::<Result<Vec<_>, String>>()?,
210-
),
211-
})
160+
petros_schema::author::from_json(kind, args_json).map(Payload)
212161
}
213162

214163
// The verbs the Rust peers spell out. Conveniences over [`from_value`], not a

‎docs/decisions.md‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -163,3 +163,33 @@ Petros still uses Diesel for its own three tables, and `petros::Connection` is
163163
still `diesel::SqliteConnection`. That is the engine's business. An app declares
164164
`App::SCHEMA` and `petros::batch` runs statements that take no parameters, so
165165
nothing above the engine has to name a database library at all.
166+
167+
## The seed and the JSON encoder were never ours
168+
169+
Both were copied into this app from the engine's example and were identical to
170+
it byte for byte. Neither was domain code.
171+
172+
`Seed` expands one uuid into as many ids as a verb needs, which is a rule of
173+
`fill_auto`'s contract: it is the only place non-determinism is allowed, and
174+
everything after it must be a pure function of what it wrote. `from_json` is the
175+
other end of `mutations!` — the macro declares the verbs, petros-codegen emits
176+
the TypeScript that calls them, and that TypeScript sends JSON. The id
177+
convention was documented by the generator and implemented here, separately, in
178+
every app that existed.
179+
180+
Both are `petros-schema` now, with tests the app never had: the expansion is
181+
pinned against a fixture, because what it produces goes into the log and is
182+
replayed forever.
183+
184+
## A feature on a dependency line reaches the wasm build
185+
186+
Asking for `petros-schema/author` beside `cbor` put serde_json and uuid in the
187+
module, even though `crates/harken-wasm` sets `default-features = false` on the
188+
domain crate. Features unify per target; turning a crate's own feature off does
189+
not withdraw one it asked of a dependency unconditionally.
190+
191+
This is the same trap this log already records for `default-features` itself,
192+
and it fails the same quiet way: the module builds, it runs, and it is bigger.
193+
Size is the loop here, because Metro pushes the module on every save. The
194+
feature belongs in `storage` — the one the wasm build actually turns off — and
195+
`cargo tree -p harken-wasm --target wasm32-unknown-unknown` is how to check.

0 commit comments

Comments
 (0)