use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use super::codec::{Message, Row};
use super::protocol::{
Empty, Failure, Handle, KvAllowance, KvAnswer, KvBranch, KvBucketOpen, KvCall, KvCheck, KvCount, KvCountersOpen,
KvEntry, KvFound, KvList, KvOnceOpen, KvOutcome, KvPage, KvQuotaOpen, KvRateLimitOpen, KvResealed, KvTx,
KvTxResults, KvWindowUse, KvWritten, method,
};
use super::{Lent, Route};
#[cfg(feature = "sql")]
use crate::Transaction;
use crate::clock::from_unix_millis;
use crate::engine::Home;
use crate::kv::{
Allowance, Batch, Bucket, BucketBuilder, Cell, Counters, Hand, Handed, Kind, MAX_KEY, Outcome, PAGE_KEYS, Place,
Put, Quota, RateLimit, Raw, Scope, Stamp, Version, Waiter, WriteOptions, hand, once_rows,
};
#[cfg(feature = "sql")]
use crate::kv::{call_on_branch, call_on_key, clear_work};
use crate::limits::{ANSWER_BYTES, Limit};
use crate::{Error, Store, unix_millis};
#[derive(Debug, Default)]
pub(crate) struct Handles {
open: Mutex<HashMap<u64, Opened>>,
last: AtomicU64,
}
#[derive(Clone, Debug)]
enum Opened {
Bucket(Bucket<()>),
Counters(Counters),
RateLimit(RateLimit),
Quota(Quota),
Once(Bucket<()>),
}
use super::Answered;
pub(crate) fn route(called: u16) -> Route {
match called {
method::KV_GET | method::KV_HAS | method::KV_ONCE_GET => Route::Inline,
method::KV_SET | method::KV_CREATE | method::KV_TAKE | method::KV_DELETE | method::KV_EXPIRE => Route::Submit,
method::KV_CLEAR | method::KV_TX | method::KV_ONCE_DELETE => Route::Submit,
method::KV_COUNTERS_ADD | method::KV_COUNTERS_DELETE => Route::Submit,
method::KV_ALLOW | method::KV_REFUND | method::KV_RESET => Route::Submit,
method::KV_ONCE_RUN => Route::Handover,
_ => Route::Worker,
}
}
pub(crate) fn call(
store: &Store,
handles: &Handles,
lent: Lent<'_>,
called: u16,
body: &[u8],
(max_body, read_only): (usize, bool),
) -> Answered {
match called {
method::KV_BUCKET_OPEN => handles.open(open_bucket(store, lent, KvBucketOpen::decode(body)?, read_only)?),
method::KV_COUNTERS_OPEN => handles.open(open_counters(store, KvCountersOpen::decode(body)?, read_only)?),
method::KV_RATE_LIMIT_OPEN => handles.open(open_rate_limit(store, KvRateLimitOpen::decode(body)?, read_only)?),
method::KV_QUOTA_OPEN => handles.open(open_quota(store, KvQuotaOpen::decode(body)?, read_only)?),
method::KV_ONCE_OPEN => {
let open = KvOnceOpen::decode(body)?;
held(&Home::Store(store.clone()), &open.name, Kind::Once, read_only)?;
handles.open(Opened::Once(once_rows(store, &open.name, open.keep.map(Duration::from_millis))?))
}
method::KV_GET => get(handles, KvCall::decode(body)?),
method::KV_HAS => has(handles, KvCall::decode(body)?),
method::KV_LIST => list(handles, KvList::decode(body)?, max_body),
method::KV_COUNTERS_GET => {
let call = KvCall::decode(body)?;
Ok(KvCount { value: handles.counters(call.handle, &call.under)?.get(&*call.key)? }.encode())
}
method::KV_COUNTERS_CLEAR => {
let branch = KvBranch::decode(body)?;
handles.counters(branch.handle, &branch.under)?.clear()?;
Ok(Empty {}.encode())
}
method::KV_RESEAL => {
let branch = KvBranch::decode(body)?;
Ok(KvResealed { count: handles.bucket(branch.handle, &branch.under)?.reseal()? }.encode())
}
method::KV_PEEK => limit(handles, called, KvCall::decode(body)?),
method::KV_ONCE_GET => {
let call = KvCall::decode(body)?;
let cell = handles.once(call.handle, &call.under)?.read_cell(&call.key)?;
Ok(answer(cell.map(|cell| cell.raw)).encode())
}
other => Err(Failure::unimplemented(format!("method {other:#06x}"))),
}
}
#[cfg(feature = "sql")]
pub(crate) fn call_in(handles: &Handles, tx: &Transaction<'_>, called: u16, body: &[u8], max_body: usize) -> Answered {
match called {
method::KV_CLEAR => {
let branch = KvBranch::decode(body)?;
let bucket = handles.bucket(branch.handle, &branch.under)?;
call_on_branch(tx, &bucket.scope, clear_work(&bucket.scope)?)?;
Ok(Empty {}.encode())
}
method::KV_LIST => {
let list = KvList::decode(body)?;
let bucket = handles.bucket(list.handle, &list.under)?;
let (limit, after) = (page_limit(&list), list.after.as_deref());
let read = |sql: &crate::sqlite::Tx<'_>, _: &_| bucket.page_rows(sql, limit.clamp(1, PAGE_KEYS), after);
let rows = call_on_branch(tx, &bucket.scope, read)?;
page(bucket.keyed(rows)?, &list, limit, max_body)
}
_ => key_call_in(handles, tx, called, &KvCall::decode(body)?),
}
}
#[cfg(feature = "sql")]
fn key_call_in(handles: &Handles, tx: &Transaction<'_>, called: u16, call: &KvCall) -> Answered {
let bucket = handles.bucket(call.handle, &call.under)?;
refuse_expiry(called, &bucket, call)?;
let (key, scope) = (call.key.as_str(), &bucket.scope);
match called {
method::KV_GET | method::KV_HAS => {
let cell = call_on_key(tx, scope, key, |sql, _| bucket.read_cell_in(sql, key))?;
match called {
method::KV_GET => Ok(entry(cell, None).encode()),
_ => Ok(KvFound { found: cell.is_some() }.encode()),
}
}
method::KV_SET | method::KV_CREATE => {
let put = if called == method::KV_SET { Put::Always } else { Put::OnlyNew };
let raw = raw_of(call.value.clone().unwrap_or_default());
let (_, work) = bucket.put_work(key, raw, options(call)?, put)?;
Ok(written(call_on_key(tx, scope, key, work)?))
}
method::KV_TAKE => Ok(taken(call_on_key(tx, scope, key, bucket.take_cell_work(key, options(call)?)?)?)),
method::KV_DELETE => {
let found = call_on_key(tx, scope, key, bucket.remove_work(key, options(call)?)?)?;
Ok(KvFound { found }.encode())
}
method::KV_EXPIRE => {
let found = call_on_key(tx, scope, key, bucket.expire_work(key, options(call)?)?)?;
Ok(KvFound { found }.encode())
}
other => Err(Failure::invalid(format!("method {other:#06x} is not a bucket's call inside a transaction"))),
}
}
pub(crate) fn submit(handles: &Handles, called: u16, body: &[u8], done: impl FnOnce(Answered) + Send + 'static) {
match called {
method::KV_CLEAR => clear(handles, body, done),
method::KV_TX => tx(handles, body, done),
method::KV_ONCE_DELETE => forget(handles, body, done),
method::KV_COUNTERS_ADD | method::KV_COUNTERS_DELETE => counting(handles, called, body, done),
method::KV_ALLOW | method::KV_REFUND | method::KV_RESET => using(handles, called, body, done),
_ => write(handles, called, body, done),
}
}
fn write(handles: &Handles, called: u16, body: &[u8], done: impl FnOnce(Answered) + Send + 'static) {
let prepared = || -> Result<_, Failure> {
let call = KvCall::decode(body)?;
let bucket = handles.bucket(call.handle, &call.under)?;
refuse_expiry(called, &bucket, &call)?;
let options = options(&call)?;
Ok((call, bucket, options))
};
let (call, bucket, options) = match prepared() {
Ok(prepared) => prepared,
Err(failure) => return done(Err(failure)),
};
let key = call.key.clone();
match called {
method::KV_SET | method::KV_CREATE => {
let put = if called == method::KV_SET { Put::Always } else { Put::OnlyNew };
let raw = raw_of(call.value.unwrap_or_default());
bucket
.put_raw_then(&key, (raw, options, put), move |stamp| done(stamp.map(written).map_err(Failure::from)));
}
method::KV_TAKE => {
bucket.take_cell_then(&key, options, move |cell| done(cell.map(taken).map_err(Failure::from)));
}
method::KV_DELETE => bucket.remove_then(&key, options, move |found| {
done(found.map(|found| KvFound { found }.encode()).map_err(Failure::from));
}),
method::KV_EXPIRE => bucket.expire_then(&key, options, move |found| {
done(found.map(|found| KvFound { found }.encode()).map_err(Failure::from));
}),
other => done(Err(Failure::unimplemented(format!("method {other:#06x}")))),
}
}
fn refuse_expiry(called: u16, bucket: &Bucket<()>, call: &KvCall) -> Result<(), Failure> {
let verb = match called {
method::KV_TAKE => "take",
method::KV_DELETE => "delete",
_ => return Ok(()),
};
let asked = match (call.ttl, call.expires_at) {
(None, None) => return Ok(()),
(Some(ttl), _) => bucket.key(&call.key).ttl(Duration::from_millis(ttl)),
(None, Some(at)) => bucket.key(&call.key).expires_at(from_unix_millis(at)),
};
Ok(asked.refuse_expiry(verb)?)
}
pub(crate) enum Run {
Answered(Vec<u8>),
Handed(Box<Handed>, Vec<u8>),
Waiting,
}
pub(crate) fn run(handles: &Handles, body: &[u8], again: Waiter) -> Result<Run, Failure> {
let call = KvCall::decode(body)?;
let answers = handles.once(call.handle, &call.under)?;
Ok(match hand(&answers, &call.key, again)? {
Hand::Kept(raw) => Run::Answered(answer(Some(raw)).encode()),
Hand::Yours(handed) => Run::Handed(Box::new(handed), answer(None).encode()),
Hand::Wait => Run::Waiting,
})
}
pub(crate) fn kept(handed: Handed, body: &[u8]) -> Answered {
let answered = KvAnswer::decode(body)?;
let raw = answered.found.then(|| raw_of(answered.value.unwrap_or_default()));
handed.keep(raw);
Ok(Empty {}.encode())
}
pub(crate) fn unkept(raw: &Raw) -> Run {
Run::Answered(answer(Some(raw.clone())).encode())
}
impl Handles {
fn open(&self, opened: Opened) -> Answered {
let handle = self.last.fetch_add(1, Ordering::SeqCst) + 1;
self.lock().insert(handle, opened);
Ok(Handle { handle }.encode())
}
fn opened(&self, handle: u64) -> Result<Opened, Failure> {
self.lock()
.get(&handle)
.cloned()
.ok_or_else(|| Failure::invalid(format!("handle {handle} names nothing this connection opened")))
}
fn bucket(&self, handle: u64, under: &[String]) -> Result<Bucket<()>, Failure> {
match self.opened(handle)? {
Opened::Bucket(bucket) => Ok(under.iter().fold(bucket, |bucket, owner| bucket.under(owner))),
other => Err(wrong(handle, &other, "a bucket")),
}
}
fn counters(&self, handle: u64, under: &[String]) -> Result<Counters, Failure> {
match self.opened(handle)? {
Opened::Counters(counters) => Ok(under.iter().fold(counters, |counters, owner| counters.under(owner))),
other => Err(wrong(handle, &other, "counters")),
}
}
fn once(&self, handle: u64, under: &[String]) -> Result<Bucket<()>, Failure> {
match self.opened(handle)? {
Opened::Once(answers) => Ok(under.iter().fold(answers, |answers, owner| answers.under(owner))),
other => Err(wrong(handle, &other, "once's answers")),
}
}
fn lock(&self) -> MutexGuard<'_, HashMap<u64, Opened>> {
self.open.lock().unwrap_or_else(PoisonError::into_inner)
}
}
fn held(home: &Home, name: &str, kind: Kind, read_only: bool) -> Result<(), Failure> {
if read_only {
Scope::open_as_it_is(home, name, kind)?;
}
Ok(())
}
fn open_bucket(store: &Store, lent: Lent<'_>, open: KvBucketOpen, read_only: bool) -> Result<Opened, Failure> {
if open.encrypted && read_only {
return Err(Failure::permission("a read connection opens no encrypted bucket"));
}
if open.idle.is_some() && read_only {
return Err(Failure::permission(
"a read connection gives a bucket no idle: a read that renews a key writes it",
));
}
let home = match open.database {
Some(database) => Home::Shared(lent(database)?),
None => Home::Store(store.clone()),
};
held(&home, &open.name, Kind::Values, read_only)?;
let mut builder = match home {
Home::Shared(shared) => BucketBuilder::in_file(shared, &open.name),
Home::Store(_) => store.bucket::<()>(&open.name),
};
if let Some(ttl) = open.ttl {
builder = builder.ttl(Duration::from_millis(ttl));
}
if let Some(idle) = open.idle {
builder = builder.idle(Duration::from_millis(idle));
}
if open.encrypted {
builder = builder.encrypted();
}
Ok(Opened::Bucket(builder.open()?))
}
fn open_counters(store: &Store, open: KvCountersOpen, read_only: bool) -> Result<Opened, Failure> {
if open.flush_every.is_some() && read_only {
return Err(Failure::permission(
"a read connection gives counters no flush_every: how they count is the writers'",
));
}
if read_only {
return Ok(Opened::Counters(Counters::open_as_it_is(store, &open.name)?));
}
let mut builder = store.counters(&open.name);
if let Some(ttl) = open.ttl {
builder = builder.ttl(Duration::from_millis(ttl));
}
if let Some(span) = open.flush_every {
builder = builder.flush_every(Duration::from_millis(span));
}
Ok(Opened::Counters(builder.open()?))
}
fn open_rate_limit(store: &Store, open: KvRateLimitOpen, read_only: bool) -> Result<Opened, Failure> {
held(&Home::Store(store.clone()), &open.name, Kind::RateLimit, read_only)?;
let mut builder = store.rate_limit(&open.name).rate(open.rate, Duration::from_millis(open.per));
if let Some(burst) = open.burst {
builder = builder.burst(burst);
}
Ok(Opened::RateLimit(builder.open()?))
}
fn open_quota(store: &Store, open: KvQuotaOpen, read_only: bool) -> Result<Opened, Failure> {
held(&Home::Store(store.clone()), &open.name, Kind::Quota, read_only)?;
let builder = open.windows.iter().fold(store.quota(&open.name), |quota, window| {
quota.window(&window.name, window.limit, Duration::from_millis(window.per))
});
Ok(Opened::Quota(builder.open()?))
}
fn get(handles: &Handles, call: KvCall) -> Answered {
let cell = handles.bucket(call.handle, &call.under)?.read_cell(&call.key)?;
Ok(entry(cell, None).encode())
}
fn has(handles: &Handles, call: KvCall) -> Answered {
let found = handles.bucket(call.handle, &call.under)?.has(&*call.key)?;
Ok(KvFound { found }.encode())
}
fn clear(handles: &Handles, body: &[u8], done: impl FnOnce(Answered) + Send + 'static) {
let bucket = KvBranch::decode(body).and_then(|branch| handles.bucket(branch.handle, &branch.under));
match bucket {
Ok(bucket) => {
bucket.clear_then(move |cleared| done(cleared.map(|()| Empty {}.encode()).map_err(Failure::from)))
}
Err(failure) => done(Err(failure)),
}
}
fn forget(handles: &Handles, body: &[u8], done: impl FnOnce(Answered) + Send + 'static) {
let answers = KvCall::decode(body).and_then(|call| Ok((handles.once(call.handle, &call.under)?, call.key)));
match answers {
Ok((answers, key)) => answers.remove_then(&key, WriteOptions::default(), move |removed| {
done(removed.map(|found| KvFound { found }.encode()).map_err(Failure::from));
}),
Err(failure) => done(Err(failure)),
}
}
fn list(handles: &Handles, list: KvList, max_body: usize) -> Answered {
let bucket = handles.bucket(list.handle, &list.under)?;
let limit = page_limit(&list);
let rows = bucket.list_rows(limit, list.after.as_deref())?;
page(rows, &list, limit, max_body)
}
fn page_limit(list: &KvList) -> usize {
list.limit.map_or(100, |limit| usize::try_from(limit).unwrap_or(usize::MAX))
}
fn page(rows: Vec<(String, Cell)>, list: &KvList, limit: usize, max_body: usize) -> Answered {
let full = rows.len() == limit.clamp(1, PAGE_KEYS);
let mut page = KvPage::default();
let mut room = max_body.saturating_sub(64 + list.after.as_ref().map_or(0, String::len) + MAX_KEY);
for (key, cell) in rows {
let entry = entry(Some(cell), Some(key));
let bytes = entry.encode().len() + 1;
if bytes > room {
if page.entries.is_empty() {
let agreed = Limit { bound: max_body as u64, ..ANSWER_BYTES };
let refused = "an entry past the largest body this connection agreed";
return Err(Failure::from(agreed.refuse(bytes as u64, refused)));
}
page.next = page.entries.last().and_then(|entry| entry.key.clone());
return Ok(page.encode());
}
room -= bytes;
page.entries.push(entry);
}
if full {
page.next = page.entries.last().and_then(|entry| entry.key.clone());
}
Ok(page.encode())
}
fn counting(handles: &Handles, called: u16, body: &[u8], done: impl FnOnce(Answered) + Send + 'static) {
let counters = KvCall::decode(body).and_then(|call| Ok((handles.counters(call.handle, &call.under)?, call)));
let (counters, call) = match counters {
Ok(counters) => counters,
Err(failure) => return done(Err(failure)),
};
if called == method::KV_COUNTERS_ADD {
counters.add_then(&call.key, call.n.unwrap_or(1), move |sum| {
done(sum.map(|value| KvCount { value }.encode()).map_err(Failure::from));
});
} else {
counters.delete_then(&call.key, move |found| {
done(found.map(|found| KvFound { found }.encode()).map_err(Failure::from));
});
}
}
fn using(handles: &Handles, called: u16, body: &[u8], done: impl FnOnce(Answered) + Send + 'static) {
let opened = KvCall::decode(body).and_then(|call| Ok((handles.opened(call.handle)?, call)));
let (quota, call) = match opened {
Ok((Opened::Quota(quota), call)) => (quota, call),
Ok((_, call)) => return done(limit(handles, called, call)),
Err(failure) => return done(Err(failure)),
};
let Ok(n) = u64::try_from(call.n.unwrap_or(1)) else {
return done(Err(Failure::invalid("a negative count of requests")));
};
let quota = call.under.iter().fold(quota, |quota, owner| quota.under(owner));
let nothing = |written: Result<(), Error>| written.map(|()| Empty {}.encode()).map_err(Failure::from);
match called {
method::KV_ALLOW => quota.allow_n_then(&call.key, n, move |allowance| {
done(allowance.map(|allowance| allowance_of(&allowance).encode()).map_err(Failure::from));
}),
method::KV_RESET => quota.reset_then(&call.key, move |reset| done(nothing(reset))),
_ => quota.refund_n_then(&call.key, n, move |refunded| done(nothing(refunded))),
}
}
fn limit(handles: &Handles, called: u16, call: KvCall) -> Answered {
let n = u64::try_from(call.n.unwrap_or(1)).map_err(|_| Failure::invalid("a negative count of requests"))?;
let key = &*call.key;
let answered = match handles.opened(call.handle)? {
Opened::RateLimit(limit) => {
let limit = call.under.iter().fold(limit, |limit, owner| limit.under(owner));
match called {
method::KV_ALLOW => Some(limit.allow_n(key, n)?),
method::KV_PEEK => Some(limit.peek(key)?),
method::KV_RESET => limit.reset(key).map(|()| None)?,
_ => return Err(Failure::invalid("a rate limit gives no refund: its requests are spent")),
}
}
Opened::Quota(quota) => {
let quota = call.under.iter().fold(quota, |quota, owner| quota.under(owner));
match called {
method::KV_ALLOW => Some(quota.allow_n(key, n)?),
method::KV_PEEK => Some(quota.peek(key)?),
method::KV_RESET => quota.reset(key).map(|()| None)?,
_ => quota.refund_n(key, n).map(|()| None)?,
}
}
other => return Err(wrong(call.handle, &other, "a rate limit or a quota")),
};
Ok(answered.map_or_else(|| Empty {}.encode(), |allowance| allowance_of(&allowance).encode()))
}
fn tx(handles: &Handles, body: &[u8], done: impl FnOnce(Answered) + Send + 'static) {
let batched = || -> Result<Batch, Failure> {
let tx = KvTx::decode(body)?;
let mut batch = Batch::default();
for (index, check) in tx.checks.iter().enumerate() {
add_check(handles, &mut batch, check).map_err(|failure| failure.at(Place::Check(index)))?;
}
for (index, op) in tx.writes.iter().enumerate() {
add_write(handles, &mut batch, op.method, &op.call).map_err(|failure| failure.at(Place::Write(index)))?;
}
Ok(batch)
};
match batched() {
Ok(batch) => batch.commit_then(move |committed| {
done(match committed {
Ok(outcomes) => Ok(KvTxResults { outcomes: outcomes.into_iter().map(outcome_of).collect() }.encode()),
Err((Some(place), error)) => Err(Failure::from(error).at(place)),
Err((None, error)) => Err(Failure::from(error)),
});
}),
Err(failure) => done(Err(failure)),
}
}
fn add_check(handles: &Handles, batch: &mut Batch, check: &KvCheck) -> Result<(), Failure> {
let bucket = handles.bucket(check.handle, &check.under)?;
let version = check.version.as_deref().map(revision_of).transpose()?;
Ok(batch.check(&bucket, &check.key, version)?)
}
fn add_write(handles: &Handles, batch: &mut Batch, called: u64, call: &KvCall) -> Result<(), Failure> {
let called = u16::try_from(called).map_err(|_| Failure::invalid(format!("method {called:#06x}")))?;
if called == method::KV_COUNTERS_ADD {
let counters = handles.counters(call.handle, &call.under)?;
return Ok(batch.add(&counters, &call.key, call.n.unwrap_or(1))?);
}
let bucket = handles.bucket(call.handle, &call.under)?;
refuse_expiry(called, &bucket, call)?;
let options = options(call)?;
match called {
method::KV_SET | method::KV_CREATE => {
let put = if called == method::KV_SET { Put::Always } else { Put::OnlyNew };
let raw = raw_of(call.value.clone().unwrap_or_default());
Ok(batch.put(&bucket, &call.key, (raw, options, put))?)
}
method::KV_TAKE => Ok(batch.take(&bucket, &call.key, options)?),
method::KV_DELETE => Ok(batch.remove(&bucket, &call.key, options)?),
method::KV_EXPIRE => Ok(batch.expire(&bucket, &call.key, options)?),
method::KV_CLEAR => Ok(batch.clear(&bucket.scope)?),
other => Err(Failure::invalid(format!("method {other:#06x} in a transaction, which writes"))),
}
}
fn options(call: &KvCall) -> Result<WriteOptions, Failure> {
let mut options = WriteOptions::default();
if let Some(ttl) = call.ttl {
options = options.ttl(Duration::from_millis(ttl));
}
if let Some(at) = call.expires_at {
options = options.expires_at(from_unix_millis(at));
}
if let Some(version) = &call.if_version {
options = options.if_version(Version::new(revision_of(version)?));
}
Ok(options)
}
fn revision_of(bytes: &[u8]) -> Result<i64, Failure> {
std::str::from_utf8(bytes)
.ok()
.and_then(|text| text.parse().ok())
.ok_or_else(|| Failure::invalid("a version this server never gave"))
}
fn version_bytes(revision: i64) -> Vec<u8> {
revision.to_string().into_bytes()
}
fn entry(cell: Option<Cell>, key: Option<String>) -> KvEntry {
let Some(cell) = cell else {
return KvEntry::default();
};
KvEntry {
found: true,
value: Some(row_of(cell.raw)),
version: Some(version_bytes(cell.version)),
expires_at: cell.expires,
key,
}
}
fn answer(raw: Option<Raw>) -> KvAnswer {
KvAnswer { found: raw.is_some(), value: raw.map(row_of) }
}
fn written(stamp: Stamp) -> Vec<u8> {
let written = KvWritten {
written: stamp.written,
version: version_bytes(stamp.version.revision()),
expires_at: stamp.expires,
};
written.encode()
}
fn taken(cell: Option<Cell>) -> Vec<u8> {
KvEntry { found: cell.is_some(), value: cell.map(|cell| row_of(cell.raw)), ..KvEntry::default() }.encode()
}
fn outcome_of(outcome: Outcome) -> KvOutcome {
KvOutcome {
found: outcome.found,
written: outcome.written,
value: outcome.value.map(row_of),
version: outcome.version.map(version_bytes),
expires_at: outcome.expires,
count: outcome.count,
}
}
fn allowance_of(allowance: &Allowance) -> KvAllowance {
let windows = allowance
.windows
.iter()
.map(|window| KvWindowUse {
name: window.name.clone(),
used: window.used,
limit: window.limit,
left: window.left,
resets_at: window.resets_at.map(unix_millis),
})
.collect();
KvAllowance { ok: allowance.ok, left: allowance.left, retry_at: allowance.retry_at.map(unix_millis), windows }
}
fn row_of(raw: Raw) -> Row {
match raw {
Raw::None => Row::Nil,
Raw::Int(number) => Row::Int(number),
Raw::Bytes(bytes) => Row::Bin(bytes),
}
}
fn raw_of(row: Row) -> Raw {
match row {
Row::Nil => Raw::None,
Row::Int(number) => Raw::Int(number),
Row::Bin(bytes) => Raw::Bytes(bytes),
}
}
impl Failure {
fn at(self, place: Place) -> Failure {
match place {
Place::Check(index) => self.naming("check", index.to_string()),
Place::Write(index) => self.naming("write", index.to_string()),
}
}
}
fn wrong(handle: u64, opened: &Opened, wanted: &str) -> Failure {
let opened = match opened {
Opened::Bucket(_) => "a bucket",
Opened::Counters(_) => "counters",
Opened::RateLimit(_) => "a rate limit",
Opened::Quota(_) => "a quota",
Opened::Once(_) => "once's answers",
};
Failure::invalid(format!("handle {handle} is {opened}, not {wanted}"))
}