encore-dev 2.0.0-beta.10

Rust SDK for Encore applications
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
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
//! Pub/Sub topics and subscriptions. Topics are typed by the message they
//! carry and declared at module scope; a subscription names its topic and the
//! function that handles its messages.
//!
//! ```no_run
//! use encore::pubsub::{Message, Subscription, Topic};
//! use serde::{Deserialize, Serialize};
//!
//! #[derive(Serialize, Deserialize)]
//! struct SignupEvent {
//!     user_id: String,
//! }
//!
//! static SIGNUPS: Topic<SignupEvent> = Topic::new("signups");
//!
//! #[encore::pubsub::register]
//! static WELCOME: Subscription<SignupEvent> =
//!     Subscription::new(&SIGNUPS, "send-welcome", send_welcome);
//!
//! async fn send_welcome(msg: Message<SignupEvent>) -> Result<(), encore::Error> {
//!     println!("welcome, {}", msg.data.user_id);
//!     Ok(())
//! }
//!
//! async fn signed_up(user_id: String) -> Result<(), encore::Error> {
//!     SIGNUPS.publish(&SignupEvent { user_id }).await?;
//!     Ok(())
//! }
//! ```
//!
//! # Encodings
//!
//! A topic's second type argument says how its messages are encoded: [`Json`]
//! unless said otherwise, [`Raw`] for bytes passed through as they are, and —
//! with the `protobuf` feature — `Protobuf`. It is part of the topic's type, so
//! a publisher and a subscriber cannot disagree about it, and Encore can read
//! it from the declaration.
//!
//! # Ordered topics
//!
//! An [`OrderedTopic`] delivers the messages that share an ordering key in the
//! order they were published. Its `publish` takes the key.
//!
//! # Batches
//!
//! `publish_batch` publishes up to [`MAX_BATCH_SIZE`] messages in fewer
//! requests than publishing each would take, answering with their ids in the
//! order given. It is not atomic: a [`BatchError`] says which messages were
//! not published. On an ordered topic the messages sharing a key are
//! published in the order given, and none after one of them fails.
//!
//! # References
//!
//! A topic is used by calling its methods; Encore reads from those calls what
//! each service publishes to. To hand a topic to other code, take a
//! reference stating what it may do — [`Topic::reference`] with
//! [`perms::Publisher`] — and have that code take the [`Publisher`] (or
//! [`OrderedPublisher`]) trait.
//!
//! # Running subscriptions
//!
//! A `static` does nothing until it is used, so something has to start a
//! subscription. [`#[encore::pubsub::register]`](macro@register)
//! registers one to be started with the app, by [`crate::initialize`] or
//! [`crate::run_blocking`]. One declared without it is started by hand, with
//! [`Subscription::start`].
//!
//! # Tests
//!
//! Under `encore test` what each test publishes is its own, and nothing
//! handles it on its own: no subscription is started. The test reads back
//! what it — and the code it called — published with
//! [`testing::published`](crate::testing::published), and hands it to a
//! subscription's handler with [`testing::deliver`](crate::testing::deliver).

use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use encore_sdk_core::pubsub as core_pubsub;
use encore_sdk_core::reqctx::Values;
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::error::{ErrCode, Error};
use crate::runtime::core;
use crate::testing;

/// Registers a subscription to be started with the app.
///
/// Put it on the `static`. It also lets the handler be given as the plain
/// name of an `async fn`, in place of the boxing closure [`Subscription::new`]
/// takes.
///
/// ```no_run
/// # use encore::pubsub::{Message, Subscription, Topic};
/// # static SIGNUPS: Topic<String> = Topic::new("signups");
/// #[encore::pubsub::register]
/// static WELCOME: Subscription<String> =
///     Subscription::new(&SIGNUPS, "send-welcome", send_welcome).max_concurrency(4);
///
/// async fn send_welcome(msg: Message<String>) -> Result<(), encore::Error> {
///     Ok(())
/// }
/// ```
pub use encore_macros::register;

/// A message, as a subscription's handler receives it.
#[derive(Debug, Clone)]
pub struct Message<T> {
    /// The message's id, unique within its topic.
    pub id: String,
    /// The message, decoded.
    pub data: T,
    /// The message as it was sent, before decoding.
    pub raw_data: Vec<u8>,
    /// The attributes it was published with. A delivered message's are
    /// without the `encore-ctx-*` ones carrying Request Context fields,
    /// which its handler reads from its context ([`crate::reqctx`]); what
    /// [`testing::published`] returns has them, as published.
    pub attributes: HashMap<String, String>,
    pub publish_time: SystemTime,
    /// Which attempt at delivering the message this is, from 1.
    pub delivery_attempt: u32,
    /// The key it was published with, on an [`OrderedTopic`].
    pub ordering_key: Option<String>,
}

/// How a topic's messages are encoded. Implemented by the encodings, for the
/// message types each can carry.
pub trait Encoding<T> {
    fn encode(value: &T) -> Result<Vec<u8>, Error>;
    fn decode(raw: &[u8]) -> Result<T, Error>;
}

/// JSON, for a message type that is `Serialize` and `Deserialize`. The default.
pub enum Json {}

impl<T: Serialize + DeserializeOwned> Encoding<T> for Json {
    fn encode(value: &T) -> Result<Vec<u8>, Error> {
        serde_json::to_vec(value).map_err(|e| Error::wrap(ErrCode::InvalidArgument, e))
    }

    fn decode(raw: &[u8]) -> Result<T, Error> {
        serde_json::from_slice(raw).map_err(|e| Error::wrap(ErrCode::InvalidArgument, e))
    }
}

/// No encoding: the message is the bytes, as a `Vec<u8>`.
pub enum Raw {}

impl Encoding<Vec<u8>> for Raw {
    fn encode(value: &Vec<u8>) -> Result<Vec<u8>, Error> {
        Ok(value.clone())
    }

    fn decode(raw: &[u8]) -> Result<Vec<u8>, Error> {
        Ok(raw.to_vec())
    }
}

/// Protocol Buffers, for a `prost` message type.
#[cfg(feature = "protobuf")]
pub enum Protobuf {}

#[cfg(feature = "protobuf")]
impl<T: prost::Message + Default> Encoding<T> for Protobuf {
    fn encode(value: &T) -> Result<Vec<u8>, Error> {
        Ok(value.encode_to_vec())
    }

    fn decode(raw: &[u8]) -> Result<T, Error> {
        T::decode(raw).map_err(|e| Error::wrap(ErrCode::InvalidArgument, e))
    }
}

/// Marks a [`Topic`] whose messages are delivered in no particular order.
pub enum Unordered {}

/// Marks a [`Topic`] that orders messages by key: an [`OrderedTopic`].
pub enum Ordered {}

/// A pub/sub topic carrying messages of type `T`, encoded as `E`.
pub struct Topic<T, E = Json, O = Unordered> {
    name: &'static str,
    /// Read by Encore's parser from the declaration, not by the runtime.
    #[allow(dead_code)]
    exactly_once: bool,
    _marker: PhantomData<Carries<T, E, O>>,
}

/// What a topic's type parameters stand for, none of which it holds.
type Carries<T, E, O> = fn() -> (T, E, O);

/// A [`Topic`] that delivers the messages sharing an ordering key in the order
/// they were published.
pub type OrderedTopic<T, E = Json> = Topic<T, E, Ordered>;

/// Options for publishing a message.
///
/// ```no_run
/// # use std::collections::HashMap;
/// # use encore::pubsub::{PublishOptions, Topic};
/// # static SIGNUPS: Topic<String> = Topic::new("signups");
/// # async fn f(tags: HashMap<String, String>) -> Result<(), encore::Error> {
/// let event = "ada".to_string();
/// SIGNUPS
///     .publish_with(
///         &event,
///         PublishOptions::new()
///             .attributes(tags)
///             .attribute("source", "web"),
///     )
///     .await?;
/// # Ok(())
/// # }
/// ```
///
/// Attributes are delivered alongside the message. `encore-ctx-*` ones are
/// Encore's: the message carries the Request Context fields of the context it
/// is published in instead.
#[derive(Debug, Clone, Default)]
pub struct PublishOptions {
    attributes: HashMap<String, String>,
}

impl PublishOptions {
    /// Options without attributes.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds an attribute delivered alongside the message, replacing one of
    /// the same name.
    pub fn attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.attributes.insert(key.into(), value.into());
        self
    }

    /// Adds attributes delivered alongside the message, replacing those of
    /// the same names: a map, or pairs such as `[("source", "web")]`.
    pub fn attributes<K, V>(mut self, attributes: impl IntoIterator<Item = (K, V)>) -> Self
    where
        K: Into<String>,
        V: Into<String>,
    {
        extend(&mut self.attributes, attributes);
        self
    }
}

/// Adds `attributes` to `into`, replacing those of the same names.
fn extend<K: Into<String>, V: Into<String>>(
    into: &mut HashMap<String, String>,
    attributes: impl IntoIterator<Item = (K, V)>,
) {
    into.extend(attributes.into_iter().map(|(k, v)| (k.into(), v.into())));
}

impl<T, E, O> Topic<T, E, O> {
    /// Declare a topic. `const` so it can initialize a module-scope `static`,
    /// whose type gives the message type and the encoding.
    ///
    /// Options follow the name, each a method of its own:
    ///
    /// ```no_run
    /// use encore::pubsub::{OrderedTopic, Raw, Topic};
    ///
    /// static EVENTS: Topic<String> = Topic::new("events");
    /// static PAYMENTS: Topic<String> = Topic::new("payments").exactly_once();
    /// static BLOBS: Topic<Vec<u8>, Raw> = Topic::new("blobs");
    /// static CHANGES: OrderedTopic<String> = OrderedTopic::new("changes");
    /// ```
    pub const fn new(name: &'static str) -> Self {
        Self {
            name,
            exactly_once: false,
            _marker: PhantomData,
        }
    }

    /// Reference an existing topic by name: one another service declares,
    /// possibly in another language. To declare a new topic, use
    /// [`Topic::new`] instead.
    ///
    /// The name must be a string literal, so Encore can resolve it statically.
    /// A named topic takes no options: it is configured where it is declared.
    /// Its message type and encoding are the author's claim: across languages
    /// they cannot be checked.
    ///
    /// ```no_run
    /// static SIGNUPS: encore::pubsub::Topic<String> = encore::pubsub::Topic::named("signups");
    /// ```
    pub const fn named(name: &'static str) -> Self {
        Self::new(name)
    }

    /// Has each message delivered exactly once, rather than at least once.
    ///
    /// Part of the declaration: it takes the topic by value, so it cannot be
    /// called on the `static`.
    pub const fn exactly_once(mut self) -> Self {
        self.exactly_once = true;
        self
    }

    /// Tags the topic with `key` and `value`: key/value classification, such
    /// as `.tag("data", "pci")`, for policies to read. One call per tag, each
    /// with its own key. Encore reads them from the source, so both are string
    /// literals. A key is lowercase letters, digits, `_` and `-`, starting with
    /// a letter and not with `encore`, which is kept for Encore's own tags; a
    /// value is the same characters, or empty. Each is at most 63 characters,
    /// and a topic has at most 32 tags.
    ///
    /// Part of the declaration: it takes the topic by value, so it cannot be
    /// called on the `static`.
    ///
    /// ```no_run
    /// use encore::pubsub::Topic;
    ///
    /// static PAYMENTS: Topic<String> = Topic::new("payments").tag("data", "pci");
    /// ```
    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
        self
    }

    /// The name the topic was declared with.
    pub const fn name(&self) -> &'static str {
        self.name
    }

    /// A reference to the topic that grants only the permissions `P`: for
    /// now [`perms::Publisher`], the only one. Unlike the topic, a reference
    /// can be passed to other code; the service is granted the permissions it
    /// names.
    ///
    /// The permissions must be written as the type argument, since they are
    /// what the service is granted: the compiler never infers them. `const`,
    /// so a reference can initialize a module-scope `static`.
    ///
    /// ```no_run
    /// use encore::pubsub::{perms, Publisher, Topic, TopicRef};
    ///
    /// static SIGNUPS: Topic<String> = Topic::new("signups");
    /// static NOTIFY: TopicRef<perms::Publisher, String> = SIGNUPS.reference::<perms::Publisher>();
    ///
    /// // Library code takes the permission's trait.
    /// async fn notify(topic: &impl Publisher<String>, user: &String) -> Result<(), encore::Error> {
    ///     topic.publish(user).await?;
    ///     Ok(())
    /// }
    /// ```
    ///
    /// ```compile_fail,E0284
    /// # use encore::pubsub::{perms, Topic, TopicRef};
    /// # static SIGNUPS: Topic<String> = Topic::new("signups");
    /// // Not even from the type it is assigned to.
    /// static NOTIFY: TopicRef<perms::Publisher, String> = SIGNUPS.reference();
    /// ```
    pub const fn reference<P: TopicPerms>(&'static self) -> TopicRef<P::Id, T, E, O> {
        TopicRef {
            name: self.name,
            perms: PhantomData,
            _marker: PhantomData,
        }
    }
}

impl<T, E: Encoding<T>, O> Topic<T, E, O> {
    /// The app's topic, which a publish outside a test goes to.
    fn topic(&self) -> Result<core_pubsub::TopicObj, Error> {
        core()
            .pubsub()
            .topic(self.name.into())
            .ok_or_else(|| Error::not_found(format!("topic {:?} is not configured", self.name)))
    }

    /// Records a message the current test published, as the runtime would
    /// have sent it: with the Request Context fields it keeps. It is sent
    /// nowhere: nothing handles what a test publishes until it delivers it.
    fn record(
        &self,
        test: &testing::Scope,
        payload: Vec<u8>,
        mut attributes: HashMap<String, String>,
        ordering_key: Option<String>,
    ) -> Result<String, Error> {
        core().reqctx_fields().retain_published(&mut attributes);
        Ok(test
            .core_scope()?
            .record_published(self.name, payload, attributes, ordering_key))
    }

    /// Encodes and publishes a message: to the app's topic, or under `encore
    /// test` to the current test, which notes it for the test to read back
    /// and sends it nowhere.
    ///
    /// The message carries the Request Context fields of the current
    /// context, in place of any `encore-ctx-*` attributes given: the runtime
    /// publishes it with those the app declares with `pubsub`.
    async fn send(
        &self,
        data: &T,
        mut attributes: HashMap<String, String>,
        ordering_key: Option<&str>,
    ) -> Result<String, Error> {
        use encore_sdk_core::telemetry::opentelemetry::trace::FutureExt as _;
        use encore_sdk_core::telemetry::opentelemetry::Context;

        let payload = E::encode(data)?;
        let ordering_key = ordering_key.map(str::to_owned);
        // In a system test the message carries the test, and is sent: the
        // subscriptions handle it in the services that declare them.
        let cx = testing::outgoing(&Context::current());
        Values::of(&cx).to_attributes(&mut attributes);
        if core().system_test().is_none() {
            if let Some(test) = testing::active()? {
                return self.record(&test, payload, attributes, ordering_key);
            }
        }
        self.topic()?
            .publish(payload, attributes, ordering_key)
            .with_context(cx)
            .await
            .map_err(unavailable)
    }

    /// Encodes and publishes a batch of messages, as [`send`](Self::send)
    /// does each. A batch with a message that cannot be sent as it is — one
    /// that does not encode, or has an empty ordering key — or more than
    /// [`MAX_BATCH_SIZE`] messages is not sent at all.
    async fn send_batch(&self, messages: Vec<Outgoing<'_, T>>) -> Result<Vec<String>, BatchError> {
        let count = messages.len();
        if count == 0 {
            return Ok(Vec::new());
        }
        if count > MAX_BATCH_SIZE {
            return Err(BatchError::refused(
                count,
                Error::invalid_argument(format!(
                    "a batch has at most {MAX_BATCH_SIZE} messages, and this one has {count}"
                )),
            ));
        }

        use encore_sdk_core::telemetry::opentelemetry::trace::FutureExt as _;
        use encore_sdk_core::telemetry::opentelemetry::Context;

        let mut outgoing = Vec::with_capacity(count);
        let mut unsendable = Vec::new();
        for (i, msg) in messages.into_iter().enumerate() {
            let payload = match msg.ordering_key {
                Some("") => Err(Error::invalid_argument(format!(
                    "the ordering key for topic {} cannot be empty",
                    self.name
                ))),
                _ => E::encode(msg.data),
            };
            match payload {
                Ok(payload) => outgoing.push(core_pubsub::OutgoingMessage {
                    payload,
                    attrs: msg.attributes.clone(),
                    ordering_key: msg.ordering_key.map(str::to_owned),
                }),
                Err(err) => unsendable.push((i, err)),
            }
        }
        if let Some(&(first, _)) = unsendable.first() {
            return Err(BatchError::unsendable(count, first, unsendable));
        }

        // Each message carries the Request Context fields, as one sent alone.
        // Read once the batch is known to be sendable: which test the batch
        // is for is the runtime's to say, and a batch refused as it is
        // needs none.
        let cx = testing::outgoing(&Context::current());
        let fields = Values::of(&cx);
        for msg in &mut outgoing {
            fields.to_attributes(&mut msg.attrs);
        }

        let refused = |err| BatchError::refused(count, err);
        if core().system_test().is_none() {
            if let Some(test) = testing::active().map_err(refused)? {
                return outgoing
                    .into_iter()
                    .map(|msg| self.record(&test, msg.payload, msg.attrs, msg.ordering_key))
                    .collect::<Result<_, _>>()
                    .map_err(refused);
            }
        }
        let results = self
            .topic()
            .map_err(refused)?
            .publish_batch(outgoing)
            .with_context(cx)
            .await
            .map_err(|err| refused(Error::wrap(ErrCode::InvalidArgument, format!("{err:#}"))))?;
        let results = settle(count, results);
        BatchError::check(results)
    }

    /// What the current test has published to the topic, decoded.
    pub(crate) fn published_in(&self, test: &testing::Scope) -> Result<Vec<Message<T>>, Error> {
        test.published(self.name)
            .into_iter()
            .map(|published| {
                Ok(Message {
                    data: E::decode(&published.payload)?,
                    id: published.id,
                    raw_data: published.payload,
                    ordering_key: published.ordering_key,
                    attributes: published.attributes,
                    publish_time: published.publish_time,
                    delivery_attempt: 1,
                })
            })
            .collect()
    }
}

impl<T, E: Encoding<T>> Topic<T, E, Unordered> {
    /// Publish a message, returning its id.
    pub async fn publish(&self, data: &T) -> Result<String, Error> {
        self.send(data, HashMap::new(), None).await
    }

    /// Publish a message with explicit options: attributes delivered alongside
    /// it.
    pub async fn publish_with(&self, data: &T, options: PublishOptions) -> Result<String, Error> {
        self.send(data, options.attributes, None).await
    }

    /// Publish up to [`MAX_BATCH_SIZE`] messages at once, returning their ids
    /// in the order given. Fewer requests than publishing each on its own.
    ///
    /// Not atomic: when some are not published, the [`BatchError`] says which,
    /// and the ids of the rest. No messages publishes nothing.
    pub async fn publish_batch(
        &self,
        messages: &[BatchMessage<'_, T>],
    ) -> Result<Vec<String>, BatchError> {
        let messages = messages
            .iter()
            .map(|msg| Outgoing {
                data: msg.data,
                attributes: &msg.attributes,
                ordering_key: None,
            })
            .collect();
        self.send_batch(messages).await
    }
}

impl<T, E: Encoding<T>> Topic<T, E, Ordered> {
    /// Publish a message, returning its id. Messages published with the same
    /// `ordering_key` are delivered in the order they were published.
    pub async fn publish(&self, data: &T, ordering_key: &str) -> Result<String, Error> {
        self.publish_with(data, ordering_key, PublishOptions::default())
            .await
    }

    /// Publish a message with explicit options: attributes delivered alongside
    /// it.
    pub async fn publish_with(
        &self,
        data: &T,
        ordering_key: &str,
        options: PublishOptions,
    ) -> Result<String, Error> {
        if ordering_key.is_empty() {
            return Err(Error::invalid_argument(format!(
                "the ordering key for topic {} cannot be empty",
                self.name
            )));
        }
        self.send(data, options.attributes, Some(ordering_key))
            .await
    }

    /// Publish up to [`MAX_BATCH_SIZE`] messages at once, returning their ids
    /// in the order given. Fewer requests than publishing each on its own.
    ///
    /// The messages sharing an ordering key are published in the order
    /// given. Not atomic: when some are not published, the [`BatchError`]
    /// says which, and the ids of the rest. Once a message of a key is not
    /// published, the later ones with that key are not either, so that they
    /// are never delivered out of order. No messages publishes nothing.
    pub async fn publish_batch(
        &self,
        messages: &[OrderedBatchMessage<'_, T>],
    ) -> Result<Vec<String>, BatchError> {
        let messages = messages
            .iter()
            .map(|msg| Outgoing {
                data: msg.data,
                attributes: &msg.attributes,
                ordering_key: Some(msg.ordering_key),
            })
            .collect();
        self.send_batch(messages).await
    }
}

/// A core error publishing a message, as the SDK's.
fn unavailable(err: anyhow::Error) -> Error {
    Error::wrap(ErrCode::Unavailable, format!("{err:#}"))
}

/// The core's answers for a batch of `count` messages, as the SDK's. A
/// message the core did not answer for was not published.
fn settle(
    count: usize,
    answers: Vec<anyhow::Result<core_pubsub::MessageId>>,
) -> Vec<Result<String, Error>> {
    let mut answers = answers.into_iter();
    (0..count)
        .map(|_| match answers.next() {
            Some(Ok(id)) => Ok(id),
            Some(Err(err)) => Err(unavailable(err)),
            None => Err(Error::unavailable("the message was not answered for")),
        })
        .collect()
}

/// The most messages one `publish_batch` takes.
pub const MAX_BATCH_SIZE: usize = core_pubsub::MAX_BATCH_SIZE;

/// A message of a batch for a [`Topic`]'s
/// [`publish_batch`](Topic::publish_batch): the message, and the attributes
/// delivered alongside it.
///
/// ```no_run
/// # use encore::pubsub::{BatchMessage, Topic};
/// # static SIGNUPS: Topic<String> = Topic::new("signups");
/// # async fn f() -> Result<(), encore::Error> {
/// let (ada, grace) = ("ada".to_string(), "grace".to_string());
/// let ids = SIGNUPS
///     .publish_batch(&[
///         BatchMessage::new(&ada),
///         BatchMessage::new(&grace).attribute("source", "import"),
///     ])
///     .await?;
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct BatchMessage<'a, T> {
    pub data: &'a T,
    /// Attributes delivered alongside the message, as
    /// [`PublishOptions::attributes`] are.
    pub attributes: HashMap<String, String>,
}

impl<'a, T> BatchMessage<'a, T> {
    /// A message without attributes.
    pub fn new(data: &'a T) -> Self {
        Self {
            data,
            attributes: HashMap::new(),
        }
    }

    /// Adds an attribute delivered alongside the message, replacing one of
    /// the same name.
    pub fn attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.attributes.insert(key.into(), value.into());
        self
    }

    /// Adds attributes delivered alongside the message, replacing those of
    /// the same names: a map, or pairs such as `[("source", "web")]`.
    pub fn attributes<K, V>(mut self, attributes: impl IntoIterator<Item = (K, V)>) -> Self
    where
        K: Into<String>,
        V: Into<String>,
    {
        extend(&mut self.attributes, attributes);
        self
    }
}

impl<T> Clone for BatchMessage<'_, T> {
    fn clone(&self) -> Self {
        Self {
            data: self.data,
            attributes: self.attributes.clone(),
        }
    }
}

/// A message of a batch for an [`OrderedTopic`]'s
/// [`publish_batch`](Topic::publish_batch): the message, its ordering key, and
/// the attributes delivered alongside it.
#[derive(Debug)]
pub struct OrderedBatchMessage<'a, T> {
    pub data: &'a T,
    /// The messages sharing a key are delivered in the order they were
    /// published. It cannot be empty.
    pub ordering_key: &'a str,
    /// Attributes delivered alongside the message, as
    /// [`PublishOptions::attributes`] are.
    pub attributes: HashMap<String, String>,
}

impl<'a, T> OrderedBatchMessage<'a, T> {
    /// A message without attributes.
    pub fn new(data: &'a T, ordering_key: &'a str) -> Self {
        Self {
            data,
            ordering_key,
            attributes: HashMap::new(),
        }
    }

    /// Adds an attribute delivered alongside the message, replacing one of
    /// the same name.
    pub fn attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.attributes.insert(key.into(), value.into());
        self
    }

    /// Adds attributes delivered alongside the message, replacing those of
    /// the same names: a map, or pairs such as `[("source", "web")]`.
    pub fn attributes<K, V>(mut self, attributes: impl IntoIterator<Item = (K, V)>) -> Self
    where
        K: Into<String>,
        V: Into<String>,
    {
        extend(&mut self.attributes, attributes);
        self
    }
}

impl<T> Clone for OrderedBatchMessage<'_, T> {
    fn clone(&self) -> Self {
        Self {
            data: self.data,
            ordering_key: self.ordering_key,
            attributes: self.attributes.clone(),
        }
    }
}

/// A message of a batch, whichever kind of topic it is for.
struct Outgoing<'a, T> {
    data: &'a T,
    attributes: &'a HashMap<String, String>,
    ordering_key: Option<&'a str>,
}

/// Why a batch was not published whole: what became of each of its messages,
/// in the order given — its id if it was published, or why it was not.
///
/// A batch is not atomic: some messages can be published and others not. A
/// batch the SDK cannot send as it is — more than [`MAX_BATCH_SIZE`]
/// messages, or a message that does not encode or has an empty ordering key
/// — is refused whole: nothing is published, and every result is an error.
///
/// It converts to an [`Error`], so `?` hands it on from an API or a
/// subscription handler. The error has the code of the first message that
/// failed.
#[derive(Debug, Clone)]
pub struct BatchError {
    pub results: Vec<Result<String, Error>>,
}

impl BatchError {
    /// The ids of the messages that were published, in the order given.
    pub fn published(&self) -> impl Iterator<Item = &str> {
        self.results.iter().filter_map(|r| r.as_deref().ok())
    }

    /// The index and error of each message that was not published.
    pub fn failed(&self) -> impl Iterator<Item = (usize, &Error)> {
        self.results
            .iter()
            .enumerate()
            .filter_map(|(i, r)| r.as_ref().err().map(|err| (i, err)))
    }

    /// A batch of `count` messages refused whole, for `err`.
    fn refused(count: usize, err: Error) -> Self {
        Self {
            results: vec![Err(err); count],
        }
    }

    /// A batch of `count` messages refused whole for the messages that cannot
    /// be sent, the first at index `first`: each says why, and the rest that
    /// they were not sent because of it.
    fn unsendable(count: usize, first: usize, unsendable: Vec<(usize, Error)>) -> Self {
        let mut results: Vec<Result<String, Error>> = (0..count)
            .map(|_| {
                Err(Error::invalid_argument(format!(
                    "not published: message {first} of the batch cannot be sent, so none of it was"
                )))
            })
            .collect();
        for (i, err) in unsendable {
            results[i] = Err(err);
        }
        Self { results }
    }

    /// The ids, when every message was published.
    fn check(results: Vec<Result<String, Error>>) -> Result<Vec<String>, BatchError> {
        if results.iter().all(Result::is_ok) {
            Ok(results.into_iter().map(Result::unwrap).collect())
        } else {
            Err(Self { results })
        }
    }
}

impl fmt::Display for BatchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let failed = self.failed().count();
        let total = self.results.len();
        write!(f, "{failed} of the {total} messages were not published")?;
        if let Some((i, err)) = self.failed().next() {
            write!(f, "; message {i}: {}", err.message)?;
        }
        Ok(())
    }
}

impl std::error::Error for BatchError {}

impl From<BatchError> for Error {
    fn from(err: BatchError) -> Self {
        let code = err
            .failed()
            .next()
            .map_or(ErrCode::Unknown, |(_, err)| err.code);
        Error::new(code, err.to_string())
    }
}

/// The permissions a [`TopicRef`] can grant, as types for its type argument.
/// Each has a trait in [`pubsub`](super) with the methods it grants.
pub mod perms {
    use super::{sealed::Sealed, TopicPerms};

    /// Publish messages: [`Publisher`](super::Publisher) on a topic,
    /// [`OrderedPublisher`](super::OrderedPublisher) on an ordered one.
    pub enum Publisher {}

    impl Sealed for Publisher {}

    impl TopicPerms for Publisher {
        type Id = Self;
    }
}

mod sealed {
    pub trait Sealed {}
}

/// A set of topic permissions: one of the [`perms`]. Sealed: the SDK's
/// permissions are the only ones.
pub trait TopicPerms: sealed::Sealed {
    /// Always `Self`. [`Topic::reference`] returns `TopicRef<P::Id, …>`,
    /// which the compiler cannot work back from to `P`, so `P` is never
    /// inferred.
    #[doc(hidden)]
    type Id: TopicPerms;
}

/// A reference to a [`Topic`] carrying `T`, encoded as `E`, that grants only
/// the permissions `P`, made by [`Topic::reference`]. `Copy`, and free to pass
/// to other code.
///
/// Its methods are the topic's, for the permissions it grants: a
/// `TopicRef<perms::Publisher, T>` can `publish`. Each is also a method of
/// its permission's trait — [`Publisher`], or [`OrderedPublisher`] on an
/// [`OrderedTopicRef`] — which library code takes instead of a `TopicRef`.
pub struct TopicRef<P, T, E = Json, O = Unordered> {
    name: &'static str,
    perms: PhantomData<fn() -> P>,
    _marker: PhantomData<Carries<T, E, O>>,
}

/// A reference to an [`OrderedTopic`].
pub type OrderedTopicRef<P, T, E = Json> = TopicRef<P, T, E, Ordered>;

impl<P, T, E, O> Clone for TopicRef<P, T, E, O> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<P, T, E, O> Copy for TopicRef<P, T, E, O> {}

impl<P, T, E, O> TopicRef<P, T, E, O> {
    /// The name of the topic it refers to.
    pub const fn name(&self) -> &'static str {
        self.name
    }

    /// The topic, to publish through.
    const fn topic(&self) -> Topic<T, E, O> {
        Topic::new(self.name)
    }
}

impl<T, E: Encoding<T>> TopicRef<perms::Publisher, T, E, Unordered> {
    /// See [`Topic::publish`].
    pub async fn publish(&self, data: &T) -> Result<String, Error> {
        self.topic().publish(data).await
    }

    /// See [`Topic::publish_with`].
    pub async fn publish_with(&self, data: &T, options: PublishOptions) -> Result<String, Error> {
        self.topic().publish_with(data, options).await
    }

    /// See [`Topic::publish_batch`].
    pub async fn publish_batch(
        &self,
        messages: &[BatchMessage<'_, T>],
    ) -> Result<Vec<String>, BatchError> {
        self.topic().publish_batch(messages).await
    }
}

impl<T, E: Encoding<T>> TopicRef<perms::Publisher, T, E, Ordered> {
    /// See [`Topic::publish`](Topic#method.publish-1).
    pub async fn publish(&self, data: &T, ordering_key: &str) -> Result<String, Error> {
        self.topic().publish(data, ordering_key).await
    }

    /// See [`Topic::publish_with`](Topic#method.publish_with-1).
    pub async fn publish_with(
        &self,
        data: &T,
        ordering_key: &str,
        options: PublishOptions,
    ) -> Result<String, Error> {
        self.topic().publish_with(data, ordering_key, options).await
    }

    /// See [`Topic::publish_batch`](Topic#method.publish_batch-1).
    pub async fn publish_batch(
        &self,
        messages: &[OrderedBatchMessage<'_, T>],
    ) -> Result<Vec<String>, BatchError> {
        self.topic().publish_batch(messages).await
    }
}

/// Publish messages of type `T` to a topic. Implemented by a [`TopicRef`]
/// granting [`perms::Publisher`], for library code, which takes
/// `&impl Publisher<T>`:
///
/// ```no_run
/// # use encore::pubsub::{perms, Publisher, Topic};
/// # static SIGNUPS: Topic<String> = Topic::new("signups");
/// async fn signed_up(topic: &impl Publisher<String>, user: &String) -> Result<(), encore::Error> {
///     topic.publish(user).await?;
///     Ok(())
/// }
///
/// # async fn f(user: String) -> Result<(), encore::Error> {
/// signed_up(&SIGNUPS.reference::<perms::Publisher>(), &user).await?;
/// # Ok(())
/// # }
/// ```
///
/// A [`Topic`] implements neither trait: it is used by calling its methods,
/// which is how Encore sees what a service publishes to, and is handed to
/// other code only through a reference.
///
/// ```compile_fail,E0277
/// # use encore::pubsub::{Publisher, Topic};
/// # static SIGNUPS: Topic<String> = Topic::new("signups");
/// # async fn signed_up(topic: &impl Publisher<String>) {}
/// # async fn f() {
/// signed_up(&SIGNUPS).await;
/// # }
/// ```
///
/// The methods return `impl Future + Send`, so it works in spawned tasks, but
/// it is not dyn-compatible: code is generic over it, not `Box<dyn Publisher<T>>`.
pub trait Publisher<T>: Send + Sync {
    /// See [`Topic::publish`].
    fn publish(&self, data: &T) -> impl Future<Output = Result<String, Error>> + Send {
        self.publish_with(data, PublishOptions::default())
    }

    /// See [`Topic::publish_with`].
    fn publish_with(
        &self,
        data: &T,
        options: PublishOptions,
    ) -> impl Future<Output = Result<String, Error>> + Send;

    /// See [`Topic::publish_batch`].
    fn publish_batch(
        &self,
        messages: &[BatchMessage<'_, T>],
    ) -> impl Future<Output = Result<Vec<String>, BatchError>> + Send;

    /// The name of the topic.
    fn name(&self) -> &'static str;
}

/// Publish messages of type `T` to an ordered topic, each with its ordering
/// key. Implemented by an [`OrderedTopicRef`] granting [`perms::Publisher`],
/// for library code, which takes `&impl OrderedPublisher<T>`.
pub trait OrderedPublisher<T>: Send + Sync {
    /// See [`Topic::publish`](Topic#method.publish-1).
    fn publish(
        &self,
        data: &T,
        ordering_key: &str,
    ) -> impl Future<Output = Result<String, Error>> + Send {
        self.publish_with(data, ordering_key, PublishOptions::default())
    }

    /// See [`Topic::publish_with`](Topic#method.publish_with-1).
    fn publish_with(
        &self,
        data: &T,
        ordering_key: &str,
        options: PublishOptions,
    ) -> impl Future<Output = Result<String, Error>> + Send;

    /// See [`Topic::publish_batch`](Topic#method.publish_batch-1).
    fn publish_batch(
        &self,
        messages: &[OrderedBatchMessage<'_, T>],
    ) -> impl Future<Output = Result<Vec<String>, BatchError>> + Send;

    /// The name of the topic.
    fn name(&self) -> &'static str;
}

impl<T: Sync, E: Encoding<T>> Publisher<T> for TopicRef<perms::Publisher, T, E, Unordered> {
    fn publish_with(
        &self,
        data: &T,
        options: PublishOptions,
    ) -> impl Future<Output = Result<String, Error>> + Send {
        self.publish_with(data, options)
    }

    fn publish_batch(
        &self,
        messages: &[BatchMessage<'_, T>],
    ) -> impl Future<Output = Result<Vec<String>, BatchError>> + Send {
        self.publish_batch(messages)
    }

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

impl<T: Sync, E: Encoding<T>> OrderedPublisher<T> for TopicRef<perms::Publisher, T, E, Ordered> {
    fn publish_with(
        &self,
        data: &T,
        ordering_key: &str,
        options: PublishOptions,
    ) -> impl Future<Output = Result<String, Error>> + Send {
        self.publish_with(data, ordering_key, options)
    }

    fn publish_batch(
        &self,
        messages: &[OrderedBatchMessage<'_, T>],
    ) -> impl Future<Output = Result<Vec<String>, BatchError>> + Send {
        self.publish_batch(messages)
    }

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

/// A subscription's handler: a function returning the future that handles a
/// message. An error has the message delivered again, as the retry policy says.
pub type Handler<T> = fn(Message<T>) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>;

/// A subscription to a topic: every message published to the topic is handed
/// to its handler.
pub struct Subscription<T> {
    name: &'static str,
    topic: &'static str,
    decode: fn(&[u8]) -> Result<T, Error>,
    handler: Handler<T>,
    started: AtomicBool,
}

impl<T> Subscription<T> {
    /// Declare a subscription to `topic`. `const` so it can initialize a
    /// module-scope `static`.
    ///
    /// The handler is a function, boxing the future that handles a message:
    /// `|msg| Box::pin(send_welcome(msg))`. Under
    /// [`#[encore::pubsub::register]`](macro@register), which also has
    /// the subscription started with the app, it can be just `send_welcome`.
    ///
    /// Options follow, each a method of its own:
    ///
    /// ```no_run
    /// # use std::time::Duration;
    /// # use encore::pubsub::{Message, Subscription, Topic};
    /// # static SIGNUPS: Topic<String> = Topic::new("signups");
    /// # async fn send_welcome(_: Message<String>) -> Result<(), encore::Error> { Ok(()) }
    /// static WELCOME: Subscription<String> =
    ///     Subscription::new(&SIGNUPS, "send-welcome", |msg| Box::pin(send_welcome(msg)))
    ///         .ack_deadline(Duration::from_secs(60))
    ///         .max_retries(5);
    /// ```
    pub const fn new<E: Encoding<T>, O>(
        topic: &'static Topic<T, E, O>,
        name: &'static str,
        handler: Handler<T>,
    ) -> Self {
        Self {
            name,
            topic: topic.name,
            decode: E::decode,
            handler,
            started: AtomicBool::new(false),
        }
    }

    /// How long a message is kept for its handler before it is delivered
    /// again. While the handler runs, a pulled message's lease is extended
    /// for an hour, or for this long when that is longer; a message pushed
    /// to the service (a GCP push subscription) has this long. 30 seconds if
    /// not given.
    ///
    /// The options are part of the declaration, read by Encore's parser: each
    /// takes the subscription by value, so it cannot be called on the `static`.
    pub const fn ack_deadline(self, _deadline: Duration) -> Self {
        self
    }

    /// How long an undelivered message is kept. Seven days if not given.
    pub const fn message_retention(self, _retention: Duration) -> Self {
        self
    }

    /// The shortest wait before a failed message is delivered again. 10
    /// seconds if not given.
    pub const fn min_backoff(self, _backoff: Duration) -> Self {
        self
    }

    /// The longest wait before a failed message is delivered again. 10 minutes
    /// if not given.
    pub const fn max_backoff(self, _backoff: Duration) -> Self {
        self
    }

    /// How many times a failed message is delivered again before it is
    /// dead-lettered. 100 if not given; `0` dead-letters it on the first
    /// failure. To never dead-letter it, use
    /// [`retry_forever`](Self::retry_forever) instead.
    pub const fn max_retries(self, _retries: u32) -> Self {
        self
    }

    /// Delivers a failed message again for as long as its handler fails: it
    /// is never dead-lettered. In place of [`max_retries`](Self::max_retries).
    pub const fn retry_forever(self) -> Self {
        self
    }

    /// How many messages are handled at once. Unlimited if not given.
    pub const fn max_concurrency(self, _concurrency: u32) -> Self {
        self
    }

    /// Which of the topic's messages the subscription receives: those whose
    /// attributes `filter` matches. Messages it does not match are never
    /// delivered to the subscription. All of them if not given.
    ///
    /// It is written in a subset of the [expr language](https://expr-lang.org),
    /// which every cloud Encore deploys to can filter on:
    ///
    /// ```text
    /// .filter(r#"attrs.region in ["eu-west-1", "eu-north-1"] and not (attrs.kind startsWith "test-")"#)
    /// ```
    ///
    /// - `attrs.region == "eu"`, `!=`, `in [...]`, `not in [...]`, and
    ///   `startsWith "eu-"`; `attrs["iana.org-lang"]` for a name with other
    ///   characters than letters, digits and `_`.
    /// - `"region" in attrs` and `"region" not in attrs`: whether a message
    ///   has the attribute. A test of a value does not hold for a message
    ///   without the attribute, and a negated one does.
    /// - `and` (`&&`), `or` (`||`), `not (...)` (`!(...)`) and parentheses.
    ///
    /// Encore reads it from the source, so it is a string written out, and
    /// checks it fits the clouds' limits.
    pub const fn filter(self, _filter: &'static str) -> Self {
        self
    }

    /// The Worker of the service that consumes the subscription: a
    /// long-running process of the service that serves no requests, declared
    /// in the `workers` section of its `encore.service.json`. Only that
    /// process takes its messages; another process of the service that
    /// declares the subscription takes none. The service's main process
    /// consumes it if not given.
    ///
    /// Encore reads it from the source, so it is a string written out.
    pub const fn worker(self, _worker: &'static str) -> Self {
        self
    }

    /// Tags the subscription with `key` and `value`: key/value classification, such
    /// as `.tag("data", "pci")`, for policies to read. One call per tag, each
    /// with its own key. Encore reads them from the source, so both are string
    /// literals. A key is lowercase letters, digits, `_` and `-`, starting with
    /// a letter and not with `encore`, which is kept for Encore's own tags; a
    /// value is the same characters, or empty. Each is at most 63 characters,
    /// and a subscription has at most 32 tags.
    ///
    /// Part of the declaration: it takes the subscription by value, so it cannot be
    /// called on the `static`.
    ///
    /// ```no_run
    /// # use encore::pubsub::{Message, Subscription, Topic};
    /// # static SIGNUPS: Topic<String> = Topic::new("signups");
    /// # async fn send_welcome(_: Message<String>) -> Result<(), encore::Error> { Ok(()) }
    /// static WELCOME: Subscription<String> =
    ///     Subscription::new(&SIGNUPS, "send-welcome", |msg| Box::pin(send_welcome(msg)))
    ///         .tag("team", "growth");
    /// ```
    pub const fn tag(self, _key: &'static str, _value: &'static str) -> Self {
        self
    }

    /// The name the subscription was declared with.
    pub const fn name(&self) -> &'static str {
        self.name
    }
}

impl<T: Send + 'static> Subscription<T> {
    /// Starts handling the topic's messages, if it has not been started.
    ///
    /// A subscription under [`#[encore::pubsub::register]`](macro@register)
    /// is started with the app; this is for one that is not.
    pub fn start(&'static self) -> Result<(), Error> {
        if self.started.swap(true, Ordering::SeqCst) {
            return Ok(());
        }
        let subscription = core()
            .pubsub()
            .subscription(core_pubsub::SubName {
                topic: self.topic.into(),
                subscription: self.name.into(),
            })
            .ok_or_else(|| {
                Error::not_found(format!(
                    "subscription {:?} on topic {:?} is not configured",
                    self.name, self.topic
                ))
            })?;
        let (topic, name) = (self.topic, self.name);
        core().tokio_handle().spawn(async move {
            let handler = Arc::new(Runner { subscription: self });
            if let Err(err) = subscription.subscribe(handler).await {
                eprintln!("encore: subscription {name:?} on topic {topic:?} stopped: {err}");
            }
        });
        Ok(())
    }
}

impl<T: Send + 'static> Subscription<T> {
    /// Hands the subscription's handler what the test `test` published to
    /// its topic and it has not handled: see [`testing::deliver`].
    pub(crate) async fn deliver_in(&'static self, test: &testing::Scope) -> Result<usize, Error> {
        use encore_sdk_core::telemetry::opentelemetry::trace::FutureExt;
        use encore_sdk_core::telemetry::opentelemetry::Context;
        use encore_sdk_core::test_scope::MAX_DELIVERIES;

        let scope = test.core_scope()?;
        let mut handled = 0;
        while let Some(delivery) = scope.next_delivery(self.topic, self.name) {
            if handled == MAX_DELIVERIES {
                return Err(Error::new(
                    ErrCode::ResourceExhausted,
                    format!(
                        "subscription {:?} handled {MAX_DELIVERIES} messages in one delivery \
                         and was still handed more: does its handler publish to its own topic \
                         {:?} every time?",
                        self.name, self.topic
                    ),
                ));
            }
            let published = delivery.message;
            // The Request Context fields the message carries are the
            // handler's context, as in a real delivery.
            let mut attributes = published.attributes;
            let fields = Values::take_attributes(&mut attributes);
            let context = fields.in_context(&Context::new());
            let outcome = async {
                let message = Message {
                    data: (self.decode)(&published.payload)?,
                    id: published.id,
                    raw_data: published.payload,
                    ordering_key: published.ordering_key,
                    attributes,
                    publish_time: published.publish_time,
                    delivery_attempt: delivery.attempt,
                };
                (self.handler)(message).await
            }
            .with_context(context)
            .await;
            scope.settle_delivery(self.topic, self.name, outcome.is_ok());
            outcome?;
            handled += 1;
        }
        Ok(handled)
    }
}

/// Hands the runtime's messages to a subscription's handler.
struct Runner<T: 'static> {
    subscription: &'static Subscription<T>,
}

impl<T> fmt::Debug for Runner<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Subscription")
            .field("topic", &self.subscription.topic)
            .field("name", &self.subscription.name)
            .finish()
    }
}

impl<T: Send + 'static> core_pubsub::SubscriptionHandler for Runner<T> {
    fn handle_message(
        &self,
        msg: Arc<core_pubsub::Message>,
        span_ctx: encore_sdk_core::telemetry::SpanContext,
    ) -> Pin<Box<dyn Future<Output = Result<(), encore_sdk_core::api::Error>> + Send + 'static>>
    {
        use encore_sdk_core::telemetry::opentelemetry::trace::{FutureExt, TraceContextExt};
        use encore_sdk_core::telemetry::opentelemetry::Context;

        let subscription = self.subscription;
        // What the handler does is traced under the delivery's span, with the
        // Request Context fields the message carries. Their attributes are
        // Encore's: the handler reads the fields from its context.
        let mut attributes = msg.data.attrs.clone();
        let fields = Values::take_attributes(&mut attributes);
        let mut delivery = Context::new().with_remote_span_context(span_ctx);
        if !fields.is_empty() {
            delivery = fields.in_context(&delivery);
        }
        let handle = async move {
            // What the core records of a failure: no client is answered
            // with it, so the message is all internal.
            let failed = |err: Error| {
                let code = encore_sdk_core::api::ErrCode::from(err.code);
                encore_sdk_core::api::Error {
                    code,
                    message: code.default_public_message().into(),
                    internal_message: Some(err.message),
                    stack: None,
                    details: None,
                    exception: None,
                }
            };
            let message = Message {
                id: msg.id.clone(),
                data: (subscription.decode)(&msg.data.raw_body).map_err(failed)?,
                raw_data: msg.data.raw_body.clone(),
                ordering_key: msg.ordering_key.clone(),
                attributes,
                publish_time: msg.publish_time.into(),
                delivery_attempt: msg.attempt,
            };
            (subscription.handler)(message).await.map_err(failed)
        };
        Box::pin(handle.with_context(delivery))
    }
}

/// What `#[encore::pubsub::register]` expands to. Not for use by hand: it
/// changes with the macro.
#[doc(hidden)]
pub mod __private {
    use super::*;

    pub use linkme;

    /// A subscription, whatever its message type.
    pub trait AnySubscription: Sync {
        fn start(&'static self) -> Result<(), Error>;
    }

    impl<T: Send + 'static> AnySubscription for Subscription<T> {
        fn start(&'static self) -> Result<(), Error> {
            Subscription::start(self)
        }
    }

    /// Every subscription registered to be started with the app, collected at
    /// link time: a `static` says nothing of itself until it is used.
    #[linkme::distributed_slice]
    pub static SUBSCRIPTIONS: [&'static dyn AnySubscription];
}

/// Starts every subscription registered with
/// [`#[encore::pubsub::register]`](macro@register). Called when the
/// app starts; not under `encore test`, where nothing handles what a test
/// publishes.
pub(crate) fn start_registered() {
    if core().postgres().isolates_instances() {
        return;
    }
    for subscription in __private::SUBSCRIPTIONS {
        if let Err(err) = subscription.start() {
            eprintln!("encore: {err}");
        }
    }
    core().pubsub().subscriptions_started();
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use encore_sdk_core::pubsub::SubscriptionHandler as _;

    use super::*;
    use crate::reqctx::Field;

    static USER: Field<String> = Field::new("user").pubsub();
    static EVENTS: Topic<String> = Topic::new("events");
    /// The field and attributes each message was handled with.
    type Seen = (Option<String>, HashMap<String, String>);
    static SEEN: Mutex<Vec<Seen>> = Mutex::new(Vec::new());
    static AUDIT: Subscription<String> = Subscription::new(&EVENTS, "audit", |msg| {
        Box::pin(async move {
            SEEN.lock().unwrap().push((USER.get(), msg.attributes));
            Ok(())
        })
    });

    #[test]
    fn publish_options_add_attributes_one_at_a_time_or_all_at_once() {
        let tags = HashMap::from([
            ("source".to_string(), "web".to_string()),
            ("tier".to_string(), "free".to_string()),
        ]);
        // A map, or pairs; a later value for a name replaces an earlier one.
        let options = PublishOptions::new()
            .attributes(tags)
            .attributes([("tier", "pro")])
            .attribute("region", "eu");
        let want: HashMap<String, String> = [("source", "web"), ("tier", "pro"), ("region", "eu")]
            .into_iter()
            .map(|(k, v)| (k.to_string(), v.to_string()))
            .collect();
        assert_eq!(options.attributes, want);
    }

    #[test]
    fn a_handler_runs_with_the_fields_its_message_carries() {
        let message = Arc::new(core_pubsub::Message {
            id: "1".into(),
            publish_time: SystemTime::now().into(),
            attempt: 1,
            ordering_key: None,
            data: core_pubsub::MessageData {
                attrs: HashMap::from([
                    ("encore-ctx-user".into(), "ImFkYSI".into()),
                    ("source".into(), "test".into()),
                ]),
                raw_body: b"\"hi\"".to_vec(),
            },
        });
        let runner = Runner {
            subscription: &AUDIT,
        };
        let rt = tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap();
        rt.block_on(runner.handle_message(
            message,
            encore_sdk_core::telemetry::SpanContext::empty_context(),
        ))
        .unwrap();
        let seen = SEEN.lock().unwrap();
        assert_eq!(
            *seen,
            [(
                Some("ada".to_string()),
                HashMap::from([("source".to_string(), "test".to_string())])
            )]
        );
    }

    #[test]
    fn each_message_is_answered_for_in_its_place() {
        let results = settle(
            4,
            vec![
                Ok("a".to_string()),
                Err(anyhow::anyhow!("refused")),
                Ok("c".to_string()),
            ],
        );
        assert_eq!(results[0].as_deref().unwrap(), "a");
        assert_eq!(results[1].as_ref().unwrap_err().code, ErrCode::Unavailable);
        assert_eq!(results[2].as_deref().unwrap(), "c");
        // Not answered for: not published.
        assert!(results[3].is_err());
        assert!(BatchError::check(results).is_err());
    }

    #[test]
    fn a_batch_published_whole_is_its_ids() {
        let results = settle(2, vec![Ok("a".into()), Ok("b".into())]);
        assert_eq!(BatchError::check(results).unwrap(), ["a", "b"]);
    }
}