Skip to main content

causa_runtime/session/
handle.rs

1//! The cloneable operation entry — [`SessionHandle`] — for one session.
2//!
3//! A handle shares the session's private execution core but never owns the
4//! lifecycle and never exposes the writable conversation state.
5
6use std::sync::Arc;
7use std::time::Duration;
8
9use causa_kernel::ConversationId;
10
11use crate::resume::ResumeRequest;
12
13use super::execution::SessionCore;
14use super::types::{
15    CancelReceipt, SessionError, SubmitRequest, WaitOutcome, WorkObservation, WorkReceipt, WorkRef,
16};
17
18/// A cloneable operation entry for one [`Session`](crate::session::Session).
19///
20/// Handles never own the lifecycle: dropping the last handle does not close
21/// the session, and after the owner is dropped they can still read retained
22/// observations and replay an accepted `request_key` to its original
23/// receipt, while new submissions are refused with [`SessionError::Closed`].
24#[derive(Clone)]
25pub struct SessionHandle {
26    pub(super) core: Arc<SessionCore>,
27}
28
29impl std::fmt::Debug for SessionHandle {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        f.debug_struct("SessionHandle")
32            .field("conversation_id", &self.core.conversation_id())
33            .finish_non_exhaustive()
34    }
35}
36
37impl SessionHandle {
38    /// The conversation this handle operates on.
39    pub fn id(&self) -> ConversationId {
40        self.core.conversation_id()
41    }
42
43    /// Submit one new work.
44    ///
45    /// Accepts on an idle session, atomically allocates a fresh turn id,
46    /// writes the request parts as the turn's first fact block, and spawns the
47    /// worker. Rejections (busy, conflict, capacity, invalid input, closed,
48    /// faulted) leave no accepted work behind and do not consume the request
49    /// key. Idempotent on `request_key` + parts: a repeat returns the original
50    /// receipt without executing again, even once the owner has closed.
51    ///
52    /// Synchronous: admission never blocks on the runner. Spawning the worker
53    /// still requires a Tokio runtime context.
54    ///
55    /// # Errors
56    ///
57    /// See [`SessionError`].
58    pub fn submit(&self, request: SubmitRequest) -> Result<WorkReceipt, SessionError> {
59        self.core.submit(request)
60    }
61
62    /// Read one work's current published state.
63    ///
64    /// A paused observation includes the prepared calls needed to construct
65    /// a resume decision, copied from the same revision. Never blocks on the
66    /// runner and never mutates the work.
67    ///
68    /// # Errors
69    ///
70    /// [`SessionError::NotFound`] if the ref does not belong to this session.
71    pub fn observe(&self, work: &WorkRef) -> Result<WorkObservation, SessionError> {
72        self.core.observe(work)
73    }
74
75    /// Wait finitely for a work to reach `Paused` / `Finished` / `Faulted`.
76    ///
77    /// Returns as soon as one of those states is observed, or `TimedOut` with
78    /// a consistent snapshot when `timeout` elapses first; a wakeup is never
79    /// lost, and timing out does not change the work's state.
80    ///
81    /// # Errors
82    ///
83    /// [`SessionError::NotFound`] if the ref does not belong to this session.
84    pub async fn wait(
85        &self,
86        work: &WorkRef,
87        timeout: Duration,
88    ) -> Result<WaitOutcome, SessionError> {
89        self.core.wait(work, timeout).await
90    }
91
92    /// Continue a paused work.
93    ///
94    /// Validates the ref, the work's current paused revision, and the request
95    /// against the paused continuation before anything runs: a rejected request
96    /// executes nothing and leaves the paused material untouched. On acceptance
97    /// the work returns to `Running` in the same turn id and continues under the
98    /// deadline measured from its original acceptance. Idempotent on
99    /// `request_key` + `(work, expected_revision, request)`: a same-key repeat
100    /// returns the original receipt without re-executing, while the same key
101    /// with a different decision or injection is [`SessionError::Conflict`].
102    ///
103    /// Synchronous: admission never blocks on the runner.
104    ///
105    /// # Errors
106    ///
107    /// [`SessionError::NotFound`] for a foreign or unknown ref,
108    /// [`SessionError::NotPaused`] when the work is not paused,
109    /// [`SessionError::StaleRevision`] when `expected_revision` is not the
110    /// work's current paused revision, [`SessionError::Busy`] while another work
111    /// owns the conversation, [`SessionError::InvalidResume`] when the driver
112    /// rejects the request, [`SessionError::Conflict`] on a key reuse with
113    /// different arguments, and [`SessionError::Closed`] for a request that is
114    /// not a replay after shutdown.
115    pub fn resume(
116        &self,
117        work: &WorkRef,
118        expected_revision: u64,
119        request_key: String,
120        request: ResumeRequest,
121    ) -> Result<WorkReceipt, SessionError> {
122        self.core
123            .resume(work, expected_revision, request_key, request)
124    }
125
126    /// Read the receipt of an already-accepted resume without starting work.
127    ///
128    /// Hosts can resolve a retry before applying their own capacity gate.
129    /// `Some` is the original receipt for exactly these arguments; `None`
130    /// means this session has not accepted the key. Neither outcome changes
131    /// the work, consumes the key, nor requires a paused or open session.
132    /// A missing record does not reserve admission: a later [`Self::resume`]
133    /// still performs its atomic replay and state checks.
134    ///
135    /// # Errors
136    ///
137    /// [`SessionError::Conflict`] if this key was accepted with a different
138    /// work, paused revision, or request.
139    pub fn resume_receipt(
140        &self,
141        work: &WorkRef,
142        expected_revision: u64,
143        request_key: &str,
144        request: &ResumeRequest,
145    ) -> Result<Option<WorkReceipt>, SessionError> {
146        self.core
147            .resume_receipt(work, expected_revision, request_key, request)
148    }
149
150    /// Cancel one work.
151    ///
152    /// Fires the work's own control token while it runs — a completion that
153    /// races the cancel keeps its result — or terminates a paused work in
154    /// place, retaining its committed facts and continuation. A work
155    /// that already finished is never rewritten. Idempotent on `request_key`: a
156    /// same-key retry returns the original receipt.
157    ///
158    /// Synchronous: admission never blocks on the runner.
159    ///
160    /// # Errors
161    ///
162    /// [`SessionError::NotFound`] for a foreign, unknown, or already-cleared
163    /// ref, [`SessionError::Busy`] while another work owns the conversation,
164    /// [`SessionError::Conflict`] on a key reuse with a different work, and
165    /// [`SessionError::Closed`] for a request that is not a replay after
166    /// shutdown.
167    pub fn cancel(
168        &self,
169        work: &WorkRef,
170        request_key: String,
171    ) -> Result<CancelReceipt, SessionError> {
172        self.core.cancel(work, request_key)
173    }
174}