aerospike/commands/
exists_command.rs

1// Copyright 2015-2018 Aerospike, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::sync::Arc;
16use std::time::Duration;
17
18use crate::cluster::{Cluster, Node};
19use crate::commands::{buffer, Command, SingleCommand};
20use crate::errors::{ErrorKind, Result};
21use crate::net::Connection;
22use crate::policy::WritePolicy;
23use crate::{Key, ResultCode};
24
25pub struct ExistsCommand<'a> {
26    single_command: SingleCommand<'a>,
27    policy: &'a WritePolicy,
28    pub exists: bool,
29}
30
31impl<'a> ExistsCommand<'a> {
32    pub fn new(policy: &'a WritePolicy, cluster: Arc<Cluster>, key: &'a Key) -> Self {
33        ExistsCommand {
34            single_command: SingleCommand::new(cluster, key),
35            policy,
36            exists: false,
37        }
38    }
39
40    pub fn execute(&mut self) -> Result<()> {
41        SingleCommand::execute(self.policy, self)
42    }
43}
44
45impl<'a> Command for ExistsCommand<'a> {
46    fn write_timeout(&mut self, conn: &mut Connection, timeout: Option<Duration>) -> Result<()> {
47        conn.buffer.write_timeout(timeout);
48        Ok(())
49    }
50
51    fn write_buffer(&mut self, conn: &mut Connection) -> Result<()> {
52        conn.flush()
53    }
54
55    fn prepare_buffer(&mut self, conn: &mut Connection) -> Result<()> {
56        conn.buffer.set_exists(self.policy, self.single_command.key)
57    }
58
59    fn get_node(&self) -> Result<Arc<Node>> {
60        self.single_command.get_node()
61    }
62
63    fn parse_result(&mut self, conn: &mut Connection) -> Result<()> {
64        // Read header.
65        if let Err(err) = conn.read_buffer(buffer::MSG_TOTAL_HEADER_SIZE as usize) {
66            warn!("Parse result error: {}", err);
67            return Err(err);
68        }
69
70        conn.buffer.reset_offset()?;
71
72        // A number of these are commented out because we just don't care enough to read
73        // that section of the header. If we do care, uncomment and check!
74        let result_code = ResultCode::from(conn.buffer.read_u8(Some(13))?);
75
76        if result_code != ResultCode::Ok && result_code != ResultCode::KeyNotFoundError {
77            bail!(ErrorKind::ServerError(result_code));
78        }
79
80        self.exists = result_code == ResultCode::Ok;
81
82        SingleCommand::empty_socket(conn)
83    }
84}