Coverage Report

Created: 2026-12-04 15:23

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/build/source/nativelink-config/src/backcompat.rs
Line
Count
Source
1
// Copyright 2026 Trace Machina, Inc. All rights reserved.
2
//
3
// Licensed under the Functional Source License, Version 1.1, Apache 2.0 Future License (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//    See LICENSE file for details
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14
15
use core::fmt;
16
use core::marker::PhantomData;
17
use std::collections::HashMap;
18
19
use serde::de::value::{MapAccessDeserializer, SeqAccessDeserializer};
20
use serde::de::{MapAccess, SeqAccess, Visitor};
21
use serde::{Deserialize, Deserializer, Serialize};
22
use tracing::warn;
23
24
use crate::cas_server::{ByteStreamConfig, OldByteStreamConfig, WithInstanceName};
25
26
enum WithInstanceNameBackCompat<T> {
27
    Map(HashMap<String, T>),
28
    Vec(Vec<WithInstanceName<T>>),
29
}
30
31
/// Picks the old map form or the new list form by the first token, instead
32
/// of `#[serde(untagged)]`. Untagged buffers the value and tries each form
33
/// in turn, so any mistake inside an entry was reported as "data did not
34
/// match any variant" with no field name. Streaming keeps the error from the
35
/// entry itself, with its line and column.
36
struct MapOrSeq<M, S>(PhantomData<(M, S)>);
37
38
impl<'de, M: Deserialize<'de>, S: Deserialize<'de>> Visitor<'de> for MapOrSeq<M, S> {
39
    type Value = Option<Result<M, S>>;
40
41
0
    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
42
0
        f.write_str("a list of service entries, or the older map from instance name to entry")
43
0
    }
44
45
1
    fn visit_none<E>(self) -> Result<Self::Value, E> {
46
1
        Ok(None)
47
1
    }
48
49
0
    fn visit_unit<E>(self) -> Result<Self::Value, E> {
50
0
        Ok(None)
51
0
    }
52
53
193
    fn visit_some<D: Deserializer<'de>>(self, deserializer: D) -> Result<Self::Value, D::Error> {
54
193
        deserializer.deserialize_any(self)
55
193
    }
56
57
11
    fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<Self::Value, A::Error> {
58
11
        M::deserialize(MapAccessDeserializer::new(map)).map(|value| Some(
Ok(value)8
))
59
11
    }
60
61
182
    fn visit_seq<A: SeqAccess<'de>>(self, seq: A) -> Result<Self::Value, A::Error> {
62
182
        S::deserialize(SeqAccessDeserializer::new(seq)).map(|value| Some(
Err(value)178
))
63
182
    }
64
}
65
66
8
fn deprecated(old_map: &String, new_map: &String) {
67
8
    warn!(
68
        r"WARNING: Using deprecated map format for services. Please migrate to the new array format:
69
// Old:
70
{}
71
// New:
72
{}
73
",
74
        old_map, new_map
75
    );
76
8
}
77
78
/// Use `#[serde(default, deserialize_with = "backcompat::opt_vec_with_instance_name")]` for backwards
79
/// compatibility with map-based access. A deprecation warning will be written to stderr if the
80
/// old format is used.
81
159
pub(crate) fn opt_vec_with_instance_name<'de, D, T>(
82
159
    deserializer: D,
83
159
) -> Result<Option<Vec<WithInstanceName<T>>>, D::Error>
84
159
where
85
159
    D: Deserializer<'de>,
86
159
    T: Deserialize<'de> + Serialize,
87
{
88
159
    let Some(
back_compat152
) = deserializer
89
159
        .deserialize_option(MapOrSeq::<HashMap<String, T>, Vec<WithInstanceName<T>>>(
90
159
            PhantomData,
91
159
        ))
?6
92
153
        .map(|form| match 
form152
{
93
5
            Ok(map) => WithInstanceNameBackCompat::Map(map),
94
147
            Err(vec) => WithInstanceNameBackCompat::Vec(vec),
95
152
        })
96
    else {
97
1
        return Ok(None);
98
    };
99
100
152
    match back_compat {
101
5
        WithInstanceNameBackCompat::Map(map) => {
102
            // TODO(palfrey): ideally this would be serde_json5::to_string_pretty but that doesn't exist
103
            // JSON is close enough to be workable for now
104
5
            let serde_map = serde_json::to_string_pretty(&map).expect("valid map");
105
5
            let vec: Vec<WithInstanceName<T>> = map
106
5
                .into_iter()
107
6
                .
map5
(|(instance_name, config)| WithInstanceName::new(instance_name, config))
108
5
                .collect();
109
5
            deprecated(
110
5
                &serde_map,
111
                // TODO(palfrey): ideally this would be serde_json5::to_string_pretty but that doesn't exist
112
                // JSON is close enough to be workable for now
113
5
                &serde_json::to_string_pretty(&vec).expect("valid new map"),
114
            );
115
5
            Ok(Some(vec))
116
        }
117
147
        WithInstanceNameBackCompat::Vec(vec) => Ok(Some(vec)),
118
    }
119
159
}
120
121
enum ByteStreamKind {
122
    New(Vec<WithInstanceName<ByteStreamConfig>>),
123
    Old(OldByteStreamConfig),
124
}
125
126
/// Use `#[serde(default, deserialize_with = "backcompat::opt_bytestream")]` for backwards
127
/// compatibility with older bytestream config . A deprecation warning will be written to stderr if the
128
/// old format is used.
129
35
pub(crate) fn opt_bytestream<'de, D>(
130
35
    deserializer: D,
131
35
) -> Result<Option<Vec<WithInstanceName<ByteStreamConfig>>>, D::Error>
132
35
where
133
35
    D: Deserializer<'de>,
134
{
135
35
    let Some(
back_compat34
) = deserializer
136
35
        .deserialize_option(MapOrSeq::<
137
35
            OldByteStreamConfig,
138
35
            Vec<WithInstanceName<ByteStreamConfig>>,
139
35
        >(PhantomData))
?1
140
34
        .map(|form| match form {
141
3
            Ok(old) => ByteStreamKind::Old(old),
142
31
            Err(new) => ByteStreamKind::New(new),
143
34
        })
144
    else {
145
0
        return Ok(None);
146
    };
147
148
34
    match back_compat {
149
3
        ByteStreamKind::Old(old_config) => {
150
3
            if old_config.max_decoding_message_size != 0 {
151
0
                warn!(
152
                    "WARNING: max_decoding_message_size is ignored on Bytestream now. Please set on the HTTP listener instead"
153
                );
154
3
            }
155
            // TODO(palfrey): ideally this would be serde_json5::to_string_pretty but that doesn't exist
156
            // JSON is close enough to be workable for now
157
3
            let serde_map = serde_json::to_string_pretty(&old_config).expect("valid map");
158
3
            let names = old_config.cas_stores;
159
3
            let vec: Vec<WithInstanceName<_>> = names
160
3
                .iter()
161
3
                .map(|(instance_name, cas_store)| {
162
3
                    WithInstanceName::new(
163
3
                        instance_name.clone(),
164
3
                        ByteStreamConfig {
165
3
                            cas_store: cas_store.clone(),
166
3
                            max_bytes_per_stream: old_config.max_bytes_per_stream,
167
3
                            persist_stream_on_disconnect_timeout_s: old_config
168
3
                                .persist_stream_on_disconnect_timeout_s,
169
3
                            recover_unknown_uuid_resumes: true,
170
3
                        },
171
                    )
172
3
                })
173
3
                .collect();
174
3
            deprecated(
175
3
                &serde_map,
176
                // TODO(palfrey): ideally this would be serde_json5::to_string_pretty but that doesn't exist
177
                // JSON is close enough to be workable for now
178
3
                &serde_json::to_string_pretty(&vec).expect("valid new map"),
179
            );
180
3
            Ok(Some(vec))
181
        }
182
31
        ByteStreamKind::New(vec) => Ok(Some(vec)),
183
    }
184
35
}
185
186
#[cfg(test)]
187
mod tests {
188
    use serde_json::json;
189
    use tracing_test::traced_test;
190
191
    use super::*;
192
193
    #[derive(Debug, Deserialize, Serialize, PartialEq)]
194
    struct PartialConfig {
195
        store: String,
196
    }
197
198
    #[derive(Debug, Deserialize, Serialize, PartialEq)]
199
    struct FullConfig {
200
        #[serde(default, deserialize_with = "opt_vec_with_instance_name")]
201
        cas: Option<Vec<WithInstanceName<PartialConfig>>>,
202
    }
203
204
    #[test]
205
    #[traced_test]
206
1
    fn test_configs_deserialization() {
207
1
        let old_format = json!({
208
1
            "cas": {
209
1
                "foo": { "store": "foo_store" },
210
1
                "bar": { "store": "bar_store" }
211
            }
212
        });
213
214
1
        let new_format = json!({
215
1
            "cas": [
216
                {
217
1
                    "instance_name": "foo",
218
1
                    "store": "foo_store"
219
                },
220
                {
221
1
                    "instance_name": "bar",
222
1
                    "store": "bar_store"
223
                }
224
            ]
225
        });
226
227
1
        let mut old_format: FullConfig = serde_json::from_value(old_format).unwrap();
228
1
        let mut new_format: FullConfig = serde_json::from_value(new_format).unwrap();
229
230
        // Ensure deterministic ordering.
231
1
        if let Some(vec) = old_format.cas.as_mut() {
232
1
            vec.sort_by(|a, b| a.instance_name.cmp(&b.instance_name));
233
0
        }
234
1
        if let Some(vec) = new_format.cas.as_mut() {
235
1
            vec.sort_by(|a, b| a.instance_name.cmp(&b.instance_name));
236
0
        }
237
238
1
        assert_eq!(old_format, new_format);
239
240
1
        logs_assert(|lines: &[&str]| {
241
1
            if lines.len() != 1 {
242
0
                return Err(format!("Expected 1 log line, got: {lines:?}"));
243
1
            }
244
1
            let line = lines[0];
245
            // TODO(palfrey): we should be checking the whole thing, but tracing-test is broken with multi-line items
246
            // See https://github.com/dbrgn/tracing-test/issues/48
247
1
            assert!(line.ends_with("WARNING: Using deprecated map format for services. Please migrate to the new array format:"));
248
1
            Ok(())
249
1
        });
250
1
    }
251
252
    #[test]
253
1
    fn test_deserialize_none() {
254
1
        let json = json!({});
255
256
1
        let value: FullConfig = serde_json::from_value(json).unwrap();
257
1
        assert_eq!(value.cas, None);
258
1
    }
259
260
    #[derive(Debug, Deserialize, Serialize, PartialEq)]
261
    struct FullBytestreamConfig {
262
        #[serde(default, deserialize_with = "opt_bytestream")]
263
        pub bytestream: Option<Vec<WithInstanceName<ByteStreamConfig>>>,
264
    }
265
266
    #[test]
267
    #[traced_test]
268
1
    fn test_bytestream_old_config() {
269
1
        let old_format = json!({
270
1
            "bytestream": {
271
1
                "cas_stores": {
272
1
                    "": "WORKER_FAST_SLOW_STORE"
273
            }}
274
        });
275
276
1
        let new_format = json!({
277
1
            "bytestream": [
278
                {
279
1
                    "cas_store": "WORKER_FAST_SLOW_STORE",
280
                },
281
            ],
282
        });
283
284
1
        let old_format: FullBytestreamConfig = serde_json::from_value(old_format).unwrap();
285
1
        let new_format: FullBytestreamConfig = serde_json::from_value(new_format).unwrap();
286
287
1
        assert_eq!(old_format, new_format);
288
289
1
        logs_assert(|lines: &[&str]| {
290
1
            if lines.len() != 1 {
291
0
                return Err(format!("Expected 1 log line, got: {lines:?}"));
292
1
            }
293
1
            let line = lines[0];
294
            // TODO(palfrey): we should be checking the whole thing, but tracing-test is broken with multi-line items
295
            // See https://github.com/dbrgn/tracing-test/issues/48
296
1
            assert!(line.ends_with("WARNING: Using deprecated map format for services. Please migrate to the new array format:"));
297
1
            Ok(())
298
1
        });
299
1
    }
300
}