elastik-core 8.0.1

Elastik — Audi-ted L5 storage engine. SQLite for files.
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
//! Per-verb handlers driven by the FSM pipeline.
//!
//! `handler::execute(verb, ...)` is called from `pipeline::run` after
//! the driver has handled authentication, path canonicalization /
//! validation, and method-to-verb dispatch. Each `execute_*` function:
//!
//! 1. Runs its verb-specific authorization gate (`can_read` /
//!    `can_write` / `can_delete`). Authentication is the driver's
//!    job; authorization lives next to the verb because the gate is
//!    verb-and-path-specific.
//! 2. Performs the verb's actual work -- including, for write verbs,
//!    the lock acquire / preconditions / SQLite write+audit append /
//!    counter update / notify sequence. The verb owns audit + notify
//!    ordering; the FSM only models the request envelope.
//! 3. Returns either `Phase::ExecutedRead(Response)` (GET / HEAD),
//!    `Phase::CommittedWrite(Response)` (PUT / POST / DELETE), or
//!    `Phase::Error { resp, reason }`.
//!
//! Verb handlers call `trace.emit_aux(...)` and
//! `trace.emit_aux_kv(...)` to surface sub-step timings: `lock_acquired`,
//! `quota_check used=N quota=M`, `sqlite_committed etag=...`,
//! `notify_sent`. DELETE additionally emits the
//! `audit_intent` / `audit_commit` / `audit_commit_failed[_event_failed]`
//! sequence so an operator reading `grep req-N` can reconstruct the
//! intent / commit dance -- including the honest double-failure case
//! where the commit append AND the subsequent failure-event append
//! both fail (e.g. persistent DiskFull).
//!
//! ## CoAP coexistence
//!
//! HTTP and CoAP do not share the request lifecycle, but both now call public
//! Engine methods. Each adapter keeps owning its wire rendering.

#[path = "handler/delete.rs"]
mod delete;
#[path = "handler/post.rs"]
mod post;
pub(crate) use delete::execute_delete;
pub(crate) use post::execute_post;

use axum::{
    body::Bytes,
    http::{header, HeaderMap, HeaderValue, StatusCode},
    response::IntoResponse,
};
use std::sync::Arc;

#[cfg(test)]
use crate::Core;
use crate::{
    content_range_value, decimal_header_value,
    engine::{Engine, EngineError},
    engine_trace::EngineWriteTraceHooks,
    engine_types::{AccessTier, Representation, ValidatedWorldPath, WriteKind},
    http_semantics as hs,
    http_semantics::HeaderAllowlist,
    insufficient_storage, not_found, payload_too_large, precondition_failed,
    server::ServerState,
    server_error, storage_quota_exceeded, storage_temporarily_unavailable, to_header_map,
    unauthorized, ErrorReason, Phase, TraceCtx, Verb,
};

pub(crate) trait HandlerEngineState {
    fn engine(&self) -> Engine;
    fn persist_header_allowlist(&self) -> Arc<HeaderAllowlist>;
    fn persist_header_user_deny(&self) -> Arc<HeaderAllowlist>;
}

impl HandlerEngineState for &ServerState {
    fn engine(&self) -> Engine {
        ServerState::engine(self).clone()
    }

    fn persist_header_allowlist(&self) -> Arc<HeaderAllowlist> {
        ServerState::persist_header_allowlist(self)
    }

    fn persist_header_user_deny(&self) -> Arc<HeaderAllowlist> {
        ServerState::persist_header_user_deny(self)
    }
}

#[cfg(test)]
impl HandlerEngineState for &Arc<Core> {
    fn engine(&self) -> Engine {
        Engine::from_core_for_tests((*self).clone())
    }

    fn persist_header_allowlist(&self) -> Arc<HeaderAllowlist> {
        // Legacy white-box tests that pass Core directly use the default HTTP
        // adapter policy. Tests for custom policy should construct ServerState.
        Arc::new(HeaderAllowlist::empty())
    }

    fn persist_header_user_deny(&self) -> Arc<HeaderAllowlist> {
        Arc::new(HeaderAllowlist::empty())
    }
}

#[cfg(test)]
impl HandlerEngineState for &Core {
    fn engine(&self) -> Engine {
        Engine::from_core_for_tests(Arc::new((*self).clone()))
    }

    fn persist_header_allowlist(&self) -> Arc<HeaderAllowlist> {
        // Legacy white-box tests that pass Core directly use the default HTTP
        // adapter policy. Tests for custom policy should construct ServerState.
        Arc::new(HeaderAllowlist::empty())
    }

    fn persist_header_user_deny(&self) -> Arc<HeaderAllowlist> {
        Arc::new(HeaderAllowlist::empty())
    }
}

/// Dispatch from `Phase::Dispatched` to the verb-specific handler.
/// Called from inside `pipeline::run`'s match arm.
pub(crate) async fn execute(
    verb: Verb,
    headers: HeaderMap,
    body: Bytes,
    tier: impl Into<AccessTier>,
    world: ValidatedWorldPath,
    state: &ServerState,
    trace: &TraceCtx,
) -> Phase {
    let tier = tier.into();
    match verb {
        Verb::Get => execute_get(headers, tier, world, state, trace).await,
        Verb::Head => execute_head(headers, tier, world, state, trace).await,
        Verb::Put => execute_put(headers, body, tier, world, state, trace).await,
        Verb::Post => execute_post(headers, body, tier, world, state, trace).await,
        Verb::Delete => execute_delete(headers, tier, world, state, trace).await,
    }
}

pub(crate) async fn execute_get<S: HandlerEngineState>(
    headers: HeaderMap,
    tier: impl Into<AccessTier>,
    world: ValidatedWorldPath,
    state: S,
    trace: &TraceCtx,
) -> Phase {
    let tier = tier.into();
    let result = match state.engine().read(&world, tier) {
        Ok(Some(result)) => result,
        Ok(None) => {
            return Phase::Error {
                resp: not_found(),
                reason: ErrorReason::NotFound,
            };
        }
        Err(err) => return read_error_phase(err),
    };
    let stage = result.representation;
    let etag = result.etag;
    if hs::read_not_modified(&headers, &etag) {
        // 304: no body, but emit body_size for diagnostic clarity
        // ("the cached body would be N bytes if the client revalidated").
        trace.emit_aux_kv("body_size", &stage.body.len().to_string());
        return Phase::ExecutedRead(hs::not_modified(
            world.as_str(),
            &etag,
            &stage.content_type,
            &stage.headers,
        ));
    }
    let mut resp_headers = vec![
        (
            header::CONTENT_TYPE,
            HeaderValue::from_str(&stage.content_type)
                .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")),
        ),
        (header::ACCEPT_RANGES, HeaderValue::from_static("bytes")),
        (header::ETAG, hs::etag_header(&etag)),
    ];
    hs::apply_world_links(world.as_str(), &mut resp_headers);
    hs::apply_meta_headers(&stage.headers, &mut resp_headers);
    match hs::effective_range(&headers, stage.body.len(), &etag) {
        Ok(Some((start, end))) => {
            let chunk = stage.body[start..=end].to_vec();
            resp_headers.push((header::CONTENT_LENGTH, decimal_header_value(chunk.len())));
            resp_headers.push((
                header::CONTENT_RANGE,
                content_range_value(start, end, stage.body.len()),
            ));
            trace.emit_aux_kv("body_size", &chunk.len().to_string());
            Phase::ExecutedRead(
                (
                    StatusCode::PARTIAL_CONTENT,
                    to_header_map(resp_headers),
                    chunk,
                )
                    .into_response(),
            )
        }
        Ok(None) => {
            resp_headers.push((
                header::CONTENT_LENGTH,
                decimal_header_value(stage.body.len()),
            ));
            trace.emit_aux_kv("body_size", &stage.body.len().to_string());
            Phase::ExecutedRead(
                (StatusCode::OK, to_header_map(resp_headers), stage.body).into_response(),
            )
        }
        Err(()) => Phase::Error {
            resp: hs::range_not_satisfiable(stage.body.len()),
            reason: ErrorReason::RangeNotSatisfiable,
        },
    }
}

pub(crate) async fn execute_head<S: HandlerEngineState>(
    headers: HeaderMap,
    tier: impl Into<AccessTier>,
    world: ValidatedWorldPath,
    state: S,
    trace: &TraceCtx,
) -> Phase {
    let tier = tier.into();
    let result = match state.engine().read(&world, tier) {
        Ok(Some(result)) => result,
        Ok(None) => {
            return Phase::Error {
                resp: not_found(),
                reason: ErrorReason::NotFound,
            };
        }
        Err(err) => return read_error_phase(err),
    };
    let stage = result.representation;
    let etag = result.etag;
    if hs::read_not_modified(&headers, &etag) {
        trace.emit_aux_kv("body_size", &stage.body.len().to_string());
        return Phase::ExecutedRead(hs::not_modified(
            world.as_str(),
            &etag,
            &stage.content_type,
            &stage.headers,
        ));
    }
    let mut resp_headers = vec![
        (
            header::CONTENT_TYPE,
            HeaderValue::from_str(&stage.content_type)
                .unwrap_or_else(|_| HeaderValue::from_static("application/octet-stream")),
        ),
        (
            header::CONTENT_LENGTH,
            decimal_header_value(stage.body.len()),
        ),
        (header::ACCEPT_RANGES, HeaderValue::from_static("bytes")),
        (header::ETAG, hs::etag_header(&etag)),
    ];
    hs::apply_world_links(world.as_str(), &mut resp_headers);
    hs::apply_meta_headers(&stage.headers, &mut resp_headers);
    match hs::effective_range(&headers, stage.body.len(), &etag) {
        Ok(Some((start, end))) => {
            resp_headers.retain(|(name, _)| name != header::CONTENT_LENGTH);
            let chunk_len = end - start + 1;
            resp_headers.push((header::CONTENT_LENGTH, decimal_header_value(chunk_len)));
            resp_headers.push((
                header::CONTENT_RANGE,
                content_range_value(start, end, stage.body.len()),
            ));
            trace.emit_aux_kv("body_size", &chunk_len.to_string());
            Phase::ExecutedRead(
                (StatusCode::PARTIAL_CONTENT, to_header_map(resp_headers), "").into_response(),
            )
        }
        Ok(None) => {
            trace.emit_aux_kv("body_size", &stage.body.len().to_string());
            Phase::ExecutedRead((StatusCode::OK, to_header_map(resp_headers), "").into_response())
        }
        Err(()) => Phase::Error {
            resp: hs::range_not_satisfiable(stage.body.len()),
            reason: ErrorReason::RangeNotSatisfiable,
        },
    }
}

pub(crate) async fn execute_put<S: HandlerEngineState>(
    headers: HeaderMap,
    body: Bytes,
    tier: impl Into<AccessTier>,
    world: ValidatedWorldPath,
    state: S,
    trace: &TraceCtx,
) -> Phase {
    let tier = tier.into();
    let content_type = hs::request_content_type(&headers);
    let persist_header_allowlist = state.persist_header_allowlist();
    let persist_header_user_deny = state.persist_header_user_deny();
    let meta = hs::request_meta_headers(
        &headers,
        &persist_header_allowlist,
        &persist_header_user_deny,
    );
    let representation = Representation::new(body, content_type, meta);
    let outcome = match state
        .engine()
        .replace_traced(
            &world,
            representation,
            hs::request_preconditions(&headers),
            tier,
            &HttpWriteTrace { trace },
        )
        .await
    {
        Ok(outcome) => outcome,
        Err(err) => return write_error_phase(err),
    };
    let status = match outcome.kind {
        WriteKind::Created => StatusCode::CREATED,
        WriteKind::Updated => StatusCode::OK,
        #[cfg(not(test))]
        _ => StatusCode::OK,
    };
    let mut resp_headers = vec![(header::ETAG, hs::etag_header(&outcome.etag))];
    if status == StatusCode::CREATED {
        resp_headers.push((
            header::LOCATION,
            HeaderValue::from_str(&hs::world_url(world.as_str()))
                .unwrap_or_else(|_| HeaderValue::from_static("/")),
        ));
    }
    Phase::CommittedWrite((status, to_header_map(resp_headers), "").into_response())
}

/// First 16 chars of an etag string for compact aux trace lines.
/// Etags are HMAC-SHA256 hex (64 chars) or `sha256-<64 chars>`; a
/// 16-char prefix is enough to disambiguate while staying readable.
///
/// Crate-visible so the sibling `post.rs` module can reuse it while the
/// handler tree is temporarily compiled by both the lib tests and bin target.
/// ETag presentation remains a verb-handler concern, not a crate-wide utility.
pub(crate) fn etag_preview(etag: &str) -> String {
    etag.chars().take(16).collect()
}

pub(crate) struct HttpWriteTrace<'a> {
    pub(crate) trace: &'a TraceCtx,
}

impl EngineWriteTraceHooks for HttpWriteTrace<'_> {
    fn lock_acquired(&self) {
        self.trace.emit_aux("lock_acquired");
    }

    fn quota_check(&self, used: usize, quota: usize) {
        self.trace
            .emit_aux_kv("quota_check", &format!("used={used} quota={quota}"));
    }

    fn sqlite_committed(&self, etag: &str) {
        self.trace
            .emit_aux_kv("sqlite_committed", &format!("etag={}", etag_preview(etag)));
    }

    fn notify_sent(&self) {
        self.trace.emit_aux("notify_sent");
    }
}

fn read_error_phase(err: EngineError) -> Phase {
    match err {
        EngineError::Auth(gate) => Phase::Error {
            resp: unauthorized("read requires read token"),
            reason: ErrorReason::Auth(gate),
        },
        EngineError::TransientStorage { .. } => Phase::Error {
            resp: storage_temporarily_unavailable(),
            reason: ErrorReason::StorageRead,
        },
        EngineError::InsufficientStorage { .. } => Phase::Error {
            resp: insufficient_storage(),
            reason: ErrorReason::InsufficientStorage,
        },
        EngineError::Storage { .. } | EngineError::InternalInvariant(_) => Phase::Error {
            resp: server_error("storage failure".to_string()),
            reason: ErrorReason::StorageRead,
        },
        EngineError::ShuttingDown => Phase::Error {
            resp: storage_temporarily_unavailable(),
            reason: ErrorReason::StorageRead,
        },
        EngineError::SubscriptionLimit => Phase::Error {
            resp: server_error("unexpected read subscription limit".to_string()),
            reason: ErrorReason::StorageRead,
        },
        EngineError::InvalidWorldName
        | EngineError::NotFound
        | EngineError::AppendOnly
        | EngineError::PayloadTooLarge { .. }
        | EngineError::PreconditionFailed { .. }
        | EngineError::QuotaExceeded { .. } => Phase::Error {
            resp: server_error("unexpected read error".to_string()),
            reason: ErrorReason::StorageRead,
        },
        #[cfg(not(test))]
        _ => Phase::Error {
            resp: server_error("unknown read error".to_string()),
            reason: ErrorReason::StorageRead,
        },
    }
}

pub(crate) fn write_error_phase(err: EngineError) -> Phase {
    match err {
        EngineError::Auth(gate) => Phase::Error {
            resp: unauthorized("write requires token; system worlds need approve token"),
            reason: ErrorReason::Auth(gate),
        },
        EngineError::PayloadTooLarge { max } => Phase::Error {
            resp: payload_too_large(max),
            reason: ErrorReason::PayloadTooLarge,
        },
        EngineError::PreconditionFailed { message } => Phase::Error {
            resp: precondition_failed(message),
            reason: ErrorReason::PreconditionFailed,
        },
        EngineError::NotFound => Phase::Error {
            resp: not_found(),
            reason: ErrorReason::NotFound,
        },
        EngineError::QuotaExceeded {
            used,
            quota,
            projected,
        } => Phase::Error {
            resp: storage_quota_exceeded(used, quota, projected),
            reason: ErrorReason::QuotaExceeded,
        },
        EngineError::TransientStorage { .. } => Phase::Error {
            resp: storage_temporarily_unavailable(),
            reason: ErrorReason::StorageWriteAudit,
        },
        EngineError::InsufficientStorage { .. } => Phase::Error {
            resp: insufficient_storage(),
            reason: ErrorReason::InsufficientStorage,
        },
        EngineError::Storage { .. } => Phase::Error {
            resp: server_error("storage failure".to_string()),
            reason: ErrorReason::StorageRead,
        },
        EngineError::InternalInvariant(message) => Phase::Error {
            resp: server_error(message.to_string()),
            reason: ErrorReason::StorageWriteAudit,
        },
        EngineError::ShuttingDown => Phase::Error {
            resp: storage_temporarily_unavailable(),
            reason: ErrorReason::StorageWriteAudit,
        },
        EngineError::SubscriptionLimit => Phase::Error {
            resp: server_error("unexpected write subscription limit".to_string()),
            reason: ErrorReason::StorageWriteAudit,
        },
        EngineError::InvalidWorldName | EngineError::AppendOnly => Phase::Error {
            resp: server_error("invalid world reached write adapter".to_string()),
            reason: ErrorReason::StorageWriteAudit,
        },
        #[cfg(not(test))]
        _ => Phase::Error {
            resp: server_error("unknown write error".to_string()),
            reason: ErrorReason::StorageWriteAudit,
        },
    }
}