mongodb/event/command.rs
1//! Contains the events and functionality to monitor the commands and responses that a `Client`
2//! sends and receives from the server.
3
4use std::time::Duration;
5
6use serde::Serialize;
7
8use crate::{
9 bson::{oid::ObjectId, Document},
10 error::Error,
11 serde_util,
12};
13
14pub use crate::cmap::ConnectionInfo;
15
16/// An event that triggers when a database command is initiated.
17#[derive(Clone, Debug, Serialize)]
18#[serde(rename_all = "camelCase")]
19#[non_exhaustive]
20pub struct CommandStartedEvent {
21 /// The command being run.
22 pub command: Document,
23
24 /// The name of the database the command is being run against.
25 pub db: String,
26
27 /// The type of command being run, e.g. "find" or "hello".
28 pub command_name: String,
29
30 /// The driver-generated identifier for the request. Applications can use this to identify the
31 /// corresponding event triggered by the completion of this command (i.e. either
32 /// [`CommandSucceededEvent`](struct.CommandSucceededEvent.html) or
33 /// [`CommandFailedEvent`](struct.CommandFailedEvent.html)).
34 pub request_id: i32,
35
36 /// Information about the connect the command will be run on.
37 pub connection: ConnectionInfo,
38
39 /// If the client connection is to a load balancer, the id of the selected backend.
40 pub service_id: Option<ObjectId>,
41}
42
43/// An event that triggers when a database command completes without an error.
44#[derive(Clone, Debug, Serialize)]
45#[serde(rename_all = "camelCase")]
46#[non_exhaustive]
47pub struct CommandSucceededEvent {
48 /// The total execution time of the command (including the network round-trip).
49 pub duration: Duration,
50
51 /// The server's reply to the command.
52 pub reply: Document,
53
54 /// The type of command that was run, e.g. "find" or "hello".
55 pub command_name: String,
56
57 /// The driver-generated identifier for the request. Applications can use this to identify the
58 /// corresponding [`CommandStartedEvent`](struct.CommandStartedEvent.html) that triggered
59 /// earlier.
60 pub request_id: i32,
61
62 /// Information about the connect the command will be run on.
63 pub connection: ConnectionInfo,
64
65 /// If the client connection is to a load balancer, the id of the selected backend.
66 pub service_id: Option<ObjectId>,
67}
68
69/// An event that triggers when a command failed to complete successfully.
70#[derive(Clone, Debug, Serialize)]
71#[serde(rename_all = "camelCase")]
72#[non_exhaustive]
73pub struct CommandFailedEvent {
74 /// The total execution time of the command (including the network round-trip).
75 pub duration: Duration,
76
77 /// The type of command that was run, e.g. "find" or "hello".
78 pub command_name: String,
79
80 /// The error that the driver returned due to the event failing.
81 #[serde(serialize_with = "serde_util::serialize_error_as_string")]
82 pub failure: Error,
83
84 /// The driver-generated identifier for the request. Applications can use this to identify the
85 /// corresponding [`CommandStartedEvent`](struct.CommandStartedEvent.html) that triggered
86 /// earlier.
87 pub request_id: i32,
88
89 /// Information about the connect the command will be run on.
90 pub connection: ConnectionInfo,
91
92 /// If the client connection is to a load balancer, the id of the selected backend.
93 pub service_id: Option<ObjectId>,
94}
95
96/// Usage of this trait is deprecated. Applications should use the
97/// [`EventHandler`](crate::event::EventHandler) API.
98///
99/// Applications can implement this trait to specify custom logic to run on each command event sent
100/// by the driver.
101///
102/// ```rust
103/// # use std::sync::Arc;
104/// #
105/// # use mongodb::{
106/// # error::Result,
107/// # event::command::{
108/// # CommandEventHandler,
109/// # CommandFailedEvent
110/// # },
111/// # options::ClientOptions,
112/// # };
113/// # #[cfg(feature = "sync")]
114/// # use mongodb::sync::Client;
115/// # #[cfg(not(feature = "sync"))]
116/// # use mongodb::Client;
117/// #
118/// struct FailedCommandLogger;
119///
120/// impl CommandEventHandler for FailedCommandLogger {
121/// fn handle_command_failed_event(&self, event: CommandFailedEvent) {
122/// eprintln!("Failed command: {:?}", event);
123/// }
124/// }
125///
126/// # fn do_stuff() -> Result<()> {
127/// let handler = Arc::new(FailedCommandLogger);
128/// let options = ClientOptions::builder()
129/// .command_event_handler(handler)
130/// .build();
131/// let client = Client::with_options(options)?;
132///
133/// // Do things with the client, and failed command events will be logged to stderr.
134/// # Ok(())
135/// # }
136/// ```
137#[deprecated = "use the EventHandler API"]
138pub trait CommandEventHandler: Send + Sync {
139 /// A [`Client`](../../struct.Client.html) will call this method on each registered handler
140 /// whenever a database command is initiated.
141 fn handle_command_started_event(&self, _event: CommandStartedEvent) {}
142
143 /// A [`Client`](../../struct.Client.html) will call this method on each registered handler
144 /// whenever a database command successfully completes.
145 fn handle_command_succeeded_event(&self, _event: CommandSucceededEvent) {}
146
147 /// A [`Client`](../../struct.Client.html) will call this method on each registered handler
148 /// whenever a database command fails to complete successfully.
149 fn handle_command_failed_event(&self, _event: CommandFailedEvent) {}
150}
151
152#[derive(Clone, Debug, Serialize)]
153#[allow(missing_docs)]
154#[serde(untagged)]
155#[non_exhaustive]
156pub enum CommandEvent {
157 Started(CommandStartedEvent),
158 Succeeded(CommandSucceededEvent),
159 Failed(CommandFailedEvent),
160}