pcs-external 0.3.0

Ppoppo Chat System (PCS) External API client -- gRPC client for the External Developer Platform
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
//! Domain types for the PCS External API client hot path.
//!
//! No proto types appear here — [`crate::PcsExternalClient`] translates at
//! the wire boundary. These newtypes encode invariants the proto schema cannot
//! (ppnum format, recipient list size + dedup) so violations are caught at
//! construction, not at the wire.

use std::collections::{BTreeMap, HashSet};

/// Identifier for a previously-issued send request, returned from
/// [`crate::PcsExternalClient::send_alert`] and consumed by
/// [`crate::PcsExternalClient::get_send_status`].
///
/// Opaque from the SDK's perspective — PCS owns the format. Currently
/// a ULID, but the port does not require that shape.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SendRequestId(pub String);

impl SendRequestId {
    #[must_use]
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }
}

/// Identifier for a registered template on the PCS External platform.
///
/// PCS External API is template-driven: every `send_alert` call cites
/// a template that the calling app pre-registered through
/// `ExternalTemplateService::CreateTemplate` (today on the escape-hatch
/// path). Per-recipient `vars` substitute placeholders in the template.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TemplateId(pub String);

impl TemplateId {
    #[must_use]
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }
}

/// A validated Ppoppo number — the canonical recipient identifier.
///
/// Per workspace contract (`CLAUDE.md` Architecture Terms): ≥11 digits,
/// `^[0-9]{11,}$`. Validated once at construction so adapters never
/// re-validate and the wire never sees a malformed value.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Ppnum(String);

/// Construction-time error for a [`Ppnum`].
#[derive(Debug, Clone, thiserror::Error)]
pub enum PpnumError {
    /// Empty string.
    #[error("ppnum is empty")]
    Empty,
    /// Length below the 11-digit minimum.
    #[error("ppnum too short ({len} digits, minimum 11)")]
    TooShort { len: usize },
    /// Contains a non-digit character at the given byte index.
    #[error("ppnum contains non-digit character at position {pos}")]
    NonDigit { pos: usize },
}

impl Ppnum {
    /// Validate and wrap a candidate ppnum string.
    ///
    /// # Errors
    ///
    /// Returns [`PpnumError`] if the string is empty, shorter than 11
    /// characters, or contains non-digit bytes.
    pub fn try_new(s: impl Into<String>) -> Result<Self, PpnumError> {
        let s = s.into();
        if s.is_empty() {
            return Err(PpnumError::Empty);
        }
        for (i, b) in s.bytes().enumerate() {
            if !b.is_ascii_digit() {
                return Err(PpnumError::NonDigit { pos: i });
            }
        }
        if s.len() < 11 {
            return Err(PpnumError::TooShort { len: s.len() });
        }
        Ok(Self(s))
    }

    /// Borrow the underlying digit string (no formatting hyphens).
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume into the owned `String`.
    #[must_use]
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl AsRef<str> for Ppnum {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

/// A single recipient entry: ppnum plus per-recipient template variables.
///
/// `vars` are substituted into the template referenced by the surrounding
/// [`crate::PcsExternalClient::send_alert`] call. Hot-path sticks to
/// `BTreeMap<String, String>` (95% of templating uses string substitution
/// like `{{name}} → "John"`); richer payloads are out of scope and
/// reachable only via the the raw channel escape hatch.
#[derive(Debug, Clone)]
pub struct Recipient {
    pub ppnum: Ppnum,
    pub vars: BTreeMap<String, String>,
}

impl Recipient {
    /// Recipient with no template variables.
    #[must_use]
    pub fn bare(ppnum: Ppnum) -> Self {
        Self { ppnum, vars: BTreeMap::new() }
    }
}

/// A validated batch of recipients enforcing both PCS quotas and SDK
/// invariants:
///
/// - **Non-empty**: at least one recipient (PCS rejects empty batches).
/// - **At most 1,000**: PCS External API limit per send request.
/// - **Deduplicated by ppnum**: avoids paying for two deliveries to the
///   same recipient if the caller's caller passed dupes.
///
/// Construct via [`Self::try_new`]; the only unchecked path is
/// `From<Vec<Recipient>>` which is intentionally not provided.
#[derive(Debug, Clone)]
pub struct RecipientList(Vec<Recipient>);

/// Construction-time error for a [`RecipientList`].
#[derive(Debug, Clone, thiserror::Error)]
pub enum RecipientListError {
    /// Zero recipients passed in.
    #[error("recipient list is empty")]
    Empty,
    /// More than 1,000 recipients (PCS hard limit).
    #[error("recipient list exceeds 1000 (got {count})")]
    TooLarge { count: usize },
}

const RECIPIENT_LIST_MAX: usize = 1000;

impl RecipientList {
    /// Validate and dedupe a recipient batch.
    ///
    /// Dedup is by [`Ppnum`] equality, preserving first-occurrence order.
    /// The deduped count must be in `1..=1000`.
    ///
    /// # Errors
    ///
    /// Returns [`RecipientListError::Empty`] when the input is empty,
    /// [`RecipientListError::TooLarge`] when the *deduped* result still
    /// exceeds 1,000 entries.
    pub fn try_new(recipients: Vec<Recipient>) -> Result<Self, RecipientListError> {
        if recipients.is_empty() {
            return Err(RecipientListError::Empty);
        }
        let mut seen: HashSet<String> = HashSet::with_capacity(recipients.len());
        let mut deduped = Vec::with_capacity(recipients.len());
        for r in recipients {
            if seen.insert(r.ppnum.as_str().to_string()) {
                deduped.push(r);
            }
        }
        if deduped.len() > RECIPIENT_LIST_MAX {
            return Err(RecipientListError::TooLarge { count: deduped.len() });
        }
        Ok(Self(deduped))
    }

    /// Convenience constructor for the common case where only ppnums
    /// are needed and templates require no per-recipient variables.
    ///
    /// # Errors
    ///
    /// Same as [`Self::try_new`].
    pub fn from_ppnums(ppnums: Vec<Ppnum>) -> Result<Self, RecipientListError> {
        Self::try_new(ppnums.into_iter().map(Recipient::bare).collect())
    }

    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Iterate over the underlying recipients (read-only — invariants
    /// stay locked).
    pub fn iter(&self) -> impl Iterator<Item = &Recipient> {
        self.0.iter()
    }
}

impl<'a> IntoIterator for &'a RecipientList {
    type Item = &'a Recipient;
    type IntoIter = std::slice::Iter<'a, Recipient>;
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

/// Optional poll configuration when the cited template includes a poll.
///
/// Maps to proto `PollConfig`. Default is "no poll attached".
#[derive(Debug, Clone, Default)]
pub struct PollConfig {
    /// Hours until the poll closes. `None` = template default.
    pub expires_in_hours: Option<i32>,
    /// Whether a recipient may submit multiple responses. Default `false`.
    pub allow_multiple: bool,
}

/// Outcome of a successful [`crate::PcsExternalClient::send_alert`] call.
#[derive(Debug, Clone)]
pub struct SendOutcome {
    pub id: SendRequestId,
    pub state: SendRequestState,
    pub total_recipients: u32,
}

/// Domain mirror of proto `SendRequestStatus`. Catch-all `Unknown` for
/// forward compatibility — proto enum addition won't break consumers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SendRequestState {
    Queued,
    Processing,
    Completed,
    Failed,
    /// Reserved value not understood by this SDK release.
    Unknown,
}

/// Aggregate status returned by
/// [`crate::PcsExternalClient::get_send_status`]. Per-recipient detail is
/// out of scope for the hot path and reachable via the escape hatch
/// when needed.
#[derive(Debug, Clone)]
pub struct SendStatus {
    pub id: SendRequestId,
    pub state: SendRequestState,
    pub totals: SendStatusTotals,
}

/// Delivery counters within a [`SendStatus`].
#[derive(Debug, Clone, Copy, Default)]
pub struct SendStatusTotals {
    pub total: u32,
    pub delivered: u32,
    pub pending_consent: u32,
    pub failed: u32,
}

// =============================================================================
// Streaming event types
// =============================================================================

/// Wrapper stream returned by
/// [`crate::PcsExternalClient::stream_send_request_events`].
///
/// Call `.message().await` in a loop to receive events. Returns `Ok(None)`
/// when the server closes the stream (normal end — reconnect to resume).
pub struct DeliveryStream(
    Box<dyn futures_core::Stream<Item = Result<DeliveryEvent, crate::Error>> + Send + Unpin>,
);

impl DeliveryStream {
    pub(crate) fn new(
        inner: impl futures_core::Stream<Item = Result<DeliveryEvent, crate::Error>>
            + Send
            + Unpin
            + 'static,
    ) -> Self {
        Self(Box::new(inner))
    }

    /// Receive the next delivery event.
    ///
    /// Returns `Ok(None)` when the stream ends normally. Returns `Err(…)` on
    /// transport, token, or proto mapping failure.
    pub async fn message(&mut self) -> Result<Option<DeliveryEvent>, crate::Error> {
        use futures_util::StreamExt as _;
        match self.0.next().await {
            None => Ok(None),
            Some(Ok(evt)) => Ok(Some(evt)),
            Some(Err(e)) => Err(e),
        }
    }
}

impl std::fmt::Debug for DeliveryStream {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DeliveryStream").finish_non_exhaustive()
    }
}

/// A single lifecycle event from
/// [`crate::PcsExternalClient::stream_send_request_events`].
#[derive(Debug, Clone)]
pub struct DeliveryEvent {
    /// ULID cursor — pass as `after_event_id` on reconnect to resume without
    /// replay.
    pub event_id: String,
    pub send_request_id: SendRequestId,
    pub kind: DeliveryEventKind,
    /// Server-reported event time. `None` if the server omitted the field.
    pub occurred_at: Option<prost_types::Timestamp>,
}

/// Discriminated payload of a [`DeliveryEvent`].
///
/// `ppnum` fields carry the raw digit string as received from PCS — validated
/// at send time, trusted on the receive path.
#[derive(Debug, Clone)]
pub enum DeliveryEventKind {
    RecipientDelivered { ppnum: String, message_id: Option<String> },
    RecipientFailed    { ppnum: String, error_code: Option<String> },
    RecipientPendingConsent { ppnum: String },
    ConsentGranted,
    ConsentDenied,
    RequestCompleted,
    PollResponseReceived,
    /// Unknown event type — forward-compat catch-all for future proto variants.
    Unknown,
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    #[test]
    fn ppnum_accepts_11_digits() {
        let p = Ppnum::try_new("12345678901").unwrap();
        assert_eq!(p.as_str(), "12345678901");
    }

    #[test]
    fn ppnum_accepts_longer_than_11() {
        let p = Ppnum::try_new("123456789012345").unwrap();
        assert_eq!(p.as_str().len(), 15);
    }

    #[test]
    fn ppnum_rejects_short() {
        let err = Ppnum::try_new("1234567890").unwrap_err();
        assert!(matches!(err, PpnumError::TooShort { len: 10 }));
    }

    #[test]
    fn ppnum_rejects_empty() {
        let err = Ppnum::try_new("").unwrap_err();
        assert!(matches!(err, PpnumError::Empty));
    }

    #[test]
    fn ppnum_rejects_non_digit() {
        let err = Ppnum::try_new("1234567890a").unwrap_err();
        assert!(matches!(err, PpnumError::NonDigit { pos: 10 }));
    }

    #[test]
    fn ppnum_rejects_hyphens() {
        // Display format is `123-1234-5678` but storage is digits-only.
        let err = Ppnum::try_new("123-1234-5678").unwrap_err();
        assert!(matches!(err, PpnumError::NonDigit { .. }));
    }

    fn p(s: &str) -> Ppnum {
        Ppnum::try_new(s).unwrap()
    }

    #[test]
    fn recipient_list_rejects_empty() {
        let err = RecipientList::try_new(vec![]).unwrap_err();
        assert!(matches!(err, RecipientListError::Empty));
    }

    #[test]
    fn recipient_list_dedupes_by_ppnum() {
        let list = RecipientList::from_ppnums(vec![
            p("12345678901"),
            p("12345678901"),
            p("12345678902"),
        ])
        .unwrap();
        assert_eq!(list.len(), 2);
    }

    #[test]
    fn recipient_list_dedup_keeps_first_occurrence() {
        let mut a = Recipient::bare(p("12345678901"));
        a.vars.insert("name".into(), "first".into());
        let mut b = Recipient::bare(p("12345678901"));
        b.vars.insert("name".into(), "second".into());
        let c = Recipient::bare(p("12345678902"));
        let list = RecipientList::try_new(vec![a, b, c]).unwrap();
        assert_eq!(list.len(), 2);
        let first = list.iter().next().unwrap();
        assert_eq!(first.vars.get("name").map(String::as_str), Some("first"));
    }

    #[test]
    fn recipient_list_accepts_max_1000() {
        let ppnums: Vec<Ppnum> =
            (0..1000).map(|i| p(&format!("100000{:05}", i))).collect();
        let list = RecipientList::from_ppnums(ppnums).unwrap();
        assert_eq!(list.len(), 1000);
    }

    #[test]
    fn recipient_list_rejects_over_1000_after_dedup() {
        let ppnums: Vec<Ppnum> =
            (0..1001).map(|i| p(&format!("100000{:05}", i))).collect();
        let err = RecipientList::from_ppnums(ppnums).unwrap_err();
        assert!(matches!(err, RecipientListError::TooLarge { count: 1001 }));
    }

    #[test]
    fn recipient_list_dedup_can_rescue_oversize_input() {
        // 1500 entries collapse to 750 unique → valid.
        let mut ppnums: Vec<Ppnum> =
            (0..750).map(|i| p(&format!("100000{:05}", i))).collect();
        ppnums.extend(ppnums.clone());
        let list = RecipientList::from_ppnums(ppnums).unwrap();
        assert_eq!(list.len(), 750);
    }
}