wechat-calls 2.1.0

WeChat voice session and media building blocks, PCM pacing, mixing and native Opus
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
//! Call admission and controller ownership, independent of a daemon or transport.
//! All operations run under one caller-held lock. Use one instance per account.
//!
//! This policy layer performs no network I/O. A reservation authorizes one
//! account operation only after its host persists the intent and checks
//! its current credential/logout generation. Uncertain active operations retain
//! the slot until the backend stops and the local session closes. This module
//! owns no credentials, account lifecycle, storage, threads or network I/O.
use std::collections::BTreeMap;

const MAX_CLIENTS: usize = 64;
const MAX_REQUESTS: usize = 256;
const REQUEST_TTL_MS: u64 = 300_000;

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AccountAuthority {
    pub account_id: String,
    /// A nonsecret accepted-credential/logout generation supplied by the actor.
    pub generation: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Phase {
    Ringing,
    Dialing,
    Answering,
    Connected,
    Ending,
    Uncertain,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Operation {
    Dial,
    Answer,
    Reject,
    Cancel,
    Hangup,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CallView {
    pub call_id: String,
    pub revision: u64,
    pub phase: Phase,
    pub owned: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Snapshot {
    /// Availability within this admission instance.
    pub busy: bool,
    /// Only the incoming offer or the owner's call is visible in detail.
    pub current: Option<CallView>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Error {
    Invalid,
    Capacity,
    Busy,
    NotConnected,
    NotReady,
    Stale,
    NotOwner,
    Conflict,
    InvalidTransition,
}
/// Opaque identity for one local call attempt. A reused public call ID cannot
/// make a delayed actor event apply to a newer attempt.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CallIdentity {
    attempt: u64,
    call_id: String,
}
impl CallIdentity {
    pub fn call_id(&self) -> &str {
        &self.call_id
    }
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Ticket {
    attempt: u64,
    authority: AccountAuthority,
    call_id: String,
    revision: u64,
    operation: Operation,
}
impl Ticket {
    pub fn identity(&self) -> CallIdentity {
        CallIdentity {
            attempt: self.attempt,
            call_id: self.call_id.clone(),
        }
    }
    pub fn authority(&self) -> &AccountAuthority {
        &self.authority
    }
    pub fn call_id(&self) -> &str {
        &self.call_id
    }
    pub fn operation(&self) -> Operation {
        self.operation
    }
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Decision {
    /// A unique operation. Persist its account intent before submitting it.
    Submit(Ticket),
    /// Same request on the same identity: observe its result, never submit again.
    Replay(Ticket),
}
#[derive(Clone)]
struct Client {
    logical_id: u64,
    authority: AccountAuthority,
    principal: String,
    ready: bool,
}
struct Session {
    attempt: u64,
    authority: AccountAuthority,
    id: String,
    revision: u64,
    phase: Phase,
    owner: Option<String>,
    owner_principal: Option<String>,
    owner_logical_id: Option<u64>,
    owner_closed_at: Option<u64>,
    offer_until: Option<u64>,
    pending: Option<Ticket>,
    invalidated: bool,
}
#[derive(Clone, PartialEq, Eq)]
struct Intent {
    operation: Operation,
    call_id: String,
    expected_revision: Option<u64>,
    parameters: String,
}
struct Receipt {
    intent: Intent,
    ticket: Ticket,
    expires: u64,
}
/// No durable settled history is stored here. The account actor owns pending
/// intents and their uncertain network outcomes; official profiles own history.
#[derive(Default)]
pub struct Ownership {
    next_attempt: u64,
    next_client: u64,
    clients: BTreeMap<String, Client>,
    session: Option<Session>,
    requests: BTreeMap<(u64, String), Receipt>,
}
fn valid_id(s: &str) -> bool {
    !s.is_empty() && s.len() <= 200 && !s.chars().any(char::is_control)
}
impl Ownership {
    /// IDs are server-generated connection identities, never user-chosen claims.
    /// Snapshot and event subscription must be installed under the same lock.
    pub fn connect(
        &mut self,
        client_id: &str,
        authority: AccountAuthority,
        principal: &str,
    ) -> Result<Snapshot, Error> {
        if !valid_id(client_id)
            || !valid_id(&authority.account_id)
            || !valid_id(&authority.generation)
            || !valid_id(principal)
            || self.clients.contains_key(client_id)
        {
            return Err(Error::Invalid);
        }
        if self.clients.len() >= MAX_CLIENTS {
            return Err(Error::Capacity);
        }
        let logical_id = self.next_client.checked_add(1).ok_or(Error::Capacity)?;
        self.next_client = logical_id;
        self.clients.insert(
            client_id.into(),
            Client {
                logical_id,
                authority,
                principal: principal.into(),
                ready: false,
            },
        );
        self.snapshot(client_id)
    }
    pub fn ready(&mut self, client_id: &str, ready: bool) -> Result<(), Error> {
        self.clients
            .get_mut(client_id)
            .ok_or(Error::NotConnected)?
            .ready = ready;
        Ok(())
    }
    pub fn snapshot(&self, client_id: &str) -> Result<Snapshot, Error> {
        let client = self.clients.get(client_id).ok_or(Error::NotConnected)?;
        let current = self.session.as_ref().and_then(|s| {
            let owned = s.owner.as_deref() == Some(client_id)
                && s.owner_logical_id == Some(client.logical_id)
                && s.owner_principal.as_deref() == Some(client.principal.as_str());
            (s.authority == client.authority
                && (owned || (s.phase == Phase::Ringing && s.owner.is_none())))
            .then(|| CallView {
                call_id: s.id.clone(),
                revision: s.revision,
                phase: s.phase,
                owned,
            })
        });
        Ok(Snapshot {
            busy: self.session.is_some(),
            current,
        })
    }
    /// Only the account actor may introduce an independently current offer.
    /// No client readiness is needed to retain it for late attachment.
    pub fn offer(
        &mut self,
        authority: AccountAuthority,
        call_id: &str,
        expires: u64,
        now: u64,
    ) -> Result<CallIdentity, Error> {
        if !valid_id(call_id)
            || !valid_id(&authority.account_id)
            || !valid_id(&authority.generation)
            || expires <= now
        {
            return Err(Error::Invalid);
        }
        if self.session.is_some() {
            return Err(Error::Busy);
        }
        let attempt = self.next_attempt.checked_add(1).ok_or(Error::Capacity)?;
        self.next_attempt = attempt;
        self.session = Some(Session {
            attempt,
            authority,
            id: call_id.into(),
            revision: 1,
            phase: Phase::Ringing,
            owner: None,
            owner_principal: None,
            owner_logical_id: None,
            owner_closed_at: None,
            offer_until: Some(expires),
            pending: None,
            invalidated: false,
        });
        Ok(CallIdentity {
            attempt,
            call_id: call_id.into(),
        })
    }
    /// Apply a newer revision to the same still-unclaimed incoming offer.
    pub fn offer_revision(
        &mut self,
        authority: &AccountAuthority,
        identity: &CallIdentity,
        revision: u64,
    ) -> Result<(), Error> {
        let session = self.session.as_mut().ok_or(Error::Stale)?;
        if &session.authority != authority
            || session.attempt != identity.attempt
            || session.id != identity.call_id
            || session.invalidated
            || session.owner.is_some()
            || session.phase != Phase::Ringing
            || revision <= session.revision
        {
            return Err(Error::Stale);
        }
        session.revision = revision;
        Ok(())
    }
    /// Inspect the unresolved start operation for this exact account attempt.
    pub fn pending_start(
        &self,
        authority: &AccountAuthority,
        identity: &CallIdentity,
    ) -> Option<Operation> {
        let session = self.session.as_ref()?;
        if &session.authority != authority
            || session.attempt != identity.attempt
            || session.id != identity.call_id
            || session.invalidated
        {
            return None;
        }
        session
            .pending
            .as_ref()
            .map(|ticket| ticket.operation)
            .filter(|operation| matches!(operation, Operation::Dial | Operation::Answer))
    }

    /// Inspect an unresolved terminal operation without resubmitting it.
    pub fn pending_terminal_operation(
        &self,
        authority: &AccountAuthority,
        identity: &CallIdentity,
    ) -> Option<Operation> {
        let session = self.session.as_ref().filter(|session| {
            &session.authority == authority
                && session.attempt == identity.attempt
                && session.id == identity.call_id
                && !session.invalidated
                && session.phase == Phase::Ending
        })?;
        session
            .pending
            .as_ref()
            .map(|ticket| ticket.operation)
            .filter(|operation| {
                matches!(
                    operation,
                    Operation::Reject | Operation::Cancel | Operation::Hangup
                )
            })
    }

    /// Whether this exact attempt has a pending cancel or hangup.
    pub fn pending_end(&self, authority: &AccountAuthority, identity: &CallIdentity) -> bool {
        matches!(
            self.pending_terminal_operation(authority, identity),
            Some(Operation::Cancel | Operation::Hangup)
        )
    }
    /// Reserve this account's slot for the initiating client before Invite.
    pub fn dial(
        &mut self,
        client_id: &str,
        request_id: &str,
        new_call_id: &str,
        parameters: &str,
        now: u64,
    ) -> Result<Decision, Error> {
        self.command(
            client_id,
            request_id,
            Intent {
                operation: Operation::Dial,
                call_id: new_call_id.into(),
                expected_revision: None,
                parameters: parameters.into(),
            },
            now,
        )
    }
    /// Parameters is a canonical nonsecret digest over all resolved arguments.
    pub fn act(
        &mut self,
        client_id: &str,
        request_id: &str,
        call_id: &str,
        revision: u64,
        operation: Operation,
        now: u64,
    ) -> Result<Decision, Error> {
        if operation == Operation::Dial {
            return Err(Error::Invalid);
        }
        self.command(
            client_id,
            request_id,
            Intent {
                operation,
                call_id: call_id.into(),
                expected_revision: Some(revision),
                parameters: String::new(),
            },
            now,
        )
    }
    fn command(
        &mut self,
        client_id: &str,
        request_id: &str,
        intent: Intent,
        now: u64,
    ) -> Result<Decision, Error> {
        if !valid_id(request_id) || !valid_id(&intent.call_id) || intent.parameters.len() > 200 {
            return Err(Error::Invalid);
        }
        let client = self
            .clients
            .get(client_id)
            .ok_or(Error::NotConnected)?
            .clone();
        self.requests.retain(|_, r| {
            now < r.expires
                || self
                    .session
                    .as_ref()
                    .is_some_and(|s| s.attempt == r.ticket.attempt)
        });
        let key = (client.logical_id, request_id.to_owned());
        if let Some(prior) = self.requests.get(&key) {
            return if prior.intent == intent && prior.ticket.authority == client.authority {
                Ok(Decision::Replay(prior.ticket.clone()))
            } else {
                Err(Error::Conflict)
            };
        }
        if self.requests.len() >= MAX_REQUESTS {
            return Err(Error::Capacity);
        }
        if intent.operation == Operation::Dial {
            if !client.ready {
                return Err(Error::NotReady);
            }
            if self.session.is_some() {
                return Err(Error::Busy);
            }
            let attempt = self.next_attempt.checked_add(1).ok_or(Error::Capacity)?;
            self.next_attempt = attempt;
            self.session = Some(Session {
                attempt,
                authority: client.authority.clone(),
                id: intent.call_id.clone(),
                revision: 1,
                phase: Phase::Dialing,
                owner: Some(client_id.into()),
                owner_principal: Some(client.principal.clone()),
                owner_logical_id: Some(client.logical_id),
                owner_closed_at: None,
                offer_until: None,
                pending: None,
                invalidated: false,
            });
        } else {
            let s = self.session.as_mut().ok_or(Error::Stale)?;
            if s.invalidated
                || s.authority != client.authority
                || s.id != intent.call_id
                || intent.expected_revision != Some(s.revision)
                || s.offer_until.is_some_and(|until| now >= until)
            {
                return Err(Error::Stale);
            }
            if let Some(owner) = &s.owner {
                if owner != client_id
                    || s.owner_logical_id != Some(client.logical_id)
                    || s.owner_principal.as_deref() != Some(client.principal.as_str())
                {
                    return Err(Error::NotOwner);
                }
            }
            // Dispatch only after the previous operation has an admitted or
            // terminal result. In particular, an early Cancel must not replace
            // an unresolved Invite and lose its possible accepted outcome.
            if s.pending.is_some() {
                return Err(Error::InvalidTransition);
            }
            let next_phase = match intent.operation {
                Operation::Answer if s.phase == Phase::Ringing && s.owner.is_none() => {
                    if !client.ready {
                        return Err(Error::NotReady);
                    }
                    Phase::Answering
                }
                Operation::Reject if s.phase == Phase::Ringing && s.owner.is_none() => {
                    Phase::Ending
                }
                Operation::Cancel if s.phase == Phase::Dialing => Phase::Ending,
                Operation::Hangup if matches!(s.phase, Phase::Answering | Phase::Connected) => {
                    Phase::Ending
                }
                _ => return Err(Error::InvalidTransition),
            };
            let revision = s.revision.checked_add(1).ok_or(Error::Capacity)?;
            s.owner = Some(client_id.into());
            s.owner_principal = Some(client.principal.clone());
            s.owner_logical_id = Some(client.logical_id);
            s.phase = next_phase;
            s.revision = revision;
            s.offer_until = None;
        }
        let s = self.session.as_ref().expect("reserved session");
        let ticket = Ticket {
            attempt: s.attempt,
            authority: s.authority.clone(),
            call_id: s.id.clone(),
            revision: s.revision,
            operation: intent.operation,
        };
        self.session.as_mut().expect("reserved session").pending = Some(ticket.clone());
        self.requests.insert(
            key,
            Receipt {
                intent,
                ticket: ticket.clone(),
                expires: now.saturating_add(REQUEST_TTL_MS),
            },
        );
        Ok(Decision::Submit(ticket))
    }
    /// An account actor reports a correlated result. Late results cannot clear
    /// or connect another call. Unknown outcomes keep the account slot occupied.
    pub fn result(&mut self, ticket: &Ticket, phase: Option<Phase>) -> Result<(), Error> {
        let s = self.session.as_mut().ok_or(Error::Stale)?;
        if s.attempt != ticket.attempt
            || s.authority != ticket.authority
            || s.id != ticket.call_id
            || s.pending.as_ref() != Some(ticket)
            || s.invalidated
        {
            return Err(Error::Stale);
        }
        if phase.is_some_and(|phase| !matches!(phase, Phase::Uncertain))
            && !s
                .owner
                .as_ref()
                .and_then(|owner| self.clients.get(owner))
                .is_some_and(|client| {
                    s.owner_logical_id == Some(client.logical_id)
                        && client.authority == s.authority
                        && s.owner_principal.as_deref() == Some(client.principal.as_str())
                })
        {
            return Err(Error::Stale);
        }
        let next = match (ticket.operation, phase) {
            (_, None) => None,
            (_, Some(Phase::Uncertain)) => Some(Phase::Uncertain),
            (Operation::Dial, Some(Phase::Dialing)) => Some(Phase::Dialing),
            (Operation::Answer, Some(Phase::Answering)) => Some(Phase::Answering),
            (Operation::Dial | Operation::Answer, Some(Phase::Connected)) => Some(Phase::Connected),
            _ => return Err(Error::InvalidTransition),
        };
        if let Some(phase) = next {
            s.revision = s.revision.checked_add(1).ok_or(Error::Capacity)?;
            s.phase = phase;
            s.pending = None;
        } else {
            self.session = None;
        }
        Ok(())
    }
    /// Invite/Join admission and peer connection are different facts. The actor
    /// may report admission with `result(ticket, Some(Dialing/Answering))`, then
    /// call this only on verified peer/media readiness. The original ticket's
    /// attempt identity fences reused IDs and a newer operation such as Cancel.
    pub fn connected(&mut self, ticket: &Ticket) -> Result<(), Error> {
        let s = self.session.as_mut().ok_or(Error::Stale)?;
        if s.attempt != ticket.attempt
            || s.authority != ticket.authority
            || s.id != ticket.call_id
            || s.invalidated
            || s.pending.is_some()
            || !matches!(ticket.operation, Operation::Dial | Operation::Answer)
            || !matches!(s.phase, Phase::Dialing | Phase::Answering)
        {
            return Err(Error::Stale);
        }
        let revision = s.revision.checked_add(1).ok_or(Error::Capacity)?;
        s.revision = revision;
        s.phase = Phase::Connected;
        Ok(())
    }
    /// Stop local work without claiming that the remote call has ended.
    pub fn uncertain(
        &mut self,
        authority: &AccountAuthority,
        identity: &CallIdentity,
    ) -> Result<(), Error> {
        let s = self.session.as_mut().ok_or(Error::Stale)?;
        if &s.authority != authority || s.attempt != identity.attempt || s.id != identity.call_id {
            return Err(Error::Stale);
        }
        let revision = s.revision.checked_add(1).ok_or(Error::Capacity)?;
        s.revision = revision;
        s.phase = Phase::Uncertain;
        s.pending = None;
        s.owner_closed_at = None;
        Ok(())
    }
    /// Match the one pending business action without changing its ownership.
    pub fn pending_ticket_matches(&self, ticket: &Ticket) -> bool {
        self.session.as_ref().is_some_and(|session| {
            !session.invalidated
                && session.attempt == ticket.attempt
                && session.authority == ticket.authority
                && session.id == ticket.call_id
                && session.pending.as_ref() == Some(ticket)
        })
    }
    /// Verified terminal signaling from the accepted generation, including a
    /// pickup by another official device. The source adapter establishes meaning.
    pub fn terminal(
        &mut self,
        authority: &AccountAuthority,
        identity: &CallIdentity,
    ) -> Result<(), Error> {
        if !self.session.as_ref().is_some_and(|s| {
            &s.authority == authority && s.id == identity.call_id && s.attempt == identity.attempt
        }) {
            return Err(Error::Stale);
        }
        self.session = None;
        Ok(())
    }
    pub fn disconnect(&mut self, client_id: &str, now: u64) {
        // Several transport error paths can close one connection. Only the
        // first close requests cleanup; old callbacks cannot postpone it.
        let Some(client) = self.clients.remove(client_id) else {
            return;
        };
        if let Some(s) = self.session.as_mut().filter(|s| {
            !s.invalidated
                && s.owner.as_deref() == Some(client_id)
                && s.owner_logical_id == Some(client.logical_id)
                && s.owner_principal.as_deref() == Some(client.principal.as_str())
        }) {
            s.owner_closed_at = Some(now);
        }
    }
    /// A closed owner connection requests cleanup immediately. The actor receives
    /// its call identity once; reconnecting never transfers that ownership.
    pub fn expire(&mut self, now: u64) -> Option<(AccountAuthority, CallIdentity)> {
        let s = self.session.as_mut()?;
        if s.phase == Phase::Ringing && s.offer_until.is_some_and(|until| now >= until) {
            self.session = None;
            return None;
        }
        if s.owner_closed_at.is_some_and(|until| now >= until) {
            s.owner_closed_at = None;
            // Any late accepted Invite/Join result must not revive a call whose
            // owner has gone. The actor reconciles/terminates it by identity.
            // Keep only an in-flight start's correlation for its received
            // allocation/Join cleanup. It does not restore controller authority.
            if !s.pending.as_ref().is_some_and(|ticket| {
                matches!(ticket.operation, Operation::Dial | Operation::Answer)
            }) {
                s.pending = None;
            }
            s.phase = Phase::Uncertain;
            s.revision = s.revision.saturating_add(1);
            return Some((
                s.authority.clone(),
                CallIdentity {
                    attempt: s.attempt,
                    call_id: s.id.clone(),
                },
            ));
        }
        None
    }
    /// Credential replacement/logout fences all sockets and stops affected work.
    /// The account actor still reconciles any pending remote operation separately.
    pub fn invalidate(&mut self, authority: &AccountAuthority) -> Option<String> {
        self.clients.retain(|_, c| &c.authority != authority);
        if self
            .session
            .as_ref()
            .is_some_and(|s| &s.authority == authority)
        {
            let s = self.session.as_mut().expect("matched session");
            if s.invalidated {
                return None;
            }
            s.invalidated = true;
            s.phase = Phase::Uncertain;
            s.revision = s.revision.saturating_add(1);
            s.owner_closed_at = None;
            return Some(s.id.clone());
        }
        None
    }
}

#[cfg(test)]
#[path = "admission/tests.rs"]
mod tests;