paper-client 1.11.0

The Rust PaperCache client.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
/*
 * Copyright (c) Kia Shakiba
 *
 * This source code is licensed under the GNU AGPLv3 license found in the
 * LICENSE file in the root directory of this source tree.
 */

use std::net::TcpStream;

pub use paper_utils::stream::{StreamError, StreamReader};

use crate::{
	addr::FromPaperAddr,
	arg::{AsPaperAuthToken, AsPaperKey},
	command::Command,
	error::{PaperClientError, PaperClientResult},
	policy::PaperPolicy,
	status::Status,
	value::PaperValue,
};

const RECONNECT_MAX_ATTEMPTS: u8 = 3;

#[derive(Debug)]
pub struct PaperClient {
	addr: String,

	auth_token:         Option<String>,
	reconnect_attempts: u8,

	stream: TcpStream,
}

impl PaperClient {
	/// Creates a new instance of the client and connects to the server.
	/// If a connection could not be established, a `PaperClientError`
	/// is returned.
	///
	/// # Examples
	/// ```
	/// use paper_client::PaperClient;
	///
	/// let client = PaperClient::new("paper://127.0.0.1:3145").unwrap();
	/// ```
	pub fn new(paper_addr: impl FromPaperAddr) -> PaperClientResult<Self> {
		let addr = paper_addr.to_addr()?;
		let stream = init_stream(&addr)?;

		let mut client = PaperClient {
			addr,

			auth_token: None,
			reconnect_attempts: 0,

			stream,
		};

		client.handshake()?;

		Ok(client)
	}

	/// Pings the server.
	///
	/// # Examples
	/// ```
	/// use paper_client::PaperClient;
	///
	/// let mut client = PaperClient::new("paper://127.0.0.1:3145").unwrap();
	///
	/// match client.ping() {
	///     Ok(value) => println!("{value:?}"),
	///     Err(err) => println!("{err:?}"),
	/// }
	/// ```
	pub fn ping(&mut self) -> PaperClientResult<PaperValue> {
		self.process_value(&Command::Ping)
	}

	/// Gets the cache version.
	///
	/// # Examples
	/// ```
	/// use paper_client::PaperClient;
	///
	/// let mut client = PaperClient::new("paper://127.0.0.1:3145").unwrap();
	///
	/// match client.version() {
	///     Ok(value) => println!("{value:?}"),
	///     Err(err) => println!("{err:?}"),
	/// }
	/// ```
	pub fn version(&mut self) -> PaperClientResult<PaperValue> {
		self.process_value(&Command::Version)
	}

	/// Attempts to authorize the connection with the supplied auth token. This
	/// must match the auth token specified in the server's configuration to be
	/// successful.
	///
	/// # Examples
	/// ```
	/// use paper_client::PaperClient;
	///
	/// let mut client = PaperClient::new("paper://127.0.0.1:3145").unwrap();
	///
	/// match client.auth("my_token") {
	///     Ok(_) => println!("done"),
	///     Err(err) => println!("{err:?}"),
	/// }
	/// ```
	pub fn auth(&mut self, token: impl AsPaperAuthToken) -> PaperClientResult<()> {
		let auth_token = token.as_paper_auth_token();

		let command = Command::Auth(auth_token);
		let result = self.process(&command);

		self.auth_token = Some(auth_token.to_owned());

		result
	}

	/// Gets the value of the supplied key from the cache.
	///
	/// # Examples
	/// ```
	/// use paper_client::PaperClient;
	///
	/// let mut client = PaperClient::new("paper://127.0.0.1:3145").unwrap();
	///
	/// match client.get("key") {
	///     Ok(value) => println!("{value:?}"),
	///     Err(err) => println!("{err:?}"),
	/// }
	/// ```
	pub fn get(&mut self, key: impl AsPaperKey) -> PaperClientResult<PaperValue> {
		let command = Command::Get(key.as_paper_key());
		self.process_value(&command)
	}

	/// Sets the supplied key, value, and ttl to the cache.
	///
	/// # Examples
	/// ```
	/// use paper_client::PaperClient;
	///
	/// let mut client = PaperClient::new("paper://127.0.0.1:3145").unwrap();
	///
	/// match client.set("key", "value", None) {
	///     Ok(_) => println!("done"),
	///     Err(err) => println!("{err:?}"),
	/// }
	/// ```
	pub fn set(
		&mut self,
		key: impl AsPaperKey,
		value: impl TryInto<PaperValue>,
		ttl: Option<u32>,
	) -> PaperClientResult<()> {
		let value: PaperValue = value
			.try_into()
			.map_err(|_| PaperClientError::InvalidValue)?;

		let command = Command::Set(key.as_paper_key(), value, ttl.unwrap_or(0));

		self.process(&command)
	}

	/// Deletes the value of the supplied key from the cache.
	///
	/// # Examples
	/// ```
	/// use paper_client::PaperClient;
	///
	/// let mut client = PaperClient::new("paper://127.0.0.1:3145").unwrap();
	///
	/// match client.del("key") {
	///     Ok(_) => println!("done"),
	///     Err(err) => println!("{err:?}"),
	/// }
	/// ```
	pub fn del(&mut self, key: impl AsPaperKey) -> PaperClientResult<()> {
		let command = Command::Del(key.as_paper_key());
		self.process(&command)
	}

	/// Checks if the cache contains an object with the supplied key
	/// without altering the eviction order of the objects.
	///
	/// # Examples
	/// ```
	/// use paper_client::PaperClient;
	///
	/// let mut client = PaperClient::new("paper://127.0.0.1:3145").unwrap();
	///
	/// match client.has("key") {
	///     Ok(has) => println!("{has}"),
	///     Err(err) => println!("{err:?}"),
	/// }
	/// ```
	pub fn has(&mut self, key: impl AsPaperKey) -> PaperClientResult<bool> {
		let command = Command::Has(key.as_paper_key());
		self.process_has(&command)
	}

	/// Gets (peeks) the value of the supplied key from the cache without
	/// altering the eviction order of the objects.
	///
	/// # Examples
	/// ```
	/// use paper_client::PaperClient;
	///
	/// let mut client = PaperClient::new("paper://127.0.0.1:3145").unwrap();
	///
	/// match client.peek("key") {
	///     Ok(value) => println!("{value:?}"),
	///     Err(err) => println!("{err:?}"),
	/// }
	/// ```
	pub fn peek(&mut self, key: impl AsPaperKey) -> PaperClientResult<PaperValue> {
		let command = Command::Peek(key.as_paper_key());
		self.process_value(&command)
	}

	/// Sets the TTL associated with the supplied key.
	///
	/// # Examples
	/// ```
	/// use paper_client::PaperClient;
	///
	/// let mut client = PaperClient::new("paper://127.0.0.1:3145").unwrap();
	///
	/// match client.ttl("key", Some(5)) {
	///     Ok(_) => println!("done"),
	///     Err(err) => println!("{err:?}"),
	/// }
	/// ```
	pub fn ttl(&mut self, key: impl AsPaperKey, ttl: Option<u32>) -> PaperClientResult<()> {
		let command = Command::Ttl(key.as_paper_key(), ttl.unwrap_or(0));
		self.process(&command)
	}

	/// Gets the size of the value of the supplied key from the cache in bytes.
	///
	/// # Examples
	/// ```
	/// use paper_client::PaperClient;
	///
	/// let mut client = PaperClient::new("paper://127.0.0.1:3145").unwrap();
	///
	/// match client.size("key") {
	///     Ok(size) => println!("{size}"),
	///     Err(err) => println!("{err:?}"),
	/// }
	/// ```
	pub fn size(&mut self, key: impl AsPaperKey) -> PaperClientResult<u32> {
		let command = Command::Size(key.as_paper_key());
		self.process_size(&command)
	}

	/// Wipes the contents of the cache.
	///
	/// # Examples
	/// ```
	/// use paper_client::PaperClient;
	///
	/// let mut client = PaperClient::new("paper://127.0.0.1:3145").unwrap();
	///
	/// match client.wipe() {
	///     Ok(_) => println!("done"),
	///     Err(err) => println!("{err:?}"),
	/// }
	/// ```
	pub fn wipe(&mut self) -> PaperClientResult<()> {
		self.process(&Command::Wipe)
	}

	/// Resizes the cache to the supplied size.
	///
	/// # Examples
	/// ```
	/// use paper_client::PaperClient;
	///
	/// let mut client = PaperClient::new("paper://127.0.0.1:3145").unwrap();
	///
	/// match client.resize(10) {
	///     Ok(_) => println!("done"),
	///     Err(err) => println!("{err:?}"),
	/// }
	/// ```
	pub fn resize(&mut self, size: u64) -> PaperClientResult<()> {
		let command = Command::Resize(size);
		self.process(&command)
	}

	/// Sets the cache's eviction policy.
	///
	/// # Examples
	/// ```
	/// use paper_client::{PaperClient, PaperPolicy};
	///
	/// let mut client = PaperClient::new("paper://127.0.0.1:3145").unwrap();
	///
	/// match client.policy(PaperPolicy::Lru) {
	///     Ok(_) => println!("done"),
	///     Err(err) => println!("{err:?}"),
	/// }
	/// ```
	pub fn policy(&mut self, policy: PaperPolicy) -> PaperClientResult<()> {
		let command = Command::Policy(policy);
		self.process(&command)
	}

	/// Gets the cache's status.
	///
	/// # Examples
	/// ```
	/// use paper_client::PaperClient;
	///
	/// let mut client = PaperClient::new("paper://127.0.0.1:3145").unwrap();
	///
	/// match client.status() {
	///     Ok(status) => println!("{status:?}"),
	///     Err(err) => println!("{err:?}"),
	/// }
	/// ```
	pub fn status(&mut self) -> PaperClientResult<Status> {
		self.process_status(&Command::Status)
	}

	fn process(&mut self, command: &Command<'_>) -> PaperClientResult<()> {
		match self
			.send(command)
			.and_then(|_| self.receive(command))
		{
			Ok(response) => {
				self.reconnect_attempts = 0;
				Ok(response)
			},

			Err(PaperClientError::InvalidResponse) => {
				self.reconnect_attempts += 1;
				self.reconnect()?;
				self.process(command)
			},

			err => err,
		}
	}

	fn process_value(&mut self, command: &Command<'_>) -> PaperClientResult<PaperValue> {
		match self
			.send(command)
			.and_then(|_| self.receive_value(command))
		{
			Ok(response) => {
				self.reconnect_attempts = 0;
				Ok(response)
			},

			Err(PaperClientError::InvalidResponse) => {
				self.reconnect_attempts += 1;
				self.reconnect()?;
				self.process_value(command)
			},

			err => err,
		}
	}

	fn process_has(&mut self, command: &Command<'_>) -> PaperClientResult<bool> {
		match self
			.send(command)
			.and_then(|_| self.receive_has(command))
		{
			Ok(response) => {
				self.reconnect_attempts = 0;
				Ok(response)
			},

			Err(PaperClientError::InvalidResponse) => {
				self.reconnect_attempts += 1;
				self.reconnect()?;
				self.process_has(command)
			},

			err => err,
		}
	}

	fn process_size(&mut self, command: &Command<'_>) -> PaperClientResult<u32> {
		match self
			.send(command)
			.and_then(|_| self.receive_size(command))
		{
			Ok(response) => {
				self.reconnect_attempts = 0;
				Ok(response)
			},

			Err(PaperClientError::InvalidResponse) => {
				self.reconnect_attempts += 1;
				self.reconnect()?;
				self.process_size(command)
			},

			err => err,
		}
	}

	fn process_status(&mut self, command: &Command<'_>) -> PaperClientResult<Status> {
		match self
			.send(command)
			.and_then(|_| self.receive_status(command))
		{
			Ok(response) => {
				self.reconnect_attempts = 0;
				Ok(response)
			},

			Err(PaperClientError::InvalidResponse) => {
				self.reconnect_attempts += 1;
				self.reconnect()?;
				self.process_status(command)
			},

			err => err,
		}
	}

	fn send(&mut self, command: &Command<'_>) -> PaperClientResult<()> {
		command
			.write(&mut self.stream)
			.map_err(|err| match err {
				StreamError::InvalidStream => PaperClientError::Disconnected,
				_ => PaperClientError::InvalidCommand,
			})
	}

	fn receive(&mut self, command: &Command<'_>) -> PaperClientResult<()> {
		command.parse_reader(&mut self.stream)
	}

	fn receive_value(&mut self, command: &Command<'_>) -> PaperClientResult<PaperValue> {
		command.parse_buf_reader(&mut self.stream)
	}

	fn receive_has(&mut self, command: &Command<'_>) -> PaperClientResult<bool> {
		command.parse_has_reader(&mut self.stream)
	}

	fn receive_size(&mut self, command: &Command<'_>) -> PaperClientResult<u32> {
		command.parse_size_reader(&mut self.stream)
	}

	fn receive_status(&mut self, command: &Command<'_>) -> PaperClientResult<Status> {
		command.parse_status_reader(&mut self.stream)
	}

	fn handshake(&mut self) -> PaperClientResult<()> {
		let mut reader = StreamReader::new(&mut self.stream);

		let is_ok = reader
			.read_bool()
			.map_err(|_| PaperClientError::UnreachableServer)?;

		match is_ok {
			true => Ok(()),
			false => Err(PaperClientError::from_reader(reader)),
		}
	}

	fn reconnect(&mut self) -> PaperClientResult<()> {
		if self.reconnect_attempts > RECONNECT_MAX_ATTEMPTS {
			return Err(PaperClientError::Disconnected);
		}

		self.stream = init_stream(&self.addr)?;
		self.handshake()?;

		if let Some(token) = self.auth_token.clone() {
			self.auth(token)?;
		}

		Ok(())
	}
}

fn init_stream(addr: &str) -> PaperClientResult<TcpStream> {
	let stream = TcpStream::connect(addr).map_err(|_| PaperClientError::UnreachableServer)?;

	if stream.set_nodelay(true).is_err() {
		return Err(PaperClientError::Internal);
	}

	Ok(stream)
}