phantom-frame 0.2.11

A high-performance prerendering proxy engine with caching support
Documentation
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
use crate::cache::CacheHandle;
use axum::{
    extract::State,
    http::{header, HeaderMap, StatusCode},
    response::IntoResponse,
    routing::post,
    Json, Router,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::task::JoinHandle;

#[derive(Clone)]
pub struct ControlState {
    /// Named server handles — (server_name, handle) pairs.
    handles: Vec<(String, CacheHandle)>,
    auth_token: Option<String>,
}

impl ControlState {
    pub fn new(handles: Vec<(String, CacheHandle)>, auth_token: Option<String>) -> Self {
        Self {
            handles,
            auth_token,
        }
    }

    /// Return handles matching `server` (if provided) or all handles.
    /// Returns `Err` when a name was given but no server matched.
    fn resolve_handles(
        &self,
        server: Option<&str>,
    ) -> Result<Vec<&CacheHandle>, (StatusCode, String)> {
        match server {
            None => Ok(self.handles.iter().map(|(_, h)| h).collect()),
            Some(name) => {
                let matched: Vec<&CacheHandle> = self
                    .handles
                    .iter()
                    .filter(|(n, _)| n == name)
                    .map(|(_, h)| h)
                    .collect();
                if matched.is_empty() {
                    Err((
                        StatusCode::NOT_FOUND,
                        format!("No server named '{}' found", name),
                    ))
                } else {
                    Ok(matched)
                }
            }
        }
    }

    /// Like `resolve_handles`, but for snapshot operations:
    /// - When a specific server is named, return it even if it's in Dynamic mode
    ///   (the operation will then fail with BAD_REQUEST from the handle itself).
    /// - When broadcasting (no server specified), silently skip Dynamic-mode
    ///   servers that don't support snapshots.
    fn resolve_snapshot_handles(
        &self,
        server: Option<&str>,
    ) -> Result<Vec<&CacheHandle>, (StatusCode, String)> {
        match server {
            None => {
                let handles: Vec<&CacheHandle> = self
                    .handles
                    .iter()
                    .filter(|(_, h)| h.is_snapshot_capable())
                    .map(|(_, h)| h)
                    .collect();
                if handles.is_empty() {
                    return Err((
                        StatusCode::BAD_REQUEST,
                        "No servers running in PreGenerate mode — snapshot operations are not available".to_string(),
                    ));
                }
                Ok(handles)
            }
            Some(name) => {
                let matched: Vec<&CacheHandle> = self
                    .handles
                    .iter()
                    .filter(|(n, _)| n == name)
                    .map(|(_, h)| h)
                    .collect();
                if matched.is_empty() {
                    Err((
                        StatusCode::NOT_FOUND,
                        format!("No server named '{}' found", name),
                    ))
                } else {
                    Ok(matched)
                }
            }
        }
    }
}

#[derive(Deserialize)]
struct PatternBody {
    pattern: String,
    /// Optional: only invalidate this named server's cache.
    server: Option<String>,
}

#[derive(Deserialize)]
struct PathBody {
    path: String,
    /// Optional: only operate on this named server.
    /// When omitted, the operation is broadcast to all servers.
    server: Option<String>,
}

#[derive(Deserialize)]
struct BulkPatternBody {
    patterns: Vec<String>,
    /// Optional: only invalidate this named server's cache.
    server: Option<String>,
}

#[derive(Deserialize)]
struct BulkPathBody {
    paths: Vec<String>,
    /// Optional: only operate on this named server.
    /// When omitted, the operation is broadcast to all servers.
    server: Option<String>,
}

#[derive(Serialize)]
struct BulkOperationItemResult {
    item: String,
    success: bool,
    error: Option<String>,
}

#[derive(Serialize)]
struct BulkOperationResponse {
    operation: &'static str,
    server: Option<String>,
    requested: usize,
    succeeded: usize,
    failed: usize,
    results: Vec<BulkOperationItemResult>,
}

#[derive(Clone, Copy)]
enum BulkSnapshotAction {
    Add,
    Refresh,
    Remove,
}

/// Returns `Err(UNAUTHORIZED)` when the request lacks a valid Bearer token.
fn check_auth(state: &ControlState, headers: &HeaderMap) -> Result<(), StatusCode> {
    if let Some(required_token) = &state.auth_token {
        let auth_header = headers
            .get(header::AUTHORIZATION)
            .and_then(|h| h.to_str().ok());
        let expected = format!("Bearer {}", required_token);
        if auth_header != Some(expected.as_str()) {
            tracing::warn!("Unauthorized control endpoint attempt");
            return Err(StatusCode::UNAUTHORIZED);
        }
    }
    Ok(())
}

fn validate_bulk_items<T>(items: &[T], field_name: &str) -> Result<(), (StatusCode, String)> {
    if items.is_empty() {
        return Err((
            StatusCode::BAD_REQUEST,
            format!("'{}' must contain at least one item", field_name),
        ));
    }
    Ok(())
}

fn bulk_response(
    operation: &'static str,
    server: Option<String>,
    results: Vec<BulkOperationItemResult>,
) -> (StatusCode, Json<BulkOperationResponse>) {
    let requested = results.len();
    let succeeded = results.iter().filter(|result| result.success).count();
    let failed = requested - succeeded;

    (
        StatusCode::OK,
        Json(BulkOperationResponse {
            operation,
            server,
            requested,
            succeeded,
            failed,
            results,
        }),
    )
}

async fn run_bulk_snapshot_operation(
    handles: Vec<&CacheHandle>,
    paths: &[String],
    action: BulkSnapshotAction,
) -> Vec<BulkOperationItemResult> {
    let handles: Arc<Vec<CacheHandle>> = Arc::new(handles.into_iter().cloned().collect());
    let tasks: Vec<JoinHandle<BulkOperationItemResult>> = paths
        .iter()
        .cloned()
        .map(|path| {
            let handles = Arc::clone(&handles);
            tokio::spawn(async move {
                let error = run_snapshot_operation_for_path(handles.as_ref(), &path, action).await;

                BulkOperationItemResult {
                    item: path,
                    success: error.is_none(),
                    error,
                }
            })
        })
        .collect();

    let mut results = Vec::with_capacity(tasks.len());

    for task in tasks {
        match task.await {
            Ok(result) => results.push(result),
            Err(err) => {
                tracing::error!("bulk snapshot task failed: {}", err);
                results.push(BulkOperationItemResult {
                    item: "<unknown>".to_string(),
                    success: false,
                    error: Some("bulk snapshot task failed".to_string()),
                });
            }
        }
    }

    results
}

async fn run_snapshot_operation_for_path(
    handles: &[CacheHandle],
    path: &str,
    action: BulkSnapshotAction,
) -> Option<String> {
    for handle in handles {
        let outcome = match action {
            BulkSnapshotAction::Add => handle.add_snapshot(path).await,
            BulkSnapshotAction::Refresh => handle.refresh_snapshot(path).await,
            BulkSnapshotAction::Remove => handle.remove_snapshot(path).await,
        };

        if let Err(err) = outcome {
            return Some(err.to_string());
        }
    }

    None
}

/// POST /invalidate_all — invalidate every cached entry across all servers.
async fn invalidate_all_handler(
    State(state): State<Arc<ControlState>>,
    headers: HeaderMap,
) -> Result<impl IntoResponse, StatusCode> {
    check_auth(&state, &headers)?;

    for (_, handle) in &state.handles {
        handle.invalidate_all();
    }
    tracing::info!(
        "invalidate_all triggered via control endpoint ({} server(s))",
        state.handles.len()
    );
    Ok((StatusCode::OK, "Cache invalidated"))
}

/// POST /invalidate — invalidate entries matching a wildcard pattern.
///
/// Body: `{ "pattern": "/api/*" }` or `{ "pattern": "/api/*", "server": "frontend" }`
async fn invalidate_handler(
    State(state): State<Arc<ControlState>>,
    headers: HeaderMap,
    Json(body): Json<PatternBody>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    check_auth(&state, &headers).map_err(|s| (s, String::new()))?;

    let handles = state.resolve_handles(body.server.as_deref())?;
    for handle in handles {
        handle.invalidate(&body.pattern);
    }
    tracing::info!(
        "invalidate('{}') triggered via control endpoint (server={:?})",
        body.pattern,
        body.server
    );
    Ok((StatusCode::OK, "Pattern invalidation triggered".to_string()))
}

/// POST /bulk_invalidate — invalidate entries matching multiple wildcard patterns.
///
/// Body: `{ "patterns": ["/api/*", "/blog/*"], "server": "frontend" }`
/// or `{ "patterns": ["/api/*", "/blog/*"] }`
async fn bulk_invalidate_handler(
    State(state): State<Arc<ControlState>>,
    headers: HeaderMap,
    Json(body): Json<BulkPatternBody>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    check_auth(&state, &headers).map_err(|s| (s, String::new()))?;
    validate_bulk_items(&body.patterns, "patterns")?;

    let handles = state.resolve_handles(body.server.as_deref())?;
    let mut results = Vec::with_capacity(body.patterns.len());

    for pattern in &body.patterns {
        for handle in &handles {
            handle.invalidate(pattern);
        }

        results.push(BulkOperationItemResult {
            item: pattern.clone(),
            success: true,
            error: None,
        });
    }

    tracing::info!(
        "bulk_invalidate(count={}) triggered via control endpoint (server={:?})",
        body.patterns.len(),
        body.server
    );

    Ok(bulk_response("bulk_invalidate", body.server, results))
}

/// POST /add_snapshot — fetch a path from upstream, cache it, and track it.
///
/// Only available when the proxy is running in `PreGenerate` mode.
/// Body: `{ "path": "/about" }` or `{ "path": "/about", "server": "frontend" }`
async fn add_snapshot_handler(
    State(state): State<Arc<ControlState>>,
    headers: HeaderMap,
    Json(body): Json<PathBody>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    check_auth(&state, &headers).map_err(|s| (s, String::new()))?;

    let handles = state.resolve_snapshot_handles(body.server.as_deref())?;
    for handle in handles {
        handle
            .add_snapshot(&body.path)
            .await
            .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
    }
    tracing::info!(
        "add_snapshot('{}') triggered via control endpoint (server={:?})",
        body.path,
        body.server
    );
    Ok((StatusCode::OK, "Snapshot added".to_string()))
}

/// POST /bulk_add_snapshot — fetch multiple paths from upstream, cache them, and track them.
///
/// Only available when the proxy is running in `PreGenerate` mode.
/// Body: `{ "paths": ["/about", "/pricing"], "server": "frontend" }`
/// or `{ "paths": ["/about", "/pricing"] }`
async fn bulk_add_snapshot_handler(
    State(state): State<Arc<ControlState>>,
    headers: HeaderMap,
    Json(body): Json<BulkPathBody>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    check_auth(&state, &headers).map_err(|s| (s, String::new()))?;
    validate_bulk_items(&body.paths, "paths")?;

    let handles = state.resolve_snapshot_handles(body.server.as_deref())?;
    let results = run_bulk_snapshot_operation(handles, &body.paths, BulkSnapshotAction::Add).await;

    tracing::info!(
        "bulk_add_snapshot(count={}) triggered via control endpoint (server={:?})",
        body.paths.len(),
        body.server
    );

    Ok(bulk_response("bulk_add_snapshot", body.server, results))
}

/// POST /refresh_snapshot — re-fetch a cached snapshot path from upstream.
///
/// Only available when the proxy is running in `PreGenerate` mode.
/// Body: `{ "path": "/about" }` or `{ "path": "/about", "server": "frontend" }`
async fn refresh_snapshot_handler(
    State(state): State<Arc<ControlState>>,
    headers: HeaderMap,
    Json(body): Json<PathBody>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    check_auth(&state, &headers).map_err(|s| (s, String::new()))?;

    let handles = state.resolve_snapshot_handles(body.server.as_deref())?;
    for handle in handles {
        handle
            .refresh_snapshot(&body.path)
            .await
            .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
    }
    tracing::info!(
        "refresh_snapshot('{}') triggered via control endpoint (server={:?})",
        body.path,
        body.server
    );
    Ok((StatusCode::OK, "Snapshot refreshed".to_string()))
}

/// POST /bulk_refresh_snapshot — re-fetch multiple cached snapshot paths from upstream.
///
/// Only available when the proxy is running in `PreGenerate` mode.
/// Body: `{ "paths": ["/about", "/pricing"], "server": "frontend" }`
/// or `{ "paths": ["/about", "/pricing"] }`
async fn bulk_refresh_snapshot_handler(
    State(state): State<Arc<ControlState>>,
    headers: HeaderMap,
    Json(body): Json<BulkPathBody>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    check_auth(&state, &headers).map_err(|s| (s, String::new()))?;
    validate_bulk_items(&body.paths, "paths")?;

    let handles = state.resolve_snapshot_handles(body.server.as_deref())?;
    let results =
        run_bulk_snapshot_operation(handles, &body.paths, BulkSnapshotAction::Refresh).await;

    tracing::info!(
        "bulk_refresh_snapshot(count={}) triggered via control endpoint (server={:?})",
        body.paths.len(),
        body.server
    );

    Ok(bulk_response("bulk_refresh_snapshot", body.server, results))
}

/// POST /remove_snapshot — remove a path from the cache and snapshot list.
///
/// Only available when the proxy is running in `PreGenerate` mode.
/// Body: `{ "path": "/about" }` or `{ "path": "/about", "server": "frontend" }`
async fn remove_snapshot_handler(
    State(state): State<Arc<ControlState>>,
    headers: HeaderMap,
    Json(body): Json<PathBody>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    check_auth(&state, &headers).map_err(|s| (s, String::new()))?;

    let handles = state.resolve_snapshot_handles(body.server.as_deref())?;
    for handle in handles {
        handle
            .remove_snapshot(&body.path)
            .await
            .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
    }
    tracing::info!(
        "remove_snapshot('{}') triggered via control endpoint (server={:?})",
        body.path,
        body.server
    );
    Ok((StatusCode::OK, "Snapshot removed".to_string()))
}

/// POST /bulk_remove_snapshot — remove multiple paths from the cache and snapshot list.
///
/// Only available when the proxy is running in `PreGenerate` mode.
/// Body: `{ "paths": ["/about", "/pricing"], "server": "frontend" }`
/// or `{ "paths": ["/about", "/pricing"] }`
async fn bulk_remove_snapshot_handler(
    State(state): State<Arc<ControlState>>,
    headers: HeaderMap,
    Json(body): Json<BulkPathBody>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    check_auth(&state, &headers).map_err(|s| (s, String::new()))?;
    validate_bulk_items(&body.paths, "paths")?;

    let handles = state.resolve_snapshot_handles(body.server.as_deref())?;
    let results =
        run_bulk_snapshot_operation(handles, &body.paths, BulkSnapshotAction::Remove).await;

    tracing::info!(
        "bulk_remove_snapshot(count={}) triggered via control endpoint (server={:?})",
        body.paths.len(),
        body.server
    );

    Ok(bulk_response("bulk_remove_snapshot", body.server, results))
}

/// POST /refresh_all_snapshots — re-fetch every tracked snapshot from upstream.
///
/// Only available when the proxy is running in `PreGenerate` mode.
/// Optional body: `{ "server": "frontend" }` to target a specific server.
async fn refresh_all_snapshots_handler(
    State(state): State<Arc<ControlState>>,
    headers: HeaderMap,
    body: Option<Json<serde_json::Value>>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    check_auth(&state, &headers).map_err(|s| (s, String::new()))?;

    let server_filter = body
        .as_ref()
        .and_then(|Json(v)| v.get("server"))
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let handles = state.resolve_snapshot_handles(server_filter.as_deref())?;
    for handle in handles {
        handle
            .refresh_all_snapshots()
            .await
            .map_err(|e| (StatusCode::BAD_REQUEST, e.to_string()))?;
    }
    tracing::info!(
        "refresh_all_snapshots triggered via control endpoint (server={:?})",
        server_filter
    );
    Ok((StatusCode::OK, "All snapshots refreshed".to_string()))
}

/// Create the control server router.
///
/// `handles` contains one `(server_name, CacheHandle)` pair per named proxy server.
pub fn create_control_router(
    handles: Vec<(String, CacheHandle)>,
    auth_token: Option<String>,
) -> Router {
    let state = Arc::new(ControlState::new(handles, auth_token));

    Router::new()
        .route("/invalidate_all", post(invalidate_all_handler))
        .route("/invalidate", post(invalidate_handler))
        .route("/bulk_invalidate", post(bulk_invalidate_handler))
        .route("/add_snapshot", post(add_snapshot_handler))
        .route("/bulk_add_snapshot", post(bulk_add_snapshot_handler))
        .route("/refresh_snapshot", post(refresh_snapshot_handler))
        .route(
            "/bulk_refresh_snapshot",
            post(bulk_refresh_snapshot_handler),
        )
        .route("/remove_snapshot", post(remove_snapshot_handler))
        .route("/bulk_remove_snapshot", post(bulk_remove_snapshot_handler))
        .route(
            "/refresh_all_snapshots",
            post(refresh_all_snapshots_handler),
        )
        .with_state(state)
}