harn-serve 0.8.132

Shared outbound workflow server core for Harn adapters
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
//! Axum router exposing the session-store primitive at `/v1/sessions`.
//!
//! Hosted alongside the existing api/a2a/mcp adapters. The router is
//! pure axum so callers can compose it with their own auth/observability
//! middleware before mounting.

use std::sync::Arc;

use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::response::IntoResponse;
use axum::routing::{delete, get, post};
use axum::{Json, Router};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};

use super::event::{AppendEvent, EventId, EventSignature, SessionEventKind};
use super::store::{
    CreateSession, ListFilter, ReadRange, SessionId, SessionMeta, SessionStatus, SessionStore,
    SharedSessionStore, SnapshotId, StoreError,
};

/// Build an unprefixed router. Callers nest it under whichever prefix
/// fits their deployment (e.g. `Router::new().nest("/v1/session-store",
/// sessions_router(store))`). The store is shared via `Arc` and cloned
/// cheaply per request.
pub fn sessions_router(store: SharedSessionStore) -> Router {
    Router::new()
        .route("/sessions", post(create_session).get(list_sessions))
        .route(
            "/sessions/{id}",
            get(describe_session).delete(soft_delete_session),
        )
        .route("/sessions/{id}/view", get(session_view))
        .route("/sessions/{id}/events", post(append_event).get(read_events))
        .route("/sessions/{id}/fork", post(fork_session))
        .route("/sessions/{id}/truncate", post(truncate_session))
        .route("/sessions/{id}/snapshot", post(snapshot_session))
        .route("/snapshots/{snapshot_id}/replay", post(replay_snapshot))
        .route("/sessions/{id}/close", post(close_session))
        .route("/sessions/{id}/verify", get(verify_session))
        .route("/sessions/{id}/hard_delete", delete(hard_delete_session))
        .with_state(SessionsState { store })
}

#[derive(Clone)]
struct SessionsState {
    store: Arc<dyn SessionStore>,
}

#[derive(Debug, Deserialize)]
struct AppendRequest {
    kind: SessionEventKind,
    #[serde(default)]
    payload: Value,
    #[serde(default)]
    parent_event_id: Option<EventId>,
    #[serde(default)]
    actor: Option<String>,
    #[serde(default)]
    tags: Vec<String>,
    #[serde(default)]
    headers: std::collections::BTreeMap<String, String>,
}

#[derive(Debug, Deserialize)]
struct ForkRequest {
    at_event_id: EventId,
    #[serde(default)]
    child_session_id: Option<SessionId>,
}

#[derive(Debug, Deserialize)]
struct TruncateRequest {
    at_event_id: EventId,
}

#[derive(Debug, Serialize)]
struct ErrorBody {
    error: ErrorBodyInner,
}

#[derive(Debug, Serialize)]
struct ErrorBodyInner {
    code: &'static str,
    message: String,
}

fn map_error(error: StoreError) -> (StatusCode, Json<ErrorBody>) {
    let (status, code) = match &error {
        StoreError::NotFound(_) => (StatusCode::NOT_FOUND, "not_found"),
        StoreError::AlreadyExists(_) => (StatusCode::CONFLICT, "already_exists"),
        StoreError::Conflict(_) => (StatusCode::CONFLICT, "conflict"),
        StoreError::InvalidInput(_) => (StatusCode::BAD_REQUEST, "invalid_input"),
        StoreError::Tenant(_) => (StatusCode::FORBIDDEN, "tenant"),
        StoreError::Backend(_) => (StatusCode::INTERNAL_SERVER_ERROR, "backend_error"),
    };
    (
        status,
        Json(ErrorBody {
            error: ErrorBodyInner {
                code,
                message: error.to_string(),
            },
        }),
    )
}

// Span names and attribute keys follow the published `harn.session.*`
// vocabulary so session-store telemetry can flow through any A.10 backend.
#[tracing::instrument(
    name = "harn.session.create",
    skip_all,
    fields(
        harn.session.tenant_id = payload.tenant_id.as_deref().unwrap_or(""),
        harn.session.persona = payload.persona.as_deref().unwrap_or(""),
    ),
)]
async fn create_session(
    State(state): State<SessionsState>,
    Json(payload): Json<CreateSession>,
) -> impl IntoResponse {
    match state.store.create(payload).await {
        Ok(meta) => (StatusCode::CREATED, Json(json!(meta))).into_response(),
        Err(error) => map_error(error).into_response(),
    }
}

#[tracing::instrument(
    name = "harn.session.list",
    skip_all,
    fields(
        harn.session.tenant_id = filter.tenant_id.as_deref().unwrap_or(""),
    ),
)]
async fn list_sessions(
    State(state): State<SessionsState>,
    Query(filter): Query<ListFilter>,
) -> impl IntoResponse {
    match state.store.list(filter).await {
        Ok(metas) => (
            StatusCode::OK,
            Json(json!({
                "object": "list",
                "data": metas,
            })),
        )
            .into_response(),
        Err(error) => map_error(error).into_response(),
    }
}

#[tracing::instrument(
    name = "harn.session.describe",
    skip_all,
    fields(harn.session.id = %id),
)]
async fn describe_session(
    State(state): State<SessionsState>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    match state.store.describe(&id).await {
        Ok(meta) => (StatusCode::OK, Json(json!(meta))).into_response(),
        Err(error) => map_error(error).into_response(),
    }
}

#[tracing::instrument(
    name = "harn.session.view",
    skip_all,
    fields(harn.session.id = %id),
)]
async fn session_view(
    State(state): State<SessionsState>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    match state.store.describe(&id).await {
        Ok(meta) => {
            let view = session_view_from_meta(&meta);
            (StatusCode::OK, Json(json!(view))).into_response()
        }
        Err(error) => map_error(error).into_response(),
    }
}

#[tracing::instrument(
    name = "harn.session.soft_delete",
    skip_all,
    fields(harn.session.id = %id),
)]
async fn soft_delete_session(
    State(state): State<SessionsState>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    match state.store.soft_delete(&id).await {
        Ok(meta) => (StatusCode::OK, Json(json!(meta))).into_response(),
        Err(error) => map_error(error).into_response(),
    }
}

#[tracing::instrument(
    name = "harn.session.hard_delete",
    skip_all,
    fields(harn.session.id = %id),
)]
async fn hard_delete_session(
    State(state): State<SessionsState>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    match state.store.hard_delete(&id).await {
        Ok(()) => StatusCode::NO_CONTENT.into_response(),
        Err(error) => map_error(error).into_response(),
    }
}

#[tracing::instrument(
    name = "harn.session.append",
    skip_all,
    fields(
        harn.session.id = %id,
        harn.session.event_kind = body.kind.discriminator(),
        harn.session.signed = tracing::field::Empty,
        harn.session.signature_key_id = tracing::field::Empty,
        harn.session.signature_algorithm = tracing::field::Empty,
    ),
)]
async fn append_event(
    State(state): State<SessionsState>,
    Path(id): Path<String>,
    Json(body): Json<AppendRequest>,
) -> impl IntoResponse {
    let event = AppendEvent {
        kind: body.kind,
        payload: body.payload,
        parent_event_id: body.parent_event_id,
        actor: body.actor,
        tags: body.tags,
        headers: body.headers,
    };
    match state.store.append(&id, event).await {
        Ok(stored) => {
            record_signature_fields(
                stored.signed_by.as_ref(),
                "harn.session.signed",
                "harn.session.signature_key_id",
                "harn.session.signature_algorithm",
            );
            (StatusCode::CREATED, Json(json!(stored))).into_response()
        }
        Err(error) => map_error(error).into_response(),
    }
}

#[tracing::instrument(
    name = "harn.session.read",
    skip_all,
    fields(harn.session.id = %id),
)]
async fn read_events(
    State(state): State<SessionsState>,
    Path(id): Path<String>,
    Query(range): Query<ReadRange>,
) -> impl IntoResponse {
    match state.store.read(&id, range).await {
        Ok(page) => (
            StatusCode::OK,
            Json(json!({
                "object": "list",
                "data": page.events,
                "next_cursor": page.next_cursor,
            })),
        )
            .into_response(),
        Err(error) => map_error(error).into_response(),
    }
}

fn session_view_from_meta(meta: &SessionMeta) -> harn_vm::orchestration::SessionView {
    harn_vm::orchestration::build_session_view_from_run_views(
        Vec::new(),
        harn_vm::orchestration::SessionViewOptions {
            session_id: Some(meta.id.clone()),
            parent_session_id: meta.parent_session_id.clone(),
            status: Some(session_status_string(meta.status)),
            started_at: Some(meta.created_at.clone()),
            updated_at: Some(meta.updated_at.clone()),
            last_event_id: meta.last_event_id,
            chain_root_hash: meta.chain_root_hash.clone(),
            event_count: meta.event_count,
            has_event_log: true,
            ..harn_vm::orchestration::SessionViewOptions::default()
        },
    )
}

fn session_status_string(status: SessionStatus) -> String {
    match status {
        SessionStatus::Open => "open",
        SessionStatus::Closed => "closed",
        SessionStatus::SoftDeleted => "soft_deleted",
        SessionStatus::HardDeleted => "hard_deleted",
    }
    .to_string()
}

#[tracing::instrument(
    name = "harn.session.fork",
    skip_all,
    fields(
        harn.session.id = %id,
        harn.session.fork_at_event_id = body.at_event_id,
    ),
)]
async fn fork_session(
    State(state): State<SessionsState>,
    Path(id): Path<String>,
    Json(body): Json<ForkRequest>,
) -> impl IntoResponse {
    match state
        .store
        .fork(&id, body.at_event_id, body.child_session_id)
        .await
    {
        Ok(result) => (StatusCode::CREATED, Json(json!(result))).into_response(),
        Err(error) => map_error(error).into_response(),
    }
}

#[tracing::instrument(
    name = "harn.session.truncate",
    skip_all,
    fields(
        harn.session.id = %id,
        harn.session.truncate_at_event_id = body.at_event_id,
    ),
)]
async fn truncate_session(
    State(state): State<SessionsState>,
    Path(id): Path<String>,
    Json(body): Json<TruncateRequest>,
) -> impl IntoResponse {
    match state.store.truncate(&id, body.at_event_id).await {
        Ok(result) => (StatusCode::OK, Json(json!(result))).into_response(),
        Err(error) => map_error(error).into_response(),
    }
}

#[tracing::instrument(
    name = "harn.session.snapshot",
    skip_all,
    fields(harn.session.id = %id),
)]
async fn snapshot_session(
    State(state): State<SessionsState>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    match state.store.snapshot(&id).await {
        Ok(snapshot) => (StatusCode::CREATED, Json(json!(snapshot))).into_response(),
        Err(error) => map_error(error).into_response(),
    }
}

#[tracing::instrument(
    name = "harn.session.replay",
    skip_all,
    fields(harn.session.snapshot_id = %snapshot_id),
)]
async fn replay_snapshot(
    State(state): State<SessionsState>,
    Path(snapshot_id): Path<String>,
) -> impl IntoResponse {
    match state.store.replay(&SnapshotId(snapshot_id)).await {
        Ok(snapshot) => (StatusCode::OK, Json(json!(snapshot))).into_response(),
        Err(error) => map_error(error).into_response(),
    }
}

#[tracing::instrument(
    name = "harn.session.close",
    skip_all,
    fields(
        harn.session.id = %id,
        harn.session.receipt_signed = tracing::field::Empty,
        harn.session.receipt_signature_key_id = tracing::field::Empty,
        harn.session.receipt_signature_algorithm = tracing::field::Empty,
    ),
)]
async fn close_session(
    State(state): State<SessionsState>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    match state.store.close(&id).await {
        Ok(receipt) => {
            record_signature_fields(
                receipt.signed_by.as_ref(),
                "harn.session.receipt_signed",
                "harn.session.receipt_signature_key_id",
                "harn.session.receipt_signature_algorithm",
            );
            (StatusCode::OK, Json(json!(receipt))).into_response()
        }
        Err(error) => map_error(error).into_response(),
    }
}

#[tracing::instrument(
    name = "harn.session.verify",
    skip_all,
    fields(harn.session.id = %id),
)]
async fn verify_session(
    State(state): State<SessionsState>,
    Path(id): Path<String>,
) -> impl IntoResponse {
    match state.store.verify(&id).await {
        Ok(report) => (StatusCode::OK, Json(json!(report))).into_response(),
        Err(error) => map_error(error).into_response(),
    }
}

fn record_signature_fields(
    signed_by: Option<&EventSignature>,
    signed_field: &'static str,
    key_id_field: &'static str,
    algorithm_field: &'static str,
) {
    let span = tracing::Span::current();
    match signed_by {
        Some(signature) => {
            span.record(signed_field, true);
            span.record(key_id_field, signature.key_id.as_str());
            span.record(algorithm_field, signature.algorithm.as_str());
        }
        None => {
            span.record(signed_field, false);
        }
    }
}