openmeter 0.1.2

A Rust client for OpenMeter API
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
//! A simple Rust library that demonstrates how to call the Meter endpoints of OpenMeter.
//!
//! Add the following to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! reqwest = "0.11"
//! serde = { version = "1.0", features = ["derive"] }
//! serde_json = "1.0"
//! tokio = { version = "1", features = ["macros"] }
//! ```
//!
//! # Example
//! ```ignore
//! use openmeter::{MeterClient, CreateMeterRequest};
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let client = MeterClient::new("https://openmeter.cloud".to_string(), "YOUR_SECRET_TOKEN".to_string());
//!
//!     // Create a meter
//!     let create_req = CreateMeterRequest {
//!         slug: "tokens_total".to_string(),
//!         name: Some("Tokens Total".to_string()),
//!         description: Some("AI Token Usage".to_string()),
//!         aggregation: "SUM".to_string(),
//!         event_type: "prompt".to_string(),
//!         event_from: None,
//!         value_property: Some("$.tokens".to_string()),
//!         group_by: Some(serde_json::json!({
//!             "model": "$.model",
//!             "type": "$.type"
//!         })),
//!         metadata: None,
//!     };
//!     let meter = client.create_meter(&create_req).await?;
//!     println!("Created meter: {:?}", meter);
//!
//!     Ok(())
//! }
//! ```

#![allow(dead_code)]

use reqwest::{Client, Error};
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// A convenient client to interact with the Meter esndpoints.
#[derive(Debug, Clone)]
pub struct MeterClient {
    base_url: String,
    token: String,
    http_client: Client,
}

impl MeterClient {
    /// Create a new client with the given base URL and an auth token.
    pub fn new(base_url: String, token: String) -> Self {
        MeterClient {
            base_url,
            token,
            http_client: Client::new(),
        }
    }

    fn get_auth_header(&self) -> String {
        format!("Bearer {}", self.token)
    }

    /// Create a new meter.
    ///
    /// POST /api/v1/meters
    pub async fn create_meter(&self, body: &CreateMeterRequest) -> Result<Meter, Error> {
        let url = format!("{}/api/v1/meters", self.base_url);
        let resp = self
            .http_client
            .post(url)
            .header("Authorization", self.get_auth_header())
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Meter>().await?)
    }

    /// Delete a meter by ID or slug.
    ///
    /// DELETE /api/v1/meters/{meterIdOrSlug}
    pub async fn delete_meter(&self, meter_id_or_slug: &str) -> Result<(), Error> {
        let url = format!("{}/api/v1/meters/{}", self.base_url, meter_id_or_slug);
        self.http_client
            .delete(url)
            .header("Authorization", self.get_auth_header())
            .send()
            .await?
            .error_for_status()?;

        Ok(())
    }

    /// Get a meter by ID or slug.
    ///
    /// GET /api/v1/meters/{meterIdOrSlug}
    pub async fn get_meter(&self, meter_id_or_slug: &str) -> Result<Meter, Error> {
        let url = format!("{}/api/v1/meters/{}", self.base_url, meter_id_or_slug);
        let resp = self
            .http_client
            .get(url)
            .header("Authorization", self.get_auth_header())
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Meter>().await?)
    }

    /// List all meters.
    ///
    /// GET /api/v1/meters
    pub async fn list_meters(&self) -> Result<Vec<Meter>, Error> {
        let url = format!("{}/api/v1/meters", self.base_url);
        let resp = self
            .http_client
            .get(url)
            .header("Authorization", self.get_auth_header())
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Vec<Meter>>().await?)
    }

    /// List subjects for a meter.
    ///
    /// GET /api/v1/meters/{meterIdOrSlug}/subjects
    pub async fn list_meter_subjects(&self, meter_id_or_slug: &str) -> Result<Vec<String>, Error> {
        let url = format!(
            "{}/api/v1/meters/{}/subjects",
            self.base_url, meter_id_or_slug
        );
        let resp = self
            .http_client
            .get(url)
            .header("Authorization", self.get_auth_header())
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Vec<String>>().await?)
    }

    /// Query meter usage.
    ///
    /// GET /api/v1/meters/{meterIdOrSlug}/query
    ///
    /// Supports optional query parameters:
    /// - from
    /// - to
    /// - windowSize
    /// - windowTimeZone
    /// - subject (repeated)
    /// - filterGroupBy[...] (etc.)
    pub async fn query_meter(
        &self,
        meter_id_or_slug: &str,
        params: &QueryParams,
    ) -> Result<QueryResponse, Error> {
        let url = format!("{}/api/v1/meters/{}/query", self.base_url, meter_id_or_slug);
        let request_builder = self
            .http_client
            .get(url)
            .header("Authorization", self.get_auth_header());

        // We build the query parameters manually:
        let mut query_params = vec![];
        if let Some(ref from) = params.from {
            query_params.push(("from", from.clone()));
        }
        if let Some(ref to) = params.to {
            query_params.push(("to", to.clone()));
        }
        if let Some(ref window_size) = params.window_size {
            query_params.push(("windowSize", window_size.clone()));
        }
        if let Some(ref window_tz) = params.window_time_zone {
            query_params.push(("windowTimeZone", window_tz.clone()));
        }
        if let Some(subjects) = &params.subject {
            for s in subjects {
                query_params.push(("subject", s.clone()));
            }
        }
        // If you have groupBy filters or other items, add them here as well.

        let resp = request_builder
            .query(&query_params)
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<QueryResponse>().await?)
    }

    /// Update a meter by ID or slug.
    ///
    /// PUT /api/v1/meters/{meterIdOrSlug}
    pub async fn update_meter(
        &self,
        meter_id_or_slug: &str,
        body: &UpdateMeterRequest,
    ) -> Result<Meter, Error> {
        let url = format!("{}/api/v1/meters/{}", self.base_url, meter_id_or_slug);
        let resp = self
            .http_client
            .put(url)
            .header("Authorization", self.get_auth_header())
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Meter>().await?)
    }

    /*  -----------------------------
    Event Endpoints
    ----------------------------- */

    /// Ingest a single or batch of CloudEvents.
    ///
    /// POST /api/v1/events
    pub async fn ingest_events(&self, events: &[CloudEvent]) -> Result<(), Error> {
        let url = format!("{}/api/v1/events", self.base_url);
        // The docs mention `application/cloudevents+json`, but the example uses `application/json`.
        // Adjust if your server enforces `application/cloudevents+json`.
        self.http_client
            .post(url)
            .header("Authorization", self.get_auth_header())
            .header("Content-Type", "application/json")
            .json(&events)
            .send()
            .await?
            .error_for_status()?;

        Ok(())
    }

    /// List ingested events within a time range or by other filters.
    ///
    /// GET /api/v1/events
    ///
    /// For example:
    /// - from / to
    /// - ingestedAtFrom / ingestedAtTo
    /// - subject (partial match)
    /// - id (partial match)
    /// - limit
    pub async fn list_events(
        &self,
        params: &ListEventsParams,
    ) -> Result<Vec<IngestedEvent>, Error> {
        let url = format!("{}/api/v1/events", self.base_url);
        let mut query_params = vec![];

        if let Some(ref client_id) = params.client_id {
            query_params.push(("clientId", client_id.clone()));
        }
        if let Some(ref ingested_at_from) = params.ingested_at_from {
            query_params.push(("ingestedAtFrom", ingested_at_from.clone()));
        }
        if let Some(ref ingested_at_to) = params.ingested_at_to {
            query_params.push(("ingestedAtTo", ingested_at_to.clone()));
        }
        if let Some(ref id) = params.id {
            query_params.push(("id", id.clone()));
        }
        if let Some(ref subject) = params.subject {
            query_params.push(("subject", subject.clone()));
        }
        if let Some(ref from) = params.from {
            query_params.push(("from", from.clone()));
        }
        if let Some(ref to) = params.to {
            query_params.push(("to", to.clone()));
        }
        if let Some(limit) = params.limit {
            query_params.push(("limit", format!("{}", limit)));
        }

        let resp = self
            .http_client
            .get(url)
            .header("Authorization", self.get_auth_header())
            .query(&query_params)
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Vec<IngestedEvent>>().await?)
    }

    // -----------------------------------------------------------------------
    // Entitlements & Features
    // -----------------------------------------------------------------------

    //
    // 1. Create Entitlement: POST /api/v1/subjects/{subjectIdOrKey}/entitlements
    //
    pub async fn create_entitlement(
        &self,
        subject_id_or_key: &str,
        req: CreateEntitlementRequest,
    ) -> Result<Entitlement, Error> {
        let url = format!(
            "{}/api/v1/subjects/{}/entitlements",
            self.base_url, subject_id_or_key
        );
        let resp = self
            .http_client
            .post(url)
            .header("Authorization", self.get_auth_header())
            .json(&req)
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Entitlement>().await?)
    }

    //
    // 2. Create Feature: POST /api/v1/features
    //
    pub async fn create_feature(&self, req: CreateFeatureRequest) -> Result<Feature, Error> {
        let url = format!("{}/api/v1/features", self.base_url);
        let resp = self
            .http_client
            .post(url)
            .header("Authorization", self.get_auth_header())
            .json(&req)
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Feature>().await?)
    }

    //
    // 3. Create Grant: POST /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants
    //
    pub async fn create_grant(
        &self,
        subject_id_or_key: &str,
        entitlement_id_or_feature_key: &str,
        req: GrantRequest,
    ) -> Result<Grant, Error> {
        let url = format!(
            "{}/api/v1/subjects/{}/entitlements/{}/grants",
            self.base_url, subject_id_or_key, entitlement_id_or_feature_key
        );
        let resp = self
            .http_client
            .post(url)
            .header("Authorization", self.get_auth_header())
            .json(&req)
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Grant>().await?)
    }

    //
    // 4. Delete Entitlement: DELETE /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}
    //
    pub async fn delete_entitlement(
        &self,
        subject_id_or_key: &str,
        entitlement_id: &str,
    ) -> Result<(), Error> {
        let url = format!(
            "{}/api/v1/subjects/{}/entitlements/{}",
            self.base_url, subject_id_or_key, entitlement_id
        );
        self.http_client
            .delete(url)
            .header("Authorization", self.get_auth_header())
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    //
    // 5. Delete Feature: DELETE /api/v1/features/{featureId}
    //
    pub async fn delete_feature(&self, feature_id: &str) -> Result<(), Error> {
        let url = format!("{}/api/v1/features/{}", self.base_url, feature_id);
        self.http_client
            .delete(url)
            .header("Authorization", self.get_auth_header())
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    //
    // 6. Get Entitlement: GET /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}
    //
    pub async fn get_entitlement(
        &self,
        subject_id_or_key: &str,
        entitlement_id: &str,
    ) -> Result<Entitlement, Error> {
        let url = format!(
            "{}/api/v1/subjects/{}/entitlements/{}",
            self.base_url, subject_id_or_key, entitlement_id
        );
        let resp = self
            .http_client
            .get(url)
            .header("Authorization", self.get_auth_header())
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Entitlement>().await?)
    }

    //
    // 7. Get Entitlement by ID: GET /api/v1/entitlements/{entitlementId}
    //
    pub async fn get_entitlement_by_id(&self, entitlement_id: &str) -> Result<Entitlement, Error> {
        let url = format!("{}/api/v1/entitlements/{}", self.base_url, entitlement_id);
        let resp = self
            .http_client
            .get(url)
            .header("Authorization", self.get_auth_header())
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Entitlement>().await?)
    }

    //
    // 8. Get Entitlement History: GET /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/history
    //
    pub async fn get_entitlement_history(
        &self,
        subject_id_or_key: &str,
        entitlement_id: &str,
        from: Option<String>,
        to: Option<String>,
        window_size: String, // MINUTE, HOUR, DAY
        window_time_zone: Option<String>,
    ) -> Result<Value, Error> {
        let url = format!(
            "{}/api/v1/subjects/{}/entitlements/{}/history",
            self.base_url, subject_id_or_key, entitlement_id
        );

        let mut query_params = vec![("windowSize", window_size)];
        if let Some(f) = from {
            query_params.push(("from", f));
        }
        if let Some(t) = to {
            query_params.push(("to", t));
        }
        if let Some(tz) = window_time_zone {
            query_params.push(("windowTimeZone", tz));
        }

        let resp = self
            .http_client
            .get(url)
            .header("Authorization", self.get_auth_header())
            .query(&query_params)
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Value>().await?)
    }

    //
    // 9. Get Entitlement Value: GET /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/value
    //
    pub async fn get_entitlement_value(
        &self,
        subject_id_or_key: &str,
        entitlement_id_or_feature_key: &str,
        time: Option<String>,
    ) -> Result<Value, Error> {
        let url = format!(
            "{}/api/v1/subjects/{}/entitlements/{}/value",
            self.base_url, subject_id_or_key, entitlement_id_or_feature_key
        );

        let mut query_params = vec![];
        if let Some(t) = time {
            query_params.push(("time", t));
        }

        let resp = self
            .http_client
            .get(url)
            .header("Authorization", self.get_auth_header())
            .query(&query_params)
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Value>().await?)
    }

    //
    // 10. Get Feature: GET /api/v1/features/{featureId}
    //
    pub async fn get_feature(&self, feature_id: &str) -> Result<Feature, Error> {
        let url = format!("{}/api/v1/features/{}", self.base_url, feature_id);
        let resp = self
            .http_client
            .get(url)
            .header("Authorization", self.get_auth_header())
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Feature>().await?)
    }

    //
    // 11. List All Entitlements: GET /api/v1/entitlements
    //
    pub async fn list_all_entitlements(&self) -> Result<Vec<Entitlement>, Error> {
        let url = format!("{}/api/v1/entitlements", self.base_url);
        let resp = self
            .http_client
            .get(url)
            .header("Authorization", self.get_auth_header())
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Vec<Entitlement>>().await?)
    }

    //
    // 12. List Entitlement Grants: GET /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/grants
    //
    pub async fn list_entitlement_grants(
        &self,
        subject_id_or_key: &str,
        entitlement_id_or_feature_key: &str,
    ) -> Result<Vec<Grant>, Error> {
        let url = format!(
            "{}/api/v1/subjects/{}/entitlements/{}/grants",
            self.base_url, subject_id_or_key, entitlement_id_or_feature_key
        );
        let resp = self
            .http_client
            .get(url)
            .header("Authorization", self.get_auth_header())
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Vec<Grant>>().await?)
    }

    //
    // 13. List Entitlements for a subject: GET /api/v1/subjects/{subjectIdOrKey}/entitlements
    //
    pub async fn list_entitlements(
        &self,
        subject_id_or_key: &str,
    ) -> Result<Vec<Entitlement>, Error> {
        let url = format!(
            "{}/api/v1/subjects/{}/entitlements",
            self.base_url, subject_id_or_key
        );
        let resp = self
            .http_client
            .get(url)
            .header("Authorization", self.get_auth_header())
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Vec<Entitlement>>().await?)
    }

    //
    // 14. List Features: GET /api/v1/features
    //
    pub async fn list_features(&self) -> Result<Vec<Feature>, Error> {
        let url = format!("{}/api/v1/features", self.base_url);
        let resp = self
            .http_client
            .get(url)
            .header("Authorization", self.get_auth_header())
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Vec<Feature>>().await?)
    }

    //
    // 15. List Grants: GET /api/v1/grants
    //
    pub async fn list_grants(&self) -> Result<Vec<Grant>, Error> {
        let url = format!("{}/api/v1/grants", self.base_url);
        let resp = self
            .http_client
            .get(url)
            .header("Authorization", self.get_auth_header())
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Vec<Grant>>().await?)
    }

    //
    // 16. Override Entitlement: PUT /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementIdOrFeatureKey}/override
    //
    pub async fn override_entitlement(
        &self,
        subject_id_or_key: &str,
        entitlement_id_or_feature_key: &str,
        req: CreateEntitlementRequest,
    ) -> Result<Entitlement, Error> {
        let url = format!(
            "{}/api/v1/subjects/{}/entitlements/{}/override",
            self.base_url, subject_id_or_key, entitlement_id_or_feature_key
        );
        let resp = self
            .http_client
            .put(url)
            .header("Authorization", self.get_auth_header())
            .json(&req)
            .send()
            .await?
            .error_for_status()?;

        Ok(resp.json::<Entitlement>().await?)
    }

    //
    // 17. Reset Entitlement: POST /api/v1/subjects/{subjectIdOrKey}/entitlements/{entitlementId}/reset
    //
    pub async fn reset_entitlement(
        &self,
        subject_id_or_key: &str,
        entitlement_id: &str,
        req: ResetEntitlementRequest,
    ) -> Result<(), Error> {
        let url = format!(
            "{}/api/v1/subjects/{}/entitlements/{}/reset",
            self.base_url, subject_id_or_key, entitlement_id
        );
        self.http_client
            .post(url)
            .header("Authorization", self.get_auth_header())
            .json(&req)
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }

    //
    // 18. Void Grant: DELETE /api/v1/grants/{grantId}
    //
    pub async fn void_grant(&self, grant_id: &str) -> Result<(), Error> {
        let url = format!("{}/api/v1/grants/{}", self.base_url, grant_id);
        self.http_client
            .delete(url)
            .header("Authorization", self.get_auth_header())
            .send()
            .await?
            .error_for_status()?;
        Ok(())
    }
}

/// Request body to create a meter.
///
/// This mirrors the required format for POST /api/v1/meters.
#[derive(Debug, Serialize, Deserialize)]
pub struct CreateMeterRequest {
    /// A unique, human-readable identifier for the meter.
    /// Must consist only of alphanumeric and underscore characters.
    #[serde(rename = "slug")]
    pub slug: String,

    /// Human-readable name for the resource.
    /// Defaults to the slug if not specified.
    #[serde(rename = "name")]
    pub name: Option<String>,

    /// Optional description for the meter.
    #[serde(rename = "description")]
    pub description: Option<String>,

    /// The aggregation type to use for the meter (SUM, UNIQUE_COUNT, COUNT, etc.).
    #[serde(rename = "aggregation")]
    pub aggregation: String,

    /// The event type to aggregate.
    #[serde(rename = "eventType")]
    pub event_type: String,

    /// The date since the meter should include events.
    /// Example "2023-01-01T00:00:00Z". If not specified, all events are included.
    #[serde(rename = "eventFrom")]
    pub event_from: Option<String>,

    /// JSONPath expression to extract the value from the ingested event's data property.
    #[serde(rename = "valueProperty")]
    pub value_property: Option<String>,

    /// Named JSONPath expressions to extract the group by values from the event data.
    #[serde(rename = "groupBy")]
    pub group_by: Option<Value>,

    /// Additional metadata for the resource.
    #[serde(rename = "metadata")]
    pub metadata: Option<Value>,
}

/// Request body to update a meter.
///
/// This mirrors the required format for PUT /api/v1/meters/{meterIdOrSlug}.
#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateMeterRequest {
    /// Optional new name for the meter.
    #[serde(rename = "name")]
    pub name: Option<String>,

    /// Optional new description for the meter.
    #[serde(rename = "description")]
    pub description: Option<String>,

    /// Named JSONPath expressions to extract the group by values from the event data.
    #[serde(rename = "groupBy")]
    pub group_by: Option<Value>,

    /// Additional metadata for the resource.
    #[serde(rename = "metadata")]
    pub metadata: Option<Value>,
}

/// Represents a Meter object returned from the API.
#[derive(Debug, Serialize, Deserialize)]
pub struct Meter {
    pub id: String,
    pub slug: String,
    pub name: String,
    pub description: Option<String>,
    pub aggregation: String,
    pub eventType: String,
    pub valueProperty: Option<String>,
    pub groupBy: Option<Value>,
    pub createdAt: String,
    pub updatedAt: String,
}

/// Represents optional parameters for querying meter usage.
#[derive(Debug, Default)]
pub struct QueryParams {
    pub from: Option<String>,
    pub to: Option<String>,
    pub window_size: Option<String>,
    pub window_time_zone: Option<String>,
    /// If you want to filter usage by subject(s).
    pub subject: Option<Vec<String>>,
    // Example extension: pub filter_group_by: Option<HashMap<String, String>>,
}

/// Represents the response structure from Querying usage.
#[derive(Debug, Serialize, Deserialize)]
pub struct QueryResponse {
    pub from: String,
    pub to: String,
    pub windowSize: Option<String>,
    pub data: Vec<QueryData>,
}

/// Individual data point in the usage query response.
#[derive(Debug, Serialize, Deserialize)]
pub struct QueryData {
    pub value: f64,
    pub windowStart: Option<String>,
    pub windowEnd: Option<String>,
    pub subject: Option<String>,

    /// The groupBy object if grouping was requested.
    #[serde(default)]
    pub groupBy: Option<Value>,
}

/*  -----------------------------
 Events Data Structures
----------------------------- */

/// Represents a single CloudEvent.
///
/// See CloudEvents schema: https://github.com/cloudevents/spec
#[derive(Debug, Serialize, Deserialize)]
pub struct CloudEvent {
    /// Identifies the event.
    pub id: String,

    /// Identifies the context in which an event happened.
    pub source: String,

    /// The version of the CloudEvents specification (defaults: "1.0").
    pub specversion: String,

    /// The type of event (e.g., "prompt").
    #[serde(rename = "type")]
    pub r#type: String,

    /// Subject of the event. Must be at least 1 character.
    pub subject: String,

    /// Timestamp of when the occurrence happened. Must adhere to RFC 3339 or be omitted.
    pub time: Option<String>,

    /// Identifies the schema that data adheres to.
    pub dataschema: Option<String>,

    /// Content type of the CloudEvents data value, typically "application/json".
    pub datacontenttype: Option<String>,

    /// The event payload. Optional, if present must be a JSON object.
    pub data: Option<Value>,
}

/// Parameters for listing events.
///
/// If neither `from` nor `ingested_at_from` is specified, it defaults to last 72 hours.
#[derive(Debug, Default)]
pub struct ListEventsParams {
    pub client_id: Option<String>,
    pub ingested_at_from: Option<String>,
    pub ingested_at_to: Option<String>,
    pub id: Option<String>,
    pub subject: Option<String>,
    pub from: Option<String>,
    pub to: Option<String>,
    pub limit: Option<u32>,
}

/// Represents an event that was ingested, including timestamps.
#[derive(Debug, Serialize, Deserialize)]
pub struct IngestedEvent {
    pub event: CloudEvent,
    pub ingestedAt: String,
    pub storedAt: String,
}

// ---------------------------------------------------------------------------
// Request/Response Models for Entitlements & Features
// ---------------------------------------------------------------------------

/// Request body to create an Entitlement (all entitlement types).
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateEntitlementRequest {
    /// Feature key for the entitlement.
    pub feature_key: String,

    /// Optional feature ID to link (if known).
    pub feature_id: Option<String>,

    /// One of "metered", "boolean", "static".
    pub r#type: String,

    /// For "metered" entitlements only
    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_soft_limit: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub is_unlimited: Option<bool>,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub usage_period: Option<Value>, // e.g. { "interval": "DAY", "anchor": "2023-01-01T01:01:01Z" }

    #[serde(skip_serializing_if = "Option::is_none")]
    pub measure_usage_from: Option<String>, // e.g. "CURRENT_PERIOD_START"

    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

/// Response model for an Entitlement.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Entitlement {
    pub id: String,
    pub feature_id: String,
    pub feature_key: String,
    pub subject_key: String,
    pub r#type: String,
    pub is_soft_limit: bool,
    pub is_unlimited: bool,
    pub created_at: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deleted_at: Option<String>,
    // etc. (expand as needed)
}

/// Request body to create a Feature.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateFeatureRequest {
    pub key: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub meter_slug: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub meter_group_by_filters: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
}

/// Response model for a Feature.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Feature {
    pub id: String,
    pub key: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deleted_at: Option<String>,
    // etc. (expand as needed)
}

/// Request body to create a Grant.
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GrantRequest {
    pub amount: f64,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<u8>,
    pub effective_at: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expiration: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub max_rollover_amount: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_rollover_amount: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recurrence: Option<Value>,
}

/// Response model for a Grant.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Grant {
    pub id: String,
    pub entitlement_id: String,
    pub amount: f64,
    pub effective_at: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deleted_at: Option<String>,
    // etc. (expand as needed)
}

/// Request body to reset an Entitlement.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResetEntitlementRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub effective_at: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retain_anchor: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub preserve_overage: Option<bool>,
}