| 1 | use std::collections::HashMap; |
| 2 | use std::path::PathBuf; |
| 3 | use std::sync::Arc; |
| 4 | use std::time::Duration; |
| 5 | |
| 6 | use anyhow::{Context as _, Result}; |
| 7 | use codewhale_app_server_protocol::rpc::RequestId; |
| 8 | use codewhale_app_server_protocol::runtime::{ |
| 9 | MAX_RUNTIME_IMAGE_BODY_BYTES, NATIVE_RUNTIME_CAPABILITY, NATIVE_RUNTIME_METHODS, |
| 10 | NativeRuntimeRequest, |
| 11 | }; |
| 12 | use futures_util::StreamExt as _; |
| 13 | use serde::Deserialize; |
| 14 | use serde_json::{Value, json}; |
| 15 | use tokio::io::{AsyncBufRead, AsyncBufReadExt as _, AsyncWrite}; |
| 16 | use tokio::sync::{OwnedSemaphorePermit, Semaphore, mpsc}; |
| 17 | use tokio_util::sync::CancellationToken; |
| 18 | |
| 19 | use crate::{RuntimeOwnerFrontend, RuntimeOwnerRequest}; |
| 20 | |
| 21 | pub fn capabilities() -> Value { |
| 22 | json!({"capabilities":[NATIVE_RUNTIME_CAPABILITY],"methods":NATIVE_RUNTIME_METHODS,"max_in_flight":64,"max_subscriptions":16,"max_frame_bytes":MAX_RUNTIME_IMAGE_BODY_BYTES,"max_output_frames":64,"max_output_bytes":MAX_RUNTIME_IMAGE_BODY_BYTES}) |
| 23 | } |
| 24 | |
| 25 | #[derive(Debug, Clone, Deserialize, serde::Serialize)] |
| 26 | #[serde(deny_unknown_fields)] |
| 27 | pub struct NativeSelection { |
| 28 | pub capability: String, |
| 29 | pub workspace: PathBuf, |
| 30 | } |
| 31 | |
| 32 | impl NativeSelection { |
| 33 | pub(crate) fn validate(&self) -> Result<()> { |
| 34 | anyhow::ensure!( |
| 35 | self.capability == NATIVE_RUNTIME_CAPABILITY |
| 36 | && self.workspace.is_absolute() |
| 37 | && self.workspace.as_os_str().len() <= 4096, |
| 38 | "unsupported native Runtime selection" |
| 39 | ); |
| 40 | Ok(()) |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | type SentSequence = Arc<parking_lot::Mutex<Option<u64>>>; |
| 45 | |
| 46 | struct Queued { |
| 47 | bytes: Vec<u8>, |
| 48 | _bytes: OwnedSemaphorePermit, |
| 49 | sent_sequence: Option<(SentSequence, u64)>, |
| 50 | closed_sequence: Option<SentSequence>, |
| 51 | } |
| 52 | |
| 53 | impl Queued { |
| 54 | async fn write<W: AsyncWrite + Unpin>(mut self, writer: &mut W) -> Result<()> { |
| 55 | if let Some(sequence) = self.closed_sequence.as_ref() { |
| 56 | let mut terminal: Value = serde_json::from_slice(&self.bytes)?; |
| 57 | terminal["params"]["last_sent_sequence"] = json!(*sequence.lock()); |
| 58 | self.bytes = crate::stdio::serialize_control_frame(&terminal)?; |
| 59 | } |
| 60 | tokio::time::timeout( |
| 61 | Duration::from_secs(5), |
| 62 | crate::stdio::write_control_line(writer, &self.bytes), |
| 63 | ) |
| 64 | .await |
| 65 | .context("native write deadline expired")??; |
| 66 | if let Some((sequence, sent)) = self.sent_sequence { |
| 67 | *sequence.lock() = Some(sent); |
| 68 | } |
| 69 | Ok(()) |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | #[derive(Clone)] |
| 74 | struct Output { |
| 75 | sender: mpsc::Sender<Queued>, |
| 76 | bytes: Arc<Semaphore>, |
| 77 | closed: CancellationToken, |
| 78 | } |
| 79 | |
| 80 | impl Output { |
| 81 | fn try_send(&self, value: Value) -> Result<()> { |
| 82 | self.try_send_tracked(value, None, None) |
| 83 | } |
| 84 | |
| 85 | fn try_send_tracked( |
| 86 | &self, |
| 87 | value: Value, |
| 88 | sent_sequence: Option<(SentSequence, u64)>, |
| 89 | closed_sequence: Option<SentSequence>, |
| 90 | ) -> Result<()> { |
| 91 | let bytes = crate::stdio::serialize_control_frame(&value)?; |
| 92 | let permit = self |
| 93 | .bytes |
| 94 | .clone() |
| 95 | .try_acquire_many_owned(u32::try_from(bytes.len())?)?; |
| 96 | self.sender |
| 97 | .try_send(Queued { |
| 98 | bytes, |
| 99 | _bytes: permit, |
| 100 | sent_sequence, |
| 101 | closed_sequence, |
| 102 | }) |
| 103 | .map_err(|_| anyhow::anyhow!("output queue is full"))?; |
| 104 | Ok(()) |
| 105 | } |
| 106 | |
| 107 | async fn send(&self, value: Value) -> Result<()> { |
| 108 | let bytes = crate::stdio::serialize_control_frame(&value)?; |
| 109 | let result = tokio::time::timeout(Duration::from_secs(5), async { |
| 110 | let permit = self |
| 111 | .bytes |
| 112 | .clone() |
| 113 | .acquire_many_owned(u32::try_from(bytes.len())?) |
| 114 | .await?; |
| 115 | self.sender |
| 116 | .send(Queued { |
| 117 | bytes, |
| 118 | _bytes: permit, |
| 119 | sent_sequence: None, |
| 120 | closed_sequence: None, |
| 121 | }) |
| 122 | .await |
| 123 | .map_err(|_| anyhow::anyhow!("output closed"))?; |
| 124 | Ok::<_, anyhow::Error>(()) |
| 125 | }) |
| 126 | .await; |
| 127 | match result { |
| 128 | Ok(Ok(())) => Ok(()), |
| 129 | _ => { |
| 130 | self.closed.cancel(); |
| 131 | anyhow::bail!("native output unavailable") |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | pub(crate) fn error(id: Value, code: i64, message: &str, status: u16, outcome: &str) -> Value { |
| 138 | json!({"jsonrpc":"2.0","id":id,"error":{"code":code,"message":message.chars().take(512).collect::<String>(),"data":{"status":status,"code":if status==429 {"busy"} else {"native_runtime_refused"},"outcome":outcome}}}) |
| 139 | } |
| 140 | |
| 141 | fn result(id: Value, value: Value) -> Value { |
| 142 | json!({"jsonrpc":"2.0","id":id,"result":value}) |
| 143 | } |
| 144 | |
| 145 | fn failed(id: Value, failure: anyhow::Error) -> Value { |
| 146 | if let Some(failure) = failure.downcast_ref::<crate::RuntimeOwnerFailure>() { |
| 147 | let mut response = error( |
| 148 | id, |
| 149 | if failure.status == 400 { |
| 150 | -32602 |
| 151 | } else { |
| 152 | -32000 |
| 153 | }, |
| 154 | &failure.message, |
| 155 | failure.status, |
| 156 | "known", |
| 157 | ); |
| 158 | if let Some(code) = failure.code.as_deref() { |
| 159 | response["error"]["data"]["code"] = json!(code); |
| 160 | } |
| 161 | response |
| 162 | } else { |
| 163 | error(id, -32000, "Runtime operation failed", 500, "unknown") |
| 164 | } |
| 165 | } |
| 166 | |
| 167 | #[derive(Deserialize)] |
| 168 | #[serde(deny_unknown_fields)] |
| 169 | pub(crate) struct Envelope { |
| 170 | pub(crate) jsonrpc: String, |
| 171 | #[serde(default, deserialize_with = "present_request_id")] |
| 172 | pub(crate) id: Option<RequestId>, |
| 173 | pub(crate) method: String, |
| 174 | #[serde(default)] |
| 175 | pub(crate) params: Value, |
| 176 | } |
| 177 | |
| 178 | fn present_request_id<'de, D: serde::Deserializer<'de>>( |
| 179 | deserializer: D, |
| 180 | ) -> std::result::Result<Option<RequestId>, D::Error> { |
| 181 | RequestId::deserialize(deserializer).map(Some) |
| 182 | } |
| 183 | |
| 184 | pub(crate) fn decode_envelope(line: &str) -> Result<Envelope> { |
| 185 | let request: Envelope = serde_json::from_str(line)?; |
| 186 | anyhow::ensure!(request.jsonrpc == "2.0", "invalid JSON-RPC version"); |
| 187 | if request.id.is_none() { |
| 188 | anyhow::ensure!( |
| 189 | matches!( |
| 190 | request.method.as_str(), |
| 191 | "initialized" | "daemon/input_closed" |
| 192 | ) && (request.params.is_null() || request.params == json!({})), |
| 193 | "invalid native notification" |
| 194 | ); |
| 195 | } else { |
| 196 | anyhow::ensure!( |
| 197 | !matches!( |
| 198 | request.method.as_str(), |
| 199 | "initialized" | "daemon/input_closed" |
| 200 | ), |
| 201 | "notification requires no ID" |
| 202 | ); |
| 203 | } |
| 204 | Ok(request) |
| 205 | } |
| 206 | |
| 207 | pub(crate) async fn serve<R, W>( |
| 208 | frontend: Arc<dyn RuntimeOwnerFrontend>, |
| 209 | workspace: PathBuf, |
| 210 | lines: crate::stdio::BoundedLines<R>, |
| 211 | mut writer: W, |
| 212 | peer: Arc<crate::daemon_socket::AuthorizedPeer>, |
| 213 | ) -> Result<()> |
| 214 | where |
| 215 | R: AsyncBufRead + Unpin, |
| 216 | W: AsyncWrite + Unpin, |
| 217 | { |
| 218 | let closed = CancellationToken::new(); |
| 219 | let _cancel = closed.clone().drop_guard(); |
| 220 | let (sender, mut receiver) = mpsc::channel::<Queued>(64); |
| 221 | let output = Output { |
| 222 | sender, |
| 223 | bytes: Arc::new(Semaphore::new(MAX_RUNTIME_IMAGE_BODY_BYTES)), |
| 224 | closed: closed.clone(), |
| 225 | }; |
| 226 | let pending = Arc::new(Semaphore::new(64)); |
| 227 | let pending_bytes = Arc::new(Semaphore::new(MAX_RUNTIME_IMAGE_BODY_BYTES)); |
| 228 | let mut lines = |
| 229 | crate::stdio::BoundedLines::with_budget(lines.into_inner(), pending_bytes.clone()); |
| 230 | let mut subscriptions = HashMap::<String, CancellationToken>::new(); |
| 231 | let mut session = crate::connection::ConnectionSession::default(); |
| 232 | let mut initialized = false; |
| 233 | let initialize_deadline = tokio::time::Instant::now() + Duration::from_secs(5); |
| 234 | loop { |
| 235 | tokio::select! { |
| 236 | _=closed.cancelled()=>return Ok(()), |
| 237 | _=tokio::time::sleep_until(initialize_deadline),if !initialized=>anyhow::bail!("native initialize deadline expired"), |
| 238 | queued=receiver.recv()=>{ |
| 239 | let queued=queued.context("native output closed")?; |
| 240 | let check=peer.clone(); |
| 241 | codewhale_runtime::runtime_control::owner_work(move||check.check()).await?; |
| 242 | queued.write(&mut writer).await?; |
| 243 | } |
| 244 | line=lines.next_line()=>{ |
| 245 | let line = match line { |
| 246 | Ok(line) => line, |
| 247 | Err(refusal) if refusal.get_ref().and_then(|source|source.downcast_ref::<crate::stdio::FrameRefusal>()).is_some_and(|failure|matches!(failure,crate::stdio::FrameRefusal::Busy)) => { |
| 248 | output.try_send(error(Value::Null,-32000,"Connection input is full",429,"not_started"))?; |
| 249 | continue; |
| 250 | } |
| 251 | Err(error) => return Err(error.into()), |
| 252 | }; |
| 253 | let Some(line)=line else {return Ok(())}; |
| 254 | let bytes=lines.take_frame_budget(); |
| 255 | let check=peer.clone(); |
| 256 | codewhale_runtime::runtime_control::owner_work(move||check.check()).await?; |
| 257 | let request=match decode_envelope(&line) { |
| 258 | Ok(value)=>value, |
| 259 | Err(_)=>{output.try_send(error(Value::Null,-32600,"Invalid request",400,"not_started"))?;continue;} |
| 260 | }; |
| 261 | let id=json!(request.id); |
| 262 | if request.jsonrpc!="2.0" {output.try_send(error(id,-32600,"Invalid JSON-RPC version",400,"not_started"))?;continue;} |
| 263 | if request.method=="daemon/input_closed" && request.id.is_none() {return Ok(());} |
| 264 | if request.method=="initialized" && request.id.is_none() && session.initialized() && !initialized {initialized=true;continue;} |
| 265 | if request.id.is_none() {continue;} |
| 266 | if request.method=="initialize" { |
| 267 | let response=match session.initialize(request.params) { |
| 268 | Ok(mut response)=>{response["capabilities"]=json!([NATIVE_RUNTIME_CAPABILITY]);result(id,response)}, |
| 269 | Err(_)=>error(id,-32600,"Initialization refused",400,"not_started"), |
| 270 | }; |
| 271 | output.try_send(response)?;continue; |
| 272 | } |
| 273 | if !initialized {output.try_send(error(id,-32600,"Not initialized",400,"not_started"))?;continue;} |
| 274 | if request.method=="capabilities" || request.method=="healthz" { |
| 275 | if request.params!=json!({}) && !request.params.is_null() {output.try_send(error(id,-32602,"Invalid params",400,"not_started"))?;} else {output.try_send(result(id,capabilities()))?;} |
| 276 | continue; |
| 277 | } |
| 278 | let operation:NativeRuntimeRequest=match serde_json::from_value(json!({"method":request.method,"params":request.params})) { |
| 279 | Ok(operation)=>operation, |
| 280 | Err(_)=>{output.try_send(error(id,if NATIVE_RUNTIME_METHODS.contains(&request.method.as_str()) {-32602}else{-32601},"Unsupported method or invalid params",400,"not_started"))?;continue;} |
| 281 | }; |
| 282 | if let NativeRuntimeRequest::Unsubscribe(params)=operation { |
| 283 | let removed=subscriptions.remove(¶ms.subscription_id).map(|token|token.cancel()).is_some(); |
| 284 | output.try_send(result(id,json!({"subscription_id":params.subscription_id,"removed":removed})))?;continue; |
| 285 | } |
| 286 | let permit=match pending.clone().try_acquire_owned() {Ok(permit)=>permit,Err(_)=>{output.try_send(error(id,-32000,"Connection is busy",429,"not_started"))?;continue;}}; |
| 287 | |
| 288 | let subscription=if let NativeRuntimeRequest::Subscribe(params)=&operation { |
| 289 | subscriptions.retain(|_,token|!token.is_cancelled()); |
| 290 | if subscriptions.len()>=16 {output.try_send(error(id,-32000,"Subscription limit reached",429,"not_started"))?;continue;} |
| 291 | let subscription_id=uuid::Uuid::new_v4().to_string(); |
| 292 | let token=closed.child_token(); |
| 293 | subscriptions.insert(subscription_id.clone(),token.clone()); |
| 294 | Some((subscription_id,params.clone(),token)) |
| 295 | }else{None}; |
| 296 | let frontend=frontend.clone();let workspace=workspace.clone();let output=output.clone(); |
| 297 | tokio::spawn(async move { |
| 298 | let _permit=permit;let _bytes=bytes; |
| 299 | let response=frontend.execute(RuntimeOwnerRequest::Native {workspace:workspace.clone(),request:operation}).await; |
| 300 | if let Some((subscription_id,params,token))=subscription { |
| 301 | let _cancel=token.clone().drop_guard(); |
| 302 | let stream=match response { |
| 303 | Ok(_)=>frontend.events_in_workspace(workspace.clone(),params.thread_id.clone(),params.since_seq).await, |
| 304 | Err(error)=>Err(error), |
| 305 | }; |
| 306 | let mut stream=match stream {Ok(stream)=>stream,Err(error)=>{let _=output.send(failed(id,error)).await;return;}}; |
| 307 | if output.send(result(id,json!({"subscription_id":subscription_id,"thread_id":params.thread_id,"since_seq":params.since_seq}))).await.is_err(){return;} |
| 308 | drop(_permit);drop(_bytes); |
| 309 | let last:SentSequence=Arc::new(parking_lot::Mutex::new(None)); |
| 310 | loop { |
| 311 | let frame=tokio::select! {_=token.cancelled()=>return,frame=stream.next()=>match frame {Some(frame)=>frame,None=>return}}; |
| 312 | let valid=frontend.execute(RuntimeOwnerRequest::Native {workspace:workspace.clone(),request:NativeRuntimeRequest::Subscribe(params.clone())}).await; |
| 313 | if valid.is_err() {token.cancel();output.closed.cancel();return;} |
| 314 | let sequence=frame.sequence; |
| 315 | let end=frame.event=="stream.end"; |
| 316 | if output.try_send_tracked(json!({"jsonrpc":"2.0","method":"runtime/event","params":{"subscription_id":subscription_id,"thread_id":params.thread_id,"frame":{"event":frame.event,"data":frame.data,"sequence":sequence}}}),sequence.map(|sequence|(last.clone(),sequence)),None).is_err() { |
| 317 | if output.try_send_tracked(json!({"jsonrpc":"2.0","method":"runtime/events/closed","params":{"subscription_id":subscription_id,"reason":"backpressure","last_sent_sequence":u64::MAX}}),None,Some(last.clone())).is_err(){output.closed.cancel();} |
| 318 | return; |
| 319 | } |
| 320 | if end{return;} |
| 321 | } |
| 322 | } else { |
| 323 | let response=match response {Ok(value)=>result(id,value),Err(error)=>failed(id,error)}; |
| 324 | let _=output.send(response).await; |
| 325 | } |
| 326 | }); |
| 327 | } |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | #[derive(Deserialize)] |
| 333 | #[serde(deny_unknown_fields)] |
| 334 | struct AttachPrelude { |
| 335 | contract_version: u32, |
| 336 | target_id: String, |
| 337 | selection_revision: u64, |
| 338 | workspace: PathBuf, |
| 339 | expect_owner: codewhale_protocol::RuntimeOwnerReceipt, |
| 340 | } |
| 341 | |
| 342 | #[derive(Deserialize)] |
| 343 | #[serde(deny_unknown_fields)] |
| 344 | struct DescribePrelude { |
| 345 | contract_version: u32, |
| 346 | workspace: PathBuf, |
| 347 | expected_pid: u32, |
| 348 | expected_data_dir: PathBuf, |
| 349 | config_path: Option<PathBuf>, |
| 350 | } |
| 351 | |
| 352 | #[cfg(any(unix, windows))] |
| 353 | pub async fn run_attach_only(describe: bool) -> Result<()> { |
| 354 | attach_io( |
| 355 | describe, |
| 356 | tokio::io::BufReader::new(tokio::io::stdin()), |
| 357 | tokio::io::stdout(), |
| 358 | ) |
| 359 | .await |
| 360 | } |
| 361 | |
| 362 | #[cfg(not(any(unix, windows)))] |
| 363 | pub async fn run_attach_only(_describe: bool) -> Result<()> { |
| 364 | anyhow::bail!("native attachment is unavailable on this platform") |
| 365 | } |
| 366 | |
| 367 | #[cfg(any(unix, windows))] |
| 368 | pub async fn attach_io<R, W>(describe: bool, mut input: R, mut output: W) -> Result<()> |
| 369 | where |
| 370 | R: AsyncBufRead + Unpin, |
| 371 | W: AsyncWrite + Unpin, |
| 372 | { |
| 373 | use tokio::io::AsyncReadExt as _; |
| 374 | let mut bytes = Vec::new(); |
| 375 | tokio::time::timeout( |
| 376 | Duration::from_secs(5), |
| 377 | (&mut input).take(16385).read_until(b'\n', &mut bytes), |
| 378 | ) |
| 379 | .await |
| 380 | .context("native attachment prelude deadline expired")??; |
| 381 | anyhow::ensure!( |
| 382 | bytes.len() <= 16384 && bytes.last() == Some(&b'\n'), |
| 383 | "invalid attachment prelude framing" |
| 384 | ); |
| 385 | let envelope: Envelope = serde_json::from_slice(&bytes)?; |
| 386 | anyhow::ensure!( |
| 387 | envelope.jsonrpc == "2.0" && envelope.id.is_some(), |
| 388 | "invalid attachment envelope" |
| 389 | ); |
| 390 | let id = json!(envelope.id); |
| 391 | if describe { |
| 392 | anyhow::ensure!( |
| 393 | envelope.method == "runtime/describe-target", |
| 394 | "target probe prelude required" |
| 395 | ); |
| 396 | let params: DescribePrelude = serde_json::from_value(envelope.params)?; |
| 397 | anyhow::ensure!( |
| 398 | params.contract_version == 1 |
| 399 | && params.expected_pid > 0 |
| 400 | && params.expected_data_dir.is_absolute(), |
| 401 | "invalid target probe selection" |
| 402 | ); |
| 403 | #[cfg(unix)] |
| 404 | let endpoint = |
| 405 | crate::runtime_api::store_selected_control_socket(None, ¶ms.expected_data_dir) |
| 406 | .await?; |
| 407 | #[cfg(windows)] |
| 408 | let endpoint = codewhale_runtime::runtime_control::owner_work(|| { |
| 409 | crate::daemon_socket::default_socket_path().map_err(Into::into) |
| 410 | }) |
| 411 | .await?; |
| 412 | let observed = crate::daemon_client::connect(params.config_path, Some(endpoint)).await?; |
| 413 | anyhow::ensure!( |
| 414 | observed.receipt().pid == params.expected_pid, |
| 415 | "target probe process mismatch" |
| 416 | ); |
| 417 | crate::runtime_api::validate_selected_owner(&observed, params.expected_data_dir).await?; |
| 418 | let receipt = observed.receipt().clone(); |
| 419 | drop(observed); |
| 420 | let mut client = |
| 421 | crate::daemon_client::connect_native(receipt, params.workspace.clone()).await?; |
| 422 | client |
| 423 | .send(json!("native-probe"), "runtime/capabilities", json!({})) |
| 424 | .await?; |
| 425 | let response = tokio::time::timeout(Duration::from_secs(5), client.recv()) |
| 426 | .await |
| 427 | .context("native probe response deadline expired")?? |
| 428 | .context("native probe closed")?; |
| 429 | anyhow::ensure!( |
| 430 | response["id"] == "native-probe" && response.get("error").is_none(), |
| 431 | "native probe refused" |
| 432 | ); |
| 433 | crate::stdio::write_stdio_line(&mut output,&result(id,json!({"contract_version":1,"workspace":params.workspace,"expect_owner":client.receipt(),"capabilities":[NATIVE_RUNTIME_CAPABILITY]}))).await?; |
| 434 | return Ok(()); |
| 435 | } |
| 436 | anyhow::ensure!( |
| 437 | envelope.method == "runtime/attach", |
| 438 | "native attachment prelude required" |
| 439 | ); |
| 440 | let params: AttachPrelude = serde_json::from_value(envelope.params)?; |
| 441 | anyhow::ensure!( |
| 442 | params.contract_version == 1 |
| 443 | && !params.target_id.is_empty() |
| 444 | && params.target_id.len() <= 256 |
| 445 | && params.selection_revision > 0, |
| 446 | "invalid native target binding" |
| 447 | ); |
| 448 | let client = |
| 449 | crate::daemon_client::connect_native(params.expect_owner, params.workspace.clone()).await?; |
| 450 | tokio::time::timeout(Duration::from_secs(5),crate::stdio::write_stdio_line(&mut output,&result(id,json!({"contract_version":1,"target_id":params.target_id,"selection_revision":params.selection_revision,"workspace":params.workspace,"expect_owner":client.receipt(),"capabilities":[NATIVE_RUNTIME_CAPABILITY]})))).await.context("native attach acknowledgement deadline expired")??; |
| 451 | client.forward_native(input, output).await |
| 452 | } |
| 453 | |
| 454 | #[cfg(test)] |
| 455 | mod tests { |
| 456 | use super::*; |
| 457 | |
| 458 | fn output(frames: usize, bytes: usize) -> (Output, mpsc::Receiver<Queued>) { |
| 459 | let (sender, receiver) = mpsc::channel(frames); |
| 460 | ( |
| 461 | Output { |
| 462 | sender, |
| 463 | bytes: Arc::new(Semaphore::new(bytes)), |
| 464 | closed: CancellationToken::new(), |
| 465 | }, |
| 466 | receiver, |
| 467 | ) |
| 468 | } |
| 469 | |
| 470 | #[tokio::test] |
| 471 | async fn native_cursor_advances_only_after_successful_write_and_closed_frame_is_current() { |
| 472 | let (output, mut receiver) = output(4, 4096); |
| 473 | let sequence: SentSequence = Arc::new(parking_lot::Mutex::new(None)); |
| 474 | output |
| 475 | .try_send_tracked(json!({"event":"first"}), Some((sequence.clone(), 42)), None) |
| 476 | .unwrap(); |
| 477 | output |
| 478 | .try_send_tracked( |
| 479 | json!({"params":{"last_sent_sequence":u64::MAX}}), |
| 480 | None, |
| 481 | Some(sequence.clone()), |
| 482 | ) |
| 483 | .unwrap(); |
| 484 | assert_eq!(*sequence.lock(), None); |
| 485 | receiver |
| 486 | .recv() |
| 487 | .await |
| 488 | .unwrap() |
| 489 | .write(&mut tokio::io::sink()) |
| 490 | .await |
| 491 | .unwrap(); |
| 492 | assert_eq!(*sequence.lock(), Some(42)); |
| 493 | let mut terminal = Vec::new(); |
| 494 | receiver |
| 495 | .recv() |
| 496 | .await |
| 497 | .unwrap() |
| 498 | .write(&mut terminal) |
| 499 | .await |
| 500 | .unwrap(); |
| 501 | assert_eq!( |
| 502 | serde_json::from_slice::<Value>(&terminal).unwrap()["params"]["last_sent_sequence"], |
| 503 | 42 |
| 504 | ); |
| 505 | output |
| 506 | .try_send_tracked( |
| 507 | json!({"event":"second"}), |
| 508 | Some((sequence.clone(), 43)), |
| 509 | None, |
| 510 | ) |
| 511 | .unwrap(); |
| 512 | let (mut failed, read) = tokio::io::duplex(64); |
| 513 | drop(read); |
| 514 | assert!( |
| 515 | receiver |
| 516 | .recv() |
| 517 | .await |
| 518 | .unwrap() |
| 519 | .write(&mut failed) |
| 520 | .await |
| 521 | .is_err() |
| 522 | ); |
| 523 | assert_eq!(*sequence.lock(), Some(42)); |
| 524 | assert_eq!(output.bytes.available_permits(), 4096); |
| 525 | } |
| 526 | |
| 527 | #[tokio::test] |
| 528 | async fn native_output_frames_and_bytes_have_independent_bounds() { |
| 529 | let (frames, mut receiver) = output(2, 4096); |
| 530 | frames.try_send(json!({})).unwrap(); |
| 531 | frames.try_send(json!({})).unwrap(); |
| 532 | assert!(frames.try_send(json!({})).is_err()); |
| 533 | drop(receiver.recv().await); |
| 534 | drop(receiver.recv().await); |
| 535 | assert_eq!(frames.bytes.available_permits(), 4096); |
| 536 | let (bytes, mut receiver) = output(64, 2); |
| 537 | bytes.try_send(json!({})).unwrap(); |
| 538 | assert!(bytes.try_send(json!({})).is_err()); |
| 539 | drop(receiver.recv().await); |
| 540 | assert_eq!(bytes.bytes.available_permits(), 2); |
| 541 | } |
| 542 | } |
| 543 |