Skip to main content

tuwunel_admin/query/raw/
mod.rs

1// Fires in clap's Subcommand derive output, which an item-level allow does not reach.
2#![expect(clippy::large_unopt_stack_frames)]
3
4mod clear;
5mod compact;
6mod count;
7mod del;
8mod flush;
9mod get;
10mod iter;
11mod keys;
12mod keys_sizes;
13mod keys_total;
14mod maps;
15mod put;
16mod sequence;
17mod vals_sizes;
18mod vals_total;
19
20use std::sync::Arc;
21
22use clap::Subcommand;
23use tuwunel_core::{Result, err, expected, itertools::Itertools, utils::bytes::escape_bytes};
24use tuwunel_database::Map;
25use tuwunel_service::Services;
26
27use crate::admin_command_dispatch;
28
29#[admin_command_dispatch(handler_prefix = "raw")]
30#[derive(Debug, Subcommand)]
31/// Query tables from database
32pub(crate) enum RawCommand {
33	/// - List database maps
34	Maps,
35
36	/// - Current rocksdb sequence number.
37	Sequence,
38
39	/// - Raw database query
40	Get {
41		/// Map name
42		map: String,
43
44		/// Key
45		key: String,
46
47		/// Encode as base64
48		#[arg(long, short)]
49		base64: bool,
50	},
51
52	/// - Raw database keys iteration
53	Keys {
54		/// Map name
55		map: String,
56
57		/// Key prefix
58		prefix: Option<String>,
59
60		/// Limit
61		#[arg(short, long)]
62		limit: Option<usize>,
63
64		/// Lower bound
65		#[arg(short, long)]
66		from: Option<String>,
67
68		/// Reverse iteration order
69		#[arg(short, long, default_value("false"))]
70		backwards: bool,
71	},
72
73	/// - Raw database items iteration
74	Iter {
75		/// Map name
76		map: String,
77
78		/// Key prefix
79		prefix: Option<String>,
80
81		/// Limit
82		#[arg(short, long)]
83		limit: Option<usize>,
84
85		/// Lower bound
86		#[arg(short, long)]
87		from: Option<String>,
88
89		/// Reverse iteration order
90		#[arg(short, long, default_value("false"))]
91		backwards: bool,
92	},
93
94	/// - Raw database key size breakdown
95	KeysSizes {
96		/// Map name
97		map: Option<String>,
98
99		/// Key prefix
100		prefix: Option<String>,
101	},
102
103	/// - Raw database keys total bytes
104	KeysTotal {
105		/// Map name
106		map: Option<String>,
107
108		/// Key prefix
109		prefix: Option<String>,
110	},
111
112	/// - Raw database values size breakdown
113	ValsSizes {
114		/// Map name
115		map: Option<String>,
116
117		/// Key prefix
118		prefix: Option<String>,
119	},
120
121	/// - Raw database values total bytes
122	ValsTotal {
123		/// Map name
124		map: Option<String>,
125
126		/// Key prefix
127		prefix: Option<String>,
128	},
129
130	/// - Raw database record count
131	Count {
132		/// Map name
133		map: Option<String>,
134
135		/// Key prefix
136		prefix: Option<String>,
137	},
138
139	/// - Raw database put
140	Put {
141		/// Map name
142		map: String,
143
144		/// Key
145		key: String,
146
147		/// Value
148		value: String,
149	},
150
151	/// - Raw database delete (for string keys) DANGER!!!
152	Del {
153		/// Map name
154		map: String,
155
156		/// Key
157		key: String,
158	},
159
160	/// - Clear database table DANGER!!!
161	Clear {
162		/// Map name
163		map: String,
164
165		/// Confirm
166		#[arg(long)]
167		confirm: bool,
168	},
169
170	/// - Compact database DANGER!!!
171	Compact {
172		#[arg(short, long, alias("column"))]
173		maps: Option<Vec<String>>,
174
175		#[arg(long)]
176		start: Option<String>,
177
178		#[arg(long)]
179		stop: Option<String>,
180
181		#[arg(long)]
182		from: Option<usize>,
183
184		#[arg(long)]
185		into: Option<usize>,
186
187		/// There is one compaction job per column; then this controls how many
188		/// columns are compacted in parallel. If zero, one compaction job is
189		/// still run at a time here, but in exclusive-mode blocking any other
190		/// automatic compaction jobs until complete.
191		#[arg(long)]
192		parallelism: Option<usize>,
193
194		#[arg(long, default_value("false"))]
195		exhaustive: bool,
196	},
197
198	/// - Flush RocksDB memtables to SST files (LSM flush, not fsync/fflush)
199	Flush,
200}
201
202fn with_map_or(map: Option<&str>, services: &Services) -> Result<Vec<Arc<Map>>> {
203	with_maps_or(
204		map.map(|map| [map])
205			.as_ref()
206			.map(<[&str; 1]>::as_slice),
207		services,
208	)
209}
210
211fn with_maps_or<S: AsRef<str>>(maps: Option<&[S]>, services: &Services) -> Result<Vec<Arc<Map>>> {
212	Ok(if let Some(maps) = maps {
213		maps.iter()
214			.map(|map| {
215				let map = map.as_ref();
216				services
217					.db
218					.get(map)
219					.cloned()
220					.map_err(|_| err!("map {map} not found"))
221			})
222			.try_collect()?
223	} else {
224		services.db.iter().map(|x| x.1.clone()).collect()
225	})
226}
227
228fn from_hex(byte: u8) -> Option<u8> {
229	match byte {
230		| 0x30..=0x39 => Some(expected!(byte - 0x30)),
231		| 0x41..=0x46 => Some(expected!((byte - 0x41) + 10)),
232		| 0x61..=0x66 => Some(expected!((byte - 0x61) + 10)),
233		| _ => None,
234	}
235}
236
237fn decode(data: &str) -> Vec<u8> {
238	let mut res = Vec::with_capacity(data.len());
239
240	for byte in data.bytes() {
241		res.push(byte);
242
243		let length = res.len();
244
245		if length >= 4
246			&& let Some(slice) = res.get(expected!(length - 4)..length)
247			&& slice.starts_with(b"\\x")
248			&& let Some(a) = from_hex(slice[2])
249			&& let Some(b) = from_hex(slice[3])
250		{
251			res.truncate(expected!(length - 4));
252
253			let byte = (a << 4) | b;
254			res.push(byte);
255		}
256	}
257
258	res
259}
260
261fn encode(data: &[u8]) -> String { escape_bytes(data).to_string() }