bonsaidb_core/
networking.rs

1use arc_bytes::serde::Bytes;
2use serde::{Deserialize, Serialize};
3
4use crate::api::{Api, ApiName};
5use crate::connection::{
6    AccessPolicy, Database, IdentityReference, Range, SerializedQueryKey, Session, SessionId, Sort,
7};
8use crate::document::{DocumentId, Header, OwnedDocument};
9use crate::keyvalue::{KeyOperation, Output};
10use crate::schema::view::map::{self, MappedSerializedDocuments};
11use crate::schema::{CollectionName, NamedReference, Qualified, SchemaSummary, ViewName};
12use crate::transaction::{Executed, OperationResult, Transaction};
13
14/// The current protocol version.
15pub const CURRENT_PROTOCOL_VERSION: &str = "bonsai-pre-1";
16
17/// A payload with an associated id.
18#[derive(Clone, Deserialize, Serialize, Debug)]
19pub struct Payload {
20    /// The authentication session id for this payload.
21    pub session_id: Option<SessionId>,
22    /// The unique id for this payload.
23    pub id: Option<u32>,
24    /// The unique name of the api
25    pub name: ApiName,
26    /// The payload
27    pub value: Result<Bytes, crate::Error>,
28}
29
30/// Creates a database.
31#[derive(Clone, Deserialize, Serialize, Debug)]
32pub struct CreateDatabase {
33    /// The database to create.
34    pub database: Database,
35    /// Only attempts to create the database if it doesn't already exist.
36    pub only_if_needed: bool,
37}
38
39impl Api for CreateDatabase {
40    type Error = crate::Error;
41    type Response = ();
42
43    fn name() -> ApiName {
44        ApiName::new("bonsaidb", "CreateDatabase")
45    }
46}
47
48/// Deletes the database named `name`
49#[derive(Clone, Deserialize, Serialize, Debug)]
50pub struct DeleteDatabase {
51    /// The name of the database to delete.
52    pub name: String,
53}
54
55impl Api for DeleteDatabase {
56    type Error = crate::Error;
57    type Response = ();
58
59    fn name() -> ApiName {
60        ApiName::new("bonsaidb", "DeleteDatabase")
61    }
62}
63
64/// Lists all databases.
65#[derive(Clone, Deserialize, Serialize, Debug)]
66pub struct ListDatabases;
67
68impl Api for ListDatabases {
69    type Error = crate::Error;
70    type Response = Vec<Database>;
71
72    fn name() -> ApiName {
73        ApiName::new("bonsaidb", "ListDatabases")
74    }
75}
76
77/// Lists available schemas.
78#[derive(Clone, Deserialize, Serialize, Debug)]
79pub struct ListAvailableSchemas;
80
81impl Api for ListAvailableSchemas {
82    type Error = crate::Error;
83    type Response = Vec<SchemaSummary>;
84
85    fn name() -> ApiName {
86        ApiName::new("bonsaidb", "ListAvailableSchemas")
87    }
88}
89
90/// Creates a user.
91#[derive(Clone, Deserialize, Serialize, Debug)]
92pub struct CreateUser {
93    /// The unique username of the user to create.
94    pub username: String,
95}
96
97impl Api for CreateUser {
98    type Error = crate::Error;
99    type Response = u64;
100
101    fn name() -> ApiName {
102        ApiName::new("bonsaidb", "CreateUser")
103    }
104}
105
106/// Deletes a user.
107#[derive(Clone, Deserialize, Serialize, Debug)]
108pub struct DeleteUser {
109    /// The unique primary key of the user to be deleted.
110    pub user: NamedReference<'static, u64>,
111}
112
113impl Api for DeleteUser {
114    type Error = crate::Error;
115    type Response = ();
116
117    fn name() -> ApiName {
118        ApiName::new("bonsaidb", "DeleteUser")
119    }
120}
121
122/// Set's a user's password.
123#[cfg(feature = "password-hashing")]
124#[derive(Clone, Deserialize, Serialize, Debug)]
125pub struct SetUserPassword {
126    /// The username or id of the user.
127    pub user: NamedReference<'static, u64>,
128    /// The user's new password.
129    pub password: crate::connection::SensitiveString,
130}
131
132#[cfg(feature = "password-hashing")]
133impl Api for SetUserPassword {
134    type Error = crate::Error;
135    type Response = ();
136
137    fn name() -> ApiName {
138        ApiName::new("bonsaidb", "SetUserPassword")
139    }
140}
141
142/// Authenticate the current connection.
143#[cfg(any(feature = "password-hashing", feature = "token-authentication"))]
144#[derive(Clone, Deserialize, Serialize, Debug)]
145pub struct Authenticate {
146    /// The method of authentication.
147    pub authentication: crate::connection::Authentication,
148}
149
150#[cfg(any(feature = "password-hashing", feature = "token-authentication"))]
151impl Api for Authenticate {
152    type Error = crate::Error;
153    type Response = Session;
154
155    fn name() -> ApiName {
156        ApiName::new("bonsaidb", "Authenticate")
157    }
158}
159
160/// Assume an identity.
161#[derive(Clone, Deserialize, Serialize, Debug)]
162pub struct AssumeIdentity(pub IdentityReference<'static>);
163
164impl Api for AssumeIdentity {
165    type Error = crate::Error;
166    type Response = Session;
167
168    fn name() -> ApiName {
169        ApiName::new("bonsaidb", "AssumeIdentity")
170    }
171}
172
173/// Logs out from a session.
174#[derive(Clone, Deserialize, Serialize, Debug)]
175pub struct LogOutSession(pub SessionId);
176
177impl Api for LogOutSession {
178    type Error = crate::Error;
179    type Response = ();
180
181    fn name() -> ApiName {
182        ApiName::new("bonsaidb", "LogOutSession")
183    }
184}
185
186/// Alter's a user's membership in a permission group.
187#[derive(Clone, Deserialize, Serialize, Debug)]
188pub struct AlterUserPermissionGroupMembership {
189    /// The username or id of the user.
190    pub user: NamedReference<'static, u64>,
191
192    /// The name or id of the group.
193    pub group: NamedReference<'static, u64>,
194
195    /// Whether the user should be in the group.
196    pub should_be_member: bool,
197}
198
199impl Api for AlterUserPermissionGroupMembership {
200    type Error = crate::Error;
201    type Response = ();
202
203    fn name() -> ApiName {
204        ApiName::new("bonsaidb", "AlterUserPermissionGroupMembership")
205    }
206}
207
208/// Alter's a user's role
209#[derive(Clone, Deserialize, Serialize, Debug)]
210pub struct AlterUserRoleMembership {
211    /// The username or id of the user.
212    pub user: NamedReference<'static, u64>,
213
214    /// The name or id of the role.
215    pub role: NamedReference<'static, u64>,
216
217    /// Whether the user should have the role.
218    pub should_be_member: bool,
219}
220
221impl Api for AlterUserRoleMembership {
222    type Error = crate::Error;
223    type Response = ();
224
225    fn name() -> ApiName {
226        ApiName::new("bonsaidb", "AlterUserRoleMembership")
227    }
228}
229
230/// Retrieve a single document.
231#[derive(Clone, Deserialize, Serialize, Debug)]
232pub struct Get {
233    /// The name of the database.
234    pub database: String,
235    /// The collection of the document.
236    pub collection: CollectionName,
237    /// The id of the document.
238    pub id: DocumentId,
239}
240
241impl Api for Get {
242    type Error = crate::Error;
243    type Response = Option<OwnedDocument>;
244
245    fn name() -> ApiName {
246        ApiName::new("bonsaidb", "Get")
247    }
248}
249
250/// Retrieve multiple documents.
251#[derive(Clone, Deserialize, Serialize, Debug)]
252pub struct GetMultiple {
253    /// The name of the database.
254    pub database: String,
255    /// The collection of the documents.
256    pub collection: CollectionName,
257    /// The ids of the documents.
258    pub ids: Vec<DocumentId>,
259}
260
261impl Api for GetMultiple {
262    type Error = crate::Error;
263    type Response = Vec<OwnedDocument>;
264
265    fn name() -> ApiName {
266        ApiName::new("bonsaidb", "GetMultiple")
267    }
268}
269
270/// Retrieve multiple documents.
271#[derive(Clone, Deserialize, Serialize, Debug)]
272pub struct List {
273    /// The name of the database.
274    pub database: String,
275    /// The collection of the documents.
276    pub collection: CollectionName,
277    /// The range of ids to list.
278    pub ids: Range<DocumentId>,
279    /// The order for the query into the collection.
280    pub order: Sort,
281    /// The maximum number of results to return.
282    pub limit: Option<u32>,
283}
284
285impl Api for List {
286    type Error = crate::Error;
287    type Response = Vec<OwnedDocument>;
288
289    fn name() -> ApiName {
290        ApiName::new("bonsaidb", "List")
291    }
292}
293
294/// Retrieve multiple document headers.
295#[derive(Clone, Deserialize, Serialize, Debug)]
296pub struct ListHeaders(pub List);
297
298impl Api for ListHeaders {
299    type Error = crate::Error;
300    type Response = Vec<Header>;
301
302    fn name() -> ApiName {
303        ApiName::new("bonsaidb", "ListHeaders")
304    }
305}
306
307/// Counts the number of documents in the specified range.
308#[derive(Clone, Deserialize, Serialize, Debug)]
309pub struct Count {
310    /// The name of the database.
311    pub database: String,
312    /// The collection of the documents.
313    pub collection: CollectionName,
314    /// The range of ids to count.
315    pub ids: Range<DocumentId>,
316}
317
318impl Api for Count {
319    type Error = crate::Error;
320    type Response = u64;
321
322    fn name() -> ApiName {
323        ApiName::new("bonsaidb", "Count")
324    }
325}
326
327/// Queries a view.
328#[derive(Clone, Deserialize, Serialize, Debug)]
329pub struct Query {
330    /// The name of the database.
331    pub database: String,
332    /// The name of the view.
333    pub view: ViewName,
334    /// The filter for the view.
335    pub key: Option<SerializedQueryKey>,
336    /// The order for the query into the view.
337    pub order: Sort,
338    /// The maximum number of results to return.
339    pub limit: Option<u32>,
340    /// The access policy for the query.
341    pub access_policy: AccessPolicy,
342}
343
344impl Api for Query {
345    type Error = crate::Error;
346    type Response = Vec<map::Serialized>;
347
348    fn name() -> ApiName {
349        ApiName::new("bonsaidb", "Query")
350    }
351}
352
353/// Queries a view with the associated documents.
354#[derive(Clone, Deserialize, Serialize, Debug)]
355pub struct QueryWithDocs(pub Query);
356
357impl Api for QueryWithDocs {
358    type Error = crate::Error;
359    type Response = MappedSerializedDocuments;
360
361    fn name() -> ApiName {
362        ApiName::new("bonsaidb", "QueryWithDocs")
363    }
364}
365
366/// Reduces a view.
367#[derive(Clone, Deserialize, Serialize, Debug)]
368pub struct Reduce {
369    /// The name of the database.
370    pub database: String,
371    /// The name of the view.
372    pub view: ViewName,
373    /// The filter for the view.
374    pub key: Option<SerializedQueryKey>,
375    /// The access policy for the query.
376    pub access_policy: AccessPolicy,
377}
378
379impl Api for Reduce {
380    type Error = crate::Error;
381    type Response = Bytes;
382
383    fn name() -> ApiName {
384        ApiName::new("bonsaidb", "Reduce")
385    }
386}
387
388/// Reduces a view, grouping the reduced values by key.
389#[derive(Clone, Deserialize, Serialize, Debug)]
390pub struct ReduceGrouped(pub Reduce);
391
392impl Api for ReduceGrouped {
393    type Error = crate::Error;
394    type Response = Vec<map::MappedSerializedValue>;
395
396    fn name() -> ApiName {
397        ApiName::new("bonsaidb", "ReduceGrouped")
398    }
399}
400
401/// Deletes the associated documents resulting from the view query.
402#[derive(Clone, Deserialize, Serialize, Debug)]
403pub struct DeleteDocs {
404    /// The name of the database.
405    pub database: String,
406    /// The name of the view.
407    pub view: ViewName,
408    /// The filter for the view.
409    pub key: Option<SerializedQueryKey>,
410    /// The access policy for the query.
411    pub access_policy: AccessPolicy,
412}
413
414impl Api for DeleteDocs {
415    type Error = crate::Error;
416    type Response = u64;
417
418    fn name() -> ApiName {
419        ApiName::new("bonsaidb", "DeleteDocs")
420    }
421}
422
423/// Applies a transaction.
424#[derive(Clone, Deserialize, Serialize, Debug)]
425pub struct ApplyTransaction {
426    /// The name of the database.
427    pub database: String,
428    /// The trasnaction to apply.
429    pub transaction: Transaction,
430}
431
432impl Api for ApplyTransaction {
433    type Error = crate::Error;
434    type Response = Vec<OperationResult>;
435
436    fn name() -> ApiName {
437        ApiName::new("bonsaidb", "ApplyTransaction")
438    }
439}
440
441/// Lists executed transactions.
442#[derive(Clone, Deserialize, Serialize, Debug)]
443pub struct ListExecutedTransactions {
444    /// The name of the database.
445    pub database: String,
446    /// The starting transaction id.
447    pub starting_id: Option<u64>,
448    /// The maximum number of results.
449    pub result_limit: Option<u32>,
450}
451
452impl Api for ListExecutedTransactions {
453    type Error = crate::Error;
454    type Response = Vec<Executed>;
455
456    fn name() -> ApiName {
457        ApiName::new("bonsaidb", "ListExecutedTransactions")
458    }
459}
460
461/// Queries the last transaction id.
462#[derive(Clone, Deserialize, Serialize, Debug)]
463pub struct LastTransactionId {
464    /// The name of the database.
465    pub database: String,
466}
467
468impl Api for LastTransactionId {
469    type Error = crate::Error;
470    type Response = Option<u64>;
471
472    fn name() -> ApiName {
473        ApiName::new("bonsaidb", "LastTransactionId")
474    }
475}
476
477/// Creates a `PubSub` [`Subscriber`](crate::pubsub::Subscriber)
478#[derive(Clone, Deserialize, Serialize, Debug)]
479pub struct CreateSubscriber {
480    /// The name of the database.
481    pub database: String,
482}
483
484impl Api for CreateSubscriber {
485    type Error = crate::Error;
486    type Response = u64;
487
488    fn name() -> ApiName {
489        ApiName::new("bonsaidb", "CreateSubscriber")
490    }
491}
492
493/// Publishes `payload` to all subscribers of `topic`.
494#[derive(Clone, Deserialize, Serialize, Debug)]
495pub struct Publish {
496    /// The name of the database.
497    pub database: String,
498    /// The topics to publish to.
499    pub topic: Bytes,
500    /// The payload to publish.
501    pub payload: Bytes,
502}
503
504impl Api for Publish {
505    type Error = crate::Error;
506    type Response = ();
507
508    fn name() -> ApiName {
509        ApiName::new("bonsaidb", "Publish")
510    }
511}
512
513/// Publishes `payload` to all subscribers of all `topics`.
514#[derive(Clone, Deserialize, Serialize, Debug)]
515pub struct PublishToAll {
516    /// The name of the database.
517    pub database: String,
518    /// The topics to publish to.
519    pub topics: Vec<Bytes>,
520    /// The payload to publish.
521    pub payload: Bytes,
522}
523
524impl Api for PublishToAll {
525    type Error = crate::Error;
526    type Response = ();
527
528    fn name() -> ApiName {
529        ApiName::new("bonsaidb", "PublishToAll")
530    }
531}
532
533/// Subscribes `subscriber_id` to messages for `topic`.
534#[derive(Clone, Deserialize, Serialize, Debug)]
535pub struct SubscribeTo {
536    /// The name of the database.
537    pub database: String,
538    /// The id of the [`Subscriber`](crate::pubsub::Subscriber).
539    pub subscriber_id: u64,
540    /// The topic to subscribe to.
541    pub topic: Bytes,
542}
543
544impl Api for SubscribeTo {
545    type Error = crate::Error;
546    type Response = ();
547
548    fn name() -> ApiName {
549        ApiName::new("bonsaidb", "SubscribeTo")
550    }
551}
552
553/// A PubSub message was received.
554#[derive(Clone, Deserialize, Serialize, Debug)]
555pub struct MessageReceived {
556    /// The ID of the subscriber receiving the message.
557    pub subscriber_id: u64,
558    /// The topic the payload was received on.
559    pub topic: Bytes,
560    /// The message payload.
561    pub payload: Bytes,
562}
563
564impl Api for MessageReceived {
565    type Error = crate::Error;
566    type Response = Self;
567
568    fn name() -> ApiName {
569        ApiName::new("bonsaidb", "MessageReceived")
570    }
571}
572
573/// Unsubscribes `subscriber_id` from messages for `topic`.
574#[derive(Clone, Deserialize, Serialize, Debug)]
575pub struct UnsubscribeFrom {
576    /// The name of the database.
577    pub database: String,
578    /// The id of the [`Subscriber`](crate::pubsub::Subscriber).
579    pub subscriber_id: u64,
580    /// The topic to unsubscribe from.
581    pub topic: Bytes,
582}
583
584impl Api for UnsubscribeFrom {
585    type Error = crate::Error;
586    type Response = ();
587
588    fn name() -> ApiName {
589        ApiName::new("bonsaidb", "UnsubscribeFrom")
590    }
591}
592
593/// Unregisters the subscriber.
594#[derive(Clone, Deserialize, Serialize, Debug)]
595pub struct UnregisterSubscriber {
596    /// The name of the database.
597    pub database: String,
598    /// The id of the [`Subscriber`](crate::pubsub::Subscriber).
599    pub subscriber_id: u64,
600}
601
602impl Api for UnregisterSubscriber {
603    type Error = crate::Error;
604    type Response = ();
605
606    fn name() -> ApiName {
607        ApiName::new("bonsaidb", "UnregisterSubscriber")
608    }
609}
610
611/// Excutes a key-value store operation.
612#[derive(Clone, Deserialize, Serialize, Debug)]
613pub struct ExecuteKeyOperation {
614    /// The name of the database.
615    pub database: String,
616    /// The operation to execute.
617    pub op: KeyOperation,
618}
619
620impl Api for ExecuteKeyOperation {
621    type Error = crate::Error;
622    type Response = Output;
623
624    fn name() -> ApiName {
625        ApiName::new("bonsaidb", "ExecuteKeyOperation")
626    }
627}
628
629/// Compacts the collection.
630#[derive(Clone, Deserialize, Serialize, Debug)]
631pub struct CompactCollection {
632    /// The name of the database.
633    pub database: String,
634    /// The name of the collection to compact.
635    pub name: CollectionName,
636}
637
638impl Api for CompactCollection {
639    type Error = crate::Error;
640    type Response = ();
641
642    fn name() -> ApiName {
643        ApiName::new("bonsaidb", "CompactCollection")
644    }
645}
646
647/// Compacts the key-value store.
648#[derive(Clone, Deserialize, Serialize, Debug)]
649pub struct CompactKeyValueStore {
650    /// The name of the database.
651    pub database: String,
652}
653
654impl Api for CompactKeyValueStore {
655    type Error = crate::Error;
656    type Response = ();
657
658    fn name() -> ApiName {
659        ApiName::new("bonsaidb", "CompactKeyValueStore")
660    }
661}
662
663/// Compacts the entire database.
664#[derive(Clone, Deserialize, Serialize, Debug)]
665pub struct Compact {
666    /// The name of the database.
667    pub database: String,
668}
669
670impl Api for Compact {
671    type Error = crate::Error;
672    type Response = ();
673
674    fn name() -> ApiName {
675        ApiName::new("bonsaidb", "Compact")
676    }
677}
678
679/// A networking error.
680#[derive(Clone, thiserror::Error, Debug, Serialize, Deserialize)]
681pub enum Error {
682    /// The server responded with a message that wasn't expected for the request
683    /// sent.
684    #[error("unexpected response: {0}")]
685    UnexpectedResponse(String),
686
687    /// A timeout occurred while connecting to the server.
688    #[error("connection timeout")]
689    ConnectTimeout,
690
691    /// A timeout occurred waiting on a request to complete.
692    #[error("request timeout")]
693    RequestTimeout,
694
695    /// The connection was interrupted.
696    #[error("unexpected disconnection")]
697    Disconnected,
698}