Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: updates detection of tile docs and doesn't log them by default #514

Merged
merged 3 commits into from
Sep 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion one/src/migrations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ pub struct FromIpfsOpts {
#[arg(long, env = "CERAMIC_ONE_LOCAL_NETWORK_ID")]
local_network_id: Option<u32>,

/// Log information about tile documents found during the migration.
#[arg(long, env = "CERAMIC_ONE_LOG_TILE_DOCS", default_value_t = false)]
log_tile_docs: bool,

#[command(flatten)]
log_opts: LogOpts,
}
Expand Down Expand Up @@ -93,7 +97,9 @@ async fn from_ipfs(opts: FromIpfsOpts) -> Result<()> {
let blocks = FSBlockStore {
input_ipfs_path: opts.input_ipfs_path,
};
db.event_store.migrate_from_ipfs(network, blocks).await?;
db.event_store
.migrate_from_ipfs(network, blocks, opts.log_tile_docs)
.await?;
Ok(())
}

Expand Down
95 changes: 75 additions & 20 deletions service/src/event/migration.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::collections::BTreeSet;

use anyhow::{anyhow, bail, Context as _, Result};
use anyhow::{anyhow, Context as _};
use ceramic_core::{EventId, Network};
use ceramic_event::unvalidated::{self, signed::cacao::Capability};
use cid::Cid;
Expand All @@ -21,6 +21,7 @@ pub struct Migrator<'a, S> {
network: Network,
blocks: S,
batch: Vec<ReconItem<EventId>>,
log_tile_docs: bool,

// All unsigned init payloads we have found.
unsigned_init_payloads: BTreeSet<Cid>,
Expand All @@ -32,6 +33,7 @@ pub struct Migrator<'a, S> {
referenced_unsigned_init_payloads: BTreeSet<Cid>,

error_count: usize,
tile_doc_count: usize,
event_count: usize,
}

Expand All @@ -40,15 +42,18 @@ impl<'a, S: BlockStore> Migrator<'a, S> {
service: &'a CeramicEventService,
network: Network,
blocks: S,
) -> Result<Self> {
log_tile_docs: bool,
) -> anyhow::Result<Self> {
Ok(Self {
network,
service,
blocks,
log_tile_docs,
batch: Default::default(),
unsigned_init_payloads: Default::default(),
referenced_unsigned_init_payloads: Default::default(),
error_count: 0,
tile_doc_count: 0,
event_count: 0,
})
}
Expand All @@ -57,28 +62,46 @@ impl<'a, S: BlockStore> Migrator<'a, S> {
if let Some(block) = self.blocks.block_data(cid).await? {
Ok(block)
} else {
Err(AnalyzeError::MissingBlock(*cid).into())
Err(Error::MissingBlock(*cid))
}
}

#[instrument(skip(self), ret(level = Level::DEBUG))]
pub async fn migrate(mut self) -> Result<()> {
pub async fn migrate(mut self) -> anyhow::Result<()> {
const PROGRESS_COUNT: usize = 1_000;

let mut all_blocks = self.blocks.blocks();
let mut count = 0;
while let Some((cid, data)) = all_blocks.try_next().await? {
let ret = self.process_block(cid, &data).await;
if let Err(err) = ret {
self.error_count += 1;
error!(%cid, err=format!("{err:#}"), "error processing block");
let log = match err {
Error::FoundInitTileDoc(_) | Error::FoundDataTileDoc(_) => {
self.tile_doc_count += 1;
self.log_tile_docs
}
Error::MissingBlock(_) | Error::Fatal(_) => {
self.error_count += 1;
true
}
};
if log {
error!(%cid, err=format!("{err:#}"), "error processing block");
}
}
if self.batch.len() > 1000 {
self.write_batch().await?
}
count += 1;
if count % PROGRESS_COUNT == 0 {
info!(last_block=%cid, count, error_count = self.error_count, "migrated blocks");
info!(
last_block=%cid,
block_count = count,
event_count = self.event_count,
error_count = self.error_count,
tile_doc_count = self.tile_doc_count,
"migrated blocks"
);
}
}
self.write_batch().await?;
Expand All @@ -88,6 +111,7 @@ impl<'a, S: BlockStore> Migrator<'a, S> {
info!(
event_count = self.event_count,
error_count = self.error_count,
tile_doc_count = self.tile_doc_count,
"migration finished"
);
Ok(())
Expand All @@ -96,7 +120,8 @@ impl<'a, S: BlockStore> Migrator<'a, S> {
// event.
#[instrument(skip(self, data), ret(level = Level::DEBUG))]
async fn process_block(&mut self, cid: Cid, data: &[u8]) -> Result<()> {
let event: Result<unvalidated::RawEvent<Ipld>, _> = serde_ipld_dagcbor::from_slice(data);
let event: Result<unvalidated::RawEvent<Ipld>> =
serde_ipld_dagcbor::from_slice(data).map_err(Error::new_fatal);
match event {
Ok(unvalidated::RawEvent::Unsigned(_)) => {
self.unsigned_init_payloads.insert(cid);
Expand Down Expand Up @@ -128,7 +153,8 @@ impl<'a, S: BlockStore> Migrator<'a, S> {
.load_block(&cid)
.await
.context("finding init event block")?;
let payload: unvalidated::init::Payload<Ipld> = serde_ipld_dagcbor::from_slice(&data)?;
let payload: unvalidated::init::Payload<Ipld> =
serde_ipld_dagcbor::from_slice(&data).map_err(Error::new_fatal)?;
let event_builder = EventBuilder::new(
cid,
payload.header().model().to_vec(),
Expand All @@ -148,7 +174,8 @@ impl<'a, S: BlockStore> Migrator<'a, S> {
async fn write_batch(&mut self) -> Result<()> {
self.service
.insert_events(&self.batch, DeliverableRequirement::Lazy)
.await?;
.await
.map_err(Error::new_fatal)?;
self.event_count += self.batch.len();
self.batch.truncate(0);
Ok(())
Expand All @@ -172,9 +199,11 @@ impl<'a, S: BlockStore> Migrator<'a, S> {
.context("decoding payload")
.map_err(|err| {
if self.is_tile_doc_data(&payload_data) {
anyhow!("found data Tile Document, skipping")
Error::FoundDataTileDoc(cid)
} else if self.is_tile_doc_init(&payload_data) {
Error::FoundInitTileDoc(cid)
} else {
anyhow!("{err}")
Error::new_fatal(err)
}
})?;
let event_builder = match &payload {
Expand Down Expand Up @@ -205,7 +234,8 @@ impl<'a, S: BlockStore> Migrator<'a, S> {
.await
.context("finding capability block")?;
// Parse capability to ensure it is valid
let cap: Capability = serde_ipld_dagcbor::from_slice(&data)?;
let cap: Capability =
serde_ipld_dagcbor::from_slice(&data).map_err(Error::new_fatal)?;
debug!(%capability_cid, ?cap, "capability");
capability = Some((capability_cid, cap));
}
Expand Down Expand Up @@ -241,10 +271,21 @@ impl<'a, S: BlockStore> Migrator<'a, S> {
.load_block(cid)
.await
.context("finding init payload block")?;
let init: unvalidated::RawEvent<Ipld> =
serde_ipld_dagcbor::from_slice(&init_data).context("decoding init envelope")?;
let init: unvalidated::RawEvent<Ipld> = serde_ipld_dagcbor::from_slice(&init_data)
.context("decoding init envelope")
.map_err(|err| {
if self.is_tile_doc_init(&init_data) {
Error::FoundInitTileDoc(*cid)
} else {
Error::new_fatal(err)
}
})?;
match init {
unvalidated::RawEvent::Time(_) => bail!("init event must not be a time event"),
unvalidated::RawEvent::Time(_) => {
return Err(Error::new_fatal(anyhow!(
"init event must not be a time event"
)))
}
unvalidated::RawEvent::Signed(init) => {
let init_payload_data = self
.load_block(
Expand All @@ -259,9 +300,9 @@ impl<'a, S: BlockStore> Migrator<'a, S> {
.context("decoding init payload")
.map_err(|err| {
if self.is_tile_doc_init(&init_payload_data) {
anyhow!("found init Tile Document, skipping")
Error::FoundInitTileDoc(*cid)
} else {
anyhow!("{err}")
Error::new_fatal(err)
}
})
}
Expand All @@ -288,7 +329,8 @@ impl<'a, S: BlockStore> Migrator<'a, S> {
.load_block(&proof_id)
.await
.context("finding proof block")?;
let proof: unvalidated::Proof = serde_ipld_dagcbor::from_slice(&data)?;
let proof: unvalidated::Proof =
serde_ipld_dagcbor::from_slice(&data).map_err(Error::new_fatal)?;
let mut curr = proof.root();
let mut proof_edges = Vec::new();
for index in event.path().split('/') {
Expand Down Expand Up @@ -324,10 +366,23 @@ impl<'a, S: BlockStore> Migrator<'a, S> {
}
}

type Result<T> = std::result::Result<T, Error>;

#[derive(Error, Debug)]
enum AnalyzeError {
enum Error {
#[error("missing linked block from event {0}")]
MissingBlock(Cid),
#[error("block is an init tile document: {0}")]
FoundInitTileDoc(Cid),
#[error("block is a data tile document: {0}")]
FoundDataTileDoc(Cid),
#[error("fatal error: {0:#}")]
Fatal(#[from] anyhow::Error),
}
impl Error {
fn new_fatal(err: impl Into<anyhow::Error>) -> Self {
Self::from(err.into())
}
}

struct EventBuilder {
Expand Down
9 changes: 7 additions & 2 deletions service/src/event/service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,13 @@ impl CeramicEventService {
.await
}

pub async fn migrate_from_ipfs(&self, network: Network, blocks: impl BlockStore) -> Result<()> {
let migrator = Migrator::new(self, network, blocks)
pub async fn migrate_from_ipfs(
&self,
network: Network,
blocks: impl BlockStore,
log_tile_docs: bool,
) -> Result<()> {
let migrator = Migrator::new(self, network, blocks, log_tile_docs)
.await
.map_err(Error::new_fatal)?;
migrator.migrate().await.map_err(Error::new_fatal)?;
Expand Down
2 changes: 1 addition & 1 deletion service/src/tests/migration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ async fn test_migration(cars: Vec<Vec<u8>>) {
.await
.unwrap();
service
.migrate_from_ipfs(Network::Local(42), blocks)
.migrate_from_ipfs(Network::Local(42), blocks, false)
.await
.unwrap();
let actual_events: BTreeSet<_> = recon::Store::range_with_values(
Expand Down
Loading