Coverage Report

Created: 2026-12-01 07:53

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 Trace Machina, Inc. All rights reserved.
2
//
3
// Licensed under the Functional Source License, Version 1.1, Apache 2.0 Future License (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
//    See LICENSE file for details
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 core::time::Duration;
16
use std::collections::HashMap;
17
use std::sync::Arc;
18
19
use rand::Rng;
20
#[cfg(feature = "dev-schema")]
21
use schemars::JsonSchema;
22
use serde::{Deserialize, Serialize};
23
24
use crate::serde_utils::{
25
    convert_boolean_with_shellexpand, convert_data_size_with_shellexpand,
26
    convert_duration_with_shellexpand, convert_numeric_with_shellexpand,
27
    convert_optional_data_size_with_shellexpand, convert_optional_numeric_with_shellexpand,
28
    convert_optional_string_with_shellexpand, convert_string_with_shellexpand,
29
    convert_vec_string_with_shellexpand,
30
};
31
32
/// Name of the store. This type will be used when referencing a store
33
/// in the `CasConfig::stores`'s map key.
34
pub type StoreRefName = String;
35
36
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
37
#[serde(rename_all = "snake_case")]
38
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
39
pub enum ConfigDigestHashFunction {
40
    /// Use the sha256 hash function.
41
    /// <https://en.wikipedia.org/wiki/SHA-2>
42
    Sha256,
43
44
    /// Use the blake3 hash function.
45
    /// <https://en.wikipedia.org/wiki/BLAKE_(hash_function)>
46
    Blake3,
47
}
48
49
#[derive(Serialize, Deserialize, Debug, Clone)]
50
#[serde(rename_all = "snake_case")]
51
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
52
pub enum StoreSpec {
53
    /// Cache metrics store wraps another store and emits low-cardinality
54
    /// OpenTelemetry cache operation metrics for the wrapped store.
55
    ///
56
    /// This wrapper is opt-in. Stores that are not explicitly wrapped by
57
    /// `cache_metrics` are constructed exactly as they are without this
58
    /// wrapper and do not pay its hot-path timing or recording cost.
59
    ///
60
    /// **Example JSON Config:**
61
    /// ```json
62
    /// "cache_metrics": {
63
    ///   "cache_type": "cas",
64
    ///   "backend": {
65
    ///     "filesystem": {
66
    ///       "content_path": "~/.cache/nativelink/content_path-cas",
67
    ///       "temp_path": "~/.cache/nativelink/tmp_path-cas"
68
    ///     }
69
    ///   }
70
    /// }
71
    /// ```
72
    ///
73
    CacheMetrics(Box<CacheMetricsSpec>),
74
75
    /// Memory store will store all data in a hashmap in memory.
76
    ///
77
    /// **Example JSON Config:**
78
    /// ```json
79
    /// "memory": {
80
    ///   "eviction_policy": {
81
    ///     "max_bytes": "10mb",
82
    ///   }
83
    /// }
84
    /// ```
85
    ///
86
    Memory(MemorySpec),
87
88
    /// A generic blob store that will store files on the cloud
89
    /// provider. This configuration will never delete files, so you are
90
    /// responsible for purging old files in other ways.
91
    /// It supports the following backends:
92
    ///
93
    /// 1. **Amazon S3:**
94
    ///    S3 store will use Amazon's S3 service as a backend to store
95
    ///    the files. This configuration can be used to share files
96
    ///    across multiple instances. Uses system certificates for TLS
97
    ///    verification via `rustls-platform-verifier`.
98
    ///
99
    ///   **Example JSON Config:**
100
    ///   ```json
101
    ///   "experimental_cloud_object_store": {
102
    ///     "provider": "aws",
103
    ///     "region": "eu-north-1",
104
    ///     "bucket": "crossplane-bucket-af79aeca9",
105
    ///     "key_prefix": "test-prefix-index/",
106
    ///     "retry": {
107
    ///       "max_retries": 6,
108
    ///       "delay": 0.3,
109
    ///       "jitter": 0.5
110
    ///     },
111
    ///     "multipart_max_concurrent_uploads": 10
112
    ///   }
113
    ///   ```
114
    ///
115
    /// 2. **Google Cloud Storage:**
116
    ///    GCS store uses Google's GCS service as a backend to store
117
    ///    the files. This configuration can be used to share files
118
    ///    across multiple instances.
119
    ///
120
    ///   **Example JSON Config:**
121
    ///   ```json
122
    ///   "experimental_cloud_object_store": {
123
    ///     "provider": "gcs",
124
    ///     "bucket": "test-bucket",
125
    ///     "key_prefix": "test-prefix-index/",
126
    ///     "retry": {
127
    ///       "max_retries": 6,
128
    ///       "delay": 0.3,
129
    ///       "jitter": 0.5
130
    ///     },
131
    ///     "multipart_max_concurrent_uploads": 10
132
    ///   }
133
    ///   ```
134
    ///
135
    /// 3. **Azure Blob Store:**
136
    ///    Azure Blob store will use Microsoft's Azure Blob service as a
137
    ///    backend to store the files. This configuration can be used to
138
    ///    share files across multiple instances.
139
    ///
140
    ///   **Example JSON Config:**
141
    ///   ```json
142
    ///   "experimental_cloud_object_store": {
143
    ///     "provider": "azure",
144
    ///     "account_name": "cloudshell1393657559",
145
    ///     "container": "simple-test-container",
146
    ///     "key_prefix": "folder/",
147
    ///     "retry": {
148
    ///         "max_retries": 6,
149
    ///         "delay": 0.3,
150
    ///         "jitter": 0.5
151
    ///     },
152
    ///     "multipart_max_concurrent_uploads": 10
153
    ///   }
154
    ///   ```
155
    ///
156
    /// 4. **NetApp ONTAP S3:**
157
    ///    NetApp ONTAP S3 store will use ONTAP's S3-compatible storage as a backend
158
    ///    to store files. This store is specifically configured for ONTAP's S3 requirements
159
    ///    including custom TLS configuration, credentials management, and proper vserver
160
    ///    configuration.
161
    ///
162
    ///    This store uses AWS environment variables for credentials:
163
    ///    - `AWS_ACCESS_KEY_ID`
164
    ///    - `AWS_SECRET_ACCESS_KEY`
165
    ///    - `AWS_DEFAULT_REGION`
166
    ///
167
    ///    **Example JSON Config:**
168
    ///    ```json
169
    ///    "experimental_cloud_object_store": {
170
    ///      "provider": "ontap",
171
    ///      "endpoint": "https://ontap-s3-endpoint:443",
172
    ///      "vserver_name": "your-vserver",
173
    ///      "bucket": "your-bucket",
174
    ///      "root_certificates": "/path/to/certs.pem",  // Optional
175
    ///      "key_prefix": "test-prefix/",               // Optional
176
    ///      "retry": {
177
    ///        "max_retries": 6,
178
    ///        "delay": 0.3,
179
    ///        "jitter": 0.5
180
    ///      },
181
    ///      "multipart_max_concurrent_uploads": 10
182
    ///    }
183
    ///    ```
184
    ///
185
    /// 5. **Cloudflare R2:**
186
    ///    R2 store uses Cloudflare's R2 service as a backend. R2 speaks the
187
    ///    S3 API, so this is a thin wrapper that derives the account-scoped
188
    ///    endpoint (`https://{account_id}.r2.cloudflarestorage.com`) for you.
189
    ///
190
    ///    **Example JSON Config:**
191
    ///    ```json
192
    ///    "experimental_cloud_object_store": {
193
    ///      "provider": "r2",
194
    ///      "account_id": "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4",
195
    ///      "bucket": "nativelink-cas",
196
    ///      "key_prefix": "test-prefix/",
197
    ///      "retry": {
198
    ///        "max_retries": 6,
199
    ///        "delay": 0.3,
200
    ///        "jitter": 0.5
201
    ///      },
202
    ///      "multipart_max_concurrent_uploads": 10
203
    ///    }
204
    ///    ```
205
    ///
206
    /// 6. **Oracle Cloud Infrastructure (OCI) Object Storage:**
207
    ///    OCI store uses Oracle Cloud Infrastructure's S3-compatible Object
208
    ///    Storage API. The path-style endpoint is derived from your Object
209
    ///    Storage `namespace` and `region` as
210
    ///    `https://{namespace}.compat.objectstorage.{region}.oci.customer-oci.com`.
211
    ///    Authenticate with a Customer Secret Key (Access Key/Secret Key pair
212
    ///    created under User Settings -> Customer secret keys in the OCI
213
    ///    console); the secret cannot be retrieved after generation, so read
214
    ///    it from an env var via shellexpand.
215
    ///
216
    ///    **Example JSON Config:**
217
    ///    ```json
218
    ///    "experimental_cloud_object_store": {
219
    ///      "provider": "oci",
220
    ///      "namespace": "your-object-storage-namespace",
221
    ///      "region": "us-phoenix-1",
222
    ///      "bucket": "nativelink-cas",
223
    ///      "access_key_id": "oci_access_key_id",
224
    ///      "secret_access_key": "oci_secret_access_key",
225
    ///      "key_prefix": "test-prefix/",
226
    ///      "retry": {
227
    ///        "max_retries": 6,
228
    ///        "delay": 0.3,
229
    ///        "jitter": 0.5
230
    ///      }
231
    ///    }
232
    ///    ```
233
    ///
234
    /// 7. **Alibaba Cloud OSS:**
235
    ///    Uses the OSS S3-compatible endpoint and AWS `SigV4`. Supply the OSS
236
    ///    access key explicitly per store, for example by shell-expanding
237
    ///    `OSS_ACCESS_KEY_ID` and `OSS_ACCESS_KEY_SECRET` in the config.
238
    ///    Set `cname` to true with an explicit HTTPS `endpoint` to use a custom
239
    ///    domain bound to the bucket, without adding the bucket to the host or
240
    ///    path. The default is false. Configure the domain binding, DNS, and
241
    ///    TLS certificate before starting the store.
242
    ///
243
    ///    **Example JSON Config:**
244
    ///    ```json
245
    ///    "experimental_cloud_object_store": {
246
    ///      "provider": "oss",
247
    ///      "region": "cn-hangzhou",
248
    ///      "bucket": "example-build-cache",
249
    ///      "access_key_id": "oss_access_key_id",
250
    ///      "secret_access_key": "oss_secret_access_key",
251
    ///      "cname": false,
252
    ///      "key_prefix": "cas/"
253
    ///    }
254
    ///    ```
255
    ExperimentalCloudObjectStore(ExperimentalCloudObjectSpec),
256
257
    /// ONTAP S3 Existence Cache provides a caching layer on top of the ONTAP S3 store
258
    /// to optimize repeated existence checks. It maintains an in-memory cache of object
259
    /// digests and periodically syncs this cache to disk for persistence.
260
    ///
261
    /// The cache helps reduce latency for repeated calls to check object existence,
262
    /// while still ensuring eventual consistency with the underlying ONTAP S3 store.
263
    ///
264
    /// Example JSON Config:
265
    /// ```json
266
    /// "ontap_s3_existence_cache": {
267
    ///   "index_path": "/path/to/cache/index.json",
268
    ///   "sync_interval_seconds": 300,
269
    ///   "backend": {
270
    ///     "endpoint": "https://ontap-s3-endpoint:443",
271
    ///     "vserver_name": "your-vserver",
272
    ///     "bucket": "your-bucket",
273
    ///     "key_prefix": "test-prefix/"
274
    ///   }
275
    /// }
276
    /// ```
277
    ///
278
    OntapS3ExistenceCache(Box<OntapS3ExistenceCacheSpec>),
279
280
    /// Verify store is used to apply verifications to an underlying
281
    /// store implementation. It is strongly encouraged to validate
282
    /// as much data as you can before accepting data from a client,
283
    /// failing to do so may cause the data in the store to be
284
    /// populated with invalid data causing all kinds of problems.
285
    ///
286
    /// The suggested configuration is to have the CAS validate the
287
    /// hash and size and the AC validate nothing.
288
    ///
289
    /// **Example JSON Config:**
290
    /// ```json
291
    /// "verify": {
292
    ///   "backend": {
293
    ///     "memory": {
294
    ///       "eviction_policy": {
295
    ///         "max_bytes": "500mb"
296
    ///       }
297
    ///     },
298
    ///   },
299
    ///   "verify_size": true,
300
    ///   "verify_hash": true
301
    /// }
302
    /// ```
303
    ///
304
    Verify(Box<VerifySpec>),
305
306
    /// Completeness checking store verifies if the
307
    /// output files & folders exist in the CAS before forwarding
308
    /// the request to the underlying store.
309
    /// Note: This store should only be used on AC stores.
310
    ///
311
    /// **Example JSON Config:**
312
    /// ```json
313
    /// "completeness_checking": {
314
    ///   "backend": {
315
    ///     "filesystem": {
316
    ///       "content_path": "~/.cache/nativelink/content_path-ac",
317
    ///       "temp_path": "~/.cache/nativelink/tmp_path-ac",
318
    ///       "eviction_policy": {
319
    ///         "max_bytes": "500mb",
320
    ///       }
321
    ///     }
322
    ///   },
323
    ///   "cas_store": {
324
    ///     "ref_store": {
325
    ///       "name": "CAS_MAIN_STORE"
326
    ///     }
327
    ///   }
328
    /// }
329
    /// ```
330
    ///
331
    CompletenessChecking(Box<CompletenessCheckingSpec>),
332
333
    /// A compression store that will compress the data inbound and
334
    /// outbound. There will be a non-trivial cost to compress and
335
    /// decompress the data, but in many cases if the final store is
336
    /// a store that requires network transport and/or storage space
337
    /// is a concern it is often faster and more efficient to use this
338
    /// store before those stores.
339
    ///
340
    /// **Example JSON Config:**
341
    /// ```json
342
    /// "compression": {
343
    ///   "compression_algorithm": {
344
    ///     "lz4": {}
345
    ///   },
346
    ///   "backend": {
347
    ///     "filesystem": {
348
    ///       "content_path": "/tmp/nativelink/data/content_path-cas",
349
    ///       "temp_path": "/tmp/nativelink/data/tmp_path-cas",
350
    ///       "eviction_policy": {
351
    ///         "max_bytes": "2gb",
352
    ///       }
353
    ///     }
354
    ///   }
355
    /// }
356
    /// ```
357
    ///
358
    Compression(Box<CompressionSpec>),
359
360
    /// A dedup store will take the inputs and run a rolling hash
361
    /// algorithm on them to slice the input into smaller parts then
362
    /// run a sha256 algorithm on the slice and if the object doesn't
363
    /// already exist, upload the slice to the `content_store` using
364
    /// a new digest of just the slice. Once all parts exist, an
365
    /// Action-Cache-like digest will be built and uploaded to the
366
    /// `index_store` which will contain a reference to each
367
    /// chunk/digest of the uploaded file. Downloading a request will
368
    /// first grab the index from the `index_store`, and forward the
369
    /// download content of each chunk as if it were one file.
370
    ///
371
    /// This store is exceptionally good when the following conditions
372
    /// are met:
373
    /// * Content is mostly the same (inserts, updates, deletes are ok)
374
    /// * Content is not compressed or encrypted
375
    /// * Uploading or downloading from `content_store` is the bottleneck.
376
    ///
377
    /// Note: This store pairs well when used with `CompressionSpec` as
378
    /// the `content_store`, but never put `DedupSpec` as the backend of
379
    /// `CompressionSpec` as it will negate all the gains.
380
    ///
381
    /// Note: When running `.has()` on this store, it will only check
382
    /// to see if the entry exists in the `index_store` and not check
383
    /// if the individual chunks exist in the `content_store`.
384
    ///
385
    /// **Example JSON Config:**
386
    /// ```json
387
    /// "dedup": {
388
    ///   "index_store": {
389
    ///     "memory": {
390
    ///       "eviction_policy": {
391
    ///          "max_bytes": "1GB",
392
    ///       }
393
    ///     }
394
    ///   },
395
    ///   "content_store": {
396
    ///     "compression": {
397
    ///       "compression_algorithm": {
398
    ///         "lz4": {}
399
    ///       },
400
    ///       "backend": {
401
    ///         "fast_slow": {
402
    ///           "fast": {
403
    ///             "memory": {
404
    ///               "eviction_policy": {
405
    ///                 "max_bytes": "500MB",
406
    ///               }
407
    ///             }
408
    ///           },
409
    ///           "slow": {
410
    ///             "filesystem": {
411
    ///               "content_path": "/tmp/nativelink/data/content_path-content",
412
    ///               "temp_path": "/tmp/nativelink/data/tmp_path-content",
413
    ///               "eviction_policy": {
414
    ///                 "max_bytes": "2gb"
415
    ///               }
416
    ///             }
417
    ///           }
418
    ///         }
419
    ///       }
420
    ///     }
421
    ///   }
422
    /// }
423
    /// ```
424
    ///
425
    Dedup(Box<DedupSpec>),
426
427
    /// Existence store will wrap around another store and cache calls
428
    /// to has so that subsequent `has_with_results` calls will be
429
    /// faster. This is useful for cases when you have a store that
430
    /// is slow to respond to has calls.
431
    /// Note: This store should only be used on CAS stores.
432
    ///
433
    /// **Example JSON Config:**
434
    /// ```json
435
    /// "existence_cache": {
436
    ///   "backend": {
437
    ///     "memory": {
438
    ///       "eviction_policy": {
439
    ///         "max_bytes": "500mb",
440
    ///       }
441
    ///     }
442
    ///   },
443
    ///   // Note this is the existence store policy, not the backend policy
444
    ///   "eviction_policy": {
445
    ///     "max_seconds": 100,
446
    ///   }
447
    /// }
448
    /// ```
449
    ///
450
    ExistenceCache(Box<ExistenceCacheSpec>),
451
452
    /// `FastSlow` store will first try to fetch the data from the `fast`
453
    /// store and then if it does not exist try the `slow` store.
454
    /// When the object does exist in the `slow` store, it will copy
455
    /// the data to the `fast` store while returning the data.
456
    /// This store should be thought of as a store that "buffers"
457
    /// the data to the `fast` store.
458
    /// On uploads it will mirror data to both `fast` and `slow` stores.
459
    ///
460
    /// WARNING: If you need data to always exist in the `slow` store
461
    /// for something like remote execution, be careful because this
462
    /// store will never check to see if the objects exist in the
463
    /// `slow` store if it exists in the `fast` store (i.e. it assumes
464
    /// that if an object exists in the `fast` store it will exist in
465
    /// the `slow` store).
466
    ///
467
    /// ***Example JSON Config:***
468
    /// ```json
469
    /// "fast_slow": {
470
    ///   "fast": {
471
    ///     "filesystem": {
472
    ///       "content_path": "/tmp/nativelink/data/content_path-index",
473
    ///       "temp_path": "/tmp/nativelink/data/tmp_path-index",
474
    ///       "eviction_policy": {
475
    ///         "max_bytes": "500mb",
476
    ///       }
477
    ///     }
478
    ///   },
479
    ///   "slow": {
480
    ///     "filesystem": {
481
    ///       "content_path": "/tmp/nativelink/data/content_path-index",
482
    ///       "temp_path": "/tmp/nativelink/data/tmp_path-index",
483
    ///       "eviction_policy": {
484
    ///         "max_bytes": "500mb",
485
    ///       }
486
    ///     }
487
    ///   }
488
    /// }
489
    /// ```
490
    ///
491
    FastSlow(Box<FastSlowSpec>),
492
493
    /// Shards the data to multiple stores. This is useful for cases
494
    /// when you want to distribute the load across multiple stores.
495
    /// The digest hash is used to determine which store to send the
496
    /// data to.
497
    ///
498
    /// **Example JSON Config:**
499
    /// ```json
500
    /// "shard": {
501
    ///   "stores": [
502
    ///    {
503
    ///     "store": {
504
    ///       "memory": {
505
    ///         "eviction_policy": {
506
    ///             "max_bytes": "10mb"
507
    ///         },
508
    ///       },
509
    ///     },
510
    ///     "weight": 1
511
    ///   }]
512
    /// }
513
    /// ```
514
    ///
515
    Shard(ShardSpec),
516
517
    /// Stores the data on the filesystem. This store is designed for
518
    /// local persistent storage. Restarts of this program should restore
519
    /// the previous state, meaning anything uploaded will be persistent
520
    /// as long as the filesystem integrity holds.
521
    ///
522
    /// **Example JSON Config:**
523
    /// ```json
524
    /// "filesystem": {
525
    ///   "content_path": "/tmp/nativelink/data-worker-test/content_path-cas",
526
    ///   "temp_path": "/tmp/nativelink/data-worker-test/tmp_path-cas",
527
    ///   "eviction_policy": {
528
    ///     "max_bytes": "10gb",
529
    ///   }
530
    /// }
531
    /// ```
532
    ///
533
    Filesystem(FilesystemSpec),
534
535
    /// Store used to reference a store in the root store manager.
536
    /// This is useful for cases when you want to share a store in different
537
    /// nested stores. Example, you may want to share the same memory store
538
    /// used for the action cache, but use a `FastSlowSpec` and have the fast
539
    /// store also share the memory store for efficiency.
540
    ///
541
    /// **Example JSON Config:**
542
    /// ```json
543
    /// "ref_store": {
544
    ///   "name": "FS_CONTENT_STORE"
545
    /// }
546
    /// ```
547
    ///
548
    RefStore(RefSpec),
549
550
    /// Uses the size field of the digest to separate which store to send the
551
    /// data. This is useful for cases when you'd like to put small objects
552
    /// in one store and large objects in another store. This should only be
553
    /// used if the size field is the real size of the content, in other
554
    /// words, don't use on AC (Action Cache) stores. Any store where you can
555
    /// safely use `VerifySpec.verify_size = true`, this store should be safe
556
    /// to use (i.e. CAS stores).
557
    ///
558
    /// **Example JSON Config:**
559
    /// ```json
560
    /// "size_partitioning": {
561
    ///   "size": "128mib",
562
    ///   "lower_store": {
563
    ///     "memory": {
564
    ///       "eviction_policy": {
565
    ///         "max_bytes": "${NATIVELINK_CAS_MEMORY_CONTENT_LIMIT:-100mb}"
566
    ///       }
567
    ///     }
568
    ///   },
569
    ///   "upper_store": {
570
    ///     /// This store discards data larger than 128mib.
571
    ///     "noop": {}
572
    ///   }
573
    /// }
574
    /// ```
575
    ///
576
    SizePartitioning(Box<SizePartitioningSpec>),
577
578
    /// This store will pass-through calls to another gRPC store. This store
579
    /// is not designed to be used as a sub-store of another store, but it
580
    /// does satisfy the interface and will likely work.
581
    ///
582
    /// One major GOTCHA is that some stores use a special function on this
583
    /// store to get the size of the underlying object, which is only reliable
584
    /// when this store is serving the a CAS store, not an AC store. If using
585
    /// this store directly without being a child of any store there are no
586
    /// side effects and is the most efficient way to use it.
587
    ///
588
    /// **Example JSON Config:**
589
    /// ```json
590
    /// "grpc": {
591
    ///   "instance_name": "main",
592
    ///   "endpoints": [
593
    ///     {"address": "grpc://${CAS_ENDPOINT:-127.0.0.1}:50051"}
594
    ///   ],
595
    ///   "connections_per_endpoint": "5",
596
    ///   "rpc_timeout_s": "5m",
597
    ///   "store_type": "ac",
598
    ///   // Static headers attached to every outgoing request to the upstream
599
    ///   // remote cache. Useful for fixed service-account credentials.
600
    ///   "headers": {
601
    ///     "authorization": "Bearer my-static-token"
602
    ///   },
603
    ///   // Header names to copy from the inbound client request and forward to
604
    ///   // the upstream remote cache. Use this to pass through dynamic
605
    ///   // credentials such as a JWT sent by the build client.
606
    ///   "forward_headers": ["authorization", "x-custom-token"]
607
    /// }
608
    /// ```
609
    ///
610
    Grpc(GrpcSpec),
611
612
    /// Stores data in any stores compatible with Redis APIs.
613
    ///
614
    /// Pairs well with `SizePartitioning` and/or `FastSlow` stores.
615
    /// Ideal for accepting small object sizes as most redis store
616
    /// services have a max file upload of between 256Mb-512Mb.
617
    ///
618
    /// If you are using Redis together with any stores above it
619
    /// e.g. existence cache, you will need to configure `notify-keyspace-events`
620
    /// to `KA` as per <https://redis.io/docs/latest/develop/pubsub/keyspace-notifications/#configuration>
621
    /// in order for us to get eviction events. Failing to do so will get you
622
    /// log messages complaining about it, as well as errors like <https://github.com/TraceMachina/nativelink/issues/2436>
623
    ///
624
    /// **Example JSON Config:**
625
    /// ```json
626
    /// "redis_store": {
627
    ///   "addresses": [
628
    ///     "redis://127.0.0.1:6379/",
629
    ///   ],
630
    ///   "max_client_permits": 1000,
631
    /// }
632
    /// ```
633
    ///
634
    RedisStore(RedisSpec),
635
636
    /// Noop store is a store that sends streams into the void and all data
637
    /// retrieval will return 404 (`NotFound`). This can be useful for cases
638
    /// where you may need to partition your data and part of your data needs
639
    /// to be discarded.
640
    ///
641
    /// **Example JSON Config:**
642
    /// ```json
643
    /// "noop": {}
644
    /// ```
645
    ///
646
    Noop(NoopSpec),
647
648
    /// Experimental `MongoDB` store implementation.
649
    ///
650
    /// This store uses `MongoDB` as a backend for storing data. It supports
651
    /// both CAS (Content Addressable Storage) and scheduler data with
652
    /// optional change streams for real-time updates.
653
    ///
654
    /// **Example JSON Config:**
655
    /// ```json
656
    /// "experimental_mongo": {
657
    ///     "connection_string": "mongodb://localhost:27017",
658
    ///     "database": "nativelink",
659
    ///     "cas_collection": "cas",
660
    ///     "key_prefix": "cas:",
661
    ///     "read_chunk_size": 65536,
662
    ///     "max_concurrent_uploads": 10,
663
    ///     "enable_change_streams": false,
664
    ///     "max_requests": "100"
665
    /// }
666
    /// ```
667
    ///
668
    ExperimentalMongo(ExperimentalMongoSpec),
669
}
670
671
impl StoreSpec {
672
291
    pub(crate) fn visit_grpc_specs(&self, visitor: &mut dyn FnMut(&GrpcSpec)) {
673
291
        match self {
674
1
            Self::CacheMetrics(spec) => spec.backend.visit_grpc_specs(visitor),
675
9
            Self::Verify(spec) => spec.backend.visit_grpc_specs(visitor),
676
15
            Self::Compression(spec) => spec.backend.visit_grpc_specs(visitor),
677
9
            Self::Dedup(spec) => {
678
9
                spec.index_store.visit_grpc_specs(visitor);
679
9
                spec.content_store.visit_grpc_specs(visitor);
680
9
            }
681
2
            Self::ExistenceCache(spec) => spec.backend.visit_grpc_specs(visitor),
682
2
            Self::CompletenessChecking(spec) => {
683
2
                spec.backend.visit_grpc_specs(visitor);
684
2
                spec.cas_store.visit_grpc_specs(visitor);
685
2
            }
686
43
            Self::FastSlow(spec) => {
687
43
                spec.fast.visit_grpc_specs(visitor);
688
43
                spec.slow.visit_grpc_specs(visitor);
689
43
            }
690
2
            Self::Shard(spec) => {
691
3
                for shard in 
&spec.stores2
{
692
3
                    shard.store.visit_grpc_specs(visitor);
693
3
                }
694
            }
695
4
            Self::SizePartitioning(spec) => {
696
4
                spec.lower_store.visit_grpc_specs(visitor);
697
4
                spec.upper_store.visit_grpc_specs(visitor);
698
4
            }
699
22
            Self::Grpc(spec) => visitor(spec),
700
            Self::Memory(_)
701
            | Self::ExperimentalCloudObjectStore(_)
702
            | Self::OntapS3ExistenceCache(_)
703
            | Self::Filesystem(_)
704
            | Self::RefStore(_)
705
            | Self::RedisStore(_)
706
            | Self::Noop(_)
707
182
            | Self::ExperimentalMongo(_) => {}
708
        }
709
291
    }
710
711
287
    pub(crate) fn visit_grpc_specs_mut(&mut self, visitor: &mut dyn FnMut(&mut GrpcSpec)) {
712
287
        match self {
713
1
            Self::CacheMetrics(spec) => spec.backend.visit_grpc_specs_mut(visitor),
714
9
            Self::Verify(spec) => spec.backend.visit_grpc_specs_mut(visitor),
715
15
            Self::Compression(spec) => spec.backend.visit_grpc_specs_mut(visitor),
716
9
            Self::Dedup(spec) => {
717
9
                spec.index_store.visit_grpc_specs_mut(visitor);
718
9
                spec.content_store.visit_grpc_specs_mut(visitor);
719
9
            }
720
2
            Self::ExistenceCache(spec) => spec.backend.visit_grpc_specs_mut(visitor),
721
2
            Self::CompletenessChecking(spec) => {
722
2
                spec.backend.visit_grpc_specs_mut(visitor);
723
2
                spec.cas_store.visit_grpc_specs_mut(visitor);
724
2
            }
725
43
            Self::FastSlow(spec) => {
726
43
                spec.fast.visit_grpc_specs_mut(visitor);
727
43
                spec.slow.visit_grpc_specs_mut(visitor);
728
43
            }
729
2
            Self::Shard(spec) => {
730
3
                for shard in 
&mut spec.stores2
{
731
3
                    shard.store.visit_grpc_specs_mut(visitor);
732
3
                }
733
            }
734
4
            Self::SizePartitioning(spec) => {
735
4
                spec.lower_store.visit_grpc_specs_mut(visitor);
736
4
                spec.upper_store.visit_grpc_specs_mut(visitor);
737
4
            }
738
18
            Self::Grpc(spec) => visitor(spec),
739
            Self::Memory(_)
740
            | Self::ExperimentalCloudObjectStore(_)
741
            | Self::OntapS3ExistenceCache(_)
742
            | Self::Filesystem(_)
743
            | Self::RefStore(_)
744
            | Self::RedisStore(_)
745
            | Self::Noop(_)
746
182
            | Self::ExperimentalMongo(_) => {}
747
        }
748
287
    }
749
}
750
751
/// Configuration for an individual shard of the store.
752
#[derive(Serialize, Deserialize, Debug, Clone)]
753
#[serde(deny_unknown_fields)]
754
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
755
pub struct ShardConfig {
756
    /// Store to shard the data to.
757
    pub store: StoreSpec,
758
759
    /// The weight of the store. This is used to determine how much data
760
    /// should be sent to the store. The actual percentage is the sum of
761
    /// all the store's weights divided by the individual store's weight.
762
    ///
763
    /// Default: 1
764
    #[serde(deserialize_with = "convert_optional_numeric_with_shellexpand")]
765
    pub weight: Option<u32>,
766
}
767
768
#[derive(Serialize, Deserialize, Debug, Clone)]
769
#[serde(deny_unknown_fields)]
770
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
771
pub struct ShardSpec {
772
    /// Stores to shard the data to.
773
    pub stores: Vec<ShardConfig>,
774
}
775
776
#[derive(Serialize, Deserialize, Debug, Clone)]
777
#[serde(deny_unknown_fields)]
778
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
779
pub struct CacheMetricsSpec {
780
    /// Low-cardinality cache type label for metrics, for example `cas` or `ac`.
781
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
782
    pub cache_type: String,
783
784
    /// Allow repair requests to remove the backend's copy. Defaults to false.
785
    /// Enable only for disposable cache tiers with a separate correct copy to
786
    /// refill from. Memory and filesystem stores evict when asked, even if
787
    /// they hold the only copy. Keep this disabled when wrapping such a tier.
788
    /// This only gates removal through this wrapper, not the backend's own
789
    /// eviction policy. Place the wrapper around the tier inside the verifier.
790
    #[serde(default, deserialize_with = "convert_boolean_with_shellexpand")]
791
    pub allow_remove: bool,
792
793
    /// Store to wrap with cache operation metrics.
794
    pub backend: StoreSpec,
795
}
796
797
#[derive(Serialize, Deserialize, Debug, Clone)]
798
#[serde(deny_unknown_fields)]
799
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
800
pub struct SizePartitioningSpec {
801
    /// Size to partition the data on.
802
    #[serde(deserialize_with = "convert_data_size_with_shellexpand")]
803
    pub size: u64,
804
805
    /// Store to send data when object is < (less than) size.
806
    pub lower_store: StoreSpec,
807
808
    /// Store to send data when object is >= (less than eq) size.
809
    pub upper_store: StoreSpec,
810
}
811
812
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
813
#[serde(deny_unknown_fields)]
814
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
815
pub struct RefSpec {
816
    /// Name of the store under the root "stores" config object.
817
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
818
    pub name: String,
819
}
820
821
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
822
#[serde(deny_unknown_fields)]
823
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
824
pub struct FilesystemSpec {
825
    /// Path on the system where to store the actual content. This is where
826
    /// the bulk of the data will be placed.
827
    /// On service boot this folder will be scanned and all files will be
828
    /// added to the cache. In the event one of the files doesn't match the
829
    /// criteria, the file will be deleted.
830
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
831
    pub content_path: String,
832
833
    /// A temporary location of where files that are being uploaded or
834
    /// deleted will be placed while the content cannot be guaranteed to be
835
    /// accurate. This location must be on the same block device as
836
    /// `content_path` so atomic moves can happen (i.e. move without copy).
837
    /// All files in this folder will be deleted on every startup.
838
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
839
    pub temp_path: String,
840
841
    /// Buffer size to use when reading files. Generally this should be left
842
    /// to the default value except for testing.
843
    /// Default: 32k.
844
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
845
    pub read_buffer_size: u32,
846
847
    /// Policy used to evict items out of the store. Failure to set this
848
    /// value will cause items to never be removed from the store causing
849
    /// infinite memory usage.
850
    pub eviction_policy: Option<EvictionPolicy>,
851
852
    /// The block size of the filesystem for the running machine
853
    /// value is used to determine an entry's actual size on disk consumed
854
    /// For a 4KB block size filesystem, a 1B file actually consumes 4KB
855
    /// Default: 4kb
856
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
857
    pub block_size: u64,
858
859
    /// Maximum number of concurrent write operations allowed.
860
    /// Each write involves streaming data to a temp file and calling `sync_all()`,
861
    /// which can saturate disk I/O when many writes happen simultaneously.
862
    /// Limiting concurrency prevents disk saturation from blocking the async
863
    /// runtime.
864
    /// A value of 0 means unlimited (no concurrency limit).
865
    /// Default: unlimited
866
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
867
    pub max_concurrent_writes: usize,
868
869
    /// When true, advise the kernel to drop the page cache for each blob after
870
    /// it is written or read (`posix_fadvise` with `POSIX_FADV_DONTNEED`). On
871
    /// real filesystems this takes a globally serialized, all-CPU kernel path
872
    /// that stalls on many-core hosts, and it evicts the page-cache tier that
873
    /// fast-disk deployments rely on. Leave off unless you specifically want to
874
    /// keep this store's I/O out of the page cache.
875
    /// Default: false
876
    #[serde(default)]
877
    pub evict_page_cache: bool,
878
}
879
880
// NetApp ONTAP S3 Spec
881
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
882
#[serde(deny_unknown_fields)]
883
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
884
pub struct ExperimentalOntapS3Spec {
885
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
886
    pub endpoint: String,
887
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
888
    pub vserver_name: String,
889
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
890
    pub bucket: String,
891
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
892
    pub root_certificates: Option<String>,
893
894
    /// Common retry and upload configuration
895
    #[serde(flatten)]
896
    pub common: CommonObjectSpec,
897
}
898
899
// Cloudflare R2 Spec
900
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
901
#[serde(deny_unknown_fields)]
902
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
903
pub struct ExperimentalR2Spec {
904
    /// Cloudflare account ID. Endpoint is derived as
905
    /// `https://{account_id}.r2.cloudflarestorage.com`.
906
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
907
    pub account_id: String,
908
909
    /// Bucket name to use as the backend.
910
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
911
    pub bucket: String,
912
913
    /// Explicit R2 access key.
914
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
915
    pub access_key_id: Option<String>,
916
917
    /// Explicit R2 secret key.
918
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
919
    pub secret_access_key: Option<String>,
920
921
    /// Retry and upload settings.
922
    #[serde(flatten)]
923
    pub common: CommonObjectSpec,
924
}
925
926
// Oracle Cloud Infrastructure (OCI) Object Storage Spec.
927
//
928
// Uses the OCI Object Storage Amazon S3 Compatibility API. The store talks to
929
// the path-style compatibility endpoint, which embeds the Object Storage
930
// namespace in the host and the bucket in the request path:
931
// `https://{namespace}.compat.objectstorage.{region}.oci.customer-oci.com/{bucket}/{object}`.
932
// Authentication uses a Customer Secret Key (an Access Key/Secret Key pair
933
// generated under User Settings in the OCI console) signed with AWS SigV4.
934
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
935
#[serde(deny_unknown_fields)]
936
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
937
pub struct ExperimentalOciSpec {
938
    /// OCI Object Storage namespace. This is the immutable, system-generated
939
    /// top-level container assigned to the tenancy (the same name in every
940
    /// region). It is the host prefix of the derived path-style endpoint:
941
    /// `https://{namespace}.compat.objectstorage.{region}.oci.customer-oci.com`.
942
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
943
    pub namespace: String,
944
945
    /// OCI region identifier, for example `us-phoenix-1` or `us-ashburn-1`.
946
    /// Used both to build the endpoint host and as the AWS `SigV4` signing
947
    /// region. If your tooling cannot set an OCI region identifier, OCI also
948
    /// accepts `us-east-1` to target the tenancy home region.
949
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
950
    pub region: String,
951
952
    /// Bucket name to use as the backend. Bucket names must be unique within
953
    /// the Object Storage namespace.
954
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
955
    pub bucket: String,
956
957
    /// Customer Secret Key access key. When omitted (along with
958
    /// `secret_access_key`), the default AWS credential chain is used instead.
959
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
960
    pub access_key_id: Option<String>,
961
962
    /// Customer Secret Key secret. OCI does not allow retrieving a secret key
963
    /// after generation, so store it securely (for example via `${ENV_VAR}`
964
    /// shell expansion).
965
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
966
    pub secret_access_key: Option<String>,
967
968
    /// Retry and upload settings.
969
    #[serde(flatten)]
970
    pub common: CommonObjectSpec,
971
}
972
973
/// Alibaba Cloud OSS through its S3-compatible API.
974
#[derive(Serialize, Deserialize, Default, Clone)]
975
#[serde(deny_unknown_fields)]
976
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
977
pub struct ExperimentalOssSpec {
978
    /// OSS region, for example `cn-hangzhou`. Used for AWS `SigV4` signing
979
    /// and to derive the default S3-compatible endpoint.
980
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
981
    pub region: String,
982
983
    /// Bucket name to use as the backend.
984
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
985
    pub bucket: String,
986
987
    /// Access key ID for this store. Required; no AWS credential-chain fallback.
988
    /// Use shell expansion, for example `${OSS_ACCESS_KEY_ID}`.
989
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
990
    pub access_key_id: String,
991
992
    /// Access key secret for this store. Use `${OSS_ACCESS_KEY_SECRET}` to
993
    /// keep it out of the config file. Independent of AWS S3 store credentials.
994
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
995
    pub secret_access_key: String,
996
997
    /// Optional STS token for this store, for example `${OSS_SESSION_TOKEN}`.
998
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
999
    pub session_token: Option<String>,
1000
1001
    /// Optional HTTPS S3-compatible service endpoint, without a bucket or path.
1002
    /// Default: `https://s3.oss-{region}.aliyuncs.com`.
1003
    /// With `cname: true`, this must be the custom domain bound to the bucket.
1004
    /// Native OSS REST endpoints are not interchangeable with this endpoint.
1005
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
1006
    pub endpoint: Option<String>,
1007
1008
    /// Use `endpoint` as the bucket's custom domain without adding the bucket
1009
    /// to the host or path. Requires an explicit HTTPS endpoint, an OSS domain
1010
    /// binding, and a valid certificate for that domain. Default: false.
1011
    #[serde(default)]
1012
    pub cname: bool,
1013
1014
    /// Prefix prepended verbatim to each object key, for example `cas/`.
1015
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
1016
    pub key_prefix: Option<String>,
1017
1018
    /// Retry policy for the shared S3 store. SDK retries are disabled to avoid
1019
    /// multiplying attempts. Default: the standard store retry policy.
1020
    #[serde(default)]
1021
    pub retry: Retry,
1022
1023
    /// Maximum concurrent part requests per upload. Must be positive.
1024
    /// Default: 2. Queued parts are bounded by the same count; this is not
1025
    /// a global byte budget. Part size is chosen by the shared S3 store.
1026
    #[serde(
1027
        default,
1028
        deserialize_with = "convert_optional_numeric_with_shellexpand"
1029
    )]
1030
    pub multipart_max_concurrent_uploads: Option<usize>,
1031
}
1032
1033
impl core::fmt::Debug for ExperimentalOssSpec {
1034
1
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1035
1
        f.debug_struct("ExperimentalOssSpec")
1036
1
            .field("region", &self.region)
1037
1
            .field("bucket", &self.bucket)
1038
1
            .field("endpoint", &self.endpoint)
1039
1
            .field("cname", &self.cname)
1040
1
            .field("key_prefix", &self.key_prefix)
1041
1
            .field("retry", &self.retry)
1042
1
            .field(
1043
1
                "multipart_max_concurrent_uploads",
1044
1
                &self.multipart_max_concurrent_uploads,
1045
1
            )
1046
1
            .field("credentials", &"<redacted>")
1047
1
            .finish()
1048
1
    }
1049
}
1050
1051
#[derive(Serialize, Deserialize, Debug, Clone)]
1052
#[serde(deny_unknown_fields)]
1053
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1054
pub struct OntapS3ExistenceCacheSpec {
1055
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
1056
    pub index_path: String,
1057
    #[serde(deserialize_with = "convert_numeric_with_shellexpand")]
1058
    pub sync_interval_seconds: u32,
1059
    pub backend: Box<ExperimentalOntapS3Spec>,
1060
}
1061
1062
#[derive(Serialize, Deserialize, Default, Debug, Clone, Copy, PartialEq, Eq)]
1063
#[serde(rename_all = "snake_case")]
1064
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1065
pub enum StoreDirection {
1066
    /// The store operates normally and all get and put operations are
1067
    /// handled by it.
1068
    #[default]
1069
    Both,
1070
    /// Update operations will cause persistence to this store, but Get
1071
    /// operations will be ignored.
1072
    /// This only makes sense on the fast store as the slow store will
1073
    /// never get written to on Get anyway.
1074
    Update,
1075
    /// Get operations will cause persistence to this store, but Update
1076
    /// operations will be ignored.
1077
    Get,
1078
    /// Operate as a read only store, only really makes sense if there's
1079
    /// another way to write to it.
1080
    ReadOnly,
1081
}
1082
1083
#[derive(Serialize, Deserialize, Debug, Clone)]
1084
#[serde(deny_unknown_fields)]
1085
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1086
pub struct FastSlowSpec {
1087
    /// Fast store that will be attempted to be contacted before reaching
1088
    /// out to the `slow` store.
1089
    pub fast: StoreSpec,
1090
1091
    /// How to handle the fast store. This can be useful to set to Get for
1092
    /// worker nodes such that results are persisted to the slow store only.
1093
    #[serde(default)]
1094
    pub fast_direction: StoreDirection,
1095
1096
    /// If the object does not exist in the `fast` store it will try to
1097
    /// get it from this store.
1098
    pub slow: StoreSpec,
1099
1100
    /// How to handle the slow store. This can be useful if creating a diode
1101
    /// and you wish to have an upstream read only store.
1102
    #[serde(default)]
1103
    pub slow_direction: StoreDirection,
1104
1105
    /// Reads of blobs at or above this size skip the leader/follower dedup
1106
    /// map and stream straight from the slow store without populating the
1107
    /// fast tier. `0` (the default) disables the bypass: every read goes
1108
    /// through dedup, matching the prior behaviour. Enable it by setting a
1109
    /// threshold — 256 MiB is a reasonable starting point for backends where
1110
    /// large-blob dedup is a net loss (followers tend to time out anyway),
1111
    /// but the right value is workload-dependent.
1112
    /// Default: disabled (0)
1113
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
1114
    pub bypass_dedup_threshold_bytes: u64,
1115
1116
    /// Maximum seconds an existence check (`has`, which serves
1117
    /// `FindMissingBlobs` and upload checks) waits on a key whose
1118
    /// slow-store write is still in flight before reporting the key
1119
    /// missing. The clock runs from when the write registered, not per
1120
    /// call, so a wedged write delays existence checks at most once. A
1121
    /// missing report costs at worst a duplicate upload of a blob that was
1122
    /// landing anyway — or, through a completeness check over an action
1123
    /// result, a rebuild of that action — while an unbounded wait hands
1124
    /// every existence check a wedged writer's fate. Size it under your
1125
    /// clients' own deadlines (Bazel's default `--remote_timeout` is 60)
1126
    /// and above your slow store's usual worst-case write; 30 is a sound
1127
    /// starting point. `0` (the default) waits indefinitely — the behavior
1128
    /// before this field existed — so nothing changes until it is set.
1129
    /// Default: 0 (wait indefinitely)
1130
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1131
    pub has_slow_write_wait_timeout_s: usize,
1132
1133
    /// Maximum seconds a cache fill (the read that populates the fast tier
1134
    /// from the slow tier while streaming to its reader) may go without
1135
    /// moving a single byte before it fails with `DEADLINE_EXCEEDED`. Only
1136
    /// the stalled fill fails: its dedup entry is removed so the next
1137
    /// reader of the key leads a fresh fill, and followers already fall
1138
    /// back to reading the slow store directly after their own bounded
1139
    /// wait. The clock measures inactivity and resets on every chunk — a
1140
    /// whole-transfer deadline would be wrong here, because a
1141
    /// multi-gigabyte blob legitimately streams for minutes. The same
1142
    /// timeout bounds the sizing `has()` the fill issues first, and a
1143
    /// transfer that has fully moved gets one further window for the fast
1144
    /// tier's commit — grace enough that a completed fill is not discarded
1145
    /// over a slow local sync, still a bound when the fast tier is a
1146
    /// remote store whose commit can wedge.
1147
    /// `0` (the default) keeps today's behavior: no inactivity bound.
1148
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1149
    pub leader_inactivity_timeout_s: usize,
1150
}
1151
1152
#[derive(Serialize, Deserialize, Debug, Default, Clone, Copy)]
1153
#[serde(deny_unknown_fields)]
1154
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1155
pub struct MemorySpec {
1156
    /// Policy used to evict items out of the store. Failure to set this
1157
    /// value will cause items to never be removed from the store causing
1158
    /// infinite memory usage.
1159
    pub eviction_policy: Option<EvictionPolicy>,
1160
}
1161
1162
#[derive(Serialize, Deserialize, Debug, Clone)]
1163
#[serde(deny_unknown_fields)]
1164
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1165
pub struct DedupSpec {
1166
    /// Store used to store the index of each dedup slice. This store
1167
    /// should generally be fast and small.
1168
    pub index_store: StoreSpec,
1169
1170
    /// The store where the individual chunks will be uploaded. This
1171
    /// store should generally be the slower & larger store.
1172
    pub content_store: StoreSpec,
1173
1174
    /// Minimum size that a chunk will be when slicing up the content.
1175
    /// Note: This setting can be increased to improve performance
1176
    /// because it will actually not check this number of bytes when
1177
    /// deciding where to partition the data.
1178
    ///
1179
    /// Default: 64k
1180
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
1181
    pub min_size: u32,
1182
1183
    /// A best-effort attempt will be made to keep the average size
1184
    /// of the chunks to this number. It is not a guarantee, but a
1185
    /// slight attempt will be made.
1186
    ///
1187
    /// This value will also be about the threshold used to determine
1188
    /// if we should even attempt to dedup the entry or just forward
1189
    /// it directly to the `content_store` without an index. The actual
1190
    /// value will be about `normal_size * 1.3` due to implementation
1191
    /// details.
1192
    ///
1193
    /// Default: 256k
1194
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
1195
    pub normal_size: u32,
1196
1197
    /// Maximum size a chunk is allowed to be.
1198
    ///
1199
    /// Default: 512k
1200
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
1201
    pub max_size: u32,
1202
1203
    /// Due to implementation detail, we want to prefer to download
1204
    /// the first chunks of the file so we can stream the content
1205
    /// out and free up some of our buffers. This configuration
1206
    /// will be used to restrict the number of concurrent chunk
1207
    /// downloads at a time per `get()` request.
1208
    ///
1209
    /// This setting will also affect how much memory might be used
1210
    /// per `get()` request. Estimated worst case memory per `get()`
1211
    /// request is: `max_concurrent_fetch_per_get * max_size`.
1212
    ///
1213
    /// Default: 10
1214
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1215
    pub max_concurrent_fetch_per_get: u32,
1216
}
1217
1218
#[derive(Serialize, Deserialize, Debug, Clone)]
1219
#[serde(deny_unknown_fields)]
1220
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1221
pub struct ExistenceCacheSpec {
1222
    /// The underlying store wrap around. All content will first flow
1223
    /// through self before forwarding to backend. In the event there
1224
    /// is an error detected in self, the connection to the backend
1225
    /// will be terminated, and early termination should always cause
1226
    /// updates to fail on the backend.
1227
    pub backend: StoreSpec,
1228
1229
    /// Policy used to evict items out of the store. Failure to set this
1230
    /// value will cause items to never be removed from the store causing
1231
    /// infinite memory usage.
1232
    pub eviction_policy: Option<EvictionPolicy>,
1233
}
1234
1235
#[derive(Serialize, Deserialize, Debug, Clone)]
1236
#[serde(deny_unknown_fields)]
1237
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1238
pub struct VerifySpec {
1239
    /// The underlying store wrap around. All content will first flow
1240
    /// through self before forwarding to backend. In the event there
1241
    /// is an error detected in self, the connection to the backend
1242
    /// will be terminated, and early termination should always cause
1243
    /// updates to fail on the backend.
1244
    pub backend: StoreSpec,
1245
1246
    /// If set the store will verify the size of the data before accepting
1247
    /// an upload of data.
1248
    ///
1249
    /// This should be set to false for AC, but true for CAS stores.
1250
    #[serde(default, deserialize_with = "convert_boolean_with_shellexpand")]
1251
    pub verify_size: bool,
1252
1253
    /// If the data should be hashed and verify that the key matches the
1254
    /// computed hash. The hash function is automatically determined based
1255
    /// request and if not set will use the global default.
1256
    ///
1257
    /// This should be set to false for AC, but true for CAS stores.
1258
    #[serde(default, deserialize_with = "convert_boolean_with_shellexpand")]
1259
    pub verify_hash: bool,
1260
}
1261
1262
#[derive(Serialize, Deserialize, Debug, Clone)]
1263
#[serde(deny_unknown_fields)]
1264
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1265
pub struct CompletenessCheckingSpec {
1266
    /// The underlying store that will have it's results validated before sending to client.
1267
    pub backend: StoreSpec,
1268
1269
    /// When a request is made, the results are decoded and all output digests/files are verified
1270
    /// to exist in this CAS store before returning success.
1271
    pub cas_store: StoreSpec,
1272
}
1273
1274
#[derive(Serialize, Deserialize, Debug, Default, PartialEq, Eq, Clone, Copy)]
1275
#[serde(deny_unknown_fields)]
1276
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1277
pub struct Lz4Config {
1278
    /// Size of the blocks to compress.
1279
    /// Higher values require more ram, but might yield slightly better
1280
    /// compression ratios.
1281
    ///
1282
    /// Default: 65536 (64k).
1283
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
1284
    pub block_size: u32,
1285
1286
    /// Maximum size allowed to attempt to deserialize data into.
1287
    /// This is needed because the `block_size` is embedded into the data
1288
    /// so if there was a bad actor, they could upload an extremely large
1289
    /// `block_size`'ed entry and we'd allocate a large amount of memory
1290
    /// when retrieving the data. To prevent this from happening, we
1291
    /// allow you to specify the maximum that we'll attempt to deserialize.
1292
    ///
1293
    /// Default: value in `block_size`.
1294
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
1295
    pub max_decode_block_size: u32,
1296
}
1297
1298
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone, Copy)]
1299
#[serde(rename_all = "snake_case")]
1300
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1301
pub enum CompressionAlgorithm {
1302
    /// LZ4 compression algorithm is extremely fast for compression and
1303
    /// decompression, however does not perform very well in compression
1304
    /// ratio. In most cases build artifacts are highly compressible, however
1305
    /// lz4 is quite good at aborting early if the data is not deemed very
1306
    /// compressible.
1307
    ///
1308
    /// see: <https://lz4.github.io/lz4/>
1309
    Lz4(Lz4Config),
1310
}
1311
1312
#[derive(Serialize, Deserialize, Debug, Clone)]
1313
#[serde(deny_unknown_fields)]
1314
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1315
pub struct CompressionSpec {
1316
    /// The underlying store wrap around. All content will first flow
1317
    /// through self before forwarding to backend. In the event there
1318
    /// is an error detected in self, the connection to the backend
1319
    /// will be terminated, and early termination should always cause
1320
    /// updates to fail on the backend.
1321
    pub backend: StoreSpec,
1322
1323
    /// The compression algorithm to use.
1324
    pub compression_algorithm: CompressionAlgorithm,
1325
}
1326
1327
/// Eviction policy always works on LRU (Least Recently Used). Any time an entry
1328
/// is touched it updates the timestamp. Inserts and updates will execute the
1329
/// eviction policy removing any expired entries and/or the oldest entries
1330
/// until the store size becomes smaller than `max_bytes`.
1331
#[derive(Serialize, Deserialize, Debug, Default, Clone, Copy)]
1332
#[serde(deny_unknown_fields)]
1333
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1334
pub struct EvictionPolicy {
1335
    /// Maximum number of bytes before eviction takes place.
1336
    /// Default: 0. Zero means never evict based on size.
1337
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
1338
    pub max_bytes: usize,
1339
1340
    /// When eviction starts based on hitting `max_bytes`, continue until
1341
    /// `max_bytes - evict_bytes` is met to create a low watermark. This stops
1342
    /// operations from thrashing when the store is close to the limit.
1343
    /// Default: 0
1344
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
1345
    pub evict_bytes: usize,
1346
1347
    /// Maximum number of seconds for an entry to live since it was last
1348
    /// accessed before it is evicted.
1349
    /// Default: 0. Zero means never evict based on time.
1350
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1351
    pub max_seconds: u32,
1352
1353
    /// Maximum size of the store before an eviction takes place.
1354
    /// Default: 0. Zero means never evict based on count.
1355
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1356
    pub max_count: u64,
1357
}
1358
1359
#[derive(Serialize, Deserialize, Debug, Clone)]
1360
#[serde(tag = "provider", rename_all = "snake_case")]
1361
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1362
pub enum ExperimentalCloudObjectSpec {
1363
    Aws(ExperimentalAwsSpec),
1364
    Gcs(ExperimentalGcsSpec),
1365
    Azure(ExperimentalAzureSpec),
1366
    Ontap(ExperimentalOntapS3Spec),
1367
    R2(ExperimentalR2Spec),
1368
    Oci(ExperimentalOciSpec),
1369
    Oss(ExperimentalOssSpec),
1370
}
1371
1372
impl Default for ExperimentalCloudObjectSpec {
1373
0
    fn default() -> Self {
1374
0
        Self::Aws(ExperimentalAwsSpec::default())
1375
0
    }
1376
}
1377
1378
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
1379
#[serde(deny_unknown_fields)]
1380
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1381
pub struct ExperimentalAwsSpec {
1382
    /// S3 region. Usually us-east-1, us-west-2, af-south-1, exc...
1383
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
1384
    pub region: String,
1385
1386
    /// Bucket name to use as the backend.
1387
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
1388
    pub bucket: String,
1389
1390
    /// Endpoint to talk to instead of the AWS regional endpoint. Set this to
1391
    /// point the store at an S3-compatible service, for example
1392
    /// `https://s3.example.com`. When omitted, the SDK resolves the endpoint
1393
    /// from `region`.
1394
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
1395
    pub endpoint: Option<String>,
1396
1397
    /// Address objects as `{endpoint}/{bucket}/{key}` rather than
1398
    /// `{bucket}.{endpoint}/{key}`. Many S3-compatible services serve only the
1399
    /// path-style form.
1400
    ///
1401
    /// Default: false
1402
    #[serde(default, deserialize_with = "convert_boolean_with_shellexpand")]
1403
    pub force_path_style: bool,
1404
1405
    /// Access key to sign requests with. When this and `secret_access_key` are
1406
    /// both omitted, the default AWS credential chain is used instead.
1407
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
1408
    pub access_key_id: Option<String>,
1409
1410
    /// Secret key to sign requests with. Prefer `${ENV_VAR}` shell expansion
1411
    /// over writing the secret into the config file.
1412
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
1413
    pub secret_access_key: Option<String>,
1414
1415
    /// Common retry and upload configuration
1416
    #[serde(flatten)]
1417
    pub common: CommonObjectSpec,
1418
}
1419
1420
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
1421
#[serde(deny_unknown_fields)]
1422
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1423
pub struct ExperimentalGcsSpec {
1424
    /// Bucket name to use as the backend.
1425
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
1426
    pub bucket: String,
1427
1428
    /// Chunk size for resumable uploads.
1429
    ///
1430
    /// Default: 2MB
1431
    #[serde(
1432
        default,
1433
        deserialize_with = "convert_optional_data_size_with_shellexpand"
1434
    )]
1435
    pub resumable_chunk_size: Option<usize>,
1436
1437
    /// Common retry and upload configuration
1438
    #[serde(flatten)]
1439
    pub common: CommonObjectSpec,
1440
1441
    /// Error if authentication was not found.
1442
    #[serde(default, deserialize_with = "convert_boolean_with_shellexpand")]
1443
    pub authentication_required: bool,
1444
1445
    /// Connection timeout in milliseconds.
1446
    /// Default: 3000
1447
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1448
    pub connection_timeout_s: u64,
1449
1450
    /// Read timeout in milliseconds.
1451
    /// Default: 3000
1452
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1453
    pub read_timeout_s: u64,
1454
}
1455
1456
#[derive(Serialize, Deserialize, Debug, Default, Clone)]
1457
#[serde(deny_unknown_fields)]
1458
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1459
pub struct ExperimentalAzureSpec {
1460
    /// The Azure Storage account name. Used to build the default container URL
1461
    /// `https://{account_name}.blob.core.windows.net/{container}` when `sas_url`
1462
    /// is not provided.
1463
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
1464
    pub account_name: String,
1465
1466
    /// The container name to use as the backend.
1467
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
1468
    pub container: String,
1469
1470
    /// Optional blob endpoint host override (for example an Azurite emulator host
1471
    /// such as `http://127.0.0.1:10000/devstoreaccount1`). When set, this replaces
1472
    /// the default `https://{account_name}.blob.core.windows.net` endpoint. The
1473
    /// container is always appended to form the final container URL. Ignored when
1474
    /// `sas_url` is set.
1475
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
1476
    pub endpoint: Option<String>,
1477
1478
    /// Optional pre-formed SAS URL pointing at the container. When set, the store
1479
    /// uses it directly as the container URL with no credential (the SAS token is
1480
    /// expected to already be present in the URL), and `account_name`, `container`,
1481
    /// and `endpoint` are ignored for URL construction.
1482
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
1483
    pub sas_url: Option<String>,
1484
1485
    /// Common retry and upload configuration.
1486
    #[serde(flatten)]
1487
    pub common: CommonObjectSpec,
1488
}
1489
1490
#[derive(Serialize, Deserialize, Debug, Clone)]
1491
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1492
pub struct CommonObjectSpec {
1493
    /// If you wish to prefix the location in the bucket. If None, no prefix will be used.
1494
    #[serde(default)]
1495
    pub key_prefix: Option<String>,
1496
1497
    /// Retry configuration to use when a network request fails.
1498
    #[serde(default)]
1499
    pub retry: Retry,
1500
1501
    /// If the number of seconds since the `last_modified` time of the object
1502
    /// is greater than this value, the object will not be considered
1503
    /// "existing". This allows for external tools to delete objects that
1504
    /// have not been uploaded in a long time. If a client receives a `NotFound`
1505
    /// the client should re-upload the object.
1506
    ///
1507
    /// There should be sufficient buffer time between how long the expiration
1508
    /// configuration of the external tool is and this value. Keeping items
1509
    /// around for a few days is generally a good idea.
1510
    ///
1511
    /// Default: 0. Zero means never consider an object expired.
1512
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1513
    pub consider_expired_after_s: u32,
1514
1515
    /// The maximum buffer size to retain in case of a retryable error
1516
    /// during upload. Setting this to zero will disable upload buffering;
1517
    /// this means that in the event of a failure during upload, the entire
1518
    /// upload will be aborted and the client will likely receive an error.
1519
    ///
1520
    /// Default: 5MB.
1521
    #[serde(
1522
        default,
1523
        deserialize_with = "convert_optional_data_size_with_shellexpand"
1524
    )]
1525
    pub max_retry_buffer_per_request: Option<usize>,
1526
1527
    /// Maximum number of concurrent `UploadPart` requests per `MultipartUpload`.
1528
    ///
1529
    /// Default: 10.
1530
    ///
1531
    #[serde(
1532
        default,
1533
        deserialize_with = "convert_optional_numeric_with_shellexpand"
1534
    )]
1535
    pub multipart_max_concurrent_uploads: Option<usize>,
1536
1537
    /// Allow unencrypted HTTP connections. Only use this for local testing.
1538
    ///
1539
    /// Default: false
1540
    #[serde(default, deserialize_with = "convert_boolean_with_shellexpand")]
1541
    pub insecure_allow_http: bool,
1542
1543
    /// Disable HTTP/2 connections and only use HTTP/1.1. Default client
1544
    /// configuration will have HTTP/1.1 and HTTP/2 enabled for connection
1545
    /// schemes. HTTP/2 should be disabled if environments have poor support
1546
    /// or performance related to HTTP/2. Safe to keep default unless
1547
    /// underlying network environment, S3, or GCS API servers specify otherwise.
1548
    ///
1549
    /// Default: false
1550
    #[serde(default, deserialize_with = "convert_boolean_with_shellexpand")]
1551
    pub disable_http2: bool,
1552
1553
    /// Minimum number of seconds to wait after a response that asked the
1554
    /// client to slow down (HTTP 503 `ServerBusy` or 429) when it carries no
1555
    /// `Retry-After` header.
1556
    ///
1557
    /// Default: 2.0
1558
    #[serde(default = "default_throttle_retry_delay_s")]
1559
    pub throttle_retry_delay_s: f32,
1560
1561
    /// Longest wait honoured from a `Retry-After` header. A server or proxy
1562
    /// asking for more waits this long instead, and the capped wait is
1563
    /// logged. Must not be less than `throttle_retry_delay_s`.
1564
    ///
1565
    /// Default: 60.0
1566
    #[serde(default = "default_throttle_retry_max_delay_s")]
1567
    pub throttle_retry_max_delay_s: f32,
1568
1569
    /// Seconds one operation may spend waiting on throttled responses
1570
    /// without spending any of `retry.max_retries`: while the budget lasts
1571
    /// each throttle waits what the server asked (at least
1572
    /// `throttle_retry_delay_s`, at most `throttle_retry_max_delay_s`) and
1573
    /// the attempt is not counted, so a long throttle is ridden out rather
1574
    /// than failed on the seventh try. Once it is used up, throttles spend
1575
    /// attempts and backoff like any other transient error. 0 turns the
1576
    /// budget off.
1577
    ///
1578
    /// Default: 120.0
1579
    #[serde(default = "default_throttle_retry_budget_s")]
1580
    pub throttle_retry_budget_s: f32,
1581
1582
    /// Most downloads (`GET`) this process keeps in flight against the
1583
    /// object store at once, each counted until its body has been sent on.
1584
    /// Further downloads wait in the process for a permit instead of being
1585
    /// sent and refused, which turns an account over its limit into
1586
    /// queueing here rather than wasted requests and retries in lockstep.
1587
    /// Existence checks (`HEAD`) are not counted: they move no bytes, so
1588
    /// they never wait behind a body going to a slow client, and a
1589
    /// throttled `HEAD` does not move the limit. 0 (the default) leaves
1590
    /// downloads unbounded, as before.
1591
    ///
1592
    /// Default: 0
1593
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1594
    pub max_concurrent_reads: usize,
1595
1596
    /// With `max_concurrent_reads` set, let the bound move: a throttled
1597
    /// download (503 `ServerBusy` or 429) halves it, not below
1598
    /// `min_concurrent_reads`, and a run of answered downloads raises it
1599
    /// by one back toward `max_concurrent_reads`. Many processes behind one
1600
    /// account then converge on a share of its limit. Off, the bound is
1601
    /// fixed at `max_concurrent_reads`.
1602
    ///
1603
    /// Default: false
1604
    #[serde(default, deserialize_with = "convert_boolean_with_shellexpand")]
1605
    pub adaptive_read_concurrency: bool,
1606
1607
    /// Floor for the adaptive read bound.
1608
    ///
1609
    /// Default: 4
1610
    #[serde(
1611
        default = "default_min_concurrent_reads",
1612
        deserialize_with = "convert_numeric_with_shellexpand"
1613
    )]
1614
    pub min_concurrent_reads: usize,
1615
1616
    /// Most requests of any kind this store keeps in flight against the
1617
    /// object store at once: existence checks (`HEAD`), downloads, uploads,
1618
    /// block staging and commits, and the cleanup after a failed upload.
1619
    /// Each request holds a connection of its own for its whole length
1620
    /// (Azure Blob Storage speaks HTTP/1.1), so this bounds the connections
1621
    /// the store opens and the local ports they take toward the account.
1622
    /// At the limit, further requests wait in the process, first come first
1623
    /// served, for one in flight to finish: nothing is sent or refused, so
1624
    /// the cost shows up as latency against callers' deadlines. A download
1625
    /// holds its permit while its body streams to the reader, so the store
1626
    /// refuses to start unless `max_concurrent_reads` is above 0 and below
1627
    /// this: downloads then never hold more than `max_concurrent_reads`
1628
    /// permits, and existence checks and uploads always keep the rest.
1629
    /// Every store in a `shard` has a limit of its own, so N shards hold up
1630
    /// to N times this. 0 (the default) leaves requests unbounded, as
1631
    /// before.
1632
    ///
1633
    /// Default: 0
1634
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1635
    pub max_concurrent_requests: usize,
1636
}
1637
1638
343
const fn default_min_concurrent_reads() -> usize {
1639
343
    4
1640
343
}
1641
1642
343
const fn default_throttle_retry_delay_s() -> f32 {
1643
343
    2.0
1644
343
}
1645
1646
343
const fn default_throttle_retry_max_delay_s() -> f32 {
1647
343
    60.0
1648
343
}
1649
1650
343
const fn default_throttle_retry_budget_s() -> f32 {
1651
343
    120.0
1652
343
}
1653
1654
impl Default for CommonObjectSpec {
1655
0
    fn default() -> Self {
1656
0
        Self {
1657
0
            key_prefix: None,
1658
0
            retry: Retry::default(),
1659
0
            consider_expired_after_s: 0,
1660
0
            max_retry_buffer_per_request: None,
1661
0
            multipart_max_concurrent_uploads: None,
1662
0
            insecure_allow_http: false,
1663
0
            disable_http2: false,
1664
0
            throttle_retry_delay_s: default_throttle_retry_delay_s(),
1665
0
            throttle_retry_max_delay_s: default_throttle_retry_max_delay_s(),
1666
0
            throttle_retry_budget_s: default_throttle_retry_budget_s(),
1667
0
            max_concurrent_reads: 0,
1668
0
            adaptive_read_concurrency: false,
1669
0
            min_concurrent_reads: default_min_concurrent_reads(),
1670
0
            max_concurrent_requests: 0,
1671
0
        }
1672
0
    }
1673
}
1674
1675
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
1676
#[serde(rename_all = "snake_case")]
1677
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1678
pub enum StoreType {
1679
    /// The store is content addressable storage.
1680
    Cas,
1681
    /// The store is an action cache.
1682
    Ac,
1683
    /// A write-only event sink using `ByteStream.Write`. Only string keys and
1684
    /// exact upload sizes are accepted. The resource hash identifies the key,
1685
    /// not the payload; the size describes the payload. The upstream must be an
1686
    /// event receiver, not a CAS. Reads and existence checks are unsupported.
1687
    /// Use this for BEP/origin event forwarding, never for cache data.
1688
    EventSink,
1689
}
1690
1691
#[derive(Serialize, Deserialize, Debug, Clone)]
1692
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1693
pub struct ClientTlsConfig {
1694
    /// Path to the certificate authority to use to validate the remote.
1695
    ///
1696
    /// Default: None
1697
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
1698
    pub ca_file: Option<String>,
1699
1700
    /// Path to the certificate file for client authentication.
1701
    ///
1702
    /// Default: None
1703
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
1704
    pub cert_file: Option<String>,
1705
1706
    /// Path to the private key file for client authentication.
1707
    ///
1708
    /// Default: None
1709
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
1710
    pub key_file: Option<String>,
1711
1712
    /// If set the client will use the native roots for TLS connections.
1713
    ///
1714
    /// Default: false
1715
    #[serde(default)]
1716
    pub use_native_roots: Option<bool>,
1717
}
1718
1719
#[derive(Serialize, Deserialize, Debug, Clone)]
1720
#[serde(deny_unknown_fields)]
1721
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1722
pub struct GrpcEndpoint {
1723
    /// The endpoint address (i.e. `grpc(s)://example.com:443`).
1724
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
1725
    pub address: String,
1726
    /// The TLS configuration to use to connect to the endpoint (if grpcs).
1727
    pub tls_config: Option<ClientTlsConfig>,
1728
    /// The maximum concurrency to allow on this endpoint.
1729
    #[serde(
1730
        default,
1731
        deserialize_with = "convert_optional_numeric_with_shellexpand"
1732
    )]
1733
    pub concurrency_limit: Option<usize>,
1734
1735
    /// Timeout for establishing a TCP connection to the endpoint (seconds).
1736
    /// If not set or 0, defaults to 30 seconds.
1737
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1738
    pub connect_timeout_s: u64,
1739
1740
    /// TCP keepalive interval (seconds). Sends TCP keepalive probes at this
1741
    /// interval to detect dead connections at the OS level.
1742
    /// If not set or 0, defaults to 30 seconds.
1743
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1744
    pub tcp_keepalive_s: u64,
1745
1746
    /// HTTP/2 keepalive interval (seconds). Sends HTTP/2 PING frames at this
1747
    /// interval to detect dead connections at the application level.
1748
    /// If not set or 0, defaults to 30 seconds.
1749
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1750
    pub http2_keepalive_interval_s: u64,
1751
1752
    /// HTTP/2 keepalive timeout (seconds). If a PING response is not received
1753
    /// within this duration, the connection is considered dead.
1754
    /// If not set or 0, defaults to 20 seconds.
1755
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1756
    pub http2_keepalive_timeout_s: u64,
1757
}
1758
1759
#[derive(Serialize, Deserialize, Debug, Clone)]
1760
#[serde(deny_unknown_fields)]
1761
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1762
pub struct GrpcSpec {
1763
    /// Instance name for gRPC calls. Proxy calls will have the `instance_name` changed to this.
1764
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
1765
    pub instance_name: String,
1766
1767
    /// The endpoint of the grpc connection.
1768
    pub endpoints: Vec<GrpcEndpoint>,
1769
1770
    /// The type of the upstream store, this ensures that the correct server calls are made.
1771
    pub store_type: StoreType,
1772
1773
    /// Retry configuration to use when a network request fails.
1774
    #[serde(default)]
1775
    pub retry: Retry,
1776
1777
    /// Limit the number of simultaneous upstream requests to this many. A
1778
    /// value of zero is treated as unlimited. If the limit is reached the
1779
    /// request is queued.
1780
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1781
    pub max_concurrent_requests: usize,
1782
1783
    /// The number of connections to make to each specified endpoint to balance
1784
    /// the load over multiple TCP connections.
1785
    /// Default: 1.
1786
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1787
    pub connections_per_endpoint: usize,
1788
1789
    /// Maximum time (seconds) allowed for a single RPC request (e.g. a
1790
    /// `ByteStream.Write` call) before it is cancelled.
1791
    ///
1792
    /// A value of 0 (the default) disables the per-RPC timeout. Dead
1793
    /// connections are still detected by the HTTP/2 and TCP keepalive
1794
    /// mechanisms configured on each endpoint.
1795
    ///
1796
    /// For large uploads (multi-GB), either leave this at 0 or set it
1797
    /// large enough to accommodate the full transfer time.
1798
    ///
1799
    /// Default: 0 (disabled)
1800
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1801
    pub rpc_timeout_s: u64,
1802
1803
    /// Use legacy `ByteStream` resource name format, omitting the digest
1804
    /// function component from the path.
1805
    ///
1806
    /// Modern `NativeLink` generates resource names like:
1807
    ///   `{instance}/blobs/{digest_function}/{hash}/{size}`
1808
    ///
1809
    /// Older backends (e.g. Buildbarn pre-v0.3) expect the original format:
1810
    ///   `{instance}/blobs/{hash}/{size}`
1811
    ///
1812
    /// Set this to `true` when connecting to such backends to avoid
1813
    /// `InvalidArgument: Unsupported digest function` errors.
1814
    ///
1815
    /// Default: false
1816
    #[serde(default, deserialize_with = "convert_boolean_with_shellexpand")]
1817
    pub use_legacy_resource_names: bool,
1818
1819
    /// Static headers to attach to every outgoing gRPC request sent to this
1820
    /// store's upstream endpoints. Useful for fixed authentication tokens
1821
    /// (e.g. `{"authorization": "Bearer <token>"}`) and other static metadata.
1822
    #[serde(default)]
1823
    pub headers: HashMap<String, String>,
1824
1825
    /// Header names to forward from the incoming client request to every
1826
    /// outgoing upstream request. The header value is taken from the client
1827
    /// request that triggered this store operation. Use this to pass through
1828
    /// dynamic credentials such as JWT tokens sent by build clients.
1829
    ///
1830
    /// Example: `["authorization", "x-custom-token"]`
1831
    ///
1832
    /// `NativeLink` also automatically injects the current OpenTelemetry trace
1833
    /// context (`traceparent` / `tracestate`) into every outgoing request.
1834
    #[serde(default)]
1835
    pub forward_headers: Vec<String>,
1836
1837
    /// Optional and experimental: coalesce small-blob reads into
1838
    /// `BatchReadBlobs` RPCs instead of issuing one `ByteStream` `Read`
1839
    /// stream per blob. Each `ByteStream` read carries a fixed per-RPC cost,
1840
    /// so batching many small reads into a single `BatchReadBlobs` request
1841
    /// can dramatically reduce read latency for small blobs.
1842
    ///
1843
    /// Only full reads (offset 0, whole blob) of blobs at or below
1844
    /// `max_blob_size_bytes` are batched; everything else continues to use
1845
    /// the `ByteStream` `Read` path.
1846
    ///
1847
    /// Incompatible with `forward_headers`: batched reads share one upstream
1848
    /// RPC across many client requests, so per-client forwarded headers
1849
    /// (e.g. credentials) cannot be attached. Configuring both is rejected
1850
    /// at startup.
1851
    ///
1852
    /// Default: unset (disabled). When unset there is zero behavior change.
1853
    #[serde(default)]
1854
    pub experimental_read_batching: Option<GrpcReadBatchingConfig>,
1855
1856
    /// Compress this store's own blob transfers on the wire with REAPI
1857
    /// `compressed-blobs/zstd`. Uploads and full-blob downloads of blobs at
1858
    /// or above 64 KiB are zstd-compressed; smaller blobs and ranged reads
1859
    /// keep the identity path.
1860
    ///
1861
    /// The upstream instance must have
1862
    /// `capabilities.remote_cache_compression` enabled, otherwise compressed
1863
    /// requests fail with `InvalidArgument`. This setting is what makes
1864
    /// NativeLink-to-NativeLink hops (for example worker to CAS) benefit
1865
    /// from wire compression; it is independent of what external clients
1866
    /// such as Bazel negotiate for themselves.
1867
    ///
1868
    /// Compressed uploads do not resume mid-stream (mirroring the REAPI
1869
    /// server contract): a transport failure part-way through a compressed
1870
    /// upload surfaces immediately to the caller instead of retrying, and
1871
    /// outer callers retry the whole upload.
1872
    ///
1873
    /// When combined with `experimental_chunked_uploads`, chunked uploads
1874
    /// take precedence for blobs at or above the chunking threshold.
1875
    ///
1876
    /// When zstd wire compression is enabled elsewhere in the process,
1877
    /// omitting this setting enables it automatically for CAS gRPC stores.
1878
    /// Set it explicitly to `false` to opt this store out.
1879
    ///
1880
    /// Default: inherited from the process-wide zstd wire-compression intent.
1881
    #[serde(
1882
        default,
1883
        skip_serializing_if = "Option::is_none",
1884
        deserialize_with = "convert_boolean_with_shellexpand"
1885
    )]
1886
    pub experimental_remote_cache_compression: Option<bool>,
1887
}
1888
1889
impl GrpcSpec {
1890
    /// Whether this store should use REAPI zstd wire compression.
1891
    #[must_use]
1892
0
    pub fn remote_cache_compression_enabled(&self) -> bool {
1893
0
        self.experimental_remote_cache_compression.unwrap_or(false)
1894
0
    }
1895
}
1896
1897
/// Configuration for experimental small-blob read coalescing in a gRPC
1898
/// store. See [`GrpcSpec::experimental_read_batching`].
1899
#[derive(Serialize, Deserialize, Debug, Clone, Copy)]
1900
#[serde(deny_unknown_fields)]
1901
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1902
pub struct GrpcReadBatchingConfig {
1903
    /// Only blobs at or below this size (in bytes) are eligible for
1904
    /// batching. Larger blobs always use the `ByteStream` `Read` path.
1905
    ///
1906
    /// Default: 131072 (128 KiB).
1907
    #[serde(
1908
        default = "default_read_batching_max_blob_size_bytes",
1909
        deserialize_with = "convert_data_size_with_shellexpand"
1910
    )]
1911
    pub max_blob_size_bytes: u64,
1912
1913
    /// Maximum total payload bytes packed into a single `BatchReadBlobs`
1914
    /// request. This should leave headroom under the 4 MiB default gRPC
1915
    /// message limit for protobuf framing overhead.
1916
    ///
1917
    /// Default: 3145728 (3 MiB).
1918
    #[serde(
1919
        default = "default_read_batching_max_batch_bytes",
1920
        deserialize_with = "convert_data_size_with_shellexpand"
1921
    )]
1922
    pub max_batch_bytes: u64,
1923
1924
    /// Maximum number of concurrent `BatchReadBlobs` RPCs dispatched by the
1925
    /// coalescer. Must be greater than zero.
1926
    ///
1927
    /// Default: 4.
1928
    #[serde(
1929
        default = "default_read_batching_dispatch_slots",
1930
        deserialize_with = "convert_numeric_with_shellexpand"
1931
    )]
1932
    pub dispatch_slots: usize,
1933
1934
    /// Bound on the number of payload bytes waiting in the coalescer queue.
1935
    /// When exceeded, new read requests bypass batching and fall back to the
1936
    /// regular `ByteStream` `Read` path instead of blocking.
1937
    ///
1938
    /// Default: 33554432 (32 MiB).
1939
    #[serde(
1940
        default = "default_read_batching_max_queued_bytes",
1941
        deserialize_with = "convert_data_size_with_shellexpand"
1942
    )]
1943
    pub max_queued_bytes: u64,
1944
}
1945
1946
0
const fn default_read_batching_max_blob_size_bytes() -> u64 {
1947
0
    128 * 1024 // 128 KiB.
1948
0
}
1949
1950
0
const fn default_read_batching_max_batch_bytes() -> u64 {
1951
0
    3 * 1024 * 1024 // 3 MiB.
1952
0
}
1953
1954
0
const fn default_read_batching_dispatch_slots() -> usize {
1955
0
    4
1956
0
}
1957
1958
0
const fn default_read_batching_max_queued_bytes() -> u64 {
1959
0
    32 * 1024 * 1024 // 32 MiB.
1960
0
}
1961
1962
/// The possible error codes that might occur on an upstream request.
1963
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
1964
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1965
pub enum ErrorCode {
1966
    Cancelled = 1,
1967
    Unknown = 2,
1968
    InvalidArgument = 3,
1969
    DeadlineExceeded = 4,
1970
    NotFound = 5,
1971
    AlreadyExists = 6,
1972
    PermissionDenied = 7,
1973
    ResourceExhausted = 8,
1974
    FailedPrecondition = 9,
1975
    Aborted = 10,
1976
    OutOfRange = 11,
1977
    Unimplemented = 12,
1978
    Internal = 13,
1979
    Unavailable = 14,
1980
    DataLoss = 15,
1981
    Unauthenticated = 16,
1982
    // Note: This list is duplicated from nativelink-error/lib.rs.
1983
}
1984
1985
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
1986
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1987
pub struct RedisSpec {
1988
    /// The hostname or IP address of the Redis server.
1989
    /// Ex: `["redis://username:password@redis-server-url:6380/99"]`
1990
    /// 99 Represents database ID, 6380 represents the port.
1991
    #[serde(deserialize_with = "convert_vec_string_with_shellexpand")]
1992
    pub addresses: Vec<String>,
1993
1994
    /// DEPRECATED: use `command_timeout_ms`
1995
    /// The response timeout for the Redis connection in seconds.
1996
    ///
1997
    /// Default: 10
1998
    #[serde(default)]
1999
    pub response_timeout_s: u64,
2000
2001
    /// DEPRECATED: use `connection_timeout_ms`
2002
    ///
2003
    /// The connection timeout for the Redis connection in seconds.
2004
    ///
2005
    /// Default: 10
2006
    #[serde(default)]
2007
    pub connection_timeout_s: u64,
2008
2009
    /// An optional and experimental Redis channel to publish write events to.
2010
    ///
2011
    /// If set, every time a write operation is made to a Redis node
2012
    /// then an event will be published to a Redis channel with the given name.
2013
    /// If unset, the writes will still be made,
2014
    /// but the write events will not be published.
2015
    ///
2016
    /// Default: (Empty String / No Channel)
2017
    #[serde(default)]
2018
    pub experimental_pub_sub_channel: Option<String>,
2019
2020
    /// An optional prefix to prepend to all keys in this store.
2021
    ///
2022
    /// Setting this value can make it convenient to query or
2023
    /// organize your data according to the shared prefix.
2024
    ///
2025
    /// Default: (Empty String / No Prefix)
2026
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
2027
    pub key_prefix: String,
2028
2029
    /// Set the mode Redis is operating in.
2030
    ///
2031
    /// Available options are "cluster" for
2032
    /// [cluster mode](https://redis.io/docs/latest/operate/oss_and_stack/reference/cluster-spec/),
2033
    /// "sentinel" for [sentinel mode](https://redis.io/docs/latest/operate/oss_and_stack/management/sentinel/),
2034
    /// or "standard" if Redis is operating in neither cluster nor sentinel mode.
2035
    ///
2036
    /// Default: standard,
2037
    #[serde(default)]
2038
    pub mode: RedisMode,
2039
2040
    /// Deprecated as redis-rs doesn't use it
2041
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
2042
    pub broadcast_channel_capacity: usize,
2043
2044
    /// The amount of time in milliseconds until the redis store considers the
2045
    /// command to be timed out. This will trigger a retry of the command and
2046
    /// potentially a reconnection to the redis server.
2047
    ///
2048
    /// Default: 10000 (10 seconds)
2049
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
2050
    pub command_timeout_ms: u64,
2051
2052
    /// The amount of time in milliseconds until the redis store considers the
2053
    /// connection to unresponsive. This will trigger a reconnection to the
2054
    /// redis server.
2055
    ///
2056
    /// Default: 3000 (3 seconds)
2057
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
2058
    pub connection_timeout_ms: u64,
2059
2060
    /// Per-call ceiling for the `check_health` PING in milliseconds.
2061
    ///
2062
    /// Default: 4000 (4 seconds)
2063
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
2064
    pub health_check_timeout_ms: u64,
2065
2066
    /// The amount of data to read from the redis server at a time.
2067
    /// This is used to limit the amount of memory used when reading
2068
    /// large objects from the redis server as well as limiting the
2069
    /// amount of time a single read operation can take.
2070
    ///
2071
    /// IMPORTANT: If this value is too high, the `command_timeout_ms`
2072
    /// might be triggered if the latency or throughput to the redis
2073
    /// server is too low.
2074
    ///
2075
    /// Default: 64KiB
2076
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
2077
    pub read_chunk_size: usize,
2078
2079
    /// The number of connections to keep open to the redis servers.
2080
    ///
2081
    /// Default: 3
2082
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
2083
    pub connection_pool_size: usize,
2084
2085
    /// Expire keys written by this store after this many seconds.
2086
    ///
2087
    /// Redis does not expire these on its own, so a store whose consumer
2088
    /// stops keeps every key it ever wrote. A BEP store is the case this
2089
    /// exists for: if the ETL stops consuming, the backlog grows until the
2090
    /// Redis node runs out of memory.
2091
    ///
2092
    /// Set this per store, not globally. The same store type backs the CAS
2093
    /// fast tier and the scheduler, and expiring scheduler state would drop
2094
    /// in-flight actions.
2095
    ///
2096
    /// This trades data for a bound. Anything not consumed within the window
2097
    /// is deleted, so the value has to exceed the longest consumer outage you
2098
    /// intend to survive, and it must also exceed how long a single upload can
2099
    /// take: the temp key an upload builds carries this same TTL, and an
2100
    /// upload that outlives it fails rather than publishing a key that was
2101
    /// recreated without its first chunks.
2102
    ///
2103
    /// Unset, the temp key still expires, after an hour, so an upload that
2104
    /// stops part way (its client gone, the process gone) never leaves a key
2105
    /// behind for good. Nothing else cleans those up.
2106
    ///
2107
    /// Zero disables expiry. One second is the smallest value that enables it,
2108
    /// and any value that small is almost certainly a mistake.
2109
    ///
2110
    /// Default: 0 (keys never expire)
2111
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
2112
    pub key_ttl_s: u64,
2113
2114
    /// The maximum number of upload chunks to allow per update.
2115
    /// This is used to limit the amount of memory used when uploading
2116
    /// large objects to the redis server. A good rule of thumb is to
2117
    /// think of the data as:
2118
    /// `AVAIL_MEMORY / (read_chunk_size * max_chunk_uploads_per_update) = THORETICAL_MAX_CONCURRENT_UPLOADS`
2119
    /// (note: it's a good idea to divide `AVAIL_MAX_MEMORY` by ~10 to account for other memory usage)
2120
    ///
2121
    /// Default: 10
2122
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
2123
    pub max_chunk_uploads_per_update: usize,
2124
2125
    /// The COUNT value passed when scanning keys in Redis.
2126
    /// This is used to hint the amount of work that should be done per response.
2127
    ///
2128
    /// Default: 10000
2129
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
2130
    pub scan_count: usize,
2131
2132
    /// Retry configuration to use when a network request fails.
2133
    #[serde(default)]
2134
    pub retry: Retry,
2135
2136
    /// Maximum number of permitted actions to the Redis store at any one time
2137
    /// This stops problems with timeouts due to many, many inflight actions
2138
    /// Default: 500
2139
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
2140
    pub max_client_permits: usize,
2141
2142
    /// Maximum number of items returned per cursor for the search indexes
2143
    /// May reduce thundering herd issues with worker provisioner at higher node counts,
2144
    /// Default: 1500
2145
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
2146
    pub max_count_per_cursor: u64,
2147
2148
    /// Replace scheduler indexes an older release created `TEMPORARY` with
2149
    /// persistent ones, keeping every hash.
2150
    ///
2151
    /// A temporary index is never garbage collected on `RediSearch` 2.10, so
2152
    /// every query walks every dead entry it has collected, and dropping one
2153
    /// the ordinary way deletes the hashes it covers (so does its idle
2154
    /// expiry). With this set, a persistent index is built beside each
2155
    /// temporary one, reads move to it once it holds every key (the scan
2156
    /// finished, nothing failed to index, and it counts as many keys as the
2157
    /// old one), and the old one is removed with the keys left in place.
2158
    ///
2159
    /// Set it only once no process older than v1.8.1 writes this store: those
2160
    /// create the index temporary again. Turn it on for every process that
2161
    /// reads the store together where possible: during a rolling restart,
2162
    /// the processes without it recreate the old index each time it is
2163
    /// retired and the ones with it retire it again. No key is lost, but each
2164
    /// round costs a backfill.
2165
    ///
2166
    /// Building the replacement needs free memory below `maxmemory`, about
2167
    /// what a clean index of the live keys takes. A Redis already full of
2168
    /// dead entries refuses it; the migration then waits, logs an error and
2169
    /// leaves everything in place. Restarting Redis frees that memory: it
2170
    /// rebuilds every index from the keys, without the dead entries, though
2171
    /// a temporary index stays temporary and fills up again.
2172
    ///
2173
    /// Default: false
2174
    #[serde(default)]
2175
    pub migrate_temporary_indexes: bool,
2176
}
2177
2178
#[derive(Debug, Default, Deserialize, Serialize, Clone, Copy, PartialEq, Eq)]
2179
#[serde(rename_all = "snake_case")]
2180
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
2181
pub enum RedisMode {
2182
    /// Use Redis Cluster.
2183
    Cluster,
2184
2185
    /// Use Redis Sentinel.
2186
    Sentinel,
2187
2188
    /// Use a standalone Redis server.
2189
    #[default]
2190
    Standard,
2191
}
2192
2193
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
2194
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
2195
pub struct NoopSpec {}
2196
2197
/// Retry configuration. This configuration is exponential and each iteration
2198
/// a jitter as a percentage is applied of the calculated delay. For example:
2199
/// ```haskell
2200
/// Retry{
2201
///   max_retries: 7,
2202
///   delay: 0.1,
2203
///   jitter: 0.5,
2204
/// }
2205
/// ```
2206
/// will result in:
2207
/// Attempt - Delay
2208
/// 1         0ms
2209
/// 2         75ms - 125ms
2210
/// 3         150ms - 250ms
2211
/// 4         300ms - 500ms
2212
/// 5         600ms - 1s
2213
/// 6         1.2s - 2s
2214
/// 7         2.4s - 4s
2215
/// 8         4.8s - 8s
2216
/// Remember that to get total results is additive, meaning the above results
2217
/// would mean a single request would have a total delay of 9.525s - 15.875s.
2218
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
2219
#[serde(deny_unknown_fields)]
2220
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
2221
pub struct Retry {
2222
    /// Maximum number of retries until retrying stops.
2223
    /// Setting this to zero will always attempt 1 time, but not retry.
2224
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
2225
    pub max_retries: usize,
2226
2227
    /// Delay in seconds for exponential back off.
2228
    #[serde(default)]
2229
    pub delay: f32,
2230
2231
    /// Amount of jitter to add as a percentage in decimal form. This will
2232
    /// change the formula like:
2233
    /// ```haskell
2234
    /// random(
2235
    ///    (2 ^ {attempt_number}) * {delay} * (1 - (jitter / 2)),
2236
    ///    (2 ^ {attempt_number}) * {delay} * (1 + (jitter / 2)),
2237
    /// )
2238
    /// ```
2239
    #[serde(default)]
2240
    pub jitter: f32,
2241
2242
    /// A list of error codes to retry on, if this isn't set then the default
2243
    /// error codes to retry on are used. These default codes are the most
2244
    /// likely to be non-permanent.
2245
    ///  - `Unknown`
2246
    ///  - `Cancelled`
2247
    ///  - `DeadlineExceeded`
2248
    ///  - `ResourceExhausted`
2249
    ///  - `Aborted`
2250
    ///  - `Internal`
2251
    ///  - `Unavailable`
2252
    ///  - `DataLoss`
2253
    #[serde(default)]
2254
    pub retry_on_errors: Option<Vec<ErrorCode>>,
2255
}
2256
2257
/// Configuration for `ExperimentalMongoDB` store.
2258
#[derive(Serialize, Deserialize, Debug, Clone)]
2259
#[serde(deny_unknown_fields)]
2260
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
2261
pub struct ExperimentalMongoSpec {
2262
    /// `ExperimentalMongoDB` connection string.
2263
    /// Example: <mongodb://localhost:27017> or <mongodb+srv://cluster.mongodb.net>
2264
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
2265
    pub connection_string: String,
2266
2267
    /// The database name to use.
2268
    /// Default: "nativelink"
2269
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
2270
    pub database: String,
2271
2272
    /// The collection name for CAS data.
2273
    /// Default: "cas"
2274
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
2275
    pub cas_collection: String,
2276
2277
    /// The collection name for scheduler data.
2278
    /// Default: "scheduler"
2279
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
2280
    pub scheduler_collection: String,
2281
2282
    /// Prefix to prepend to all keys stored in `MongoDB`.
2283
    /// Default: ""
2284
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
2285
    pub key_prefix: Option<String>,
2286
2287
    /// The maximum amount of data to read from `MongoDB` in a single chunk (in bytes).
2288
    /// Default: 65536 (64KB)
2289
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
2290
    pub read_chunk_size: usize,
2291
2292
    /// Deprecated, unused
2293
    /// Maximum number of concurrent uploads allowed.
2294
    /// Default: 10
2295
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
2296
    pub max_concurrent_uploads: usize,
2297
2298
    /// Connection timeout in milliseconds.
2299
    /// Default: 3000
2300
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
2301
    pub connection_timeout_ms: u64,
2302
2303
    /// Command timeout in milliseconds.
2304
    /// Default: 10000
2305
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
2306
    pub command_timeout_ms: u64,
2307
2308
    /// Enable `MongoDB` change streams for real-time updates.
2309
    /// Required for scheduler subscriptions.
2310
    /// Default: false
2311
    #[serde(default, deserialize_with = "convert_boolean_with_shellexpand")]
2312
    pub enable_change_streams: bool,
2313
2314
    /// Write concern 'w' parameter.
2315
    /// Can be a number (e.g., 1) or string (e.g., "majority").
2316
    /// Default: None (uses `MongoDB` default)
2317
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
2318
    pub write_concern_w: Option<String>,
2319
2320
    /// Write concern 'j' parameter (journal acknowledgment).
2321
    /// Default: None (uses `MongoDB` default)
2322
    #[serde(default)]
2323
    pub write_concern_j: Option<bool>,
2324
2325
    /// Write concern timeout in milliseconds.
2326
    /// Default: None (uses `MongoDB` default)
2327
    #[serde(
2328
        default,
2329
        deserialize_with = "convert_optional_numeric_with_shellexpand"
2330
    )]
2331
    pub write_concern_timeout_ms: Option<u32>,
2332
2333
    /// Limits the number of requests at any one time
2334
    /// Default: Unlimited
2335
    #[serde(
2336
        default,
2337
        deserialize_with = "convert_optional_numeric_with_shellexpand"
2338
    )]
2339
    pub max_requests: Option<usize>,
2340
}
2341
2342
impl Retry {
2343
105
    pub fn make_jitter_fn(&self) -> Arc<dyn Fn(Duration) -> Duration + Send + Sync> {
2344
105
        if self.jitter == 0f32 {
2345
105
            Arc::new(move |delay: Duration| delay)
2346
        } else {
2347
0
            let local_jitter = self.jitter;
2348
0
            Arc::new(move |delay: Duration| {
2349
0
                delay.mul_f32(local_jitter.mul_add(rand::rng().random::<f32>() - 0.5, 1.))
2350
0
            })
2351
        }
2352
105
    }
2353
}