use std::sync::{Arc, Mutex};
use crate::{Backend, ChangePage, FieldValue, RawRecord, RecordOutcome, SavePolicy, SyncResult};
pub(super) const MAX_PASS_RECORDS: usize = 20_000;
pub(super) const MAX_PASS_BYTES: usize = 48 * 1024 * 1024;
pub(super) const MAX_PASS_PAGES: usize = 256;
#[derive(Default)]
struct WindowState {
records: usize,
bytes: usize,
expect: Option<Option<Vec<u8>>>,
truncated: bool,
pages: usize,
stalled: bool,
}
pub(super) struct WindowTotals {
pub(super) truncated: bool,
pub(super) stalled: bool,
pub(super) end_token: Option<Vec<u8>>,
}
pub(super) struct RemoteWindow {
state: Mutex<WindowState>,
}
impl RemoteWindow {
pub(super) fn new() -> Self {
Self {
state: Mutex::new(WindowState::default()),
}
}
pub(super) fn begin_pass(&self) {
if let Ok(mut state) = self.state.lock() {
*state = WindowState::default();
}
}
pub(super) fn finish_pass(&self) -> WindowTotals {
self.state.lock().map_or(
WindowTotals {
truncated: false,
stalled: true,
end_token: None,
},
|state| WindowTotals {
truncated: state.truncated,
stalled: state.stalled,
end_token: state.expect.clone().flatten(),
},
)
}
fn account(&self, since: Option<&[u8]>, page: &mut ChangePage) {
let Ok(mut state) = self.state.lock() else {
return;
};
let continuing = matches!(&state.expect, Some(previous) if previous.as_deref() == since);
if !continuing {
state.records = 0;
state.bytes = 0;
state.truncated = false;
state.pages = 0;
state.stalled = false;
}
state.pages = state.pages.saturating_add(1);
let content_bytes = page
.records
.iter()
.map(record_bytes)
.fold(0usize, usize::saturating_add);
let name_bytes = page
.deleted_record_names
.iter()
.map(String::len)
.fold(0usize, usize::saturating_add);
state.records = state
.records
.saturating_add(page.records.len())
.saturating_add(page.deleted_record_names.len());
state.bytes = state
.bytes
.saturating_add(content_bytes)
.saturating_add(name_bytes);
state.expect = Some(page.new_token.clone().or_else(|| since.map(<[u8]>::to_vec)));
if page.more_coming {
let progressing = match (page.new_token.as_deref(), since) {
(None, _) => false,
(Some(new), Some(previous)) => new != previous,
(Some(_), None) => true,
};
if !progressing {
page.more_coming = false;
state.stalled = true;
state.truncated = false;
return;
}
let full = state.records >= MAX_PASS_RECORDS
|| state.bytes >= MAX_PASS_BYTES
|| state.pages >= MAX_PASS_PAGES;
if full {
page.more_coming = false;
state.truncated = true;
}
}
}
}
fn record_bytes(record: &RawRecord) -> usize {
let fields = record.fields.iter().fold(0usize, |total, (key, value)| {
let value_bytes = match value {
FieldValue::Text(text) => text.len(),
FieldValue::Bytes(bytes) => bytes.len(),
FieldValue::Strings(list) => {
list.iter().map(String::len).fold(0, usize::saturating_add)
}
FieldValue::I64(_) | FieldValue::F64(_) | FieldValue::Date(_) => 8,
};
total.saturating_add(key.len()).saturating_add(value_bytes)
});
fields
.saturating_add(record.record_name.len())
.saturating_add(record.record_type.len())
.saturating_add(64)
}
pub(super) struct WindowedBackend {
inner: Arc<dyn Backend>,
window: Arc<RemoteWindow>,
}
impl WindowedBackend {
pub(super) fn new(inner: Arc<dyn Backend>, window: Arc<RemoteWindow>) -> Self {
Self { inner, window }
}
}
impl Backend for WindowedBackend {
fn prepare(&self) -> SyncResult<()> {
self.inner.prepare()
}
fn fetch_changes(&self, since: Option<&[u8]>) -> SyncResult<ChangePage> {
let mut page = self.inner.fetch_changes(since)?;
self.window.account(since, &mut page);
Ok(page)
}
fn fetch_record(&self, record_name: &str) -> SyncResult<Option<RawRecord>> {
self.inner.fetch_record(record_name)
}
fn save_records(
&self,
records: &[RawRecord],
policy: SavePolicy,
) -> SyncResult<Vec<RecordOutcome>> {
self.inner.save_records(records, policy)
}
fn max_batch(&self) -> usize {
self.inner.max_batch()
}
}