mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 11:42:17 +00:00
test(cli-rs): prove API requests and decoding against the TS client
A P-ORACLE fixture records the requests the TypeScript Promise client builds; the generated Rust client must build the same ones, and query::append must match appendQuery. Unit tests cover tagged unions (known, rpc.*, unknown), literal enums, double options, declared errors, binary bodies, auth, and the event stream through F.3's SSE reader.
This commit is contained in:
parent
a477234497
commit
34e9ec7d47
8 changed files with 1375 additions and 25 deletions
|
|
@ -48,6 +48,16 @@ impl Error {
|
|||
}
|
||||
}
|
||||
|
||||
impl From<crate::sse::Error> for Error {
|
||||
fn from(error: crate::sse::Error) -> Self {
|
||||
match error {
|
||||
crate::sse::Error::Transport(cause) => Self::Transport(cause),
|
||||
crate::sse::Error::MalformedResponse(cause) => Self::MalformedResponse(cause),
|
||||
crate::sse::Error::EventTooLarge => Self::SseEventTooLarge,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A declared error body. The tag is `_tag`, else `name`; the message is `message`, else `data.message`,
|
||||
/// as `declared` in the TypeScript client.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
|
|
@ -6,6 +6,10 @@ use std::pin::Pin;
|
|||
|
||||
use bytes::Bytes;
|
||||
use futures_util::{Stream, StreamExt};
|
||||
use serde::de::DeserializeOwned;
|
||||
|
||||
use crate::error::Error;
|
||||
use crate::generated::V2Event;
|
||||
|
||||
/// A future a transport returns.
|
||||
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
|
||||
|
|
@ -80,6 +84,24 @@ impl<T> SseResponse<T> {
|
|||
}
|
||||
}
|
||||
|
||||
impl<T: DeserializeOwned + Send> SseResponse<T> {
|
||||
/// The events, decoded by [`crate::sse::events`]. `activity` runs for every received chunk,
|
||||
/// keepalive comments included. The stream ends after the first error.
|
||||
pub fn events(
|
||||
self,
|
||||
activity: impl FnMut() + Send + 'static,
|
||||
) -> impl Stream<Item = Result<T, Error>> + Send {
|
||||
crate::sse::events(self.response.body, activity).map(|item| item.map_err(Error::from))
|
||||
}
|
||||
}
|
||||
|
||||
/// Lets F.3's connection loop and shared subscription carry the generated event type.
|
||||
impl crate::events::Event for V2Event {
|
||||
fn kind(&self) -> &str {
|
||||
self.tag()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> std::fmt::Debug for SseResponse<T> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_tuple("SseResponse").field(&self.response).finish()
|
||||
|
|
|
|||
217
packages/cli-rs/crates/api/tests/api.rs
Normal file
217
packages/cli-rs/crates/api/tests/api.rs
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
//! Decoding rules of docs/F.2.md and the request core, over a scripted transport.
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use bytes::Bytes;
|
||||
use futures_util::StreamExt;
|
||||
use opencode_api::client::{Auth, Client, RequestOptions};
|
||||
use opencode_api::error::Error;
|
||||
use opencode_api::events::Event;
|
||||
use opencode_api::generated::*;
|
||||
use opencode_api::transport::{BoxFuture, Request, Response, Transport};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Answers every request with one canned response and records the requests.
|
||||
struct Script {
|
||||
status: u16,
|
||||
content_type: &'static str,
|
||||
body: Vec<u8>,
|
||||
requests: Mutex<Vec<Request>>,
|
||||
}
|
||||
|
||||
impl Script {
|
||||
fn new(status: u16, content_type: &'static str, body: impl Into<Vec<u8>>) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
status,
|
||||
content_type,
|
||||
body: body.into(),
|
||||
requests: Mutex::default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Transport for Script {
|
||||
fn send(&self, request: Request) -> BoxFuture<'_, Result<Response, String>> {
|
||||
self.requests.lock().unwrap().push(request);
|
||||
// Two chunks, so readers cannot assume one.
|
||||
let (head, tail) = self.body.split_at(self.body.len() / 2);
|
||||
let chunks = vec![Ok(Bytes::copy_from_slice(head)), Ok(Bytes::copy_from_slice(tail))];
|
||||
let response = Response {
|
||||
status: self.status,
|
||||
headers: vec![("content-type".to_owned(), self.content_type.to_owned())],
|
||||
body: Box::pin(futures_util::stream::iter(chunks)),
|
||||
};
|
||||
Box::pin(async move { Ok(response) })
|
||||
}
|
||||
}
|
||||
|
||||
fn client(script: &Arc<Script>) -> Client {
|
||||
Client::with_transport("http://127.0.0.1:4096", script.clone()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tagged_union_decodes_known_rpc_and_unknown_members() {
|
||||
let connected: V2Event =
|
||||
serde_json::from_value(json!({ "id": "evt_1", "type": "server.connected", "data": {} })).unwrap();
|
||||
assert!(matches!(connected, V2Event::ServerConnected(_)), "{connected:?}");
|
||||
assert_eq!(connected.kind(), "server.connected");
|
||||
|
||||
let rpc = json!({
|
||||
"id": "evt_2", "created": 1.5, "type": "rpc.plugin.ping",
|
||||
"location": { "directory": "/w" }, "data": { "a": 1 }
|
||||
});
|
||||
let decoded: V2Event = serde_json::from_value(rpc.clone()).unwrap();
|
||||
let V2Event::Rpc(event) = &decoded else { panic!("{decoded:?}") };
|
||||
assert_eq!(event.r#type, "rpc.plugin.ping");
|
||||
assert_eq!(event.data["a"], json!(1));
|
||||
assert_eq!(decoded.tag(), "rpc.plugin.ping");
|
||||
assert_eq!(serde_json::to_value(&decoded).unwrap(), rpc);
|
||||
|
||||
// An unknown tag keeps its payload, and serializes back unchanged.
|
||||
let future = json!({ "type": "future.event", "data": { "x": [1, 2] } });
|
||||
let decoded: V2Event = serde_json::from_value(future.clone()).unwrap();
|
||||
assert_eq!(decoded, V2Event::Unknown(future.clone()));
|
||||
assert_eq!(decoded.tag(), "future.event");
|
||||
assert_eq!(serde_json::to_value(&decoded).unwrap(), future);
|
||||
|
||||
// No tag at all is unknown too; a known tag with a broken payload is an error.
|
||||
assert_eq!(serde_json::from_value::<V2Event>(json!({})).unwrap(), V2Event::Unknown(json!({})));
|
||||
let error = serde_json::from_value::<V2Event>(json!({ "type": "server.connected" })).unwrap_err();
|
||||
assert!(error.to_string().contains("missing field"), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tagged_union_ignores_unknown_fields() {
|
||||
let event: V2Event = serde_json::from_value(
|
||||
json!({ "id": "evt_1", "type": "server.connected", "data": {}, "added": "later" }),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(matches!(event, V2Event::ServerConnected(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_enum_keeps_unknown_values() {
|
||||
let order: SessionListInputOrder = serde_json::from_value(json!("sideways")).unwrap();
|
||||
assert_eq!(order, SessionListInputOrder::Unknown("sideways".to_owned()));
|
||||
assert_eq!(serde_json::to_value(&order).unwrap(), json!("sideways"));
|
||||
let desc: SessionListInputOrder = serde_json::from_value(json!("desc")).unwrap();
|
||||
assert_eq!(desc, SessionListInputOrder::Desc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn optional_nullable_fields_keep_absent_and_null_apart() {
|
||||
let decode = |value: Value| serde_json::from_value::<SessionsResponseCursor>(value).unwrap();
|
||||
assert_eq!(decode(json!({})).previous, None);
|
||||
assert_eq!(decode(json!({ "previous": null })).previous, Some(None));
|
||||
assert!(matches!(decode(json!({ "previous": "c1" })).previous, Some(Some(_))));
|
||||
assert_eq!(serde_json::to_value(decode(json!({ "previous": null }))).unwrap()["previous"], Value::Null);
|
||||
assert!(serde_json::to_value(decode(json!({}))).unwrap().get("previous").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn data_envelope_is_unwrapped() {
|
||||
let script = Script::new(200, "application/json", r#"{"data":{"ses_1":{"type":"busy"}}}"#);
|
||||
let active = client(&script).session_active(&RequestOptions::default()).await.unwrap();
|
||||
assert_eq!(active["ses_1"].r#type, "busy");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn declared_errors_decode_and_other_statuses_do_not() {
|
||||
let body = r#"{"_tag":"SessionNotFoundError","message":"Session not found: ses_1","sessionID":"ses_1"}"#;
|
||||
let script = Script::new(404, "application/json; charset=utf-8", body);
|
||||
let input = SessionGetInput { session_id: "ses_1".into() };
|
||||
let error = client(&script).session_get(&input, &RequestOptions::default()).await.unwrap_err();
|
||||
let declared = error.declared().expect("declared");
|
||||
assert_eq!((declared.status, declared.tag.as_deref()), (404, Some("SessionNotFoundError")));
|
||||
assert_eq!(declared.message.as_deref(), Some("Session not found: ses_1"));
|
||||
assert_eq!(error.reason(), "SessionNotFoundError");
|
||||
assert_eq!(declared.decode::<Value>().unwrap()["sessionID"], "ses_1");
|
||||
|
||||
let script = Script::new(502, "text/plain", "bad gateway");
|
||||
let error = client(&script).session_get(&input, &RequestOptions::default()).await.unwrap_err();
|
||||
assert!(matches!(error, Error::UnexpectedStatus { status: 502 }), "{error:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn content_type_and_empty_bodies_are_checked() {
|
||||
let script = Script::new(200, "text/html", "<html>");
|
||||
let error = client(&script).session_active(&RequestOptions::default()).await.unwrap_err();
|
||||
assert!(matches!(error, Error::UnsupportedContentType(Some(ref value)) if value == "text/html"), "{error:?}");
|
||||
|
||||
let script = Script::new(200, "application/json", "");
|
||||
let error = client(&script).session_active(&RequestOptions::default()).await.unwrap_err();
|
||||
assert!(matches!(error, Error::MalformedResponse(_)), "{error:?}");
|
||||
|
||||
// A schema mismatch names the field that failed.
|
||||
let script = Script::new(200, "application/json", r#"{"data":{"ses_1":{"type":7}}}"#);
|
||||
let error = client(&script).session_active(&RequestOptions::default()).await.unwrap_err();
|
||||
assert!(error.to_string().contains("data.ses_1.type"), "{error}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn binary_endpoints_return_and_send_bytes() {
|
||||
let script = Script::new(200, "image/png", vec![0x89, b'P', b'N', b'G', 0, 255]);
|
||||
let input = ExperimentalMediaGetInput { hash: "abc".into() };
|
||||
let bytes = client(&script).experimental_media_get(&input, &RequestOptions::default()).await.unwrap();
|
||||
assert_eq!(bytes.as_ref(), &[0x89, b'P', b'N', b'G', 0, 255]);
|
||||
|
||||
let script = Script::new(200, "application/json", r#"{"ok":true}"#);
|
||||
let input = ExperimentalFileWriteInput {
|
||||
location: None,
|
||||
path: "a.bin".to_owned(),
|
||||
payload: Bytes::from_static(&[0, 1, 2]),
|
||||
};
|
||||
let _ = client(&script).experimental_file_write(&input, &RequestOptions::default()).await;
|
||||
let request = script.requests.lock().unwrap().pop().unwrap();
|
||||
assert_eq!(request.body.as_deref(), Some(&[0, 1, 2][..]));
|
||||
assert!(request.headers.contains(&("content-type".to_owned(), "application/octet-stream".to_owned())));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn headers_layer_client_input_then_call() {
|
||||
let script = Script::new(200, "text/plain", "");
|
||||
let client = client(&script).auth(Auth::password("secret")).header("X-Client", "a").header("x-call", "client");
|
||||
let input = SessionRemoveInput { session_id: "ses_1".into() };
|
||||
let options = RequestOptions::default().header("X-Call", "call");
|
||||
client.session_remove(&input, &options).await.unwrap();
|
||||
let request = script.requests.lock().unwrap().pop().unwrap();
|
||||
let header = |name: &str| request.headers.iter().find(|(key, _)| key == name).map(|(_, value)| value.as_str());
|
||||
assert_eq!(header("authorization"), Some("Basic b3BlbmNvZGU6c2VjcmV0"));
|
||||
assert_eq!(header("x-client"), Some("a"));
|
||||
assert_eq!(header("x-call"), Some("call"));
|
||||
assert_eq!(request.headers.iter().filter(|(key, _)| key == "x-call").count(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn query_auth_puts_the_token_in_the_url() {
|
||||
let script = Script::new(200, "text/plain", "");
|
||||
let client = client(&script).auth(Auth::Query {
|
||||
username: "opencode".to_owned(),
|
||||
password: "secret".to_owned(),
|
||||
});
|
||||
let input = SessionRemoveInput { session_id: "ses_1".into() };
|
||||
client.session_remove(&input, &RequestOptions::default()).await.unwrap();
|
||||
let request = script.requests.lock().unwrap().pop().unwrap();
|
||||
assert_eq!(request.url.query(), Some("auth_token=b3BlbmNvZGU6c2VjcmV0"));
|
||||
assert!(!request.headers.iter().any(|(key, _)| key == "authorization"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn event_stream_decodes_generated_events() {
|
||||
let body = "data: {\"id\":\"e1\",\"type\":\"server.connected\",\"data\":{}}\n\n: keepalive\n\ndata: {\"type\":\"future.event\"}\n\n";
|
||||
let script = Script::new(200, "text/event-stream", body);
|
||||
let response = client(&script)
|
||||
.event_subscribe(&EventSubscribeInput::default(), &RequestOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let events: Vec<_> = response.events(|| {}).collect().await;
|
||||
let kinds: Vec<_> = events.iter().map(|event| event.as_ref().unwrap().kind().to_owned()).collect();
|
||||
assert_eq!(kinds, ["server.connected", "future.event"]);
|
||||
|
||||
let script = Script::new(200, "application/json", "{}");
|
||||
let error = client(&script)
|
||||
.event_subscribe(&EventSubscribeInput::default(), &RequestOptions::default())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, Error::UnsupportedContentType(_)), "{error:?}");
|
||||
}
|
||||
144
packages/cli-rs/crates/api/tests/oracle.rs
Normal file
144
packages/cli-rs/crates/api/tests/oracle.rs
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
//! P-ORACLE: the generated client builds the same requests as the TypeScript Promise client.
|
||||
//! `parity/oracle/F.2-requests.ts` records the TypeScript side into `parity/fixtures/F.2/requests.json`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use base64::Engine;
|
||||
use opencode_api::client::{Auth, Client, RequestOptions};
|
||||
use opencode_api::generated::*;
|
||||
use opencode_api::query;
|
||||
use opencode_api::transport::{BoxFuture, Request, Response, Transport};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Records every request and fails it, as the TypeScript oracle's fetch does.
|
||||
#[derive(Default)]
|
||||
struct Record(Mutex<Vec<Request>>);
|
||||
|
||||
impl Transport for Record {
|
||||
fn send(&self, request: Request) -> BoxFuture<'_, Result<Response, String>> {
|
||||
self.0.lock().unwrap().push(request);
|
||||
Box::pin(async { Err("recorded".to_owned()) })
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture() -> Value {
|
||||
serde_json::from_str(include_str!("../../../parity/fixtures/F.2/requests.json")).unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn requests_match_the_typescript_client() {
|
||||
let record = Arc::new(Record::default());
|
||||
let client = Client::with_transport("http://127.0.0.1:4096/prefix", record.clone())
|
||||
.unwrap()
|
||||
.auth(Auth::Basic {
|
||||
username: "opencode".to_owned(),
|
||||
password: "secret".to_owned(),
|
||||
});
|
||||
let none = RequestOptions::default();
|
||||
let location = |directory: &str| {
|
||||
Some(LocationQueryInput {
|
||||
directory: Some(directory.to_owned()),
|
||||
})
|
||||
};
|
||||
let _ = client
|
||||
.config_get(&ConfigGetInput { location: location("/tmp/a b&c=d") }, &none)
|
||||
.await;
|
||||
let _ = client
|
||||
.session_list(
|
||||
&SessionListInput {
|
||||
limit: Some(5),
|
||||
order: Some(SessionListInputOrder::Desc),
|
||||
search: Some("héllo wörld+?".to_owned()),
|
||||
parent_id: Some(None),
|
||||
archived: Some(false),
|
||||
..Default::default()
|
||||
},
|
||||
&none,
|
||||
)
|
||||
.await;
|
||||
let _ = client
|
||||
.session_get(
|
||||
&SessionGetInput { session_id: "ses_1 /?#%".into() },
|
||||
&RequestOptions::default().header("X-Opencode-Directory", "/override"),
|
||||
)
|
||||
.await;
|
||||
let _ = client
|
||||
.file_read(
|
||||
&FileReadInput {
|
||||
location: location("/w"),
|
||||
path: "dir/a b/c#?.txt".to_owned(),
|
||||
},
|
||||
&none,
|
||||
)
|
||||
.await;
|
||||
let _ = client
|
||||
.session_prompt(
|
||||
&SessionPromptInput {
|
||||
session_id: "ses_1".into(),
|
||||
id: None,
|
||||
text: "hi".to_owned(),
|
||||
files: None,
|
||||
agents: None,
|
||||
skills: None,
|
||||
metadata: Some(BTreeMap::from([("k".to_owned(), json!(1))])),
|
||||
delivery: None,
|
||||
resume: Some(None),
|
||||
},
|
||||
&none,
|
||||
)
|
||||
.await;
|
||||
let _ = client
|
||||
.experimental_file_write(
|
||||
&ExperimentalFileWriteInput {
|
||||
location: None,
|
||||
path: "a.txt".to_owned(),
|
||||
payload: bytes::Bytes::from_static(&[1, 2, 255]),
|
||||
},
|
||||
&none,
|
||||
)
|
||||
.await;
|
||||
let _ = client
|
||||
.event_subscribe(
|
||||
&EventSubscribeInput {
|
||||
types: Some(vec!["session.created".to_owned(), "rpc.x".to_owned()]),
|
||||
},
|
||||
&none,
|
||||
)
|
||||
.await;
|
||||
let _ = client
|
||||
.session_remove(&SessionRemoveInput { session_id: "ses_2".into() }, &none)
|
||||
.await;
|
||||
|
||||
let actual = record.0.lock().unwrap();
|
||||
let expected = fixture()["requests"].as_array().unwrap().clone();
|
||||
assert_eq!(actual.len(), expected.len());
|
||||
for (request, expected) in actual.iter().zip(expected) {
|
||||
let name = expected["name"].as_str().unwrap();
|
||||
assert_eq!(request.method, expected["method"], "{name}: method");
|
||||
assert_eq!(request.url.as_str(), expected["url"], "{name}: url");
|
||||
let headers: BTreeMap<_, _> = request.headers.iter().cloned().collect();
|
||||
let wanted: BTreeMap<String, String> = serde_json::from_value(expected["headers"].clone()).unwrap();
|
||||
assert_eq!(headers, wanted, "{name}: headers");
|
||||
let body = request.body.as_ref();
|
||||
match (&expected["body"], &expected["bodyBase64"]) {
|
||||
(Value::String(text), _) => {
|
||||
assert_eq!(body.map(|body| String::from_utf8_lossy(body).into_owned()).as_deref(), Some(text.as_str()), "{name}: body")
|
||||
}
|
||||
(_, Value::String(encoded)) => {
|
||||
let bytes = base64::engine::general_purpose::STANDARD.decode(encoded).unwrap();
|
||||
assert_eq!(body.map(|body| body.to_vec()), Some(bytes), "{name}: body")
|
||||
}
|
||||
_ => assert!(body.is_none(), "{name}: no body"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_values_match_append_query() {
|
||||
for case in fixture()["query"].as_array().unwrap() {
|
||||
let mut pairs = Vec::new();
|
||||
query::append(&mut pairs, "location", &case["value"]);
|
||||
assert_eq!(query::encode(&pairs), case["search"].as_str().unwrap(), "{}", case["value"]);
|
||||
}
|
||||
}
|
||||
158
packages/cli-rs/parity/fixtures/F.2/requests.json
vendored
Normal file
158
packages/cli-rs/parity/fixtures/F.2/requests.json
vendored
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
{
|
||||
"requests": [
|
||||
{
|
||||
"name": "config.get",
|
||||
"method": "GET",
|
||||
"url": "http://127.0.0.1:4096/prefix/api/config?location%5Bdirectory%5D=%2Ftmp%2Fa+b%26c%3Dd",
|
||||
"headers": {
|
||||
"authorization": "Basic b3BlbmNvZGU6c2VjcmV0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "session.list",
|
||||
"method": "GET",
|
||||
"url": "http://127.0.0.1:4096/prefix/api/session?limit=5&order=desc&search=h%C3%A9llo+w%C3%B6rld%2B%3F&parentID=null&archived=false",
|
||||
"headers": {
|
||||
"authorization": "Basic b3BlbmNvZGU6c2VjcmV0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "session.get",
|
||||
"method": "GET",
|
||||
"url": "http://127.0.0.1:4096/prefix/api/session/ses_1%20%2F%3F%23%25",
|
||||
"headers": {
|
||||
"authorization": "Basic b3BlbmNvZGU6c2VjcmV0",
|
||||
"x-opencode-directory": "/override"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "file.read",
|
||||
"method": "GET",
|
||||
"url": "http://127.0.0.1:4096/prefix/api/fs/read/dir/a%20b/c%23%3F.txt?location%5Bdirectory%5D=%2Fw",
|
||||
"headers": {
|
||||
"authorization": "Basic b3BlbmNvZGU6c2VjcmV0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "session.prompt",
|
||||
"method": "POST",
|
||||
"url": "http://127.0.0.1:4096/prefix/api/session/ses_1/prompt",
|
||||
"headers": {
|
||||
"authorization": "Basic b3BlbmNvZGU6c2VjcmV0",
|
||||
"content-type": "application/json"
|
||||
},
|
||||
"body": "{\"text\":\"hi\",\"metadata\":{\"k\":1},\"resume\":null}"
|
||||
},
|
||||
{
|
||||
"name": "experimental.file.write",
|
||||
"method": "POST",
|
||||
"url": "http://127.0.0.1:4096/prefix/api/experimental/fs/write?path=a.txt",
|
||||
"headers": {
|
||||
"authorization": "Basic b3BlbmNvZGU6c2VjcmV0",
|
||||
"content-type": "application/octet-stream"
|
||||
},
|
||||
"bodyBase64": "AQL/"
|
||||
},
|
||||
{
|
||||
"name": "event.subscribe",
|
||||
"method": "GET",
|
||||
"url": "http://127.0.0.1:4096/prefix/api/event?types=session.created&types=rpc.x",
|
||||
"headers": {
|
||||
"authorization": "Basic b3BlbmNvZGU6c2VjcmV0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "session.remove",
|
||||
"method": "DELETE",
|
||||
"url": "http://127.0.0.1:4096/prefix/api/session/ses_2",
|
||||
"headers": {
|
||||
"authorization": "Basic b3BlbmNvZGU6c2VjcmV0"
|
||||
}
|
||||
}
|
||||
],
|
||||
"query": [
|
||||
{
|
||||
"value": {
|
||||
"directory": "a"
|
||||
},
|
||||
"search": "location%5Bdirectory%5D=a"
|
||||
},
|
||||
{
|
||||
"value": {
|
||||
"a": {
|
||||
"b": {
|
||||
"c": "d"
|
||||
}
|
||||
}
|
||||
},
|
||||
"search": "location%5Ba%5D%5Bb%5D%5Bc%5D=d"
|
||||
},
|
||||
{
|
||||
"value": [
|
||||
"x",
|
||||
"y"
|
||||
],
|
||||
"search": "location=x&location=y"
|
||||
},
|
||||
{
|
||||
"value": null,
|
||||
"search": "location=null"
|
||||
},
|
||||
{
|
||||
"value": 1,
|
||||
"search": "location=1"
|
||||
},
|
||||
{
|
||||
"value": 1.5,
|
||||
"search": "location=1.5"
|
||||
},
|
||||
{
|
||||
"value": 1e+21,
|
||||
"search": "location=1e%2B21"
|
||||
},
|
||||
{
|
||||
"value": 1e-7,
|
||||
"search": "location=1e-7"
|
||||
},
|
||||
{
|
||||
"value": 0.000001,
|
||||
"search": "location=0.000001"
|
||||
},
|
||||
{
|
||||
"value": 0,
|
||||
"search": "location=0"
|
||||
},
|
||||
{
|
||||
"value": 123456789012,
|
||||
"search": "location=123456789012"
|
||||
},
|
||||
{
|
||||
"value": true,
|
||||
"search": "location=true"
|
||||
},
|
||||
{
|
||||
"value": false,
|
||||
"search": "location=false"
|
||||
},
|
||||
{
|
||||
"value": "ü ✓ & = + % # / ? ~*'()!",
|
||||
"search": "location=%C3%BC+%E2%9C%93+%26+%3D+%2B+%25+%23+%2F+%3F+%7E*%27%28%29%21"
|
||||
},
|
||||
{
|
||||
"value": {
|
||||
"list": [
|
||||
1,
|
||||
{
|
||||
"x": 2
|
||||
}
|
||||
],
|
||||
"empty": []
|
||||
},
|
||||
"search": "location%5Blist%5D=1&location%5Blist%5D%5Bx%5D=2"
|
||||
},
|
||||
{
|
||||
"value": "",
|
||||
"search": "location="
|
||||
}
|
||||
]
|
||||
}
|
||||
93
packages/cli-rs/parity/oracle/F.2-requests.ts
Normal file
93
packages/cli-rs/parity/oracle/F.2-requests.ts
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
// P-ORACLE for F.2: records the requests the TypeScript Promise client builds, for
|
||||
// crates/api/tests/oracle.rs to compare with the generated Rust client. Writes parity/fixtures/F.2/requests.json.
|
||||
// The raw generated client: the exported `OpenCode.make` wraps it (one shared event subscription without
|
||||
// input), and the Rust generated client corresponds to the raw one. The package exports do not expose it.
|
||||
import { make } from "../../../client/src/promise/generated/client.ts"
|
||||
|
||||
type Recorded = {
|
||||
name: string
|
||||
method: string
|
||||
url: string
|
||||
headers: Record<string, string>
|
||||
body?: string
|
||||
bodyBase64?: string
|
||||
}
|
||||
|
||||
const recorded: Array<Recorded> = []
|
||||
let current = ""
|
||||
const client = make({
|
||||
baseUrl: "http://127.0.0.1:4096/prefix",
|
||||
headers: { authorization: "Basic b3BlbmNvZGU6c2VjcmV0" },
|
||||
fetch: (async (url: URL, init: RequestInit) => {
|
||||
const headers = Object.fromEntries(new Headers(init.headers))
|
||||
const body = init.body
|
||||
recorded.push({
|
||||
name: current,
|
||||
method: init.method ?? "GET",
|
||||
url: String(url),
|
||||
headers,
|
||||
...(typeof body === "string" ? { body } : {}),
|
||||
...(body instanceof Uint8Array ? { bodyBase64: Buffer.from(body).toString("base64") } : {}),
|
||||
})
|
||||
throw new Error("recorded")
|
||||
}) as typeof fetch,
|
||||
})
|
||||
|
||||
const call = async (name: string, run: () => Promise<unknown> | AsyncIterable<unknown>) => {
|
||||
current = name
|
||||
const result = run()
|
||||
try {
|
||||
if (Symbol.asyncIterator in result) for await (const _ of result) break
|
||||
else await result
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Typed calls; crates/api/tests/oracle.rs makes the same calls with the same values.
|
||||
await call("config.get", () => client.config.get({ location: { directory: "/tmp/a b&c=d" } }))
|
||||
await call("session.list", () =>
|
||||
client.session.list({ limit: 5, order: "desc", search: "héllo wörld+?", parentID: null, archived: false }),
|
||||
)
|
||||
await call("session.get", () =>
|
||||
client.session.get({ sessionID: "ses_1 /?#%" }, { headers: { "X-Opencode-Directory": "/override" } }),
|
||||
)
|
||||
await call("file.read", () => client.file.read({ path: "dir/a b/c#?.txt", location: { directory: "/w" } }))
|
||||
await call("session.prompt", () =>
|
||||
client.session.prompt({ sessionID: "ses_1", text: "hi", resume: null, metadata: { k: 1 } }),
|
||||
)
|
||||
await call("experimental.file.write", () =>
|
||||
client.experimental.file.write({ path: "a.txt", payload: new Uint8Array([1, 2, 255]) }),
|
||||
)
|
||||
await call("event.subscribe", () => client.event.subscribe({ types: ["session.created", "rpc.x"] }))
|
||||
await call("session.remove", () => client.session.remove({ sessionID: "ses_2" }))
|
||||
|
||||
const requests = recorded.slice()
|
||||
|
||||
// appendQuery over values the types do not limit; the Rust side feeds them to query::append.
|
||||
const values: Array<unknown> = [
|
||||
{ directory: "a" },
|
||||
{ a: { b: { c: "d" } } },
|
||||
["x", "y"],
|
||||
null,
|
||||
1,
|
||||
1.5,
|
||||
1e21,
|
||||
1e-7,
|
||||
0.000001,
|
||||
-0,
|
||||
123456789012,
|
||||
true,
|
||||
false,
|
||||
"ü ✓ & = + % # / ? ~*'()!",
|
||||
{ list: [1, { x: 2 }], empty: [] },
|
||||
"",
|
||||
]
|
||||
const query = values.map((value) => {
|
||||
recorded.length = 0
|
||||
void client.config.get({ location: value } as never).catch(() => {})
|
||||
return { value, search: new URL(recorded[0].url).search.slice(1) }
|
||||
})
|
||||
|
||||
await Bun.write(
|
||||
new URL("../fixtures/F.2/requests.json", import.meta.url),
|
||||
JSON.stringify({ requests, query }, null, 2) + "\n",
|
||||
)
|
||||
|
|
@ -89,6 +89,8 @@ export class Types {
|
|||
case "Never":
|
||||
return "()"
|
||||
case "Objects":
|
||||
// An empty object says nothing about its role, so it keeps its own name instead of sharing one.
|
||||
if (r.propertySignatures.length === 0 && r.indexSignatures.length === 0) return this.objects(r, this.name(hint), hint)
|
||||
return this.shaped(r, () => this.objects(r, this.name(hint), hint))
|
||||
case "Arrays":
|
||||
return this.arrays(r, hint)
|
||||
|
|
@ -232,7 +234,7 @@ export class Types {
|
|||
return wrap(values.every(Number.isInteger) ? "i64" : "f64")
|
||||
return wrap("serde_json::Value")
|
||||
}
|
||||
if (resolved.every((member) => member._tag === "Literal" || member._tag === "String")) return wrap("String")
|
||||
if (resolved.every((member) => ["Literal", "String", "TemplateLiteral"].includes(member._tag))) return wrap("String")
|
||||
if (resolved.every((member) => member._tag === "Objects")) {
|
||||
const tagged = this.discriminator(resolved as Array<Objects>)
|
||||
if (tagged !== undefined) return wrap(this.tagged(rest, tagged, ref ?? hint, ref))
|
||||
|
|
@ -324,9 +326,13 @@ export class Types {
|
|||
),
|
||||
])
|
||||
const ordered = [...arms.filter((arm) => !arm.includes("starts_with")), ...arms.filter((arm) => arm.includes("starts_with"))]
|
||||
const tagMethod =
|
||||
kind === "boolean"
|
||||
? ""
|
||||
: `\n\nimpl ${name} {\n /// The \`${tag.key}\` tag, also of an unknown member.\n pub fn tag(&self) -> &str {\n match self {\n${variants.map((variant) => ` Self::${variant}(value) => value.${snake(tag.key)}.as_str(),`).join("\n")}\n Self::Unknown(value) => value.get(${JSON.stringify(tag.key)}).and_then(serde_json::Value::as_str).unwrap_or_default(),\n }\n }\n}`
|
||||
const doc = ref === undefined ? "" : `/// \`${ref}\`, tagged by \`${tag.key}\`.\n`
|
||||
this.items.push(
|
||||
`${doc}#[derive(Debug, Clone, PartialEq, Serialize)]\n#[serde(untagged)]\npub enum ${name} {\n${variants.map((variant, index) => ` ${variant}(${types[index]}),`).join("\n")}\n /// A member this client does not know, kept as it arrived.\n Unknown(serde_json::Value),\n}\n\nimpl<'de> Deserialize<'de> for ${name} {\n fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {\n let value = serde_json::Value::deserialize(deserializer)?;\n match value.get(${JSON.stringify(tag.key)}).and_then(serde_json::Value::${access}) {\n${ordered.join("\n")}\n _ => Ok(Self::Unknown(value)),\n }\n }\n}`,
|
||||
`${doc}#[derive(Debug, Clone, PartialEq, Serialize)]\n#[serde(untagged)]\npub enum ${name} {\n${variants.map((variant, index) => ` ${variant}(${types[index]}),`).join("\n")}\n /// A member this client does not know, kept as it arrived.\n Unknown(serde_json::Value),\n}\n\nimpl<'de> Deserialize<'de> for ${name} {\n fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {\n let value = serde_json::Value::deserialize(deserializer)?;\n match value.get(${JSON.stringify(tag.key)}).and_then(serde_json::Value::${access}) {\n${ordered.join("\n")}\n _ => Ok(Self::Unknown(value)),\n }\n }\n}${tagMethod}`,
|
||||
)
|
||||
return name
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue