Skip to main content

tuwunel_database/map/
contains.rs

1use std::{fmt::Debug, io::Write, sync::Arc};
2
3use futures::FutureExt;
4use serde::Serialize;
5use tuwunel_core::{
6	Result,
7	arrayvec::ArrayVec,
8	err, implement,
9	utils::{
10		future::TryExtExt,
11		result::{FlatOk, NotFound},
12	},
13};
14
15use crate::{
16	keyval::{KeyBuf, serialize_key},
17	ser,
18};
19
20/// Checks whether a serialized key exists.
21///
22/// The key is encoded into an owned buffer before asynchronous raw-key lookup.
23/// Missing keys and database errors are folded into `false`.
24///
25/// # Panics
26///
27/// Panics if the key cannot be serialized.
28#[inline]
29#[implement(super::Map)]
30pub fn contains<K>(
31	self: &Arc<Self>,
32	key: &K,
33) -> impl Future<Output = bool> + Send + '_ + use<'_, K>
34where
35	K: Serialize + ?Sized + Debug,
36{
37	let mut buf = KeyBuf::new();
38	self.bcontains(key, &mut buf)
39}
40
41/// Checks whether a serialized key exists, returning a failed read as an error.
42///
43/// Unlike [`contains`](Self::contains), only a missing record reads as absent.
44///
45/// # Panics
46///
47/// Panics if the key cannot be serialized.
48#[inline]
49#[implement(super::Map)]
50pub fn try_contains<K>(
51	self: &Arc<Self>,
52	key: &K,
53) -> impl Future<Output = Result<bool>> + Send + '_ + use<'_, K>
54where
55	K: Serialize + ?Sized + Debug,
56{
57	let key = serialize_key(key).expect("failed to serialize query key");
58
59	self.exists(&key)
60		.map(|result| result.present().map(|found| found.is_some()))
61}
62
63/// Checks whether a serialized key exists using fixed-capacity storage.
64///
65/// `MAX` bounds the complete encoded key without a heap fallback. Missing keys
66/// and database errors are folded into `false`.
67///
68/// # Panics
69///
70/// Panics if the encoded key exceeds `MAX` or serialization otherwise fails.
71#[inline]
72#[implement(super::Map)]
73pub fn acontains<const MAX: usize, K>(
74	self: &Arc<Self>,
75	key: &K,
76) -> impl Future<Output = bool> + Send + '_ + use<'_, MAX, K>
77where
78	K: Serialize + ?Sized + Debug,
79{
80	let mut buf = ArrayVec::<u8, MAX>::new();
81	self.bcontains(key, &mut buf)
82}
83
84/// Checks whether a serialized key exists using a caller-supplied buffer.
85///
86/// Serialization appends to the supplied buffer, and lookup uses its full
87/// resulting contents. Missing keys and database errors are folded into
88/// `false`.
89///
90/// # Panics
91///
92/// Panics if the key cannot be serialized.
93#[implement(super::Map)]
94#[tracing::instrument(skip(self, buf), fields(%self), level = "trace")]
95pub fn bcontains<K, B>(
96	self: &Arc<Self>,
97	key: &K,
98	buf: &mut B,
99) -> impl Future<Output = bool> + Send + '_ + use<'_, K, B>
100where
101	K: Serialize + ?Sized + Debug,
102	B: Write + AsRef<[u8]>,
103{
104	let key = ser::serialize(buf, key).expect("failed to serialize query key");
105	self.exists(key).is_ok()
106}
107
108/// Checks whether a raw key exists asynchronously.
109///
110/// Success returns unit, while missing keys and database failures remain
111/// errors. The lookup uses the same cache-first path as `get`.
112#[inline]
113#[implement(super::Map)]
114pub fn exists<'a, K>(
115	self: &'a Arc<Self>,
116	key: &K,
117) -> impl Future<Output = Result> + Send + 'a + use<'a, K>
118where
119	K: AsRef<[u8]> + ?Sized + Debug + 'a,
120{
121	self.get(key).map(|res| res.map(|_| ()))
122}
123
124/// Checks synchronously whether a raw key exists.
125///
126/// A cache-tier existence hint can avoid a point read when absence is certain.
127/// Missing keys return the map's not-found error, while database failures
128/// remain errors.
129#[implement(super::Map)]
130#[tracing::instrument(skip(self, key), fields(%self), level = "trace")]
131pub fn exists_blocking<K>(&self, key: &K) -> Result
132where
133	K: AsRef<[u8]> + ?Sized + Debug,
134{
135	self.maybe_exists(key)
136		.then(|| self.get_blocking(key))
137		.flat_ok()
138		.map(|_| ())
139		.ok_or_else(|| err!(Request(NotFound("Not found in database"))))
140}
141
142/// Tests whether RocksDB can rule out a raw key without storage I/O.
143///
144/// A `false` result proves absence, while `true` still requires a point read.
145/// The configured read options restrict the probe to block cache.
146#[implement(super::Map)]
147pub(crate) fn maybe_exists<K>(&self, key: &K) -> bool
148where
149	K: AsRef<[u8]> + ?Sized,
150{
151	self.engine
152		.db
153		.key_may_exist_cf_opt(&self.cf(), key, &self.cache_read_options)
154}