ax_sdk 0.2.0

Tools for interacting with the services of an ax node
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
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
use crate::files::FilesGetResponse;
use anyhow::Result;
use ax_types::{
    service::{
        AuthenticationResponse, OffsetsResponse, Order, PublishEvent, PublishRequest, PublishResponse, QueryRequest,
        QueryResponse, SessionId, SubscribeMonotonicRequest, SubscribeMonotonicResponse, SubscribeRequest,
        SubscribeResponse,
    },
    AppManifest, NodeId, OffsetMap, Payload, TagSet,
};
use bytes::Bytes;
use futures::{
    future::{self, BoxFuture, FusedFuture},
    stream::{iter, BoxStream, Stream, StreamExt},
    FutureExt,
};
use libipld::Cid;
use rand::Rng;
use reqwest::{
    header::{CONTENT_DISPOSITION, CONTENT_TYPE},
    multipart::Form,
    Client, RequestBuilder, Response, StatusCode,
};
use serde::{Deserialize, Serialize};
use std::{
    fmt::Debug,
    future::Future,
    mem::replace,
    pin::Pin,
    str::FromStr,
    sync::{Arc, RwLock},
};
use url::Url;

/// [`Ax`]'s configuration options.
pub struct AxOpts {
    pub url: url::Url,
    pub manifest: AppManifest,
}

impl AxOpts {
    /// Create an [`AxOpts`] with a custom URL and the default application manifest.
    ///
    /// This function is similar manually constructing the following:
    /// ```no_run
    /// # use ax_sdk::AxOpts;
    /// # fn opts() -> AxOpts {
    /// AxOpts {
    ///     url: "https://your.host:1234".parse().unwrap(),
    ///     ..Default::default()
    /// }.into()
    /// # }
    /// ```
    pub fn url(url: &str) -> anyhow::Result<Self> {
        Ok(Self {
            url: Url::from_str(url)?,
            ..Default::default()
        })
    }

    /// Create an [`AxOpts`] with a custom application manifest and the default URL.
    ///
    /// This function is similar manually constructing the following:
    /// ```no_run
    /// # use ax_sdk::{types::{app_id, AppManifest}, AxOpts};
    /// # fn opts() -> AxOpts {
    /// AxOpts {
    ///     manifest: AppManifest::trial(
    ///         app_id!("com.example.app"),
    ///         "Example manifest".to_string(),
    ///         "0.1.0".to_string()
    ///     ).unwrap(),
    ///     ..Default::default()
    /// }.into()
    /// # }
    /// ```
    pub fn manifest(manifest: AppManifest) -> anyhow::Result<Self> {
        Ok(Self {
            manifest,
            ..Default::default()
        })
    }
}

impl Default for AxOpts {
    /// Return a default set of options.
    ///
    /// The default URL is `http://localhost:4454`,
    /// for the default manifest see [`AppManifest`].
    fn default() -> Self {
        Self {
            url: url::Url::from_str("http://localhost:4454").unwrap(),
            manifest: Default::default(),
        }
    }
}

async fn get_token(client: &Client, base_url: &Url, app_manifest: &AppManifest) -> anyhow::Result<String> {
    let body = serde_json::to_value(app_manifest).context(|| format!("serializing {:?}", app_manifest))?;
    let response = client.post(base_url.join("auth")?).json(&body).send().await?;
    let bytes = response
        .bytes()
        .await
        .context(|| "getting body for authentication response")?;
    let token: AuthenticationResponse =
        serde_json::from_slice(bytes.as_ref()).context(|| "deserializing authentication response")?;
    Ok(token.token)
}

/// The AX client.
#[derive(Clone)]
pub struct Ax {
    client: Client,
    base_url: Url,
    token: Arc<RwLock<String>>,
    app_manifest: AppManifest,
    node_id: NodeId,
}

impl Ax {
    /// Instantiate a new [`Ax`] with the provided options.
    ///
    /// See [`AxOpts`] for more information.
    pub async fn new(opts: AxOpts) -> anyhow::Result<Self> {
        let origin = opts.url;
        let app_manifest = opts.manifest;

        // NOTE(duarte): we could probably validate this in the opts
        // We would need to provide a `new` instead of letting users do struct instantiation by hand though
        anyhow::ensure!(!origin.cannot_be_a_base(), "{} is not a valid base address", origin);
        let mut base_url = origin;
        base_url.set_path("api/v2/");
        let client = Client::new();

        let node_id = client
            .get(base_url.join("node/id").unwrap())
            .send()
            .await?
            .text()
            .await
            .context(|| "getting body for GET node/id")?
            .parse()?;

        let token = get_token(&client, &base_url, &app_manifest).await?;

        Ok(Self {
            client,
            base_url,
            token: Arc::new(RwLock::new(token)),
            app_manifest,
            node_id,
        })
    }

    /// Return the ID of the node [`Ax`] is connected to.
    pub fn node_id(&self) -> NodeId {
        self.node_id
    }

    pub(crate) fn events_url(&self, path: &str) -> Url {
        // Safe to unwrap, because we fully control path creation
        self.base_url.join(&format!("events/{}", path)).unwrap()
    }

    pub(crate) fn files_url(&self) -> Url {
        self.base_url.join("files/").unwrap()
    }

    async fn re_authenticate(&self) -> anyhow::Result<String> {
        let token = get_token(&self.client, &self.base_url, &self.app_manifest).await?;
        let mut write_guard = self.token.write().unwrap();
        *write_guard = token.clone();
        Ok(token)
    }

    /// Perform a request (to AX APIs).
    /// If an authorization error (code 401) is returned, it will try to re-authenticate.
    /// If the service is unavailable (code 503), this method will retry to perform the
    /// request up to 10 times with exponentially increasing delay - currently,
    /// this behavior is only available if the `with-tokio` feature is enabled.
    pub(crate) async fn do_request(&self, f: impl FnOnce(&Client) -> RequestBuilder) -> anyhow::Result<Response> {
        let token = self.token.read().unwrap().clone();
        let builder = f(&self.client);
        let builder_clone = builder.try_clone();

        let req = builder.header("Authorization", &format!("Bearer {}", token)).build()?;
        let url = req.url().clone();
        let method = req.method().clone();
        let mut response = self
            .client
            .execute(req)
            .await
            .context(|| format!("sending {} {}", method, url))?;

        if let Some(builder) = builder_clone.as_ref() {
            // Request body is not a Stream, so we can retry
            if response.status() == StatusCode::UNAUTHORIZED {
                let token = self.re_authenticate().await?;
                response = builder
                    .try_clone()
                    .expect("Already cloned it once")
                    .header("Authorization", &format!("Bearer {}", token))
                    .send()
                    .await
                    .context(|| format!("sending {} {}", method, url))?;
            }

            let mut retries = 10;
            let mut delay = std::time::Duration::from_secs(0);
            loop {
                if response.status() == StatusCode::SERVICE_UNAVAILABLE && retries > 0 {
                    retries -= 1;
                    delay = delay * 2 + std::time::Duration::from_millis(rand::thread_rng().gen_range(10..200));
                    tracing::debug!(
                        "AX Node is overloaded, retrying {} {} with a delay of {:?}",
                        method,
                        url,
                        delay
                    );
                    tokio::time::sleep(delay).await;
                    response = builder
                        .try_clone()
                        .expect("Already cloned it once")
                        .header("Authorization", &format!("Bearer {}", token))
                        .send()
                        .await
                        .context(|| format!("sending {} {}", method, url))?;
                } else {
                    break;
                }
            }
        } else {
            tracing::warn!("Request can't be retried, as its body is based on a stream");
            // Request body is a stream, so impossible to retry
            if response.status() == StatusCode::UNAUTHORIZED {
                tracing::info!("Can't retry request, but re-authenticated anyway. SDK user must retry request.");
                self.re_authenticate().await?;
            }
        }

        if response.status().is_success() {
            Ok(response)
        } else {
            let error_code = response.status().as_u16();
            Err(AxError {
                error: response
                    .json()
                    .await
                    .context(|| format!("getting body for {} reply to {:?}", error_code, builder_clone))?,
                error_code,
                context: format!("sending {:?}", builder_clone),
            }
            .into())
        }
    }

    // TODO: #558
    pub async fn files_post(&self, files: impl IntoIterator<Item = reqwest::multipart::Part>) -> anyhow::Result<Cid> {
        let mut form = Form::new();
        for file in files {
            form = form.part("file", file);
        }
        let response = self
            .do_request(move |c| c.post(self.files_url()).multipart(form))
            .await?;
        let hash = response
            .text_with_charset("utf-8")
            .await
            .context(|| "Parsing response".to_string())?;
        let cid = Cid::from_str(&hash).map_err(|e| AxError {
            error: serde_json::Value::String(e.to_string()),
            error_code: 102,
            context: format!("Tried to parse {} into a Cid", hash),
        })?;
        Ok(cid)
    }

    // TODO: #558
    pub async fn files_get(&self, cid_or_name: &str) -> anyhow::Result<FilesGetResponse> {
        let url = self.files_url().join(cid_or_name)?;
        let response = self.do_request(move |c| c.get(url)).await?;

        let maybe_name = response.headers().get(CONTENT_DISPOSITION).cloned();
        let maybe_mime = response.headers().get(CONTENT_TYPE).cloned();
        let bytes = response.bytes().await?;
        if let Ok(dir @ FilesGetResponse::Directory { .. }) = serde_json::from_slice(bytes.as_ref()) {
            Ok(dir)
        } else {
            let mime = maybe_mime
                .and_then(|h| h.to_str().ok().map(|x| x.to_string()))
                .unwrap_or_else(|| "application/octet-stream".to_string());
            let name = maybe_name
                .and_then(|n| {
                    n.to_str().ok().and_then(|p| {
                        p.split(';')
                            .find(|x| x.starts_with("filename="))
                            .map(|f| f.trim_start_matches("filename=").to_string())
                    })
                })
                .unwrap_or_default();
            Ok(FilesGetResponse::File {
                name,
                bytes: bytes.to_vec(),
                mime,
            })
        }
    }

    /// Returns known offsets across local and replicated streams.
    ///
    /// If an authorization error (code 401) is returned, it will try to re-authenticate.
    /// If the service is unavailable (code 503), this method will retry to perform the
    /// request up to 10 times with exponentially increasing delay - currently,
    /// this behavior is only available if the `with-tokio` feature is enabled.
    pub async fn offsets(&self) -> anyhow::Result<OffsetsResponse> {
        let response = self.do_request(|c| c.get(self.events_url("offsets"))).await?;
        let bytes = response
            .bytes()
            .await
            .context(|| format!("getting body for GET {}", self.events_url("offsets")))?;
        Ok(serde_json::from_slice(bytes.as_ref()).context(|| {
            format!(
                "deserializing offsets response from {:?} received from GET {}",
                bytes,
                self.events_url("offsets")
            )
        })?)
    }

    /// Returns a builder for publishing events.
    ///
    /// [`Publish`] implements the [`Future`] trait, thus, it can be `.await`ed.
    ///
    /// Example:
    /// ```no_run
    /// use ax_sdk::{Ax, AxOpts, types::service::PublishResponse};
    /// async fn publish_example() {
    ///     let response = Ax::new(AxOpts::default())
    ///         .await
    ///         .unwrap()
    ///         .publish()
    ///         .await
    ///         .unwrap();
    ///     println!("{:?}", response);
    /// }
    /// ```
    pub fn publish(&self) -> Publish<'_> {
        Publish::new(self)
    }

    /// Returns a builder to query events.
    ///
    /// Query order defined in the query itself takes precedence over options.
    /// See [`Query::with_order`] for more information.
    ///
    /// [`Query`] implements the [`Future`] trait, thus, it can be `.await`ed.
    ///
    /// Example:
    /// ```no_run
    /// use ax_sdk::{Ax, AxOpts, types::service::QueryResponse};
    /// use futures::stream::StreamExt;
    /// async fn query_example() {
    ///     let mut response = Ax::new(AxOpts::default())
    ///         .await
    ///         .unwrap()
    ///         .query("FROM allEvents")
    ///         .await
    ///         .unwrap();
    ///     while let Some(event) = response.next().await {
    ///         println!("{:?}", event);
    ///     }
    /// }
    /// ```
    pub fn query<Q: Into<String> + Send>(&self, query: Q) -> Query<'_> {
        Query::new(self, query)
    }

    /// Returns a builder to subscribe to an event query.
    ///
    /// [`Subscribe`] implements the [`Future`] trait, thus, it can be `.await`ed.
    ///
    /// Example:
    /// ```no_run
    /// use ax_sdk::{Ax, AxOpts, types::service::SubscribeResponse};
    /// use futures::stream::StreamExt;
    /// async fn subscribe_example() {
    ///     let service = Ax::new(AxOpts::default()).await.unwrap();
    ///     let mut subscribe_stream = service.subscribe("FROM 'example:tag'").await.unwrap();
    ///     while let Some(response) = subscribe_stream.next().await {
    ///         println!("{:?}", response)
    ///     }
    /// }
    /// ```
    pub fn subscribe<Q: Into<String> + Send>(&self, query: Q) -> Subscribe<'_> {
        Subscribe::new(self, query)
    }

    /// Returns a builder to subscribe to an event query.
    ///
    /// [`SubscribeMonotonic`] implements the [`Future`] trait, thus, it can be `.await`ed.
    ///
    /// Example:
    /// ```no_run
    /// use ax_sdk::{Ax, AxOpts, types::service::SubscribeMonotonicResponse};
    /// use futures::stream::StreamExt;
    /// async fn subscribe_monotonic_example() {
    ///     let service = Ax::new(AxOpts::default()).await.unwrap();
    ///     let mut subscribe_stream = service.subscribe_monotonic("FROM 'example:tag'").await.unwrap();
    ///     while let Some(response) = subscribe_stream.next().await {
    ///         println!("{:?}", response)
    ///     }
    /// }
    /// ```
    pub fn subscribe_monotonic<Q: Into<String> + Send>(&self, query: Q) -> SubscribeMonotonic<'_> {
        SubscribeMonotonic::new(self, query)
    }
}

impl Debug for Ax {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Ax")
            .field("base_url", &self.base_url.as_str())
            .field("app_manifest", &self.app_manifest)
            .finish()
    }
}

pub(crate) fn to_lines(stream: impl Stream<Item = Result<Bytes, reqwest::Error>>) -> impl Stream<Item = Vec<u8>> {
    let mut buf = Vec::<u8>::new();
    let to_lines = move |bytes: Bytes| {
        buf.extend_from_slice(bytes.as_ref());
        let mut ret = buf.split(|b| *b == b'\n').map(|bs| bs.to_vec()).collect::<Vec<_>>();
        if let Some(last) = ret.pop() {
            buf.clear();
            buf.extend_from_slice(last.as_ref());
        }
        iter(ret.into_iter().map(|mut bs| {
            if bs.ends_with(b"\r") {
                bs.pop();
            }
            bs
        }))
    };
    stream
        .take_while(|res| future::ready(res.is_ok()))
        .map(|res| res.unwrap())
        .map(to_lines)
        .flatten()
}

/// Request builder for event publishing.
///
/// Warning: [`Publish`] implements the [`Future`] trait and as such it can be polled.
/// Calling _any_ [`Publish`] function after polling will result in a panic!
pub enum Publish<'a> {
    Initial { client: &'a Ax, request: PublishRequest },
    Pending(BoxFuture<'a, anyhow::Result<PublishResponse>>),
    Void,
}

impl<'a> Publish<'a> {
    fn new(client: &'a Ax) -> Self {
        Self::Initial {
            client,
            request: PublishRequest { data: vec![] },
        }
    }

    /// Add an event.
    ///
    /// This adds the given event to the list of events that will be emitted once this
    /// publishing request is submitted by using `.await` on it.
    ///
    /// # Panics
    ///
    /// Calling this function after polling [`Publish`] will result in a panic.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ax_sdk::{Ax, AxOpts, types::{tags, service::PublishResponse}};
    /// async fn event_example() -> PublishResponse {
    ///     let service = Ax::new(AxOpts::default()).await.unwrap();
    ///     service
    ///         .publish()
    ///         .event(
    ///             tags!("temperature", "sensor:temp-sensor1"),
    ///             &serde_json::json!({ "temperature": 10 }),
    ///         )
    ///         .unwrap()
    ///         .event(
    ///             tags!("temperature", "sensor:temp-sensor2"),
    ///             &serde_json::json!({ "temperature": 21 }),
    ///         )
    ///         .unwrap()
    ///         .await
    ///         .unwrap()
    /// }
    /// ```
    pub fn event<E: Serialize>(mut self, tags: TagSet, event: &E) -> Result<Self, serde_cbor::Error> {
        if let Self::Initial { ref mut request, .. } = self {
            request.data.push(PublishEvent {
                tags,
                payload: Payload::compact(event)?,
            });
            return Ok(self);
        }
        panic!("Calling Publish::event after polling.")
    }

    /// Add events from an iterable.
    ///
    /// This adds the given events to the list of events that will be emitted once this
    /// publishing request is submitted by using `.await` on it.
    ///
    /// # Panics
    ///
    ///  Calling this function after polling [`Publish`] will result in a panic.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ax_sdk::{types::{tags, Payload, service::{PublishEvent, PublishResponse}}, Ax, AxOpts};
    /// async fn events_example() -> PublishResponse {
    ///     let service = Ax::new(AxOpts::default()).await.unwrap();
    ///     service
    ///         .publish()
    ///         .events([
    ///             PublishEvent {
    ///                 tags: tags!("temperature", "sensor:temp-sensor1"),
    ///                 payload: Payload::compact(&serde_json::json!({ "temperature": 10 })).unwrap(),
    ///             },
    ///             PublishEvent {
    ///                 tags: tags!("temperature", "sensor:temp-sensor2"),
    ///                 payload: Payload::compact(&serde_json::json!({ "temperature": 27 })).unwrap(),
    ///             },
    ///         ])
    ///         .await
    ///         .unwrap()
    /// }
    /// ```
    pub fn events<E: IntoIterator<Item = impl Into<PublishEvent>>>(mut self, events: E) -> Self {
        if let Self::Initial { ref mut request, .. } = self {
            request.data.extend(events.into_iter().map(Into::into));
            return self;
        }
        panic!("Calling Publish::events after polling.");
    }
}

impl<'a> Future for Publish<'a> {
    type Output = anyhow::Result<PublishResponse>;

    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output> {
        let this = self.get_mut();
        loop {
            *this = match replace(this, Publish::Void) {
                Publish::Initial { client, request } => {
                    let publish_response = async move {
                        let publish_url = client.events_url("publish");
                        let response = client.do_request(|c| c.post(publish_url).json(&request)).await?;
                        let body = response.bytes().await?;
                        Ok(serde_json::from_slice::<PublishResponse>(&body)?)
                    };
                    Publish::Pending(publish_response.boxed())
                }
                Publish::Pending(mut publish_response_future) => {
                    let polled = publish_response_future.poll_unpin(cx);
                    if polled.is_pending() {
                        *this = Publish::Pending(publish_response_future);
                    }
                    return polled;
                }
                Publish::Void => panic!("Polling a terminated Publish future"),
            };
        }
    }
}

impl<'a> FusedFuture for Publish<'a> {
    fn is_terminated(&self) -> bool {
        matches!(self, Publish::Void)
    }
}

/// Request builder for queries.
///
/// Warning: [`Query`] implements the [`Future`] trait, as such it can be polled.
/// Calling _any_ [`Query`] function after polling will result in a panic!
pub enum Query<'a> {
    Initial { client: &'a Ax, request: QueryRequest },
    Pending(BoxFuture<'a, anyhow::Result<BoxStream<'static, QueryResponse>>>),
    Void,
}

impl<'a> Query<'a> {
    fn new<Q: Into<String>>(client: &'a Ax, query: Q) -> Self {
        Self::Initial {
            client,
            request: QueryRequest {
                query: query.into(),
                lower_bound: Some(OffsetMap::empty()),
                upper_bound: None,
                order: Order::Asc,
            },
        }
    }

    /// Add a (exclusive) lower bound to the query.
    ///
    /// For more information on offsets, as well as lower and upper bounds refer to the
    /// [offsets and partitions](https://developer.actyx.com/docs/conceptual/event-streams#offsets-and-partitions) documentation page.
    ///
    /// The lower bound limits the start of the query events.
    /// As an example, consider the following (example) events:
    /// ```json
    /// { "offset": 1, "event": { "temperature": 10 } }
    /// { "offset": 3, "event": { "temperature": 12 } }
    /// { "offset": 14, "event": { "temperature": 9 } }
    /// ```
    /// If you set the lower bound to `10`, only the last event will be returned.
    ///
    /// # Panics
    ///
    /// Calling this function after polling [`Query`] will result in a panic.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ax_sdk::{Ax, AxOpts, types::service::QueryResponse};
    /// use futures::stream::StreamExt;
    /// async fn lower_bound_example() {
    ///     let service = Ax::new(AxOpts::default()).await.unwrap();
    ///     // It's not always the case that you need to read the past
    ///     // hence, you can get the current offsets and read from then onwards
    ///     let present_offsets = service.offsets().await.unwrap().present;
    ///     let mut response = service.query("FROM allEvents")
    ///         .with_lower_bound(present_offsets)
    ///         .await
    ///         .unwrap();
    ///     while let Some(event) = response.next().await {
    ///         println!("{:?}", event);
    ///     }
    /// }
    /// ```
    ///
    /// Generating an `OffsetMap` out of thin air is usually not possible because they
    /// require stream IDs — which require knowledge of the streams and so on.
    /// Hence, a more involved and useful example requires you to perform a query to
    /// get an offset map when the query finishes streaming all results.
    ///
    /// ```no_run
    /// use ax_sdk::{types::{tags, Offset, service::QueryResponse}, Ax, AxOpts};
    /// use futures::stream::StreamExt;
    /// async fn lower_bound_example() {
    ///     let service = Ax::new(AxOpts::default()).await.unwrap();
    ///     // We're publishing events for a completely functional example
    ///     let publish_response = service
    ///         .publish()
    ///         .event(
    ///             tags!("temperature", "sensor:temp-sensor1"),
    ///             &serde_json::json!({ "temperature": 10 }),
    ///         ).unwrap()
    ///         .event(
    ///             tags!("temperature", "sensor:temp-sensor2"),
    ///             &serde_json::json!({ "temperature": 21 }),
    ///         ).unwrap()
    ///         .event(
    ///             tags!("temperature", "sensor:temp-sensor3"),
    ///             &serde_json::json!({ "temperature": 40 }),
    ///         ).unwrap()
    ///         .await.unwrap();
    ///     // Query for the "halfway" event
    ///     let mut query_response = service
    ///         .query("FROM 'sensor:temp-sensor2'")
    ///         .await
    ///         .unwrap();
    ///     // This loop is a bit of a dirty hack for demonstration purposes
    ///     // in real world usage you will most likely be using the events
    ///     // and keeping the offset map in the end.
    ///     let offsets = loop {
    ///         let result = query_response.next().await.unwrap();
    ///         if let QueryResponse::Offsets(offsets) = result {
    ///             break offsets.offsets;
    ///         }
    ///     };
    ///     // Query for all 'temperature' events with the previous query `OffsetMap`
    ///     // as a lower bound. We're expecting to only see events after the "halfway"
    ///     // event — {"temperature"}
    ///     let mut query_response = service
    ///         .query("FROM 'temperature'")
    ///         .with_lower_bound(offsets.clone())
    ///         .await.unwrap();
    ///     while let Some(response) = query_response.next().await {
    ///         println!("{:?}", response);
    ///     }
    /// }
    /// ```
    pub fn with_lower_bound(mut self, lower_bound: OffsetMap) -> Self {
        if let Self::Initial { ref mut request, .. } = self {
            request.lower_bound = Some(lower_bound);
            return self;
        }
        panic!("Calling Query::with_lower_bound after polling.")
    }

    /// Add an (inclusive) upper bound to the query.
    ///
    /// For more information on offsets, as well as lower and upper bounds refer to the
    /// [offsets and partitions](https://developer.actyx.com/docs/conceptual/event-streams#offsets-and-partitions) documentation page.
    ///
    /// The upper bound limits the start of the query events.
    /// As an example, consider the following (example) events:
    /// ```json
    /// { "offset": 1, "event": { "temperature": 10 } }
    /// { "offset": 3, "event": { "temperature": 12 } }
    /// { "offset": 14, "event": { "temperature": 9 } }
    /// ```
    /// If you set the upper bound to `10`, the first two events will be returned.
    ///
    /// # Panics
    ///
    /// Calling this function after polling [`Query`] will result in a panic.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use ax_sdk::{Ax, AxOpts};
    /// use futures::stream::StreamExt;
    /// async fn upper_bound_example() {
    ///     let service = Ax::new(AxOpts::default()).await.unwrap();
    ///     let present_offsets = service.offsets().await.unwrap().present;
    ///     let mut response = service.query("FROM allEvents")
    ///         .with_upper_bound(present_offsets)
    ///         .await
    ///         .unwrap();
    ///     while let Some(event) = response.next().await {
    ///         println!("{:?}", event);
    ///     }
    /// }
    /// ```
    ///
    /// Generating an `OffsetMap` out of thin air is usually not possible because they
    /// require stream IDs — which require knowledge of the streams and so on.
    /// Hence, a more involved and useful example requires you to perform a query to
    /// get an offset map when the query finishes streaming all results.
    ///
    /// ```no_run
    /// use ax_sdk::{types::{tags, Offset, service::QueryResponse}, Ax, AxOpts};
    /// use futures::stream::StreamExt;
    /// async fn upper_bound_example() {
    ///     let service = Ax::new(AxOpts::default()).await.unwrap();
    ///     // We're publishing events for a completely functional example
    ///     let publish_response = service
    ///         .publish()
    ///         .event(
    ///             tags!("temperature", "sensor:temp-sensor1"),
    ///             &serde_json::json!({ "temperature": 10 }),
    ///         ).unwrap()
    ///         .event(
    ///             tags!("temperature", "sensor:temp-sensor2"),
    ///             &serde_json::json!({ "temperature": 21 }),
    ///         ).unwrap()
    ///         .event(
    ///             tags!("temperature", "sensor:temp-sensor3"),
    ///             &serde_json::json!({ "temperature": 40 }),
    ///         ).unwrap()
    ///         .await.unwrap();
    ///     // Query for the "halfway" event
    ///     let mut query_response = service
    ///         .query("FROM 'sensor:temp-sensor2'")
    ///         .await
    ///         .unwrap();
    ///     // This loop is a bit of a dirty hack for demonstration purposes
    ///     // in real world usage you will most likely be using the events
    ///     // and keeping the offset map in the end.
    ///     let offsets = loop {
    ///         let result = query_response.next().await.unwrap();
    ///         if let QueryResponse::Offsets(offsets) = result {
    ///             break offsets.offsets;
    ///         }
    ///     };
    ///     // Query for all 'temperature' events with the previous query `OffsetMap`
    ///     // as an upper bound. We're expecting to only see events after the "halfway"
    ///     // event — {"temperature"}
    ///     let mut query_response = service
    ///         .query("FROM 'temperature'")
    ///         .with_upper_bound(offsets.clone())
    ///         .await.unwrap();
    ///     while let Some(response) = query_response.next().await {
    ///         println!("{:?}", response);
    ///     }
    /// }
    /// ```
    pub fn with_upper_bound(mut self, upper_bound: OffsetMap) -> Self {
        if let Self::Initial { ref mut request, .. } = self {
            request.upper_bound = Some(upper_bound);
            return self;
        }
        panic!("Calling Query::with_upper_bound after polling.")
    }

    /// Dual to [`Query::with_upper_bound`], removes the upper bound.
    ///
    /// When no upper bound is provided or is removed using this function
    /// it will be filled in by AX when processing the query, the upper bound
    /// will then be the currently known offsets (in other words, the "present").
    ///
    /// # Panics
    ///
    /// Calling this function after polling [`Query`] will result in a panic.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ax_sdk::{Ax, AxOpts};
    /// use futures::stream::StreamExt;
    /// async fn upper_bound_example() {
    ///     let service = Ax::new(AxOpts::default()).await.unwrap();
    ///     let present_offsets = service.offsets().await.unwrap().present;
    ///     let mut response = service.query("FROM allEvents")
    ///         .with_upper_bound(present_offsets)
    ///         // Remove the upper bound (the example is obtuse for demonstration purposes)
    ///         .without_upper_bound()
    ///         .await
    ///         .unwrap();
    ///     while let Some(event) = response.next().await {
    ///         println!("{:?}", event);
    ///     }
    /// }
    /// ```
    pub fn without_upper_bound(mut self) -> Self {
        if let Self::Initial { ref mut request, .. } = self {
            request.upper_bound = None;
            return self;
        }
        panic!("Calling Query::without_upper_bound after polling.")
    }

    /// Set the query's event order.
    ///
    /// By default, this value is set to [`Order::Asc`], however,
    /// order set in the query takes precedence over the order defined using this function.
    /// The precedence order flows like so:
    ///
    /// 1. Explicit `ORDER` in query
    /// 2. Inferred from `AGGREGATE` in query
    /// 3. [`Query::with_order`] call
    ///
    /// As an example, consider the following (example) events:
    /// ```json
    /// { "offset": 1, "event": { "temperature": 10 } }
    /// { "offset": 3, "event": { "temperature": 12 } }
    /// { "offset": 14, "event": { "temperature": 9 } }
    /// ```
    /// If your query sets [`Order::Desc`], the result will instead look like:
    /// ```json
    /// { "offset": 14, "event": { "temperature": 9 } }
    /// { "offset": 3, "event": { "temperature": 12 } }
    /// { "offset": 1, "event": { "temperature": 10 } }
    /// ```
    ///
    /// # Panics
    ///
    /// Calling this function after polling [`Query`] will result in a panic.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ax_sdk::{Ax, AxOpts, types::service::Order};
    /// use futures::stream::StreamExt;
    /// async fn order_example() {
    ///     let service = Ax::new(AxOpts::default()).await.unwrap();
    ///     let mut response = service.query("FROM allEvents")
    ///         .with_order(Order::Desc)
    ///         .await
    ///         .unwrap();
    ///     while let Some(event) = response.next().await {
    ///         println!("{:?}", event);
    ///     }
    /// }
    /// ```
    pub fn with_order(mut self, order: Order) -> Self {
        if let Self::Initial { ref mut request, .. } = self {
            request.order = order;
            return self;
        }
        panic!("Calling Query::with_order after polling.")
    }
}

impl<'a> Future for Query<'a> {
    type Output = anyhow::Result<BoxStream<'static, QueryResponse>>;

    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output> {
        let this = self.get_mut();
        loop {
            *this = match replace(this, Query::Void) {
                Query::Initial { client, request } => {
                    let query_response = async move {
                        let query_url = client.events_url("query");
                        let response = client.do_request(|c| c.post(query_url).json(&request)).await?;
                        let response_stream = to_lines(response.bytes_stream())
                            .map(|bytes| serde_json::from_slice::<QueryResponse>(&bytes))
                            // FIXME this swallows deserialization errors, silently dropping event envelopes
                            .filter_map(|res| future::ready(res.ok()))
                            .boxed();
                        Ok(response_stream)
                    };
                    Query::Pending(query_response.boxed())
                }
                Query::Pending(mut query_responses_future) => {
                    let polled = query_responses_future.poll_unpin(cx);
                    if polled.is_pending() {
                        *this = Query::Pending(query_responses_future);
                    }
                    return polled;
                }
                Query::Void => panic!("Polling a terminated Query future"),
            }
        }
    }
}

impl<'a> FusedFuture for Query<'a> {
    fn is_terminated(&self) -> bool {
        matches!(self, Query::Void)
    }
}

/// Request builder for subscriptions.
///
/// Warning: [`Subscribe`] implements the [`Future`] trait, as such it can be polled.
/// Calling _any_ [`Subscribe`] function after polling will result in a panic!
pub enum Subscribe<'a> {
    Initial { client: &'a Ax, request: SubscribeRequest },
    Pending(BoxFuture<'a, anyhow::Result<BoxStream<'static, SubscribeResponse>>>),
    Void,
}

impl<'a> Subscribe<'a> {
    fn new<Q: Into<String>>(client: &'a Ax, query: Q) -> Self {
        Self::Initial {
            client,
            request: SubscribeRequest {
                query: query.into(),
                lower_bound: Some(OffsetMap::empty()),
            },
        }
    }

    /// Add a (exclusive) lower bound to the subscription query.
    ///
    /// For more information on offsets, as well as lower and upper bounds refer to the
    /// [offsets and partitions](https://developer.actyx.com/docs/conceptual/event-streams#offsets-and-partitions) documentation page.
    ///
    /// The lower bound limits the start of the query events.
    /// As an example, consider the following (example) events:
    /// ```json
    /// { "offset": 1, "event": { "temperature": 10 } }
    /// { "offset": 3, "event": { "temperature": 12 } }
    /// { "offset": 14, "event": { "temperature": 9 } }
    /// ```
    /// If you set the lower bound to `10`, the first event to be returned
    /// would be the last of the example.
    ///
    /// # Panics
    ///
    /// Calling this function after polling [`Subscribe`] will result in a panic.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ax_sdk::{Ax, AxOpts};
    /// use futures::stream::StreamExt;
    /// async fn lower_bound_example() {
    ///     let service = Ax::new(AxOpts::default()).await.unwrap();
    ///     let present_offsets = service.offsets().await.unwrap().present;
    ///     let mut response = service.subscribe("FROM allEvents")
    ///         .with_lower_bound(present_offsets)
    ///         .await
    ///         .unwrap();
    ///     while let Some(event) = response.next().await {
    ///         println!("{:?}", event);
    ///     }
    /// }
    /// ```
    ///
    /// Generating an `OffsetMap` out of thin air is usually not possible because they
    /// require stream IDs — which require knowledge of the streams and so on.
    /// Hence, a more involved and useful example requires you to perform a query to
    /// get an offset map when the query finishes streaming all results.
    ///
    /// ```no_run
    /// use ax_sdk::{types::{tags, Offset, service::QueryResponse}, Ax, AxOpts};
    /// use futures::stream::StreamExt;
    /// async fn lower_bound_example() {
    ///     let service = Ax::new(AxOpts::default()).await.unwrap();
    ///     // We're publishing events for a completely functional example
    ///     let publish_response = service
    ///         .publish()
    ///         .event(
    ///             tags!("temperature", "sensor:temp-sensor1"),
    ///             &serde_json::json!({ "temperature": 10 }),
    ///         ).unwrap()
    ///         .event(
    ///             tags!("temperature", "sensor:temp-sensor2"),
    ///             &serde_json::json!({ "temperature": 21 }),
    ///         ).unwrap()
    ///         .event(
    ///             tags!("temperature", "sensor:temp-sensor3"),
    ///             &serde_json::json!({ "temperature": 40 }),
    ///         ).unwrap()
    ///         .await.unwrap();
    ///     // Query for the "halfway" event
    ///     let mut query_response = service
    ///         .query("FROM 'sensor:temp-sensor2'")
    ///         .await
    ///         .unwrap();
    ///     // This loop is a dirty hack for demonstration purposes
    ///     // in real world usage you will most likely be using the events
    ///     // and keeping the offset map in the end.
    ///     let offsets = loop {
    ///         let result = query_response.next().await.unwrap();
    ///         if let QueryResponse::Offsets(offsets) = result {
    ///             break offsets.offsets;
    ///         }
    ///     };
    ///     // Subcribe for all 'temperature' events with the previous query `OffsetMap`
    ///     // as a lower bound. We're expecting to only see events after the "halfway"
    ///     // event — {"temperature"}
    ///     let mut subscribe_response = service
    ///         .subscribe("FROM 'temperature'")
    ///         .with_lower_bound(offsets.clone())
    ///         .await.unwrap();
    ///     while let Some(response) = query_response.next().await {
    ///         println!("{:?}", response);
    ///     }
    /// }
    /// ```
    pub fn with_lower_bound(mut self, lower_bound: OffsetMap) -> Self {
        if let Self::Initial { ref mut request, .. } = self {
            request.lower_bound = Some(lower_bound);
            return self;
        }
        panic!("Calling Subscribe::with_lower_bound after polling.")
    }
}

impl<'a> Future for Subscribe<'a> {
    type Output = anyhow::Result<BoxStream<'static, SubscribeResponse>>;

    fn poll(self: Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output> {
        let this = self.get_mut();
        loop {
            *this = match replace(this, Self::Void) {
                Self::Initial { client, request } => {
                    let query_response = async move {
                        let query_url = client.events_url("subscribe");
                        let response = client.do_request(|c| c.post(query_url).json(&request)).await?;
                        let response_stream = to_lines(response.bytes_stream())
                            .map(|bytes| serde_json::from_slice::<SubscribeResponse>(&bytes))
                            // FIXME this swallows deserialization errors, silently dropping event envelopes
                            .filter_map(|res| future::ready(res.ok()))
                            .boxed();
                        Ok(response_stream)
                    };
                    Self::Pending(query_response.boxed())
                }
                Self::Pending(mut query_responses_future) => {
                    let polled = query_responses_future.poll_unpin(cx);
                    if polled.is_pending() {
                        *this = Self::Pending(query_responses_future);
                    }
                    return polled;
                }
                Self::Void => panic!("Polling a terminated Query future"),
            }
        }
    }
}

impl<'a> FusedFuture for Subscribe<'a> {
    fn is_terminated(&self) -> bool {
        matches!(self, Subscribe::Void)
    }
}

/// Request builder for monotonic subscriptions.
///
/// Monotonic subscriptions keep track of the highest sort order
/// ([`LamportTimestamp`](crate::types::LamportTimestamp) and
/// [`StreamId`](crate::types::StreamId)) seen so far, ending the stream with a
/// [`SubscribeMonotonicResponse::TimeTravel`](SubscribeMonotonicResponse::TimeTravel)
/// message if the next event would be out of order.
///
/// Warning: [`SubscribeMonotonic`] implements the [`Future`] trait, as such it can be polled.
/// Calling _any_ [`SubscribeMonotonic`] function after polling will result in a panic!
pub enum SubscribeMonotonic<'a> {
    Initial {
        client: &'a Ax,
        request: SubscribeMonotonicRequest,
    },
    Pending(BoxFuture<'a, anyhow::Result<BoxStream<'static, SubscribeMonotonicResponse>>>),
    Void,
}

impl<'a> SubscribeMonotonic<'a> {
    fn new<Q: Into<String>>(client: &'a Ax, query: Q) -> Self {
        Self::Initial {
            client,
            request: SubscribeMonotonicRequest {
                query: query.into(),
                session: SessionId::from("me"),
                lower_bound: OffsetMap::empty(),
            },
        }
    }

    // NOTE: Currently not being used. This is an "artifact" for future reference.
    #[allow(dead_code)]
    fn with_session_id<T: Into<SessionId>>(mut self, session_id: T) -> Self {
        if let Self::Initial { ref mut request, .. } = self {
            request.session = session_id.into();
            return self;
        }
        panic!("Calling SubscribeMonotonic::with_session_id after polling.")
    }

    // TODO: there's info missing about the difference between Subscribe and SubscribeMonotonic
    /// Add a (exclusive) lower bound to the subscription query.
    ///
    /// For more information on offsets, as well as lower and upper bounds refer to the
    /// [offsets and partitions](https://developer.actyx.com/docs/conceptual/event-streams#offsets-and-partitions) documentation page.
    ///
    /// The lower bound limits the start of the query events.
    /// As an example, consider the following (example) events:
    /// ```json
    /// { "offset": 1, "event": { "temperature": 10 } }
    /// { "offset": 3, "event": { "temperature": 12 } }
    /// { "offset": 14, "event": { "temperature": 9 } }
    /// ```
    /// If you set the lower bound to `10`, the first event to be returned
    /// would be the last of the example.
    ///
    /// # Panics
    ///
    /// Calling this function after polling [`Subscribe`] will result in a panic.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ax_sdk::{Ax, AxOpts};
    /// use futures::stream::StreamExt;
    /// async fn lower_bound_example() {
    ///     let service = Ax::new(AxOpts::default()).await.unwrap();
    ///     let present_offsets = service.offsets().await.unwrap().present;
    ///     let mut response = service.subscribe("FROM allEvents")
    ///         .with_lower_bound(present_offsets)
    ///         .await
    ///         .unwrap();
    ///     while let Some(event) = response.next().await {
    ///         println!("{:?}", event);
    ///     }
    /// }
    /// ```
    ///
    /// Generating an `OffsetMap` out of thin air is usually not possible because they
    /// require stream IDs — which require knowledge of the streams and so on.
    /// Hence, a more involved and useful example requires you to perform a query to
    /// get an offset map when the query finishes streaming all results.
    ///
    /// ```no_run
    /// use ax_sdk::{types::{tags, Offset, service::QueryResponse}, Ax, AxOpts};
    /// use futures::stream::StreamExt;
    /// async fn lower_bound_example() {
    ///     let service = Ax::new(AxOpts::default()).await.unwrap();
    ///     // We're publishing events for a completely functional example
    ///     let publish_response = service
    ///         .publish()
    ///         .event(
    ///             tags!("temperature", "sensor:temp-sensor1"),
    ///             &serde_json::json!({ "temperature": 10 }),
    ///         ).unwrap()
    ///         .event(
    ///             tags!("temperature", "sensor:temp-sensor2"),
    ///             &serde_json::json!({ "temperature": 21 }),
    ///         ).unwrap()
    ///         .event(
    ///             tags!("temperature", "sensor:temp-sensor3"),
    ///             &serde_json::json!({ "temperature": 40 }),
    ///         ).unwrap()
    ///         .await.unwrap();
    ///     // Query for the "halfway" event
    ///     let mut query_response = service
    ///         .query("FROM 'sensor:temp-sensor2'")
    ///         .await
    ///         .unwrap();
    ///     // This loop is a dirty hack for demonstration purposes
    ///     // in real world usage you will most likely be using the events
    ///     // and keeping the offset map in the end.
    ///     let offsets = loop {
    ///         let result = query_response.next().await.unwrap();
    ///         if let QueryResponse::Offsets(offsets) = result {
    ///             break offsets.offsets;
    ///         }
    ///     };
    ///     // Subcribe for all 'temperature' events with the previous query `OffsetMap`
    ///     // as a lower bound. We're expecting to only see events after the "halfway"
    ///     // event — {"temperature"}
    ///     let mut subscribe_response = service
    ///         .subscribe_monotonic("FROM 'temperature'")
    ///         .with_lower_bound(offsets.clone())
    ///         .await.unwrap();
    ///     while let Some(response) = query_response.next().await {
    ///         println!("{:?}", response);
    ///     }
    /// }
    /// ```
    pub fn with_lower_bound(mut self, lower_bound: OffsetMap) -> Self {
        if let Self::Initial { ref mut request, .. } = self {
            request.lower_bound = lower_bound;
            return self;
        }
        panic!("Calling SubscribeMonotonic::with_lower_bound after polling.")
    }
}

impl<'a> Future for SubscribeMonotonic<'a> {
    type Output = anyhow::Result<BoxStream<'static, SubscribeMonotonicResponse>>;

    fn poll(self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>) -> std::task::Poll<Self::Output> {
        let this = self.get_mut();
        loop {
            *this = match replace(this, Self::Void) {
                Self::Initial { client, request } => {
                    let query_response = async move {
                        let query_url = client.events_url("subscribe_monotonic");
                        let response = client.do_request(|c| c.post(query_url).json(&request)).await?;
                        let response_stream = to_lines(response.bytes_stream())
                            .map(|bytes| serde_json::from_slice::<SubscribeMonotonicResponse>(&bytes))
                            // FIXME this swallows deserialization errors, silently dropping event envelopes
                            .filter_map(|res| future::ready(res.ok()))
                            .boxed();
                        Ok(response_stream)
                    };
                    Self::Pending(query_response.boxed())
                }
                Self::Pending(mut query_responses_future) => {
                    let polled = query_responses_future.poll_unpin(cx);
                    if polled.is_pending() {
                        *this = Self::Pending(query_responses_future);
                    }
                    return polled;
                }
                Self::Void => panic!("Polling a terminated Query future"),
            }
        }
    }
}

impl<'a> FusedFuture for SubscribeMonotonic<'a> {
    fn is_terminated(&self) -> bool {
        matches!(self, SubscribeMonotonic::Void)
    }
}

/// Error type that is returned in the response body by the Event Service when requests fail
///
/// The Event Service does not map client errors or internal errors to HTTP status codes,
/// instead it gives more structured information using this data type, except when the request
/// is not understood at all.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, derive_more::Error, derive_more::Display)]
#[display(fmt = "error {} while {}: {}", error_code, context, error)]
#[serde(rename_all = "camelCase")]
pub struct AxError {
    pub error: serde_json::Value,
    pub error_code: u16,
    pub context: String,
}

pub(crate) trait WithContext {
    type Output;
    fn context<F, T>(self, context: F) -> Self::Output
    where
        T: Into<String>,
        F: FnOnce() -> T;
}
impl<T, E> WithContext for std::result::Result<T, E>
where
    AxError: From<(String, E)>,
{
    type Output = std::result::Result<T, AxError>;

    #[inline]
    fn context<F, C>(self, context: F) -> Self::Output
    where
        C: Into<String>,
        F: FnOnce() -> C,
    {
        match self {
            Ok(value) => Ok(value),
            Err(err) => Err(AxError::from((context().into(), err))),
        }
    }
}

impl From<(String, reqwest::Error)> for AxError {
    fn from(e: (String, reqwest::Error)) -> Self {
        Self {
            error: serde_json::json!(format!("{:?}", e.1)),
            error_code: 101,
            context: e.0,
        }
    }
}

impl From<(String, serde_json::Error)> for AxError {
    fn from(e: (String, serde_json::Error)) -> Self {
        Self {
            error: serde_json::json!(format!("{:?}", e.1)),
            error_code: 102,
            context: e.0,
        }
    }
}

impl From<(String, serde_cbor::Error)> for AxError {
    fn from(e: (String, serde_cbor::Error)) -> Self {
        Self {
            error: serde_json::json!(format!("{:?}", e.1)),
            error_code: 102,
            context: e.0,
        }
    }
}

/// Tests for the builder. Most of these are "dumb" as to keep sure the values or
/// semantics aren't changed without a "purposeful" change — i.e. they are here to make
/// you double check when you change semantics or ensure you didn't miss an `else` that
/// leads to an unconditional panic (not that has ever happened...),
#[cfg(test)]
mod tests {
    use std::sync::{Arc, RwLock};

    use reqwest::Client;

    use ax_types::{
        service::{Order, PublishEvent},
        tags, NodeId, OffsetMap, Payload,
    };

    use super::{Ax, AxOpts, Publish, Query, Subscribe, SubscribeMonotonic};

    /// The normal [`Ax::new`] connects to a client, the client returned by this
    /// function is a "mock" client instead that allows us to test the builder
    /// functions without requiring a connection to AX
    fn new_test_client() -> Ax {
        let opts = AxOpts::default();
        let client = Client::new();

        Ax {
            client,
            base_url: opts.url,
            token: Arc::new(RwLock::new("empty_token".to_string())),
            app_manifest: opts.manifest,
            node_id: NodeId::new([
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            ]),
        }
    }

    #[test]
    fn test_publish_event() {
        let ax = new_test_client();
        let publish = ax
            .publish()
            .event(tags!("test"), &"test_string")
            .expect("The event payload should be serializable");

        if let Publish::Initial { request, .. } = publish {
            assert_eq!(
                request.data,
                vec![PublishEvent::from((
                    tags!("test"),
                    Payload::compact(&"test_string").expect("The event payload must be serializable")
                ))]
            )
        }
    }

    #[test]
    fn test_publish_events() {
        let ax = new_test_client();
        let publish = ax.publish().events([(
            tags!("test"),
            Payload::compact(&"test_string").expect("The event payload should be serializable"),
        )]);

        if let Publish::Initial { request, .. } = publish {
            assert_eq!(
                request.data,
                vec![PublishEvent::from((
                    tags!("test"),
                    Payload::compact(&"test_string").expect("The event payload must be serializable")
                ))]
            )
        }
    }

    #[test]
    fn test_query() {
        let ax = new_test_client();
        let query = ax.query("FROM allEvents");
        if let Query::Initial { request, .. } = query {
            assert_eq!(request.query, "FROM allEvents");
        }
    }

    #[test]
    fn test_query_with_lower_bound() {
        let ax = new_test_client();
        let query = ax.query("FROM allEvents").with_lower_bound(OffsetMap::empty());
        if let Query::Initial { request, .. } = query {
            assert_eq!(request.lower_bound, Some(OffsetMap::empty()));
        }
    }

    #[test]
    fn test_query_with_upper_bound() {
        let ax = new_test_client();
        let query = ax.query("FROM allEvents").with_upper_bound(OffsetMap::empty());
        if let Query::Initial { request, .. } = query {
            assert_eq!(request.upper_bound, Some(OffsetMap::empty()));
        }
    }

    #[test]
    fn test_query_without_upper_bound() {
        let ax = new_test_client();
        let query = ax.query("FROM allEvents").without_upper_bound();
        if let Query::Initial { request, .. } = query {
            assert_eq!(request.upper_bound, None);
        }
    }

    #[test]
    fn test_query_with_order() {
        let ax = new_test_client();
        let query = ax.query("FROM allEvents").with_order(Order::Desc);
        if let Query::Initial { request, .. } = query {
            assert_eq!(request.order, Order::Desc);
        }
    }

    #[test]
    fn test_subcribe() {
        let ax = new_test_client();
        let subscribe = ax.subscribe("FROM allEvents");
        if let Subscribe::Initial { request, .. } = subscribe {
            assert_eq!(request.query, "FROM allEvents");
        }
    }

    #[test]
    fn test_subcribe_with_lower_bound() {
        let ax = new_test_client();
        let subscribe = ax.subscribe("FROM allEvents").with_lower_bound(OffsetMap::empty());
        if let Subscribe::Initial { request, .. } = subscribe {
            assert_eq!(request.lower_bound, Some(OffsetMap::empty()));
        }
    }

    #[test]
    fn test_subscribe_monotonic() {
        let ax = new_test_client();
        let subscribe = ax.subscribe_monotonic("FROM allEvents");
        if let SubscribeMonotonic::Initial { request, .. } = subscribe {
            assert_eq!(request.query, "FROM allEvents");
        }
    }

    #[test]
    fn test_subscribe_monotonic_with_session_id() {
        let ax = new_test_client();
        let subscribe = ax.subscribe_monotonic("FROM allEvents").with_session_id("session_id");
        if let SubscribeMonotonic::Initial { request, .. } = subscribe {
            assert_eq!(request.session.as_str(), "session_id");
        }
    }

    #[test]
    fn test_subscribe_monotonic_with_start_from() {
        let ax = new_test_client();
        let subscribe = ax
            .subscribe_monotonic("FROM allEvents")
            .with_lower_bound(OffsetMap::empty());
        if let SubscribeMonotonic::Initial { request, .. } = subscribe {
            assert_eq!(request.lower_bound, OffsetMap::empty());
        }
    }
}