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
//! Streaming control for pause/resume/cancel operations
//!
//! This module provides control mechanisms for streaming responses, allowing
//! pause, resume, and cancellation of active streams.
#[ cfg( feature = "streaming-control" ) ]
mod private
{
use std::sync::{ Arc, Mutex };
use std::collections::VecDeque;
use std::pin::Pin;
use std::task::{ Context, Poll };
use futures::Stream;
use crate::streaming::StreamEvent;
/// State of a controlled stream
#[ derive( Debug, Clone, Copy, PartialEq, Eq ) ]
pub enum StreamState
{
/// Stream is actively consuming events
Running,
/// Stream is paused, buffering events
Paused,
/// Stream is cancelled, no more events
Cancelled,
}
/// Internal state for stream control
#[ derive( Debug ) ]
struct ControlState
{
state : StreamState,
buffer : VecDeque< StreamEvent >,
buffer_limit : usize,
}
/// Handle for controlling stream operations
///
/// Provides pause, resume, and cancel functionality for streaming responses.
#[ derive( Debug, Clone ) ]
pub struct StreamControl
{
state : Arc< Mutex< ControlState > >,
}
impl StreamControl
{
/// Create a new stream control handle
pub fn new( buffer_limit : usize ) -> Self
{
Self
{
state : Arc::new( Mutex::new( ControlState
{
state : StreamState::Running,
buffer : VecDeque::new(),
buffer_limit,
} ) ),
}
}
/// Pause the stream
///
/// When paused, events are buffered up to the buffer limit.
/// If the buffer fills, oldest events are dropped.
///
/// # Errors
///
/// Returns an error if the stream is already cancelled.
///
/// # Panics
///
/// Panics if the internal mutex is poisoned.
pub fn pause( &self ) -> Result< (), String >
{
let mut state = self.state.lock().unwrap();
if state.state == StreamState::Cancelled
{
return Err( "Cannot pause cancelled stream".to_string() );
}
state.state = StreamState::Paused;
Ok( () )
}
/// Resume the stream
///
/// Buffered events will be delivered before new events.
///
/// # Errors
///
/// Returns an error if the stream is already cancelled.
///
/// # Panics
///
/// Panics if the internal mutex is poisoned.
pub fn resume( &self ) -> Result< (), String >
{
let mut state = self.state.lock().unwrap();
if state.state == StreamState::Cancelled
{
return Err( "Cannot resume cancelled stream".to_string() );
}
state.state = StreamState::Running;
Ok( () )
}
/// Cancel the stream
///
/// This is irreversible. The stream will stop producing events.
///
/// # Panics
///
/// Panics if the internal mutex is poisoned.
pub fn cancel( &self )
{
let mut state = self.state.lock().unwrap();
state.state = StreamState::Cancelled;
state.buffer.clear();
}
/// Check if stream is paused
///
/// # Panics
///
/// Panics if the internal mutex is poisoned.
pub fn is_paused( &self ) -> bool
{
let state = self.state.lock().unwrap();
state.state == StreamState::Paused
}
/// Check if stream is cancelled
///
/// # Panics
///
/// Panics if the internal mutex is poisoned.
pub fn is_cancelled( &self ) -> bool
{
let state = self.state.lock().unwrap();
state.state == StreamState::Cancelled
}
/// Check if stream is running
///
/// # Panics
///
/// Panics if the internal mutex is poisoned.
pub fn is_running( &self ) -> bool
{
let state = self.state.lock().unwrap();
state.state == StreamState::Running
}
/// Get current state
///
/// # Panics
///
/// Panics if the internal mutex is poisoned.
pub fn get_state( &self ) -> StreamState
{
let state = self.state.lock().unwrap();
state.state
}
/// Get number of buffered events
///
/// # Panics
///
/// Panics if the internal mutex is poisoned.
pub fn buffer_size( &self ) -> usize
{
let state = self.state.lock().unwrap();
state.buffer.len()
}
/// Buffer an event (called internally by `ControlledStream`)
fn buffer_event( &self, event : StreamEvent )
{
let mut state = self.state.lock().unwrap();
if state.buffer.len() >= state.buffer_limit
{
// Drop oldest event if buffer is full
state.buffer.pop_front();
}
state.buffer.push_back( event );
}
/// Get next buffered event (called internally by `ControlledStream`)
fn next_buffered( &self ) -> Option< StreamEvent >
{
let mut state = self.state.lock().unwrap();
state.buffer.pop_front()
}
/// Check if there are buffered events
fn has_buffered( &self ) -> bool
{
let state = self.state.lock().unwrap();
!state.buffer.is_empty()
}
}
/// Controlled stream wrapper
///
/// Wraps a stream with pause/resume/cancel control functionality.
#[ derive( Debug ) ]
pub struct ControlledStream< S >
where
S: Stream< Item = Result< StreamEvent, crate::error::AnthropicError > > + Unpin,
{
inner : S,
control : StreamControl,
}
impl< S > ControlledStream< S >
where
S: Stream< Item = Result< StreamEvent, crate::error::AnthropicError > > + Unpin,
{
/// Create a new controlled stream
///
/// # Arguments
///
/// * `inner` - The underlying stream to control
/// * `buffer_limit` - Maximum number of events to buffer when paused
pub fn new( inner : S, buffer_limit : usize ) -> ( Self, StreamControl )
{
let control = StreamControl::new( buffer_limit );
let controlled = Self
{
inner,
control : control.clone(),
};
( controlled, control )
}
/// Get a clone of the control handle
pub fn control( &self ) -> StreamControl
{
self.control.clone()
}
}
impl< S > Stream for ControlledStream< S >
where
S: Stream< Item = Result< StreamEvent, crate::error::AnthropicError > > + Unpin,
{
type Item = Result< StreamEvent, crate::error::AnthropicError >;
fn poll_next( mut self : Pin< &mut Self >, cx : &mut Context< '_ > ) -> Poll< Option< Self::Item > >
{
// Check if cancelled
if self.control.is_cancelled()
{
return Poll::Ready( None );
}
// If paused, buffer events from inner stream
if self.control.is_paused()
{
// Try to poll inner stream to buffer events
match Pin::new( &mut self.inner ).poll_next( cx )
{
Poll::Ready( Some( Ok( event ) ) ) =>
{
self.control.buffer_event( event );
Poll::Pending
}
Poll::Ready( Some( Err( e ) ) ) =>
{
// Don't buffer errors, return them immediately
Poll::Ready( Some( Err( e ) ) )
}
Poll::Ready( None ) =>
{
// Stream ended while paused
Poll::Ready( None )
}
Poll::Pending => Poll::Pending,
}
}
else
{
// Running - first deliver any buffered events
if self.control.has_buffered()
{
if let Some( event ) = self.control.next_buffered()
{
return Poll::Ready( Some( Ok( event ) ) );
}
}
// Then poll inner stream
Pin::new( &mut self.inner ).poll_next( cx )
}
}
}
}
#[ cfg( feature = "streaming-control" ) ]
crate::mod_interface!
{
exposed use
{
StreamControl,
StreamState,
ControlledStream,
};
}
#[ cfg( not( feature = "streaming-control" ) ) ]
crate::mod_interface!
{
// Empty when streaming-control feature is disabled
}