Dungeon: a per-timeline append-only turn log written from the play row, served paged at /api/history/{timeline}; a Retry is a new entry naming the old one
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
c58ccbe2de
commit
1fcef6499d
4 changed files with 536 additions and 1 deletions
|
|
@ -14,7 +14,7 @@ use crate::{
|
|||
};
|
||||
use axum::{
|
||||
Json, Router,
|
||||
extract::{DefaultBodyLimit, Path, State},
|
||||
extract::{DefaultBodyLimit, Path, Query, State},
|
||||
http::{HeaderMap, HeaderValue, StatusCode, header},
|
||||
response::{
|
||||
IntoResponse, Response,
|
||||
|
|
@ -49,6 +49,7 @@ pub(crate) fn router() -> Router<AppState> {
|
|||
.route("/api/play", post(play))
|
||||
.route("/api/turn/{timeline}", get(turn))
|
||||
.route("/api/turn/{timeline}/stream", get(turn_stream))
|
||||
.route("/api/history/{timeline}", get(history))
|
||||
.route("/api/auth/begin", post(auth_begin))
|
||||
.route("/api/auth/complete", post(auth_complete))
|
||||
.route("/api/auth/logout", post(auth_logout))
|
||||
|
|
@ -91,6 +92,7 @@ pub(crate) fn turn_view_json(timeline: &str, view: Option<&PlayTurnView>) -> Val
|
|||
"question": question,
|
||||
"refusal": view.refusal,
|
||||
"fault": view.fault.then_some(PLAY_FAULT_LINE),
|
||||
"text": view.player_text,
|
||||
"resolving": view.run_in_progress,
|
||||
"continue_hint": (view.state == PlayTurnState::Running && !view.run_in_progress)
|
||||
.then_some(CONTINUE_HINT),
|
||||
|
|
@ -277,6 +279,10 @@ struct PlayBody {
|
|||
/// The token of the question this text answers, as the turn view showed it.
|
||||
#[serde(default)]
|
||||
answers: Option<String>,
|
||||
/// The log entry (`seq`) this text retries. The new entry names it; the
|
||||
/// old one stays.
|
||||
#[serde(default)]
|
||||
retry_of: Option<u64>,
|
||||
}
|
||||
|
||||
async fn play(
|
||||
|
|
@ -340,6 +346,12 @@ async fn play(
|
|||
Some(question.id.clone())
|
||||
}
|
||||
};
|
||||
if let Some(seq) = body.retry_of
|
||||
&& !host.play.logged(seq).await
|
||||
{
|
||||
return refuse(StatusCode::CONFLICT, "that turn is not in the history");
|
||||
}
|
||||
let retry_of = body.retry_of;
|
||||
let admission = match host
|
||||
.play
|
||||
.admit(body.key, PlayRequest { text: body.text, answers })
|
||||
|
|
@ -361,6 +373,9 @@ async fn play(
|
|||
Admission::Replayed { .. } => return reply(StatusCode::OK, json!({"outcome": "replayed"})),
|
||||
Admission::Spawn(admitted) => admitted,
|
||||
};
|
||||
if let Some(seq) = retry_of {
|
||||
host.play.note_retry(&admitted, seq);
|
||||
}
|
||||
let _ = host.changes.send(());
|
||||
let spawned = host.clone();
|
||||
let state = state.clone();
|
||||
|
|
@ -425,6 +440,50 @@ async fn turn(
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct HistoryQuery {
|
||||
/// Read the entries older than this `seq`; the newest page when absent.
|
||||
before: Option<u64>,
|
||||
limit: Option<usize>,
|
||||
}
|
||||
|
||||
const HISTORY_PAGE: usize = 30;
|
||||
const HISTORY_PAGE_MAX: usize = 100;
|
||||
|
||||
/// The signed-in account's own turn log for one timeline, a page at a time,
|
||||
/// oldest first so the newest entry is last. `owned_host` refuses any
|
||||
/// timeline the account does not own, so another account's log is unreachable.
|
||||
async fn history(
|
||||
Path(timeline): Path<String>,
|
||||
Query(query): Query<HistoryQuery>,
|
||||
headers: HeaderMap,
|
||||
State(state): State<AppState>,
|
||||
) -> Response {
|
||||
let host = match owned_host(&headers, &state, &timeline).await {
|
||||
Ok(host) => host,
|
||||
Err(response) => return response,
|
||||
};
|
||||
let limit = query.limit.unwrap_or(HISTORY_PAGE).clamp(1, HISTORY_PAGE_MAX);
|
||||
let page = match host.play.history(query.before, limit).await {
|
||||
Ok(page) => page,
|
||||
Err(error) => {
|
||||
tracing::error!(%error, %timeline, "the turn log could not be read");
|
||||
return refuse(StatusCode::INTERNAL_SERVER_ERROR, "the turn history could not be read");
|
||||
}
|
||||
};
|
||||
let entries: Vec<Value> = page
|
||||
.entries
|
||||
.into_iter()
|
||||
.map(|(entry, superseded_by)| {
|
||||
let mut value = serde_json::to_value(entry).expect("a log entry is plain data");
|
||||
value["superseded_by"] = json!(superseded_by);
|
||||
value
|
||||
})
|
||||
.collect();
|
||||
reply(StatusCode::OK, json!({"timeline": timeline, "entries": entries, "older": page.older}))
|
||||
}
|
||||
|
||||
async fn turn_stream(
|
||||
Path(timeline): Path<String>,
|
||||
headers: HeaderMap,
|
||||
|
|
@ -935,6 +994,142 @@ mod tests {
|
|||
(status, body)
|
||||
}
|
||||
|
||||
async fn history_of(app: &App, cookie: &str, timeline: &str, query: &str) -> (StatusCode, Value) {
|
||||
let (status, _, body) = call(app, Method::GET, &format!("/api/history/{timeline}{query}"), Some(cookie), None).await;
|
||||
(status, body)
|
||||
}
|
||||
|
||||
async fn play_and_settle(app: &App, cookie: &str, timeline: &str, text: &str, answers: Option<&str>) -> Value {
|
||||
let (status, body) = play_text(app, cookie, timeline, text, answers).await;
|
||||
assert_eq!(status, StatusCode::ACCEPTED, "{body}");
|
||||
settled_turn(app, cookie, timeline).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_history_keeps_every_turn_newest_last_and_pages_backwards() {
|
||||
let mut script = vec![];
|
||||
for n in 0..3 {
|
||||
script.push(output(&format!("r{n}"), vec![call_event(&format!("c{n}"), END_TURN_TOOL, json!({}))]));
|
||||
script.push(output(&format!("p{n}"), vec![text_event(&format!("Story number {n}."))]));
|
||||
}
|
||||
let app = app(script, &["alice"]).await;
|
||||
let cookie = app.cookies[0].clone();
|
||||
let timeline = begin_one(&app, &cookie).await;
|
||||
let (_, empty) = history_of(&app, &cookie, &timeline, "").await;
|
||||
assert_eq!(empty["entries"].as_array().unwrap().len(), 0);
|
||||
let texts = [" I open the door. ", "I step in.", "I light a lamp."];
|
||||
for text in texts {
|
||||
play_and_settle(&app, &cookie, &timeline, text, None).await;
|
||||
}
|
||||
let (status, all) = history_of(&app, &cookie, &timeline, "").await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let entries = all["entries"].as_array().unwrap();
|
||||
assert_eq!(entries.len(), 3);
|
||||
for (n, entry) in entries.iter().enumerate() {
|
||||
assert_eq!(entry["seq"], n as u64 + 1, "oldest first, newest last");
|
||||
assert_eq!(entry["text"], texts[n], "the text exactly as sent");
|
||||
assert_eq!(entry["narration"], format!("Story number {n}."));
|
||||
assert_eq!(entry["status"], "committed");
|
||||
assert!(entry["world_revision"].is_u64(), "{entry}");
|
||||
assert!(entry["retry_of"].is_null() && entry["superseded_by"].is_null());
|
||||
}
|
||||
assert!(all["older"].is_null());
|
||||
let (_, newest) = history_of(&app, &cookie, &timeline, "?limit=2").await;
|
||||
let seqs: Vec<u64> = newest["entries"].as_array().unwrap().iter().map(|e| e["seq"].as_u64().unwrap()).collect();
|
||||
assert_eq!(seqs, [2, 3]);
|
||||
let (_, oldest) = history_of(&app, &cookie, &timeline, &format!("?limit=2&before={}", newest["older"])).await;
|
||||
assert_eq!(oldest["entries"].as_array().unwrap().len(), 1);
|
||||
assert_eq!(oldest["entries"][0]["text"], texts[0]);
|
||||
assert!(oldest["older"].is_null());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_question_and_its_answer_are_two_entries() {
|
||||
let script = vec![
|
||||
output("r0", vec![call_event("c0", ASK_PLAYER_TOOL, json!({"question": "Which way?"}))]),
|
||||
output("r1", vec![call_event("c1", END_TURN_TOOL, json!({}))]),
|
||||
output("proj-0", vec![text_event("You choose.")]),
|
||||
];
|
||||
let app = app(script, &["alice"]).await;
|
||||
let cookie = app.cookies[0].clone();
|
||||
let timeline = begin_one(&app, &cookie).await;
|
||||
let view = play_and_settle(&app, &cookie, &timeline, "A crossroads.", None).await;
|
||||
let token = view["turn"]["question"]["token"].as_str().unwrap().to_owned();
|
||||
play_and_settle(&app, &cookie, &timeline, "left", Some(&token)).await;
|
||||
let (_, log) = history_of(&app, &cookie, &timeline, "").await;
|
||||
let entries = log["entries"].as_array().unwrap();
|
||||
assert_eq!(entries.len(), 2, "{log}");
|
||||
assert_eq!((entries[0]["status"].as_str(), entries[0]["question"].as_str()), (Some("asked"), Some("Which way?")));
|
||||
assert_eq!(entries[0]["text"], "A crossroads.");
|
||||
assert_eq!((entries[1]["status"].as_str(), entries[1]["text"].as_str()), (Some("committed"), Some("left")));
|
||||
assert_eq!(entries[1]["narration"], "You choose.");
|
||||
assert_eq!(entries[0]["turn_id"], entries[1]["turn_id"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_retry_is_a_new_entry_and_the_faulted_one_stays_marked_superseded() {
|
||||
let app = app(vec![], &["alice"]).await;
|
||||
let cookie = app.cookies[0].clone();
|
||||
let timeline = begin_one(&app, &cookie).await;
|
||||
play_and_settle(&app, &cookie, &timeline, "I knock.", None).await;
|
||||
let (status, _, body) = call(
|
||||
&app,
|
||||
Method::POST,
|
||||
"/api/play",
|
||||
Some(&cookie),
|
||||
Some(json!({"timeline": timeline, "key": Uuid::new_v4(), "text": "x", "retry_of": 99})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::CONFLICT, "{body}");
|
||||
let (status, _, _) = call(
|
||||
&app,
|
||||
Method::POST,
|
||||
"/api/play",
|
||||
Some(&cookie),
|
||||
Some(json!({"timeline": timeline, "key": Uuid::new_v4(), "text": "I knock.", "retry_of": 1})),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::ACCEPTED);
|
||||
for _ in 0..200 {
|
||||
if history_of(&app, &cookie, &timeline, "").await.1["entries"].as_array().unwrap().len() == 2 {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
let (_, log) = history_of(&app, &cookie, &timeline, "").await;
|
||||
let entries = log["entries"].as_array().unwrap();
|
||||
assert_eq!(entries.len(), 2, "{log}");
|
||||
assert_eq!(entries[0]["status"], "faulted");
|
||||
assert_eq!(entries[0]["fault"], PLAY_FAULT_LINE);
|
||||
assert_eq!(entries[0]["superseded_by"], 2, "the old entry stays, marked");
|
||||
assert_eq!(entries[1]["retry_of"], 1);
|
||||
assert_eq!(entries[1]["text"], "I knock.");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn another_accounts_history_is_unreadable() {
|
||||
let script = vec![
|
||||
output("r0", vec![call_event("c0", END_TURN_TOOL, json!({}))]),
|
||||
output("p0", vec![text_event("A private story.")]),
|
||||
];
|
||||
let app = app(script, &["alice", "mallory"]).await;
|
||||
let (alice, mallory) = (app.cookies[0].clone(), app.cookies[1].clone());
|
||||
let timeline = begin_one(&app, &alice).await;
|
||||
play_and_settle(&app, &alice, &timeline, "A private act.", None).await;
|
||||
let (status, body) = history_of(&app, &mallory, &timeline, "").await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
assert!(!body.to_string().contains("private"), "{body}");
|
||||
let (status, _, body) = call(&app, Method::GET, &format!("/api/history/{timeline}"), None, None).await;
|
||||
assert_eq!(status, StatusCode::UNAUTHORIZED, "{body}");
|
||||
let (status, _) = history_of(&app, &alice, &timeline, "").await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
// Mallory's own timeline holds none of Alice's entries.
|
||||
let theirs = begin_one(&app, &mallory).await;
|
||||
let (status, own) = history_of(&app, &mallory, &theirs, "").await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(own["entries"].as_array().unwrap().len(), 0);
|
||||
}
|
||||
|
||||
async fn settled_turn(app: &App, cookie: &str, timeline: &str) -> Value {
|
||||
for _ in 0..200 {
|
||||
let (_, _, view) = call(app, Method::GET, &format!("/api/turn/{timeline}"), Some(cookie), None).await;
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ mod runtime;
|
|||
mod session_refresh;
|
||||
mod state_layout;
|
||||
mod timelines;
|
||||
mod turn_log;
|
||||
mod vaults;
|
||||
|
||||
use anyhow::bail;
|
||||
|
|
|
|||
|
|
@ -59,6 +59,8 @@ use serde_json::Value;
|
|||
use sha2::{Digest, Sha256};
|
||||
use tokio::sync::{Mutex, Semaphore};
|
||||
|
||||
use crate::turn_log::{NewEntry, Page as TurnPage, TurnLog, TurnStatus};
|
||||
|
||||
const STORE_TYPE: &str = "ghostlight.play_turn_store.v1";
|
||||
/// PA.f172 bumped this from v1 to v2 when `question_surface_version` was
|
||||
/// added to `PlayTurn` without `#[serde(default)]`. PA.f170 (Cut 13) bumps it
|
||||
|
|
@ -1263,6 +1265,9 @@ pub(crate) struct PlayTurnView {
|
|||
/// detail stays in the stored row and the log; the card shows a fixed
|
||||
/// player-safe line, never the detail (invariant 8, PA.f187).
|
||||
pub(crate) fault: bool,
|
||||
/// What the player sent for the submission now running or last run: the
|
||||
/// text the page shows while the turn is in flight, from any device.
|
||||
pub(crate) player_text: Option<String>,
|
||||
}
|
||||
|
||||
/// One outcome of executing a round's already-decided tool calls.
|
||||
|
|
@ -1298,6 +1303,13 @@ pub(crate) struct PlayTable {
|
|||
/// itself.
|
||||
permits: Arc<Semaphore>,
|
||||
store: Mutex<PlayTurnStore>,
|
||||
/// What the player was shown, turn by turn (`turn_log`): written from the
|
||||
/// row in `persist`, right after the row commits, and never edited.
|
||||
log: Mutex<TurnLog>,
|
||||
/// The entry the turn just admitted retries, until that turn's entry is
|
||||
/// written. Held in memory only: a restart before the entry lands loses
|
||||
/// the link, never the entry.
|
||||
pending_retry: std::sync::Mutex<Option<(String, u64)>>,
|
||||
/// PA.f186/PA.f193-E: the store's own on-disk path, kept beside `store`
|
||||
/// so `retired_row_sidecar` can scan for sidecars without taking
|
||||
/// `store`'s lock. Not the fact of a retirement itself — that is derived
|
||||
|
|
@ -1356,6 +1368,7 @@ impl PlayTable {
|
|||
let play = PlayPort::new(world.clone());
|
||||
let store_path = store_path.as_ref().to_path_buf();
|
||||
let store = PlayTurnStore::open(&store_path)?;
|
||||
let log = TurnLog::open(store_path.with_file_name("turn-log-v1.cc"))?;
|
||||
Ok(Self {
|
||||
play,
|
||||
world,
|
||||
|
|
@ -1364,6 +1377,8 @@ impl PlayTable {
|
|||
model,
|
||||
permits,
|
||||
store: Mutex::new(store),
|
||||
log: Mutex::new(log),
|
||||
pending_retry: std::sync::Mutex::new(None),
|
||||
store_path,
|
||||
run_lock: Arc::new(Mutex::new(())),
|
||||
poisoned: AtomicBool::new(false),
|
||||
|
|
@ -1709,6 +1724,7 @@ impl PlayTable {
|
|||
revision: store.state.revision,
|
||||
run_in_progress,
|
||||
fault: turn.fault.is_some(),
|
||||
player_text: turn.player_prose.last().cloned(),
|
||||
})
|
||||
}
|
||||
|
||||
|
|
@ -2323,9 +2339,84 @@ impl PlayTable {
|
|||
/// resume.
|
||||
async fn persist(&self, turn: &PlayTurn) -> Result<(), PlayError> {
|
||||
self.store.lock().await.commit(turn.clone())?;
|
||||
self.log_if_shown(turn).await
|
||||
}
|
||||
|
||||
/// Writes the turn log entry for a submission the screen now shows as
|
||||
/// finished (closed, or waiting on a question). Called after the row
|
||||
/// commits and derived from that same turn, so the log never runs ahead of
|
||||
/// the screen; `history` calls it again for the stored turn, so a crash
|
||||
/// between the two writes is repaired on the next read. A submission
|
||||
/// already in the log is left exactly as it was.
|
||||
async fn log_if_shown(&self, turn: &PlayTurn) -> Result<(), PlayError> {
|
||||
if turn.state == PlayTurnState::Running {
|
||||
return Ok(());
|
||||
}
|
||||
let submission = turn.player_prose.len() as u32;
|
||||
if self.log.lock().await.recorded(&turn.turn_id, submission) {
|
||||
return Ok(());
|
||||
}
|
||||
// `None` when the kernel cannot be read now: the entry says so.
|
||||
let world_revision = self.play.snapshot().await.ok().map(|snapshot| snapshot.revision);
|
||||
let retry_of = {
|
||||
let mut pending = self.pending_retry.lock().unwrap();
|
||||
match pending.take() {
|
||||
Some((turn_id, seq)) if turn_id == turn.turn_id && submission == 1 => Some(seq),
|
||||
other => {
|
||||
*pending = other;
|
||||
None
|
||||
}
|
||||
}
|
||||
};
|
||||
let (status, fault) = if turn.fault.is_some() {
|
||||
(TurnStatus::Faulted, Some(crate::api::PLAY_FAULT_LINE.to_owned()))
|
||||
} else if turn.state == PlayTurnState::AwaitingPlayer {
|
||||
(TurnStatus::Asked, None)
|
||||
} else if turn.refusal.is_some() {
|
||||
(TurnStatus::Refused, None)
|
||||
} else {
|
||||
(TurnStatus::Committed, None)
|
||||
};
|
||||
let entry = NewEntry {
|
||||
turn_id: turn.turn_id.clone(),
|
||||
submission,
|
||||
text: turn.player_prose.last().cloned().unwrap_or_default(),
|
||||
narration: turn.narration.clone(),
|
||||
question: turn.question.clone(),
|
||||
refusal: turn.refusal.clone(),
|
||||
fault,
|
||||
status,
|
||||
world_revision,
|
||||
retry_of,
|
||||
};
|
||||
self.log.lock().await.record(entry)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A page of the turn log, oldest first, newest last: up to `limit`
|
||||
/// entries older than `before` (the newest when `None`). The stored turn
|
||||
/// is logged first if a crash left it unlogged, so what this returns is
|
||||
/// never behind what the turn view shows.
|
||||
pub(crate) async fn history(&self, before: Option<u64>, limit: usize) -> Result<TurnPage, PlayError> {
|
||||
let stored = self.store.lock().await.current().cloned();
|
||||
if let Some(turn) = stored {
|
||||
self.log_if_shown(&turn).await?;
|
||||
}
|
||||
Ok(self.log.lock().await.page(before, limit))
|
||||
}
|
||||
|
||||
pub(crate) async fn logged(&self, seq: u64) -> bool {
|
||||
self.log.lock().await.contains(seq)
|
||||
}
|
||||
|
||||
/// Marks the turn just admitted as a retry of log entry `seq`. Only a turn
|
||||
/// this admission opened can be a retry.
|
||||
pub(crate) fn note_retry(&self, admitted: &Admitted, seq: u64) {
|
||||
if admitted.turn.player_prose.len() == 1 && admitted.turn.rounds.is_empty() {
|
||||
*self.pending_retry.lock().unwrap() = Some((admitted.turn.turn_id.clone(), seq));
|
||||
}
|
||||
}
|
||||
|
||||
async fn execute_advance_time(
|
||||
&self,
|
||||
turn: &mut PlayTurn,
|
||||
|
|
@ -3850,6 +3941,7 @@ pub(crate) mod tests {
|
|||
revision: 1,
|
||||
run_in_progress: false,
|
||||
fault: false,
|
||||
player_text: None,
|
||||
};
|
||||
let surface = authenticated_surface(
|
||||
"player-interrupted-turn",
|
||||
|
|
@ -3876,6 +3968,7 @@ pub(crate) mod tests {
|
|||
revision: 1,
|
||||
run_in_progress: false,
|
||||
fault: false,
|
||||
player_text: None,
|
||||
};
|
||||
let awaiting_surface = authenticated_surface(
|
||||
"player-interrupted-turn",
|
||||
|
|
@ -3917,6 +4010,7 @@ pub(crate) mod tests {
|
|||
revision: 1,
|
||||
run_in_progress: true,
|
||||
fault: false,
|
||||
player_text: None,
|
||||
};
|
||||
let surface = authenticated_surface(
|
||||
"player-interrupted-turn-busy",
|
||||
|
|
@ -3960,6 +4054,7 @@ pub(crate) mod tests {
|
|||
revision: 1,
|
||||
run_in_progress: true,
|
||||
fault: false,
|
||||
player_text: None,
|
||||
};
|
||||
let surface = authenticated_surface(
|
||||
"player-round-in-flight",
|
||||
|
|
@ -3983,6 +4078,7 @@ pub(crate) mod tests {
|
|||
revision: 1,
|
||||
run_in_progress: false,
|
||||
fault: false,
|
||||
player_text: None,
|
||||
};
|
||||
let idle_surface = authenticated_surface(
|
||||
"player-round-in-flight",
|
||||
|
|
@ -4019,6 +4115,7 @@ pub(crate) mod tests {
|
|||
revision: 1,
|
||||
run_in_progress: false,
|
||||
fault: false,
|
||||
player_text: None,
|
||||
};
|
||||
let surface = authenticated_surface(
|
||||
"player-stalled-turn-text",
|
||||
|
|
|
|||
242
crates/ghostlight-dungeon/src/turn_log.rs
Normal file
242
crates/ghostlight-dungeon/src/turn_log.rs
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
//! The turn log: what the player was shown, turn by turn, kept for as long as
|
||||
//! the timeline lives.
|
||||
//!
|
||||
//! The kernel journal records what happened in the world, not the prose the
|
||||
//! storyteller wrote about it, and the play row holds only the current turn.
|
||||
//! So the narration a player read exists in one place until the next turn
|
||||
//! replaces it. This log is where it stays. It sits next to the timeline's
|
||||
//! other state and is written by `PlayTable` from the row the screen is drawn
|
||||
//! from, right after that row is committed, so an entry can never say
|
||||
//! something the screen did not. It is append-only: nothing here edits or
|
||||
//! deletes an entry, and a Retry is a new entry that names the one it retries.
|
||||
|
||||
use anyhow::{Context, bail, ensure};
|
||||
use chrono::{DateTime, Utc};
|
||||
use cultcache_rs::{CacheBackingStore, CultCacheEnvelope, OwnedRedbMessagePackBackingStore};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{collections::HashMap, path::Path};
|
||||
|
||||
const TYPE: &str = "ghostlight.dungeon_turn_log.v1";
|
||||
|
||||
/// How a submission ended, as the player was told.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub(crate) enum TurnStatus {
|
||||
/// The turn closed and narrated.
|
||||
Committed,
|
||||
/// The world refused an act of the turn; `refusal` holds the line.
|
||||
Refused,
|
||||
/// The turn died on its model; `fault` holds the line shown.
|
||||
Faulted,
|
||||
/// The storyteller asked a question and is waiting; `question` holds it.
|
||||
Asked,
|
||||
}
|
||||
|
||||
/// One submission and what it produced. `seq` is its place in the log, from 1.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) struct LogEntry {
|
||||
pub(crate) seq: u64,
|
||||
pub(crate) turn_id: String,
|
||||
/// Which submission of that turn this is: 1 opens it, each answer adds one.
|
||||
pub(crate) submission: u32,
|
||||
/// The player's text exactly as sent.
|
||||
pub(crate) text: String,
|
||||
pub(crate) narration: Option<String>,
|
||||
pub(crate) question: Option<String>,
|
||||
pub(crate) refusal: Option<String>,
|
||||
pub(crate) fault: Option<String>,
|
||||
pub(crate) status: TurnStatus,
|
||||
/// The world revision the entry rests on, or `None` when the kernel could
|
||||
/// not be read at the moment the entry was written.
|
||||
pub(crate) world_revision: Option<u64>,
|
||||
/// The entry this one retries.
|
||||
pub(crate) retry_of: Option<u64>,
|
||||
pub(crate) recorded_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
/// An entry before it has a place in the log.
|
||||
pub(crate) struct NewEntry {
|
||||
pub(crate) turn_id: String,
|
||||
pub(crate) submission: u32,
|
||||
pub(crate) text: String,
|
||||
pub(crate) narration: Option<String>,
|
||||
pub(crate) question: Option<String>,
|
||||
pub(crate) refusal: Option<String>,
|
||||
pub(crate) fault: Option<String>,
|
||||
pub(crate) status: TurnStatus,
|
||||
pub(crate) world_revision: Option<u64>,
|
||||
pub(crate) retry_of: Option<u64>,
|
||||
}
|
||||
|
||||
/// A page of the log, oldest first, newest last.
|
||||
pub(crate) struct Page {
|
||||
pub(crate) entries: Vec<(LogEntry, Option<u64>)>,
|
||||
/// Pass as `before` to read the page of older entries; `None` at the start.
|
||||
pub(crate) older: Option<u64>,
|
||||
}
|
||||
|
||||
pub(crate) struct TurnLog {
|
||||
store: OwnedRedbMessagePackBackingStore,
|
||||
/// Every entry, `entries[n]` having `seq == n + 1`.
|
||||
entries: Vec<LogEntry>,
|
||||
}
|
||||
|
||||
fn key_of(seq: u64) -> String {
|
||||
format!("{seq:012}")
|
||||
}
|
||||
|
||||
impl TurnLog {
|
||||
pub(crate) fn open(path: impl AsRef<Path>) -> anyhow::Result<Self> {
|
||||
let store = OwnedRedbMessagePackBackingStore::new(path.as_ref())?;
|
||||
store.validate_path_identity().context("turn log path identity is invalid")?;
|
||||
let mut entries = Vec::new();
|
||||
for row in store.pull_all()? {
|
||||
ensure!(row.r#type == TYPE, "turn log holds a foreign record");
|
||||
let entry: LogEntry = rmp_serde::from_slice(&row.payload).context("a turn log entry did not decode")?;
|
||||
ensure!(row.key == key_of(entry.seq), "a turn log entry sits under the wrong key");
|
||||
entries.push(entry);
|
||||
}
|
||||
entries.sort_by_key(|entry| entry.seq);
|
||||
for (index, entry) in entries.iter().enumerate() {
|
||||
if entry.seq != index as u64 + 1 {
|
||||
bail!("the turn log has a gap before entry {}", entry.seq);
|
||||
}
|
||||
}
|
||||
Ok(Self { store, entries })
|
||||
}
|
||||
|
||||
pub(crate) fn contains(&self, seq: u64) -> bool {
|
||||
seq >= 1 && seq <= self.entries.len() as u64
|
||||
}
|
||||
|
||||
pub(crate) fn recorded(&self, turn_id: &str, submission: u32) -> bool {
|
||||
self.entries
|
||||
.iter()
|
||||
.rev()
|
||||
.any(|entry| entry.turn_id == turn_id && entry.submission == submission)
|
||||
}
|
||||
|
||||
/// Appends `new` unless that turn's submission is already recorded.
|
||||
/// Returns the new entry's `seq`, or `None` when it was already there.
|
||||
pub(crate) fn record(&mut self, new: NewEntry) -> anyhow::Result<Option<u64>> {
|
||||
if self.recorded(&new.turn_id, new.submission) {
|
||||
return Ok(None);
|
||||
}
|
||||
if let Some(target) = new.retry_of {
|
||||
ensure!(self.contains(target), "a retry names an entry the log does not hold");
|
||||
}
|
||||
let seq = self.entries.len() as u64 + 1;
|
||||
let entry = LogEntry {
|
||||
seq,
|
||||
turn_id: new.turn_id,
|
||||
submission: new.submission,
|
||||
text: new.text,
|
||||
narration: new.narration,
|
||||
question: new.question,
|
||||
refusal: new.refusal,
|
||||
fault: new.fault,
|
||||
status: new.status,
|
||||
world_revision: new.world_revision,
|
||||
retry_of: new.retry_of,
|
||||
recorded_at: Utc::now(),
|
||||
};
|
||||
let row = CultCacheEnvelope {
|
||||
key: key_of(seq),
|
||||
r#type: TYPE.into(),
|
||||
payload: rmp_serde::to_vec_named(&entry)?,
|
||||
stored_at: entry.recorded_at.to_rfc3339(),
|
||||
schema_id: Some(TYPE.into()),
|
||||
};
|
||||
self.store.validate_path_identity().context("turn log ownership was lost")?;
|
||||
if !self.store.compare_and_swap_batch(&[], vec![row])? {
|
||||
bail!("turn log entry {seq} already exists on disk");
|
||||
}
|
||||
self.entries.push(entry);
|
||||
Ok(Some(seq))
|
||||
}
|
||||
|
||||
/// Up to `limit` entries older than `before` (the newest when `None`),
|
||||
/// each with the `seq` of the entry that retried it, if one did.
|
||||
pub(crate) fn page(&self, before: Option<u64>, limit: usize) -> Page {
|
||||
let end = before.map_or(self.entries.len(), |before| (before.saturating_sub(1) as usize).min(self.entries.len()));
|
||||
let start = end.saturating_sub(limit.max(1));
|
||||
let retried_by: HashMap<u64, u64> = self
|
||||
.entries
|
||||
.iter()
|
||||
.rev()
|
||||
.filter_map(|entry| entry.retry_of.map(|target| (target, entry.seq)))
|
||||
.collect();
|
||||
let entries = self.entries[start..end]
|
||||
.iter()
|
||||
.map(|entry| (entry.clone(), retried_by.get(&entry.seq).copied()))
|
||||
.collect();
|
||||
Page { entries, older: (start > 0).then_some(start as u64 + 1) }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn new(turn: &str, submission: u32, text: &str) -> NewEntry {
|
||||
NewEntry {
|
||||
turn_id: turn.into(),
|
||||
submission,
|
||||
text: text.into(),
|
||||
narration: Some(format!("story of {text}")),
|
||||
question: None,
|
||||
refusal: None,
|
||||
fault: None,
|
||||
status: TurnStatus::Committed,
|
||||
world_revision: Some(7),
|
||||
retry_of: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entries_append_page_newest_last_and_survive_a_reopen() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("turn-log-v1.cc");
|
||||
{
|
||||
let mut log = TurnLog::open(&path).unwrap();
|
||||
for n in 1..=5 {
|
||||
assert_eq!(log.record(new(&format!("t{n}"), 1, &format!("say {n}"))).unwrap(), Some(n));
|
||||
}
|
||||
assert_eq!(log.record(new("t3", 1, "say 3 again")).unwrap(), None, "a recorded submission is never rewritten");
|
||||
let newest = log.page(None, 2);
|
||||
assert_eq!(newest.entries.iter().map(|(e, _)| e.seq).collect::<Vec<_>>(), [4, 5]);
|
||||
assert_eq!(newest.older, Some(4));
|
||||
let older = log.page(newest.older, 2);
|
||||
assert_eq!(older.entries.iter().map(|(e, _)| e.seq).collect::<Vec<_>>(), [2, 3]);
|
||||
let oldest = log.page(older.older, 2);
|
||||
assert_eq!(oldest.entries.iter().map(|(e, _)| e.seq).collect::<Vec<_>>(), [1]);
|
||||
assert_eq!(oldest.older, None);
|
||||
}
|
||||
let log = TurnLog::open(&path).unwrap();
|
||||
let all = log.page(None, 50);
|
||||
assert_eq!(all.entries.len(), 5);
|
||||
assert_eq!(all.entries[2].0.text, "say 3", "the first write stands");
|
||||
assert_eq!(all.entries[2].0.narration.as_deref(), Some("story of say 3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retry_is_a_new_entry_and_the_old_one_reads_as_superseded() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let mut log = TurnLog::open(directory.path().join("turn-log-v1.cc")).unwrap();
|
||||
let mut faulted = new("t1", 1, "I knock");
|
||||
faulted.status = TurnStatus::Faulted;
|
||||
faulted.narration = None;
|
||||
faulted.fault = Some("the storyteller lost the thread".into());
|
||||
log.record(faulted).unwrap();
|
||||
let mut retry = new("t2", 1, "I knock");
|
||||
retry.retry_of = Some(1);
|
||||
log.record(retry).unwrap();
|
||||
let page = log.page(None, 10);
|
||||
assert_eq!(page.entries[0].0.status, TurnStatus::Faulted, "the old entry stays as it was");
|
||||
assert_eq!(page.entries[0].1, Some(2), "and reads as superseded by the retry");
|
||||
assert_eq!(page.entries[1].1, None);
|
||||
let mut bad = new("t3", 1, "x");
|
||||
bad.retry_of = Some(99);
|
||||
assert!(log.record(bad).is_err(), "a retry must name an entry the log holds");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue