couchbase-core 1.0.1

Couchbase SDK core networking and protocol implementation, not intended for direct use
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
/*
 *
 *  * Copyright (c) 2025 Couchbase, Inc.
 *  *
 *  * Licensed under the Apache License, Version 2.0 (the "License");
 *  * you may not use this file except in compliance with the License.
 *  * You may obtain a copy of the License at
 *  *
 *  *    http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  * Unless required by applicable law or agreed to in writing, software
 *  * distributed under the License is distributed on an "AS IS" BASIS,
 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  * See the License for the specific language governing permissions and
 *  * limitations under the License.
 *
 */

use crate::mgmtx::bucket_settings_json::BucketSettingsJson;
use std::fmt::Display;
use std::string::ToString;
use std::time::Duration;
use url::form_urlencoded::Serializer;

#[derive(Default, Debug, Clone, PartialOrd, PartialEq, Eq)]
pub struct BucketSettings {
    pub flush_enabled: Option<bool>,
    pub ram_quota_mb: Option<u64>,
    pub replica_number: Option<u32>,
    pub eviction_policy: Option<EvictionPolicyType>,
    pub max_ttl: Option<Duration>,
    pub compression_mode: Option<CompressionMode>,
    pub durability_min_level: Option<DurabilityLevel>,
    pub history_retention_collection_default: Option<bool>,
    pub history_retention_bytes: Option<u64>,
    pub history_retention_seconds: Option<u32>,
    pub conflict_resolution_type: Option<ConflictResolutionType>,
    pub replica_index: Option<bool>,
    pub bucket_type: Option<BucketType>,
    pub storage_backend: Option<StorageBackend>,
    pub num_vbuckets: Option<u16>,
}

impl BucketSettings {
    pub fn flush_enabled(mut self, flush_enabled: bool) -> Self {
        self.flush_enabled = Some(flush_enabled);
        self
    }

    pub fn ram_quota_mb(mut self, ram_quota_mb: u64) -> Self {
        self.ram_quota_mb = Some(ram_quota_mb);
        self
    }

    pub fn replica_number(mut self, replica_number: u32) -> Self {
        self.replica_number = Some(replica_number);
        self
    }

    pub fn eviction_policy(mut self, eviction_policy: impl Into<EvictionPolicyType>) -> Self {
        self.eviction_policy = Some(eviction_policy.into());
        self
    }

    pub fn max_ttl(mut self, max_ttl: Duration) -> Self {
        self.max_ttl = Some(max_ttl);
        self
    }

    pub fn compression_mode(mut self, compression_mode: impl Into<CompressionMode>) -> Self {
        self.compression_mode = Some(compression_mode.into());
        self
    }

    pub fn durability_min_level(
        mut self,
        durability_min_level: impl Into<DurabilityLevel>,
    ) -> Self {
        self.durability_min_level = Some(durability_min_level.into());
        self
    }

    pub fn history_retention_collection_default(
        mut self,
        history_retention_collection_default: bool,
    ) -> Self {
        self.history_retention_collection_default = Some(history_retention_collection_default);
        self
    }

    pub fn history_retention_bytes(mut self, history_retention_bytes: u64) -> Self {
        self.history_retention_bytes = Some(history_retention_bytes);
        self
    }

    pub fn history_retention_seconds(mut self, history_retention_seconds: u32) -> Self {
        self.history_retention_seconds = Some(history_retention_seconds);
        self
    }

    pub fn conflict_resolution_type(
        mut self,
        conflict_resolution_type: impl Into<ConflictResolutionType>,
    ) -> Self {
        self.conflict_resolution_type = Some(conflict_resolution_type.into());
        self
    }

    pub fn replica_index(mut self, replica_index: bool) -> Self {
        self.replica_index = Some(replica_index);
        self
    }

    pub fn bucket_type(mut self, bucket_type: impl Into<BucketType>) -> Self {
        self.bucket_type = Some(bucket_type.into());
        self
    }

    pub fn storage_backend(mut self, storage_backend: impl Into<StorageBackend>) -> Self {
        self.storage_backend = Some(storage_backend.into());
        self
    }

    pub fn num_vbuckets(mut self, num_vbuckets: u16) -> Self {
        self.num_vbuckets = Some(num_vbuckets);
        self
    }
}

#[derive(Debug, Clone, PartialOrd, PartialEq)]
pub struct BucketDef {
    pub name: String,
    pub bucket_settings: BucketSettings,
}

impl BucketDef {
    pub fn new(name: String, bucket_settings: BucketSettings) -> Self {
        Self {
            name,
            bucket_settings,
        }
    }
}

impl From<BucketSettingsJson> for BucketDef {
    fn from(settings: BucketSettingsJson) -> Self {
        Self {
            name: settings.name,
            bucket_settings: BucketSettings {
                flush_enabled: settings.controllers.as_ref().map(|c| {
                    if let Some(f) = &c.flush {
                        !f.is_empty()
                    } else {
                        false
                    }
                }),
                ram_quota_mb: Some(settings.quota.raw_ram / 1024 / 1024),
                replica_number: settings.replica_number,
                eviction_policy: settings.eviction_policy,
                max_ttl: settings.max_ttl.map(|d| Duration::from_secs(d as u64)),
                compression_mode: settings.compression_mode,
                durability_min_level: settings.durability_min_level,
                history_retention_collection_default: settings.history_retention_collection_default,
                history_retention_bytes: settings.history_retention_bytes,
                history_retention_seconds: settings.history_retention_seconds,
                conflict_resolution_type: settings.conflict_resolution_type,
                replica_index: settings.replica_index,
                bucket_type: settings.bucket_type,
                storage_backend: settings.storage_backend,
                num_vbuckets: settings.num_vbuckets,
            },
        }
    }
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct BucketType(InnerBucketType);

impl BucketType {
    pub const COUCHBASE: BucketType = BucketType(InnerBucketType::Couchbase);

    pub const EPHEMERAL: BucketType = BucketType(InnerBucketType::Ephemeral);

    pub(crate) fn other(val: String) -> BucketType {
        BucketType(InnerBucketType::Other(val))
    }
}

impl Display for BucketType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            InnerBucketType::Couchbase => write!(f, "membase"),
            InnerBucketType::Ephemeral => write!(f, "ephemeral"),
            InnerBucketType::Other(val) => write!(f, "unknown({val})"),
        }
    }
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub(crate) enum InnerBucketType {
    Couchbase,
    Ephemeral,
    Other(String),
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct EvictionPolicyType(InnerEvictionPolicyType);

impl EvictionPolicyType {
    pub const VALUE_ONLY: EvictionPolicyType =
        EvictionPolicyType(InnerEvictionPolicyType::ValueOnly);

    pub const FULL: EvictionPolicyType = EvictionPolicyType(InnerEvictionPolicyType::Full);

    pub const NOT_RECENTLY_USED: EvictionPolicyType =
        EvictionPolicyType(InnerEvictionPolicyType::NotRecentlyUsed);

    pub const NO_EVICTION: EvictionPolicyType =
        EvictionPolicyType(InnerEvictionPolicyType::NoEviction);

    pub(crate) fn other(val: String) -> EvictionPolicyType {
        EvictionPolicyType(InnerEvictionPolicyType::Other(val))
    }
}

impl Display for EvictionPolicyType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            InnerEvictionPolicyType::ValueOnly => write!(f, "valueOnly"),
            InnerEvictionPolicyType::Full => write!(f, "fullEviction"),
            InnerEvictionPolicyType::NotRecentlyUsed => write!(f, "nruEviction"),
            InnerEvictionPolicyType::NoEviction => write!(f, "noEviction"),
            InnerEvictionPolicyType::Other(val) => write!(f, "unknown({val})"),
        }
    }
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub(crate) enum InnerEvictionPolicyType {
    ValueOnly,
    Full,
    NotRecentlyUsed,
    NoEviction,
    Other(String),
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct CompressionMode(InnerCompressionMode);

impl CompressionMode {
    pub const OFF: CompressionMode = CompressionMode(InnerCompressionMode::Off);

    pub const PASSIVE: CompressionMode = CompressionMode(InnerCompressionMode::Passive);

    pub const ACTIVE: CompressionMode = CompressionMode(InnerCompressionMode::Active);

    pub(crate) fn other(val: String) -> CompressionMode {
        CompressionMode(InnerCompressionMode::Other(val))
    }
}

impl Display for CompressionMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            InnerCompressionMode::Off => write!(f, "off"),
            InnerCompressionMode::Passive => write!(f, "passive"),
            InnerCompressionMode::Active => write!(f, "active"),
            InnerCompressionMode::Other(val) => write!(f, "unknown({val})"),
        }
    }
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub(crate) enum InnerCompressionMode {
    Off,
    Passive,
    Active,
    Other(String),
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct DurabilityLevel(InnerDurabilityLevel);

impl DurabilityLevel {
    pub const NONE: DurabilityLevel = DurabilityLevel(InnerDurabilityLevel::None);

    pub const MAJORITY: DurabilityLevel = DurabilityLevel(InnerDurabilityLevel::Majority);

    pub const MAJORITY_AND_PERSIST_ACTIVE: DurabilityLevel =
        DurabilityLevel(InnerDurabilityLevel::MajorityAndPersistActive);

    pub const PERSIST_TO_MAJORITY: DurabilityLevel =
        DurabilityLevel(InnerDurabilityLevel::PersistToMajority);

    pub(crate) fn other(val: String) -> DurabilityLevel {
        DurabilityLevel(InnerDurabilityLevel::Other(val))
    }
}

impl Display for DurabilityLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            InnerDurabilityLevel::None => write!(f, "none"),
            InnerDurabilityLevel::Majority => write!(f, "majority"),
            InnerDurabilityLevel::MajorityAndPersistActive => write!(f, "majorityAndPersistActive"),
            InnerDurabilityLevel::PersistToMajority => write!(f, "persistToMajority"),
            InnerDurabilityLevel::Other(val) => write!(f, "unknown({val})"),
        }
    }
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub(crate) enum InnerDurabilityLevel {
    None,
    Majority,
    MajorityAndPersistActive,
    PersistToMajority,
    Other(String),
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct ConflictResolutionType(InnerConflictResolutionType);

impl ConflictResolutionType {
    pub const SEQUENCE_NUMBER: ConflictResolutionType =
        ConflictResolutionType(InnerConflictResolutionType::SequenceNumber);

    pub const TIMESTAMP: ConflictResolutionType =
        ConflictResolutionType(InnerConflictResolutionType::Timestamp);

    pub const CUSTOM: ConflictResolutionType =
        ConflictResolutionType(InnerConflictResolutionType::Custom);

    pub(crate) fn other(val: String) -> ConflictResolutionType {
        ConflictResolutionType(InnerConflictResolutionType::Other(val))
    }
}

impl Display for ConflictResolutionType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            InnerConflictResolutionType::SequenceNumber => write!(f, "seqno"),
            InnerConflictResolutionType::Timestamp => write!(f, "lww"),
            InnerConflictResolutionType::Custom => write!(f, "custom"),
            InnerConflictResolutionType::Other(val) => write!(f, "unknown({val})"),
        }
    }
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub(crate) enum InnerConflictResolutionType {
    SequenceNumber,
    Timestamp,
    Custom,
    Other(String),
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct StorageBackend(InnerStorageBackend);

impl StorageBackend {
    pub const COUCHSTORE: StorageBackend = StorageBackend(InnerStorageBackend::Couchstore);

    pub const MAGMA: StorageBackend = StorageBackend(InnerStorageBackend::Magma);

    pub(crate) fn other(val: String) -> StorageBackend {
        StorageBackend(InnerStorageBackend::Other(val))
    }
}

impl Display for StorageBackend {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.0 {
            InnerStorageBackend::Couchstore => write!(f, "couchstore"),
            InnerStorageBackend::Magma => write!(f, "magma"),
            InnerStorageBackend::Other(val) => write!(f, "unknown({val})"),
        }
    }
}

#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub(crate) enum InnerStorageBackend {
    Couchstore,
    Magma,
    Other(String),
}

pub(crate) fn encode_bucket_settings(serializer: &mut Serializer<String>, opts: &BucketSettings) {
    if let Some(flush) = opts.flush_enabled {
        serializer.append_pair("flushEnabled", if flush { "1" } else { "0" });
    }
    if let Some(quota) = opts.ram_quota_mb {
        serializer.append_pair("ramQuotaMB", quota.to_string().as_str());
    }
    if let Some(num) = opts.replica_number {
        serializer.append_pair("replicaNumber", num.to_string().as_str());
    }
    if let Some(eviction_policy) = &opts.eviction_policy {
        serializer.append_pair("evictionPolicy", eviction_policy.to_string().as_str());
    }
    if let Some(max_ttl) = &opts.max_ttl {
        serializer.append_pair("maxTTL", max_ttl.as_secs().to_string().as_str());
    }
    if let Some(compression_mode) = &opts.compression_mode {
        serializer.append_pair("compressionMode", compression_mode.to_string().as_str());
    }
    if let Some(durability_min_level) = &opts.durability_min_level {
        serializer.append_pair(
            "durabilityMinLevel",
            durability_min_level.to_string().as_str(),
        );
    }
    if let Some(retention) = opts.history_retention_bytes {
        serializer.append_pair("historyRetentionBytes", retention.to_string().as_str());
    }
    if let Some(retention) = opts.history_retention_seconds {
        serializer.append_pair("historyRetentionSeconds", retention.to_string().as_str());
    }
    if let Some(history_retention_collection_default) = &opts.history_retention_collection_default {
        serializer.append_pair(
            "historyRetentionCollectionDefault",
            history_retention_collection_default.to_string().as_str(),
        );
    }
    if let Some(conflict_resolution_type) = &opts.conflict_resolution_type {
        serializer.append_pair(
            "conflictResolutionType",
            conflict_resolution_type.to_string().as_str(),
        );
    }
    if let Some(index) = opts.replica_index {
        serializer.append_pair("replicaIndex", if index { "1" } else { "0" });
    }
    if let Some(bucket_type) = &opts.bucket_type {
        serializer.append_pair("bucketType", bucket_type.to_string().as_str());
    }
    if let Some(storage_backend) = &opts.storage_backend {
        serializer.append_pair("storageBackend", storage_backend.to_string().as_str());
    }
    if let Some(num_vbuckets) = opts.num_vbuckets {
        serializer.append_pair("numVBuckets", num_vbuckets.to_string().as_str());
    }
}