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

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

            
20
/// The current protocol version.
21
pub const CURRENT_PROTOCOL_VERSION: &str = "bonsai/pre/0";
22

            
23
/// A payload with an associated id.
24
5369419
#[derive(Clone, Deserialize, Serialize, Debug)]
25
pub struct Payload {
26
    /// The authentication session id for this payload.
27
    pub session_id: Option<SessionId>,
28
    /// The unique id for this payload.
29
    pub id: Option<u32>,
30
    /// The unique name of the api
31
    pub name: ApiName,
32
    /// The payload
33
    pub value: Result<Bytes, crate::Error>,
34
}
35

            
36
/// Creates a database.
37
13444
#[derive(Clone, Deserialize, Serialize, Debug)]
38
pub struct CreateDatabase {
39
    /// The database to create.
40
    pub database: Database,
41
    /// Only attempts to create the database if it doesn't already exist.
42
    pub only_if_needed: bool,
43
}
44

            
45
impl Api for CreateDatabase {
46
    type Response = ();
47
    type Error = crate::Error;
48

            
49
21390
    fn name() -> ApiName {
50
21390
        ApiName::new("bonsaidb", "CreateDatabase")
51
21390
    }
52
}
53

            
54
/// Deletes the database named `name`
55
10608
#[derive(Clone, Deserialize, Serialize, Debug)]
56
pub struct DeleteDatabase {
57
    /// The name of the database to delete.
58
    pub name: String,
59
}
60

            
61
impl Api for DeleteDatabase {
62
    type Response = ();
63
    type Error = crate::Error;
64

            
65
18228
    fn name() -> ApiName {
66
18228
        ApiName::new("bonsaidb", "DeleteDatabase")
67
18228
    }
68
}
69

            
70
/// Lists all databases.
71
60
#[derive(Clone, Deserialize, Serialize, Debug)]
72
pub struct ListDatabases;
73

            
74
impl Api for ListDatabases {
75
    type Response = Vec<Database>;
76
    type Error = crate::Error;
77

            
78
2635
    fn name() -> ApiName {
79
2635
        ApiName::new("bonsaidb", "ListDatabases")
80
2635
    }
81
}
82

            
83
/// Lists available schemas.
84
60
#[derive(Clone, Deserialize, Serialize, Debug)]
85
pub struct ListAvailableSchemas;
86

            
87
impl Api for ListAvailableSchemas {
88
    type Response = Vec<SchemaName>;
89
    type Error = crate::Error;
90

            
91
2635
    fn name() -> ApiName {
92
2635
        ApiName::new("bonsaidb", "ListAvailableSchemas")
93
2635
    }
94
}
95

            
96
/// Creates a user.
97
105
#[derive(Clone, Deserialize, Serialize, Debug)]
98
pub struct CreateUser {
99
    /// The unique username of the user to create.
100
    pub username: String,
101
}
102

            
103
impl Api for CreateUser {
104
    type Response = u64;
105
    type Error = crate::Error;
106

            
107
2697
    fn name() -> ApiName {
108
2697
        ApiName::new("bonsaidb", "CreateUser")
109
2697
    }
110
}
111

            
112
/// Deletes a user.
113
9
#[derive(Clone, Deserialize, Serialize, Debug)]
114
pub struct DeleteUser {
115
    /// The unique primary key of the user to be deleted.
116
    pub user: NamedReference<'static, u64>,
117
}
118

            
119
impl Api for DeleteUser {
120
    type Response = ();
121
    type Error = crate::Error;
122

            
123
2635
    fn name() -> ApiName {
124
2635
        ApiName::new("bonsaidb", "DeleteUser")
125
2635
    }
126
}
127

            
128
/// Set's a user's password.
129
#[cfg(feature = "password-hashing")]
130
#[derive(Clone, Deserialize, Serialize, Debug)]
131
pub struct SetUserPassword {
132
    /// The username or id of the user.
133
    pub user: NamedReference<'static, u64>,
134
    /// The user's new password.
135
    pub password: crate::connection::SensitiveString,
136
}
137

            
138
#[cfg(feature = "password-hashing")]
139
impl Api for SetUserPassword {
140
    type Response = ();
141
    type Error = crate::Error;
142

            
143
2542
    fn name() -> ApiName {
144
2542
        ApiName::new("bonsaidb", "SetUserPassword")
145
2542
    }
146
}
147

            
148
/// Authenticate as a user.
149
#[cfg(feature = "password-hashing")]
150
25
#[derive(Clone, Deserialize, Serialize, Debug)]
151
pub struct Authenticate {
152
    /// The username or id of the user.
153
    pub user: NamedReference<'static, u64>,
154
    /// The method of authentication.
155
    pub authentication: crate::connection::Authentication,
156
}
157

            
158
#[cfg(feature = "password-hashing")]
159
impl Api for Authenticate {
160
    type Response = Session;
161
    type Error = crate::Error;
162

            
163
2697
    fn name() -> ApiName {
164
2697
        ApiName::new("bonsaidb", "Authenticate")
165
2697
    }
166
}
167

            
168
/// Assume an identity.
169
38
#[derive(Clone, Deserialize, Serialize, Debug)]
170
pub struct AssumeIdentity(pub IdentityReference<'static>);
171

            
172
impl Api for AssumeIdentity {
173
    type Response = Session;
174
    type Error = crate::Error;
175

            
176
2604
    fn name() -> ApiName {
177
2604
        ApiName::new("bonsaidb", "AssumeIdentity")
178
2604
    }
179
}
180

            
181
/// Logs out from a session.
182
133
#[derive(Clone, Deserialize, Serialize, Debug)]
183
pub struct LogOutSession(pub SessionId);
184

            
185
impl Api for LogOutSession {
186
    type Response = ();
187
    type Error = crate::Error;
188

            
189
2759
    fn name() -> ApiName {
190
2759
        ApiName::new("bonsaidb", "LogOutSession")
191
2759
    }
192
}
193

            
194
/// Alter's a user's membership in a permission group.
195
84
#[derive(Clone, Deserialize, Serialize, Debug)]
196
pub struct AlterUserPermissionGroupMembership {
197
    /// The username or id of the user.
198
    pub user: NamedReference<'static, u64>,
199

            
200
    /// The name or id of the group.
201
    pub group: NamedReference<'static, u64>,
202

            
203
    /// Whether the user should be in the group.
204
    pub should_be_member: bool,
205
}
206

            
207
impl Api for AlterUserPermissionGroupMembership {
208
    type Response = ();
209
    type Error = crate::Error;
210

            
211
2914
    fn name() -> ApiName {
212
2914
        ApiName::new("bonsaidb", "AlterUserPermissionGroupMembership")
213
2914
    }
214
}
215

            
216
/// Alter's a user's role
217
84
#[derive(Clone, Deserialize, Serialize, Debug)]
218
pub struct AlterUserRoleMembership {
219
    /// The username or id of the user.
220
    pub user: NamedReference<'static, u64>,
221

            
222
    /// The name or id of the role.
223
    pub role: NamedReference<'static, u64>,
224

            
225
    /// Whether the user should have the role.
226
    pub should_be_member: bool,
227
}
228

            
229
impl Api for AlterUserRoleMembership {
230
    type Response = ();
231
    type Error = crate::Error;
232

            
233
2914
    fn name() -> ApiName {
234
2914
        ApiName::new("bonsaidb", "AlterUserRoleMembership")
235
2914
    }
236
}
237

            
238
/// Retrieve a single document.
239
208986
#[derive(Clone, Deserialize, Serialize, Debug)]
240
pub struct Get {
241
    /// The name of the database.
242
    pub database: String,
243
    /// The collection of the document.
244
    pub collection: CollectionName,
245
    /// The id of the document.
246
    pub id: DocumentId,
247
}
248

            
249
impl Api for Get {
250
    type Response = Option<OwnedDocument>;
251
    type Error = crate::Error;
252

            
253
272862
    fn name() -> ApiName {
254
272862
        ApiName::new("bonsaidb", "Get")
255
272862
    }
256
}
257

            
258
/// Retrieve multiple documents.
259
109882
#[derive(Clone, Deserialize, Serialize, Debug)]
260
pub struct GetMultiple {
261
    /// The name of the database.
262
    pub database: String,
263
    /// The collection of the documents.
264
    pub collection: CollectionName,
265
    /// The ids of the documents.
266
    pub ids: Vec<DocumentId>,
267
}
268

            
269
impl Api for GetMultiple {
270
    type Response = Vec<OwnedDocument>;
271
    type Error = crate::Error;
272

            
273
139004
    fn name() -> ApiName {
274
139004
        ApiName::new("bonsaidb", "GetMultiple")
275
139004
    }
276
}
277

            
278
/// Retrieve multiple documents.
279
435
#[derive(Clone, Deserialize, Serialize, Debug)]
280
pub struct List {
281
    /// The name of the database.
282
    pub database: String,
283
    /// The collection of the documents.
284
    pub collection: CollectionName,
285
    /// The range of ids to list.
286
    pub ids: Range<DocumentId>,
287
    /// The order for the query into the collection.
288
    pub order: Sort,
289
    /// The maximum number of results to return.
290
    pub limit: Option<u32>,
291
}
292

            
293
impl Api for List {
294
    type Response = Vec<OwnedDocument>;
295
    type Error = crate::Error;
296

            
297
2914
    fn name() -> ApiName {
298
2914
        ApiName::new("bonsaidb", "List")
299
2914
    }
300
}
301

            
302
/// Retrieve multiple document headers.
303
57
#[derive(Clone, Deserialize, Serialize, Debug)]
304
pub struct ListHeaders(pub List);
305

            
306
impl Api for ListHeaders {
307
    type Response = Vec<Header>;
308
    type Error = crate::Error;
309

            
310
2635
    fn name() -> ApiName {
311
2635
        ApiName::new("bonsaidb", "ListHeaders")
312
2635
    }
313
}
314

            
315
/// Counts the number of documents in the specified range.
316
150
#[derive(Clone, Deserialize, Serialize, Debug)]
317
pub struct Count {
318
    /// The name of the database.
319
    pub database: String,
320
    /// The collection of the documents.
321
    pub collection: CollectionName,
322
    /// The range of ids to count.
323
    pub ids: Range<DocumentId>,
324
}
325

            
326
impl Api for Count {
327
    type Response = u64;
328
    type Error = crate::Error;
329

            
330
2728
    fn name() -> ApiName {
331
2728
        ApiName::new("bonsaidb", "Count")
332
2728
    }
333
}
334

            
335
/// Queries a view.
336
137446
#[derive(Clone, Deserialize, Serialize, Debug)]
337
pub struct Query {
338
    /// The name of the database.
339
    pub database: String,
340
    /// The name of the view.
341
    pub view: ViewName,
342
    /// The filter for the view.
343
    pub key: Option<QueryKey<Bytes>>,
344
    /// The order for the query into the view.
345
    pub order: Sort,
346
    /// The maximum number of results to return.
347
    pub limit: Option<u32>,
348
    /// The access policy for the query.
349
    pub access_policy: AccessPolicy,
350
}
351

            
352
impl Api for Query {
353
    type Response = Vec<map::Serialized>;
354
    type Error = crate::Error;
355

            
356
141236
    fn name() -> ApiName {
357
141236
        ApiName::new("bonsaidb", "Query")
358
141236
    }
359
}
360

            
361
/// Queries a view with the associated documents.
362
#[derive(Clone, Deserialize, Serialize, Debug)]
363
pub struct QueryWithDocs(pub Query);
364

            
365
impl Api for QueryWithDocs {
366
    type Response = MappedSerializedDocuments;
367
    type Error = crate::Error;
368

            
369
2542
    fn name() -> ApiName {
370
2542
        ApiName::new("bonsaidb", "QueryWithDocs")
371
2542
    }
372
}
373

            
374
/// Reduces a view.
375
237438
#[derive(Clone, Deserialize, Serialize, Debug)]
376
pub struct Reduce {
377
    /// The name of the database.
378
    pub database: String,
379
    /// The name of the view.
380
    pub view: ViewName,
381
    /// The filter for the view.
382
    pub key: Option<QueryKey<Bytes>>,
383
    /// The access policy for the query.
384
    pub access_policy: AccessPolicy,
385
}
386

            
387
impl Api for Reduce {
388
    type Response = Bytes;
389
    type Error = crate::Error;
390

            
391
275156
    fn name() -> ApiName {
392
275156
        ApiName::new("bonsaidb", "Reduce")
393
275156
    }
394
}
395

            
396
/// Reduces a view, grouping the reduced values by key.
397
152
#[derive(Clone, Deserialize, Serialize, Debug)]
398
pub struct ReduceGrouped(pub Reduce);
399

            
400
impl Api for ReduceGrouped {
401
    type Response = Vec<map::MappedSerializedValue>;
402
    type Error = crate::Error;
403

            
404
2790
    fn name() -> ApiName {
405
2790
        ApiName::new("bonsaidb", "ReduceGrouped")
406
2790
    }
407
}
408

            
409
/// Deletes the associated documents resulting from the view query.
410
162
#[derive(Clone, Deserialize, Serialize, Debug)]
411
pub struct DeleteDocs {
412
    /// The name of the database.
413
    pub database: String,
414
    /// The name of the view.
415
    pub view: ViewName,
416
    /// The filter for the view.
417
    pub key: Option<QueryKey<Bytes>>,
418
    /// The access policy for the query.
419
    pub access_policy: AccessPolicy,
420
}
421

            
422
impl Api for DeleteDocs {
423
    type Response = u64;
424
    type Error = crate::Error;
425

            
426
2728
    fn name() -> ApiName {
427
2728
        ApiName::new("bonsaidb", "DeleteDocs")
428
2728
    }
429
}
430

            
431
/// Applies a transaction.
432
241732
#[derive(Clone, Deserialize, Serialize, Debug)]
433
pub struct ApplyTransaction {
434
    /// The name of the database.
435
    pub database: String,
436
    /// The trasnaction to apply.
437
    pub transaction: Transaction,
438
}
439

            
440
impl Api for ApplyTransaction {
441
    type Response = Vec<OperationResult>;
442
    type Error = crate::Error;
443

            
444
360189
    fn name() -> ApiName {
445
360189
        ApiName::new("bonsaidb", "ApplyTransaction")
446
360189
    }
447
}
448

            
449
/// Lists executed transactions.
450
25972
#[derive(Clone, Deserialize, Serialize, Debug)]
451
pub struct ListExecutedTransactions {
452
    /// The name of the database.
453
    pub database: String,
454
    /// The starting transaction id.
455
    pub starting_id: Option<u64>,
456
    /// The maximum number of results.
457
    pub result_limit: Option<u32>,
458
}
459

            
460
impl Api for ListExecutedTransactions {
461
    type Response = Vec<Executed>;
462
    type Error = crate::Error;
463

            
464
35216
    fn name() -> ApiName {
465
35216
        ApiName::new("bonsaidb", "ListExecutedTransactions")
466
35216
    }
467
}
468

            
469
/// Queries the last transaction id.
470
63
#[derive(Clone, Deserialize, Serialize, Debug)]
471
pub struct LastTransactionId {
472
    /// The name of the database.
473
    pub database: String,
474
}
475

            
476
impl Api for LastTransactionId {
477
    type Response = Option<u64>;
478
    type Error = crate::Error;
479

            
480
2635
    fn name() -> ApiName {
481
2635
        ApiName::new("bonsaidb", "LastTransactionId")
482
2635
    }
483
}
484

            
485
/// Creates a `PubSub` [`Subscriber`](crate::pubsub::Subscriber)
486
504
#[derive(Clone, Deserialize, Serialize, Debug)]
487
pub struct CreateSubscriber {
488
    /// The name of the database.
489
    pub database: String,
490
}
491

            
492
impl Api for CreateSubscriber {
493
    type Response = u64;
494
    type Error = crate::Error;
495

            
496
3286
    fn name() -> ApiName {
497
3286
        ApiName::new("bonsaidb", "CreateSubscriber")
498
3286
    }
499
}
500

            
501
/// Publishes `payload` to all subscribers of `topic`.
502
750
#[derive(Clone, Deserialize, Serialize, Debug)]
503
pub struct Publish {
504
    /// The name of the database.
505
    pub database: String,
506
    /// The topics to publish to.
507
    pub topic: Bytes,
508
    /// The payload to publish.
509
    pub payload: Bytes,
510
}
511

            
512
impl Api for Publish {
513
    type Response = ();
514
    type Error = crate::Error;
515

            
516
3472
    fn name() -> ApiName {
517
3472
        ApiName::new("bonsaidb", "Publish")
518
3472
    }
519
}
520

            
521
/// Publishes `payload` to all subscribers of all `topics`.
522
21
#[derive(Clone, Deserialize, Serialize, Debug)]
523
pub struct PublishToAll {
524
    /// The name of the database.
525
    pub database: String,
526
    /// The topics to publish to.
527
    pub topics: Vec<Bytes>,
528
    /// The payload to publish.
529
    pub payload: Bytes,
530
}
531

            
532
impl Api for PublishToAll {
533
    type Response = ();
534
    type Error = crate::Error;
535

            
536
2635
    fn name() -> ApiName {
537
2635
        ApiName::new("bonsaidb", "PublishToAll")
538
2635
    }
539
}
540

            
541
/// Subscribes `subscriber_id` to messages for `topic`.
542
975
#[derive(Clone, Deserialize, Serialize, Debug)]
543
pub struct SubscribeTo {
544
    /// The name of the database.
545
    pub database: String,
546
    /// The id of the [`Subscriber`](crate::pubsub::Subscriber).
547
    pub subscriber_id: u64,
548
    /// The topic to subscribe to.
549
    pub topic: Bytes,
550
}
551

            
552
impl Api for SubscribeTo {
553
    type Response = ();
554
    type Error = crate::Error;
555

            
556
3751
    fn name() -> ApiName {
557
3751
        ApiName::new("bonsaidb", "SubscribeTo")
558
3751
    }
559
}
560

            
561
/// A PubSub message was received.
562
5985
#[derive(Clone, Deserialize, Serialize, Debug)]
563
pub struct MessageReceived {
564
    /// The ID of the subscriber receiving the message.
565
    pub subscriber_id: u64,
566
    /// The topic the payload was received on.
567
    pub topic: Bytes,
568
    /// The message payload.
569
    pub payload: Bytes,
570
}
571

            
572
impl Api for MessageReceived {
573
    type Response = Self;
574
    type Error = crate::Error;
575

            
576
6014
    fn name() -> ApiName {
577
6014
        ApiName::new("bonsaidb", "MessageReceived")
578
6014
    }
579
}
580

            
581
/// Unsubscribes `subscriber_id` from messages for `topic`.
582
75
#[derive(Clone, Deserialize, Serialize, Debug)]
583
pub struct UnsubscribeFrom {
584
    /// The name of the database.
585
    pub database: String,
586
    /// The id of the [`Subscriber`](crate::pubsub::Subscriber).
587
    pub subscriber_id: u64,
588
    /// The topic to unsubscribe from.
589
    pub topic: Bytes,
590
}
591

            
592
impl Api for UnsubscribeFrom {
593
    type Response = ();
594
    type Error = crate::Error;
595

            
596
2635
    fn name() -> ApiName {
597
2635
        ApiName::new("bonsaidb", "UnsubscribeFrom")
598
2635
    }
599
}
600

            
601
/// Unregisters the subscriber.
602
230
#[derive(Clone, Deserialize, Serialize, Debug)]
603
pub struct UnregisterSubscriber {
604
    /// The name of the database.
605
    pub database: String,
606
    /// The id of the [`Subscriber`](crate::pubsub::Subscriber).
607
    pub subscriber_id: u64,
608
}
609

            
610
impl Api for UnregisterSubscriber {
611
    type Response = ();
612
    type Error = crate::Error;
613

            
614
2852
    fn name() -> ApiName {
615
2852
        ApiName::new("bonsaidb", "UnregisterSubscriber")
616
2852
    }
617
}
618

            
619
/// Excutes a key-value store operation.
620
697299
#[derive(Clone, Deserialize, Serialize, Debug)]
621
pub struct ExecuteKeyOperation {
622
    /// The name of the database.
623
    pub database: String,
624
    /// The operation to execute.
625
    pub op: KeyOperation,
626
}
627

            
628
impl Api for ExecuteKeyOperation {
629
    type Response = Output;
630
    type Error = crate::Error;
631

            
632
942555
    fn name() -> ApiName {
633
942555
        ApiName::new("bonsaidb", "ExecuteKeyOperation")
634
942555
    }
635
}
636

            
637
/// Compacts the collection.
638
69
#[derive(Clone, Deserialize, Serialize, Debug)]
639
pub struct CompactCollection {
640
    /// The name of the database.
641
    pub database: String,
642
    /// The name of the collection to compact.
643
    pub name: CollectionName,
644
}
645

            
646
impl Api for CompactCollection {
647
    type Response = ();
648
    type Error = crate::Error;
649

            
650
2635
    fn name() -> ApiName {
651
2635
        ApiName::new("bonsaidb", "CompactCollection")
652
2635
    }
653
}
654

            
655
/// Compacts the key-value store.
656
63
#[derive(Clone, Deserialize, Serialize, Debug)]
657
pub struct CompactKeyValueStore {
658
    /// The name of the database.
659
    pub database: String,
660
}
661

            
662
impl Api for CompactKeyValueStore {
663
    type Response = ();
664
    type Error = crate::Error;
665

            
666
2635
    fn name() -> ApiName {
667
2635
        ApiName::new("bonsaidb", "CompactKeyValueStore")
668
2635
    }
669
}
670

            
671
/// Compacts the entire database.
672
63
#[derive(Clone, Deserialize, Serialize, Debug)]
673
pub struct Compact {
674
    /// The name of the database.
675
    pub database: String,
676
}
677

            
678
impl Api for Compact {
679
    type Response = ();
680
    type Error = crate::Error;
681

            
682
2635
    fn name() -> ApiName {
683
2635
        ApiName::new("bonsaidb", "Compact")
684
2635
    }
685
}
686

            
687
/// A networking error.
688
#[derive(Clone, thiserror::Error, Debug, Serialize, Deserialize)]
689
pub enum Error {
690
    /// The server responded with a message that wasn't expected for the request
691
    /// sent.
692
    #[error("unexpected response: {0}")]
693
    UnexpectedResponse(String),
694

            
695
    /// The connection was interrupted.
696
    #[error("unexpected disconnection")]
697
    Disconnected,
698
}