1use std::io::{self, Write};
6use std::time::{Duration, Instant};
7
8use kevy_resp::Reply;
9use kevy_resp_client::RespClient;
10
11pub struct RateLimiter {
16 rate: u64,
17 tokens: f64,
18 last: Instant,
19}
20
21impl RateLimiter {
22 pub fn new(rate: u64) -> Self {
24 Self { rate, tokens: 0.0, last: Instant::now() }
25 }
26
27 pub fn take(&mut self) {
29 if self.rate == 0 {
30 return;
31 }
32 loop {
33 let now = Instant::now();
34 self.tokens = (self.tokens + now.duration_since(self.last).as_secs_f64() * self.rate as f64)
35 .min(self.rate as f64);
36 self.last = now;
37 if self.tokens >= 1.0 {
38 self.tokens -= 1.0;
39 return;
40 }
41 std::thread::sleep(Duration::from_millis(2));
42 }
43 }
44}
45
46fn scan_page(client: &mut RespClient, cursor: &[u8], pattern: &[u8]) -> io::Result<(Vec<u8>, Vec<Vec<u8>>)> {
47 let reply = client.request_borrowed(&[b"SCAN", cursor, b"MATCH", pattern, b"COUNT", b"512"])?;
48 let Reply::Array(items) = reply else {
49 return Err(io::Error::new(io::ErrorKind::InvalidData, "SCAN reply shape"));
50 };
51 let (Some(Reply::Bulk(next)), Some(Reply::Array(keys))) = (items.first(), items.get(1)) else {
52 return Err(io::Error::new(io::ErrorKind::InvalidData, "SCAN reply shape"));
53 };
54 let keys = keys
55 .iter()
56 .filter_map(|k| if let Reply::Bulk(b) = k { Some(b.clone()) } else { None })
57 .collect();
58 Ok((next.clone(), keys))
59}
60
61pub fn run_delete_prefix(
63 client: &mut RespClient,
64 prefix: &[u8],
65 rate: u64,
66 dry_run: bool,
67) -> io::Result<u64> {
68 let mut pattern = prefix.to_vec();
69 pattern.push(b'*');
70 let mut cursor: Vec<u8> = b"0".to_vec();
71 let mut limiter = RateLimiter::new(rate);
72 let mut n = 0u64;
73 loop {
74 let (next, keys) = scan_page(client, &cursor, &pattern)?;
75 for key in &keys {
76 if dry_run {
77 n += 1;
78 continue;
79 }
80 limiter.take();
81 if let Reply::Int(d) = client.request_borrowed(&[b"UNLINK", key])? {
82 n += d as u64;
83 }
84 }
85 cursor = next;
86 if cursor == b"0" {
87 return Ok(n);
88 }
89 }
90}
91
92pub fn run_copy_prefix(
100 client: &mut RespClient,
101 src_prefix: &[u8],
102 dst_prefix: &[u8],
103 rate: u64,
104) -> io::Result<crate::migrate::Export> {
105 let mut pattern = src_prefix.to_vec();
106 pattern.push(b'*');
107 let mut cursor: Vec<u8> = b"0".to_vec();
108 let mut limiter = RateLimiter::new(rate);
109 let mut n = 0u64;
110 let mut skipped: std::collections::BTreeMap<Vec<u8>, u64> = Default::default();
113 loop {
114 let (next, keys) = scan_page(client, &cursor, &pattern)?;
115 for key in &keys {
116 limiter.take();
117 let mut dst = dst_prefix.to_vec();
118 dst.extend_from_slice(&key[src_prefix.len()..]);
119 let frames = match crate::migrate::rebuild_frames(client, key, &dst)? {
120 crate::migrate::Rebuilt::Frames(f) => f,
121 crate::migrate::Rebuilt::Vanished => continue,
122 crate::migrate::Rebuilt::UnsupportedType(ty) => {
123 *skipped.entry(ty).or_insert(0u64) += 1;
124 continue;
125 }
126 };
127 let n_cmds = count_commands(&frames);
128 for r in client.pipeline_raw(&frames, n_cmds)? {
129 if let Reply::Error(e) = r {
130 return Err(io::Error::new(
131 io::ErrorKind::InvalidData,
132 String::from_utf8_lossy(&e).into_owned(),
133 ));
134 }
135 }
136 n += 1;
137 }
138 cursor = next;
139 if cursor == b"0" {
140 return Ok(crate::migrate::Export { keys: n, skipped });
141 }
142 }
143}
144
145fn count_commands(mut b: &[u8]) -> usize {
147 let mut n = 0;
148 while let Some(len) = crate::migrate::command_len_pub(b) {
149 n += 1;
150 b = &b[len..];
151 }
152 n
153}
154
155pub fn run_digest(client: &mut RespClient, prefix: &[u8]) -> io::Result<(i64, String)> {
157 let r = client.request_borrowed(&[b"PREFIX.DIGEST", prefix])?;
158 let Reply::Array(items) = r else {
159 return Err(io::Error::new(io::ErrorKind::InvalidData, "PREFIX.DIGEST reply"));
160 };
161 let (Some(Reply::Int(n)), Some(Reply::Bulk(hex))) = (items.first(), items.get(1)) else {
162 return Err(io::Error::new(io::ErrorKind::InvalidData, "PREFIX.DIGEST reply"));
163 };
164 Ok((*n, String::from_utf8_lossy(hex).into_owned()))
165}
166
167pub fn run_diff(
170 a: &mut RespClient,
171 b: &mut RespClient,
172 prefixes: &[Vec<u8>],
173 out: &mut impl Write,
174) -> io::Result<Vec<Vec<u8>>> {
175 let mut bad = Vec::new();
176 for p in prefixes {
177 let (na, da) = run_digest(a, p)?;
178 let (nb, db) = run_digest(b, p)?;
179 let ok = na == nb && da == db;
180 writeln!(
181 out,
182 "{} A: {na} keys {da} B: {nb} keys {db} {}",
183 String::from_utf8_lossy(p),
184 if ok { "OK" } else { "MISMATCH" }
185 )?;
186 if !ok {
187 bad.push(p.clone());
188 }
189 }
190 Ok(bad)
191}
192
193pub fn run_inspect(client: &mut RespClient, prefix: &[u8], out: &mut impl Write) -> io::Result<()> {
195 let mut pattern = prefix.to_vec();
196 pattern.push(b'*');
197 let mut cursor: Vec<u8> = b"0".to_vec();
198 let mut total = 0u64;
199 let mut by_type: Vec<(String, u64)> = Vec::new();
200 let mut samples: Vec<String> = Vec::new();
201 loop {
202 let (next, keys) = scan_page(client, &cursor, &pattern)?;
203 for key in &keys {
204 total += 1;
205 if samples.len() < 8 {
206 samples.push(String::from_utf8_lossy(key).into_owned());
207 }
208 if let Reply::Simple(t) = client.request_borrowed(&[b"TYPE", key])? {
209 let t = String::from_utf8_lossy(&t).into_owned();
210 match by_type.iter_mut().find(|(n, _)| *n == t) {
211 Some((_, c)) => *c += 1,
212 None => by_type.push((t, 1)),
213 }
214 }
215 }
216 cursor = next;
217 if cursor == b"0" {
218 break;
219 }
220 }
221 writeln!(out, "prefix {}: {total} keys", String::from_utf8_lossy(prefix))?;
222 by_type.sort_by_key(|(_, c)| std::cmp::Reverse(*c));
223 for (t, c) in &by_type {
224 writeln!(out, " {t}: {c}")?;
225 }
226 if !samples.is_empty() {
227 writeln!(out, " samples: {}", samples.join(", "))?;
228 }
229 Ok(())
230}