actr-protocol 0.3.1

Unified protocol, types, and URI parsing for Actor-RTC framework
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
use std::fmt::{self, Display};
use std::ops::{Deref, DerefMut};
use std::str::FromStr;
use thiserror::Error;

// Protobuf Package name
// Syntax: composed of letters, digits and underscores, segments separated by '.' (similar to Java package names)
// Naming conventions:
// - All lowercase
// - Reverse domain name form recommended (e.g. com.example.project) to avoid conflicts
// - Must not start with a digit, no special characters other than '.' and '_'

// Protobuf Service name
// Syntax: composed of letters, digits and underscores
// Naming conventions:
// - PascalCase (first letter uppercase)
// - Typically nouns or noun phrases
// - Must not start with a digit, no special characters

// Protobuf Method name
// Syntax: composed of letters, digits and underscores
// Naming conventions:
// - camelCase (first letter lowercase)
// - Typically verbs or verb phrases
// - Must not start with a digit, no special characters

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct PackageName(String);

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct ServiceName(String);

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct MethodName(String);

/// A validated actor name.
///
/// Names must:
/// - Start with an alphabetic character
/// - End with an alphanumeric character
/// - Contain only alphanumeric characters, hyphens, underscores, and dots
/// - Be non-empty
/// - Not exceed 32 characters in length
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Name(String);

#[derive(Debug, Error, Eq, PartialEq)]
pub enum NameError {
    #[error("Name is empty")]
    Empty,

    #[error("Name exceeds 32 characters, length: {0}")]
    TooLong(usize),

    #[error("Name must start with an alphabetic character, found: {0}")]
    InvalidStartChar(char),

    #[error("Name must end with an alphanumeric character, found: {0}")]
    InvalidEndChar(char),

    #[error("Name contains invalid character: {0}")]
    InvalidChar(char),
}

impl Name {
    /// Creates a new validated Name.
    ///
    /// # Errors
    ///
    /// Returns `NameError` with specific reason if the name doesn't meet the validation criteria.
    pub fn new(name: String) -> Result<Self, NameError> {
        if name.is_empty() {
            return Err(NameError::Empty);
        }
        if name.len() > 32 {
            return Err(NameError::TooLong(name.len()));
        }
        let mut chars = name.chars();
        let first = chars.next().ok_or(NameError::Empty)?;
        if !first.is_alphabetic() {
            return Err(NameError::InvalidStartChar(first));
        }
        let mut last = first;
        for c in chars {
            last = c;
            if !c.is_alphanumeric() && c != '-' && c != '_' && c != '.' {
                return Err(NameError::InvalidChar(c));
            }
        }
        if !last.is_alphanumeric() {
            return Err(NameError::InvalidEndChar(last));
        }
        Ok(Self(name))
    }
}

impl FromStr for Name {
    type Err = NameError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s.to_string())
    }
}

impl Deref for Name {
    type Target = String;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for Name {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl TryFrom<String> for Name {
    type Error = NameError;
    fn try_from(s: String) -> Result<Self, Self::Error> {
        Self::new(s)
    }
}

impl Display for Name {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

// ----------------------------- PackageName -----------------------------

#[derive(Debug, Error, Eq, PartialEq)]
pub enum PackageNameError {
    #[error("Package name is empty")]
    Empty,

    #[error("Package name exceeds 256 characters, length: {0}")]
    TooLong(usize),

    #[error("Package name must not start with a digit or '.', found: {0}")]
    InvalidStartChar(char),

    #[error("Package name must not end with '.', found: {0}")]
    InvalidEndChar(char),

    #[error("Package name contains invalid character: {0}")]
    InvalidChar(char),

    #[error("Package name contains empty segment")]
    EmptySegment,

    #[error("Package name segment must not start with a digit, found: {0}")]
    InvalidSegmentStartChar(char),
}

impl PackageName {
    pub fn new(name: String) -> Result<Self, PackageNameError> {
        const MAX_LEN: usize = 256;
        if name.is_empty() {
            return Err(PackageNameError::Empty);
        }
        if name.len() > MAX_LEN {
            return Err(PackageNameError::TooLong(name.len()));
        }

        let mut chars = name.chars();
        let first = chars.next().ok_or(PackageNameError::Empty)?;

        // First character rules: cannot be digit or '.'; letters must be lowercase
        if first == '.' || first.is_ascii_digit() {
            return Err(PackageNameError::InvalidStartChar(first));
        }
        if first.is_alphabetic() && first.is_uppercase() {
            return Err(PackageNameError::InvalidChar(first));
        }
        if !(first.is_alphanumeric() || first == '_') {
            // Only letters/digits/underscore are allowed ('.' only as separator handled below)
            return Err(PackageNameError::InvalidChar(first));
        }

        let mut last = first;
        let mut at_segment_start = false; // after first char we've already started first segment

        for c in chars {
            // Dot separates segments
            if c == '.' {
                if last == '.' {
                    return Err(PackageNameError::EmptySegment);
                }
                at_segment_start = true;
                last = c;
                continue;
            }

            // Segment start cannot be digit
            if at_segment_start && c.is_ascii_digit() {
                return Err(PackageNameError::InvalidSegmentStartChar(c));
            }
            at_segment_start = false;

            // Allowed chars inside segments
            if !(c.is_alphanumeric() || c == '_') {
                return Err(PackageNameError::InvalidChar(c));
            }
            // Enforce lowercase for alphabetic
            if c.is_alphabetic() && c.is_uppercase() {
                return Err(PackageNameError::InvalidChar(c));
            }

            last = c;
        }

        if last == '.' {
            return Err(PackageNameError::InvalidEndChar(last));
        }

        Ok(Self(name))
    }
}

impl FromStr for PackageName {
    type Err = PackageNameError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s.to_string())
    }
}

impl Deref for PackageName {
    type Target = String;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for PackageName {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl TryFrom<String> for PackageName {
    type Error = PackageNameError;
    fn try_from(s: String) -> Result<Self, Self::Error> {
        Self::new(s)
    }
}

impl Display for PackageName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

// ----------------------------- ServiceName -----------------------------

#[derive(Debug, Error, Eq, PartialEq)]
pub enum ServiceNameError {
    #[error("Service name is empty")]
    Empty,

    #[error("Service name exceeds 64 characters, length: {0}")]
    TooLong(usize),

    #[error("Service name must start with an uppercase alphabetic character, found: {0}")]
    InvalidStartChar(char),

    #[error("Service name must end with an alphanumeric character, found: {0}")]
    InvalidEndChar(char),

    #[error("Service name contains invalid character: {0}")]
    InvalidChar(char),
}

impl ServiceName {
    pub fn new(name: String) -> Result<Self, ServiceNameError> {
        const MAX_LEN: usize = 64;
        if name.is_empty() {
            return Err(ServiceNameError::Empty);
        }
        if name.len() > MAX_LEN {
            return Err(ServiceNameError::TooLong(name.len()));
        }

        let mut chars = name.chars();
        let first = chars.next().ok_or(ServiceNameError::Empty)?;
        if !first.is_alphabetic() || !first.is_uppercase() {
            return Err(ServiceNameError::InvalidStartChar(first));
        }
        let mut last = first;
        for c in chars {
            if !(c.is_alphanumeric() || c == '_') {
                return Err(ServiceNameError::InvalidChar(c));
            }
            last = c;
        }
        if !last.is_alphanumeric() {
            return Err(ServiceNameError::InvalidEndChar(last));
        }
        Ok(Self(name))
    }
}

impl FromStr for ServiceName {
    type Err = ServiceNameError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s.to_string())
    }
}

impl Deref for ServiceName {
    type Target = String;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for ServiceName {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl TryFrom<String> for ServiceName {
    type Error = ServiceNameError;
    fn try_from(s: String) -> Result<Self, Self::Error> {
        Self::new(s)
    }
}

impl Display for ServiceName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

// ----------------------------- MethodName -----------------------------

#[derive(Debug, Error, Eq, PartialEq)]
pub enum MethodNameError {
    #[error("Method name is empty")]
    Empty,

    #[error("Method name exceeds 64 characters, length: {0}")]
    TooLong(usize),

    #[error("Method name must start with a lowercase alphabetic character, found: {0}")]
    InvalidStartChar(char),

    #[error("Method name must end with an alphanumeric character, found: {0}")]
    InvalidEndChar(char),

    #[error("Method name contains invalid character: {0}")]
    InvalidChar(char),
}

impl MethodName {
    pub fn new(name: String) -> Result<Self, MethodNameError> {
        const MAX_LEN: usize = 64;
        if name.is_empty() {
            return Err(MethodNameError::Empty);
        }
        if name.len() > MAX_LEN {
            return Err(MethodNameError::TooLong(name.len()));
        }

        let mut chars = name.chars();
        let first = chars.next().ok_or(MethodNameError::Empty)?;
        if !first.is_alphabetic() || !first.is_lowercase() {
            return Err(MethodNameError::InvalidStartChar(first));
        }
        let mut last = first;
        for c in chars {
            if !(c.is_alphanumeric() || c == '_') {
                return Err(MethodNameError::InvalidChar(c));
            }
            last = c;
        }
        if !last.is_alphanumeric() {
            return Err(MethodNameError::InvalidEndChar(last));
        }
        Ok(Self(name))
    }
}

impl FromStr for MethodName {
    type Err = MethodNameError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::new(s.to_string())
    }
}

impl Deref for MethodName {
    type Target = String;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl DerefMut for MethodName {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl TryFrom<String> for MethodName {
    type Error = MethodNameError;
    fn try_from(s: String) -> Result<Self, Self::Error> {
        Self::new(s)
    }
}

impl Display for MethodName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_valid_name() {
        assert!(Name::new("valid-name_123".to_string()).is_ok());
        assert!(Name::new("A".to_string()).is_ok());
        assert!(Name::new("actor-1".to_string()).is_ok());
        assert!(Name::new("actor.1".to_string()).is_ok());
        assert!(Name::new("com.example.actor".to_string()).is_ok());
    }

    #[test]
    fn test_invalid_name() {
        assert_eq!(Name::new("".to_string()).unwrap_err(), NameError::Empty);
        assert_eq!(
            Name::new("-invalid".to_string()).unwrap_err(),
            NameError::InvalidStartChar('-')
        );
        assert_eq!(
            Name::new(".invalid".to_string()).unwrap_err(),
            NameError::InvalidStartChar('.')
        );
        assert_eq!(
            Name::new("invalid-".to_string()).unwrap_err(),
            NameError::InvalidEndChar('-')
        );
        assert_eq!(
            Name::new("invalid.".to_string()).unwrap_err(),
            NameError::InvalidEndChar('.')
        );
        assert_eq!(
            Name::new("has invalid char!".to_string()).unwrap_err(),
            NameError::InvalidChar(' ')
        );
        assert_eq!(
            Name::new("too_long_name_that_exceeds_thirty_two_characters".to_string()).unwrap_err(),
            NameError::TooLong(48)
        );
        assert_eq!(
            Name::new("1starts_with_number".to_string()).unwrap_err(),
            NameError::InvalidStartChar('1')
        );
    }

    #[test]
    fn test_valid_package_name() {
        assert!(PackageName::new("com.example.project".to_string()).is_ok());
        assert!(PackageName::new("a_b.c_d.e1".to_string()).is_ok());
        assert!(PackageName::new("example".to_string()).is_ok());
        assert!(PackageName::new("_internal.pkg".to_string()).is_ok());
    }

    #[test]
    fn test_invalid_package_name() {
        assert_eq!(
            PackageName::new("".to_string()).unwrap_err(),
            PackageNameError::Empty
        );
        assert_eq!(
            PackageName::new(".leading".to_string()).unwrap_err(),
            PackageNameError::InvalidStartChar('.')
        );
        assert_eq!(
            PackageName::new("trailing.".to_string()).unwrap_err(),
            PackageNameError::InvalidEndChar('.')
        );
        assert_eq!(
            PackageName::new("com..example".to_string()).unwrap_err(),
            PackageNameError::EmptySegment
        );
        assert_eq!(
            PackageName::new("com.1example".to_string()).unwrap_err(),
            PackageNameError::InvalidSegmentStartChar('1')
        );
        assert_eq!(
            PackageName::new("Com.Example".to_string()).unwrap_err(),
            PackageNameError::InvalidChar('C')
        );
        assert_eq!(
            PackageName::new("com.exa$mple".to_string()).unwrap_err(),
            PackageNameError::InvalidChar('$')
        );
    }

    #[test]
    fn test_valid_service_name() {
        assert!(ServiceName::new("Echo".to_string()).is_ok());
        assert!(ServiceName::new("UserService".to_string()).is_ok());
        assert!(ServiceName::new("HTTPV1".to_string()).is_ok());
        assert!(ServiceName::new("Service_Name".to_string()).is_ok());
    }

    #[test]
    fn test_invalid_service_name() {
        assert_eq!(
            ServiceName::new("".to_string()).unwrap_err(),
            ServiceNameError::Empty
        );
        assert_eq!(
            ServiceName::new("service".to_string()).unwrap_err(),
            ServiceNameError::InvalidStartChar('s')
        );
        assert_eq!(
            ServiceName::new("_Service".to_string()).unwrap_err(),
            ServiceNameError::InvalidStartChar('_')
        );
        assert_eq!(
            ServiceName::new("Service-".to_string()).unwrap_err(),
            ServiceNameError::InvalidChar('-')
        );
        assert_eq!(
            ServiceName::new("Service_".to_string()).unwrap_err(),
            ServiceNameError::InvalidEndChar('_')
        );
    }

    #[test]
    fn test_valid_method_name() {
        assert!(MethodName::new("echo".to_string()).is_ok());
        assert!(MethodName::new("doWork".to_string()).is_ok());
        assert!(MethodName::new("get_v1".to_string()).is_ok());
    }

    #[test]
    fn test_invalid_method_name() {
        assert_eq!(
            MethodName::new("".to_string()).unwrap_err(),
            MethodNameError::Empty
        );
        assert_eq!(
            MethodName::new("1call".to_string()).unwrap_err(),
            MethodNameError::InvalidStartChar('1')
        );
        assert_eq!(
            MethodName::new("Call".to_string()).unwrap_err(),
            MethodNameError::InvalidStartChar('C')
        );
        assert_eq!(
            MethodName::new("do-".to_string()).unwrap_err(),
            MethodNameError::InvalidChar('-')
        );
        assert_eq!(
            MethodName::new("do_".to_string()).unwrap_err(),
            MethodNameError::InvalidEndChar('_')
        );
    }
}