usesuper::*;const VECTORS: &str = include_str!("send_vectors.json");/// A store as the vectors write one: rows by table, media sizes by key.structStore<'a> { rows: &'a Map<String, Value>, media: Option<&'a Map<String, Value>>,}implReadsforStore<'_> {fn row(&self, table: &str, id: &str) -> Result<Option<Map<String, Value>>, String> {Ok(self.table(table).into_iter().find(|r| r["id"] == json!(id))) }fn linked(&self, table: &str, column: &str, id: &str) -> Result<Vec<Map<String, Value>>, String> {Ok(self.table(table).into_iter().filter(|r| r.get(column) == Some(&json!(id))).collect()) }fn find(&self, table: &str, equals: &Map<String, Value>) -> Result<Vec<String>, String> {Ok(self.table(table).into_iter().filter(|r| equals.iter().all(|(k, v)| r.get(k) == Some(v))).map(|r| r["id"].as_str().unwrap().to_string()).collect()) }fn weigh(&self, key: &str, _folder: bool) -> Result<Option<u64>, String> {Ok(self.media.and_then(|m| m.get(key)).and_then(Value::as_u64)) }}implStore<'_> {fn table(&self, table: &str) -> Vec<Map<String, Value>> {self.rows.get(table).and_then(Value::as_array).map(|rows| rows.iter().filter_map(|r| r.as_object().cloned()).collect()).unwrap_or_default() }}fn vectors() -> Value { serde_json::from_str(VECTORS).unwrap()}fn tables(v: &Value) -> Tables { serde_json::from_value(v["tables"].clone()).unwrap()}/// One case run as the Worker runs it: contents on the sender, then held and/// keep on the receiver; `{payload, held, landing}` or `{refused}`.fn run_case(v: &Value, case: &Value) -> Value {let tables = tables(v);let sender = Store { rows: v["sender"]["rows"].as_object().unwrap(), media: v["sender"]["media"].as_object() };let make = Make { id: format!("send-{}", case["name"].as_str().unwrap()), table: case["table"].as_str().unwrap().into(), record: case["record"].as_str().unwrap().into(), from: serde_json::from_value(v["from"].clone()).unwrap(), made_at: v["made_at"].as_str().unwrap().into(), source_database: v["sender"]["database"].as_str().unwrap().into(), tables: tables.clone(), };let payload = match contents(&make, &sender) {Ok(p) => p,Err(r) => return json!({ "refused": r.code }), };let receiver = &v["receivers"][case["receiver"].as_str().unwrap()];let empty = Map::new();let store = Store { rows: receiver["rows"].as_object().unwrap_or(&empty), media: None };let land = Land { payload: json!(payload), tables, database: receiver["database"].as_str().unwrap().into(), sent_by: None, sent_at: v["sent_at"].as_str().unwrap().into() }; json!({ "payload": payload, "held": held(&land, &store).unwrap(), "landing": keep(&land, &store).unwrap() })}/// RULE: the vectors' expectations are what this build answers: the Worker's WASM reads the same file and must answer the same.#[test]fn the_vectors_hold() {letmut v = vectors();letmut answers = Map::new();for case in v["cases"].as_array().unwrap() { answers.insert(case["name"].as_str().unwrap().into(), run_case(&v, case)); }if std::env::var("SEND_VECTORS_WRITE").is_ok() { v["expect"] = Value::Object(answers);let dir = std::env::var("CARGO_MANIFEST_DIR").expect("cargo sets CARGO_MANIFEST_DIR");let path = std::path::Path::new(&dir).join("src/send_vectors.json"); std::fs::write(path, serde_json::to_string_pretty(&v).unwrap() + "\n").unwrap();return; } assert_eq!(Value::Object(answers), v["expect"], "run with SEND_VECTORS_WRITE=1 after a deliberate change");}fn case(name: &str) -> Value {let v = vectors();let case = v["cases"].as_array().unwrap().iter().find(|c| c["name"] == json!(name)).unwrap().clone(); run_case(&v, &case)}/// RULE: a book sends its file, cover and details, never the sender's own state (rating, status, reading position, review).#[test]fn a_book_sends_its_details_never_the_senders_state() {let out = case("book_with_file");let data = &out["payload"]["records"][0]["data"]; assert_eq!(data["title"], json!("The Synthetic Garden"));for own in ["status", "rating", "position", "review"] { assert!(data.get(own).is_none(), "{own} stayed behind"); } assert_eq!(out["payload"]["records"].as_array().unwrap().len(), 1, "no highlight goes with a book"); assert_eq!(out["payload"]["bytes"], json!(302_000));let landing = &out["landing"];let made = &landing["creates"][0]["data"]; assert_eq!(made["file"], json!("22222222-2222-4222-8222-222222222222/books/1111.epub"), "the key moves under the receiver's database"); assert_eq!(made["send_id"], json!("send-book_with_file")); assert_eq!(made["sent_by_number"], json!("+15550100001")); assert_eq!(landing["copies"].as_array().unwrap().len(), 2); assert_ne!(landing["creates"][0]["id"], json!("b1"), "the receiver's record has an id of its own");}/// RULE: a highlight goes alone: its words and note, and of its book only what says which book it is (no file).#[test]fn a_highlight_goes_alone_with_its_books_identity() {let out = case("highlight_alone");let records = out["payload"]["records"].as_array().unwrap(); assert_eq!(records.len(), 2);let book = records.iter().find(|r| r["table"] == json!("book")).unwrap(); assert_eq!(book["role"], json!("carried")); assert!(book["data"].get("file").is_none(), "the book's file never goes with a highlight"); assert_eq!(book["data"]["isbn"], json!("9780000000001")); assert_eq!(out["payload"]["bytes"], json!(2000), "only the cover's bytes");// Nothing held: the book is made as a shelf entry, and the highlight links to it.let creates = out["landing"]["creates"].as_array().unwrap(); assert_eq!(creates[0]["table"], json!("book"), "the book is made before what links to it"); assert_eq!(creates[1]["data"]["book"], creates[0]["id"]);}/// RULE: a carried record the receiver already holds is linked to, never made again.#[test]fn a_held_book_is_linked_not_duplicated() {let out = case("highlight_book_held");let creates = out["landing"]["creates"].as_array().unwrap(); assert_eq!(creates.len(), 1); assert_eq!(creates[0]["data"]["book"], json!("own-b1")); assert!(out["landing"]["copies"].as_array().unwrap().is_empty(), "a held book's cover is not copied");}/// RULE: a list sends its records; members the receiver holds are joined as theirs.#[test]fn a_list_sends_its_records() {let out = case("list");let tables: Vec<&str> = out["payload"]["records"].as_array().unwrap().iter().map(|r| r["table"].as_str().unwrap()).collect(); assert_eq!(tables.iter().filter(|t| **t == "book").count(), 2); assert_eq!(tables.iter().filter(|t| **t == "group_member").count(), 2);let creates = out["landing"]["creates"].as_array().unwrap();let joins: Vec<&Value> = creates.iter().filter(|c| c["table"] == json!("group_member")).collect();let pointed: BTreeSet<&str> = joins.iter().map(|j| j["data"]["record_id"].as_str().unwrap()).collect(); assert_eq!(pointed, BTreeSet::from(["own-b1", "own-b2"])); assert!(creates.iter().all(|c| c["table"] != json!("book")), "both books were held");let list = creates.iter().find(|c| c["table"] == json!("record_group")).unwrap(); assert!(joins.iter().all(|j| j["data"]["group"] == list["id"]));}/// RULE: a book the receiver holds by the same file says so and does not duplicate.#[test]fn the_same_file_is_already_held() {let out = case("duplicate_book"); assert_eq!(out["held"], json!([{ "table": "book", "sent": "b2", "id": "own-b2" }])); assert!(out["landing"]["creates"].as_array().unwrap().is_empty()); assert_eq!(out["landing"]["root"]["id"], json!("own-b2"));}/// RULE: a recipe sends its ingredients, re-pointed at the new recipe; a computed column never travels.#[test]fn a_recipe_sends_its_ingredients() {let out = case("recipe");let creates = out["landing"]["creates"].as_array().unwrap();let recipe = &creates[0]; assert_eq!(recipe["table"], json!("recipe")); assert!(recipe["data"].get("rating").is_none() && recipe["data"].get("cooked_count").is_none()); assert_eq!(creates.iter().filter(|c| c["table"] == json!("recipe_ingredient") && c["data"]["recipe"] == recipe["id"]).count(), 2);}/// RULE: a sealed table and a table with no send shape cannot be sent.#[test]fn sealed_and_shapeless_tables_are_never_sent() { assert_eq!(case("sealed"), json!({ "refused": "not_sendable" })); assert_eq!(case("no_shape"), json!({ "refused": "not_sendable" }));}/// RULE: keeping the same send twice lands the same ids.#[test]fn a_landed_id_is_the_same_each_time() { assert_eq!(landed_id("s", "book", "b1"), landed_id("s", "book", "b1")); assert_ne!(landed_id("s", "book", "b1"), landed_id("t", "book", "b1")); assert_eq!(landed_id("s", "book", "b1").len(), 36);}/// RULE: a shape names only real columns, never a computed or provenance column, and a sealed table declares none.#[test]fn a_shape_is_checked() {let v = vectors();letmut t = tables(&v); t.get_mut("book").unwrap().send.as_mut().unwrap().columns.push("nope".into()); assert_eq!(validate("book", &t).unwrap_err().code, "bad_send");letmut t = tables(&v); t.get_mut("recipe").unwrap().send.as_mut().unwrap().columns.push("cooked_count".into()); assert!(validate("recipe", &t).is_err());letmut t = tables(&v); t.get_mut("book").unwrap().sealed = true; assert!(validate("book", &t).is_err());letmut t = tables(&v); t.get_mut("book").unwrap().columns.retain(|c| c.key != "send_id"); assert!(validate("book", &t).is_err(), "provenance columns are declared");for table in tables(&v).keys() { validate(table, &tables(&v)).unwrap(); }}/// RULE: a payload of another format or version, or naming a column that does not travel, is refused.#[test]fn a_payload_is_read_strictly() {letmut payload = case("book_with_file")["payload"].clone();let t = tables(&vectors()); assert!(read_payload(payload.clone(), &t).is_ok()); payload["records"][0]["data"]["rating"] = json!(5); assert_eq!(read_payload(payload.clone(), &t).unwrap_err().code, "bad_payload"); payload["version"] = json!(2); assert!(read_payload(payload, &t).is_err());}