Coverage Report

Created: 2025-03-08 07:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/build/source/nativelink-config/src/stores.rs
Line
Count
Source
1
// Copyright 2024 The NativeLink Authors. All rights reserved.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//    http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
use serde::{Deserialize, Serialize};
16
17
use crate::serde_utils::{
18
    convert_data_size_with_shellexpand, convert_duration_with_shellexpand,
19
    convert_numeric_with_shellexpand, convert_optional_string_with_shellexpand,
20
    convert_string_with_shellexpand, convert_vec_string_with_shellexpand,
21
};
22
23
/// Name of the store. This type will be used when referencing a store
24
/// in the `CasConfig::stores`'s map key.
25
pub type StoreRefName = String;
26
27
#[allow(non_camel_case_types)]
28
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
29
pub enum ConfigDigestHashFunction {
30
    /// Use the sha256 hash function.
31
    /// <https://en.wikipedia.org/wiki/SHA-2>
32
    sha256,
33
34
    /// Use the blake3 hash function.
35
    /// <https://en.wikipedia.org/wiki/BLAKE_(hash_function)>
36
    blake3,
37
}
38
39
#[allow(non_camel_case_types)]
40
#[derive(Serialize, Deserialize, Debug, Clone)]
41
pub enum StoreSpec {
42
    /// Memory store will store all data in a hashmap in memory.
43
    ///
44
    /// **Example JSON Config:**
45
    /// ```json
46
    /// "memory": {
47
    ///     "eviction_policy": {
48
    ///       // 10mb.
49
    ///       "max_bytes": 10000000,
50
    ///     }
51
    ///   }
52
    /// }
53
    /// ```
54
    ///
55
    memory(MemorySpec),
56
57
    /// S3 store will use Amazon's S3 service as a backend to store
58
    /// the files. This configuration can be used to share files
59
    /// across multiple instances.
60
    ///
61
    /// This configuration will never delete files, so you are
62
    /// responsible for purging old files in other ways.
63
    ///
64
    /// **Example JSON Config:**
65
    /// ```json
66
    /// "experimental_s3_store": {
67
    ///   "region": "eu-north-1",
68
    ///   "bucket": "crossplane-bucket-af79aeca9",
69
    ///   "key_prefix": "test-prefix-index/",
70
    ///   "retry": {
71
    ///     "max_retries": 6,
72
    ///     "delay": 0.3,
73
    ///     "jitter": 0.5
74
    ///   },
75
    ///   "multipart_max_concurrent_uploads": 10
76
    /// }
77
    /// ```
78
    ///
79
    experimental_s3_store(S3Spec),
80
81
    /// Verify store is used to apply verifications to an underlying
82
    /// store implementation. It is strongly encouraged to validate
83
    /// as much data as you can before accepting data from a client,
84
    /// failing to do so may cause the data in the store to be
85
    /// populated with invalid data causing all kinds of problems.
86
    ///
87
    /// The suggested configuration is to have the CAS validate the
88
    /// hash and size and the AC validate nothing.
89
    ///
90
    /// **Example JSON Config:**
91
    /// ```json
92
    /// "verify": {
93
    ///   "memory": {
94
    ///     "eviction_policy": {
95
    ///       "max_bytes": 500000000 // 500mb.
96
    ///     }
97
    ///   },
98
    ///   "verify_size": true,
99
    ///   "hash_verification_function": "sha256"
100
    /// }
101
    /// ```
102
    ///
103
    verify(Box<VerifySpec>),
104
105
    /// Completeness checking store verifies if the
106
    /// output files & folders exist in the CAS before forwarding
107
    /// the request to the underlying store.
108
    /// Note: This store should only be used on AC stores.
109
    ///
110
    /// **Example JSON Config:**
111
    /// ```json
112
    /// "completeness_checking": {
113
    ///     "backend": {
114
    ///       "filesystem": {
115
    ///         "content_path": "~/.cache/nativelink/content_path-ac",
116
    ///         "temp_path": "~/.cache/nativelink/tmp_path-ac",
117
    ///         "eviction_policy": {
118
    ///           // 500mb.
119
    ///           "max_bytes": 500000000,
120
    ///         }
121
    ///       }
122
    ///     },
123
    ///     "cas_store": {
124
    ///       "ref_store": {
125
    ///         "name": "CAS_MAIN_STORE"
126
    ///       }
127
    ///     }
128
    ///   }
129
    /// ```
130
    ///
131
    completeness_checking(Box<CompletenessCheckingSpec>),
132
133
    /// A compression store that will compress the data inbound and
134
    /// outbound. There will be a non-trivial cost to compress and
135
    /// decompress the data, but in many cases if the final store is
136
    /// a store that requires network transport and/or storage space
137
    /// is a concern it is often faster and more efficient to use this
138
    /// store before those stores.
139
    ///
140
    /// **Example JSON Config:**
141
    /// ```json
142
    /// "compression": {
143
    ///     "compression_algorithm": {
144
    ///       "lz4": {}
145
    ///     },
146
    ///     "backend": {
147
    ///       "filesystem": {
148
    ///         "content_path": "/tmp/nativelink/data/content_path-cas",
149
    ///         "temp_path": "/tmp/nativelink/data/tmp_path-cas",
150
    ///         "eviction_policy": {
151
    ///           // 2gb.
152
    ///           "max_bytes": 2000000000,
153
    ///         }
154
    ///       }
155
    ///     }
156
    ///   }
157
    /// ```
158
    ///
159
    compression(Box<CompressionSpec>),
160
161
    /// A dedup store will take the inputs and run a rolling hash
162
    /// algorithm on them to slice the input into smaller parts then
163
    /// run a sha256 algorithm on the slice and if the object doesn't
164
    /// already exist, upload the slice to the `content_store` using
165
    /// a new digest of just the slice. Once all parts exist, an
166
    /// Action-Cache-like digest will be built and uploaded to the
167
    /// `index_store` which will contain a reference to each
168
    /// chunk/digest of the uploaded file. Downloading a request will
169
    /// first grab the index from the `index_store`, and forward the
170
    /// download content of each chunk as if it were one file.
171
    ///
172
    /// This store is exceptionally good when the following conditions
173
    /// are met:
174
    /// * Content is mostly the same (inserts, updates, deletes are ok)
175
    /// * Content is not compressed or encrypted
176
    /// * Uploading or downloading from `content_store` is the bottleneck.
177
    ///
178
    /// Note: This store pairs well when used with `CompressionSpec` as
179
    /// the `content_store`, but never put `DedupSpec` as the backend of
180
    /// `CompressionSpec` as it will negate all the gains.
181
    ///
182
    /// Note: When running `.has()` on this store, it will only check
183
    /// to see if the entry exists in the `index_store` and not check
184
    /// if the individual chunks exist in the `content_store`.
185
    ///
186
    /// **Example JSON Config:**
187
    /// ```json
188
    /// "dedup": {
189
    ///     "index_store": {
190
    ///       "memory_store": {
191
    ///         "max_size": 1000000000, // 1GB
192
    ///         "eviction_policy": "LeastRecentlyUsed"
193
    ///       }
194
    ///     },
195
    ///     "content_store": {
196
    ///       "compression": {
197
    ///         "compression_algorithm": {
198
    ///           "lz4": {}
199
    ///         },
200
    ///         "backend": {
201
    ///           "fast_slow": {
202
    ///             "fast": {
203
    ///               "memory_store": {
204
    ///                 "max_size": 500000000, // 500MB
205
    ///                 "eviction_policy": "LeastRecentlyUsed"
206
    ///               }
207
    ///             },
208
    ///             "slow": {
209
    ///               "filesystem": {
210
    ///                 "content_path": "/tmp/nativelink/data/content_path-content",
211
    ///                 "temp_path": "/tmp/nativelink/data/tmp_path-content",
212
    ///                 "eviction_policy": {
213
    ///                   "max_bytes": 2000000000 // 2gb.
214
    ///                 }
215
    ///               }
216
    ///             }
217
    ///           }
218
    ///         }
219
    ///       }
220
    ///     }
221
    ///   }
222
    /// ```
223
    ///
224
    dedup(Box<DedupSpec>),
225
226
    /// Existence store will wrap around another store and cache calls
227
    /// to has so that subsequent `has_with_results` calls will be
228
    /// faster. This is useful for cases when you have a store that
229
    /// is slow to respond to has calls.
230
    /// Note: This store should only be used on CAS stores.
231
    ///
232
    /// **Example JSON Config:**
233
    /// ```json
234
    /// "existence_cache": {
235
    ///     "backend": {
236
    ///       "memory": {
237
    ///         "eviction_policy": {
238
    ///           // 500mb.
239
    ///           "max_bytes": 500000000,
240
    ///         }
241
    ///       }
242
    ///     },
243
    ///     "cas_store": {
244
    ///       "ref_store": {
245
    ///         "name": "CAS_MAIN_STORE"
246
    ///       }
247
    ///     }
248
    ///   }
249
    /// ```
250
    ///
251
    existence_cache(Box<ExistenceCacheSpec>),
252
253
    /// `FastSlow` store will first try to fetch the data from the `fast`
254
    /// store and then if it does not exist try the `slow` store.
255
    /// When the object does exist in the `slow` store, it will copy
256
    /// the data to the `fast` store while returning the data.
257
    /// This store should be thought of as a store that "buffers"
258
    /// the data to the `fast` store.
259
    /// On uploads it will mirror data to both `fast` and `slow` stores.
260
    ///
261
    /// WARNING: If you need data to always exist in the `slow` store
262
    /// for something like remote execution, be careful because this
263
    /// store will never check to see if the objects exist in the
264
    /// `slow` store if it exists in the `fast` store (ie: it assumes
265
    /// that if an object exists `fast` store it will exist in `slow`
266
    /// store).
267
    ///
268
    /// ***Example JSON Config:***
269
    /// ```json
270
    /// "fast_slow": {
271
    ///     "fast": {
272
    ///       "filesystem": {
273
    ///         "content_path": "/tmp/nativelink/data/content_path-index",
274
    ///         "temp_path": "/tmp/nativelink/data/tmp_path-index",
275
    ///         "eviction_policy": {
276
    ///           // 500mb.
277
    ///           "max_bytes": 500000000,
278
    ///         }
279
    ///       }
280
    ///     },
281
    ///     "slow": {
282
    ///       "filesystem": {
283
    ///         "content_path": "/tmp/nativelink/data/content_path-index",
284
    ///         "temp_path": "/tmp/nativelink/data/tmp_path-index",
285
    ///         "eviction_policy": {
286
    ///           // 500mb.
287
    ///           "max_bytes": 500000000,
288
    ///         }
289
    ///       }
290
    ///     }
291
    ///   }
292
    /// ```
293
    ///
294
    fast_slow(Box<FastSlowSpec>),
295
296
    /// Shards the data to multiple stores. This is useful for cases
297
    /// when you want to distribute the load across multiple stores.
298
    /// The digest hash is used to determine which store to send the
299
    /// data to.
300
    ///
301
    /// **Example JSON Config:**
302
    /// ```json
303
    /// "shard": {
304
    ///     "stores": [
305
    ///         "memory": {
306
    ///             "eviction_policy": {
307
    ///                 // 10mb.
308
    ///                 "max_bytes": 10000000
309
    ///             },
310
    ///             "weight": 1
311
    ///         }
312
    ///     ]
313
    /// }
314
    /// ```
315
    ///
316
    shard(ShardSpec),
317
318
    /// Stores the data on the filesystem. This store is designed for
319
    /// local persistent storage. Restarts of this program should restore
320
    /// the previous state, meaning anything uploaded will be persistent
321
    /// as long as the filesystem integrity holds.
322
    ///
323
    /// **Example JSON Config:**
324
    /// ```json
325
    /// "filesystem": {
326
    ///     "content_path": "/tmp/nativelink/data-worker-test/content_path-cas",
327
    ///     "temp_path": "/tmp/nativelink/data-worker-test/tmp_path-cas",
328
    ///     "eviction_policy": {
329
    ///       // 10gb.
330
    ///       "max_bytes": 10000000000,
331
    ///     }
332
    /// }
333
    /// ```
334
    ///
335
    filesystem(FilesystemSpec),
336
337
    /// Store used to reference a store in the root store manager.
338
    /// This is useful for cases when you want to share a store in different
339
    /// nested stores. Example, you may want to share the same memory store
340
    /// used for the action cache, but use a `FastSlowSpec` and have the fast
341
    /// store also share the memory store for efficiency.
342
    ///
343
    /// **Example JSON Config:**
344
    /// ```json
345
    /// "ref_store": {
346
    ///     "name": "FS_CONTENT_STORE"
347
    /// }
348
    /// ```
349
    ///
350
    ref_store(RefSpec),
351
352
    /// Uses the size field of the digest to separate which store to send the
353
    /// data. This is useful for cases when you'd like to put small objects
354
    /// in one store and large objects in another store. This should only be
355
    /// used if the size field is the real size of the content, in other
356
    /// words, don't use on AC (Action Cache) stores. Any store where you can
357
    /// safely use `VerifySpec.verify_size = true`, this store should be safe
358
    /// to use (ie: CAS stores).
359
    ///
360
    /// **Example JSON Config:**
361
    /// ```json
362
    /// "size_partitioning": {
363
    ///     "size": 134217728, // 128mib.
364
    ///     "lower_store": {
365
    ///       "memory": {
366
    ///         "eviction_policy": {
367
    ///           "max_bytes": "${NATIVELINK_CAS_MEMORY_CONTENT_LIMIT:-100000000}"
368
    ///         }
369
    ///       }
370
    ///     },
371
    ///     "upper_store": {
372
    ///       /// This store discards data larger than 128mib.
373
    ///       "noop": {}
374
    ///     }
375
    ///   }
376
    /// ```
377
    ///
378
    size_partitioning(Box<SizePartitioningSpec>),
379
380
    /// This store will pass-through calls to another GRPC store. This store
381
    /// is not designed to be used as a sub-store of another store, but it
382
    /// does satisfy the interface and will likely work.
383
    ///
384
    /// One major GOTCHA is that some stores use a special function on this
385
    /// store to get the size of the underlying object, which is only reliable
386
    /// when this store is serving the a CAS store, not an AC store. If using
387
    /// this store directly without being a child of any store there are no
388
    /// side effects and is the most efficient way to use it.
389
    ///
390
    /// **Example JSON Config:**
391
    /// ```json
392
    /// "grpc": {
393
    ///     "instance_name": "main",
394
    ///     "endpoints": [
395
    ///       {"address": "grpc://${CAS_ENDPOINT:-127.0.0.1}:50051"}
396
    ///     ],
397
    ///     "store_type": "ac"
398
    ///   }
399
    /// ```
400
    ///
401
    grpc(GrpcSpec),
402
403
    /// Stores data in any stores compatible with Redis APIs.
404
    ///
405
    /// Pairs well with `SizePartitioning` and/or `FastSlow` stores.
406
    /// Ideal for accepting small object sizes as most redis store
407
    /// services have a max file upload of between 256Mb-512Mb.
408
    ///
409
    /// **Example JSON Config:**
410
    /// ```json
411
    /// "redis_store": {
412
    ///     "addresses": [
413
    ///         "redis://127.0.0.1:6379/",
414
    ///     ]
415
    /// }
416
    /// ```
417
    ///
418
    redis_store(RedisSpec),
419
420
    /// Noop store is a store that sends streams into the void and all data
421
    /// retrieval will return 404 (`NotFound`). This can be useful for cases
422
    /// where you may need to partition your data and part of your data needs
423
    /// to be discarded.
424
    ///
425
    /// **Example JSON Config:**
426
    /// ```json
427
    /// "noop": {}
428
    /// ```
429
    ///
430
    noop(NoopSpec),
431
}
432
433
/// Configuration for an individual shard of the store.
434
#[derive(Serialize, Deserialize, Debug, Clone)]
435
#[serde(deny_unknown_fields)]
436
pub struct ShardConfig {
437
    /// Store to shard the data to.
438
    pub store: StoreSpec,
439
440
    /// The weight of the store. This is used to determine how much data
441
    /// should be sent to the store. The actual percentage is the sum of
442
    /// all the store's weights divided by the individual store's weight.
443
    ///
444
    /// Default: 1
445
    pub weight: Option<u32>,
446
}
447
448
#[derive(Serialize, Deserialize, Debug, Clone)]
449
#[serde(deny_unknown_fields)]
450
pub struct ShardSpec {
451
    /// Stores to shard the data to.
452
    pub stores: Vec<ShardConfig>,
453
}
454
455
0
#[derive(Serialize, Deserialize, Debug, Clone)]
456
#[serde(deny_unknown_fields)]
457
pub struct SizePartitioningSpec {
458
    /// Size to partition the data on.
459
    #[serde(deserialize_with = "convert_data_size_with_shellexpand")]
460
    pub size: u64,
461
462
    /// Store to send data when object is < (less than) size.
463
    pub lower_store: StoreSpec,
464
465
    /// Store to send data when object is >= (less than eq) size.
466
    pub upper_store: StoreSpec,
467
}
468
469
0
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
470
#[serde(deny_unknown_fields)]
471
pub struct RefSpec {
472
    /// Name of the store under the root "stores" config object.
473
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
474
    pub name: String,
475
}
476
477
0
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
478
#[serde(deny_unknown_fields)]
479
pub struct FilesystemSpec {
480
    /// Path on the system where to store the actual content. This is where
481
    /// the bulk of the data will be placed.
482
    /// On service bootup this folder will be scanned and all files will be
483
    /// added to the cache. In the event one of the files doesn't match the
484
    /// criteria, the file will be deleted.
485
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
486
    pub content_path: String,
487
488
    /// A temporary location of where files that are being uploaded or
489
    /// deleted will be placed while the content cannot be guaranteed to be
490
    /// accurate. This location must be on the same block device as
491
    /// `content_path` so atomic moves can happen (ie: move without copy).
492
    /// All files in this folder will be deleted on every startup.
493
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
494
    pub temp_path: String,
495
496
    /// Buffer size to use when reading files. Generally this should be left
497
    /// to the default value except for testing.
498
    /// Default: 32k.
499
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
500
    pub read_buffer_size: u32,
501
502
    /// Policy used to evict items out of the store. Failure to set this
503
    /// value will cause items to never be removed from the store causing
504
    /// infinite memory usage.
505
    pub eviction_policy: Option<EvictionPolicy>,
506
507
    /// The block size of the filesystem for the running machine
508
    /// value is used to determine an entry's actual size on disk consumed
509
    /// For a 4KB block size filesystem, a 1B file actually consumes 4KB
510
    /// Default: 4096
511
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
512
    pub block_size: u64,
513
}
514
515
#[derive(Serialize, Deserialize, Debug, Clone)]
516
#[serde(deny_unknown_fields)]
517
pub struct FastSlowSpec {
518
    /// Fast store that will be attempted to be contacted before reaching
519
    /// out to the `slow` store.
520
    pub fast: StoreSpec,
521
522
    /// If the object does not exist in the `fast` store it will try to
523
    /// get it from this store.
524
    pub slow: StoreSpec,
525
}
526
527
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
528
#[serde(deny_unknown_fields)]
529
pub struct MemorySpec {
530
    /// Policy used to evict items out of the store. Failure to set this
531
    /// value will cause items to never be removed from the store causing
532
    /// infinite memory usage.
533
    pub eviction_policy: Option<EvictionPolicy>,
534
}
535
536
0
#[derive(Serialize, Deserialize, Debug, Clone)]
537
#[serde(deny_unknown_fields)]
538
pub struct DedupSpec {
539
    /// Store used to store the index of each dedup slice. This store
540
    /// should generally be fast and small.
541
    pub index_store: StoreSpec,
542
543
    /// The store where the individual chunks will be uploaded. This
544
    /// store should generally be the slower & larger store.
545
    pub content_store: StoreSpec,
546
547
    /// Minimum size that a chunk will be when slicing up the content.
548
    /// Note: This setting can be increased to improve performance
549
    /// because it will actually not check this number of bytes when
550
    /// deciding where to partition the data.
551
    ///
552
    /// Default: 65536 (64k)
553
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
554
    pub min_size: u32,
555
556
    /// A best-effort attempt will be made to keep the average size
557
    /// of the chunks to this number. It is not a guarantee, but a
558
    /// slight attempt will be made.
559
    ///
560
    /// This value will also be about the threshold used to determine
561
    /// if we should even attempt to dedup the entry or just forward
562
    /// it directly to the `content_store` without an index. The actual
563
    /// value will be about `normal_size * 1.3` due to implementation
564
    /// details.
565
    ///
566
    /// Default: 262144 (256k)
567
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
568
    pub normal_size: u32,
569
570
    /// Maximum size a chunk is allowed to be.
571
    ///
572
    /// Default: 524288 (512k)
573
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
574
    pub max_size: u32,
575
576
    /// Due to implementation detail, we want to prefer to download
577
    /// the first chunks of the file so we can stream the content
578
    /// out and free up some of our buffers. This configuration
579
    /// will be used to to restrict the number of concurrent chunk
580
    /// downloads at a time per `get()` request.
581
    ///
582
    /// This setting will also affect how much memory might be used
583
    /// per `get()` request. Estimated worst case memory per `get()`
584
    /// request is: `max_concurrent_fetch_per_get * max_size`.
585
    ///
586
    /// Default: 10
587
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
588
    pub max_concurrent_fetch_per_get: u32,
589
}
590
591
#[derive(Serialize, Deserialize, Debug, Clone)]
592
#[serde(deny_unknown_fields)]
593
pub struct ExistenceCacheSpec {
594
    /// The underlying store wrap around. All content will first flow
595
    /// through self before forwarding to backend. In the event there
596
    /// is an error detected in self, the connection to the backend
597
    /// will be terminated, and early termination should always cause
598
    /// updates to fail on the backend.
599
    pub backend: StoreSpec,
600
601
    /// Policy used to evict items out of the store. Failure to set this
602
    /// value will cause items to never be removed from the store causing
603
    /// infinite memory usage.
604
    pub eviction_policy: Option<EvictionPolicy>,
605
}
606
607
#[derive(Serialize, Deserialize, Debug, Clone)]
608
#[serde(deny_unknown_fields)]
609
pub struct VerifySpec {
610
    /// The underlying store wrap around. All content will first flow
611
    /// through self before forwarding to backend. In the event there
612
    /// is an error detected in self, the connection to the backend
613
    /// will be terminated, and early termination should always cause
614
    /// updates to fail on the backend.
615
    pub backend: StoreSpec,
616
617
    /// If set the store will verify the size of the data before accepting
618
    /// an upload of data.
619
    ///
620
    /// This should be set to false for AC, but true for CAS stores.
621
    #[serde(default)]
622
    pub verify_size: bool,
623
624
    /// If the data should be hashed and verify that the key matches the
625
    /// computed hash. The hash function is automatically determined based
626
    /// request and if not set will use the global default.
627
    ///
628
    /// This should be set to None for AC, but hashing function like `sha256` for CAS stores.
629
    #[serde(default)]
630
    pub verify_hash: bool,
631
}
632
633
#[derive(Serialize, Deserialize, Debug, Clone)]
634
#[serde(deny_unknown_fields)]
635
pub struct CompletenessCheckingSpec {
636
    /// The underlying store that will have it's results validated before sending to client.
637
    pub backend: StoreSpec,
638
639
    /// When a request is made, the results are decoded and all output digests/files are verified
640
    /// to exist in this CAS store before returning success.
641
    pub cas_store: StoreSpec,
642
}
643
644
0
#[derive(Serialize, Deserialize, Debug, Default, PartialEq, Clone, Copy)]
645
#[serde(deny_unknown_fields)]
646
pub struct Lz4Config {
647
    /// Size of the blocks to compress.
648
    /// Higher values require more ram, but might yield slightly better
649
    /// compression ratios.
650
    ///
651
    /// Default: 65536 (64k).
652
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
653
    pub block_size: u32,
654
655
    /// Maximum size allowed to attempt to deserialize data into.
656
    /// This is needed because the `block_size` is embedded into the data
657
    /// so if there was a bad actor, they could upload an extremely large
658
    /// `block_size`'ed entry and we'd allocate a large amount of memory
659
    /// when retrieving the data. To prevent this from happening, we
660
    /// allow you to specify the maximum that we'll attempt deserialize.
661
    ///
662
    /// Default: value in `block_size`.
663
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
664
    pub max_decode_block_size: u32,
665
}
666
667
#[allow(non_camel_case_types)]
668
#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
669
pub enum CompressionAlgorithm {
670
    /// LZ4 compression algorithm is extremely fast for compression and
671
    /// decompression, however does not perform very well in compression
672
    /// ratio. In most cases build artifacts are highly compressible, however
673
    /// lz4 is quite good at aborting early if the data is not deemed very
674
    /// compressible.
675
    ///
676
    /// see: <https://lz4.github.io/lz4/>
677
    lz4(Lz4Config),
678
}
679
680
#[derive(Serialize, Deserialize, Debug, Clone)]
681
#[serde(deny_unknown_fields)]
682
pub struct CompressionSpec {
683
    /// The underlying store wrap around. All content will first flow
684
    /// through self before forwarding to backend. In the event there
685
    /// is an error detected in self, the connection to the backend
686
    /// will be terminated, and early termination should always cause
687
    /// updates to fail on the backend.
688
    pub backend: StoreSpec,
689
690
    /// The compression algorithm to use.
691
    pub compression_algorithm: CompressionAlgorithm,
692
}
693
694
/// Eviction policy always works on LRU (Least Recently Used). Any time an entry
695
/// is touched it updates the timestamp. Inserts and updates will execute the
696
/// eviction policy removing any expired entries and/or the oldest entries
697
/// until the store size becomes smaller than `max_bytes`.
698
0
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
699
#[serde(deny_unknown_fields)]
700
pub struct EvictionPolicy {
701
    /// Maximum number of bytes before eviction takes place.
702
    /// Default: 0. Zero means never evict based on size.
703
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
704
    pub max_bytes: usize,
705
706
    /// When eviction starts based on hitting `max_bytes`, continue until
707
    /// `max_bytes - evict_bytes` is met to create a low watermark.  This stops
708
    /// operations from thrashing when the store is close to the limit.
709
    /// Default: 0
710
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
711
    pub evict_bytes: usize,
712
713
    /// Maximum number of seconds for an entry to live since it was last
714
    /// accessed before it is evicted.
715
    /// Default: 0. Zero means never evict based on time.
716
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
717
    pub max_seconds: u32,
718
719
    /// Maximum size of the store before an eviction takes place.
720
    /// Default: 0. Zero means never evict based on count.
721
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
722
    pub max_count: u64,
723
}
724
725
0
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
726
#[serde(deny_unknown_fields)]
727
pub struct S3Spec {
728
    /// S3 region. Usually us-east-1, us-west-2, af-south-1, exc...
729
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
730
    pub region: String,
731
732
    /// Bucket name to use as the backend.
733
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
734
    pub bucket: String,
735
736
    /// If you wish to prefix the location on s3. If None, no prefix will be used.
737
    #[serde(default)]
738
    pub key_prefix: Option<String>,
739
740
    /// Retry configuration to use when a network request fails.
741
    #[serde(default)]
742
    pub retry: Retry,
743
744
    /// If the number of seconds since the `last_modified` time of the object
745
    /// is greater than this value, the object will not be considered
746
    /// "existing". This allows for external tools to delete objects that
747
    /// have not been uploaded in a long time. If a client receives a `NotFound`
748
    /// the client should re-upload the object.
749
    ///
750
    /// There should be sufficient buffer time between how long the expiration
751
    /// configuration of the external tool is and this value. Keeping items
752
    /// around for a few days is generally a good idea.
753
    ///
754
    /// Default: 0. Zero means never consider an object expired.
755
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
756
    pub consider_expired_after_s: u32,
757
758
    /// The maximum buffer size to retain in case of a retryable error
759
    /// during upload. Setting this to zero will disable upload buffering;
760
    /// this means that in the event of a failure during upload, the entire
761
    /// upload will be aborted and the client will likely receive an error.
762
    ///
763
    /// Default: 5MB.
764
    pub max_retry_buffer_per_request: Option<usize>,
765
766
    /// Maximum number of concurrent `UploadPart` requests per `MultipartUpload`.
767
    ///
768
    /// Default: 10.
769
    pub multipart_max_concurrent_uploads: Option<usize>,
770
771
    /// Allow unencrypted HTTP connections. Only use this for local testing.
772
    ///
773
    /// Default: false
774
    #[serde(default)]
775
    pub insecure_allow_http: bool,
776
777
    /// Disable http/2 connections and only use http/1.1. Default client
778
    /// configuration will have http/1.1 and http/2 enabled for connection
779
    /// schemes. Http/2 should be disabled if environments have poor support
780
    /// or performance related to http/2. Safe to keep default unless
781
    /// underlying network environment or S3 API servers specify otherwise.
782
    ///
783
    /// Default: false
784
    #[serde(default)]
785
    pub disable_http2: bool,
786
}
787
788
#[allow(non_camel_case_types)]
789
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
790
pub enum StoreType {
791
    /// The store is content addressable storage.
792
    cas,
793
    /// The store is an action cache.
794
    ac,
795
}
796
797
0
#[derive(Serialize, Deserialize, Debug, Clone)]
798
pub struct ClientTlsConfig {
799
    /// Path to the certificate authority to use to validate the remote.
800
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
801
    pub ca_file: String,
802
803
    /// Path to the certificate file for client authentication.
804
    #[serde(deserialize_with = "convert_optional_string_with_shellexpand")]
805
    pub cert_file: Option<String>,
806
807
    /// Path to the private key file for client authentication.
808
    #[serde(deserialize_with = "convert_optional_string_with_shellexpand")]
809
    pub key_file: Option<String>,
810
}
811
812
0
#[derive(Serialize, Deserialize, Debug, Clone)]
813
#[serde(deny_unknown_fields)]
814
pub struct GrpcEndpoint {
815
    /// The endpoint address (i.e. grpc(s)://example.com:443).
816
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
817
    pub address: String,
818
    /// The TLS configuration to use to connect to the endpoint (if grpcs).
819
    pub tls_config: Option<ClientTlsConfig>,
820
    /// The maximum concurrency to allow on this endpoint.
821
    pub concurrency_limit: Option<usize>,
822
}
823
824
0
#[derive(Serialize, Deserialize, Debug, Clone)]
825
#[serde(deny_unknown_fields)]
826
pub struct GrpcSpec {
827
    /// Instance name for GRPC calls. Proxy calls will have the `instance_name` changed to this.
828
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
829
    pub instance_name: String,
830
831
    /// The endpoint of the grpc connection.
832
    pub endpoints: Vec<GrpcEndpoint>,
833
834
    /// The type of the upstream store, this ensures that the correct server calls are made.
835
    pub store_type: StoreType,
836
837
    /// Retry configuration to use when a network request fails.
838
    #[serde(default)]
839
    pub retry: Retry,
840
841
    /// Limit the number of simultaneous upstream requests to this many.  A
842
    /// value of zero is treated as unlimited.  If the limit is reached the
843
    /// request is queued.
844
    #[serde(default)]
845
    pub max_concurrent_requests: usize,
846
847
    /// The number of connections to make to each specified endpoint to balance
848
    /// the load over multiple TCP connections.  Default 1.
849
    #[serde(default)]
850
    pub connections_per_endpoint: usize,
851
}
852
853
/// The possible error codes that might occur on an upstream request.
854
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
855
pub enum ErrorCode {
856
    Cancelled = 1,
857
    Unknown = 2,
858
    InvalidArgument = 3,
859
    DeadlineExceeded = 4,
860
    NotFound = 5,
861
    AlreadyExists = 6,
862
    PermissionDenied = 7,
863
    ResourceExhausted = 8,
864
    FailedPrecondition = 9,
865
    Aborted = 10,
866
    OutOfRange = 11,
867
    Unimplemented = 12,
868
    Internal = 13,
869
    Unavailable = 14,
870
    DataLoss = 15,
871
    Unauthenticated = 16,
872
    // Note: This list is duplicated from nativelink-error/lib.rs.
873
}
874
875
0
#[derive(Serialize, Deserialize, Debug, Clone)]
876
pub struct RedisSpec {
877
    /// The hostname or IP address of the Redis server.
878
    /// Ex: `["redis://username:password@redis-server-url:6380/99"]`
879
    /// 99 Represents database ID, 6380 represents the port.
880
    #[serde(deserialize_with = "convert_vec_string_with_shellexpand")]
881
    pub addresses: Vec<String>,
882
883
    /// The response timeout for the Redis connection in seconds.
884
    ///
885
    /// Default: 10
886
    #[serde(default)]
887
    pub response_timeout_s: u64,
888
889
    /// The connection timeout for the Redis connection in seconds.
890
    ///
891
    /// Default: 10
892
    #[serde(default)]
893
    pub connection_timeout_s: u64,
894
895
    /// An optional and experimental Redis channel to publish write events to.
896
    ///
897
    /// If set, every time a write operation is made to a Redis node
898
    /// then an event will be published to a Redis channel with the given name.
899
    /// If unset, the writes will still be made,
900
    /// but the write events will not be published.
901
    ///
902
    /// Default: (Empty String / No Channel)
903
    #[serde(default)]
904
    pub experimental_pub_sub_channel: Option<String>,
905
906
    /// An optional prefix to prepend to all keys in this store.
907
    ///
908
    /// Setting this value can make it convenient to query or
909
    /// organize your data according to the shared prefix.
910
    ///
911
    /// Default: (Empty String / No Prefix)
912
    #[serde(default)]
913
    pub key_prefix: String,
914
915
    /// Set the mode Redis is operating in.
916
    ///
917
    /// Available options are "cluster" for
918
    /// [cluster mode](https://redis.io/docs/latest/operate/oss_and_stack/reference/cluster-spec/),
919
    /// "sentinel" for [sentinel mode](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/),
920
    /// or "standard" if Redis is operating in neither cluster nor sentinel mode.
921
    ///
922
    /// Default: standard,
923
    #[serde(default)]
924
    pub mode: RedisMode,
925
926
    /// When using pubsub interface, this is the maximum number of items to keep
927
    /// queued up before dropping old items.
928
    ///
929
    /// Default: 4096
930
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
931
    pub broadcast_channel_capacity: usize,
932
933
    /// The amount of time in milliseconds until the redis store considers the
934
    /// command to be timed out. This will trigger a retry of the command and
935
    /// potentially a reconnection to the redis server.
936
    ///
937
    /// Default: 10000 (10 seconds)
938
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
939
    pub command_timeout_ms: u64,
940
941
    /// The amount of time in milliseconds until the redis store considers the
942
    /// connection to unresponsive. This will trigger a reconnection to the
943
    /// redis server.
944
    ///
945
    /// Default: 3000 (3 seconds)
946
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
947
    pub connection_timeout_ms: u64,
948
949
    /// The amount of data to read from the redis server at a time.
950
    /// This is used to limit the amount of memory used when reading
951
    /// large objects from the redis server as well as limiting the
952
    /// amount of time a single read operation can take.
953
    ///
954
    /// IMPORTANT: If this value is too high, the `command_timeout_ms`
955
    /// might be triggered if the latency or throughput to the redis
956
    /// server is too low.
957
    ///
958
    /// Default: 64KiB
959
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
960
    pub read_chunk_size: usize,
961
962
    /// The number of connections to keep open to the redis server(s).
963
    ///
964
    /// Default: 3
965
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
966
    pub connection_pool_size: usize,
967
968
    /// The maximum number of upload chunks to allow per update.
969
    /// This is used to limit the amount of memory used when uploading
970
    /// large objects to the redis server. A good rule of thumb is to
971
    /// think of the data as:
972
    /// `AVAIL_MEMORY / (read_chunk_size * max_chunk_uploads_per_update) = THORETICAL_MAX_CONCURRENT_UPLOADS`
973
    /// (note: it is a good idea to divide `AVAIL_MAX_MEMORY` by ~10 to account for other memory usage)
974
    ///
975
    /// Default: 10
976
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
977
    pub max_chunk_uploads_per_update: usize,
978
979
    /// Retry configuration to use when a network request fails.
980
    /// See the `Retry` struct for more information.
981
    ///
982
    /// ```txt
983
    /// Default: Retry {
984
    ///   max_retries: 0, /* unlimited */
985
    ///   delay: 0.1, /* 100ms */
986
    ///   jitter: 0.5, /* 50% */
987
    ///   retry_on_errors: None, /* not used in redis store */
988
    /// }
989
    /// ```
990
    #[serde(default)]
991
    pub retry: Retry,
992
}
993
994
#[derive(Debug, Default, Deserialize, Serialize, Clone, PartialEq, Eq)]
995
#[serde(rename_all = "lowercase")]
996
pub enum RedisMode {
997
    Cluster,
998
    Sentinel,
999
    #[default]
1000
    Standard,
1001
}
1002
1003
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
1004
pub struct NoopSpec {}
1005
1006
/// Retry configuration. This configuration is exponential and each iteration
1007
/// a jitter as a percentage is applied of the calculated delay. For example:
1008
/// ```haskell
1009
/// Retry{
1010
///   max_retries: 7,
1011
///   delay: 0.1,
1012
///   jitter: 0.5,
1013
/// }
1014
/// ```
1015
/// will result in:
1016
/// Attempt - Delay
1017
/// 1         0ms
1018
/// 2         75ms - 125ms
1019
/// 3         150ms - 250ms
1020
/// 4         300ms - 500ms
1021
/// 5         600ms - 1s
1022
/// 6         1.2s - 2s
1023
/// 7         2.4s - 4s
1024
/// 8         4.8s - 8s
1025
/// Remember that to get total results is additive, meaning the above results
1026
/// would mean a single request would have a total delay of 9.525s - 15.875s.
1027
0
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
1028
#[serde(deny_unknown_fields)]
1029
pub struct Retry {
1030
    /// Maximum number of retries until retrying stops.
1031
    /// Setting this to zero will always attempt 1 time, but not retry.
1032
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1033
    pub max_retries: usize,
1034
1035
    /// Delay in seconds for exponential back off.
1036
    #[serde(default)]
1037
    pub delay: f32,
1038
1039
    /// Amount of jitter to add as a percentage in decimal form. This will
1040
    /// change the formula like:
1041
    /// ```haskell
1042
    /// random(
1043
    ///    (2 ^ {attempt_number}) * {delay} * (1 - (jitter / 2)),
1044
    ///    (2 ^ {attempt_number}) * {delay} * (1 + (jitter / 2)),
1045
    /// )
1046
    /// ```
1047
    #[serde(default)]
1048
    pub jitter: f32,
1049
1050
    /// A list of error codes to retry on, if this is not set then the default
1051
    /// error codes to retry on are used.  These default codes are the most
1052
    /// likely to be non-permanent.
1053
    ///  - `Unknown`
1054
    ///  - `Cancelled`
1055
    ///  - `DeadlineExceeded`
1056
    ///  - `ResourceExhausted`
1057
    ///  - `Aborted`
1058
    ///  - `Internal`
1059
    ///  - `Unavailable`
1060
    ///  - `DataLoss`
1061
    #[serde(default)]
1062
    pub retry_on_errors: Option<Vec<ErrorCode>>,
1063
}