encore-dev 2.0.0

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
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
//! Pub/Sub topics and subscriptions.
//!
//! Declare topics and subscriptions as module-level `static`s. Topics are typed
//! by their message payload, and subscriptions bind a topic to an async handler
//! function:
//!
//! ```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 parameter specifies its wire encoding: [`Json`] by
//! default, [`Raw`] for raw byte payloads, or `Protobuf` when the `protobuf`
//! feature is enabled. Because the encoding is part of the topic's type,
//! publishers and subscribers stay in agreement and Encore can read it
//! statically.
//!
//! # Ordered topics
//!
//! An [`OrderedTopic`] delivers messages sharing the same ordering key in the
//! order they were published. Pass the ordering key when calling `publish`.
//!
//! # Batches
//!
//! `publish_batch` publishes up to [`MAX_BATCH_SIZE`] messages in fewer
//! round-trips than individual publishes, returning message IDs in input order.
//! Batch publishing is not atomic: on partial failure, [`BatchError`] reports
//! which messages succeeded and which failed. On an ordered topic, messages
//! sharing a key are published in order, and if one fails, subsequent messages
//! with that key are not published.
//!
//! # References
//!
//! Encore infers service permissions from direct method calls on a `Topic`. To
//! pass a topic to helper functions, create a permission-scoped reference via
//! [`Topic::reference`] with [`perms::Publisher`], and accept the [`Publisher`]
//! (or [`OrderedPublisher`]) trait in the helper.
//!
//! # Starting subscriptions
//!
//! Rust `static`s are lazy, so subscriptions must be started explicitly.
//! Annotate subscriptions with [`#[encore::pubsub::register]`](macro@register)
//! so [`crate::initialize`] or [`crate::run_blocking`] starts them
//! automatically; otherwise call [`Subscription::start`] manually.
//!
//! # Testing
//!
//! Under `encore test`, each test has an isolated Pub/Sub scope and
//! subscriptions do not run automatically. Inspect messages published during a
//! test with [`testing::published`](crate::testing::published), and invoke
//! subscription handlers explicitly 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::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, SystemTime};

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

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

/// Registers a subscription `static` to be started automatically when the
/// application initializes.
///
/// Apply this attribute to a `static Subscription<T>`. It also lets you pass an
/// `async fn` name directly instead of wrapping it in a boxing closure for
/// [`Subscription::new`].
///
/// ```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 Pub/Sub message delivered to a subscription handler.
#[derive(Debug, Clone)]
pub struct Message<T> {
    /// Unique message ID within the topic.
    pub id: String,
    /// Decoded message payload.
    pub data: T,
    /// Raw encoded message bytes before decoding.
    pub raw_data: Vec<u8>,
    /// Attributes published alongside the message.
    ///
    /// On delivered messages, internal `encore_ctx_*` Request Context
    /// attributes are stripped and exposed through [`crate::reqctx`] instead;
    /// messages returned by [`testing::published`] retain them as published.
    pub attributes: HashMap<String, String>,
    pub publish_time: SystemTime,
    /// 1-based delivery attempt number. On GCP, it counts the message's failed
    /// deliveries plus one, so a message redelivered because an earlier one
    /// with its ordering key failed may keep its number.
    pub delivery_attempt: u32,
    /// Ordering key set when published to an [`OrderedTopic`].
    pub ordering_key: Option<String>,
}

/// The message attribute each published message carries its payload's format
/// in: its topic's [`Encoding::CONTENT_TYPE`]. It tells a subscriber that
/// reads [`Message::raw_data`] how to read the bytes. A publisher that sets it
/// in its attributes keeps its own value, to name the format of a [`Raw`]
/// payload, say.
pub const CONTENT_TYPE_ATTRIBUTE: &str = "encore_content_type";

/// Wire encoding for a topic's messages.
pub trait Encoding<T> {
    /// The media type of the encoded bytes, sent in
    /// [`CONTENT_TYPE_ATTRIBUTE`].
    const CONTENT_TYPE: &'static str = "application/octet-stream";

    fn encode(value: &T) -> Result<Vec<u8>, Error>;
    fn decode(raw: &[u8]) -> Result<T, Error>;
}

/// Sets `attributes`' content type to `E`'s, unless they name one.
fn with_content_type<T, E: Encoding<T>>(attributes: &mut HashMap<String, String>) {
    attributes
        .entry(CONTENT_TYPE_ATTRIBUTE.to_string())
        .or_insert_with(|| E::CONTENT_TYPE.to_string());
}

/// JSON encoding for message types implementing `Serialize` and `Deserialize`
/// (the default topic encoding).
pub enum Json {}

impl<T: Serialize + DeserializeOwned> Encoding<T> for Json {
    const CONTENT_TYPE: &'static str = "application/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))
    }
}

/// Raw byte encoding that passes `Vec<u8>` payloads through unmodified.
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 encoding for `prost` message types.
#[cfg(feature = "protobuf")]
pub enum Protobuf {}

#[cfg(feature = "protobuf")]
impl<T: prost::Message + Default> Encoding<T> for Protobuf {
    const CONTENT_TYPE: &'static str = "application/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))
    }
}

/// Marker type for an unordered [`Topic`].
pub enum Unordered {}

/// Marker type for an ordered [`Topic`] ([`OrderedTopic`]).
pub enum Ordered {}

/// A Pub/Sub topic carrying messages of type `T` with encoding `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 messages sharing an ordering key in publish order.
///
/// A message that fails is retried before later messages with its key are
/// delivered. On GCP, later messages already received when one fails can be
/// handled before its retry, and are then delivered again after it, so handlers
/// must be idempotent.
pub type OrderedTopic<T, E = Json> = Topic<T, E, Ordered>;

/// Options for publishing a single 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(())
/// # }
/// ```
///
/// Custom attributes are delivered alongside the message. Attributes prefixed
/// with `encore_ctx_` are reserved for Encore's Request Context propagation.
#[derive(Debug, Clone, Default)]
pub struct PublishOptions {
    attributes: HashMap<String, String>,
}

impl PublishOptions {
    /// Creates empty publish options with no attributes.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets a message attribute, overwriting any existing value with the same key.
    pub fn attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.attributes.insert(key.into(), value.into());
        self
    }

    /// Adds multiple message attributes from a map or iterator of pairs (such as
    /// `[("source", "web")]`), overwriting any existing keys.
    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> {
    /// Declares a Pub/Sub topic.
    ///
    /// This constructor is `const` so it can initialize a module-scope `static`,
    /// whose type specifies the message type and encoding. Chain option methods
    /// directly onto the declaration:
    ///
    /// ```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,
        }
    }

    /// References an existing topic declared by another service (possibly in
    /// another language). To declare a new topic, use [`Topic::new`].
    ///
    /// `name` must be a string literal so Encore can resolve it statically.
    /// Topic options are defined at the original declaration, not on `named`.
    /// Ensure that `T` and `E` match the declaring topic's schema, as
    /// cross-language types cannot be checked by Rust's type checker.
    ///
    /// ```no_run
    /// static SIGNUPS: encore::pubsub::Topic<String> = encore::pubsub::Topic::named("signups");
    /// ```
    pub const fn named(name: &'static str) -> Self {
        Self::new(name)
    }

    /// Configures the topic for exactly-once delivery instead of at-least-once.
    pub const fn exactly_once(mut self) -> Self {
        self.exactly_once = true;
        self
    }

    /// Attaches a key/value tag to the topic (for example, `.tag("data", "pci")`)
    /// for policy and governance tooling.
    ///
    /// Call once per tag with unique keys. Both `key` and `value` must be string
    /// literals so Encore can parse them statically. Keys must start with a
    /// letter, contain only lowercase letters, digits, `_`, and `-`, and must
    /// not start with `encore` (reserved for Encore's own tags). Values use the
    /// same character set or may be empty. Each key and value is at most 63
    /// characters, and a topic may have at most 32 tags.
    ///
    /// ```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
    }

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

    /// Creates a permission-scoped [`TopicRef`] granting permission `P`
    /// (currently [`perms::Publisher`]).
    ///
    /// Unlike `Topic`, a `TopicRef` can be passed to helper functions; the
    /// calling service is granted the permissions specified in `P`. The type
    /// parameter `P` must always be written explicitly so Encore can analyze
    /// permissions statically.
    ///
    /// ```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 accepts the permission 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");
    /// // Permissions cannot be inferred from the target type.
    /// 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::Context;
        use encore_sdk_core::telemetry::opentelemetry::trace::FutureExt as _;

        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);
        with_content_type::<T, E>(&mut attributes);
        if core().system_test().is_none()
            && 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!(
                    "batch has {count} messages, exceeding the maximum of {MAX_BATCH_SIZE}"
                )),
            ));
        }

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

        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!(
                    "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);
            with_content_type::<T, E>(&mut msg.attrs);
        }

        let refused = |err| BatchError::refused(count, err);
        if core().system_test().is_none()
            && 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> {
    /// Publishes a message and returns its message ID.
    pub async fn publish(&self, data: &T) -> Result<String, Error> {
        self.send(data, HashMap::new(), None).await
    }

    /// Publishes a message with explicit [`PublishOptions`] (such as custom
    /// attributes) and returns its message ID.
    pub async fn publish_with(&self, data: &T, options: PublishOptions) -> Result<String, Error> {
        self.send(data, options.attributes, None).await
    }

    /// Publishes up to [`MAX_BATCH_SIZE`] messages in a batch and returns their
    /// message IDs in input order.
    ///
    /// Batch publishing is not atomic: if some messages fail, [`BatchError`]
    /// contains both the IDs of published messages and errors for failed ones.
    /// Passing an empty slice is a no-op.
    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> {
    /// Publishes a message with an ordering key and returns its message ID.
    ///
    /// Messages sharing the same `ordering_key` are delivered in publish order.
    pub async fn publish(&self, data: &T, ordering_key: &str) -> Result<String, Error> {
        self.publish_with(data, ordering_key, PublishOptions::default())
            .await
    }

    /// Publishes a message with an ordering key and explicit [`PublishOptions`],
    /// returning its message ID.
    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!(
                "ordering key for topic {:?} cannot be empty",
                self.name
            )));
        }
        self.send(data, options.attributes, Some(ordering_key))
            .await
    }

    /// Publishes up to [`MAX_BATCH_SIZE`] ordered messages in a batch and
    /// returns their message IDs in input order.
    ///
    /// Messages sharing an ordering key are published in order. Batch
    /// publishing is not atomic: if a message fails, subsequent messages with
    /// the same ordering key are not published to preserve ordering, and
    /// [`BatchError`] reports each message's outcome. Passing an empty slice is
    /// a no-op.
    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(
                "missing publish result for message in batch",
            )),
        })
        .collect()
}

/// Maximum number of messages accepted by a single `publish_batch` call.
pub const MAX_BATCH_SIZE: usize = core_pubsub::MAX_BATCH_SIZE;

/// A single message in a batch passed to [`Topic::publish_batch`], containing
/// the payload and optional attributes.
///
/// ```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,
    /// Custom attributes delivered alongside the message (same rules as
    /// [`PublishOptions::attributes`]).
    pub attributes: HashMap<String, String>,
}

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

    /// Sets a message attribute, overwriting any existing value with the same key.
    pub fn attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.attributes.insert(key.into(), value.into());
        self
    }

    /// Adds multiple message attributes from a map or iterator of pairs (such as
    /// `[("source", "web")]`), overwriting any existing keys.
    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 single message in a batch passed to [`OrderedTopic::publish_batch`],
/// containing the payload, ordering key, and optional attributes.
#[derive(Debug)]
pub struct OrderedBatchMessage<'a, T> {
    pub data: &'a T,
    /// Non-empty ordering key; messages sharing a key are delivered in publish
    /// order.
    pub ordering_key: &'a str,
    /// Custom attributes delivered alongside the message (same rules as
    /// [`PublishOptions::attributes`]).
    pub attributes: HashMap<String, String>,
}

impl<'a, T> OrderedBatchMessage<'a, T> {
    /// Creates an ordered batch message with no attributes.
    pub fn new(data: &'a T, ordering_key: &'a str) -> Self {
        Self {
            data,
            ordering_key,
            attributes: HashMap::new(),
        }
    }

    /// Sets a message attribute, overwriting any existing value with the same key.
    pub fn attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.attributes.insert(key.into(), value.into());
        self
    }

    /// Adds multiple message attributes from a map or iterator of pairs (such as
    /// `[("source", "web")]`), overwriting any existing keys.
    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>,
}

/// Error returned when one or more messages in a `publish_batch` call could not
/// be published.
///
/// `results` contains one entry per input message in order: `Ok(message_id)`
/// for published messages and `Err(error)` for failed ones. Batch publishing is
/// not atomic, so some messages may succeed while others fail. If the entire
/// batch is invalid before sending (for example, exceeding [`MAX_BATCH_SIZE`],
/// an encoding error, or an empty ordering key), nothing is published and every
/// entry is an `Err`.
///
/// `BatchError` converts into [`Error`] (using the error code of the first
/// failed message) so it can be propagated with `?`.
#[derive(Debug, Clone)]
pub struct BatchError {
    pub results: Vec<Result<String, Error>>,
}

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

    /// Iterates over the index and error of each message that failed to publish.
    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: batch was rejected because message {first} is invalid"
                )))
            })
            .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 {total} messages failed to publish")?;
        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())
    }
}

/// Permission marker types for [`TopicRef`]. Each permission corresponds to a
/// trait in [`pubsub`](super).
pub mod perms {
    use super::{TopicPerms, sealed::Sealed};

    /// Permission to publish messages ([`Publisher`](super::Publisher) or
    /// [`OrderedPublisher`](super::OrderedPublisher)).
    pub enum Publisher {}

    impl Sealed for Publisher {}

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

mod sealed {
    pub trait Sealed {}
}

/// Sealed trait implemented by topic permission markers in [`perms`].
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 copyable, permission-scoped reference to a [`Topic`], created by
/// [`Topic::reference`].
///
/// Exposes only the methods permitted by `P` (for example,
/// `TopicRef<perms::Publisher, T>` can publish). Library code should accept the
/// corresponding trait ([`Publisher`] or [`OrderedPublisher`]) instead of
/// `TopicRef` directly.
pub struct TopicRef<P, T, E = Json, O = Unordered> {
    name: &'static str,
    perms: PhantomData<fn() -> P>,
    _marker: PhantomData<Carries<T, E, O>>,
}

/// A permission-scoped 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> {
    /// Returns the name of the referenced topic.
    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
    }
}

/// Trait for publishing messages of type `T` to an unordered topic.
///
/// Implemented by [`TopicRef`] when granted [`perms::Publisher`]. Accept
/// `&impl Publisher<T>` in helper functions so they work with references and
/// test fakes:
///
/// ```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(())
/// # }
/// ```
///
/// [`Topic`] intentionally does not implement this trait so Encore can track
/// permissions statically via [`Topic::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;
/// # }
/// ```
///
/// Methods return `impl Future + Send` (making the trait compatible with
/// spawned tasks, though not dyn-compatible).
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;

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

/// Trait for publishing messages of type `T` with ordering keys to an ordered
/// topic.
///
/// Implemented by [`OrderedTopicRef`] when granted [`perms::Publisher`]. Accept
/// `&impl OrderedPublisher<T>` in helper functions.
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;

    /// Returns 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
    }
}

/// Async handler function signature for a [`Subscription`].
///
/// Returning `Err` triggers redelivery according to the subscription's retry
/// policy.
pub type Handler<T> = fn(Message<T>) -> Pin<Box<dyn Future<Output = Result<(), Error>> + Send>>;

/// A subscription that delivers messages from a [`Topic`] to a handler function.
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> {
    /// Declares a subscription to `topic`.
    ///
    /// This constructor is `const` so it can initialize a module-scope `static`.
    /// Pass a closure returning a boxed future (`|msg| Box::pin(send_welcome(msg))`),
    /// or annotate the `static` with
    /// [`#[encore::pubsub::register]`](macro@register) to pass `send_welcome`
    /// directly and start the subscription automatically at startup.
    ///
    /// ```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_attempts(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),
        }
    }

    /// Sets how long a handler has to acknowledge a message before it is
    /// redelivered (defaults to 30 seconds).
    ///
    /// For pull subscriptions, Encore automatically extends the lease for up to
    /// 1 hour (or this duration, if longer) while the handler is running; for
    /// push subscriptions (such as GCP push), this is the delivery timeout.
    pub const fn ack_deadline(self, _deadline: Duration) -> Self {
        self
    }

    /// Sets how long undelivered messages are retained before expiring
    /// (defaults to 7 days).
    pub const fn message_retention(self, _retention: Duration) -> Self {
        self
    }

    /// Sets the minimum retry backoff after a failed delivery (defaults to 10
    /// seconds).
    pub const fn min_backoff(self, _backoff: Duration) -> Self {
        self
    }

    /// Sets the maximum retry backoff after a failed delivery (defaults to 10
    /// minutes).
    pub const fn max_backoff(self, _backoff: Duration) -> Self {
        self
    }

    /// Sets the maximum number of times a message is delivered, including the
    /// first delivery, before it is moved to the dead-letter queue (defaults to
    /// 100). Must be between 1 (no retries) and 100. On GCP, the minimum is 5,
    /// so lower values behave as 5.
    pub const fn max_attempts(self, _attempts: u32) -> Self {
        self
    }

    /// Limits how many messages this subscription processes concurrently in
    /// each service instance (defaults to 100). Must be at least 1. On an ordered
    /// topic, messages sharing an ordering key are processed one at a time.
    ///
    /// It has no effect on GCP Cloud Run for unordered topics, whose messages
    /// are pushed with a concurrency GCP adapts.
    pub const fn max_concurrency(self, _concurrency: u32) -> Self {
        self
    }

    /// Filters which messages are delivered to this subscription based on their
    /// attributes. Unmatched messages are skipped before delivery (defaults to
    /// receiving all messages).
    ///
    /// Uses a cloud-portable subset of [CEL](https://cel.dev), the language
    /// policies are written in:
    ///
    /// ```text
    /// .filter(r#"attrs.region in ["eu-west-1", "eu-north-1"] && !attrs.kind.startsWith("test-")"#)
    /// ```
    ///
    /// Supported operations:
    /// - Comparisons: `attrs.region == "eu"`, `!=`, `in [...]`, and
    ///   `.startsWith("eu-")` (use `attrs["iana.org-lang"]` for attribute
    ///   names containing characters outside letters, digits, and `_`).
    /// - Presence checks: `has(attrs.region)`, or `"iana.org-lang" in attrs`.
    ///   A missing attribute reads as the empty string, so positive value
    ///   checks evaluate to false if it is missing, while negated checks
    ///   evaluate to true.
    /// - Boolean logic: `&&`, `||`, `!`, and parentheses.
    ///
    /// Must be a string literal so Encore can parse and validate it against
    /// cloud provider limits.
    pub const fn filter(self, _filter: &'static str) -> Self {
        self
    }

    /// Assigns this subscription to a named worker declared in the `workers`
    /// section of the service's `encore.service.json`.
    ///
    /// Only that worker process consumes messages for this subscription. If
    /// omitted, the service's main process consumes it. Must be a string
    /// literal.
    pub const fn worker(self, _worker: &'static str) -> Self {
        self
    }

    /// Attaches a key/value tag to the subscription (for example,
    /// `.tag("data", "pci")`) for policy and governance tooling.
    ///
    /// Call once per tag with unique keys. Both `key` and `value` must be string
    /// literals so Encore can parse them statically. Keys must start with a
    /// letter, contain only lowercase letters, digits, `_`, and `-`, and must
    /// not start with `encore` (reserved for Encore's own tags). Values use the
    /// same character set or may be empty. Each key and value is at most 63
    /// characters, and a subscription may have at most 32 tags.
    ///
    /// ```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
    }

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

impl<T: Send + 'static> Subscription<T> {
    /// Starts consuming messages for this subscription if it has not already
    /// been started.
    ///
    /// Subscriptions annotated with
    /// [`#[encore::pubsub::register]`](macro@register) are started
    /// automatically; call this manually for unregistered subscriptions.
    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::Context;
        use encore_sdk_core::telemetry::opentelemetry::trace::FutureExt;
        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 {:?} processed {MAX_DELIVERIES} messages in a single \
                         deliver() call and more remain: check whether the handler publishes \
                         back to its own topic {:?} on every invocation",
                        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::Context;
        use encore_sdk_core::telemetry::opentelemetry::trace::{FutureExt, TraceContextExt};

        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_message_names_its_encoding_s_content_type_unless_its_publisher_does() {
        let content_type = |encoded: fn(&mut HashMap<String, String>), given: &[(&str, &str)]| {
            let mut attributes: HashMap<String, String> = given
                .iter()
                .map(|(k, v)| (k.to_string(), v.to_string()))
                .collect();
            encoded(&mut attributes);
            attributes.remove(CONTENT_TYPE_ATTRIBUTE)
        };
        let json = with_content_type::<String, Json>;
        let raw = with_content_type::<Vec<u8>, Raw>;
        assert_eq!(content_type(json, &[]).as_deref(), Some("application/json"));
        assert_eq!(
            content_type(raw, &[]).as_deref(),
            Some("application/octet-stream")
        );
        #[cfg(feature = "protobuf")]
        assert_eq!(
            content_type(with_content_type::<prost_types::Duration, Protobuf>, &[]).as_deref(),
            Some("application/protobuf")
        );
        let own = [(CONTENT_TYPE_ATTRIBUTE, "application/avro")];
        assert_eq!(content_type(raw, &own).as_deref(), Some("application/avro"));
    }

    #[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"]);
    }
}