use crate::error::KernelError;
pub(crate) const REGISTRY_TABLE: &str = "_adk_kernel_device_migrations";
pub(crate) const PUT_CODE: &str = "\
INSERT INTO adk_kernel_pairing_codes (code_hash, expires_us, record) VALUES ($1, $2, $3) \
ON CONFLICT (code_hash) DO UPDATE SET expires_us = excluded.expires_us, record = excluded.record";
pub(crate) const TAKE_CODE: &str =
"DELETE FROM adk_kernel_pairing_codes WHERE code_hash = $1 RETURNING record";
pub(crate) const PRUNE_CODES: &str = "DELETE FROM adk_kernel_pairing_codes WHERE expires_us <= $1";
pub(crate) const CLEAR_CODES: &str = "DELETE FROM adk_kernel_pairing_codes";
pub(crate) const PUT_DEVICE: &str = "\
INSERT INTO adk_kernel_devices (id, created_us, record) VALUES ($1, $2, $3) \
ON CONFLICT (id) DO UPDATE SET created_us = excluded.created_us, record = excluded.record";
pub(crate) const GET_DEVICE: &str = "SELECT record FROM adk_kernel_devices WHERE id = $1";
pub(crate) const LIST_DEVICES: &str =
"SELECT record FROM adk_kernel_devices ORDER BY created_us, id";
pub(crate) const COUNT_ATTEMPT: &str = "\
INSERT INTO adk_kernel_pairing_attempts (id, attempts) VALUES (1, 1) \
ON CONFLICT (id) DO UPDATE SET attempts = adk_kernel_pairing_attempts.attempts + 1 \
RETURNING attempts";
pub(crate) const RESET_ATTEMPTS: &str =
"UPDATE adk_kernel_pairing_attempts SET attempts = 0 WHERE id = 1";
pub(crate) const PUT_ATTACHMENT: &str = "\
INSERT INTO adk_kernel_device_attachments (holder, kind, key, updated_us, record) \
VALUES ($1, $2, $3, $4, $5) \
ON CONFLICT (holder, kind, key) DO UPDATE SET updated_us = excluded.updated_us, record = excluded.record";
pub(crate) const PUT_ATTACHMENT_IF_ABSENT: &str = "\
INSERT INTO adk_kernel_device_attachments (holder, kind, key, updated_us, record) \
VALUES ($1, $2, $3, $4, $5) ON CONFLICT (holder, kind, key) DO NOTHING";
pub(crate) const LIST_ATTACHMENTS: &str =
"SELECT record FROM adk_kernel_device_attachments WHERE holder = $1 AND kind = $2 ORDER BY key";
pub(crate) const REMOVE_ATTACHMENT: &str =
"DELETE FROM adk_kernel_device_attachments WHERE holder = $1 AND kind = $2 AND key = $3";
pub(crate) const REMOVE_ATTACHMENTS: &str =
"DELETE FROM adk_kernel_device_attachments WHERE holder = $1";
pub(crate) fn db_error(backend: &'static str, action: &str, error: &sqlx::Error) -> KernelError {
KernelError::Store { backend, reason: format!("could not {action} the device table: {error}") }
}
pub(crate) fn decode<T: serde::de::DeserializeOwned>(
backend: &'static str,
what: &str,
text: &str,
) -> crate::error::Result<T> {
serde_json::from_str(text).map_err(|error| KernelError::Store {
backend,
reason: format!("a stored {what} is corrupt: {error}"),
})
}
macro_rules! sql_device_store {
($store:ty, $backend:literal) => {
#[async_trait::async_trait]
impl $crate::pairing::DeviceStore for $store {
async fn put_code(
&self,
code: $crate::pairing::PairingCode,
) -> $crate::error::Result<()> {
sqlx::query($crate::pairing::sql::PUT_CODE)
.bind(&code.code_hash)
.bind(code.expires_at.timestamp_micros())
.bind(serde_json::to_string(&code)?)
.execute(&self.pool)
.await
.map_err(|e| $crate::pairing::sql::db_error($backend, "write", &e))?;
Ok(())
}
async fn take_code(
&self,
code_hash: &str,
) -> $crate::error::Result<Option<$crate::pairing::PairingCode>> {
let row: Option<(String,)> = sqlx::query_as($crate::pairing::sql::TAKE_CODE)
.bind(code_hash)
.fetch_optional(&self.pool)
.await
.map_err(|e| $crate::pairing::sql::db_error($backend, "take from", &e))?;
row.map(|(text,)| $crate::pairing::sql::decode($backend, "pairing code", &text))
.transpose()
}
async fn prune_codes(
&self,
before: chrono::DateTime<chrono::Utc>,
) -> $crate::error::Result<usize> {
let done = sqlx::query($crate::pairing::sql::PRUNE_CODES)
.bind(before.timestamp_micros())
.execute(&self.pool)
.await
.map_err(|e| $crate::pairing::sql::db_error($backend, "prune", &e))?;
Ok(usize::try_from(done.rows_affected()).unwrap_or(usize::MAX))
}
async fn clear_codes(&self) -> $crate::error::Result<usize> {
let done = sqlx::query($crate::pairing::sql::CLEAR_CODES)
.execute(&self.pool)
.await
.map_err(|e| $crate::pairing::sql::db_error($backend, "clear", &e))?;
Ok(usize::try_from(done.rows_affected()).unwrap_or(usize::MAX))
}
async fn put_device(
&self,
device: $crate::pairing::DeviceRecord,
) -> $crate::error::Result<()> {
sqlx::query($crate::pairing::sql::PUT_DEVICE)
.bind(&device.id)
.bind(device.created_at.timestamp_micros())
.bind(serde_json::to_string(&device)?)
.execute(&self.pool)
.await
.map_err(|e| $crate::pairing::sql::db_error($backend, "write", &e))?;
Ok(())
}
async fn get_device(
&self,
id: &str,
) -> $crate::error::Result<Option<$crate::pairing::DeviceRecord>> {
let row: Option<(String,)> = sqlx::query_as($crate::pairing::sql::GET_DEVICE)
.bind(id)
.fetch_optional(&self.pool)
.await
.map_err(|e| $crate::pairing::sql::db_error($backend, "read", &e))?;
row.map(|(text,)| $crate::pairing::sql::decode($backend, "device", &text))
.transpose()
}
async fn list_devices(
&self,
) -> $crate::error::Result<Vec<$crate::pairing::DeviceRecord>> {
let rows: Vec<(String,)> = sqlx::query_as($crate::pairing::sql::LIST_DEVICES)
.fetch_all(&self.pool)
.await
.map_err(|e| $crate::pairing::sql::db_error($backend, "list", &e))?;
rows.iter()
.map(|(text,)| $crate::pairing::sql::decode($backend, "device", text))
.collect()
}
async fn count_claim_attempt(&self) -> $crate::error::Result<u64> {
let (attempts,): (i64,) = sqlx::query_as($crate::pairing::sql::COUNT_ATTEMPT)
.fetch_one(&self.pool)
.await
.map_err(|e| $crate::pairing::sql::db_error($backend, "count in", &e))?;
Ok(u64::try_from(attempts).unwrap_or_default())
}
async fn reset_claim_attempts(&self) -> $crate::error::Result<()> {
sqlx::query($crate::pairing::sql::RESET_ATTEMPTS)
.execute(&self.pool)
.await
.map_err(|e| $crate::pairing::sql::db_error($backend, "reset", &e))?;
Ok(())
}
async fn put_attachment(
&self,
attachment: $crate::pairing::DeviceAttachment,
) -> $crate::error::Result<()> {
sqlx::query($crate::pairing::sql::PUT_ATTACHMENT)
.bind(attachment.holder.key())
.bind(&attachment.kind)
.bind(&attachment.key)
.bind(attachment.updated_at.timestamp_micros())
.bind(serde_json::to_string(&attachment)?)
.execute(&self.pool)
.await
.map_err(|e| {
$crate::pairing::sql::db_error($backend, "write an attachment to", &e)
})?;
Ok(())
}
async fn put_attachment_if_absent(
&self,
attachment: $crate::pairing::DeviceAttachment,
) -> $crate::error::Result<bool> {
let done = sqlx::query($crate::pairing::sql::PUT_ATTACHMENT_IF_ABSENT)
.bind(attachment.holder.key())
.bind(&attachment.kind)
.bind(&attachment.key)
.bind(attachment.updated_at.timestamp_micros())
.bind(serde_json::to_string(&attachment)?)
.execute(&self.pool)
.await
.map_err(|e| {
$crate::pairing::sql::db_error($backend, "write an attachment to", &e)
})?;
Ok(done.rows_affected() == 1)
}
async fn attachments(
&self,
holder: &$crate::pairing::AttachmentHolder,
kind: &str,
) -> $crate::error::Result<Vec<$crate::pairing::DeviceAttachment>> {
let rows: Vec<(String,)> = sqlx::query_as($crate::pairing::sql::LIST_ATTACHMENTS)
.bind(holder.key())
.bind(kind)
.fetch_all(&self.pool)
.await
.map_err(|e| {
$crate::pairing::sql::db_error($backend, "list the attachments of", &e)
})?;
rows.iter()
.map(|(text,)| $crate::pairing::sql::decode($backend, "attachment", text))
.collect()
}
async fn remove_attachment(
&self,
holder: &$crate::pairing::AttachmentHolder,
kind: &str,
key: &str,
) -> $crate::error::Result<bool> {
let done = sqlx::query($crate::pairing::sql::REMOVE_ATTACHMENT)
.bind(holder.key())
.bind(kind)
.bind(key)
.execute(&self.pool)
.await
.map_err(|e| {
$crate::pairing::sql::db_error($backend, "remove an attachment from", &e)
})?;
Ok(done.rows_affected() > 0)
}
async fn remove_attachments(
&self,
holder: &$crate::pairing::AttachmentHolder,
) -> $crate::error::Result<usize> {
let done = sqlx::query($crate::pairing::sql::REMOVE_ATTACHMENTS)
.bind(holder.key())
.execute(&self.pool)
.await
.map_err(|e| {
$crate::pairing::sql::db_error($backend, "remove attachments from", &e)
})?;
Ok(usize::try_from(done.rows_affected()).unwrap_or(usize::MAX))
}
}
};
}
pub(crate) use sql_device_store;