cavs-cli 0.9.0

Package, verify and deliver deduplicated game content as .cavs files.
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
//! `cavs serve` (v0.9.0): a local content server over a CAVS workspace,
//! for development and plugin testing only — SteamPipe's "local content
//! server" idea without any production ambitions. No auth, plain HTTP,
//! and it says so at startup. Production delivery stays with
//! `cavs-server`.

// Handlers return `Result<T, Response>` so errors short-circuit into an
// HTTP response; the Response-sized Err is intentional for a dev server.
#![allow(clippy::result_large_err)]

use anyhow::{Context, Result};
use axum::extract::{Path as AxPath, Query, State};
use axum::http::{header, HeaderMap, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::{Json, Router};
use serde::Deserialize;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;

pub struct ServeArgs {
    pub workspace: PathBuf,
    pub app: Option<String>,
    pub branch: Option<String>,
    /// Optional directory of published release files, served under
    /// /api/assets/{asset}/{file} (e.g. `cavs publish-dir` output).
    pub releases: Option<PathBuf>,
    pub port: u16,
}

struct ServeState {
    root: PathBuf,
    default_app: Option<String>,
    releases: Option<PathBuf>,
}

type Shared = Arc<ServeState>;

fn ws(state: &ServeState) -> Result<cavs_workspace::Workspace, Response> {
    cavs_workspace::Workspace::open(&state.root).map_err(|e| err(StatusCode::NOT_FOUND, e))
}

fn err(code: StatusCode, e: impl std::fmt::Display) -> Response {
    (code, format!("{e}")).into_response()
}

pub fn serve(args: &ServeArgs) -> Result<()> {
    // Validate the workspace before starting the runtime.
    let workspace = cavs_workspace::Workspace::open(&args.workspace)?;
    let default_app = Some(workspace.app_id(args.app.as_deref())?);

    let state: Shared = Arc::new(ServeState {
        root: args.workspace.clone(),
        default_app,
        releases: args.releases.clone(),
    });

    let app = Router::new()
        .route("/", get(index))
        .route(
            "/api/apps/{app}/branches/{branch}/current",
            get(branch_current),
        )
        .route("/api/apps/{app}/builds/{build}", get(build_meta))
        .route(
            "/api/apps/{app}/builds/{build}/depots/{depot}/index",
            get(depot_index),
        )
        .route(
            "/api/apps/{app}/builds/{build}/depots/{depot}/files/{*path}",
            get(depot_file),
        )
        .route(
            "/api/apps/{app}/builds/{build}/depots/{depot}/chunks/{hash}",
            get(depot_chunk),
        )
        .route("/api/assets/{asset}/{file}", get(release_file))
        .route("/api/preview", get(preview))
        .with_state(state);

    eprintln!("+----------------------------------------------------------------+");
    eprintln!("|  WARNING: DEVELOPMENT SERVER ONLY                              |");
    eprintln!("|  No auth, no TLS, not production hardened.                     |");
    eprintln!("|  Never expose this to the internet or real players.            |");
    eprintln!("|  Use cavs-server for real deployments.                         |");
    eprintln!("+----------------------------------------------------------------+");
    if let Some(branch) = &args.branch {
        eprintln!("[serve] default branch: {branch}");
    }

    let runtime = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()?;
    runtime.block_on(async {
        let listener = tokio::net::TcpListener::bind(("127.0.0.1", args.port))
            .await
            .with_context(|| format!("cannot bind 127.0.0.1:{}", args.port))?;
        println!("listening on http://{}", listener.local_addr()?);
        axum::serve(listener, app).await?;
        Ok(())
    })
}

async fn index(State(state): State<Shared>) -> Response {
    let app = state.default_app.clone().unwrap_or_default();
    (
        StatusCode::OK,
        format!(
            "cavs serve — DEVELOPMENT SERVER ONLY (no auth, no TLS, not production hardened)\n\
             workspace: {}\n\
             default app: {app}\n\n\
             endpoints:\n\
             GET /api/apps/{{app}}/branches/{{branch}}/current\n\
             GET /api/apps/{{app}}/builds/{{build}}\n\
             GET /api/apps/{{app}}/builds/{{build}}/depots/{{depot}}/index\n\
             GET /api/apps/{{app}}/builds/{{build}}/depots/{{depot}}/files/{{path}} (Range supported)\n\
             GET /api/apps/{{app}}/builds/{{build}}/depots/{{depot}}/chunks/{{hash}}\n\
             GET /api/assets/{{asset}}/{{file}} (published release files)\n\
             GET /api/preview?app=...&from=build_...&to=build_...\n",
            state.root.display()
        ),
    )
        .into_response()
}

async fn branch_current(
    State(state): State<Shared>,
    AxPath((app, branch)): AxPath<(String, String)>,
) -> Response {
    let ws = match ws(&state) {
        Ok(w) => w,
        Err(r) => return r,
    };
    let meta = match ws.load_app(&app) {
        Ok(a) => a,
        Err(e) => return err(StatusCode::NOT_FOUND, e),
    };
    let b = match meta.branch(&branch) {
        Ok(b) => b.clone(),
        Err(e) => return err(StatusCode::NOT_FOUND, e),
    };
    let build = match &b.current_build {
        Some(id) => match ws.build(&app, id) {
            Ok(build) => Some(build),
            Err(e) => return err(StatusCode::INTERNAL_SERVER_ERROR, e),
        },
        None => None,
    };
    Json(serde_json::json!({ "branch": b, "build": build })).into_response()
}

async fn build_meta(
    State(state): State<Shared>,
    AxPath((app, build)): AxPath<(String, String)>,
) -> Response {
    let ws = match ws(&state) {
        Ok(w) => w,
        Err(r) => return r,
    };
    match ws.build(&app, &build) {
        Ok(b) => Json(b).into_response(),
        Err(e) => err(StatusCode::NOT_FOUND, e),
    }
}

async fn depot_index(
    State(state): State<Shared>,
    AxPath((app, build, depot)): AxPath<(String, String, String)>,
) -> Response {
    let ws = match ws(&state) {
        Ok(w) => w,
        Err(r) => return r,
    };
    match ws.depot_index(&app, &build, &depot) {
        Ok(idx) => Json(idx).into_response(),
        Err(e) => err(StatusCode::NOT_FOUND, e),
    }
}

/// The on-disk source directory a depot was indexed from.
fn depot_source(
    ws: &cavs_workspace::Workspace,
    app: &str,
    build: &str,
    depot: &str,
) -> Result<PathBuf, Response> {
    let b = ws
        .build(app, build)
        .map_err(|e| err(StatusCode::NOT_FOUND, e))?;
    let db = b
        .depots
        .iter()
        .find(|d| d.depot_id == depot)
        .ok_or_else(|| {
            err(
                StatusCode::NOT_FOUND,
                format!("no depot '{depot}' in {build}"),
            )
        })?;
    let root = PathBuf::from(&db.source_path);
    if !root.exists() {
        return Err(err(
            StatusCode::GONE,
            format!("depot source {} no longer exists", root.display()),
        ));
    }
    Ok(root)
}

/// Resolve a request path inside a depot root, rejecting traversal.
fn safe_join(root: &std::path::Path, rel: &str) -> Result<PathBuf, Response> {
    let bad = rel.starts_with('/')
        || rel.contains('\\')
        || rel.split('/').any(|seg| seg == ".." || seg.is_empty());
    if bad {
        return Err(err(
            StatusCode::BAD_REQUEST,
            "CAVS-E-ANALYZE-PATH-TRAVERSAL",
        ));
    }
    Ok(root.join(rel))
}

fn range_of(headers: &HeaderMap, len: u64) -> Option<(u64, u64)> {
    let value = headers.get(header::RANGE)?.to_str().ok()?;
    let spec = value.strip_prefix("bytes=")?;
    let (start, end) = spec.split_once('-')?;
    let start: u64 = start.parse().ok()?;
    let end: u64 = if end.is_empty() {
        len.saturating_sub(1)
    } else {
        end.parse().ok()?
    };
    (start <= end && end < len).then_some((start, end))
}

fn serve_bytes(headers: &HeaderMap, bytes: Vec<u8>) -> Response {
    let len = bytes.len() as u64;
    match range_of(headers, len) {
        Some((start, end)) => {
            let body = bytes[start as usize..=end as usize].to_vec();
            (
                StatusCode::PARTIAL_CONTENT,
                [
                    (header::CONTENT_RANGE, format!("bytes {start}-{end}/{len}")),
                    (header::ACCEPT_RANGES, "bytes".into()),
                ],
                body,
            )
                .into_response()
        }
        None => (
            StatusCode::OK,
            [(header::ACCEPT_RANGES, "bytes".to_string())],
            bytes,
        )
            .into_response(),
    }
}

async fn depot_file(
    State(state): State<Shared>,
    AxPath((app, build, depot, path)): AxPath<(String, String, String, String)>,
    headers: HeaderMap,
) -> Response {
    let ws = match ws(&state) {
        Ok(w) => w,
        Err(r) => return r,
    };
    let root = match depot_source(&ws, &app, &build, &depot) {
        Ok(r) => r,
        Err(r) => return r,
    };
    let file = match safe_join(&root, &path) {
        Ok(f) => f,
        Err(r) => return r,
    };
    match std::fs::read(&file) {
        Ok(bytes) => serve_bytes(&headers, bytes),
        Err(e) => err(StatusCode::NOT_FOUND, e),
    }
}

/// Serve one chunk by hash: located via the depot index (cumulative
/// offsets per file), read from the depot source.
async fn depot_chunk(
    State(state): State<Shared>,
    AxPath((app, build, depot, hash)): AxPath<(String, String, String, String)>,
) -> Response {
    let ws = match ws(&state) {
        Ok(w) => w,
        Err(r) => return r,
    };
    let idx = match ws.depot_index(&app, &build, &depot) {
        Ok(i) => i,
        Err(e) => return err(StatusCode::NOT_FOUND, e),
    };
    let root = match depot_source(&ws, &app, &build, &depot) {
        Ok(r) => r,
        Err(r) => return r,
    };
    for (rel, chunks) in &idx.files {
        let mut offset = 0u64;
        for (h, len) in chunks {
            if h == &hash {
                let file = match safe_join(&root, rel) {
                    Ok(f) => f,
                    Err(r) => return r,
                };
                use std::io::{Read, Seek, SeekFrom};
                let mut f = match std::fs::File::open(&file) {
                    Ok(f) => f,
                    Err(e) => return err(StatusCode::GONE, e),
                };
                let mut buf = vec![0u8; *len as usize];
                if f.seek(SeekFrom::Start(offset)).is_err() || f.read_exact(&mut buf).is_err() {
                    return err(StatusCode::GONE, "chunk out of range (source changed?)");
                }
                // Integrity: the source may have changed since indexing.
                if cavs_hash::to_hex(&cavs_hash::hash_chunk(&buf)) != hash {
                    return err(
                        StatusCode::GONE,
                        "CAVS-E-CHUNK-HASH-MISMATCH: source changed since indexing",
                    );
                }
                return (StatusCode::OK, buf).into_response();
            }
            offset += len;
        }
    }
    err(
        StatusCode::NOT_FOUND,
        format!("chunk {hash} not in depot '{depot}'"),
    )
}

/// Published release files (e.g. `cavs publish-dir` output):
/// /api/assets/{asset}/{file} → <releases>/<asset>/<file>.
async fn release_file(
    State(state): State<Shared>,
    AxPath((asset, file)): AxPath<(String, String)>,
    headers: HeaderMap,
) -> Response {
    let Some(releases) = &state.releases else {
        return err(
            StatusCode::NOT_FOUND,
            "no --releases directory configured; run with --releases <dir>",
        );
    };
    let root = releases.join(&asset);
    let path = match safe_join(&root, &file) {
        Ok(p) => p,
        Err(r) => return r,
    };
    match std::fs::read(&path) {
        Ok(bytes) => serve_bytes(&headers, bytes),
        Err(e) => err(StatusCode::NOT_FOUND, e),
    }
}

#[derive(Deserialize)]
struct PreviewParams {
    app: Option<String>,
    from: String,
    to: String,
}

/// Per-depot update estimate between two builds (raw new chunk bytes).
async fn preview(State(state): State<Shared>, Query(params): Query<PreviewParams>) -> Response {
    let ws = match ws(&state) {
        Ok(w) => w,
        Err(r) => return r,
    };
    let app = params
        .app
        .or_else(|| state.default_app.clone())
        .unwrap_or_default();
    let from = match ws.build(&app, &params.from) {
        Ok(b) => b,
        Err(e) => return err(StatusCode::NOT_FOUND, e),
    };
    let to = match ws.build(&app, &params.to) {
        Ok(b) => b,
        Err(e) => return err(StatusCode::NOT_FOUND, e),
    };
    let mut per_depot: HashMap<String, u64> = HashMap::new();
    for db in &to.depots {
        let new_idx = match ws.depot_index(&app, &to.id, &db.depot_id) {
            Ok(i) => i,
            Err(e) => return err(StatusCode::INTERNAL_SERVER_ERROR, e),
        };
        let bytes = if from.depots.iter().any(|d| d.depot_id == db.depot_id) {
            let old_idx = match ws.depot_index(&app, &from.id, &db.depot_id) {
                Ok(i) => i,
                Err(e) => return err(StatusCode::INTERNAL_SERVER_ERROR, e),
            };
            cavs_workspace::sharing::fetch_bytes(&new_idx, &[&old_idx])
        } else {
            new_idx.total_bytes
        };
        per_depot.insert(db.depot_id.clone(), bytes);
    }
    let total: u64 = per_depot.values().sum();
    Json(serde_json::json!({
        "app": app,
        "from": from.id,
        "to": to.id,
        "estimated_update_bytes_per_depot": per_depot,
        "estimated_update_bytes_total": total,
        "note": "raw new chunk bytes from content indices, before wire compression",
    }))
    .into_response()
}