1use std::collections::{HashSet, VecDeque};
4use std::error::Error as StdError;
5use std::future::Future;
6use std::time::Duration;
7
8use ebbmem_client_generated::apis::{self, configuration::Configuration};
9use ebbmem_client_generated::models;
10
11use crate::error::{self, EbbmemError};
12use crate::SDK_VERSION;
13
14#[derive(Clone)]
15pub struct EbbmemClient {
16 configuration: Configuration,
17 namespace: Option<String>,
18 max_retries: u32,
19 timeout: Duration,
20}
21
22pub struct EbbmemClientBuilder {
23 base_url: Option<String>,
24 token: Option<String>,
25 api_key: Option<String>,
26 namespace: Option<String>,
27 timeout: Option<Duration>,
28 max_retries: Option<u32>,
29 headers: Vec<(String, String)>,
30 user_agent: Option<String>,
31 base_url_set: bool,
32 token_set: bool,
33 api_key_set: bool,
34 namespace_set: bool,
35}
36
37impl EbbmemClientBuilder {
38 pub fn new() -> Self {
39 Self {
40 base_url: None,
41 token: None,
42 api_key: None,
43 namespace: None,
44 timeout: None,
45 max_retries: None,
46 headers: Vec::new(),
47 user_agent: None,
48 base_url_set: false,
49 token_set: false,
50 api_key_set: false,
51 namespace_set: false,
52 }
53 }
54
55 pub fn base_url(mut self, value: impl Into<String>) -> Self {
56 self.base_url = Some(value.into());
57 self.base_url_set = true;
58 self
59 }
60 pub fn token(mut self, value: impl Into<String>) -> Self {
61 self.token = Some(value.into());
62 self.token_set = true;
63 self
64 }
65 pub fn api_key(mut self, value: impl Into<String>) -> Self {
66 self.api_key = Some(value.into());
67 self.api_key_set = true;
68 self
69 }
70 pub fn namespace(mut self, value: impl Into<String>) -> Self {
71 self.namespace = Some(value.into());
72 self.namespace_set = true;
73 self
74 }
75 pub fn timeout(mut self, value: Duration) -> Self {
76 self.timeout = Some(value);
77 self
78 }
79 pub fn max_retries(mut self, value: u32) -> Self {
80 self.max_retries = Some(value);
81 self
82 }
83 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
84 self.headers.push((name.into(), value.into()));
85 self
86 }
87
88 pub fn build(self) -> Result<EbbmemClient, EbbmemError> {
89 let base_url = pick(self.base_url_set, self.base_url, "EBBMEM_ORIGIN").unwrap_or_default();
90 let base_url = base_url.trim_end_matches('/').to_owned();
91 if base_url.is_empty() {
92 return Err(EbbmemError {
93 status: None,
94 code: None,
95 message: "base_url is required (set it or EBBMEM_ORIGIN)".into(),
96 details: None,
97 request_id: None,
98 retry_after: None,
99 });
100 }
101 let token = pick(self.token_set, self.token, "EBBMEM_TOKEN");
102 let api_key = pick(self.api_key_set, self.api_key, "EBBMEM_API_KEY");
103 let namespace = pick(self.namespace_set, self.namespace, "EBBMEM_NAMESPACE");
104 let timeout = self.timeout.unwrap_or(Duration::from_secs(30));
105 let user_agent = self.user_agent.unwrap_or_else(|| format!("ebbmem-client-rust/{SDK_VERSION}"));
106 let mut headers = reqwest::header::HeaderMap::new();
107 for (name, value) in self.headers {
108 if let (Ok(name), Ok(value)) = (
109 reqwest::header::HeaderName::from_bytes(name.as_bytes()),
110 reqwest::header::HeaderValue::from_str(&value),
111 ) {
112 headers.insert(name, value);
113 }
114 }
115 let client = reqwest::Client::builder()
116 .timeout(timeout)
117 .user_agent(user_agent.clone())
118 .default_headers(headers)
119 .build()
120 .map_err(|err| EbbmemError {
121 status: None,
122 code: None,
123 message: err.to_string(),
124 details: None,
125 request_id: None,
126 retry_after: None,
127 })?;
128 let mut configuration = Configuration::new();
129 configuration.base_path = base_url;
130 configuration.user_agent = Some(user_agent);
131 configuration.client = client;
132 configuration.bearer_access_token = token.filter(|value| !value.is_empty());
133 configuration.api_key = api_key.filter(|value| !value.is_empty()).map(|key| apis::configuration::ApiKey {
134 prefix: None,
135 key,
136 });
137 Ok(EbbmemClient {
138 configuration,
139 namespace: namespace.filter(|value| !value.is_empty()),
140 max_retries: self.max_retries.unwrap_or(2),
141 timeout,
142 })
143 }
144}
145
146impl Default for EbbmemClientBuilder {
147 fn default() -> Self {
148 Self::new()
149 }
150}
151
152impl EbbmemClient {
153 pub fn builder() -> EbbmemClientBuilder {
154 EbbmemClientBuilder::new()
155 }
156
157 pub fn memory(&self) -> Memory<'_> {
158 Memory { client: self }
159 }
160 pub fn tasks(&self) -> Tasks<'_> {
161 Tasks { client: self }
162 }
163 pub fn events(&self) -> Events<'_> {
164 Events { client: self }
165 }
166 pub fn raw(&self) -> &Configuration {
167 &self.configuration
168 }
169
170 pub async fn health(&self) -> Result<std::collections::HashMap<String, serde_json::Value>, Box<dyn StdError + Send + Sync>> {
171 self.retry("health", None, |cfg| async move { apis::health_api::health(&cfg).await }).await
172 }
173
174 async fn retry<T, E, F, Fut>(&self, name: &str, idempotency_key: Option<&str>, mut op: F) -> Result<T, Box<dyn StdError + Send + Sync>>
175 where
176 F: FnMut(Configuration) -> Fut,
177 Fut: Future<Output = Result<T, apis::Error<E>>>,
178 {
179 let idempotent = matches!(
180 name,
181 "recall" | "recall_federated" | "get" | "list" | "status" | "why_not" | "health" | "ready" | "tasks.get" | "tasks.list" | "tasks.cancel" | "forget"
182 ) || ((name == "remember" || name == "remember_batch") && idempotency_key.is_some());
183 let mut attempt = 0u32;
184 loop {
185 let mut cfg = self.configuration.clone();
186 if let Some(key) = idempotency_key {
187 let mut headers = reqwest::header::HeaderMap::new();
188 if let Ok(value) = reqwest::header::HeaderValue::from_str(key) {
189 headers.insert("idempotency-key", value);
190 }
191 if let Ok(client) = reqwest::Client::builder().default_headers(headers).timeout(self.timeout).build() {
192 cfg.client = client;
193 }
194 }
195 match op(cfg).await {
196 Ok(value) => return Ok(value),
197 Err(err) => {
198 let mapped = map_generated(err);
199 if attempt >= self.max_retries || !idempotent || !retryable_status(&mapped) {
200 return Err(error::classify(mapped));
201 }
202 let wait = backoff(attempt, &mapped);
203 tokio::time::sleep(wait).await;
204 attempt += 1;
205 }
206 }
207 }
208 }
209}
210
211impl std::fmt::Debug for EbbmemClient {
212 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213 f.debug_struct("EbbmemClient")
214 .field("base_url", &self.configuration.base_path)
215 .field("token", &self.configuration.bearer_access_token.as_ref().map(|_| "set"))
216 .field("api_key", &self.configuration.api_key.as_ref().map(|_| "set"))
217 .finish()
218 }
219}
220
221pub struct Memory<'a> {
222 client: &'a EbbmemClient,
223}
224
225impl Memory<'_> {
226 pub async fn remember(
227 &self,
228 content: &str,
229 vector: Option<Vec<f64>>,
230 tags: Option<Vec<String>>,
231 importance: Option<f64>,
232 idempotency_key: Option<&str>,
233 ) -> Result<models::MemoryOperationResponse, Box<dyn StdError + Send + Sync>> {
234 let mut body = models::RememberRequestModel::default();
235 body.content = content.to_owned();
236 body.vector = vector.map(Some);
237 body.tags = tags.map(Some);
238 body.importance = importance;
239 let ns = self.client.namespace.clone();
240 self.client
241 .retry("remember", idempotency_key, move |cfg| {
242 let body = body.clone();
243 let ns = ns.clone();
244 async move { apis::memory_api::remember(&cfg, body, ns.as_deref()).await }
245 })
246 .await
247 }
248
249 pub async fn recall(
250 &self,
251 query: &str,
252 limit: Option<i32>,
253 vector: Option<Vec<f64>>,
254 ) -> Result<models::RecallResponseModel, Box<dyn StdError + Send + Sync>> {
255 let mut body = models::RecallRequestModel::default();
256 body.query = query.to_owned();
257 body.limit = limit;
258 body.vector = vector.map(Some);
259 body.reinforce = Some(false);
260 let ns = self.client.namespace.clone();
261 self.client
262 .retry("recall", None, move |cfg| {
263 let body = body.clone();
264 let ns = ns.clone();
265 async move { apis::memory_api::recall(&cfg, body, ns.as_deref()).await }
266 })
267 .await
268 }
269
270 pub async fn get(&self, memory_id: &str) -> Result<models::MemoryRow, Box<dyn StdError + Send + Sync>> {
271 let id = memory_id.to_owned();
272 let ns = self.client.namespace.clone();
273 self.client
274 .retry("get", None, move |cfg| {
275 let id = id.clone();
276 let ns = ns.clone();
277 async move { apis::memory_api::get_memory(&cfg, &id, None, ns.as_deref()).await }
278 })
279 .await
280 }
281
282 pub fn list(&self, limit: i32) -> MemoryList<'_> {
284 MemoryList {
285 client: self.client,
286 limit,
287 cursor: None,
288 seen: HashSet::new(),
289 buffer: VecDeque::new(),
290 done: false,
291 }
292 }
293
294 pub async fn status(&self) -> Result<models::MemoryStatusResponse, Box<dyn StdError + Send + Sync>> {
295 let ns = self.client.namespace.clone();
296 self.client
297 .retry("status", None, move |cfg| {
298 let ns = ns.clone();
299 async move { apis::memory_api::status(&cfg, None, ns.as_deref()).await }
300 })
301 .await
302 }
303
304 pub async fn forget(&self, memory_id: &str, purge: bool) -> Result<models::ResponseForgetmemory, Box<dyn StdError + Send + Sync>> {
305 let id = memory_id.to_owned();
306 let ns = self.client.namespace.clone();
307 self.client
308 .retry("forget", None, move |cfg| {
309 let id = id.clone();
310 let ns = ns.clone();
311 async move { apis::memory_api::forget_memory(&cfg, &id, Some(purge), None, ns.as_deref()).await }
312 })
313 .await
314 }
315
316 pub async fn remember_batch(
317 &self,
318 items: Vec<serde_json::Value>,
319 idempotency_key: Option<&str>,
320 ) -> Result<models::BatchRememberResponse, Box<dyn StdError + Send + Sync>> {
321 let encoded = items.into_iter().map(models::ItemsInner::from_value).collect();
322 let body = models::BatchRememberRequestModel::new(encoded);
323 let ns = self.client.namespace.clone();
324 self.client
325 .retry("remember_batch", idempotency_key, move |cfg| {
326 let body = body.clone();
327 let ns = ns.clone();
328 async move { apis::memory_api::remember_batch(&cfg, body, ns.as_deref()).await }
329 })
330 .await
331 }
332
333 pub async fn recall_federated(
334 &self,
335 query: &str,
336 limit: Option<i32>,
337 ) -> Result<Vec<models::FederatedRecallCandidate>, Box<dyn StdError + Send + Sync>> {
338 let mut body = models::FederatedRecallRequest::new(query.to_owned());
339 body.limit = limit;
340 let ns = self.client.namespace.clone();
341 self.client
342 .retry("recall_federated", None, move |cfg| {
343 let body = body.clone();
344 let ns = ns.clone();
345 async move { apis::memory_api::recall_federated(&cfg, body, ns.as_deref()).await }
346 })
347 .await
348 }
349
350 pub async fn update(
351 &self,
352 memory_id: &str,
353 request: models::UpdateMemoryRequest,
354 ) -> Result<models::MemoryRow, Box<dyn StdError + Send + Sync>> {
355 let id = memory_id.to_owned();
356 let ns = self.client.namespace.clone();
357 self.client
358 .retry("update", None, move |cfg| {
359 let id = id.clone();
360 let request = request.clone();
361 let ns = ns.clone();
362 async move { apis::memory_api::update_memory(&cfg, &id, request, None, ns.as_deref()).await }
363 })
364 .await
365 }
366
367 pub async fn reinforce(
368 &self,
369 memory_id: &str,
370 delta: f64,
371 ) -> Result<models::ReinforceResponse, Box<dyn StdError + Send + Sync>> {
372 let mut body = models::ReinforceRequestModel::new(models::MemoryId1::from_str_id(memory_id));
373 body.delta = Some(delta);
374 let ns = self.client.namespace.clone();
375 self.client
376 .retry("reinforce", None, move |cfg| {
377 let body = body.clone();
378 let ns = ns.clone();
379 async move { apis::memory_api::reinforce(&cfg, body, ns.as_deref()).await }
380 })
381 .await
382 }
383
384 pub async fn reflect(
385 &self,
386 namespace: Option<&str>,
387 ) -> Result<models::ReflectResponse, Box<dyn StdError + Send + Sync>> {
388 let mut body = models::ReflectRequestModel::new();
389 let ns = namespace
390 .map(str::to_owned)
391 .or_else(|| self.client.namespace.clone());
392 body.namespace = ns.clone().map(Some);
393 self.client
394 .retry("reflect", None, move |cfg| {
395 let body = body.clone();
396 let ns = ns.clone();
397 async move { apis::memory_api::reflect(&cfg, body, ns.as_deref()).await }
398 })
399 .await
400 }
401
402 pub async fn why_not(
403 &self,
404 memory_id: &str,
405 query: &str,
406 ) -> Result<models::WhyNotResponse, Box<dyn StdError + Send + Sync>> {
407 let body = models::WhyNotRequestModel::new(models::MemoryId1::from_str_id(memory_id), query.to_owned());
408 let ns = self.client.namespace.clone();
409 self.client
410 .retry("why_not", None, move |cfg| {
411 let body = body.clone();
412 let ns = ns.clone();
413 async move { apis::memory_api::why_not(&cfg, body, ns.as_deref()).await }
414 })
415 .await
416 }
417}
418
419pub struct MemoryList<'a> {
420 client: &'a EbbmemClient,
421 limit: i32,
422 cursor: Option<String>,
423 seen: HashSet<String>,
424 buffer: VecDeque<models::MemoryRow>,
425 done: bool,
426}
427
428impl MemoryList<'_> {
429 pub async fn next(&mut self) -> Result<Option<models::MemoryRow>, Box<dyn StdError + Send + Sync>> {
430 if self.buffer.is_empty() && !self.done {
431 self.fill().await?;
432 }
433 Ok(self.buffer.pop_front())
434 }
435
436 async fn fill(&mut self) -> Result<(), Box<dyn StdError + Send + Sync>> {
437 let page_cursor = self.cursor.clone();
438 let ns = self.client.namespace.clone();
439 let limit = self.limit;
440 let page = self
441 .client
442 .retry("list", None, move |cfg| {
443 let page_cursor = page_cursor.clone();
444 let ns = ns.clone();
445 async move {
446 apis::memory_api::list_memories(
447 &cfg,
448 page_cursor.as_deref(),
449 Some(limit),
450 None,
451 None,
452 None,
453 None,
454 None,
455 None,
456 None,
457 None,
458 None,
459 None,
460 ns.as_deref(),
461 )
462 .await
463 }
464 })
465 .await?;
466 if let Some(items) = page.items.clone() {
467 self.buffer.extend(items);
468 }
469 let next = page.next_cursor.clone().flatten().filter(|value| !value.is_empty());
470 let more = page.has_more.unwrap_or(false);
471 match next {
472 Some(value) if more && self.seen.insert(value.clone()) => self.cursor = Some(value),
473 _ => self.done = true,
474 }
475 Ok(())
476 }
477}
478
479pub struct Tasks<'a> {
480 client: &'a EbbmemClient,
481}
482
483impl Tasks<'_> {
484 pub async fn get(&self, task_id: &str) -> Result<std::collections::HashMap<String, serde_json::Value>, Box<dyn StdError + Send + Sync>> {
485 let id = task_id.to_owned();
486 self.client
487 .retry("tasks.get", None, move |cfg| {
488 let id = id.clone();
489 async move { apis::tasks_api::get_task(&cfg, &id).await }
490 })
491 .await
492 }
493
494 pub async fn list(&self, limit: Option<i32>) -> Result<std::collections::HashMap<String, serde_json::Value>, Box<dyn StdError + Send + Sync>> {
495 let ns = self.client.namespace.clone();
496 self.client
497 .retry("tasks.list", None, move |cfg| {
498 let ns = ns.clone();
499 async move { apis::tasks_api::list_tasks(&cfg, None, ns.as_deref(), limit).await }
500 })
501 .await
502 }
503
504 pub async fn cancel(&self, task_id: &str) -> Result<std::collections::HashMap<String, serde_json::Value>, Box<dyn StdError + Send + Sync>> {
505 let id = task_id.to_owned();
506 self.client
507 .retry("tasks.cancel", None, move |cfg| {
508 let id = id.clone();
509 async move { apis::tasks_api::cancel_task(&cfg, &id).await }
510 })
511 .await
512 }
513}
514
515pub struct Events<'a> {
516 client: &'a EbbmemClient,
517}
518
519impl Events<'_> {
520 pub async fn stream(&self, token: Option<&str>) -> Result<models::StreamEventsResponse200, Box<dyn StdError + Send + Sync>> {
522 let ns = self.client.namespace.clone();
523 let token = token.map(str::to_owned);
524 self.client
525 .retry("events.stream", None, move |cfg| {
526 let ns = ns.clone();
527 let token = token.clone();
528 async move {
529 apis::events_api::stream_events(&cfg, None, None, ns.as_deref(), None, None, token.as_deref()).await
530 }
531 })
532 .await
533 }
534}
535
536fn pick(explicit: bool, value: Option<String>, env_name: &str) -> Option<String> {
537 if explicit {
538 return value;
539 }
540 std::env::var(env_name).ok().map(|item| item.trim().to_owned()).filter(|item| !item.is_empty())
541}
542
543fn map_generated<T>(err: apis::Error<T>) -> EbbmemError {
544 match err {
545 apis::Error::ResponseError(content) => error::parse_body(Some(content.status.as_u16()), &content.content),
546 other => EbbmemError {
547 status: None,
548 code: None,
549 message: other.to_string(),
550 details: None,
551 request_id: None,
552 retry_after: None,
553 },
554 }
555}
556
557fn retryable_status(err: &EbbmemError) -> bool {
558 matches!(err.status, None | Some(429) | Some(502) | Some(503) | Some(504))
559}
560
561fn backoff(attempt: u32, err: &EbbmemError) -> Duration {
562 if let Some(seconds) = err.retry_after {
563 return Duration::from_secs_f64(seconds.max(0.0));
564 }
565 let base = (0.2 * 2f64.powi(attempt as i32)).min(8.0);
566 let jitter = (attempt as f64 * 0.013) % (base / 2.0);
567 Duration::from_secs_f64(base + jitter)
568}