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
315
316
317
318
319
//! Runtime SDK for the [Caravan](https://github.com/paulxiep/caravan)
//! application-definition compiler.
//!
//! A user declares a seam-interface trait, marks it with [`wagon`], registers a
//! concrete implementation via [`provide`], and dispatches through [`client`].
//! Dispatch mode (inproc / http / lambda) is read from the
//! `CARAVAN_RPC_PEERS` env var at the call site; when the env var is unset,
//! `client::<dyn I>()` returns the registered `Arc<dyn I>` directly with no
//! overhead (no-config inertness).
//!
//! See <https://github.com/paulxiep/caravan/blob/main/docs/poc_rpc_sdk.md> for
//! the wire contract and per-language surface.
//!
//! # M2 status
//!
//! 0.1.0 ships the runtime building blocks: codec (`codec`), peer-table
//! parsing (`peers`), error types (`errors`), HTTP client dispatchers
//! (`dispatch`, behind the `client` feature). The proc-macro that turns
//! `#[wagon]` into server + client adapters lands in M2 Session 3+. Until
//! then, `client::<dyn T>()` returns the inproc-registered impl regardless of
//! peer-table mode — switching to HTTP happens only after the proc-macro
//! wires per-trait HTTP adapter discovery.
//!
//! Lambda mode panics with an M7 pointer (forward-compat marker).
//!
//! ```ignore
//! use std::sync::Arc;
//! use caravan_rpc::{wagon, provide, client};
//!
//! #[wagon]
//! pub trait Embedder: Send + Sync {
//! fn embed(&self, text: &str) -> Vec<f32>;
//! }
//!
//! struct InMemoryEmbedder;
//! impl Embedder for InMemoryEmbedder {
//! fn embed(&self, _text: &str) -> Vec<f32> { vec![0.0; 8] }
//! }
//!
//! // startup
//! provide::<dyn Embedder>(Arc::new(InMemoryEmbedder));
//!
//! // call site
//! let v = client::<dyn Embedder>().embed("hello");
//! assert_eq!(v.len(), 8);
//! ```
use ;
use HashMap;
use ;
pub use wagon;
pub use ;
pub use ;
/// Internal re-exports for use by `#[wagon]`-generated code only. Lets the
/// user's crate depend solely on `caravan-rpc`; the macro reaches in here
/// rather than spelling `::serde_json::...` / `::axum::...` (which would
/// require the user to add those crates to their own Cargo.toml).
///
/// Not a stable public API — names may change without notice.
/// Factory entry for a `#[wagon]` trait's HTTP client adapter.
///
/// Macro-generated code submits one of these per full-codegen trait via
/// `inventory::submit!` so `client::<dyn T>()` can discover the
/// trait-specific HttpClient constructor at runtime, indexed by `TypeId`.
///
/// `construct` returns the HttpClient wrapped as `Arc<dyn T>` then erased
/// into `Box<dyn Any + Send + Sync>` (because `Arc<dyn T>: Any` for
/// `T: 'static`). The SDK downcasts back to `Arc<T>` in `client::<T>()`.
collect!;
Sized + 'static>
/// Factory entry for a `#[wagon]` trait's server-side router. Mirrors
/// [`HttpAdapterFactory`] but for the server direction.
///
/// Macro-generated code submits one of these per full-codegen trait via
/// `inventory::submit!`. [`run_or_serve`] iterates this collection by
/// interface name to find the right router builder when starting in
/// peer mode.
///
/// `build_router_from_registry` is macro-emitted and does the
/// trait-erased work of: `try_client::<dyn Trait>()` for the impl,
/// then `build_<trait>_router(impl)` to produce the axum router.
collect!;
/// Run the user's main, OR start a peer HTTP server, based on the
/// `CARAVAN_RPC_ROLE` env var.
///
/// **Inertness**: when the env var is unset or empty, this just awaits
/// `user_main` and returns — no overhead, no behavior change.
///
/// **Peer mode**: when `CARAVAN_RPC_ROLE=peer-<InterfaceName>`,
/// `user_main` is NOT called. Instead, the SDK:
/// 1. Looks up the macro-emitted [`HttpServerFactory`] for the named
/// interface (via inventory).
/// 2. Calls `build_router_from_registry` which (a) finds the
/// `provide()`-registered impl in the inproc registry and (b)
/// builds the axum router using the macro-generated
/// `build_<trait>_router(impl)`.
/// 3. Binds on `CARAVAN_RPC_BIND_ADDR` (default `0.0.0.0:8080`) and
/// `serve_forever`s.
///
/// Caller contract: the user's setup code (including `provide()` calls
/// for all #[wagon] traits) must run BEFORE `run_or_serve` is awaited.
/// Typical pattern:
///
/// ```ignore
/// #[tokio::main]
/// async fn main() -> Result<()> {
/// let state = AppState::from_config(...).await?; // calls provide() inside
/// caravan_rpc::run_or_serve(|| async move {
/// // user's normal app startup — only runs in non-peer mode.
/// run_chat_server(state).await
/// }).await
/// }
/// ```
pub async
/// Version of this crate.
pub const VERSION: &str = env!;
/// Process-global inproc registry mapping a seam trait's [`TypeId`] to its
/// `Arc<dyn T>` impl.
///
/// Stored as `Box<dyn Any + Send + Sync>` so we can key by any trait object's
/// `TypeId`. The stored value is always an `Arc<T>` (with `T: ?Sized`); the
/// downcast in [`client`] reconstructs that exact type.
type Registry = ;
/// Register `impl_` as the inproc provider for trait object `T`.
///
/// Call once per process at startup (worker entry, CLI `main()`) before any
/// `client::<dyn T>()` call. Re-registering an interface replaces the prior
/// impl (last-write-wins) — intentional for test isolation; production code
/// should call `provide` once per interface.
///
/// ```ignore
/// provide::<dyn Embedder>(Arc::new(FastEmbedImpl::new()?));
/// ```
Sized + Send + Sync + 'static>
/// Return an `Arc<dyn T>` to dispatch through.
///
/// Behavior depends on `CARAVAN_RPC_PEERS[interface]`:
/// * Unset or `inproc` → the locally `provide()`-ed impl (zero-overhead).
/// * `http` AND the trait was full-codegen-expanded by `#[wagon]` (so an
/// inventory factory exists) → an `Arc<<Trait>HttpClient>` whose every
/// method call goes over the wire.
/// * `http` but no inventory factory (e.g., `#[wagon(identity)]` trait) →
/// falls back to the local impl. Logged once at startup so misconfigs
/// are visible. Documented limitation: identity-marked traits don't
/// honor mode flips.
/// * `lambda` → panic with M7 pointer.
///
/// Panics if no impl is registered AND no http factory exists for `T`.
/// Use [`try_client`] for optional seams.
Sized + Send + Sync + 'static>
/// Return an `Arc<dyn T>` to dispatch through, or `None` if no impl is
/// available (neither locally `provide()`-ed nor wired via HTTP through
/// `#[wagon]`'s inventory factory).
///
/// Use this for seams that are conditionally enabled at runtime (e.g. an
/// optional reranker). For seams that must always be present, prefer the
/// panicking [`client`] for a clearer error message at startup.
///
/// Dispatch-mode selection mirrors [`client`]: HTTP mode + an inventory
/// factory → returns the macro-generated `<Trait>HttpClient`; otherwise
/// → returns the registered local impl (inproc).
Sized + Send + Sync + 'static>
/// Whether an impl has been registered for trait object `T`.
///
/// Slightly cheaper than [`try_client`] when the caller doesn't need the impl
/// itself (e.g. health checks). Subject to TOCTOU — prefer `try_client` in
/// dispatch paths.
Sized + Send + Sync + 'static>
/// Reset the registry. Intended for test isolation only; production code
/// should `provide()` once and leave the registry alone for the process
/// lifetime.