forge
Explore
Log in

Don't you dare go Hollow

Add api-read frames to hab/1

Browse files at this commit

b032b41f1abf05a92f7f677d91e4e88d6c737d8eAhmet Kaan GümüşParent: d5def02
  • feat
    • add api-read frames to hab/1
Show full message
🤖 feat: add api-read frames to hab/1
src/ai/protocol.rsmodified+96 -0
@@ -16,6 +16,12 @@
1616 //! opens it, writes one [`Request`], finishes its send side, and reads one
1717 //! [`Response`]. The stream is then closed.
1818 //!
19+//! * Each **api read** goes the other way: the service opens a *client-initiated*
20+//! bidirectional stream (any after the control one), writes one
21+//! [`ApiRequest`], finishes its send side, and reads one [`ApiResponse`].
22+//! That mirrors the REST API — the backend dispatches the path internally —
23+//! so a service asks for school data instead of being handed it.
24+//!
1925 //! There is deliberately no correlation-id matching: QUIC stream IDs already
2026 //! multiplex concurrent requests over the one connection, independently
2127 //! flow-controlled, with no head-of-line blocking between them. [`Request::id`]
@@ -128,6 +134,47 @@ pub enum Response {
128134 },
129135 }
130136
137+/// A read of the school's own API, written by the *service* on a fresh
138+/// client-initiated stream.
139+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
140+pub struct ApiRequest {
141+ /// Trace id (ULID). Not used for correlation — the stream does that.
142+ pub id: String,
143+ /// Path as the REST API spells it, e.g. `"/users/me"`. No host, no query.
144+ pub path: String,
145+ /// Query string without the leading `?`, e.g. `"limit=10&offset=0"`.
146+ #[serde(default)]
147+ pub query: Option<String>,
148+ /// User id to execute as, for own-scoped endpoints. Absent means the
149+ /// request runs as the service itself.
150+ #[serde(default)]
151+ pub on_behalf_of: Option<String>,
152+ /// HTTP method. Absent means `GET`. Not validated here — the server
153+ /// decides what it will dispatch.
154+ #[serde(default)]
155+ pub method: Option<String>,
156+}
157+
158+/// The backend's single answer frame. `Err` is a bridge-level refusal (path not
159+/// allowed, unknown user); an API call that ran and answered `404` is an `Ok`
160+/// carrying that status, because the service asked and the API replied.
161+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
162+#[serde(tag = "outcome", rename_all = "snake_case")]
163+pub enum ApiResponse {
164+ Ok {
165+ id: String,
166+ /// HTTP status the router produced.
167+ status: u16,
168+ body: Value,
169+ },
170+ Err {
171+ id: String,
172+ /// Bridge-defined, stable, machine-readable (`"path_not_allowed"`).
173+ code: String,
174+ message: String,
175+ },
176+}
177+
131178 /// Write one length-prefixed JSON frame.
132179 pub async fn write_frame<W, T>(w: &mut W, message: &T) -> Result<(), FrameError>
133180 where
@@ -305,6 +352,55 @@ mod tests {
305352 assert_eq!(ok["status"], "ok");
306353 }
307354
355+ #[tokio::test]
356+ async fn api_frame_tags_are_the_documented_wire_names() {
357+ // Same reason as above: other-language services match these literals.
358+ // The tag is `outcome`, not `status` — `status` is the HTTP code.
359+ let ok = serde_json::to_value(ApiResponse::Ok {
360+ id: "1".into(),
361+ status: 404,
362+ body: json!(null),
363+ })
364+ .unwrap();
365+ assert_eq!(ok["outcome"], "ok");
366+ assert_eq!(ok["status"], 404);
367+ let err = serde_json::to_value(ApiResponse::Err {
368+ id: "1".into(),
369+ code: "path_not_allowed".into(),
370+ message: "nope".into(),
371+ })
372+ .unwrap();
373+ assert_eq!(err["outcome"], "err");
374+ assert_eq!(err["code"], "path_not_allowed");
375+ }
376+
377+ #[tokio::test]
378+ async fn an_api_request_needs_only_an_id_and_a_path() {
379+ let bare: ApiRequest = serde_json::from_value(json!({
380+ "id": "01J",
381+ "path": "/users/me",
382+ }))
383+ .unwrap();
384+ assert_eq!(bare.query, None);
385+ assert_eq!(bare.on_behalf_of, None);
386+ assert_eq!(bare.method, None);
387+
388+ let full = ApiRequest {
389+ id: "01J".into(),
390+ path: "/notes".into(),
391+ query: Some("limit=10".into()),
392+ on_behalf_of: Some("user:abc".into()),
393+ // Not validated at this layer — any string rides the wire.
394+ method: Some("GET".into()),
395+ };
396+ let raw = serde_json::to_value(&full).unwrap();
397+ assert_eq!(raw["path"], "/notes");
398+ assert_eq!(raw["query"], "limit=10");
399+ assert_eq!(raw["on_behalf_of"], "user:abc");
400+ assert_eq!(raw["method"], "GET");
401+ assert_eq!(serde_json::from_value::<ApiRequest>(raw).unwrap(), full);
402+ }
403+
308404 #[tokio::test]
309405 async fn max_concurrent_is_optional_on_the_wire() {
310406 let raw = json!({