promptforge-gateway 0.1.0

PromptForge inference gateway: routes OpenAI-shaped chat completions to a backend
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! Semantic validation of a parsed [`Config`].
//!
//! A `Config` value cannot hold an invalid state: construction runs [`Config::validate`],
//! which rejects empty ids, unresolved references, kind-incompatible devices,
//! malformed HTTP(S) URLs, and out-of-vocabulary web-search knobs. Downstream
//! code therefore never re-validates or clamps operator input.

use std::collections::HashSet;

use url::Url;

use super::{Config, DeviceKind, is_sha256_hex};
use crate::error::ConfigError;

impl Config {
    /// Check names are unique, references resolve, URLs parse, and closed
    /// vocabularies hold.
    ///
    /// # Errors
    /// Returns [`ConfigError::Validation`] on any failed invariant: an empty or
    /// duplicate id, a model with no or duplicate endpoints, a model naming an
    /// undefined endpoint, a malformed endpoint or web-search URL, an
    /// out-of-vocabulary freshness/safesearch default, an invalid
    /// `[[local_model]]`, `queue.max_depth` below 1, or a concurrency below 1.
    pub(crate) fn validate(&self) -> Result<(), ConfigError> {
        if self.server.key.is_empty() {
            return Err(ConfigError::Validation(
                "server.key must not be empty".to_string(),
            ));
        }
        if self.queue.max_depth < 1 {
            return Err(ConfigError::Validation(
                "queue.max_depth must be at least 1".to_string(),
            ));
        }
        self.validate_devices()?;
        let endpoint_ids = self.validate_endpoints()?;
        self.validate_models(&endpoint_ids)?;
        self.validate_tools()?;
        Ok(())
    }

    /// Validate `[tools.web_search]` bounds, URL, and closed knobs at load so
    /// downstream code never has to clamp or re-parse operator input (CFG-006).
    fn validate_tools(&self) -> Result<(), ConfigError> {
        let Some(web_search) = self.web_search_config() else {
            return Ok(());
        };
        if web_search.default_count < 1 {
            return Err(ConfigError::Validation(
                "tools.web_search.default_count must be at least 1".to_string(),
            ));
        }
        if web_search.max_count < 1 {
            return Err(ConfigError::Validation(
                "tools.web_search.max_count must be at least 1".to_string(),
            ));
        }
        if web_search.default_count > web_search.max_count {
            return Err(ConfigError::Validation(
                "tools.web_search.default_count must not exceed max_count".to_string(),
            ));
        }
        if web_search.max_per_host < 1 {
            return Err(ConfigError::Validation(
                "tools.web_search.max_per_host must be at least 1".to_string(),
            ));
        }
        // Parse the base URL, don't just prefix-match it (CFG-006).
        validate_http_url("tools.web_search.base_url", web_search.base_url.trim())?;
        if !is_valid_freshness(&web_search.default_freshness) {
            return Err(ConfigError::Validation(format!(
                "tools.web_search.default_freshness {:?} is not one of pd/pw/pm/py, a \
                 YYYY-MM-DDtoYYYY-MM-DD range, or empty",
                web_search.default_freshness
            )));
        }
        if !is_valid_safesearch(&web_search.default_safesearch) {
            return Err(ConfigError::Validation(format!(
                "tools.web_search.default_safesearch {:?} is not off/moderate/strict or empty",
                web_search.default_safesearch
            )));
        }
        Ok(())
    }

    fn validate_devices(&self) -> Result<(), ConfigError> {
        let mut device_ids = HashSet::new();
        for device in &self.devices {
            if device.id.is_empty() {
                return Err(ConfigError::Validation(
                    "device id must not be empty".to_string(),
                ));
            }
            if !device_ids.insert(device.id.as_str()) {
                return Err(ConfigError::Validation(format!(
                    "duplicate device id {}",
                    device.id
                )));
            }
            if let Some(concurrency) = device.concurrency
                && concurrency < 1
            {
                return Err(ConfigError::Validation(format!(
                    "device {} concurrency must be at least 1",
                    device.id
                )));
            }
            // Kind-incompatible payloads are rejected: remote devices use flat
            // concurrency (no lanes); local devices use lanes (no flat
            // concurrency). (CFG-004)
            match device.kind {
                DeviceKind::Remote if !device.lanes.is_empty() => {
                    return Err(ConfigError::Validation(format!(
                        "remote device {} must not declare lanes",
                        device.id
                    )));
                }
                DeviceKind::Local if device.concurrency.is_some() => {
                    return Err(ConfigError::Validation(format!(
                        "local device {} uses lanes, not flat concurrency",
                        device.id
                    )));
                }
                _ => {}
            }
            let mut lane_ids = HashSet::new();
            for lane in &device.lanes {
                if lane.id.is_empty() {
                    return Err(ConfigError::Validation(format!(
                        "device {} lane id must not be empty",
                        device.id
                    )));
                }
                if !lane_ids.insert(lane.id.as_str()) {
                    return Err(ConfigError::Validation(format!(
                        "duplicate lane id {} on device {}",
                        lane.id, device.id
                    )));
                }
                if lane.concurrency < 1 {
                    return Err(ConfigError::Validation(format!(
                        "device {} lane {} concurrency must be at least 1",
                        device.id, lane.id
                    )));
                }
                if let Some(ref_id) = &lane.device
                    && ref_id != &device.id
                {
                    return Err(ConfigError::Validation(format!(
                        "lane {} device {ref_id} does not match parent device {}",
                        lane.id, device.id
                    )));
                }
            }
        }
        Ok(())
    }

    fn validate_endpoints(&self) -> Result<HashSet<&str>, ConfigError> {
        let mut endpoint_ids = HashSet::new();
        for endpoint in &self.endpoints {
            // A blank id can never be referenced by a model and silently
            // shadows the "unnamed" slot; reject it at the boundary (CFG-003).
            if endpoint.id.trim().is_empty() {
                return Err(ConfigError::Validation(
                    "endpoint id must not be empty".to_string(),
                ));
            }
            if !endpoint_ids.insert(endpoint.id.as_str()) {
                return Err(ConfigError::Validation(format!(
                    "duplicate endpoint id {}",
                    endpoint.id
                )));
            }
            // Parse and validate the base URL at load; the upstream adapter then
            // joins the request path onto a known-good origin instead of
            // concatenating an arbitrary string (CFG-003, UP-005).
            validate_http_url(
                &format!("endpoint {} base_url", endpoint.id),
                endpoint.base_url.trim(),
            )?;
            if let Some(concurrency) = endpoint.concurrency
                && concurrency < 1
            {
                return Err(ConfigError::Validation(format!(
                    "endpoint {} concurrency must be at least 1",
                    endpoint.id
                )));
            }
            if let Some(device_id) = &endpoint.device {
                let device = self.devices.iter().find(|d| d.id == *device_id);
                let Some(device) = device else {
                    return Err(ConfigError::Validation(format!(
                        "endpoint {} names undefined device {device_id}",
                        endpoint.id
                    )));
                };
                if device.kind != DeviceKind::Remote {
                    return Err(ConfigError::Validation(format!(
                        "endpoint {} references non-remote device {device_id}",
                        endpoint.id
                    )));
                }
            }
        }
        Ok(endpoint_ids)
    }

    fn validate_models(&self, endpoint_ids: &HashSet<&str>) -> Result<(), ConfigError> {
        let mut model_names = HashSet::new();
        for model in &self.models {
            if !model_names.insert(model.name.as_str()) {
                return Err(ConfigError::Validation(format!(
                    "duplicate model name {}",
                    model.name
                )));
            }
            if model.name.trim().is_empty() {
                return Err(ConfigError::Validation(
                    "model name must not be empty".to_string(),
                ));
            }
            if model.description.trim().is_empty() {
                return Err(ConfigError::Validation(format!(
                    "model {} description must not be empty",
                    model.name
                )));
            }
            if model.upstream.trim().is_empty() {
                return Err(ConfigError::Validation(format!(
                    "model {} upstream must not be empty",
                    model.name
                )));
            }
            if model.context == 0 {
                return Err(ConfigError::Validation(format!(
                    "model {} context must be greater than zero",
                    model.name
                )));
            }
            if model.default_max_tokens == Some(0) {
                return Err(ConfigError::Validation(format!(
                    "model {} default_max_tokens must be greater than zero",
                    model.name
                )));
            }
            if model.endpoints.is_empty() {
                return Err(ConfigError::Validation(format!(
                    "model {} has no endpoints",
                    model.name
                )));
            }
            let mut seen_endpoints = HashSet::new();
            for endpoint in &model.endpoints {
                if !endpoint_ids.contains(endpoint.as_str()) {
                    return Err(ConfigError::Validation(format!(
                        "model {} names undefined endpoint {endpoint}",
                        model.name
                    )));
                }
                if !seen_endpoints.insert(endpoint.as_str()) {
                    return Err(ConfigError::Validation(format!(
                        "model {} lists duplicate endpoint {endpoint}",
                        model.name
                    )));
                }
            }
        }

        self.validate_local_models(&mut model_names)
    }

    fn validate_local_models<'a>(
        &'a self,
        model_names: &mut HashSet<&'a str>,
    ) -> Result<(), ConfigError> {
        for local_model in &self.local_models {
            if local_model.name.is_empty() {
                return Err(ConfigError::Validation(
                    "local_model name must not be empty".to_string(),
                ));
            }
            if !model_names.insert(local_model.name.as_str()) {
                return Err(ConfigError::Validation(format!(
                    "duplicate model name {}",
                    local_model.name
                )));
            }
            if local_model.description.is_empty() {
                return Err(ConfigError::Validation(format!(
                    "local_model {} description must not be empty",
                    local_model.name
                )));
            }
            if local_model.source.is_empty() {
                return Err(ConfigError::Validation(format!(
                    "local_model {} source must not be empty",
                    local_model.name
                )));
            }
            if local_model.source.starts_with("http://") {
                return Err(ConfigError::Validation(format!(
                    "local_model {} source must use https, not plaintext http",
                    local_model.name
                )));
            }
            // Remote artifacts must be pinned by digest (ART-002); a local
            // filesystem source is operator-controlled and may be unpinned.
            let is_remote = local_model.source.starts_with("https://");
            if is_remote {
                validate_http_url(
                    &format!("local_model {} source", local_model.name),
                    &local_model.source,
                )?;
                if local_model.sha256.is_none() {
                    return Err(ConfigError::Validation(format!(
                        "local_model {} has a remote source and must set a sha256 pin",
                        local_model.name
                    )));
                }
            }
            if local_model.context < 1 {
                return Err(ConfigError::Validation(format!(
                    "local_model {} context must be at least 1",
                    local_model.name
                )));
            }
            if local_model.n_predict < 1 {
                return Err(ConfigError::Validation(format!(
                    "local_model {} n_predict must be at least 1",
                    local_model.name
                )));
            }
            if local_model.cache_type_k.is_empty() || local_model.cache_type_v.is_empty() {
                return Err(ConfigError::Validation(format!(
                    "local_model {} cache_type_k/v must not be empty",
                    local_model.name
                )));
            }
            if let Some(sha) = &local_model.sha256
                && !is_sha256_hex(sha)
            {
                return Err(ConfigError::Validation(format!(
                    "local_model {} sha256 must be 64 lowercase hex characters",
                    local_model.name
                )));
            }
            self.local_model_concurrency(local_model)?;
        }
        Ok(())
    }
}

/// Parse `raw` and require an `http`/`https` scheme with a non-empty host.
///
/// This is the single URL gate for operator-supplied origins: a value that
/// passes here is a real, absolute HTTP(S) URL, so adapters can join a path
/// onto it structurally rather than concatenating an unvalidated string.
fn validate_http_url(context: &str, raw: &str) -> Result<(), ConfigError> {
    let url = Url::parse(raw).map_err(|error| {
        ConfigError::Validation(format!("{context} is not a valid URL: {error}"))
    })?;
    if !matches!(url.scheme(), "http" | "https") {
        return Err(ConfigError::Validation(format!(
            "{context} must use http or https, got {:?}",
            url.scheme()
        )));
    }
    if url.host_str().is_none_or(str::is_empty) {
        return Err(ConfigError::Validation(format!(
            "{context} must include a host"
        )));
    }
    Ok(())
}

/// Whether `value` is an accepted Brave freshness knob: empty (omit), one of
/// `pd`/`pw`/`pm`/`py`, or a `YYYY-MM-DDtoYYYY-MM-DD` date range.
fn is_valid_freshness(value: &str) -> bool {
    if value.is_empty() || matches!(value, "pd" | "pw" | "pm" | "py") {
        return true;
    }
    value
        .split_once("to")
        .is_some_and(|(from, to)| is_iso_date(from) && is_iso_date(to))
}

/// Whether `value` is `YYYY-MM-DD` (digits and dashes in the right positions).
fn is_iso_date(value: &str) -> bool {
    let bytes = value.as_bytes();
    bytes.len() == 10
        && bytes[4] == b'-'
        && bytes[7] == b'-'
        && bytes
            .iter()
            .enumerate()
            .all(|(index, byte)| index == 4 || index == 7 || byte.is_ascii_digit())
}

/// Whether `value` is an accepted safesearch knob: empty (omit), `off`,
/// `moderate`, or `strict`.
fn is_valid_safesearch(value: &str) -> bool {
    matches!(value, "" | "off" | "moderate" | "strict")
}

#[cfg(test)]
mod tests {
    use super::{is_iso_date, is_valid_freshness, is_valid_safesearch, validate_http_url};

    #[test]
    fn http_url_accepts_http_and_https_with_host() {
        assert!(validate_http_url("ctx", "http://127.0.0.1:9").is_ok());
        assert!(validate_http_url("ctx", "https://api.example.com/res/v1").is_ok());
    }

    #[test]
    fn http_url_rejects_missing_scheme_and_bad_scheme() {
        assert!(validate_http_url("ctx", "not-a-url").is_err());
        assert!(validate_http_url("ctx", "ftp://example.com").is_err());
        assert!(validate_http_url("ctx", "127.0.0.1:9").is_err());
    }

    #[test]
    fn freshness_vocabulary() {
        for ok in ["", "pd", "pw", "pm", "py", "2024-01-01to2024-12-31"] {
            assert!(is_valid_freshness(ok), "expected {ok:?} to be valid");
        }
        for bad in [
            "daily",
            "p1",
            "2024/01/01to2024/12/31",
            "2024-1-1to2024-12-31",
        ] {
            assert!(!is_valid_freshness(bad), "expected {bad:?} to be invalid");
        }
    }

    #[test]
    fn safesearch_vocabulary() {
        for ok in ["", "off", "moderate", "strict"] {
            assert!(is_valid_safesearch(ok));
        }
        for bad in ["on", "medium", "safe"] {
            assert!(!is_valid_safesearch(bad));
        }
    }

    #[test]
    fn iso_date_shape() {
        assert!(is_iso_date("2024-01-01"));
        assert!(!is_iso_date("2024-1-01"));
        assert!(!is_iso_date("2024-01-01T"));
    }
}