-
Notifications
You must be signed in to change notification settings - Fork 246
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add example of a streaming response (#1862)
* Add example of a streaming response * Add model example * Resolve build / lint issues
- Loading branch information
Showing
4 changed files
with
139 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
124 changes: 124 additions & 0 deletions
124
sdk/typespec/typespec_client_core/examples/stream_response.rs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT License. | ||
|
||
use futures::StreamExt; | ||
|
||
#[tokio::main] | ||
async fn main() -> Result<(), Box<dyn std::error::Error>> { | ||
// Get a response from a service client. | ||
let response = client::get_binary_data_response()?; | ||
|
||
// Normally you'd deserialize into a type or `collect()` the body, | ||
// but this better simulates fetching multiple chunks from a slow response. | ||
let mut body = response.into_body(); | ||
while let Some(data) = body.next().await { | ||
// Assume bytes are a string in this example. | ||
let page = String::from_utf8(data?.into())?; | ||
println!("{page}"); | ||
} | ||
|
||
// You can also deserialize into a model from a slow response. | ||
let team = client::get_model_response()?.deserialize_body().await?; | ||
println!("{team:#?}"); | ||
|
||
Ok(()) | ||
} | ||
|
||
#[allow(dead_code)] | ||
mod client { | ||
use futures::Stream; | ||
use serde::Deserialize; | ||
use std::{cmp::min, task::Poll, time::Duration}; | ||
use typespec_client_core::{ | ||
http::{headers::Headers, Model, Response, StatusCode}, | ||
Bytes, | ||
}; | ||
|
||
#[derive(Debug, Model, Deserialize)] | ||
pub struct Team { | ||
pub name: Option<String>, | ||
#[serde(default)] | ||
pub members: Vec<Person>, | ||
} | ||
|
||
#[derive(Debug, Model, Deserialize)] | ||
pub struct Person { | ||
pub id: u32, | ||
pub name: Option<String>, | ||
} | ||
|
||
pub fn get_binary_data_response() -> typespec_client_core::Result<Response<()>> { | ||
let bytes = Bytes::from_static(b"Hello, world!"); | ||
let response = SlowResponse { | ||
bytes: bytes.repeat(5).into(), | ||
bytes_per_read: bytes.len(), | ||
bytes_read: 0, | ||
}; | ||
|
||
Ok(Response::new( | ||
StatusCode::Ok, | ||
Headers::new(), | ||
Box::pin(response), | ||
)) | ||
} | ||
|
||
pub fn get_model_response() -> typespec_client_core::Result<Response<Team>> { | ||
let bytes = br#"{ | ||
"name": "Contoso Dev Team", | ||
"members": [ | ||
{ | ||
"id": 1234, | ||
"name": "Jan" | ||
}, | ||
{ | ||
"id": 5678, | ||
"name": "Bill" | ||
} | ||
] | ||
}"#; | ||
let response = SlowResponse { | ||
bytes: Bytes::from_static(bytes), | ||
bytes_per_read: 64, | ||
bytes_read: 0, | ||
}; | ||
|
||
Ok(Response::new( | ||
StatusCode::Ok, | ||
Headers::new(), | ||
Box::pin(response), | ||
)) | ||
} | ||
|
||
struct SlowResponse { | ||
bytes: Bytes, | ||
bytes_per_read: usize, | ||
bytes_read: usize, | ||
} | ||
|
||
impl Stream for SlowResponse { | ||
type Item = typespec_client_core::Result<Bytes>; | ||
|
||
fn poll_next( | ||
self: std::pin::Pin<&mut Self>, | ||
_cx: &mut std::task::Context<'_>, | ||
) -> Poll<Option<Self::Item>> { | ||
let self_mut = self.get_mut(); | ||
if self_mut.bytes_read < self_mut.bytes.len() { | ||
eprintln!("getting partial response..."); | ||
std::thread::sleep(Duration::from_millis(200)); | ||
|
||
let end = self_mut.bytes_read | ||
+ min( | ||
self_mut.bytes_per_read, | ||
self_mut.bytes.len() - self_mut.bytes_read, | ||
); | ||
let bytes = self_mut.bytes.slice(self_mut.bytes_read..end); | ||
self_mut.bytes_read += bytes.len(); | ||
Poll::Ready(Some(Ok(bytes))) | ||
} else { | ||
eprintln!("done"); | ||
Poll::Ready(None) | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters