Coverage Report

Created: 2026-11-24 07:07

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/build/source/nativelink-config/src/cas_server.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 std::collections::HashMap;
16
17
use nativelink_error::{Code, Error, ResultExt, make_err, make_input_err};
18
#[cfg(feature = "dev-schema")]
19
use schemars::JsonSchema;
20
use serde::{Deserialize, Serialize};
21
use tracing::warn;
22
23
use crate::schedulers::SchedulerSpec;
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_numeric_with_shellexpand, convert_optional_string_with_shellexpand,
28
    convert_string_with_shellexpand, convert_vec_string_with_shellexpand,
29
};
30
use crate::stores::{
31
    ClientTlsConfig, ConfigDigestHashFunction, StoreRefName, StoreSpec, StoreType,
32
};
33
34
/// Name of the scheduler. This type will be used when referencing a
35
/// scheduler in the `CasConfig::schedulers`'s map key.
36
pub type SchedulerRefName = String;
37
38
/// Used when the config references `instance_name` in the protocol.
39
pub type InstanceName = String;
40
41
#[derive(Debug, Default, Clone, PartialEq, Eq, Deserialize, Serialize)]
42
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
43
pub struct WithInstanceName<T> {
44
    /// Used when the config references `instance_name` in the protocol.
45
    #[serde(default)]
46
    pub instance_name: InstanceName,
47
    #[serde(flatten)]
48
    pub config: T,
49
}
50
51
impl<T> core::ops::Deref for WithInstanceName<T> {
52
    type Target = T;
53
54
1.48k
    fn deref(&self) -> &Self::Target {
55
1.48k
        &self.config
56
1.48k
    }
57
}
58
59
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
60
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
61
pub struct NamedConfig<Spec> {
62
    pub name: String,
63
    #[serde(flatten)]
64
    pub spec: Spec,
65
}
66
67
#[derive(Deserialize, Serialize, Debug, Default, Clone, Copy)]
68
#[serde(rename_all = "snake_case")]
69
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
70
pub enum HttpCompressionAlgorithm {
71
    /// No compression.
72
    #[default]
73
    None,
74
75
    /// Zlib compression.
76
    Gzip,
77
}
78
79
/// Note: Compressing data in the cloud rarely has a benefit, since most
80
/// cloud providers have very high bandwidth backplanes. However, for
81
/// clients not inside the data center, it might be a good idea to
82
/// compress data to and from the cloud. This will however come at a high
83
/// CPU and performance cost. If you are making remote execution share the
84
/// same CAS/AC servers as client's remote cache, you can create multiple
85
/// services with different compression settings that are served on
86
/// different ports. Then configure the non-cloud clients to use one port
87
/// and cloud-clients to use another.
88
#[derive(Deserialize, Serialize, Debug, Default)]
89
#[serde(deny_unknown_fields)]
90
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
91
pub struct HttpCompressionConfig {
92
    /// The compression algorithm that the server will use when sending
93
    /// responses to clients. Enabling this will likely save a lot of
94
    /// data transfer, but will consume a lot of CPU and add a lot of
95
    /// latency.
96
    /// see: <https://github.com/tracemachina/nativelink/issues/109>
97
    ///
98
    /// Default: `HttpCompressionAlgorithm::None`
99
    pub send_compression_algorithm: Option<HttpCompressionAlgorithm>,
100
101
    /// The compression algorithm that the server will accept from clients.
102
    /// The server will broadcast the supported compression algorithms to
103
    /// clients and the client will choose which compression algorithm to
104
    /// use. Enabling this will likely save a lot of data transfer, but
105
    /// will consume a lot of CPU and add a lot of latency.
106
    /// see: <https://github.com/tracemachina/nativelink/issues/109>
107
    ///
108
    /// Default: {no supported compression}
109
    pub accepted_compression_algorithms: Vec<HttpCompressionAlgorithm>,
110
}
111
112
#[derive(Deserialize, Serialize, Debug)]
113
#[serde(deny_unknown_fields)]
114
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
115
pub struct AcStoreConfig {
116
    /// The store name referenced in the `stores` map in the main config.
117
    /// This store name referenced here may be reused multiple times.
118
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
119
    pub ac_store: StoreRefName,
120
121
    /// Whether the Action Cache store may be written to, this if set to false
122
    /// it is only possible to read from the Action Cache.
123
    #[serde(default)]
124
    pub read_only: bool,
125
}
126
127
#[derive(Deserialize, Serialize, Debug, Clone)]
128
#[serde(deny_unknown_fields)]
129
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
130
pub struct CasStoreConfig {
131
    /// The store name referenced in the `stores` map in the main config.
132
    /// This store name referenced here may be reused multiple times.
133
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
134
    pub cas_store: StoreRefName,
135
136
    /// Optional and experimental: enables the REAPI `SplitBlob`/`SpliceBlob`
137
    /// RPCs used by content-defined chunking clients (e.g. Bazel's
138
    /// `--experimental_remote_cache_chunking`). When set, the capabilities
139
    /// service advertises blob split/splice support and `FastCDC` 2020
140
    /// parameters for this instance. When `cas_store` is a grpc store the
141
    /// RPCs are forwarded to the backend (which must support chunking with
142
    /// matching parameters); otherwise they are served locally.
143
    ///
144
    /// See `nativelink-config/examples/chunking_cas.json5` for a complete
145
    /// configuration example.
146
    ///
147
    /// Default: not set — chunking RPCs are rejected, nothing is advertised,
148
    /// and behavior is identical to when this option did not exist.
149
    #[serde(default)]
150
    pub experimental_chunking: Option<CasChunkingConfig>,
151
}
152
153
#[derive(Deserialize, Serialize, Debug, Clone)]
154
#[serde(deny_unknown_fields)]
155
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
156
pub struct CasChunkingConfig {
157
    /// The store name referenced in the `stores` map in the main config used
158
    /// to persist blob-to-chunks layouts. Keys are the digests of the
159
    /// original blobs and values are serialized chunk layouts (which do not
160
    /// hash to those digests), so this store MUST NOT perform content digest
161
    /// verification and MUST NOT be the same store as `cas_store` — writing
162
    /// layouts into the CAS would overwrite blob content. Using the same
163
    /// store name as `cas_store` is rejected at startup.
164
    ///
165
    /// Required unless `cas_store` is a grpc store: for proxied instances
166
    /// the `SplitBlob`/`SpliceBlob` RPCs are forwarded to the backend, which
167
    /// owns the chunk layouts, and setting an `index_store` is rejected at
168
    /// startup.
169
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
170
    pub index_store: Option<StoreRefName>,
171
172
    /// The average chunk size in bytes advertised to clients through the
173
    /// `FastCDC` 2020 capability parameters and used for server-side
174
    /// chunking in `SplitBlob`. Clients derive the minimum and maximum
175
    /// chunk sizes from this value (avg / 4 and avg * 4). The value must
176
    /// be between 1 KiB and 1 MiB.
177
    ///
178
    /// Default: 524288 (512 KiB)
179
    #[serde(default)]
180
    pub avg_chunk_size_bytes: u64,
181
182
    /// Maximum number of chunks accepted in a `SpliceBlob` request or
183
    /// produced by on-demand chunking in `SplitBlob`. Blobs that would
184
    /// produce more chunks are served without chunking (`SplitBlob` returns
185
    /// `NOT_FOUND` and clients fall back to a regular download). This bounds
186
    /// the size of stored chunk layouts and of `SplitBlobResponse` messages
187
    /// (roughly 80-140 bytes per chunk). At the default average chunk size
188
    /// the default cap supports blobs up to ~25 GiB; note that values above
189
    /// ~50000 may produce responses that exceed default gRPC message size
190
    /// limits on clients.
191
    ///
192
    /// Default: 50000
193
    #[serde(default)]
194
    pub max_chunk_count: u64,
195
}
196
197
impl CasChunkingConfig {
198
    /// Default for `avg_chunk_size_bytes`, the value recommended by the
199
    /// REAPI spec for `FastCdc2020Params`.
200
    pub const DEFAULT_AVG_CHUNK_SIZE_BYTES: u64 = 512 * 1024;
201
    /// Bounds for `avg_chunk_size_bytes` mandated by the REAPI spec for
202
    /// `FastCdc2020Params`.
203
    pub const MIN_AVG_CHUNK_SIZE_BYTES: u64 = 1024;
204
    pub const MAX_AVG_CHUNK_SIZE_BYTES: u64 = 1024 * 1024;
205
    /// Default for `max_chunk_count`.
206
    pub const DEFAULT_MAX_CHUNK_COUNT: u64 = 50_000;
207
208
    /// Returns `avg_chunk_size_bytes` with the default applied.
209
    #[must_use]
210
13
    pub const fn resolved_avg_chunk_size_bytes(&self) -> u64 {
211
13
        if self.avg_chunk_size_bytes == 0 {
212
11
            Self::DEFAULT_AVG_CHUNK_SIZE_BYTES
213
        } else {
214
2
            self.avg_chunk_size_bytes
215
        }
216
13
    }
217
218
    /// Returns `max_chunk_count` with the default applied.
219
    #[must_use]
220
0
    pub const fn resolved_max_chunk_count(&self) -> u64 {
221
0
        if self.max_chunk_count == 0 {
222
0
            Self::DEFAULT_MAX_CHUNK_COUNT
223
        } else {
224
0
            self.max_chunk_count
225
        }
226
0
    }
227
228
    /// Returns `avg_chunk_size_bytes` with the default applied, or an error
229
    /// when the configured value is outside the REAPI-mandated bounds.
230
13
    pub fn validated_avg_chunk_size_bytes(&self) -> Result<u64, Error> {
231
13
        let avg_chunk_size_bytes = self.resolved_avg_chunk_size_bytes();
232
13
        if !(Self::MIN_AVG_CHUNK_SIZE_BYTES..=Self::MAX_AVG_CHUNK_SIZE_BYTES)
233
13
            .contains(&avg_chunk_size_bytes)
234
        {
235
0
            return Err(make_err!(
236
0
                Code::InvalidArgument,
237
0
                "'experimental_chunking.avg_chunk_size_bytes' is {avg_chunk_size_bytes}, must be between {} and {}",
238
0
                Self::MIN_AVG_CHUNK_SIZE_BYTES,
239
0
                Self::MAX_AVG_CHUNK_SIZE_BYTES
240
0
            ));
241
13
        }
242
13
        Ok(avg_chunk_size_bytes)
243
13
    }
244
}
245
246
#[derive(Deserialize, Serialize, Debug, Default)]
247
#[serde(deny_unknown_fields)]
248
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
249
pub struct CapabilitiesRemoteExecutionConfig {
250
    /// Scheduler used to configure the capabilities of remote execution.
251
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
252
    pub scheduler: SchedulerRefName,
253
}
254
255
#[derive(Deserialize, Serialize, Debug, Default)]
256
#[serde(deny_unknown_fields)]
257
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
258
pub struct CapabilitiesConfig {
259
    /// Configuration for remote execution capabilities.
260
    /// If not set the capabilities service will inform the client that remote
261
    /// execution is not supported.
262
    pub remote_execution: Option<CapabilitiesRemoteExecutionConfig>,
263
264
    /// Whether this instance supports Bazel remote cache compression.
265
    /// When enabled, the capabilities service advertises zstd wire compression
266
    /// and the ByteStream/CAS services accept REAPI compressed-blobs/zstd data.
267
    ///
268
    /// Bazel clients enable this with `--remote_cache_compression`.
269
    #[serde(
270
        default,
271
        skip_serializing_if = "is_default",
272
        deserialize_with = "convert_boolean_with_shellexpand"
273
    )]
274
    pub remote_cache_compression: bool,
275
}
276
277
#[derive(Deserialize, Serialize, Debug)]
278
#[serde(deny_unknown_fields)]
279
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
280
pub struct ExecutionConfig {
281
    /// Keep identical in-flight Buck2 actions from different invocations on
282
    /// separate workers. Completed action-cache results remain shared. Pair
283
    /// this with single-use workers when capturing execution-container files.
284
    /// Other build tools and requests without Buck2 invocation metadata retain
285
    /// the default deduplication behavior. All schedulers serving the instance
286
    /// must use a runtime supporting this execution scope before enabling it.
287
    #[serde(default, deserialize_with = "convert_boolean_with_shellexpand")]
288
    pub experimental_buck2_invocation_isolation: bool,
289
290
    /// Seconds between re-sends of the operation's current state on an
291
    /// `Execute` or `WaitExecution` stream that has produced no stage
292
    /// change. The Remote Execution API permits duplicate updates, and the
293
    /// periodic message gives the client and every intermediary (an L7 load
294
    /// balancer, for example) proof the stream is alive. Without it the
295
    /// server is silent for as long as an action sits queued or executing,
296
    /// so a client holding a connection whose server side is gone waits
297
    /// until its own timeout rather than failing when the path died.
298
    ///
299
    /// Default: 0 (disabled, no heartbeats are sent)
300
    #[serde(
301
        default,
302
        deserialize_with = "convert_duration_with_shellexpand",
303
        skip_serializing_if = "is_default",
304
        alias = "execute_stream_heartbeat"
305
    )]
306
    pub execute_stream_heartbeat_s: usize,
307
308
    /// The store name referenced in the `stores` map in the main config.
309
    /// This store name referenced here may be reused multiple times.
310
    /// This value must be a CAS store reference.
311
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
312
    pub cas_store: StoreRefName,
313
314
    /// The scheduler name referenced in the `schedulers` map in the main config.
315
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
316
    pub scheduler: SchedulerRefName,
317
}
318
319
#[derive(Deserialize, Serialize, Debug, Clone)]
320
#[serde(deny_unknown_fields)]
321
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
322
pub struct FetchConfig {
323
    /// The store name referenced in the `stores` map in the main config.
324
    /// This store name referenced here may be reused multiple times.
325
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
326
    pub fetch_store: StoreRefName,
327
328
    /// Optional HTTP and HTTPS downloader. Omitted means lookup-only, with no origin access.
329
    #[serde(default, skip_serializing_if = "Option::is_none")]
330
    pub downloader: Option<FetchDownloaderConfig>,
331
}
332
333
3
const fn default_allow_unknown_fetch_qualifiers() -> bool {
334
3
    true
335
3
}
336
337
/// Opt-in origin retrieval for the Remote Asset Fetch service.
338
#[derive(Deserialize, Serialize, Debug, Clone)]
339
#[serde(deny_unknown_fields)]
340
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
341
pub struct FetchDownloaderConfig {
342
    /// CAS used by this instance's CAS and `ByteStream` services.
343
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
344
    pub cas_store: StoreRefName,
345
346
    /// Explicit HTTP forward proxy URL, optionally including credentials.
347
    /// Prefer `http_proxy_secret_file` for credentials. Setting both is invalid.
348
    /// The default HTTP client connects directly and ignores proxy environment variables.
349
    /// An explicit proxy adds a concurrent alternative; the first successful transfer wins.
350
    #[serde(default, skip_serializing_if = "Option::is_none")]
351
    pub http_proxy: Option<String>,
352
353
    /// File containing the proxy URL. Whitespace is trimmed; read once at startup.
354
    #[serde(default, skip_serializing_if = "Option::is_none")]
355
    pub http_proxy_secret_file: Option<String>,
356
357
    /// Hosts bypassing the explicit proxy, using `reqwest` matching rules.
358
    /// Only applies to the configured proxy; an empty list bypasses no hosts.
359
    /// Proxy environment variables are not consulted.
360
    #[serde(default)]
361
    pub no_proxy: Vec<String>,
362
363
    /// Reject downloads without a supported checksum. Default: false.
364
    #[serde(default)]
365
    pub require_checksum: bool,
366
367
    /// Accept unrecognized qualifiers as opaque cache-key metadata without applying
368
    /// their semantics. Set false to reject them. Default: true.
369
    /// `bazel.canonical_id` is recognized as cache identity metadata.
370
    #[serde(default = "default_allow_unknown_fetch_qualifiers")]
371
    pub allow_unknown_qualifiers: bool,
372
373
    /// Maximum downloaded object size, checked even without Content-Length.
374
    /// Zero means no size limit (the default).
375
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
376
    pub max_size_bytes: u64,
377
378
    /// Maximum simultaneous download requests per instance, including CAS publication.
379
    /// Zero selects the default: 4. Each request can race two attempts when a proxy
380
    /// is configured. A positive `max_size_bytes` also bounds each attempt's spool.
381
    #[serde(default)]
382
    pub max_concurrent_downloads: usize,
383
384
    /// Total origin retrieval timeout across all candidate URIs, including CAS writes.
385
    /// Request timeouts are clamped to this limit. Zero selects the default: 300 seconds.
386
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
387
    pub timeout_s: u64,
388
}
389
390
#[derive(Deserialize, Serialize, Debug, Clone)]
391
#[serde(deny_unknown_fields)]
392
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
393
pub struct PushConfig {
394
    /// The store name referenced in the `stores` map in the main config.
395
    /// This store name referenced here may be reused multiple times.
396
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
397
    pub push_store: StoreRefName,
398
399
    /// Whether the Action Cache store may be written to, this if set to false
400
    /// it is only possible to read from the Action Cache.
401
    #[serde(default)]
402
    pub read_only: bool,
403
}
404
405
// From https://github.com/serde-rs/serde/issues/818#issuecomment-287438544
406
98
fn is_default<T: Default + PartialEq>(t: &T) -> bool {
407
98
    *t == Default::default()
408
98
}
409
410
#[derive(Deserialize, Serialize, Debug, PartialEq, Eq)]
411
#[serde(deny_unknown_fields)]
412
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
413
pub struct ByteStreamConfig {
414
    /// Name of the store in the "stores" configuration.
415
    pub cas_store: StoreRefName,
416
417
    /// Max number of bytes to send on each grpc stream chunk.
418
    /// According to <https://github.com/grpc/grpc.github.io/issues/371>
419
    /// 16KiB - 64KiB is optimal.
420
    ///
421
    ///
422
    /// Default: 64KiB
423
    #[serde(
424
        default,
425
        deserialize_with = "convert_data_size_with_shellexpand",
426
        skip_serializing_if = "is_default"
427
    )]
428
    pub max_bytes_per_stream: usize,
429
430
    /// In the event a client disconnects while uploading a blob, we will hold
431
    /// the internal stream open for this many seconds before closing it.
432
    /// This allows clients that disconnect to reconnect and continue uploading
433
    /// the same blob.
434
    ///
435
    /// Default: 10 seconds
436
    #[serde(
437
        default,
438
        deserialize_with = "convert_duration_with_shellexpand",
439
        skip_serializing_if = "is_default",
440
        alias = "persist_stream_on_disconnect_timeout"
441
    )]
442
    pub persist_stream_on_disconnect_timeout_s: usize,
443
444
    /// Recover a resumed upload (a write whose first offset is nonzero) that
445
    /// reaches an instance holding no state for its UUID, which happens when
446
    /// several instances sit behind a load balancer without session affinity.
447
    /// When the blob already exists in the store, the write completes
448
    /// immediately; otherwise the client receives UNAVAILABLE, re-queries the
449
    /// write status (an instance holding the upload answers with its offset,
450
    /// any other answers 0) and resumes or restarts from there. With this
451
    /// off, such a resume fails the upload with a non-retryable
452
    /// "out of order data" error.
453
    ///
454
    /// Default: true
455
    #[serde(default = "default_true")]
456
    pub recover_unknown_uuid_resumes: bool,
457
}
458
459
// Not derived: the derive would default `recover_unknown_uuid_resumes` to
460
// false, diverging from the deserialization default above.
461
impl Default for ByteStreamConfig {
462
50
    fn default() -> Self {
463
50
        Self {
464
50
            cas_store: StoreRefName::default(),
465
50
            max_bytes_per_stream: 0,
466
50
            persist_stream_on_disconnect_timeout_s: 0,
467
50
            recover_unknown_uuid_resumes: true,
468
50
        }
469
50
    }
470
}
471
472
// Older bytestream config. All fields are as per the newer docs, but this requires
473
// the hashed `cas_stores` v.s. the WithInstanceName approach. This should _not_ be updated
474
// with newer fields, and eventually dropped
475
#[derive(Deserialize, Serialize, Debug, Clone)]
476
#[serde(deny_unknown_fields)]
477
pub struct OldByteStreamConfig {
478
    pub cas_stores: HashMap<InstanceName, StoreRefName>,
479
    #[serde(
480
        default,
481
        deserialize_with = "convert_data_size_with_shellexpand",
482
        skip_serializing_if = "is_default"
483
    )]
484
    pub max_bytes_per_stream: usize,
485
    #[serde(
486
        default,
487
        deserialize_with = "convert_data_size_with_shellexpand",
488
        skip_serializing_if = "is_default"
489
    )]
490
    pub max_decoding_message_size: usize,
491
    #[serde(
492
        default,
493
        deserialize_with = "convert_duration_with_shellexpand",
494
        skip_serializing_if = "is_default",
495
        alias = "persist_stream_on_disconnect_timeout"
496
    )]
497
    pub persist_stream_on_disconnect_timeout_s: usize,
498
}
499
500
#[derive(Deserialize, Serialize, Debug)]
501
#[serde(deny_unknown_fields)]
502
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
503
pub struct WorkerApiConfig {
504
    /// The scheduler name referenced in the `schedulers` map in the main config.
505
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
506
    pub scheduler: SchedulerRefName,
507
508
    /// Disable the periodic sweep that tells workers to kill operations
509
    /// the scheduler no longer has executing on them (for example because
510
    /// every client disconnected before the action finished). With the
511
    /// sweep disabled such orphaned actions run to completion and still
512
    /// warm the action cache, which can be preferable for deployments
513
    /// with long or expensive actions whose clients merely retry.
514
    ///
515
    /// Default: false (the sweep runs)
516
    #[serde(default)]
517
    pub disable_kill_revoked_operations: bool,
518
519
    /// How often, in seconds, the scheduler checks for operations that
520
    /// are still running on a worker but are no longer executing
521
    /// according to the state manager, and tells the worker to kill
522
    /// them. Each pass costs one state-manager lookup per running
523
    /// operation, so store-backed deployments with many concurrent
524
    /// actions may want a longer interval.
525
    ///
526
    /// Default: 5 (0 uses the default)
527
    #[serde(default)]
528
    pub kill_revoked_operations_interval_s: u64,
529
}
530
531
#[derive(Deserialize, Serialize, Debug, Default)]
532
#[serde(deny_unknown_fields)]
533
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
534
pub struct AdminConfig {
535
    /// Path to register the admin API. If path is "/admin", and your
536
    /// domain is "example.com", you can reach the endpoint with:
537
    /// <http://example.com/admin>.
538
    ///
539
    /// Default: "/admin"
540
    #[serde(default)]
541
    pub path: String,
542
}
543
544
#[derive(Deserialize, Serialize, Debug, Default)]
545
#[serde(deny_unknown_fields)]
546
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
547
pub struct HealthConfig {
548
    /// Path to register the health status check. If path is "/status", and your
549
    /// domain is "example.com", you can reach the endpoint with:
550
    /// <http://example.com/status>.
551
    ///
552
    /// Default: "/status"
553
    #[serde(default)]
554
    pub path: String,
555
556
    /// Timeout on health checks. Default: 5s.
557
    #[serde(default)]
558
    pub timeout_seconds: u64,
559
560
    /// Path of the readiness check, the stricter sibling of `path`: it
561
    /// answers 503 while any component is still initializing, where `path`
562
    /// answers 200. A worker's registration with its scheduler is such a
563
    /// component, so a Kubernetes readiness probe on this path turns Ready
564
    /// only once the worker can take work. Must differ from `path`; the
565
    /// same path for both is refused at startup.
566
    ///
567
    /// Default: "/ready"
568
    #[serde(default)]
569
    pub readiness_path: String,
570
}
571
572
#[derive(Deserialize, Serialize, Debug)]
573
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
574
pub struct BepConfig {
575
    /// The store to publish build events to.
576
    /// The store name referenced in the `stores` map in the main config.
577
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
578
    pub store: StoreRefName,
579
}
580
581
#[derive(Deserialize, Serialize, Clone, Debug, Default)]
582
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
583
pub struct IdentityHeaderSpec {
584
    /// The name of the header to look for the identity in.
585
    /// Default: "x-identity"
586
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
587
    pub header_name: Option<String>,
588
589
    /// If the header is required to be set or fail the request.
590
    #[serde(default)]
591
    pub required: bool,
592
}
593
594
#[derive(Deserialize, Serialize, Clone, Debug)]
595
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
596
pub struct OriginEventsPublisherSpec {
597
    /// The store to publish nativelink events to.
598
    /// The store name referenced in the `stores` map in the main config.
599
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
600
    pub store: StoreRefName,
601
}
602
603
#[derive(Deserialize, Serialize, Clone, Debug)]
604
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
605
pub struct OriginEventsSpec {
606
    /// The publisher configuration for origin events.
607
    pub publisher: OriginEventsPublisherSpec,
608
609
    /// The maximum number of events to queue before applying back pressure.
610
    /// IMPORTANT: Backpressure causes all clients to slow down significantly.
611
    /// Zero is default.
612
    ///
613
    /// Default: 65536 (zero defaults to this)
614
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
615
    pub max_event_queue_size: usize,
616
}
617
618
#[derive(Deserialize, Serialize, Debug)]
619
#[serde(deny_unknown_fields)]
620
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
621
pub struct ServicesConfig {
622
    /// The Content Addressable Storage (CAS) backend config.
623
    /// The key is the `instance_name` used in the protocol and the
624
    /// value is the underlying CAS store config.
625
    #[serde(
626
        default,
627
        deserialize_with = "super::backcompat::opt_vec_with_instance_name"
628
    )]
629
    pub cas: Option<Vec<WithInstanceName<CasStoreConfig>>>,
630
631
    /// The Action Cache (AC) backend config.
632
    /// The key is the `instance_name` used in the protocol and the
633
    /// value is the underlying AC store config.
634
    #[serde(
635
        default,
636
        deserialize_with = "super::backcompat::opt_vec_with_instance_name"
637
    )]
638
    pub ac: Option<Vec<WithInstanceName<AcStoreConfig>>>,
639
640
    /// Capabilities service is required in order to use most of the
641
    /// bazel protocol. This service is used to provide the supported
642
    /// features and versions of this bazel gRPC service.
643
    #[serde(
644
        default,
645
        deserialize_with = "super::backcompat::opt_vec_with_instance_name"
646
    )]
647
    pub capabilities: Option<Vec<WithInstanceName<CapabilitiesConfig>>>,
648
649
    /// The remote execution service configuration.
650
    /// NOTE: This service is under development and is currently just a
651
    /// place holder.
652
    #[serde(
653
        default,
654
        deserialize_with = "super::backcompat::opt_vec_with_instance_name"
655
    )]
656
    pub execution: Option<Vec<WithInstanceName<ExecutionConfig>>>,
657
658
    /// This is the service used to stream data to and from the CAS.
659
    /// Bazel's protocol strongly encourages users to use this streaming
660
    /// interface to interact with the CAS when the data is large.
661
    #[serde(default, deserialize_with = "super::backcompat::opt_bytestream")]
662
    pub bytestream: Option<Vec<WithInstanceName<ByteStreamConfig>>>,
663
664
    /// These two are collectively the Remote Asset protocol, but it's
665
    /// defined as two separate services
666
    #[serde(
667
        default,
668
        deserialize_with = "super::backcompat::opt_vec_with_instance_name"
669
    )]
670
    pub fetch: Option<Vec<WithInstanceName<FetchConfig>>>,
671
672
    #[serde(
673
        default,
674
        deserialize_with = "super::backcompat::opt_vec_with_instance_name"
675
    )]
676
    pub push: Option<Vec<WithInstanceName<PushConfig>>>,
677
678
    /// This is the service used for workers to connect and communicate
679
    /// through.
680
    /// NOTE: This service should be served on a different, non-public port.
681
    /// In other words, `worker_api` configuration should not have any other
682
    /// services that are served on the same port. Doing so is a security
683
    /// risk, as workers have a different permission set than a client
684
    /// that makes the remote execution/cache requests.
685
    pub worker_api: Option<WorkerApiConfig>,
686
687
    /// Experimental - Build Event Protocol (BEP) configuration. This is
688
    /// the service that will consume build events from the client and
689
    /// publish them to a store for processing by an external service.
690
    pub experimental_bep: Option<BepConfig>,
691
692
    /// This is the service for any administrative tasks.
693
    /// It provides a REST API endpoint for administrative purposes.
694
    pub admin: Option<AdminConfig>,
695
696
    /// This is the service for health status check.
697
    pub health: Option<HealthConfig>,
698
}
699
700
#[derive(Deserialize, Serialize, Debug)]
701
#[serde(deny_unknown_fields)]
702
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
703
pub struct TlsConfig {
704
    /// Path to the certificate file.
705
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
706
    pub cert_file: String,
707
708
    /// Path to the private key file.
709
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
710
    pub key_file: String,
711
712
    /// Path to the certificate authority for mTLS, if client authentication is
713
    /// required for this endpoint.
714
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
715
    pub client_ca_file: Option<String>,
716
717
    /// Path to the certificate revocation list for mTLS, if client
718
    /// authentication is required for this endpoint.
719
    #[serde(default, deserialize_with = "convert_optional_string_with_shellexpand")]
720
    pub client_crl_file: Option<String>,
721
}
722
723
/// Advanced Http configurations. These are generally should not be set.
724
/// For documentation on what each of these do, see the hyper documentation:
725
/// See: <https://docs.rs/hyper/latest/hyper/server/conn/struct.Http.html>
726
///
727
/// Note: All of these default to hyper's default values unless otherwise
728
/// specified.
729
#[derive(Deserialize, Serialize, Debug, Default, Clone, Copy)]
730
#[serde(deny_unknown_fields)]
731
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
732
pub struct HttpServerConfig {
733
    /// Interval to send keep-alive pings via HTTP2.
734
    /// Note: This is in seconds.
735
    #[serde(
736
        default,
737
        deserialize_with = "convert_optional_numeric_with_shellexpand"
738
    )]
739
    pub http2_keep_alive_interval: Option<u32>,
740
741
    #[serde(
742
        default,
743
        deserialize_with = "convert_optional_numeric_with_shellexpand"
744
    )]
745
    pub experimental_http2_max_pending_accept_reset_streams: Option<u32>,
746
747
    #[serde(
748
        default,
749
        deserialize_with = "convert_optional_numeric_with_shellexpand"
750
    )]
751
    pub experimental_http2_initial_stream_window_size: Option<u32>,
752
753
    #[serde(
754
        default,
755
        deserialize_with = "convert_optional_numeric_with_shellexpand"
756
    )]
757
    pub experimental_http2_initial_connection_window_size: Option<u32>,
758
759
    #[serde(default)]
760
    pub experimental_http2_adaptive_window: Option<bool>,
761
762
    #[serde(
763
        default,
764
        deserialize_with = "convert_optional_numeric_with_shellexpand"
765
    )]
766
    pub experimental_http2_max_frame_size: Option<u32>,
767
768
    #[serde(
769
        default,
770
        deserialize_with = "convert_optional_numeric_with_shellexpand"
771
    )]
772
    pub experimental_http2_max_concurrent_streams: Option<u32>,
773
774
    #[serde(
775
        default,
776
        deserialize_with = "convert_optional_numeric_with_shellexpand",
777
        alias = "experimental_http2_keep_alive_timeout"
778
    )]
779
    pub experimental_http2_keep_alive_timeout_s: Option<u32>,
780
781
    #[serde(
782
        default,
783
        deserialize_with = "convert_optional_numeric_with_shellexpand"
784
    )]
785
    pub experimental_http2_max_send_buf_size: Option<u32>,
786
787
    #[serde(default)]
788
    pub experimental_http2_enable_connect_protocol: Option<bool>,
789
790
    #[serde(
791
        default,
792
        deserialize_with = "convert_optional_numeric_with_shellexpand"
793
    )]
794
    pub experimental_http2_max_header_list_size: Option<u32>,
795
}
796
797
#[derive(Deserialize, Serialize, Debug)]
798
#[serde(rename_all = "snake_case")]
799
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
800
pub enum ListenerConfig {
801
    /// Listener for HTTP/HTTPS/HTTP2 sockets.
802
    Http(HttpListener),
803
}
804
805
#[derive(Deserialize, Serialize, Debug, Default)]
806
#[serde(deny_unknown_fields)]
807
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
808
pub struct HttpListener {
809
    /// Address to listen on. Example: `127.0.0.1:8080` or `:8080` to listen
810
    /// to all IPs.
811
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
812
    pub socket_address: String,
813
814
    /// Allow binding `socket_address` before it is assigned locally.
815
    ///
816
    /// Default: false
817
    #[serde(default)]
818
    pub freebind: bool,
819
820
    /// Disable batching of small TCP writes on accepted connections, including
821
    /// HTTP/2 control frames.
822
    /// Applies to both plaintext and TLS connections. Set to true to opt into
823
    /// sending small writes promptly. When false or omitted, preserves default
824
    /// TCP buffering behavior.
825
    /// Older binaries without this option reject the field even when set to
826
    /// false. Config templates must omit it until all consuming binaries support
827
    /// it. Remove the field entirely before rolling back to an older binary.
828
    ///
829
    /// Default: false
830
    #[serde(default)]
831
    pub tcp_nodelay: bool,
832
833
    /// Data transport compression configuration to use for this service.
834
    #[serde(default)]
835
    pub compression: HttpCompressionConfig,
836
837
    /// Advanced Http server configuration.
838
    #[serde(default)]
839
    pub advanced_http: HttpServerConfig,
840
841
    /// Maximum number of bytes to decode on each grpc stream chunk.
842
    /// Default: 4 MiB
843
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
844
    pub max_decoding_message_size: usize,
845
846
    /// Tls Configuration for this server.
847
    /// If not set, the server will not use TLS.
848
    ///
849
    /// Default: None
850
    #[serde(default)]
851
    pub tls: Option<TlsConfig>,
852
}
853
854
#[derive(Deserialize, Serialize, Debug)]
855
#[serde(deny_unknown_fields)]
856
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
857
pub struct ServerConfig {
858
    /// Name of the server. This is used to help identify the service
859
    /// for telemetry and logs.
860
    ///
861
    /// Default: {index of server in config}
862
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
863
    pub name: String,
864
865
    /// Configuration
866
    pub listener: ListenerConfig,
867
868
    /// Services to attach to server.
869
    pub services: Option<ServicesConfig>,
870
871
    /// The config related to identifying the client.
872
    /// Default: {see `IdentityHeaderSpec`}
873
    #[serde(default)]
874
    pub experimental_identity_header: IdentityHeaderSpec,
875
}
876
877
/// The scale a CPU property is advertised on.
878
#[derive(Copy, Clone, Deserialize, Serialize, Debug, Default, PartialEq, Eq)]
879
#[serde(rename_all = "snake_case")]
880
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
881
pub enum CpuUnit {
882
    /// Whole cores, rounded down: what `cpu_count: { query_cmd: "nproc" }`
883
    /// advertises and what an action asking for `cpu_count=1` means.
884
    #[default]
885
    Cores,
886
    /// Thousandths of a core, for a fleet whose actions and workers already
887
    /// speak that scale.
888
    Millicores,
889
}
890
891
/// Advertise CPU and memory from what the worker can actually see. The
892
/// worker reads `cpu.max` and `memory.max` from its own cgroup v2 directory
893
/// (found through `/proc/self/cgroup`, so a privileged container that sees
894
/// the host's tree still finds its own) up to the nearest limited ancestor,
895
/// the pod's limits on Kubernetes; with no limit at any level the configured
896
/// properties stand. It takes off what it needs for itself, divides
897
/// the memory by the enforcement headroom, and sets the two properties to
898
/// the result at registration. What the scheduler packs against is then
899
/// derived from the one number that is enforced, instead of typed in twice.
900
#[derive(Deserialize, Serialize, Debug, Clone)]
901
#[serde(deny_unknown_fields)]
902
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
903
pub struct CapacityConfig {
904
    /// Property that carries CPU, on the scale `cpu_unit` names.
905
    /// Default: `cpu_count`
906
    #[serde(
907
        default = "default_capacity_cpu_property_name",
908
        deserialize_with = "convert_string_with_shellexpand"
909
    )]
910
    pub cpu_property_name: String,
911
912
    /// Property that carries memory, in KiB.
913
    /// Default: `memory_kb`
914
    #[serde(
915
        default = "default_capacity_memory_property_name",
916
        deserialize_with = "convert_string_with_shellexpand"
917
    )]
918
    pub memory_property_name: String,
919
920
    /// The scale the CPU property is advertised on. Whole cores by default,
921
    /// the scale every other example in this configuration uses; a fleet
922
    /// that advertises and requests thousandths of a core sets `millicores`.
923
    /// Getting this wrong is a thousandfold error in how many actions the
924
    /// scheduler packs onto the worker.
925
    /// Default: cores
926
    #[serde(default)]
927
    pub cpu_unit: CpuUnit,
928
929
    /// CPU the worker keeps for itself, in thousandths of a core whatever
930
    /// `cpu_unit` says.
931
    /// Default: 1000
932
    #[serde(
933
        default = "default_capacity_overhead_cpu_millicores",
934
        deserialize_with = "convert_numeric_with_shellexpand"
935
    )]
936
    pub overhead_cpu_millicores: u64,
937
938
    /// Memory the worker keeps for itself (the process, its directory cache,
939
    /// output buffers), in KiB.
940
    /// Default: 2097152 (2 GiB)
941
    #[serde(
942
        default = "default_capacity_overhead_memory_kb",
943
        deserialize_with = "convert_numeric_with_shellexpand"
944
    )]
945
    pub overhead_memory_kb: u64,
946
947
    /// Percent the advertised memory is reduced by, so that actions at their
948
    /// enforcement ceiling (reservation plus headroom) still fit the limit.
949
    /// Unset, it follows `resource_enforcement.memory_headroom_percent`
950
    /// while memory enforcement is on, and is 0 otherwise, so the two
951
    /// cannot drift apart by being typed twice.
952
    /// Default: unset
953
    #[serde(
954
        default,
955
        deserialize_with = "convert_optional_numeric_with_shellexpand"
956
    )]
957
    pub memory_headroom_percent: Option<u64>,
958
}
959
960
0
fn default_capacity_cpu_property_name() -> String {
961
0
    "cpu_count".to_string()
962
0
}
963
964
0
fn default_capacity_memory_property_name() -> String {
965
0
    "memory_kb".to_string()
966
0
}
967
968
0
const fn default_capacity_overhead_cpu_millicores() -> u64 {
969
0
    1000
970
0
}
971
972
0
const fn default_capacity_overhead_memory_kb() -> u64 {
973
0
    2_097_152
974
0
}
975
976
#[derive(Deserialize, Serialize, Debug, Clone)]
977
#[serde(rename_all = "snake_case")]
978
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
979
pub enum WorkerProperty {
980
    /// List of static values.
981
    /// Note: Generally there should only ever be 1 value, but if the platform
982
    /// property key is `PropertyType::Priority` it may have more than one value.
983
    #[serde(deserialize_with = "convert_vec_string_with_shellexpand")]
984
    Values(Vec<String>),
985
986
    /// A dynamic configuration. The string will be executed as a command
987
    /// (not shell) and will be split by "\n" (new line character).
988
    QueryCmd(String),
989
}
990
991
/// Generic config for an endpoint and associated configs.
992
#[derive(Deserialize, Serialize, Debug, Default)]
993
#[serde(deny_unknown_fields)]
994
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
995
pub struct EndpointConfig {
996
    /// URI of the endpoint.
997
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
998
    pub uri: String,
999
1000
    /// Timeout in seconds for connecting to the endpoint and for a request
1001
    /// to be answered. The worker's messages to the scheduler (keepalives,
1002
    /// acknowledgements, results) ride on the one `ConnectWorker` stream
1003
    /// opened at registration, which this does not bound; the `GoingAway`
1004
    /// sent at shutdown is bounded by it, so a stalled connection cannot
1005
    /// hold a pod past its grace period. A keepalive goes out every half of
1006
    /// it.
1007
    /// Default: 5 seconds
1008
    pub timeout: Option<f32>,
1009
1010
    /// TCP keepalive interval (seconds), probing the socket under the
1011
    /// scheduler connection so a dead peer is noticed at the OS level.
1012
    /// If not set or 0, defaults to 30 seconds.
1013
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1014
    pub tcp_keepalive_s: u64,
1015
1016
    /// HTTP/2 keepalive interval (seconds): PING frames on the scheduler
1017
    /// connection, so one that has gone dead underneath fails instead of
1018
    /// hanging every message on it.
1019
    /// If not set or 0, defaults to 30 seconds.
1020
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1021
    pub http2_keepalive_interval_s: u64,
1022
1023
    /// HTTP/2 keepalive timeout (seconds): a PING unanswered for this long
1024
    /// ends the connection, and the worker reconnects.
1025
    /// If not set or 0, defaults to 20 seconds.
1026
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1027
    pub http2_keepalive_timeout_s: u64,
1028
1029
    /// The TLS configuration to use to connect to the endpoint.
1030
    pub tls_config: Option<ClientTlsConfig>,
1031
}
1032
1033
#[derive(Copy, Clone, Deserialize, Serialize, Debug, Default, PartialEq, Eq)]
1034
#[serde(rename_all = "snake_case")]
1035
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1036
pub enum MemoryEnforcement {
1037
    /// Measure only.
1038
    None,
1039
    /// Kill the action's process group once two consecutive samples exceed
1040
    /// the reservation plus headroom, or one sample exceeds twice it.
1041
    #[default]
1042
    Soft,
1043
}
1044
1045
#[derive(Clone, Deserialize, Serialize, Debug)]
1046
#[serde(deny_unknown_fields)]
1047
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1048
pub struct ResourceEnforcementConfig {
1049
    /// What to do with an action that exceeds its memory reservation.
1050
    /// Default: soft
1051
    #[serde(default)]
1052
    pub memory: MemoryEnforcement,
1053
1054
    /// Whether to refuse an action whose disk reservation exceeds the free
1055
    /// space under the work directory, less what the actions already
1056
    /// admitted reserved, before its inputs are fetched. The
1057
    /// refusal is `ResourceExhausted`, which the scheduler requeues without
1058
    /// counting an attempt and holds off this worker until its next
1059
    /// keepalive.
1060
    /// Default: none
1061
    #[serde(default)]
1062
    pub disk: DiskEnforcement,
1063
1064
    /// Platform property carrying the action's disk reservation in KiB.
1065
    /// Default: `disk_kb`
1066
    #[serde(
1067
        default = "default_disk_property_name",
1068
        deserialize_with = "convert_string_with_shellexpand"
1069
    )]
1070
    pub disk_property_name: String,
1071
1072
    /// Platform property carrying the action's memory reservation in KiB,
1073
    /// as the scheduler sends it. An action without the property is not
1074
    /// enforced.
1075
    /// Default: `memory_kb`
1076
    #[serde(
1077
        default = "default_memory_property_name",
1078
        deserialize_with = "convert_string_with_shellexpand"
1079
    )]
1080
    pub memory_property_name: String,
1081
1082
    /// Percent above the reservation an action may reach before it is
1083
    /// killed.
1084
    /// Default: 20
1085
    #[serde(
1086
        default = "default_memory_headroom_percent",
1087
        deserialize_with = "convert_numeric_with_shellexpand"
1088
    )]
1089
    pub memory_headroom_percent: u64,
1090
1091
    /// Percent above its disk reservation an action's own files may reach
1092
    /// before it is killed, with `disk: soft`.
1093
    /// Default: 20
1094
    #[serde(
1095
        default = "default_memory_headroom_percent",
1096
        deserialize_with = "convert_numeric_with_shellexpand"
1097
    )]
1098
    pub disk_headroom_percent: u64,
1099
1100
    /// Kill one running action once the worker's cgroup has spent at least
1101
    /// this share of the last ten seconds, as a whole number from 0 to 100,
1102
    /// with every task stalled on memory (`full avg10` in cgroup v2
1103
    /// `memory.pressure`) for `memory_pressure_kill_after_s` without a
1104
    /// break. A worker whose actions fit under its limit only by thrashing
1105
    /// never reaches the OOM killer and stops answering the scheduler; this
1106
    /// ends the action instead, as a memory kill, so the scheduler requeues
1107
    /// it with a larger reservation. The kill lands on the action furthest
1108
    /// over its reservation, or the largest when none is over, and never
1109
    /// on one that reserves the whole worker. It does not check that the
1110
    /// actions caused the pressure: pressure from the worker itself (page
1111
    /// cache from the filesystem store, a large upload) still kills an
1112
    /// action. Needs `memory: soft`, which supplies the per-action samples
1113
    /// the choice is made from. Values over 100 are read as 100. 0 disables.
1114
    /// Default: 0
1115
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1116
    pub memory_pressure_kill_percent: u64,
1117
1118
    /// How long `memory.pressure` must stay at or above
1119
    /// `memory_pressure_kill_percent` before an action is killed, in
1120
    /// seconds. Another kill waits this long again. 0 is read as 1.
1121
    /// Default: 30
1122
    #[serde(
1123
        default = "default_memory_pressure_kill_after_s",
1124
        deserialize_with = "convert_duration_with_shellexpand"
1125
    )]
1126
    pub memory_pressure_kill_after_s: u64,
1127
}
1128
1129
0
const fn default_memory_pressure_kill_after_s() -> u64 {
1130
0
    30
1131
0
}
1132
1133
0
fn default_memory_property_name() -> String {
1134
0
    "memory_kb".to_string()
1135
0
}
1136
1137
22
const fn default_true() -> bool {
1138
22
    true
1139
22
}
1140
1141
0
fn default_disk_property_name() -> String {
1142
0
    "disk_kb".to_string()
1143
0
}
1144
1145
#[derive(Copy, Clone, Deserialize, Serialize, Debug, Default, PartialEq, Eq)]
1146
#[serde(rename_all = "snake_case")]
1147
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1148
pub enum DiskEnforcement {
1149
    /// Fetch inputs regardless of free space.
1150
    #[default]
1151
    None,
1152
    /// Refuse the action when the free space under the work directory is
1153
    /// below its reservation.
1154
    Guard,
1155
    /// `guard`, and kill an action whose files under its own directory
1156
    /// grow past its reservation plus `disk_headroom_percent`. Sampled
1157
    /// every ten seconds by walking the action directory, counting only
1158
    /// files the action itself wrote (inputs are hard links into the CAS
1159
    /// and are not counted).
1160
    Soft,
1161
}
1162
1163
0
const fn default_memory_headroom_percent() -> u64 {
1164
0
    20
1165
0
}
1166
1167
#[derive(Copy, Clone, Deserialize, Serialize, Debug, Default)]
1168
#[serde(rename_all = "snake_case")]
1169
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1170
pub enum UploadCacheResultsStrategy {
1171
    /// Only upload action results with an exit code of 0.
1172
    #[default]
1173
    SuccessOnly,
1174
1175
    /// Don't upload any action results.
1176
    Never,
1177
1178
    /// Upload all action results that complete.
1179
    Everything,
1180
1181
    /// Only upload action results that fail.
1182
    FailuresOnly,
1183
}
1184
1185
#[derive(Clone, Deserialize, Serialize, Debug)]
1186
#[serde(rename_all = "snake_case")]
1187
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1188
pub enum EnvironmentSource {
1189
    /// The name of the platform property in the action to get the value from.
1190
    Property(String),
1191
1192
    /// The raw value to set.
1193
    Value(#[serde(deserialize_with = "convert_string_with_shellexpand")] String),
1194
1195
    /// Take the value from the local environment corresponding to the name key
1196
    FromEnvironment,
1197
1198
    /// The max amount of time in milliseconds the command is allowed to run
1199
    /// (requested by the client).
1200
    TimeoutMillis,
1201
1202
    /// A special file path will be provided that can be used to communicate
1203
    /// with the parent process about out-of-band information. This file
1204
    /// will be read after the command has finished executing. Based on the
1205
    /// contents of the file, the behavior of the result may be modified.
1206
    ///
1207
    /// The format of the file contents should be json with the following
1208
    /// schema:
1209
    /// {
1210
    ///   // If set the command will be considered a failure.
1211
    ///   // May be one of the following static strings:
1212
    ///   // "timeout": Will Consider this task to be a timeout.
1213
    ///   "failure": "timeout",
1214
    /// }
1215
    ///
1216
    /// The file may also carry `peak_gpu_memory_kb`, a number: the peak
1217
    /// device memory the action held on its GPU, in KiB, when whatever
1218
    /// wraps the action measured it. The worker reads no device itself; it
1219
    /// reports the figure with the action's other resource usage, and a
1220
    /// scheduler that learns from its workers sizes the action by it.
1221
    ///
1222
    /// All fields are optional, file does not need to be created and may be
1223
    /// empty.
1224
    SideChannelFile,
1225
1226
    /// A "root" directory for the action. This directory can be used to
1227
    /// store temporary files that are not needed after the action has
1228
    /// completed. This directory will be purged after the action has
1229
    /// completed.
1230
    ///
1231
    /// For example:
1232
    /// If an action writes temporary data to a path but nativelink should
1233
    /// clean up this path after the job has executed, you may create any
1234
    /// directory under the path provided in this variable. A common pattern
1235
    /// would be to use `entrypoint` to set a shell script that reads this
1236
    /// variable, `mkdir $ENV_VAR_NAME/tmp` and `export TMPDIR=$ENV_VAR_NAME/tmp`.
1237
    /// Another example might be to bind-mount the `/tmp` path in a container to
1238
    /// this path in `entrypoint`.
1239
    ActionDirectory,
1240
}
1241
1242
#[derive(Deserialize, Serialize, Debug, Default)]
1243
#[serde(deny_unknown_fields)]
1244
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1245
pub struct UploadActionResultConfig {
1246
    /// Underlying AC store that the worker will use to publish execution results
1247
    /// into. Objects placed in this store should be reachable from the
1248
    /// scheduler/client-cas after they have finished updating.
1249
    /// Default: {No uploading is done}
1250
    pub ac_store: Option<StoreRefName>,
1251
1252
    /// In which situations should the results be published to the `ac_store`,
1253
    /// if set to `SuccessOnly` then only results with an exit code of 0 will be
1254
    /// uploaded, if set to Everything all completed results will be uploaded.
1255
    ///
1256
    /// Default: `SuccessOnly`
1257
    #[serde(default)]
1258
    pub upload_ac_results_strategy: UploadCacheResultsStrategy,
1259
1260
    /// Store to upload historical results to. This should be a CAS store if set.
1261
    ///
1262
    /// Default: {CAS store of parent}
1263
    pub historical_results_store: Option<StoreRefName>,
1264
1265
    /// In which situations should the results be published to the historical CAS.
1266
    /// The historical CAS is where failures are published. These messages conform
1267
    /// to the CAS key-value lookup format and are always a `HistoricalExecuteResponse`
1268
    /// serialized message.
1269
    ///
1270
    /// Default: `FailuresOnly`
1271
    #[serde(default)]
1272
    pub upload_historical_results_strategy: Option<UploadCacheResultsStrategy>,
1273
1274
    /// Template to use for the `ExecuteResponse.message` property. This message
1275
    /// is attached to the response before it is sent to the client. The following
1276
    /// special variables are supported:
1277
    /// - `digest_function`: Digest function used to calculate the action digest.
1278
    /// - `action_digest_hash`: Action digest hash.
1279
    /// - `action_digest_size`: Action digest size.
1280
    /// - `historical_results_hash`: `HistoricalExecuteResponse` digest hash.
1281
    /// - `historical_results_size`: `HistoricalExecuteResponse` digest size.
1282
    ///
1283
    /// A common use case of this is to provide a link to the web page that
1284
    /// contains more useful information for the user.
1285
    ///
1286
    /// An example that is fully compatible with `bb_browser` is:
1287
    /// <https://example.com/my-instance-name-here/blobs/{digest_function}/action/{action_digest_hash}-{action_digest_size}/>
1288
    ///
1289
    /// Default: "" (no message)
1290
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
1291
    pub success_message_template: String,
1292
1293
    /// Same as `success_message_template` but for failure case.
1294
    ///
1295
    /// An example that is fully compatible with `bb_browser` is:
1296
    /// <https://example.com/my-instance-name-here/blobs/{digest_function}/historical_execute_response/{historical_results_hash}-{historical_results_size}/>
1297
    ///
1298
    /// Default: "" (no message)
1299
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
1300
    pub failure_message_template: String,
1301
}
1302
1303
/// The pool of persistent worker processes (Bazel `supports-workers`).
1304
#[derive(Deserialize, Serialize, Debug, Clone, Copy)]
1305
#[serde(deny_unknown_fields)]
1306
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1307
pub struct PersistentWorkersConfig {
1308
    /// Run an action whose platform properties carry `supports-workers=1`
1309
    /// in a pooled worker process that outlives it and serves the next
1310
    /// action with the same executable, startup arguments and environment.
1311
    /// Off, every such action runs as a one-shot process like any other.
1312
    /// Default: true
1313
    #[serde(default = "default_true")]
1314
    pub enabled: bool,
1315
1316
    /// Most worker processes kept per key (executable, startup arguments,
1317
    /// environment, protocol). An action whose key is at the cap and has
1318
    /// no idle process waits `acquire_timeout_s` for one to come back, then
1319
    /// runs one-shot. 0 takes the default.
1320
    /// Default: 4
1321
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1322
    pub max_workers_per_key: usize,
1323
1324
    /// Seconds an idle worker process is kept before the sweeper shuts it
1325
    /// down. 0 takes the default.
1326
    /// Default: 300
1327
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1328
    pub idle_timeout_s: u64,
1329
1330
    /// Requests a worker process serves before it is retired and replaced,
1331
    /// which bounds what a long-lived process accumulates. 0 takes the
1332
    /// default.
1333
    /// Default: 200
1334
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1335
    pub max_requests_per_worker: u64,
1336
1337
    /// Milliseconds a worker process being shut down gets to exit on its
1338
    /// own (its stdin is closed) before SIGKILL. 0 takes the default.
1339
    /// Default: 5000
1340
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1341
    pub shutdown_grace_ms: u64,
1342
1343
    /// Seconds an action waits for a worker process to come back when its
1344
    /// key is at `max_workers_per_key` with none idle, before it runs
1345
    /// one-shot instead. 0 takes the default.
1346
    /// Default: 30
1347
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1348
    pub acquire_timeout_s: u64,
1349
}
1350
1351
/// The same as an absent block: the pool on, every size at its default.
1352
impl Default for PersistentWorkersConfig {
1353
0
    fn default() -> Self {
1354
0
        Self {
1355
0
            enabled: true,
1356
0
            max_workers_per_key: 0,
1357
0
            idle_timeout_s: 0,
1358
0
            max_requests_per_worker: 0,
1359
0
            shutdown_grace_ms: 0,
1360
0
            acquire_timeout_s: 0,
1361
0
        }
1362
0
    }
1363
}
1364
1365
/// Opt-in file capture for the actual container executing a Buck2 action.
1366
/// Requires a fresh single-use container with no outer execution wrapper or
1367
/// separate action mount namespace. For nested runtimes, run `NativeLink` and the
1368
/// capture helper inside the execution container. Other build tools never start
1369
/// capture. The helper uploads an archive before `NativeLink` cleans up the action.
1370
///
1371
/// The operator supplies the helper executable and its authenticated ingest
1372
/// service. `NativeLink` sends one JSON record on stdin and expects `ready\n`
1373
/// on stdout within 30 seconds. Closing stdin requests final capture; the helper
1374
/// must exit only after durable acknowledgement, or exit unsuccessfully if the
1375
/// archive is partial. See `nativelink-worker/README.md` for the control protocol.
1376
#[derive(Deserialize, Serialize, Debug, Clone)]
1377
#[serde(deny_unknown_fields)]
1378
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1379
pub struct Buck2FileCaptureConfig {
1380
    /// Absolute path to the compatible `buck2-file-capture` executable.
1381
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
1382
    pub executable: String,
1383
    /// Authenticated ingest endpoint understood by the capture helper.
1384
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
1385
    pub gateway: String,
1386
    /// Private token file. The helper excludes its path and hard-link aliases.
1387
    /// The token is never included in the action environment or command line.
1388
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
1389
    pub token_file: String,
1390
    /// Private directory for the helper's bounded on-disk metadata index.
1391
    /// Mount a fresh empty volume here for each single-use container.
1392
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
1393
    pub state_directory: String,
1394
    /// Identity of the actual executing container, normally the pod UID.
1395
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
1396
    pub container_id: String,
1397
    /// Credential files/directories and platform configuration excluded from
1398
    /// browsing. Their inode aliases and private secret mounts are also denied.
1399
    #[serde(default, deserialize_with = "convert_vec_string_with_shellexpand")]
1400
    pub protected_paths: Vec<String>,
1401
    /// Internal CAS/cache paths excluded from browsing. Materialized action
1402
    /// inputs hard-linked from these caches remain visible in the action tree.
1403
    #[serde(default, deserialize_with = "convert_vec_string_with_shellexpand")]
1404
    pub internal_paths: Vec<String>,
1405
    /// Maximum final archive time before action cleanup proceeds. The helper
1406
    /// records a partial capture on timeout; build success/failure is unchanged.
1407
    /// Default: 120 seconds (zero selects this default).
1408
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1409
    pub finalize_timeout_s: usize,
1410
}
1411
1412
#[expect(
1413
    clippy::struct_excessive_bools,
1414
    reason = "independent on/off switches of one worker; a nested struct per flag would not read better"
1415
)]
1416
#[derive(Deserialize, Serialize, Debug, Default)]
1417
#[serde(deny_unknown_fields)]
1418
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1419
pub struct LocalWorkerConfig {
1420
    /// Name of the worker. This is give a more friendly name to a worker for logging
1421
    /// and metric publishing. This is also the prefix of the worker id
1422
    /// (i.e. "{name}{uuidv6}").
1423
    /// Default: {Index position in the workers list}
1424
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
1425
    pub name: String,
1426
1427
    /// Endpoint which the worker will connect to the scheduler's `WorkerApiService`.
1428
    pub worker_api_endpoint: EndpointConfig,
1429
1430
    /// The maximum time an action is allowed to run. If a task requests for a timeout
1431
    /// longer than this time limit, the task will be rejected. Value in seconds.
1432
    ///
1433
    /// Default: 20 minutes
1434
    #[serde(
1435
        default,
1436
        deserialize_with = "convert_duration_with_shellexpand",
1437
        alias = "max_action_timeout"
1438
    )]
1439
    pub max_action_timeout_s: usize,
1440
1441
    /// Maximum time allowed for uploading action results to CAS after execution
1442
    /// completes. If upload takes longer than this, the action fails with
1443
    /// `DeadlineExceeded` and may be retried by the scheduler. Value in seconds.
1444
    ///
1445
    /// Default: 10 minutes
1446
    #[serde(
1447
        default,
1448
        deserialize_with = "convert_duration_with_shellexpand",
1449
        alias = "max_upload_timeout"
1450
    )]
1451
    pub max_upload_timeout_s: usize,
1452
1453
    /// Maximum time allowed for fetching an action's inputs into the worker's
1454
    /// store and its directory before the command runs. A fetch that hangs
1455
    /// (a store that never answers) otherwise holds the action's slot for
1456
    /// good while the worker looks healthy; past this the action fails with
1457
    /// `DeadlineExceeded` and may be retried by the scheduler, and a warning
1458
    /// names the action every minute before that. Value in seconds.
1459
    ///
1460
    /// A fetch that fails with a transient store error is fetched again
1461
    /// from this worker, with a pause doubling from 1 s to 30 s, for as
1462
    /// long as this leaves room for another attempt, or the action's own
1463
    /// timeout when that is shorter. The scheduler is not told of the
1464
    /// retries: it ends an executing action on its own at the action's
1465
    /// timeout plus `worker_timeout_s`, and at
1466
    /// `max_action_executing_timeout_s`, so keep this below those or the
1467
    /// action is requeued while the worker still retries.
1468
    ///
1469
    /// Default: 10 minutes
1470
    #[serde(
1471
        default,
1472
        deserialize_with = "convert_duration_with_shellexpand",
1473
        alias = "max_download_timeout"
1474
    )]
1475
    pub max_download_timeout_s: usize,
1476
1477
    /// How many input blobs this worker fetches into its store at once,
1478
    /// across every action it is staging. Each fetch is a read from the
1479
    /// CAS or the object store, so this bounds what one worker asks of
1480
    /// them at a time: several cold actions share this many fetches
1481
    /// instead of each opening its own. Blobs already in the store are
1482
    /// linked without one. 0 shares no pool; each action fetches on its
1483
    /// own.
1484
    ///
1485
    /// Without a pool, an action fetches up to 64 inputs at a time per
1486
    /// directory of its input tree. Set this when several cold actions on
1487
    /// one worker overload the CAS or the object store behind it; 64 is a
1488
    /// good start. A worker without it logs a warning suggesting it, at
1489
    /// most every 10 minutes, when an input fetch times out or fails with
1490
    /// a transient error other than `DataLoss`.
1491
    ///
1492
    /// Default: 0 (no shared pool)
1493
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1494
    pub max_concurrent_input_downloads: usize,
1495
1496
    /// Maximum time to wait for action directory cleanup before timing out.
1497
    /// Value in seconds.
1498
    ///
1499
    /// Default: 30 seconds
1500
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1501
    pub max_cleanup_wait_s: usize,
1502
1503
    /// Maximum backoff duration for exponential backoff when waiting for cleanup.
1504
    /// Value in milliseconds.
1505
    ///
1506
    /// Default: 500 milliseconds
1507
    #[serde(default, deserialize_with = "convert_duration_with_shellexpand")]
1508
    pub max_cleanup_backoff_ms: usize,
1509
1510
    /// Maximum number of inflight tasks this worker can cope with.
1511
    ///
1512
    /// Default: 0 (infinite tasks)
1513
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1514
    pub max_inflight_tasks: u64,
1515
1516
    /// Accept one action, upload its results, and exit the worker process.
1517
    /// The worker advertises one execution slot and never accepts a second
1518
    /// action, including after a scheduler disconnect. A launcher must create
1519
    /// a fresh container and fresh writable volumes for its replacement.
1520
    /// Use one local worker per process, with no scheduler or services other
1521
    /// than health checks. Reusing the container or its writable volumes does
1522
    /// not provide isolation from the previous action.
1523
    ///
1524
    /// Default: false
1525
    #[serde(default)]
1526
    pub single_use: bool,
1527
1528
    /// Capture full execution-container files for Buck2 builds only. Disabled
1529
    /// when absent. Requires `single_use`; read the capture configuration's
1530
    /// isolation requirements before enabling it for a worker pool.
1531
    #[serde(default)]
1532
    pub experimental_buck2_file_capture: Option<Buck2FileCaptureConfig>,
1533
1534
    /// If timeout is handled in `entrypoint` or another wrapper script.
1535
    /// If set to true `NativeLink` will not honor the timeout the action requested
1536
    /// and instead will always force kill the action after `max_action_timeout`
1537
    /// has been reached. If this is set to false, the smaller value of the action's
1538
    /// timeout and `max_action_timeout` will be used to which `NativeLink` will kill
1539
    /// the action.
1540
    ///
1541
    /// The real timeout can be received via an environment variable set in:
1542
    /// `EnvironmentSource::TimeoutMillis`.
1543
    ///
1544
    /// Example on where this is useful: `entrypoint` launches the action inside
1545
    /// a docker container, but the docker container may need to be downloaded. Thus
1546
    /// the timer should not start until the docker container has started executing
1547
    /// the action. In this case, action will likely be wrapped in another program,
1548
    /// like `timeout` and propagate timeouts via `EnvironmentSource::SideChannelFile`.
1549
    ///
1550
    /// Default: false (`NativeLink` fully handles timeouts)
1551
    #[serde(default)]
1552
    pub timeout_handled_externally: bool,
1553
1554
    /// On shutdown, tell the scheduler at once that this worker is draining
1555
    /// so it stops dispatching here, then finish the running actions (up to
1556
    /// `max_action_timeout_s`) and exit. Off, the worker finishes first and
1557
    /// only then announces itself, while the scheduler keeps offering it
1558
    /// work it has to refuse. Needs a scheduler that understands the drain
1559
    /// flag (v1.7.3+); an older one removes the worker and requeues its
1560
    /// actions as soon as the message arrives.
1561
    /// Default: false
1562
    #[serde(default)]
1563
    pub drain_on_shutdown: bool,
1564
1565
    /// Kill an action that grows past its memory reservation before the
1566
    /// pod's cgroup limit does. On cgroup v2 the container cgroup carries
1567
    /// `memory.oom.group`, so the kernel's kill takes the worker and every
1568
    /// action on it; this one takes only the offender and fails it with
1569
    /// `FailedPrecondition`. The memory pressure kill reads a cgroup and is
1570
    /// Linux only; on Windows the disk axis is not sampled, and a kill ends
1571
    /// the action's own process rather than every process in it.
1572
    /// Actions run through a persistent worker are not covered, since that
1573
    /// process outlives the action and serves others. With either axis on,
1574
    /// the worker reads an action's platform properties from the
1575
    /// scheduler's `StartExecute` rather than the client's request, so a
1576
    /// reservation the scheduler placed the action by is the one enforced
1577
    /// and exported to the environment.
1578
    #[serde(default)]
1579
    pub resource_enforcement: Option<ResourceEnforcementConfig>,
1580
1581
    /// The command to execute on every execution request. This will be parsed as
1582
    /// a command + arguments (not shell).
1583
    /// Example: "run.sh" and a job with command: "sleep 5" will result in a
1584
    /// command like: "run.sh sleep 5".
1585
    /// Default: {Use the command from the job request}.
1586
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
1587
    pub entrypoint: String,
1588
1589
    /// An optional script to run before every action is processed on the worker.
1590
    /// The value should be the full path to the script to execute and will pause
1591
    /// all actions on the worker if it returns an exit code other than 0.
1592
    /// If not set, then the worker will never pause and will continue to accept
1593
    /// jobs according to the scheduler configuration.
1594
    /// This is useful, for example, if the worker should not take any more
1595
    /// actions until there is enough resource available on the machine to
1596
    /// handle them.
1597
    pub experimental_precondition_script: Option<String>,
1598
1599
    /// Milliseconds the precondition script may run before it counts as
1600
    /// failed and the action is refused as backpressure. A script that
1601
    /// hangs used to hold the action forever.
1602
    /// Default: 30000
1603
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1604
    pub precondition_timeout_ms: u64,
1605
1606
    /// Bytes of an action's stdout or stderr kept in memory. Past this the
1607
    /// output spills to a file under the action directory and is uploaded
1608
    /// from disk, so an action that prints gigabytes does not grow the
1609
    /// worker by that much. 0 keeps everything in memory.
1610
    /// Default: 0
1611
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1612
    pub max_captured_output_bytes: u64,
1613
1614
    /// Seconds between sweeps of `work_directory` for action directories no
1615
    /// running action owns, left by a cleanup that failed. 0 disables the
1616
    /// sweep; the directory is still purged at startup.
1617
    /// Default: 0
1618
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1619
    pub orphan_sweep_interval_s: u64,
1620
1621
    /// Milliseconds between the SIGTERM a timed-out or cancelled action
1622
    /// receives and the SIGKILL that follows if it is still running, so a
1623
    /// tool that handles SIGTERM can write its own cleanup. The memory
1624
    /// reservation kill skips the grace and sends SIGKILL at once. Linux
1625
    /// only; elsewhere the kill is immediate. 0 takes the default.
1626
    /// Default: 5000
1627
    #[serde(default, deserialize_with = "convert_numeric_with_shellexpand")]
1628
    pub kill_grace_ms: u64,
1629
1630
    /// Give every action its own `TMPDIR` under its action directory,
1631
    /// removed with it, so concurrent actions writing the same file name
1632
    /// under `$TMPDIR` no longer collide. A `TMPDIR` in the action's own
1633
    /// environment still wins. Code that hard-codes `/tmp` is unaffected.
1634
    /// Default: true
1635
    #[serde(default = "default_true")]
1636
    pub set_tmpdir: bool,
1637
1638
    /// Bazel persistent workers: how an action whose platform properties
1639
    /// carry `supports-workers=1` is run and how the pool of worker
1640
    /// processes is sized. Unset takes every default below.
1641
    #[serde(default)]
1642
    pub persistent_workers: Option<PersistentWorkersConfig>,
1643
1644
    /// Underlying CAS store that the worker will use to download CAS artifacts.
1645
    /// This store must be a `FastSlowStore`. The `fast` store must be a
1646
    /// `FileSystemStore` because it will use hardlinks when building out the files
1647
    /// instead of copying the files. The slow store must eventually resolve to the
1648
    /// same store the scheduler/client uses to send job requests.
1649
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
1650
    pub cas_fast_slow_store: StoreRefName,
1651
1652
    /// Configuration for uploading action results.
1653
    #[serde(default)]
1654
    pub upload_action_result: UploadActionResultConfig,
1655
1656
    /// The directory work jobs will be executed from. This directory will be fully
1657
    /// managed by the worker service and will be purged on startup.
1658
    /// This directory and the directory referenced in `local_filesystem_store_ref`'s
1659
    /// `stores::FilesystemStore::content_path` must be on the same filesystem.
1660
    /// Hardlinks will be used when placing files that are accessible to the jobs
1661
    /// that are sourced from `local_filesystem_store_ref`'s `content_path`.
1662
    #[serde(deserialize_with = "convert_string_with_shellexpand")]
1663
    pub work_directory: String,
1664
1665
    /// Properties of this worker. This configuration will be sent to the scheduler
1666
    /// and used to tell the scheduler to restrict what should be executed on this
1667
    /// worker.
1668
    pub platform_properties: HashMap<String, WorkerProperty>,
1669
1670
    /// Derive the CPU and memory properties from the worker's own cgroup
1671
    /// limits instead of the values above; see `CapacityConfig`. When the
1672
    /// cgroup cannot be read (not Linux, cgroup v1, no permission) the
1673
    /// values above stand and a warning says so; if they carry neither
1674
    /// property the worker refuses to start rather than register unable to
1675
    /// take any action that asks for CPU or memory.
1676
    #[serde(default)]
1677
    pub capacity: Option<CapacityConfig>,
1678
1679
    /// An optional mapping of environment names to set for the execution
1680
    /// as well as those specified in the action itself. If set, will set each
1681
    /// key as an environment variable before executing the job with the value
1682
    /// of the environment variable being the value of the property of the
1683
    /// action being executed of that name or the fixed value.
1684
    pub additional_environment: Option<HashMap<String, EnvironmentSource>>,
1685
1686
    /// Optional directory cache configuration for improving performance by caching
1687
    /// reconstructed input directories and using hardlinks instead of rebuilding
1688
    /// them from CAS for every action.
1689
    /// Default: None (directory cache disabled)
1690
    pub directory_cache: Option<DirectoryCacheConfig>,
1691
1692
    /// Optional and experimental: lease every digest in an active action's
1693
    /// input Merkle closure in the worker's locally eviction-managed CAS
1694
    /// tiers (the `cas_fast_slow_store`'s filesystem-backed stores) until the
1695
    /// action has finished cleanup. This prevents `Lost inputs no longer
1696
    /// available remotely` failures caused by local fast-tier eviction while
1697
    /// inputs are being materialized under cache pressure.
1698
    ///
1699
    /// Trade-off: while leases are held, a local filesystem tier may
1700
    /// temporarily exceed its configured `max_bytes` / `max_count` eviction
1701
    /// limits; normal eviction resumes once the action's leases are released.
1702
    /// Operators should leave headroom on the underlying disk when enabling
1703
    /// this.
1704
    ///
1705
    /// Default: false (eviction behavior is unchanged)
1706
    #[serde(default)]
1707
    pub experimental_active_input_leases: bool,
1708
1709
    /// Reuse immutable input directories through read-only bind mounts on Linux.
1710
    /// The worker prepares each selected subtree once per REAPI `Directory`
1711
    /// digest in the directory cache, then mounts it into each action instead of
1712
    /// recreating its filesystem entries.
1713
    ///
1714
    /// Paths are relative to the action input root, for example `["out/x/sdk"]`.
1715
    /// They must be nonempty, canonical, and non-overlapping. Absolute paths,
1716
    /// empty path components, and `.`/`..` components are rejected.
1717
    /// Requires `directory_cache`, `use_namespaces: true`, and
1718
    /// `use_mount_namespace: true`.
1719
    ///
1720
    /// Actions declaring overlapping outputs, working inside a selected subtree,
1721
    /// or using a persistent worker fall back to ordinary materialization.
1722
    /// Output paths reached through symlink aliases cannot be checked for
1723
    /// overlap. Use this only with trusted workloads that do not modify the
1724
    /// selected trees; read-only input mounts are not a security boundary.
1725
    ///
1726
    /// Select trees whose contents (and Directory digest) are reused across
1727
    /// many actions. Trees that change per action add cache construction work
1728
    /// without reuse. When mounts apply, other inputs use ordinary downloads,
1729
    /// bypassing both root and subtree directory caching for that action.
1730
    /// Failed mount preparation retries once without mounts; a failed mount
1731
    /// syscall still aborts the action before its command runs.
1732
    ///
1733
    /// An action can remount its inputs writable in its own user namespace
1734
    /// and corrupt the shared cache. Later actions can then produce incorrect
1735
    /// results from those inputs. Enable only for trusted commands.
1736
    ///
1737
    /// Cache entries remain pinned until action cleanup and may temporarily
1738
    /// exceed the cache's eviction budget. Pinned bytes have no separate limit,
1739
    /// so concurrent distinct trees can exhaust the disk. Leave headroom.
1740
    ///
1741
    /// Default: [] (disabled)
1742
    #[serde(default)]
1743
    pub experimental_readonly_input_mounts: Vec<String>,
1744
1745
    /// Whether to use namespaces to isolate the execution. This is only available
1746
    /// on Linux. It is highly recommended as it avoids a number of issues with
1747
    /// zombie processes and also provides additional hermeticity. If explicitly set
1748
    /// to true and it is not supported the worker will exit with an error.
1749
    ///
1750
    /// The action runs as PID 1 of its own PID namespace, and `/proc` is
1751
    /// remounted inside it, so the processes listed there are the action's
1752
    /// own, each under the PID the action knows it by: a process reading
1753
    /// `/proc/<pid>` for a child it forked finds that child, not whichever
1754
    /// host process has the number. If the worker's environment refuses that
1755
    /// mount (an unprivileged container that masks paths under `/proc` does)
1756
    /// the worker logs a warning at startup and actions see the host's
1757
    /// `/proc` instead.
1758
    ///
1759
    /// Note: this will fail for non-privileged Dockerised workers, as workers in
1760
    /// Docker don't have permissions to make a new user namespace. Privileged
1761
    /// containers can do this.
1762
    ///
1763
    /// Default: False.
1764
    pub use_namespaces: Option<bool>,
1765
1766
    /// Whether to use a mount namespace to isolate the worker root. This is only
1767
    /// available on Linux and when `use_namespaces` is true. It is highly recommended
1768
    /// provides additional hermeticity. If explicitly set to true and it is not
1769
    /// supported or `use_namespaces` is not set to true the worker will exit with an
1770
    /// error.
1771
    /// Default: False.
1772
    pub use_mount_namespace: Option<bool>,
1773
1774
    /// Whether to give each action a private `/tmp` inside its mount
1775
    /// namespace: the action's own `tmp` directory (the one `TMPDIR` points
1776
    /// at) is bound over `/tmp`, so tools that hardcode `/tmp` write there
1777
    /// too. Concurrent actions no longer collide on predictable paths under
1778
    /// `/tmp`, nothing leaks between actions through it, and what an action
1779
    /// writes there is removed with the action.
1780
    ///
1781
    /// This is only available on Linux and requires `use_namespaces` and
1782
    /// `use_mount_namespace` to be true. If explicitly set to true without
1783
    /// both the worker will exit with an error. Set it to false to keep the
1784
    /// host's `/tmp` visible to actions, for example when a tool they need
1785
    /// lives there. The bound `/tmp` carries the work volume's mount options
1786
    /// (`noexec`, `nodev`, `nosuid` if the volume has them), not the host
1787
    /// `/tmp`'s.
1788
    ///
1789
    /// The private `/tmp` lives on the worker's disk under the work
1790
    /// directory, not in memory, so it is bounded by the volume that holds
1791
    /// the work directory and seen by the disk guard, and a tool filling it
1792
    /// cannot take the worker's memory with it.
1793
    ///
1794
    /// If `/tmp` does not exist on the worker, for example in a minimal
1795
    /// container image, there is nothing for actions to collide on, so the
1796
    /// default is False there and a warning is logged at startup.
1797
    ///
1798
    /// Default: True when `use_mount_namespace` is true and `/tmp` exists,
1799
    /// otherwise False.
1800
    pub isolate_tmp: Option<bool>,
1801
}
1802
1803
#[derive(Deserialize, Serialize, Debug, Clone)]
1804
#[serde(deny_unknown_fields)]
1805
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1806
pub struct DirectoryCacheConfig {
1807
    /// Maximum number of cached directories.
1808
    /// Default: 1000
1809
    #[serde(default = "default_directory_cache_max_entries")]
1810
    pub max_entries: usize,
1811
1812
    /// Maximum total size in bytes for all cached directories (0 = unlimited).
1813
    /// Default: 10737418240 (10 GB)
1814
    #[serde(
1815
        default = "default_directory_cache_max_size_bytes",
1816
        deserialize_with = "convert_data_size_with_shellexpand"
1817
    )]
1818
    pub max_size_bytes: u64,
1819
1820
    /// Base directory for cache storage. This directory will be managed by
1821
    /// the worker and should be on the same filesystem as `work_directory`.
1822
    /// Default: `{work_directory}/../directory_cache`
1823
    #[serde(default, deserialize_with = "convert_string_with_shellexpand")]
1824
    pub cache_root: String,
1825
1826
    /// Optional and experimental: additionally cache every subdirectory by
1827
    /// its own `Directory` digest, not just the root directory. REAPI Merkle
1828
    /// nodes are content-addressed, so a subtree that is byte-identical
1829
    /// between two different roots has the same digest and can be
1830
    /// materialized with a single hardlink pass instead of being rebuilt
1831
    /// from the CAS. This makes the common "one input file changed out of
1832
    /// thousands" case reuse every unchanged subtree.
1833
    ///
1834
    /// Note: subtree caching multiplies the entry COUNT in the cache (every
1835
    /// distinct subdirectory becomes its own entry, subject to the normal
1836
    /// eviction budgets), so operators enabling this should raise
1837
    /// `max_entries` accordingly (for example 10x). To avoid multiplying the
1838
    /// SIZE accounting too, an entry's recorded size covers only bytes not
1839
    /// owned by a descendant entry, so the cache's size total approximates
1840
    /// unique materialized bytes rather than counting each file once per
1841
    /// ancestor level.
1842
    ///
1843
    /// Trade-off: cold constructions pay roughly one extra hardlink pass per
1844
    /// tree level (measured ~10% cold overhead at depth 3, within run
1845
    /// variance) in exchange for the churn-path reuse above.
1846
    ///
1847
    /// Default: false (only root directories are cached; existing behavior)
1848
    #[serde(default)]
1849
    pub experimental_subtree_caching: bool,
1850
1851
    /// Maximum number of concurrent slow-store fetches across ALL directory
1852
    /// constructions of this cache. This bound protects backing stores from
1853
    /// RPC storms: per-level construction concurrency compounds
1854
    /// multiplicatively across tree levels and concurrent actions.
1855
    ///
1856
    /// Interaction with read coalescing: this semaphore fragments coalesced
1857
    /// batches to at most this many items and serializes fetch waves for
1858
    /// trees with many tiny files. Deployments using
1859
    /// `experimental_read_batching` on the underlying grpc store can raise
1860
    /// this substantially (for example 512), since batching collapses the
1861
    /// RPC count. Must be greater than 0.
1862
    ///
1863
    /// Default: 64
1864
    #[serde(default = "default_directory_cache_max_concurrent_fetches")]
1865
    pub max_concurrent_fetches: usize,
1866
    /// On a directory-cache miss, prefetch every `Directory` proto of the
1867
    /// tree with one logical `GetTree` traversal instead of fetching protos
1868
    /// level by level (which costs one round trip per tree DEPTH). The
1869
    /// [REAPI request contract] permits servers to impose their own limit even
1870
    /// when no page size is specified, and the [REAPI response contract]
1871
    /// requires clients to continue with the returned page token. A paginated
1872
    /// traversal may therefore use multiple RPCs. Only takes effect when the
1873
    /// slow tier is a `grpc` store;
1874
    /// any prefetch failure falls back to the per-level path. Worthwhile when
1875
    /// worker-to-CAS latency is non-trivial and trees are deep; measured 5-34x
1876
    /// on the proto phase at 5-25ms RTT. Note the serving CAS pays the tree walk
1877
    /// against its own backend, so its directory protos should be served
1878
    /// from a fast tier.
1879
    ///
1880
    /// [REAPI request contract]: https://github.com/bazelbuild/remote-apis/blob/becdd8f9ff811df88a22d3eadd6341753d51d167/build/bazel/remote/execution/v2/remote_execution.proto#L1932-L1942
1881
    /// [REAPI response contract]: https://github.com/bazelbuild/remote-apis/blob/becdd8f9ff811df88a22d3eadd6341753d51d167/build/bazel/remote/execution/v2/remote_execution.proto#L1961-L1965
1882
    /// Default: false
1883
    #[serde(default)]
1884
    pub experimental_get_tree_prefetch: bool,
1885
1886
    /// Optional and experimental, macOS only: build the cache's copy of an
1887
    /// executable input file as an APFS `clonefile(2)` clone of the worker's
1888
    /// local CAS blob instead of reading the blob into memory and writing a
1889
    /// second copy of it.
1890
    ///
1891
    /// A non-executable input is hardlinked from the `filesystem` store. An
1892
    /// executable one cannot be: the hardlink would share the blob's inode,
1893
    /// and setting its executable bit would change the mode of the blob
1894
    /// itself. It is therefore given a private inode, which without this
1895
    /// option means buffering the whole blob in memory and storing its bytes
1896
    /// a second time. Bazel marks every file it outputs as executable, so on
1897
    /// a Bazel workload that can be every input. A clone is also a private
1898
    /// inode, with its own mode, but it shares the blob's data blocks
1899
    /// copy-on-write: nothing is read or written.
1900
    ///
1901
    /// Requirements: the fast store of the worker's CAS is a `filesystem`
1902
    /// store, and its `content_path` and this cache's `cache_root` are on
1903
    /// the same APFS volume. This is checked once at startup; if a clone is
1904
    /// not possible a warning is logged and executable files are copied as
1905
    /// before. A single file that cannot be cloned is copied as well. On
1906
    /// other operating systems the option logs a warning and does nothing.
1907
    ///
1908
    /// What changes for an action: a cloned file keeps the modification time
1909
    /// of the CAS blob (as a hardlinked non-executable input does) where a
1910
    /// copy has the time the cache entry was built. A clone would also carry
1911
    /// the blob's extended attributes and BSD file flags, so a blob that has
1912
    /// either is copied instead.
1913
    ///
1914
    /// What does not change: `max_size_bytes` still counts the full size of
1915
    /// every file in an entry, so the cache evicts exactly as before even
1916
    /// though clones take no space of their own. Conversely, evicting a blob
1917
    /// from the `filesystem` store frees no disk space while a cache entry
1918
    /// or an action directory still holds a clone of it. Disk use is never
1919
    /// higher than with copies. Each clone is still a file, so the number of
1920
    /// files in the cache is unchanged.
1921
    ///
1922
    /// Default: false (executable files are copied; existing behavior)
1923
    #[serde(default)]
1924
    pub experimental_clone_executables: bool,
1925
}
1926
1927
3
const fn default_directory_cache_max_entries() -> usize {
1928
3
    1000
1929
3
}
1930
1931
3
const fn default_directory_cache_max_concurrent_fetches() -> usize {
1932
3
    64
1933
3
}
1934
1935
3
const fn default_directory_cache_max_size_bytes() -> u64 {
1936
3
    10 * 1024 * 1024 * 1024 // 10 GB
1937
3
}
1938
1939
#[derive(Deserialize, Serialize, Debug)]
1940
#[serde(rename_all = "snake_case")]
1941
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1942
pub enum WorkerConfig {
1943
    /// A worker type that executes jobs locally on this machine.
1944
    Local(LocalWorkerConfig),
1945
}
1946
1947
#[derive(Deserialize, Serialize, Debug, Clone, Copy)]
1948
#[serde(deny_unknown_fields)]
1949
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1950
pub struct GlobalConfig {
1951
    /// Maximum number of open files that can be opened at one time.
1952
    /// This value is not strictly enforced, it is a best effort. Some internal libraries
1953
    /// open files or read metadata from a files which do not obey this limit, however
1954
    /// the vast majority of cases will have this limit be honored.
1955
    /// This value must be larger than `ulimit -n` to have any effect.
1956
    /// Any network open file descriptors is not counted in this limit, but is counted
1957
    /// in the kernel limit. It is a good idea to set a very large `ulimit -n`.
1958
    /// Note: This value must be greater than 10.
1959
    ///
1960
    /// Default: 24576 (= 24 * 1024)
1961
    #[serde(deserialize_with = "convert_numeric_with_shellexpand")]
1962
    pub max_open_files: usize,
1963
1964
    /// Default hash function to use while uploading blobs to the CAS when not set
1965
    /// by client.
1966
    ///
1967
    /// Default: `ConfigDigestHashFunction::sha256`
1968
    pub default_digest_hash_function: Option<ConfigDigestHashFunction>,
1969
1970
    /// Default digest size to use for health check when running
1971
    /// diagnostics checks. Health checks are expected to use this
1972
    /// size for filling a buffer that is used for creation of
1973
    /// digest.
1974
    ///
1975
    /// Default: 1024*1024 (1MiB)
1976
    #[serde(default, deserialize_with = "convert_data_size_with_shellexpand")]
1977
    pub default_digest_size_health_check: usize,
1978
}
1979
1980
pub type StoreConfig = NamedConfig<StoreSpec>;
1981
pub type SchedulerConfig = NamedConfig<SchedulerSpec>;
1982
1983
#[derive(Deserialize, Serialize, Debug)]
1984
#[serde(deny_unknown_fields)]
1985
#[cfg_attr(feature = "dev-schema", derive(JsonSchema))]
1986
pub struct CasConfig {
1987
    /// List of stores available to use in this config.
1988
    /// The keys can be used in other configs when needing to reference a store.
1989
    pub stores: Vec<StoreConfig>,
1990
1991
    /// Worker configurations used to execute jobs.
1992
    pub workers: Option<Vec<WorkerConfig>>,
1993
1994
    /// List of schedulers available to use in this config.
1995
    /// The keys can be used in other configs when needing to reference a
1996
    /// scheduler.
1997
    pub schedulers: Option<Vec<SchedulerConfig>>,
1998
1999
    /// Servers to setup for this process.
2000
    pub servers: Vec<ServerConfig>,
2001
2002
    /// Experimental - Origin events configuration. This is the service that will
2003
    /// collect and publish nativelink events to a store for processing by an
2004
    /// external service.
2005
    pub experimental_origin_events: Option<OriginEventsSpec>,
2006
2007
    /// Any global configurations that apply to all modules live here.
2008
    pub global: Option<GlobalConfig>,
2009
}
2010
2011
impl CasConfig {
2012
    const ZSTD_COMPRESSION_DOCS_URL: &'static str =
2013
        "https://docs.nativelink.com/configuration/compression";
2014
2015
    /// # Errors
2016
    ///
2017
    /// Will return `Err` if we can't load the file.
2018
22
    pub fn try_from_json5_file(config_file: &str) -> Result<Self, Error> {
2019
22
        let json_contents = std::fs::read_to_string(config_file)
2020
22
            .err_tip(|| 
format!0
("Could not open config file {config_file}"))
?0
;
2021
22
        Self::try_from_json5_str(&json_contents)
2022
22
    }
2023
2024
45
    pub fn try_from_json5_str(json_contents: &str) -> Result<Self, Error> {
2025
45
        let mut config: Self = serde_json5::from_str(json_contents)
?0
;
2026
45
        for 
server30
in &config.servers {
2027
30
            if let Some(services) = &server.services {
2028
30
                Self::check_store_conflict(services)
?1
;
2029
0
            }
2030
        }
2031
44
        config.validate_single_use_worker()
?0
;
2032
44
        config.apply_zstd_grpc_store_defaults();
2033
44
        Ok(config)
2034
45
    }
2035
2036
    /// Map each instance name served by an Action Cache service to whether
2037
    /// that instance is read only. Collected across all server blocks, the
2038
    /// same way the capabilities service advertises instances that may be
2039
    /// served from a different block. A later entry for an instance wins.
2040
    #[must_use]
2041
3
    pub fn action_cache_read_only_by_instance(&self) -> HashMap<InstanceName, bool> {
2042
3
        self.servers
2043
3
            .iter()
2044
3
            .filter_map(|server| 
server.services2
.
as_ref2
())
2045
3
            .filter_map(|services| 
services.ac2
.
as_deref2
())
2046
3
            .flatten()
2047
3
            .map(|ac| (
ac.instance_name2
.
clone2
(),
ac.read_only2
))
2048
3
            .collect()
2049
3
    }
2050
2051
    /// True when this process runs shared (non-`single_use`) workers *and* at
2052
    /// least one Action Cache instance accepts client writes (`read_only` is
2053
    /// false). That combination is unsafe for untrusted builds: a job can
2054
    /// leave state on a worker that the next job inherits, and a client can
2055
    /// write an `ActionResult` that later builds trust. It is only a warning,
2056
    /// because it is the right configuration when every build is trusted.
2057
    #[must_use]
2058
5
    pub fn shares_workers_with_writable_action_cache(&self) -> bool {
2059
5
        let has_shared_worker = self
2060
5
            .workers
2061
5
            .as_deref()
2062
5
            .unwrap_or_default()
2063
5
            .iter()
2064
5
            .any(|WorkerConfig::Local(worker)| !
worker.single_use3
);
2065
5
        let action_cache_accepts_client_writes = self
2066
5
            .servers
2067
5
            .iter()
2068
5
            .filter_map(|server| server.services.as_ref())
2069
5
            .filter_map(|services| services.ac.as_deref())
2070
5
            .flatten()
2071
5
            .any(|ac| !
ac.read_only4
);
2072
5
        has_shared_worker && 
action_cache_accepts_client_writes2
2073
5
    }
2074
2075
60
    fn validate_single_use_worker(&self) -> Result<(), Error> {
2076
60
        let workers = self.workers.as_deref().unwrap_or_default();
2077
60
        for WorkerConfig::Local(
worker24
) in workers {
2078
24
            if let Some(
capture12
) = &worker.experimental_buck2_file_capture {
2079
12
                if !worker.single_use
2080
11
                    || !worker.entrypoint.is_empty()
2081
10
                    || worker.use_mount_namespace == Some(true)
2082
                {
2083
3
                    return Err(make_input_err!(
2084
3
                        "Buck2 file capture requires a single_use worker inside the execution container, without an entrypoint wrapper or separate action mount namespace"
2085
3
                    ));
2086
9
                }
2087
24
                for path in [
2088
9
                    &capture.executable,
2089
9
                    &capture.token_file,
2090
9
                    &capture.state_directory,
2091
9
                ]
2092
9
                .into_iter()
2093
9
                .chain(capture.protected_paths.iter())
2094
9
                .chain(capture.internal_paths.iter())
2095
                {
2096
                    // These paths belong to the Linux execution container,
2097
                    // even when an operator validates the config on Windows.
2098
24
                    if !path.starts_with('/')
2099
46
                        || 
path.split('/')22
.
all22
(|part| part.is_empty() ||
part == "."20
)
2100
19
                        || path.contains('\0')
2101
48
                        || 
path.split('/')18
.
any18
(|part| part == "..")
2102
                    {
2103
7
                        return Err(make_input_err!(
2104
7
                            "Buck2 capture paths must be absolute and cannot select the filesystem root"
2105
7
                        ));
2106
17
                    }
2107
                }
2108
2
                if capture.gateway.is_empty()
2109
2
                    || capture.container_id.is_empty()
2110
2
                    || capture.finalize_timeout_s > 3600
2111
                {
2112
0
                    return Err(make_input_err!(
2113
0
                        "Buck2 capture requires a gateway, container identity, and finalization timeout no greater than one hour"
2114
0
                    ));
2115
2
                }
2116
12
            }
2117
        }
2118
50
        if !workers.iter().any(|worker| match 
worker13
{
2119
13
            WorkerConfig::Local(worker) => worker.single_use,
2120
13
        }) {
2121
43
            return Ok(());
2122
7
        }
2123
7
        if workers.len() != 1 || 
self.schedulers6
.
as_ref6
().
is_some_and6
(|s| !
s0
.
is_empty0
()) {
2124
1
            return Err(make_input_err!(
2125
1
                "single_use requires exactly one worker and no scheduler in the process"
2126
1
            ));
2127
6
        }
2128
6
        for 
services3
in self
2129
6
            .servers
2130
6
            .iter()
2131
6
            .filter_map(|server| 
server.services3
.
as_ref3
())
2132
        {
2133
            let ServicesConfig {
2134
3
                cas,
2135
3
                ac,
2136
3
                capabilities,
2137
3
                execution,
2138
3
                bytestream,
2139
3
                fetch,
2140
3
                push,
2141
3
                worker_api,
2142
3
                experimental_bep,
2143
3
                admin,
2144
                health: _,
2145
3
            } = services;
2146
3
            if cas.is_some()
2147
2
                || ac.is_some()
2148
2
                || capabilities.is_some()
2149
2
                || execution.is_some()
2150
2
                || bytestream.is_some()
2151
2
                || fetch.is_some()
2152
2
                || push.is_some()
2153
2
                || worker_api.is_some()
2154
2
                || experimental_bep.is_some()
2155
2
                || admin.is_some()
2156
            {
2157
1
                return Err(make_input_err!(
2158
1
                    "single_use worker processes may expose only health services"
2159
1
                ));
2160
2
            }
2161
        }
2162
5
        Ok(())
2163
60
    }
2164
2165
44
    fn zstd_wire_compression_enabled_anywhere(&self) -> bool {
2166
44
        if self
2167
44
            .servers
2168
44
            .iter()
2169
44
            .filter_map(|server| 
server.services29
.
as_ref29
())
2170
44
            .filter_map(|services| 
services.capabilities29
.
as_deref29
())
2171
44
            .flatten()
2172
44
            .any(|capabilities| 
capabilities21
.remote_cache_compression)
2173
        {
2174
1
            return true;
2175
43
        }
2176
2177
73
        
self.stores.iter()43
.
any43
(|store| {
2178
73
            let mut enabled = false;
2179
73
            store.spec.visit_grpc_specs(&mut |grpc| 
{6
2180
6
                enabled |= 
matches!2
(grpc.store_type, StoreType::Cas)
2181
4
                    && grpc.experimental_remote_cache_compression == Some(true);
2182
6
            });
2183
73
            enabled
2184
73
        })
2185
44
    }
2186
2187
44
    fn apply_zstd_grpc_store_defaults(&mut self) {
2188
44
        let zstd_enabled_anywhere = self.zstd_wire_compression_enabled_anywhere();
2189
2190
75
        for store in 
&mut self.stores44
{
2191
75
            let store_name = store.name.as_str();
2192
75
            store.spec.visit_grpc_specs_mut(&mut |grpc| 
{10
2193
10
                if !
matches!3
(grpc.store_type, StoreType::Cas) {
2194
3
                    if grpc.experimental_remote_cache_compression == Some(true) {
2195
1
                        warn!(
2196
                            store = store_name,
2197
                            instance_name = grpc.instance_name,
2198
                            "'experimental_remote_cache_compression' is enabled on a non-CAS \
2199
                             gRPC store, where it has no effect: REAPI zstd wire compression \
2200
                             only applies to CAS blob transfers. Enable it on the CAS gRPC \
2201
                             stores or a capabilities instance instead. See {}",
2202
                            Self::ZSTD_COMPRESSION_DOCS_URL,
2203
                        );
2204
2
                    }
2205
3
                    return;
2206
7
                }
2207
2208
7
                if !zstd_enabled_anywhere {
2209
3
                    return;
2210
4
                }
2211
2212
4
                match grpc.experimental_remote_cache_compression {
2213
2
                    None => grpc.experimental_remote_cache_compression = Some(true),
2214
1
                    Some(false) => warn!(
2215
                        store = store_name,
2216
                        instance_name = grpc.instance_name,
2217
                        "Zstd wire compression is enabled elsewhere, but this eligible CAS gRPC \
2218
                         store explicitly disables it. Unless this upstream cannot use zstd, \
2219
                         enable 'experimental_remote_cache_compression' for substantially faster \
2220
                         transfers of compressible artifacts. See {}",
2221
                        Self::ZSTD_COMPRESSION_DOCS_URL,
2222
                    ),
2223
1
                    Some(true) => {}
2224
                }
2225
10
            });
2226
        }
2227
44
    }
2228
2229
30
    fn check_store_conflict(services: &ServicesConfig) -> Result<(), Error> {
2230
30
        if let Some(
cas_config19
) = &services.cas
2231
19
            && let Some(ac_config) = &services.ac
2232
        {
2233
            // Create a hashmap from the CAS configuration for quick lookup
2234
19
            let cas_store_map: HashMap<_, _> = cas_config
2235
19
                .iter()
2236
22
                .
map19
(|with_instance_name| {
2237
22
                    (
2238
22
                        &with_instance_name.instance_name,
2239
22
                        &with_instance_name.cas_store,
2240
22
                    )
2241
22
                })
2242
19
                .collect();
2243
2244
22
            for with_instance_name in 
ac_config19
{
2245
22
                if let Some(cas_store) = cas_store_map.get(&with_instance_name.instance_name)
2246
22
                    && cas_store == &&with_instance_name.ac_store
2247
                {
2248
1
                    return Err(make_err!(
2249
1
                        Code::InvalidArgument,
2250
1
                        "CAS and AC use the same store '{}' in the config",
2251
1
                        cas_store
2252
1
                    ));
2253
21
                }
2254
            }
2255
11
        }
2256
29
        Ok(())
2257
30
    }
2258
}
2259
2260
#[cfg(test)]
2261
mod tests {
2262
    use tracing_test::traced_test;
2263
2264
    use super::*;
2265
2266
    #[test]
2267
1
    fn single_use_worker_defaults_off_and_rejects_shared_processes() {
2268
1
        assert!(!LocalWorkerConfig::default().single_use);
2269
1
        let mut config = CasConfig::try_from_json5_str("{ stores: [], servers: [] }").unwrap();
2270
1
        config.workers = Some(vec![WorkerConfig::Local(LocalWorkerConfig {
2271
1
            single_use: true,
2272
1
            ..Default::default()
2273
1
        })]);
2274
1
        config.validate_single_use_worker().unwrap();
2275
1
        config
2276
1
            .workers
2277
1
            .as_mut()
2278
1
            .unwrap()
2279
1
            .push(WorkerConfig::Local(LocalWorkerConfig::default()));
2280
1
        assert!(config.validate_single_use_worker().is_err());
2281
1
        config.workers.as_mut().unwrap().pop();
2282
1
        config.servers = serde_json5::from_str(
2283
1
            r#"[{
2284
1
            listener: { http: { socket_address: "127.0.0.1:50061" } },
2285
1
            services: { health: { path: "/health" } }
2286
1
        }]"#,
2287
        )
2288
1
        .unwrap();
2289
1
        config.validate_single_use_worker().unwrap();
2290
1
        config.servers[0].services.as_mut().unwrap().cas = Some(vec![]);
2291
1
        assert!(config.validate_single_use_worker().is_err());
2292
1
    }
2293
2294
    #[test]
2295
1
    fn buck2_capture_requires_an_isolated_execution_container() {
2296
1
        assert!(
2297
1
            LocalWorkerConfig::default()
2298
1
                .experimental_buck2_file_capture
2299
1
                .is_none()
2300
        );
2301
1
        let capture = Buck2FileCaptureConfig {
2302
1
            executable: "/shared/buck2-file-capture".to_string(),
2303
1
            gateway: "http://capture/api-auth/v1/buck2-files".to_string(),
2304
1
            token_file: "/capture-token/token".to_string(),
2305
1
            state_directory: "/capture-state".to_string(),
2306
1
            container_id: "pod-uid".to_string(),
2307
1
            protected_paths: vec!["/worker-config".to_string()],
2308
1
            internal_paths: vec!["/cas".to_string()],
2309
1
            finalize_timeout_s: 120,
2310
1
        };
2311
5
        for (single_use, entrypoint, mount_namespace, valid) in [
2312
1
            (true, "", None, true),
2313
1
            (true, "", Some(false), true),
2314
1
            (false, "", None, false),
2315
1
            (true, "/outer-container-wrapper", None, false),
2316
1
            (true, "", Some(true), false),
2317
1
        ] {
2318
5
            let mut config = CasConfig::try_from_json5_str("{ stores: [], servers: [] }").unwrap();
2319
5
            config.workers = Some(vec![WorkerConfig::Local(LocalWorkerConfig {
2320
5
                single_use,
2321
5
                entrypoint: entrypoint.to_string(),
2322
5
                use_mount_namespace: mount_namespace,
2323
5
                experimental_buck2_file_capture: Some(capture.clone()),
2324
5
                ..Default::default()
2325
5
            })]);
2326
5
            let result = config.validate_single_use_worker();
2327
5
            assert_eq!(result.is_ok(), valid, "{result:?}");
2328
        }
2329
7
        for invalid in [
2330
1
            "relative/helper",
2331
1
            "/",
2332
1
            "/./",
2333
1
            "//",
2334
1
            "/tmp/../token",
2335
1
            "C:\\capture\\token",
2336
1
            "/tmp/\0token",
2337
1
        ] {
2338
7
            let mut invalid_capture = capture.clone();
2339
7
            invalid_capture.token_file = invalid.to_string();
2340
7
            let mut config = CasConfig::try_from_json5_str("{ stores: [], servers: [] }").unwrap();
2341
7
            config.workers = Some(vec![WorkerConfig::Local(LocalWorkerConfig {
2342
7
                single_use: true,
2343
7
                experimental_buck2_file_capture: Some(invalid_capture),
2344
7
                ..Default::default()
2345
7
            })]);
2346
7
            assert!(
2347
7
                config.validate_single_use_worker().is_err(),
2348
                "accepted {invalid:?}"
2349
            );
2350
        }
2351
1
    }
2352
2353
4
    fn grpc_compression_configs(config: &CasConfig) -> Vec<(bool, Option<bool>)> {
2354
4
        let mut configs = Vec::new();
2355
6
        for store in 
&config.stores4
{
2356
8
            
store.spec6
.
visit_grpc_specs6
(&mut |grpc| {
2357
8
                configs.push((
2358
8
                    
matches!2
(grpc.store_type, StoreType::Cas),
2359
8
                    grpc.experimental_remote_cache_compression,
2360
                ));
2361
8
            });
2362
        }
2363
4
        configs
2364
4
    }
2365
2366
    #[test]
2367
1
    fn capabilities_config_remote_cache_compression_deserializes_true() {
2368
1
        let config: CapabilitiesConfig =
2369
1
            serde_json5::from_str(r#"{"remote_cache_compression": true}"#).unwrap();
2370
2371
1
        assert!(config.remote_cache_compression);
2372
1
    }
2373
2374
    #[test]
2375
1
    fn capabilities_config_remote_cache_compression_defaults_false() {
2376
1
        let config: CapabilitiesConfig = serde_json5::from_str("{}").unwrap();
2377
2378
1
        assert!(!config.remote_cache_compression);
2379
1
    }
2380
2381
    #[test]
2382
1
    fn omitted_grpc_compression_stays_disabled_without_zstd_intent() {
2383
1
        let config = CasConfig::try_from_json5_str(
2384
1
            r#"{
2385
1
                stores: [{
2386
1
                    name: "upstream",
2387
1
                    grpc: {
2388
1
                        endpoints: [{ address: "http://localhost:1234" }],
2389
1
                        store_type: "cas",
2390
1
                    },
2391
1
                }],
2392
1
                servers: [],
2393
1
            }"#,
2394
        )
2395
1
        .unwrap();
2396
2397
1
        assert_eq!(grpc_compression_configs(&config), vec![(true, None)]);
2398
1
    }
2399
2400
    #[test]
2401
1
    fn explicit_grpc_zstd_intent_enables_other_eligible_grpc_stores() {
2402
1
        let config = CasConfig::try_from_json5_str(
2403
1
            r#"{
2404
1
                stores: [
2405
1
                    {
2406
1
                        name: "enabled",
2407
1
                        grpc: {
2408
1
                            endpoints: [{ address: "http://localhost:1234" }],
2409
1
                            store_type: "cas",
2410
1
                            experimental_remote_cache_compression: true,
2411
1
                        },
2412
1
                    },
2413
1
                    {
2414
1
                        name: "inherited",
2415
1
                        grpc: {
2416
1
                            endpoints: [{ address: "http://localhost:5678" }],
2417
1
                            store_type: "cas",
2418
1
                        },
2419
1
                    },
2420
1
                ],
2421
1
                servers: [],
2422
1
            }"#,
2423
        )
2424
1
        .unwrap();
2425
2426
1
        assert_eq!(
2427
1
            grpc_compression_configs(&config),
2428
1
            vec![(true, Some(true)), (true, Some(true))]
2429
        );
2430
1
    }
2431
2432
    #[test]
2433
    #[traced_test]
2434
1
    fn ac_grpc_compression_warns_and_expresses_no_cas_intent() {
2435
1
        let config = CasConfig::try_from_json5_str(
2436
1
            r#"{
2437
1
                stores: [
2438
1
                    {
2439
1
                        name: "action-cache",
2440
1
                        grpc: {
2441
1
                            instance_name: "ac",
2442
1
                            endpoints: [{ address: "http://localhost:1234" }],
2443
1
                            store_type: "ac",
2444
1
                            experimental_remote_cache_compression: true,
2445
1
                        },
2446
1
                    },
2447
1
                    {
2448
1
                        name: "cas",
2449
1
                        grpc: {
2450
1
                            endpoints: [{ address: "http://localhost:5678" }],
2451
1
                            store_type: "cas",
2452
1
                        },
2453
1
                    },
2454
1
                ],
2455
1
                servers: [],
2456
1
            }"#,
2457
        )
2458
1
        .unwrap();
2459
2460
        // The AC-store setting is inert: it neither compresses AC RPCs nor
2461
        // expresses process-wide zstd intent, so the CAS store stays unset.
2462
1
        assert_eq!(
2463
1
            grpc_compression_configs(&config),
2464
1
            vec![(false, Some(true)), (true, None)]
2465
        );
2466
1
        assert!(logs_contain("store=\"action-cache\""));
2467
1
        assert!(logs_contain("no effect"));
2468
1
    }
2469
2470
    #[test]
2471
    #[traced_test]
2472
1
    fn capabilities_zstd_intent_defaults_nested_cas_grpc_and_warns_on_opt_out() {
2473
1
        let config = CasConfig::try_from_json5_str(
2474
1
            r#"{
2475
1
                stores: [{
2476
1
                    name: "nested-upstreams",
2477
1
                    fast_slow: {
2478
1
                        fast: {
2479
1
                            grpc: {
2480
1
                                instance_name: "auto",
2481
1
                                endpoints: [{ address: "http://localhost:1234" }],
2482
1
                                store_type: "cas",
2483
1
                            },
2484
1
                        },
2485
1
                        slow: {
2486
1
                            shard: {
2487
1
                                stores: [
2488
1
                                    {
2489
1
                                        store: {
2490
1
                                            grpc: {
2491
1
                                                instance_name: "opt-out",
2492
1
                                                endpoints: [{
2493
1
                                                    address: "http://localhost:5678",
2494
1
                                                }],
2495
1
                                                store_type: "cas",
2496
1
                                                experimental_remote_cache_compression: false,
2497
1
                                            },
2498
1
                                        },
2499
1
                                        weight: 1,
2500
1
                                    },
2501
1
                                    {
2502
1
                                        store: {
2503
1
                                            grpc: {
2504
1
                                                instance_name: "action-cache",
2505
1
                                                endpoints: [{
2506
1
                                                    address: "http://localhost:9012",
2507
1
                                                }],
2508
1
                                                store_type: "ac",
2509
1
                                            },
2510
1
                                        },
2511
1
                                        weight: 1,
2512
1
                                    },
2513
1
                                ],
2514
1
                            },
2515
1
                        },
2516
1
                    },
2517
1
                }],
2518
1
                servers: [{
2519
1
                    listener: {
2520
1
                        http: { socket_address: "127.0.0.1:50051" },
2521
1
                    },
2522
1
                    services: {
2523
1
                        capabilities: [{
2524
1
                            instance_name: "main",
2525
1
                            remote_cache_compression: true,
2526
1
                        }],
2527
1
                    },
2528
1
                }],
2529
1
            }"#,
2530
        )
2531
1
        .unwrap();
2532
2533
1
        assert_eq!(
2534
1
            grpc_compression_configs(&config),
2535
1
            vec![(true, Some(true)), (true, Some(false)), (false, None),]
2536
        );
2537
1
        assert!(logs_contain("store=\"nested-upstreams\""));
2538
1
        assert!(logs_contain("instance_name=\"opt-out\""));
2539
1
        assert!(logs_contain(CasConfig::ZSTD_COMPRESSION_DOCS_URL));
2540
1
    }
2541
2542
    #[test]
2543
1
    fn action_cache_read_only_by_instance_reads_each_ac_service() {
2544
1
        let mut config = CasConfig::try_from_json5_str("{ stores: [], servers: [] }").unwrap();
2545
        // No Action Cache services: the map is empty.
2546
1
        assert!(config.action_cache_read_only_by_instance().is_empty());
2547
2548
1
        config.servers = serde_json5::from_str(
2549
1
            r#"[{
2550
1
                listener: { http: { socket_address: "127.0.0.1:50051" } },
2551
1
                services: { ac: [
2552
1
                    { instance_name: "main", ac_store: "AC", read_only: false },
2553
1
                    { instance_name: "pr", ac_store: "AC", read_only: true },
2554
1
                ] }
2555
1
            }]"#,
2556
        )
2557
1
        .unwrap();
2558
2559
1
        let by_instance = config.action_cache_read_only_by_instance();
2560
1
        assert_eq!(by_instance.len(), 2);
2561
1
        assert_eq!(by_instance.get("main"), Some(&false));
2562
1
        assert_eq!(by_instance.get("pr"), Some(&true));
2563
1
    }
2564
2565
    #[test]
2566
1
    fn warns_only_for_shared_workers_and_a_writable_action_cache() {
2567
4
        fn config(single_use: bool, read_only: bool) -> CasConfig {
2568
4
            let mut config = CasConfig::try_from_json5_str("{ stores: [], servers: [] }").unwrap();
2569
4
            config.workers = Some(vec![WorkerConfig::Local(LocalWorkerConfig {
2570
4
                single_use,
2571
4
                ..Default::default()
2572
4
            })]);
2573
4
            config.servers = serde_json5::from_str(&format!(
2574
4
                r#"[{{
2575
4
                    listener: {{ http: {{ socket_address: "127.0.0.1:50051" }} }},
2576
4
                    services: {{ ac: [{{ ac_store: "AC", read_only: {read_only} }}] }}
2577
4
                }}]"#
2578
4
            ))
2579
4
            .unwrap();
2580
4
            config
2581
4
        }
2582
2583
        // Unsafe: shared workers and an action cache that accepts client writes.
2584
1
        assert!(config(false, false).shares_workers_with_writable_action_cache());
2585
        // Safe: `single_use` workers isolate each job.
2586
1
        assert!(!config(true, false).shares_workers_with_writable_action_cache());
2587
        // Safe: the action cache rejects client writes.
2588
1
        assert!(!config(false, true).shares_workers_with_writable_action_cache());
2589
2590
        // Safe: a cache-only process has no workers to share.
2591
1
        let mut cache_only = config(false, false);
2592
1
        cache_only.workers = None;
2593
1
        assert!(!cache_only.shares_workers_with_writable_action_cache());
2594
1
    }
2595
}