Skip to content
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
6 changes: 5 additions & 1 deletion blockzilla/get-block/resolver/src/catalog.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use std::{
path::{Component, Path, PathBuf},
};

const SLOTS: u64 = 432_000;
pub(crate) const SLOTS: u64 = 432_000;
const MAX_CATALOG_BYTES: u64 = 16 * 1024 * 1024;
const MAX_EPOCHS: usize = 4096;
const BLOCKS: &str = "archive-v2-blocks.zstd";
Expand Down Expand Up @@ -307,6 +307,10 @@ impl Catalog {
&self.generation
}

pub fn has_epoch(&self, epoch: u64) -> bool {
self.epochs.contains_key(&epoch)
}

/// All lookups here use startup-checked RAM rows. No file reads or locks.
pub fn pending(&self, slot: u64) -> Result<Option<PendingLocatorV1>> {
let Some(epoch) = self.epochs.get(&(slot / SLOTS)) else {
Expand Down
39 changes: 37 additions & 2 deletions blockzilla/get-block/resolver/src/finalized.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
//! Slot-only admission for original native frames. JSON conversion stays in
//! the Worker. A verified small root control accompanies the unchanged body.
use super::*;
use axum::extract::RawQuery;
use blockzilla_get_block::foundation_protocol::ARCHIVE_LOOKUP_REQUIRED;

#[derive(Debug)]
struct ArchiveLookupRequired;

impl std::fmt::Display for ArchiveLookupRequired {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str(ARCHIVE_LOOKUP_REQUIRED)
}
}

impl std::error::Error for ArchiveLookupRequired {}

pub(super) async fn block(
State(state): State<Arc<AppState>>,
Expand Down Expand Up @@ -52,7 +63,11 @@ pub(super) async fn block(
let _permit = permit;
let clock = Clock::start()?;
let result = (|| -> Result<_> {
let found = recent.read_finalized_by_slot(slot)?;
let (found, native_unavailable) = match recent.read_finalized_by_slot(slot) {
Ok(found) => (found, false),
Err(error) if error.is::<recent::FinalizedFeedUnavailable>() => (None, true),
Err(error) => return Err(error),
};
let native_archive = if found.is_none() {
recent.native_archive(slot)?
} else {
Expand Down Expand Up @@ -84,6 +99,12 @@ pub(super) async fn block(
} else {
None
};
if native_unavailable && ledger.is_none() && matches!(archive, Some((None, None))) {
// The checked feed reported failed health, and the independently
// available local readers supplied no block. The archive is
// still a possible source. Errors above never enter this path.
return Err(ArchiveLookupRequired.into());
}
Ok((found, native_archive, archive, ledger))
})();
Ok((result, clock.finish()?))
Expand Down Expand Up @@ -197,6 +218,9 @@ pub(super) async fn block(
}
Ok((None, None, Some((source, hash)), None)) => {
state.counters.recent_misses.fetch_add(1, Ordering::Relaxed);
if source.is_none() {
state.enqueue_archive_miss(slot);
}
let raw = Bytes::from(
serde_json::to_vec(
&json!({"version":1,"slot":slot,"reason":"not_cached","source":source}),
Expand Down Expand Up @@ -241,6 +265,17 @@ pub(super) async fn block(
state.counters.recent_errors.fetch_add(1, Ordering::Relaxed);
unavailable(&state, slot, StatusCode::CONFLICT, "not_finalized", None)
}
Err(error) if error.is::<ArchiveLookupRequired>() => {
state.counters.recent_misses.fetch_add(1, Ordering::Relaxed);
state.enqueue_archive_miss(slot);
unavailable(
&state,
slot,
StatusCode::SERVICE_UNAVAILABLE,
ARCHIVE_LOOKUP_REQUIRED,
None,
)
}
Err(error) if error.to_string() == "ledger_compact_unavailable" => {
state.counters.recent_errors.fetch_add(1, Ordering::Relaxed);
unavailable(
Expand Down
48 changes: 47 additions & 1 deletion blockzilla/get-block/resolver/src/http.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use anyhow::{Result, ensure};
use axum::{
Router,
body::{Body, Bytes, to_bytes},
extract::{Path, Query, Request, State, rejection::QueryRejection},
extract::{Path, Query, RawQuery, Request, State, rejection::QueryRejection},
http::{HeaderMap, StatusCode, header},
response::{IntoResponse, Response},
routing::{get, post},
Expand All @@ -19,6 +19,9 @@ use blockzilla_get_block::{
use serde_json::json;
use sha2::{Digest, Sha256};
use std::{
fs::OpenOptions,
io::ErrorKind,
path::PathBuf,
sync::{
Arc,
atomic::{AtomicU64, Ordering},
Expand Down Expand Up @@ -58,6 +61,27 @@ struct AppState {
permits: Arc<Semaphore>,
counters: Counters,
recent: Option<Arc<RecentClient>>,
archive_miss_dir: Option<PathBuf>,
}

impl AppState {
fn enqueue_archive_miss(&self, slot: u64) {
let Some(dir) = &self.archive_miss_dir else {
return;
};
let epoch = slot / crate::catalog::SLOTS;
if slot > blockzilla_bank_stream_v2::SAFE || self.catalog.has_epoch(epoch) {
return;
}
let marker = dir.join(format!("epoch-{epoch}"));
// The marker is the entire request. The index importer owns all network
// and table work; an existing marker already requests this epoch.
if let Err(error) = OpenOptions::new().write(true).create_new(true).open(marker) {
if error.kind() != ErrorKind::AlreadyExists {
eprintln!("archive miss enqueue failed for epoch {epoch}: {error}");
}
}
}
}

pub fn router(
Expand All @@ -76,6 +100,23 @@ pub fn router_with_recent(
max_concurrent: usize,
recent: Option<Arc<RecentClient>>,
) -> Result<Router> {
router_with_archive_miss(catalog, token, cache_bytes, max_concurrent, recent, None)
}

pub fn router_with_archive_miss(
catalog: Arc<dyn ResolutionCatalog>,
token: &str,
cache_bytes: usize,
max_concurrent: usize,
recent: Option<Arc<RecentClient>>,
archive_miss_dir: Option<PathBuf>,
) -> Result<Router> {
if let Some(dir) = &archive_miss_dir {
ensure!(
dir.is_absolute() && dir.is_dir() && dir.canonicalize()? == *dir,
"archive miss directory must be an existing canonical absolute directory"
);
}
ensure!(
cache_bytes == 0,
"result caching is disabled; cache_bytes must be 0"
Expand Down Expand Up @@ -103,6 +144,7 @@ pub fn router_with_recent(
permits: Arc::new(Semaphore::new(max_concurrent)),
counters: Counters::default(),
recent,
archive_miss_dir,
});
Ok(Router::new()
.route("/healthz", get(|| async { "ready\n" }))
Expand Down Expand Up @@ -393,6 +435,7 @@ async fn block(
State(state): State<Arc<AppState>>,
Path(slot): Path<u64>,
headers: HeaderMap,
RawQuery(query): RawQuery,
) -> Response {
if !authorized(&headers, &state) {
return plain_error(StatusCode::UNAUTHORIZED, "unauthorized");
Expand All @@ -411,6 +454,9 @@ async fn block(
Ok(source) => source,
Err(_) => return unavailable(&state, slot, StatusCode::CONFLICT, "incomplete", None),
};
if source.is_none() && query.is_none() {
state.enqueue_archive_miss(slot);
}
let body = Bytes::from(
serde_json::to_vec(&json!({"version":1,"slot":slot,"reason":"not_cached","source":source}))
.expect("pending locator JSON"),
Expand Down
Loading
Loading