~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

pds-server: imported records keep their blocks through the log

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:repo/import-signs-every-record
.changeset/import-keeps-every-record.mdnew+7−0
@@ -0,0 +1,7 @@
---
default: patch
---
# importRepo keeps every record as the CAR file has it
A repository moved in with `com.atproto.repo.importRepo` whose records hold a map that JSON writes as another value, such as a blob ref whose `ref` is a map of the one key `$link` rather than a link, as some servers wrote them, no longer leaves the account's log unreadable: before, the server logged `store failure` ("record …, which the commit … does not sign") on the import and on every write after it, could not compact the account's log, and stopped when it next read such a record from the log. Each record is now kept byte for byte at the CID the CAR names, through compaction and restarts, and the blob such a `ref` names is the account's to hold, listed by `listMissingBlobs` until it is uploaded. The same holds for a space repo's records imported with `com.atproto.space.importRepo`.
crates/pds-repo/src/full.rs+3−3
@@ -8,7 +8,7 @@ use crate::data::*;
use crate::mst::Block;
use crate::{
Change, EvOp, MAX_EVENT_BLOCKS, Op, OpResult, Record, Refused, Tids, car_file, car_with_roots,
event_blocks_len, make_record, mst,
event_blocks_len, make_record, mst, put_record, put_value,
};
use k256::ecdsa::SigningKey;
use k256::ecdsa::signature::hazmat::PrehashSigner;
@@ -312,7 +312,7 @@ impl Repo {
for (path, j) in &c.puts {
self.records.insert(
path.clone(),
make_record(from_json(j).map_err(|e| format!("record {path}: {e}"))?),
put_record(j).map_err(|e| format!("record {path}: {e}"))?,
);
self.written.insert(path.clone(), c.rev.clone());
}
@@ -460,7 +460,7 @@ impl Repo {
}
let puts: Vec<(String, serde_json::Value)> = originals
.keys()
.filter_map(|k| self.records.get(k).map(|r| (k.clone(), to_json(&r.value))))
.filter_map(|k| self.records.get(k).map(|r| (k.clone(), put_value(r))))
.collect();
let dels: Vec<String> = originals
.keys()
crates/pds-repo/src/lib.rs+40−3
@@ -135,6 +135,7 @@ pub struct EvOp {
pub struct Change {
pub rev: String,
pub head_bytes: Vec<u8>,
/// Each record it put, by path, as `put_value` has it.
pub puts: Vec<(String, serde_json::Value)>,
/// The CID of each record of `puts`, in its order.
pub put_cids: Vec<Vec<u8>>,
@@ -641,7 +642,7 @@ impl Repo {
for (path, r) in &after {
match r {
Some(r) => {
change.puts.push((path.clone(), to_json(&r.value)));
change.puts.push((path.clone(), put_value(r)));
change.put_cids.push(r.cid.clone());
}
None => change.dels.push(path.clone()),
@@ -870,6 +871,43 @@ pub fn make_record(value: V) -> Record {
}
}
/// A record as a commit's `puts` hold it, for the log: its JSON, where that
/// reads back as its block, and otherwise its block, in hex. JSON is not
/// one-to-one: a map of the one key `$link`, a CID string, as some servers
/// wrote a blob ref's `ref`, is written as a link is, and a map with `$bytes`
/// as bytes are, so a record a CAR file brings may hold a map that JSON reads
/// back as another value, of another CID. A record is a map, so a string is
/// never one's JSON.
pub fn put_value(r: &Record) -> serde_json::Value {
let json = to_json(&r.value);
if from_json(&json).is_ok_and(|v| encode(&v) == r.bytes) {
json
} else {
serde_json::Value::String(hex::encode(&r.bytes))
}
}
/// The block of the record a put holds, as `put_value` wrote it.
pub fn put_block(put: &serde_json::Value) -> Result<Vec<u8>, String> {
match put {
serde_json::Value::String(h) => hex::decode(h).map_err(|_| format!("{h} for hex")),
_ => from_json(put).map(|v| encode(&v)),
}
}
/// The record a put holds, as `put_value` wrote it.
pub fn put_record(put: &serde_json::Value) -> Result<Record, String> {
if !put.is_string() {
return from_json(put).map(make_record);
}
let bytes = put_block(put)?;
Ok(Record {
cid: cid_of(0x71, &bytes),
value: decode(&bytes)?,
bytes,
})
}
fn varint(out: &mut Vec<u8>, mut n: usize) {
while n >= 0x80 {
out.push((n as u8 & 0x7f) | 0x80);
@@ -972,8 +1010,7 @@ mod tests {
.iter()
.position(|p| p == cid)
.expect("a record new in the tree is put");
let rec = make_record(from_json(&c.puts[at].1).unwrap());
Arc::from(rec.bytes.as_slice())
Arc::from(put_block(&c.puts[at].1).unwrap())
});
self.blocks.insert(cid.clone(), (bytes, *n, rev.clone()));
}
crates/pds-repo/Cargo.toml+1−0
@@ -8,6 +8,7 @@ license.workspace = true
[dependencies]
base64.workspace = true
bs58.workspace = true
hex.workspace = true
k256.workspace = true
rand.workspace = true
serde_json.workspace = true
crates/pds-server/src/checkpoint/unmarked.rs+55−3
@@ -18,8 +18,7 @@
use crate::blobs::{Blobs, cids_in};
use crate::space_repo;
use pds_repo::data::from_json;
use pds_repo::{Tids, valid_tid};
use pds_repo::{Tids, put_record, valid_tid};
use serde_json::{Value as Json, json};
use std::collections::BTreeMap;
@@ -125,7 +124,9 @@ impl Unmarked {
.filter_map(|p| match p.as_array().map(Vec::as_slice) {
Some([Json::String(path), value]) => Some((
path.clone(),
from_json(value).map(|v| cids_in(&v)).unwrap_or_default(),
put_record(value)
.map(|r| cids_in(&r.value))
.unwrap_or_default(),
)),
_ => None,
})
@@ -193,3 +194,54 @@ impl Unmarked {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use pds_repo::data::{V, cid_of, cid_string};
use pds_repo::{make_record, put_value};
/// A space record whose put holds its block, as `put_value` writes one
/// whose JSON would read back as another, a blob ref whose `ref` is a
/// map of the one key `$link`, references its blob when replayed before
/// the mark, from an import and from a commit alike.
#[test]
fn a_put_of_a_block_references_its_blobs() {
let blob = cid_string(&cid_of(0x55, b"blob"));
let text = |t: &str| V::Str(t.into());
let map =
|kv: &[(&str, V)]| V::Map(kv.iter().map(|(k, v)| (k.to_string(), v.clone())).collect());
let put = put_value(&make_record(map(&[
("$type", text("a.b.c")),
(
"img",
map(&[
("$type", text("blob")),
("ref", map(&[("$link", text(&blob))])),
("mimeType", text("text/plain")),
("size", V::Int(4)),
]),
),
])));
assert!(put.is_string(), "a put of the record's block");
let space = "at://did:web:example.com/space/com.example.chat/room";
let (mut unmarked, mut blobs, mut tids) =
(Unmarked::default(), Blobs::default(), Tids::new());
unmarked.replay(
&json!({ "t": space_repo::IMPORT, "space": space, "rev": "3mzzzzzzzzzz2", "records": [["a.b.c/x", put]] }),
&mut blobs,
&mut tids,
);
unmarked.replay(
&json!({ "t": space_repo::ENTRY, "space": space, "rev": "3mzzzzzzzzzz3", "puts": [["a.b.c/y", put]], "dels": [] }),
&mut blobs,
&mut tids,
);
let saved: Vec<(&str, &str, &[String])> = unmarked.saved().collect();
let cids = [blob];
assert_eq!(
saved,
[(space, "a.b.c/x", &cids[..]), (space, "a.b.c/y", &cids[..])]
);
}
}
crates/pds-server/src/migration/tests.rs+101−1
@@ -374,10 +374,20 @@ impl Built {
/// A repository of `did` holding these records, by path, its commit
/// signed with a key of its old server's.
fn of(did: &str, records: &[(&str, Json)]) -> Built {
let values: Vec<(&str, V)> = records
.iter()
.map(|(path, value)| (*path, record_from_json(value).unwrap()))
.collect();
Built::of_values(did, &values)
}
/// A repository of `did` holding these records, each the block its
/// value encodes to, whatever JSON would make of it.
fn of_values(did: &str, records: &[(&str, V)]) -> Built {
let mut entries = Vec::new();
let mut blocks = Vec::new();
for (path, value) in records {
let r = make_record(record_from_json(value).unwrap());
let r = make_record(value.clone());
entries.push((path.as_bytes().to_vec(), r.cid.clone()));
blocks.push((r.cid, r.bytes));
}
@@ -709,6 +719,96 @@ async fn imports_are_checked_and_whole() {
assert_eq!(records_of(&reopened, &m.did).len(), 2);
}
/// A CAR file's records are kept as its blocks, byte for byte, where JSON
/// would write one as another value: a map of the one key `$link`, a CID
/// string, as some servers wrote a blob ref's `ref`, which JSON writes as a
/// link; a map of `$bytes`; and a `$link` that is no CID. Each is held at
/// the CAR's CID, as its bytes, once the log is compacted into a table and
/// read from it, in `getRepo`, and through a restart; and the blob such a
/// `ref` names is missing until it is uploaded, as a link's is.
#[tokio::test]
async fn imports_keep_each_record_as_its_block() {
let m = Move::start("migration-blocks", |c| c.log_floor = 2048).await;
let token = m.moved().await;
let blob_cid = cid_string(&cid_of(0x55, b"blob"));
let text = |t: &str| V::Str(t.into());
let map =
|kv: &[(&str, V)]| V::Map(kv.iter().map(|(k, v)| (k.to_string(), v.clone())).collect());
let rec = |field: &str, v: V| {
map(&[
("$type", text("a.b.c")),
("pad", text(&"x".repeat(800))),
(field, v),
])
};
let icon = map(&[
("$type", text("blob")),
("ref", map(&[("$link", text(&blob_cid))])),
("mimeType", text("text/plain")),
("size", V::Int(4)),
]);
let values = [
("a.b.c/bytes", rec("b", map(&[("$bytes", text("AQID"))]))),
("a.b.c/icon", rec("icon", icon)),
("a.b.c/odd", rec("l", map(&[("$link", text("not a cid"))]))),
("a.b.c/plain", rec("n", V::Int(1))),
];
let built = Built::of_values(&m.did, &values);
let want: Vec<(String, Vec<u8>, Vec<u8>)> = values
.iter()
.map(|(p, v)| {
let r = make_record(v.clone());
(p.to_string(), r.cid, r.bytes)
})
.collect();
let held = |s: &Service| -> Vec<(String, Vec<u8>, Vec<u8>)> {
records_of(s, &m.did)
.into_iter()
.map(|(p, r)| (p, r.cid, r.bytes))
.collect()
};
let auth = format!("Bearer {token}");
let missing = |s: &Shared| {
let (s, auth) = (s.clone(), auth.clone());
async move {
send(&s, MISSING, Some(&auth), None, &[], b"")
.await
.unwrap()
}
};
let listed = json!({ "blobs": [{ "cid": blob_cid, "recordUri": format!("at://{}/a.b.c/icon", m.did) }], "cursor": blob_cid });
assert_eq!(import(&m.new, &token, &built.good()).await, Ok(Json::Null));
assert_eq!(held(&m.new), want);
assert_eq!(missing(&m.new).await, listed);
// Compacted, its records read from the table.
let wal = store_of(&m.new, &m.did, |st| st.wal.clone());
wal.wait_compacted();
assert!(wal.checkpoint_generation() > 0, "the log was not compacted");
store_of(&m.new, &m.did, |st| {
st.ctx.blocks.forget(st.disk.table.as_ref().unwrap().id())
});
assert_eq!(held(&m.new), want);
let car = store_of(&m.new, &m.did, |st| {
crate::sync::CarStream::of(st, None).unwrap()
});
let (_, blocks) = pds_repo::read_car(&car.bytes().unwrap()).unwrap();
assert!(
blocks.iter().all(|(c, b)| cid_of(c[1], b) == *c),
"a block of getRepo is not its CID's"
);
for (_, cid, bytes) in &want {
assert!(
blocks.contains(&(cid.clone(), bytes.clone())),
"getRepo leaves a record out"
);
}
// Through a restart.
let reopened = open_with(&m.dirs[1], &m.plc.url, |c| c.hostname = "new.test".into());
assert_eq!(repo_of(&reopened, &m.did, |r| r.root.clone()), built.root);
assert_eq!(held(&reopened), want);
assert_eq!(missing(&reopened).await, listed);
}
/// The old server signs the operation that moves the DID, with its mailed
/// token, once; the new one submits it, refusing one that would not leave
/// the DID here, and puts `#identity` with no handle on its firehose; the
crates/pds-server/src/blobs.rs+22−7
@@ -51,8 +51,8 @@ use axum::extract::{Extension, State as AxState};
use axum::http::{HeaderMap, HeaderValue, Method, header};
use axum::response::Response;
use http_body::{Frame, SizeHint};
use pds_repo::data::{V, cid_of, cid_string, from_json, valid_cid_string};
use pds_repo::{Change, Op, OpResult};
use pds_repo::data::{V, cid_of, cid_string, parse_cid, valid_cid_string};
use pds_repo::{Change, Op, OpResult, put_record};
use serde_json::{Map, Value as Json, json};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet, HashMap};
@@ -188,18 +188,28 @@ pub(crate) struct BlobRef {
}
/// The blob ref a map is: exactly `$type` blob, a link `ref`, a `mimeType`
/// with a `/`, and a `size` of 0 or more, or -1.
/// with a `/`, and a `size` of 0 or more, or -1. A `ref` that is a map of
/// the one key `$link`, a CID string, is that link, as JSON writes both
/// (`spec/BLOBS.md`, "Blob refs in records").
fn blob_ref(m: &[(String, V)]) -> Option<BlobRef> {
if m.len() != 4 {
return None;
}
let get = |k: &str| m.iter().find(|(n, _)| n == k).map(|(_, v)| v);
match (get("$type")?, get("ref")?, get("mimeType")?, get("size")?) {
(V::Str(t), V::Link(cid), V::Str(mime), V::Int(size))
let cid = match get("ref")? {
V::Link(cid) => cid.clone(),
V::Map(r) => match r.as_slice() {
[(k, V::Str(cid))] if k == "$link" => parse_cid(cid)?,
_ => return None,
},
_ => return None,
};
match (get("$type")?, get("mimeType")?, get("size")?) {
(V::Str(t), V::Str(mime), V::Int(size))
if t == "blob" && mime.contains('/') && *size >= -1 =>
{
Some(BlobRef {
cid: cid.clone(),
cid,
mime: mime.clone(),
size: *size,
})
@@ -612,7 +622,12 @@ impl Blobs {
let written: BTreeMap<&String, Vec<String>> = c
.puts
.iter()
.map(|(p, j)| (p, from_json(j).map(|v| cids_in(&v)).unwrap_or_default()))
.map(|(p, j)| {
(
p,
put_record(j).map(|r| cids_in(&r.value)).unwrap_or_default(),
)
})
.collect();
for path in c.puts.iter().map(|(p, _)| p).chain(&c.dels) {
let now = written.get(path).cloned().unwrap_or_default();
crates/pds-server/src/checkpoint.rs+5−8
@@ -86,8 +86,8 @@ use crate::space_repo::{self, Restore, Spaces};
use crate::{Account, Store};
use axum::body::Bytes;
use k256::ecdsa::SigningKey;
use pds_repo::data::{V, cid_of, cid_string, decode, encode, from_json};
use pds_repo::{Change, Record, Repo, Source, Tids};
use pds_repo::data::{V, cid_of, cid_string, decode, encode};
use pds_repo::{Change, Record, Repo, Source, Tids, put_block};
use pds_store::table::{BlockCache, Key, Table, TableWriter, file_number};
use pds_store::{Fold, Layout, Pos};
use serde_json::Value as Json;
@@ -1171,8 +1171,7 @@ impl Memtable {
}
// What the log holds is what its commits signed.
for ((p, value), cid) in change.puts.iter().zip(&put_cids) {
let bytes =
encode(&from_json(value).map_err(|why| format!("record {p}: {why}"))?);
let bytes = put_block(value).map_err(|why| format!("record {p}: {why}"))?;
if cid_of(0x71, &bytes) != *cid {
return Err(format!("record {p}, which the commit {rev} does not sign"));
}
@@ -1388,12 +1387,10 @@ fn skim<'a>(
Ok(())
}
/// A record's block, from its value as a put has it.
/// A record's block, from its value as a put has it (`put_value`).
fn record_block(value: &str) -> Result<Vec<u8>, String> {
let json: Json = serde_json::from_str(value).map_err(|e| format!("a record: {e}"))?;
Ok(encode(
&from_json(&json).map_err(|why| format!("a record: {why}"))?,
))
put_block(&json).map_err(|why| format!("a record: {why}"))
}
fn unhex(h: &str) -> Result<Vec<u8>, String> {
crates/pds-server/src/space_repo.rs+69−5
@@ -52,7 +52,7 @@ use axum::http::{StatusCode, header};
use axum::response::{IntoResponse, Response};
use pds_lexicon::Method;
use pds_repo::data::{V, cid_string, decode, from_json, parse_cid, to_json};
use pds_repo::{Record, Tids, make_record, valid_tid};
use pds_repo::{Record, Tids, make_record, put_record, put_value, valid_tid};
use pds_space::lthash::element;
use pds_space::mac::{self, ACCEPT_SIGNATURE};
use pds_space::{Commit, LtHash, MacHeaders, Profile, SharedSecret, SpaceRef, star};
@@ -234,7 +234,7 @@ impl Change {
let mut e = json!({
"t": ENTRY, "space": self.space, "rev": self.rev, "clear": self.clear,
"ops": self.ops.iter().map(|o| json!([o.path, cid_text(&o.cid), cid_text(&o.prev)])).collect::<Vec<_>>(),
"puts": self.puts.iter().map(|(p, r)| json!([p, to_json(&r.value)])).collect::<Vec<_>>(),
"puts": self.puts.iter().map(|(p, r)| json!([p, put_value(r)])).collect::<Vec<_>>(),
"dels": self.dels,
});
if let Some(kept) = &self.kept {
@@ -273,7 +273,7 @@ impl Change {
.map(|p| match p.as_array().map(Vec::as_slice) {
Some([p, v]) => Ok((
path(p)?,
make_record(from_json(v).map_err(|why| format!("a space record: {why}"))?),
put_record(v).map_err(|why| format!("a space record: {why}"))?,
)),
_ => Err(bad("put")),
})
@@ -322,7 +322,7 @@ impl Import {
fn entry(&self, data: &[u8; 32]) -> Json {
json!({
"t": IMPORT, "space": self.space, "rev": self.rev, "data": hex::encode(data),
"records": self.records.iter().map(|(p, r)| json!([p, to_json(&r.value)])).collect::<Vec<_>>(),
"records": self.records.iter().map(|(p, r)| json!([p, put_value(r)])).collect::<Vec<_>>(),
})
}
@@ -349,7 +349,7 @@ impl Import {
.map(|p| match p.as_array().map(Vec::as_slice) {
Some([Json::String(p), v]) if star::is_record_path(p) => Ok((
p.clone(),
make_record(from_json(v).map_err(|why| format!("a space record: {why}"))?),
put_record(v).map_err(|why| format!("a space record: {why}"))?,
)),
_ => Err(bad("record")),
})
@@ -4829,6 +4829,70 @@ pub(crate) mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
/// An archive's records are kept as their bytes where JSON would write
/// one as another value: a blob ref whose `ref` is a map of the one key
/// `$link`, a CID string, which JSON writes as a link; a map of
/// `$bytes`; a `$link` that is no CID. `getRepo` answers each byte for
/// byte, read from the log, from the table it is compacted into, and
/// through a restart, and the blob such a `ref` names is the repo's.
#[tokio::test]
async fn imports_keep_each_record_as_its_bytes() {
let plc = plc().await;
let dir = scratch("space-import-bytes");
let s = open(&dir, &plc);
let (alice, t) = create(&s, "alice").await;
let cid = raw_cid(b"spec-pds import blob");
let text = |t: &str| V::Str(t.into());
let map =
|kv: &[(&str, V)]| V::Map(kv.iter().map(|(k, v)| (k.to_string(), v.clone())).collect());
let rec = |field: &str, v: V| map(&[("$type", text("a.b.c")), (field, v)]);
let icon = map(&[
("$type", text("blob")),
("ref", map(&[("$link", text(&cid))])),
("mimeType", text("text/plain")),
("size", V::Int(20)),
]);
let records: Vec<(String, Vec<u8>)> = [
("a.b.c/bytes", rec("b", map(&[("$bytes", text("AQID"))]))),
("a.b.c/icon", rec("icon", icon)),
("a.b.c/odd", rec("l", map(&[("$link", text("not a cid"))]))),
]
.into_iter()
.map(|(p, v)| (p.to_string(), pds_repo::data::encode(&v)))
.collect();
let mut h = LtHash::new();
for (p, v) in &records {
h.add(&element(p, &cid_string(&pds_repo::data::cid_of(0x71, v))));
}
let commit = Commit {
repo: alice.clone(),
space: OTHER.into(),
rev: "3mzzzzzzzzzz2".into(),
data: h.digest(),
};
import_repo_of(&s, &t, &star::write_repo(&commit, &records))
.await
.unwrap();
let held = |s: &Shared| {
let (s, t, alice) = (s.clone(), t.clone(), alice.clone());
async move {
let archive = get_repo_of(&s, &t, &alice, OTHER).await.unwrap();
star::read_any_repo(&archive).unwrap().records
}
};
let cids = json!({ "cids": [cid] });
assert_eq!(held(&s).await, records, "from the log");
assert_eq!(space_cids(&s, &t, &alice, OTHER, &[]).await, cids);
compact(&s, &alice);
assert_eq!(held(&s).await, records, "from the table");
crate::space_notify::tests::idle(&s).await;
drop(s);
let s = open(&dir, &plc);
assert_eq!(held(&s).await, records, "through a restart");
assert_eq!(space_cids(&s, &t, &alice, OTHER, &[]).await, cids);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_commit_that_does_not_add_up_is_refused() {
let cache = BlockCache::new(1 << 20);
spec/BLOBS.md+8−0
@@ -110,6 +110,14 @@ ref, of a blob no account holds: `400 BlobNotFound` (below).
A blob ref is part of the record, and of what its CID covers, as any other
map is: `ref` is a CID link in DAG-CBOR.
A record that a CAR file (`MIGRATION.md`, "importRepo") or a space repo's
archive (`SPACES-EXPORT.md`, "importRepo") brings may hold, as a blob ref's
`ref`, a map of the one key `$link` whose value is a CID string, in place
of a link, as some servers wrote them. JSON writes that map as it writes
the link, and it is taken as the link: the map of the four keys is a blob
ref of that CID. The record keeps the map as it is, and the CID its block
has. A write cannot make one: in its JSON, `{"$link": …}` is a link.
The legacy shape, a map of exactly `cid`, a CID string of the `raw` codec,
and `mimeType`, a non-empty string, is refused: `400 InvalidRequest`. It is
checked with the record, right after its `$type` and `validate`, so before
spec/MIGRATION.md+6−1
Cargo.lock+1−0