forgelib 1.1.0

The standard library for agent-built SaaS: hardened infra primitives on Postgres
Documentation
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use crate::blob::{Blob, BlobInfo, PutOpts};
use crate::config_store::ConfigStore;
use crate::error::{ForgeError, Result};
use crate::kv::{Kv, SetOpts};
use crate::pubsub::Pubsub;
use crate::queue::{DequeueOpts, EnqueueOpts, Job, JobId, Queue};
use crate::ratelimit::{Decision, FailMode, Limit, RateLimit};
use async_trait::async_trait;
use bytes::Bytes;
use futures_util::stream::{BoxStream, StreamExt};
use serde::Serialize;
use serde::de::DeserializeOwned;
use std::marker::PhantomData;

fn ser<T: Serialize>(value: &T, what: &str) -> Result<Vec<u8>> {
    serde_json::to_vec(value)
        .map_err(|e| ForgeError::invalid(format!("could not serialize {what}: {e}")))
}

fn de_slice<T: DeserializeOwned>(bytes: &[u8], what: &str) -> Result<T> {
    serde_json::from_slice(bytes)
        .map_err(|e| ForgeError::invalid(format!("could not deserialize {what}: {e}")))
}

/// A kv key bound to a JSON value type `T`. Construct one constant per logical key so
/// the key string and value type are declared together, once.
#[derive(Debug, Clone)]
pub struct KvKey<T> {
    key: String,
    _marker: PhantomData<fn() -> T>,
}

impl<T> KvKey<T> {
    pub fn new(key: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            _marker: PhantomData,
        }
    }

    pub fn as_str(&self) -> &str {
        &self.key
    }
}

/// Typed JSON access over [`Kv`], keyed by [`KvKey`]. Blanket-implemented, so it works
/// on `&dyn Kv` (e.g. `forge.kv()`).
#[async_trait]
pub trait KvTyped: Kv {
    /// `get` and deserialize the value bound to `key`. `None` if absent/expired.
    async fn get_typed<T: DeserializeOwned + Send>(&self, key: &KvKey<T>) -> Result<Option<T>> {
        match self.get(key.as_str()).await? {
            Some(b) => de_slice(&b, "kv value").map(Some),
            None => Ok(None),
        }
    }

    /// Serialize `value` and `set` it at `key`. Returns whether the write happened.
    async fn set_typed<T: Serialize + Send + Sync>(
        &self,
        key: &KvKey<T>,
        value: &T,
        opts: SetOpts,
    ) -> Result<bool> {
        self.set(key.as_str(), Bytes::from(ser(value, "kv value")?), opts)
            .await
    }

    /// `delete` the value at `key`.
    async fn delete_typed<T: Send + Sync>(&self, key: &KvKey<T>) -> Result<bool> {
        self.delete(key.as_str()).await
    }
}

impl<K: Kv + ?Sized> KvTyped for K {}

/// A config key bound to a JSON value type `T`, carrying a default for when it is unset
/// at every layer.
#[derive(Debug, Clone)]
pub struct ConfigKey<T> {
    key: String,
    default: T,
}

impl<T> ConfigKey<T> {
    pub fn new(key: impl Into<String>, default: T) -> Self {
        Self {
            key: key.into(),
            default,
        }
    }

    pub fn as_str(&self) -> &str {
        &self.key
    }

    pub fn default_value(&self) -> &T {
        &self.default
    }
}

/// Typed config access over [`ConfigStore`], keyed by [`ConfigKey`]. Blanket-implemented.
#[async_trait]
pub trait ConfigTyped: ConfigStore {
    /// Resolve `key` and deserialize into `T`. `None` if unset at every layer.
    async fn get_typed<T: DeserializeOwned + Send + Sync>(
        &self,
        key: &ConfigKey<T>,
    ) -> Result<Option<T>> {
        match self.get_raw(key.as_str()).await? {
            Some(raw) => serde_json::from_str(&raw).map(Some).map_err(|e| {
                ForgeError::invalid(format!("could not deserialize config value: {e}"))
            }),
            None => Ok(None),
        }
    }

    /// Like [`ConfigTyped::get_typed`] but falls back to the key's default when unset.
    async fn get_or_default<T: DeserializeOwned + Clone + Send + Sync>(
        &self,
        key: &ConfigKey<T>,
    ) -> Result<T> {
        Ok(self
            .get_typed(key)
            .await?
            .unwrap_or_else(|| key.default_value().clone()))
    }

    /// Serialize `value` to JSON and store it at `key` (an env var still shadows it).
    async fn set_typed<T: Serialize + Send + Sync>(
        &self,
        key: &ConfigKey<T>,
        value: &T,
    ) -> Result<()> {
        let raw = serde_json::to_string(value)
            .map_err(|e| ForgeError::invalid(format!("could not serialize config value: {e}")))?;
        self.set_raw(key.as_str(), &raw).await
    }
}

impl<C: ConfigStore + ?Sized> ConfigTyped for C {}

/// A queue name bound to its payload type `T`. `const`-constructible so it can live in
/// a [`QueuePayload`] associated constant.
#[derive(Debug, Clone, Copy)]
pub struct QueueName<T> {
    name: &'static str,
    _marker: PhantomData<fn() -> T>,
}

impl<T> QueueName<T> {
    pub const fn new(name: &'static str) -> Self {
        Self {
            name,
            _marker: PhantomData,
        }
    }

    pub const fn as_str(&self) -> &'static str {
        self.name
    }
}

/// A payload type that knows its own queue and defaults. Implement it once per job
/// type; the typed enqueue/dequeue then need no queue string and no manual JSON.
///
/// ```
/// use forgelib::typed::{QueueName, QueuePayload};
/// use serde::{Serialize, Deserialize};
/// #[derive(Serialize, Deserialize)]
/// struct SendEmail { to: String, template: String }
/// impl QueuePayload for SendEmail {
///     const QUEUE: QueueName<Self> = QueueName::new("emails");
///     const MAX_ATTEMPTS: u32 = 3;
/// }
/// ```
pub trait QueuePayload: Serialize + DeserializeOwned + Send + Sync + Sized {
    /// The queue this payload is enqueued into / dequeued from.
    const QUEUE: QueueName<Self>;
    /// Default delivery attempts before dead-lettering (used by `enqueue_typed`).
    const MAX_ATTEMPTS: u32 = 5;

    /// The default enqueue options for this payload type (applies `MAX_ATTEMPTS`).
    fn enqueue_opts() -> EnqueueOpts {
        EnqueueOpts::new().with_max_attempts(Self::MAX_ATTEMPTS)
    }
}

/// A dequeued job whose payload has been decoded into `P`. Carries the raw [`Job`] so
/// the lease can be `ack`/`nack`/`heartbeat`'d.
#[derive(Debug, Clone)]
pub struct TypedJob<P> {
    pub payload: P,
    job: Job,
}

impl<P> TypedJob<P> {
    /// The underlying job (for `ack`/`nack`/`heartbeat` and its id/attempt).
    pub fn job(&self) -> &Job {
        &self.job
    }
}

/// Typed enqueue/dequeue over [`Queue`], driven by [`QueuePayload`]. Blanket-implemented.
#[async_trait]
pub trait QueueTyped: Queue {
    /// Enqueue `payload` onto its bound queue with the type's default options.
    async fn enqueue_typed<P: QueuePayload>(&self, payload: &P) -> Result<JobId> {
        self.enqueue_typed_with(payload, P::enqueue_opts()).await
    }

    /// Enqueue `payload` with caller-chosen options (queue + codec still bound to `P`).
    async fn enqueue_typed_with<P: QueuePayload>(
        &self,
        payload: &P,
        opts: EnqueueOpts,
    ) -> Result<JobId> {
        self.enqueue(
            P::QUEUE.as_str(),
            Bytes::from(ser(payload, "queue payload")?),
            opts,
        )
        .await
    }

    /// Dequeue from `P`'s bound queue and decode the payload into `P`.
    async fn dequeue_typed<P: QueuePayload>(
        &self,
        opts: DequeueOpts,
    ) -> Result<Option<TypedJob<P>>> {
        match self.dequeue(P::QUEUE.as_str(), opts).await? {
            Some(job) => {
                let payload = de_slice::<P>(&job.payload, "queue payload")?;
                Ok(Some(TypedJob { payload, job }))
            }
            None => Ok(None),
        }
    }
}

impl<Q: Queue + ?Sized> QueueTyped for Q {}

/// A value that names a rate-limit subject (the per-caller key). Blanket-implemented
/// for any `Display` type, so a `UserId` newtype works as a subject.
pub trait RateSubject {
    /// The subject string consumed by [`RateLimit::check`].
    fn rate_subject(&self) -> String;
}

impl<T: std::fmt::Display + ?Sized> RateSubject for T {
    fn rate_subject(&self) -> String {
        self.to_string()
    }
}

/// A rate-limit bucket bound to its policy, fail mode, and subject type `S`. Declare one
/// constant per bucket to keep the name, limit, and fail mode together. `S` may be unsized
/// (e.g. `RateBucket<str>`); `PhantomData<fn(&S)>` keeps it `Send`/`Sync` so a bucket can be
/// a `const`/`static`.
pub struct RateBucket<S: ?Sized> {
    bucket: &'static str,
    limit: Limit,
    fail: FailMode,
    _marker: PhantomData<fn(&S)>,
}

impl<S: RateSubject + ?Sized> RateBucket<S> {
    /// Bind `bucket` to its `limit` policy and `fail` mode for subject type `S`.
    pub const fn new(bucket: &'static str, limit: Limit, fail: FailMode) -> Self {
        Self {
            bucket,
            limit,
            fail,
            _marker: PhantomData,
        }
    }

    /// Check-and-consume one unit for `subject` against this bucket's bound policy.
    pub async fn check(&self, rl: &dyn RateLimit, subject: &S) -> Result<Decision> {
        rl.check_with(self.bucket, &subject.rate_subject(), self.limit, self.fail)
            .await
    }
}

/// A blob key bound to a "kind" marker `K`, so a path convention is named once and the
/// type system keeps avatars and exports from being mixed up at call sites.
#[derive(Debug, Clone)]
pub struct BlobKey<K> {
    key: String,
    _marker: PhantomData<fn() -> K>,
}

impl<K> BlobKey<K> {
    pub fn new(key: impl Into<String>) -> Self {
        Self {
            key: key.into(),
            _marker: PhantomData,
        }
    }

    pub fn as_str(&self) -> &str {
        &self.key
    }

    pub async fn put(&self, blob: &dyn Blob, data: Bytes, opts: PutOpts) -> Result<()> {
        blob.put(&self.key, data, opts).await
    }

    pub async fn get(&self, blob: &dyn Blob) -> Result<Option<Bytes>> {
        blob.get(&self.key).await
    }

    pub async fn head(&self, blob: &dyn Blob) -> Result<Option<BlobInfo>> {
        blob.head(&self.key).await
    }

    pub async fn delete(&self, blob: &dyn Blob) -> Result<()> {
        blob.delete(&self.key).await
    }
}

/// A pubsub topic bound to an event type `E`.
#[derive(Debug, Clone)]
pub struct Topic<E> {
    topic: String,
    _marker: PhantomData<fn() -> E>,
}

impl<E> Topic<E> {
    pub fn new(topic: impl Into<String>) -> Self {
        Self {
            topic: topic.into(),
            _marker: PhantomData,
        }
    }

    pub fn as_str(&self) -> &str {
        &self.topic
    }
}

/// A typed pubsub stream: each item is one event decoded into `E` (a decode failure is
/// surfaced as `Err` on the stream rather than dropping the message silently).
pub type TypedSubscription<E> = BoxStream<'static, Result<E>>;

/// Typed publish/subscribe over [`Pubsub`], keyed by [`Topic`]. Blanket-implemented.
#[async_trait]
pub trait PubsubTyped: Pubsub {
    /// Serialize `event` and publish it to `topic`.
    async fn publish_typed<E: Serialize + Send + Sync>(
        &self,
        topic: &Topic<E>,
        event: &E,
    ) -> Result<()> {
        self.publish(topic.as_str(), Bytes::from(ser(event, "event")?))
            .await
    }

    /// Subscribe to `topic`, decoding each payload into `E`.
    async fn subscribe_typed<E: DeserializeOwned + 'static>(
        &self,
        topic: &Topic<E>,
    ) -> Result<TypedSubscription<E>> {
        let sub = self.subscribe(topic.as_str()).await?;
        Ok(sub
            .map(|item| item.and_then(|bytes| de_slice::<E>(&bytes, "event")))
            .boxed())
    }
}

impl<P: Pubsub + ?Sized> PubsubTyped for P {}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use serde::Deserialize;
    use std::time::Duration;

    #[derive(Serialize, Deserialize, PartialEq, Debug)]
    struct SendEmail {
        to: String,
    }
    impl QueuePayload for SendEmail {
        const QUEUE: QueueName<Self> = QueueName::new("emails");
        const MAX_ATTEMPTS: u32 = 3;
    }

    #[test]
    fn queue_payload_binds_name_and_defaults() {
        assert_eq!(SendEmail::QUEUE.as_str(), "emails");
        assert_eq!(SendEmail::enqueue_opts().max_attempts, 3);
    }

    #[test]
    fn keys_carry_their_strings() {
        let k: KvKey<u64> = KvKey::new("counter:1");
        assert_eq!(k.as_str(), "counter:1");
        let c = ConfigKey::new("max_upload", 1024u64);
        assert_eq!(c.as_str(), "max_upload");
        assert_eq!(*c.default_value(), 1024);
        let t: Topic<SendEmail> = Topic::new("emails.events");
        assert_eq!(t.as_str(), "emails.events");
        let b: BlobKey<()> = BlobKey::new("avatars/u1.png");
        assert_eq!(b.as_str(), "avatars/u1.png");
    }

    #[test]
    fn rate_bucket_is_const_constructible() {
        const LOGIN: RateBucket<str> = RateBucket::new(
            "login",
            Limit {
                max: 5,
                per: Duration::from_secs(60),
                algo: crate::ratelimit::Algo::TokenBucket,
            },
            FailMode::Closed,
        );
        assert_eq!(LOGIN.bucket, "login");
    }
}