1
use arc_bytes::serde::Bytes;
2
use serde::{Deserialize, Serialize};
3

            
4
use crate::api::{Api, ApiName};
5
use crate::connection::{
6
    AccessPolicy, Database, IdentityReference, Range, SerializedQueryKey, Session, SessionId, Sort,
7
};
8
use crate::document::{DocumentId, Header, OwnedDocument};
9
use crate::keyvalue::{KeyOperation, Output};
10
use crate::schema::view::map::{self, MappedSerializedDocuments};
11
use crate::schema::{CollectionName, NamedReference, Qualified, SchemaSummary, ViewName};
12
use crate::transaction::{Executed, OperationResult, Transaction};
13

            
14
/// The current protocol version.
15
pub const CURRENT_PROTOCOL_VERSION: &str = "bonsai-pre-1";
16

            
17
/// A payload with an associated id.
18
4962606
#[derive(Clone, Deserialize, Serialize, Debug)]
19
pub 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
12468
#[derive(Clone, Deserialize, Serialize, Debug)]
32
pub 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

            
39
impl Api for CreateDatabase {
40
    type Error = crate::Error;
41
    type Response = ();
42

            
43
28600
    fn name() -> ApiName {
44
28600
        ApiName::new("bonsaidb", "CreateDatabase")
45
28600
    }
46
}
47

            
48
/// Deletes the database named `name`
49
9596
#[derive(Clone, Deserialize, Serialize, Debug)]
50
pub struct DeleteDatabase {
51
    /// The name of the database to delete.
52
    pub name: String,
53
}
54

            
55
impl Api for DeleteDatabase {
56
    type Error = crate::Error;
57
    type Response = ();
58

            
59
23920
    fn name() -> ApiName {
60
23920
        ApiName::new("bonsaidb", "DeleteDatabase")
61
23920
    }
62
}
63

            
64
/// Lists all databases.
65
119
#[derive(Clone, Deserialize, Serialize, Debug)]
66
pub struct ListDatabases;
67

            
68
impl Api for ListDatabases {
69
    type Error = crate::Error;
70
    type Response = Vec<Database>;
71

            
72
3960
    fn name() -> ApiName {
73
3960
        ApiName::new("bonsaidb", "ListDatabases")
74
3960
    }
75
}
76

            
77
/// Lists available schemas.
78
54
#[derive(Clone, Deserialize, Serialize, Debug)]
79
pub struct ListAvailableSchemas;
80

            
81
impl Api for ListAvailableSchemas {
82
    type Error = crate::Error;
83
    type Response = Vec<SchemaSummary>;
84

            
85
3800
    fn name() -> ApiName {
86
3800
        ApiName::new("bonsaidb", "ListAvailableSchemas")
87
3800
    }
88
}
89

            
90
/// Creates a user.
91
171
#[derive(Clone, Deserialize, Serialize, Debug)]
92
pub struct CreateUser {
93
    /// The unique username of the user to create.
94
    pub username: String,
95
}
96

            
97
impl Api for CreateUser {
98
    type Error = crate::Error;
99
    type Response = u64;
100

            
101
4040
    fn name() -> ApiName {
102
4040
        ApiName::new("bonsaidb", "CreateUser")
103
4040
    }
104
}
105

            
106
/// Deletes a user.
107
9
#[derive(Clone, Deserialize, Serialize, Debug)]
108
pub struct DeleteUser {
109
    /// The unique primary key of the user to be deleted.
110
    pub user: NamedReference<'static, u64>,
111
}
112

            
113
impl Api for DeleteUser {
114
    type Error = crate::Error;
115
    type Response = ();
116

            
117
3800
    fn name() -> ApiName {
118
3800
        ApiName::new("bonsaidb", "DeleteUser")
119
3800
    }
120
}
121

            
122
/// Set's a user's password.
123
#[cfg(feature = "password-hashing")]
124
#[derive(Clone, Deserialize, Serialize, Debug)]
125
pub 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")]
133
impl Api for SetUserPassword {
134
    type Error = crate::Error;
135
    type Response = ();
136

            
137
3680
    fn name() -> ApiName {
138
3680
        ApiName::new("bonsaidb", "SetUserPassword")
139
3680
    }
140
}
141

            
142
/// Authenticate the current connection.
143
#[cfg(any(feature = "password-hashing", feature = "token-authentication"))]
144
343
#[derive(Clone, Deserialize, Serialize, Debug)]
145
pub struct Authenticate {
146
    /// The method of authentication.
147
    pub authentication: crate::connection::Authentication,
148
}
149

            
150
#[cfg(any(feature = "password-hashing", feature = "token-authentication"))]
151
impl Api for Authenticate {
152
    type Error = crate::Error;
153
    type Response = Session;
154

            
155
4440
    fn name() -> ApiName {
156
4440
        ApiName::new("bonsaidb", "Authenticate")
157
4440
    }
158
}
159

            
160
/// Assume an identity.
161
34
#[derive(Clone, Deserialize, Serialize, Debug)]
162
pub struct AssumeIdentity(pub IdentityReference<'static>);
163

            
164
impl Api for AssumeIdentity {
165
    type Error = crate::Error;
166
    type Response = Session;
167

            
168
3760
    fn name() -> ApiName {
169
3760
        ApiName::new("bonsaidb", "AssumeIdentity")
170
3760
    }
171
}
172

            
173
/// Logs out from a session.
174
323
#[derive(Clone, Deserialize, Serialize, Debug)]
175
pub struct LogOutSession(pub SessionId);
176

            
177
impl Api for LogOutSession {
178
    type Error = crate::Error;
179
    type Response = ();
180

            
181
4440
    fn name() -> ApiName {
182
4440
        ApiName::new("bonsaidb", "LogOutSession")
183
4440
    }
184
}
185

            
186
/// Alter's a user's membership in a permission group.
187
84
#[derive(Clone, Deserialize, Serialize, Debug)]
188
pub 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

            
199
impl Api for AlterUserPermissionGroupMembership {
200
    type Error = crate::Error;
201
    type Response = ();
202

            
203
4160
    fn name() -> ApiName {
204
4160
        ApiName::new("bonsaidb", "AlterUserPermissionGroupMembership")
205
4160
    }
206
}
207

            
208
/// Alter's a user's role
209
84
#[derive(Clone, Deserialize, Serialize, Debug)]
210
pub 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

            
221
impl Api for AlterUserRoleMembership {
222
    type Error = crate::Error;
223
    type Response = ();
224

            
225
4160
    fn name() -> ApiName {
226
4160
        ApiName::new("bonsaidb", "AlterUserRoleMembership")
227
4160
    }
228
}
229

            
230
/// Retrieve a single document.
231
203666
#[derive(Clone, Deserialize, Serialize, Debug)]
232
pub 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

            
241
impl Api for Get {
242
    type Error = crate::Error;
243
    type Response = Option<OwnedDocument>;
244

            
245
374720
    fn name() -> ApiName {
246
374720
        ApiName::new("bonsaidb", "Get")
247
374720
    }
248
}
249

            
250
/// Retrieve multiple documents.
251
109082
#[derive(Clone, Deserialize, Serialize, Debug)]
252
pub 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

            
261
impl Api for GetMultiple {
262
    type Error = crate::Error;
263
    type Response = Vec<OwnedDocument>;
264

            
265
193680
    fn name() -> ApiName {
266
193680
        ApiName::new("bonsaidb", "GetMultiple")
267
193680
    }
268
}
269

            
270
/// Retrieve multiple documents.
271
405
#[derive(Clone, Deserialize, Serialize, Debug)]
272
pub 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

            
285
impl Api for List {
286
    type Error = crate::Error;
287
    type Response = Vec<OwnedDocument>;
288

            
289
4160
    fn name() -> ApiName {
290
4160
        ApiName::new("bonsaidb", "List")
291
4160
    }
292
}
293

            
294
/// Retrieve multiple document headers.
295
51
#[derive(Clone, Deserialize, Serialize, Debug)]
296
pub struct ListHeaders(pub List);
297

            
298
impl Api for ListHeaders {
299
    type Error = crate::Error;
300
    type Response = Vec<Header>;
301

            
302
3800
    fn name() -> ApiName {
303
3800
        ApiName::new("bonsaidb", "ListHeaders")
304
3800
    }
305
}
306

            
307
/// Counts the number of documents in the specified range.
308
138
#[derive(Clone, Deserialize, Serialize, Debug)]
309
pub 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

            
318
impl Api for Count {
319
    type Error = crate::Error;
320
    type Response = u64;
321

            
322
3920
    fn name() -> ApiName {
323
3920
        ApiName::new("bonsaidb", "Count")
324
3920
    }
325
}
326

            
327
/// Queries a view.
328
138894
#[derive(Clone, Deserialize, Serialize, Debug)]
329
pub 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

            
344
impl Api for Query {
345
    type Error = crate::Error;
346
    type Response = Vec<map::Serialized>;
347

            
348
197320
    fn name() -> ApiName {
349
197320
        ApiName::new("bonsaidb", "Query")
350
197320
    }
351
}
352

            
353
/// Queries a view with the associated documents.
354
#[derive(Clone, Deserialize, Serialize, Debug)]
355
pub struct QueryWithDocs(pub Query);
356

            
357
impl Api for QueryWithDocs {
358
    type Error = crate::Error;
359
    type Response = MappedSerializedDocuments;
360

            
361
3680
    fn name() -> ApiName {
362
3680
        ApiName::new("bonsaidb", "QueryWithDocs")
363
3680
    }
364
}
365

            
366
/// Reduces a view.
367
238548
#[derive(Clone, Deserialize, Serialize, Debug)]
368
pub 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

            
379
impl Api for Reduce {
380
    type Error = crate::Error;
381
    type Response = Bytes;
382

            
383
385440
    fn name() -> ApiName {
384
385440
        ApiName::new("bonsaidb", "Reduce")
385
385440
    }
386
}
387

            
388
/// Reduces a view, grouping the reduced values by key.
389
136
#[derive(Clone, Deserialize, Serialize, Debug)]
390
pub struct ReduceGrouped(pub Reduce);
391

            
392
impl Api for ReduceGrouped {
393
    type Error = crate::Error;
394
    type Response = Vec<map::MappedSerializedValue>;
395

            
396
4000
    fn name() -> ApiName {
397
4000
        ApiName::new("bonsaidb", "ReduceGrouped")
398
4000
    }
399
}
400

            
401
/// Deletes the associated documents resulting from the view query.
402
150
#[derive(Clone, Deserialize, Serialize, Debug)]
403
pub 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

            
414
impl Api for DeleteDocs {
415
    type Error = crate::Error;
416
    type Response = u64;
417

            
418
3920
    fn name() -> ApiName {
419
3920
        ApiName::new("bonsaidb", "DeleteDocs")
420
3920
    }
421
}
422

            
423
/// Applies a transaction.
424
223693
#[derive(Clone, Deserialize, Serialize, Debug)]
425
pub struct ApplyTransaction {
426
    /// The name of the database.
427
    pub database: String,
428
    /// The trasnaction to apply.
429
    pub transaction: Transaction,
430
}
431

            
432
impl Api for ApplyTransaction {
433
    type Error = crate::Error;
434
    type Response = Vec<OperationResult>;
435

            
436
475760
    fn name() -> ApiName {
437
475760
        ApiName::new("bonsaidb", "ApplyTransaction")
438
475760
    }
439
}
440

            
441
/// Lists executed transactions.
442
23864
#[derive(Clone, Deserialize, Serialize, Debug)]
443
pub 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

            
452
impl Api for ListExecutedTransactions {
453
    type Error = crate::Error;
454
    type Response = Vec<Executed>;
455

            
456
45840
    fn name() -> ApiName {
457
45840
        ApiName::new("bonsaidb", "ListExecutedTransactions")
458
45840
    }
459
}
460

            
461
/// Queries the last transaction id.
462
57
#[derive(Clone, Deserialize, Serialize, Debug)]
463
pub struct LastTransactionId {
464
    /// The name of the database.
465
    pub database: String,
466
}
467

            
468
impl Api for LastTransactionId {
469
    type Error = crate::Error;
470
    type Response = Option<u64>;
471

            
472
3800
    fn name() -> ApiName {
473
3800
        ApiName::new("bonsaidb", "LastTransactionId")
474
3800
    }
475
}
476

            
477
/// Creates a `PubSub` [`Subscriber`](crate::pubsub::Subscriber)
478
456
#[derive(Clone, Deserialize, Serialize, Debug)]
479
pub struct CreateSubscriber {
480
    /// The name of the database.
481
    pub database: String,
482
}
483

            
484
impl Api for CreateSubscriber {
485
    type Error = crate::Error;
486
    type Response = u64;
487

            
488
4640
    fn name() -> ApiName {
489
4640
        ApiName::new("bonsaidb", "CreateSubscriber")
490
4640
    }
491
}
492

            
493
/// Publishes `payload` to all subscribers of `topic`.
494
690
#[derive(Clone, Deserialize, Serialize, Debug)]
495
pub 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

            
504
impl Api for Publish {
505
    type Error = crate::Error;
506
    type Response = ();
507

            
508
4880
    fn name() -> ApiName {
509
4880
        ApiName::new("bonsaidb", "Publish")
510
4880
    }
511
}
512

            
513
/// Publishes `payload` to all subscribers of all `topics`.
514
21
#[derive(Clone, Deserialize, Serialize, Debug)]
515
pub 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

            
524
impl Api for PublishToAll {
525
    type Error = crate::Error;
526
    type Response = ();
527

            
528
3800
    fn name() -> ApiName {
529
3800
        ApiName::new("bonsaidb", "PublishToAll")
530
3800
    }
531
}
532

            
533
/// Subscribes `subscriber_id` to messages for `topic`.
534
897
#[derive(Clone, Deserialize, Serialize, Debug)]
535
pub 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

            
544
impl Api for SubscribeTo {
545
    type Error = crate::Error;
546
    type Response = ();
547

            
548
5240
    fn name() -> ApiName {
549
5240
        ApiName::new("bonsaidb", "SubscribeTo")
550
5240
    }
551
}
552

            
553
/// A PubSub message was received.
554
5355
#[derive(Clone, Deserialize, Serialize, Debug)]
555
pub 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

            
564
impl Api for MessageReceived {
565
    type Error = crate::Error;
566
    type Response = Self;
567

            
568
8720
    fn name() -> ApiName {
569
8720
        ApiName::new("bonsaidb", "MessageReceived")
570
8720
    }
571
}
572

            
573
/// Unsubscribes `subscriber_id` from messages for `topic`.
574
69
#[derive(Clone, Deserialize, Serialize, Debug)]
575
pub 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

            
584
impl Api for UnsubscribeFrom {
585
    type Error = crate::Error;
586
    type Response = ();
587

            
588
3800
    fn name() -> ApiName {
589
3800
        ApiName::new("bonsaidb", "UnsubscribeFrom")
590
3800
    }
591
}
592

            
593
/// Unregisters the subscriber.
594
210
#[derive(Clone, Deserialize, Serialize, Debug)]
595
pub 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

            
602
impl Api for UnregisterSubscriber {
603
    type Error = crate::Error;
604
    type Response = ();
605

            
606
4080
    fn name() -> ApiName {
607
4080
        ApiName::new("bonsaidb", "UnregisterSubscriber")
608
4080
    }
609
}
610

            
611
/// Excutes a key-value store operation.
612
636653
#[derive(Clone, Deserialize, Serialize, Debug)]
613
pub struct ExecuteKeyOperation {
614
    /// The name of the database.
615
    pub database: String,
616
    /// The operation to execute.
617
    pub op: KeyOperation,
618
}
619

            
620
impl Api for ExecuteKeyOperation {
621
    type Error = crate::Error;
622
    type Response = Output;
623

            
624
1216600
    fn name() -> ApiName {
625
1216600
        ApiName::new("bonsaidb", "ExecuteKeyOperation")
626
1216600
    }
627
}
628

            
629
/// Compacts the collection.
630
63
#[derive(Clone, Deserialize, Serialize, Debug)]
631
pub 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

            
638
impl Api for CompactCollection {
639
    type Error = crate::Error;
640
    type Response = ();
641

            
642
3800
    fn name() -> ApiName {
643
3800
        ApiName::new("bonsaidb", "CompactCollection")
644
3800
    }
645
}
646

            
647
/// Compacts the key-value store.
648
57
#[derive(Clone, Deserialize, Serialize, Debug)]
649
pub struct CompactKeyValueStore {
650
    /// The name of the database.
651
    pub database: String,
652
}
653

            
654
impl Api for CompactKeyValueStore {
655
    type Error = crate::Error;
656
    type Response = ();
657

            
658
3800
    fn name() -> ApiName {
659
3800
        ApiName::new("bonsaidb", "CompactKeyValueStore")
660
3800
    }
661
}
662

            
663
/// Compacts the entire database.
664
57
#[derive(Clone, Deserialize, Serialize, Debug)]
665
pub struct Compact {
666
    /// The name of the database.
667
    pub database: String,
668
}
669

            
670
impl Api for Compact {
671
    type Error = crate::Error;
672
    type Response = ();
673

            
674
3800
    fn name() -> ApiName {
675
3800
        ApiName::new("bonsaidb", "Compact")
676
3800
    }
677
}
678

            
679
/// A networking error.
680
1720
#[derive(Clone, thiserror::Error, Debug, Serialize, Deserialize)]
681
pub 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
}