sylphx 0.3.8

The Sylphx SDK: one API, one key, every Sylphx service. Generated from the Sylphx schema registry.
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
// @generated by sylphx-gen. Do not edit.
//! `sylphx.realtime.v1`.

#![allow(clippy::all)]

/// The request of BindSubscription.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct BindSubscriptionRequest {
    /// The Events Subscription's resource name.
    ///
    /// Field behavior: `required`.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub subscription: String,
    /// The channel its events are published to, `namespace:name`.
    ///
    /// Field behavior: `required`.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub channel: String,
}

/// The response of BindSubscription.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct BindSubscriptionResponse {
    /// The Subscription bound.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub subscription: String,
    /// The channel it feeds.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub channel: String,
}

/// ChannelGrant is the capabilities a token grants on one channel pattern.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct ChannelGrant {
    /// A channel name or pattern: `room:42`, or `room:*` for every channel of the
    /// namespace. `*` is allowed only as the whole name part, and never in the
    /// namespace part.
    ///
    /// Field behavior: `required`.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub pattern: String,
    /// The capabilities granted. At least one.
    ///
    /// Field behavior: `required`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub capabilities: Vec<Capability>,
}

/// The request of DeleteNamespace.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct DeleteNamespaceRequest {
    /// The namespace name.
    ///
    /// Field behavior: `required`.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub name: String,
}

/// The response of DeleteNamespace.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct DeleteNamespaceResponse {}

/// The request of GetNamespace.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct GetNamespaceRequest {
    /// The namespace name.
    ///
    /// Field behavior: `required`.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub name: String,
}

/// The request of IssueToken.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct IssueTokenRequest {
    /// Which kind of token to mint.
    ///
    /// Field behavior: `required`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<TokenKind>,
    /// The end user's id. Required for a connection token.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub user: String,
    /// The channels and capabilities to grant. A channel token takes exactly one
    /// grant whose pattern has no `*`. At most 64 grants.
    ///
    /// Field behavior: `required`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub grants: Vec<ChannelGrant>,
    /// How long the token lives; 1 minute to 24 hours, default 1 hour.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub ttl: String,
}

/// The response of IssueToken.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct IssueTokenResponse {
    /// The token. Opaque; sent in the `connect` frame or the `Authorization`
    /// header, never in a URL.
    ///
    /// Field behavior: `sensitive`.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub token: String,
    /// When it expires.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "expireTime"
    )]
    pub expire_time: String,
    /// The claims the service put in it, for the caller to log or check.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub claims: Option<TokenClaims>,
    /// The realtime host the client connects to. Never hard-code it: it can
    /// change, with no port, and the protocol-v1 paths are fixed.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "connectUri"
    )]
    pub connect_uri: String,
    /// The earliest the client should ask for a replacement: the in-band
    /// `refresh_required` frame arrives at this time.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "refreshTime"
    )]
    pub refresh_time: String,
}

/// The request of ListMessages.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct ListMessagesRequest {
    /// The channel, `namespace:name`.
    ///
    /// Field behavior: `required`.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub channel: String,
    /// Return messages after this cursor. Empty starts at the oldest kept
    /// message.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub cursor: String,
    /// At most this many messages; default 100, at most 1,000.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "pageSize"
    )]
    pub page_size: i32,
    /// When no message is after the cursor, wait up to this many seconds for
    /// one; 0 to 30, default 0 (answer at once).
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "waitSeconds"
    )]
    pub wait_seconds: i32,
}

/// The response of ListMessages.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct ListMessagesResponse {
    /// The messages, oldest first. Empty when the wait ran out.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub messages: Vec<Message>,
    /// The cursor to pass as `cursor` next. Always set unless the
    /// namespace is ephemeral.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "nextCursor"
    )]
    pub next_cursor: String,
}

/// The request of ListNamespaces.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct ListNamespacesRequest {
    /// At most this many namespaces; the service caps it.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "pageSize"
    )]
    pub page_size: i32,
    /// The `next_page_token` of the previous page.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "pageToken"
    )]
    pub page_token: String,
}

/// The response of ListNamespaces.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct ListNamespacesResponse {
    /// The page of namespaces.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub namespaces: Vec<Namespace>,
    /// Empty on the last page.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "nextPageToken"
    )]
    pub next_page_token: String,
}

/// The request of ListPresence.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct ListPresenceRequest {
    /// The channel, `namespace:name`.
    ///
    /// Field behavior: `required`.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub channel: String,
    /// At most this many members; default 100, at most 1,000.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "pageSize"
    )]
    pub page_size: i32,
    /// The `next_page_token` of the previous page.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "pageToken"
    )]
    pub page_token: String,
}

/// The response of ListPresence.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct ListPresenceResponse {
    /// The members present.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub members: Vec<Member>,
    /// Empty on the last page.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "nextPageToken"
    )]
    pub next_page_token: String,
}

/// Member is one connection present on a channel.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct Member {
    /// The user id from the token.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub user: String,
    /// The connection id, unique while the connection lives.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "connectionId"
    )]
    pub connection_id: String,
    /// The application's presence data, at most 4 KiB encoded.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub data: serde_json::Value,
    /// When this connection entered.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "enterTime"
    )]
    pub enter_time: String,
}

/// Message is one message of a channel.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct Message {
    /// The channel, `namespace:name`.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub channel: String,
    /// The message's cursor: opaque, ordered within the channel, and the value
    /// to resume from. Empty in an ephemeral namespace.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub cursor: String,
    /// The application's event name, for example `move`. 1 to 64 characters.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub event: String,
    /// The JSON payload, at most 64 KiB encoded.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub data: serde_json::Value,
    /// The user id of the publisher; empty when a server published without one.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub publisher: String,
    /// When the service accepted the message.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "publishTime"
    )]
    pub publish_time: String,
}

/// Namespace is the only configured object of Sylphx Realtime. It carries the
/// rules of every channel named `<namespace>:<name>`. Channels are implicit:
/// they exist from their first publish or subscribe and are never created.
/// Declared in `sylphx.toml` as `[realtime.namespaces.<name>]`.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct Namespace {
    /// The namespace name: 1 to 32 characters of `a-z`, `0-9`, `-` and `_`,
    /// starting with a letter. It is the part of a channel before the first
    /// colon, and never changes.
    ///
    /// Field behavior: `required`.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub name: String,
    /// How much history channels keep. Default NONE.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub history: Option<HistoryPreset>,
    /// Whether channels track who is present. Default off.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub presence: bool,
    /// Whether a client holding a token with the publish capability may publish.
    /// Default off: only servers publish.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "clientPublish"
    )]
    pub client_publish: bool,
    /// When the namespace was created.
    ///
    /// Field behavior: `output_only`.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "createTime"
    )]
    pub create_time: String,
    /// When the rules last changed.
    ///
    /// Field behavior: `output_only`.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "updateTime"
    )]
    pub update_time: String,
}

/// The request of Publish.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct PublishRequest {
    /// The channel, `namespace:name`: the name is 1 to 128 characters of
    /// `a-z A-Z 0-9 - _ . =` and no `*`.
    ///
    /// Field behavior: `required`.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub channel: String,
    /// The application's event name, 1 to 64 characters.
    ///
    /// Field behavior: `required`.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub event: String,
    /// The JSON payload, at most 64 KiB encoded.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub data: serde_json::Value,
}

/// The response of Publish.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct PublishResponse {
    /// The published message; its cursor is empty in an ephemeral namespace.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub message: Option<Message>,
}

/// The request of PutNamespace.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct PutNamespaceRequest {
    /// The namespace name; see Namespace.name.
    ///
    /// Field behavior: `required`.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub name: String,
    /// How much history channels keep.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub history: Option<HistoryPreset>,
    /// Whether channels track presence.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub presence: bool,
    /// Whether clients may publish.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "clientPublish"
    )]
    pub client_publish: bool,
}

/// TokenClaims are the claims every Sylphx Realtime token carries. A token is
/// opaque to SDK users; this message states what the service puts in it and
/// what it checks.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
#[non_exhaustive]
pub struct TokenClaims {
    /// The token's kind.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<TokenKind>,
    /// The authoritative Access environment id, not a client-supplied value.
    /// Valid only within the organization, project and cell below.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub environment: String,
    /// The end user's id (`sub`). Required for a connection token; it is the
    /// user shown in presence.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub user: String,
    /// The channels the holder may use. A connection token holds the grants of
    /// every channel its connection may touch; a channel token holds exactly one.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub grants: Vec<ChannelGrant>,
    /// When the token was issued.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "issueTime"
    )]
    pub issue_time: String,
    /// When the token expires. Between issue time plus 1 minute and 24 hours.
    /// The service closes a connection whose token has expired and was not
    /// refreshed.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "expireTime"
    )]
    pub expire_time: String,
    /// A unique id; the service can revoke a token by it until it expires.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "tokenId"
    )]
    pub token_id: String,
    /// The issuing Access key id (not its secret). Required: the service rechecks
    /// its freshness, expiry, revocation and token-issuing authority through the
    /// Access verifier at admission, refresh and while the connection is open.
    #[serde(
        default,
        skip_serializing_if = "crate::runtime::is_default",
        alias = "issuerKeyId"
    )]
    pub issuer_key_id: String,
    /// The authoritative Access organization id of the issuing tenant. Required.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub organization: String,
    /// The authoritative Access project id of the issuing tenant. Required.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub project: String,
    /// The authoritative Access cell id of the issuing tenant. Required.
    #[serde(default, skip_serializing_if = "crate::runtime::is_default")]
    pub cell: String,
}

/// Capability is one thing a token lets its holder do on a channel pattern.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Capability {
    /// Receive messages and read history on matching channels.
    Subscribe,
    /// Publish to matching channels. Also requires the namespace's
    /// `client_publish` to be on.
    Publish,
    /// Enter, leave, and list presence on matching channels. Also requires the
    /// namespace's `presence` to be on.
    Presence,
    /// A value this SDK version does not know.
    Unknown(String),
}

impl Capability {
    /// The wire string.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Subscribe => "subscribe",
            Self::Publish => "publish",
            Self::Presence => "presence",
            Self::Unknown(s) => s.as_str(),
        }
    }

    /// Parses a wire string; unknown values are kept.
    pub fn from_wire(s: &str) -> Self {
        match s {
            "subscribe" => Self::Subscribe,
            "publish" => Self::Publish,
            "presence" => Self::Presence,
            other => Self::Unknown(other.to_string()),
        }
    }
}

impl serde::Serialize for Capability {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_str())
    }
}

impl<'de> serde::Deserialize<'de> for Capability {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = <String as serde::Deserialize>::deserialize(d)?;
        Ok(Self::from_wire(&s))
    }
}

impl crate::runtime::QueryValue for Capability {
    fn query_value(&self) -> Option<String> {
        Some(self.as_str().to_string())
    }
}

/// HistoryPreset is how much of a channel's past a namespace keeps. Longer
/// retention is not a realtime feature: route the channel's messages to an
/// Events topic.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum HistoryPreset {
    /// Ephemeral: nothing is kept and a cursor cannot resume.
    None,
    /// The last 100 messages or 2 minutes, whichever is fewer.
    Short,
    /// The last 1,000 messages or 24 hours, whichever is fewer.
    Standard,
    /// A value this SDK version does not know.
    Unknown(String),
}

impl HistoryPreset {
    /// The wire string.
    pub fn as_str(&self) -> &str {
        match self {
            Self::None => "none",
            Self::Short => "short",
            Self::Standard => "standard",
            Self::Unknown(s) => s.as_str(),
        }
    }

    /// Parses a wire string; unknown values are kept.
    pub fn from_wire(s: &str) -> Self {
        match s {
            "none" => Self::None,
            "short" => Self::Short,
            "standard" => Self::Standard,
            other => Self::Unknown(other.to_string()),
        }
    }
}

impl serde::Serialize for HistoryPreset {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_str())
    }
}

impl<'de> serde::Deserialize<'de> for HistoryPreset {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = <String as serde::Deserialize>::deserialize(d)?;
        Ok(Self::from_wire(&s))
    }
}

impl crate::runtime::QueryValue for HistoryPreset {
    fn query_value(&self) -> Option<String> {
        Some(self.as_str().to_string())
    }
}

/// TokenKind says what a token connects.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum TokenKind {
    /// Opens a connection; its grants cover every channel the connection uses.
    Connection,
    /// Reads or publishes on one channel without a connection: the SSE stream,
    /// the long-poll and the POST publish of the fallback transport.
    Channel,
    /// A value this SDK version does not know.
    Unknown(String),
}

impl TokenKind {
    /// The wire string.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Connection => "connection",
            Self::Channel => "channel",
            Self::Unknown(s) => s.as_str(),
        }
    }

    /// Parses a wire string; unknown values are kept.
    pub fn from_wire(s: &str) -> Self {
        match s {
            "connection" => Self::Connection,
            "channel" => Self::Channel,
            other => Self::Unknown(other.to_string()),
        }
    }
}

impl serde::Serialize for TokenKind {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_str())
    }
}

impl<'de> serde::Deserialize<'de> for TokenKind {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = <String as serde::Deserialize>::deserialize(d)?;
        Ok(Self::from_wire(&s))
    }
}

impl crate::runtime::QueryValue for TokenKind {
    fn query_value(&self) -> Option<String> {
        Some(self.as_str().to_string())
    }
}

impl<T: crate::runtime::Transport> crate::runtime::Client<T> {
    /// Sylphx Realtime (`preview`).
    pub fn realtime(&self) -> RealtimeApi<'_, T> {
        RealtimeApi { client: self }
    }
}

/// ChannelService is the Channel API of Sylphx Realtime: the server side that
/// configures namespaces, publishes, reads history, lists presence, and mints
/// the tokens clients connect with. It is served by the Events service at the
/// Realtime origin, not by the Resource API, and is called with the
/// environment's secret key (`SYLPHX_API_KEY`); the key's org, project and
/// environment are the tenant. Clients connect with a token over the Sylphx
/// channel protocol v1 (`protocol.proto`).
///
/// The same calls become MCP tools. An agent cannot hold a socket, so
/// ListMessages with `wait_seconds` is its subscribe.
///
/// Namespace of Sylphx Realtime on the client.
pub struct RealtimeApi<'a, T> {
    client: &'a crate::runtime::Client<T>,
}

impl<'a, T: crate::runtime::Transport> RealtimeApi<'a, T> {
    /// The `namespaces` collection.
    pub fn namespaces(&self) -> NamespacesCollection<'a, T> {
        NamespacesCollection {
            client: self.client,
        }
    }

    /// The `channels` collection.
    pub fn channels(&self) -> ChannelsCollection<'a, T> {
        ChannelsCollection {
            client: self.client,
        }
    }

    /// The `tokens` collection.
    pub fn tokens(&self) -> TokensCollection<'a, T> {
        TokensCollection {
            client: self.client,
        }
    }

    /// The `bindings` collection.
    pub fn bindings(&self) -> BindingsCollection<'a, T> {
        BindingsCollection {
            client: self.client,
        }
    }
}

/// `namespaces` of Sylphx Realtime: served at `https://api.realtime.sylphx.com`.
pub struct NamespacesCollection<'a, T> {
    client: &'a crate::runtime::Client<T>,
}

impl<'a, T: crate::runtime::Transport> NamespacesCollection<'a, T> {
    /// Creates or replaces a namespace's rules. Existing channels follow the new
    /// rules from their next message; shortening history trims at the next
    /// publish.
    ///
    /// `PUT /v1/namespaces/{name}` · permission `realtime:write` · effect `write`
    ///
    /// Errors: `UNAUTHENTICATED`, `PERMISSION_DENIED`, `INVALID_FIELD`, `PLAN_LIMIT_REACHED`.
    pub async fn put(
        &self,
        request: PutNamespaceRequest,
    ) -> Result<Namespace, crate::runtime::Error> {
        let path = format!(
            "/v1/namespaces/{}",
            crate::runtime::protocol_param(&request.name, false, "name")?
        );
        let query = crate::runtime::Query::default();
        let http = crate::runtime::HttpRequest {
            method: "PUT",
            path,
            query: query.0,
            body: Some(crate::runtime::body_without(&request, &["name"])?),
            mutation: true,
            origin: Some("https://api.realtime.sylphx.com"),
            effect_ids: true,
        };
        self.client.call(http).await
    }

    /// Reads a namespace.
    ///
    /// `GET /v1/namespaces/{name}` · permission `realtime:read` · effect `read`
    ///
    /// Errors: `UNAUTHENTICATED`, `PERMISSION_DENIED`, `RESOURCE_NOT_FOUND`.
    pub async fn get(
        &self,
        request: GetNamespaceRequest,
    ) -> Result<Namespace, crate::runtime::Error> {
        let path = format!(
            "/v1/namespaces/{}",
            crate::runtime::protocol_param(&request.name, false, "name")?
        );
        let query = crate::runtime::Query::default();
        let http = crate::runtime::HttpRequest {
            method: "GET",
            path,
            query: query.0,
            body: None,
            mutation: false,
            origin: Some("https://api.realtime.sylphx.com"),
            effect_ids: true,
        };
        self.client.call(http).await
    }

    /// Lists the environment's namespaces.
    ///
    /// `GET /v1/namespaces` · permission `realtime:read` · effect `read`
    ///
    /// Errors: `UNAUTHENTICATED`, `PERMISSION_DENIED`, `INVALID_FIELD`.
    pub async fn list(
        &self,
        request: ListNamespacesRequest,
    ) -> Result<ListNamespacesResponse, crate::runtime::Error> {
        let path = "/v1/namespaces".to_string();
        let mut query = crate::runtime::Query::default();
        query.push("page_size", &request.page_size);
        query.push("page_token", &request.page_token);
        let http = crate::runtime::HttpRequest {
            method: "GET",
            path,
            query: query.0,
            body: None,
            mutation: false,
            origin: Some("https://api.realtime.sylphx.com"),
            effect_ids: true,
        };
        self.client.call(http).await
    }

    /// Deletes a namespace, its channels' history and presence, and closes the
    /// subscriptions on them.
    ///
    /// `DELETE /v1/namespaces/{name}` · permission `realtime:write` · effect `destructive`
    ///
    /// Errors: `UNAUTHENTICATED`, `PERMISSION_DENIED`, `RESOURCE_NOT_FOUND`.
    pub async fn delete(
        &self,
        request: DeleteNamespaceRequest,
    ) -> Result<DeleteNamespaceResponse, crate::runtime::Error> {
        let path = format!(
            "/v1/namespaces/{}",
            crate::runtime::protocol_param(&request.name, false, "name")?
        );
        let query = crate::runtime::Query::default();
        let http = crate::runtime::HttpRequest {
            method: "DELETE",
            path,
            query: query.0,
            body: None,
            mutation: true,
            origin: Some("https://api.realtime.sylphx.com"),
            effect_ids: true,
        };
        self.client.call(http).await
    }
}

/// `channels` of Sylphx Realtime: served at `https://api.realtime.sylphx.com`.
pub struct ChannelsCollection<'a, T> {
    client: &'a crate::runtime::Client<T>,
}

impl<'a, T: crate::runtime::Transport> ChannelsCollection<'a, T> {
    /// Publishes a message to a channel. The namespace must exist. The server
    /// publishes regardless of `client_publish`. A repeated Sylphx-Effect-Id
    /// publishes once.
    ///
    /// `POST /v1/channels:publish` · permission `realtime:publish` · effect `write`
    ///
    /// Errors: `UNAUTHENTICATED`, `PERMISSION_DENIED`, `INVALID_FIELD`, `RESOURCE_NOT_FOUND`.
    pub async fn publish(
        &self,
        request: PublishRequest,
    ) -> Result<PublishResponse, crate::runtime::Error> {
        let path = "/v1/channels:publish".to_string();
        let query = crate::runtime::Query::default();
        let http = crate::runtime::HttpRequest {
            method: "POST",
            path,
            query: query.0,
            body: Some(crate::runtime::body_without(&request, &[])?),
            mutation: true,
            origin: Some("https://api.realtime.sylphx.com"),
            effect_ids: true,
        };
        self.client.call(http).await
    }

    /// Lists a channel's messages after a cursor, oldest first. With
    /// `wait_seconds`, an empty result waits up to that long for the first new
    /// message and answers as soon as one arrives: this is how an agent
    /// subscribes.
    ///
    /// `GET /v1/channels/{channel}/messages` · permission `realtime:read` · effect `read`
    ///
    /// Errors: `UNAUTHENTICATED`, `PERMISSION_DENIED`, `INVALID_FIELD`, `RESOURCE_NOT_FOUND`.
    pub async fn history(
        &self,
        request: ListMessagesRequest,
    ) -> Result<ListMessagesResponse, crate::runtime::Error> {
        let path = format!(
            "/v1/channels/{}/messages",
            crate::runtime::protocol_param(&request.channel, false, "channel")?
        );
        let mut query = crate::runtime::Query::default();
        query.push("cursor", &request.cursor);
        query.push("page_size", &request.page_size);
        query.push("wait_seconds", &request.wait_seconds);
        let http = crate::runtime::HttpRequest {
            method: "GET",
            path,
            query: query.0,
            body: None,
            mutation: false,
            origin: Some("https://api.realtime.sylphx.com"),
            effect_ids: true,
        };
        self.client.call(http).await
    }

    /// Lists who is present on a channel.
    ///
    /// `GET /v1/channels/{channel}/presence` · permission `realtime:read` · effect `read`
    ///
    /// Errors: `UNAUTHENTICATED`, `PERMISSION_DENIED`, `INVALID_FIELD`, `RESOURCE_NOT_FOUND`.
    pub async fn presence(
        &self,
        request: ListPresenceRequest,
    ) -> Result<ListPresenceResponse, crate::runtime::Error> {
        let path = format!(
            "/v1/channels/{}/presence",
            crate::runtime::protocol_param(&request.channel, false, "channel")?
        );
        let mut query = crate::runtime::Query::default();
        query.push("page_size", &request.page_size);
        query.push("page_token", &request.page_token);
        let http = crate::runtime::HttpRequest {
            method: "GET",
            path,
            query: query.0,
            body: None,
            mutation: false,
            origin: Some("https://api.realtime.sylphx.com"),
            effect_ids: true,
        };
        self.client.call(http).await
    }
}

/// `tokens` of Sylphx Realtime: served at `https://api.realtime.sylphx.com`.
pub struct TokensCollection<'a, T> {
    client: &'a crate::runtime::Client<T>,
}

impl<'a, T: crate::runtime::Transport> TokensCollection<'a, T> {
    /// Mints a connection or channel token for an end user. The customer's
    /// server calls it with the secret key after authenticating the user, and
    /// hands the token to the client.
    ///
    /// `POST /v1/tokens:issue` · permission `realtime:token` · effect `write`
    ///
    /// Errors: `UNAUTHENTICATED`, `PERMISSION_DENIED`, `INVALID_FIELD`.
    pub async fn issue(
        &self,
        request: IssueTokenRequest,
    ) -> Result<IssueTokenResponse, crate::runtime::Error> {
        let path = "/v1/tokens:issue".to_string();
        let query = crate::runtime::Query::default();
        let http = crate::runtime::HttpRequest {
            method: "POST",
            path,
            query: query.0,
            body: Some(crate::runtime::body_without(&request, &[])?),
            mutation: true,
            origin: Some("https://api.realtime.sylphx.com"),
            effect_ids: true,
        };
        self.client.call(http).await
    }
}

/// `bindings` of Sylphx Realtime: served at `https://api.realtime.sylphx.com`.
pub struct BindingsCollection<'a, T> {
    client: &'a crate::runtime::Client<T>,
}

impl<'a, T: crate::runtime::Transport> BindingsCollection<'a, T> {
    /// Binds a bus Subscription's matching events to a channel: each event the
    /// Subscription matches is published to the channel, with the event's
    /// CloudEvents `type` as the message event and its `data` as the payload. The
    /// Subscription itself is an Events Resource (`sylphx.events.v1`); this call
    /// only names the channel it feeds, and replaces the Subscription's earlier
    /// binding.
    ///
    /// `POST /v1/subscription-bindings` · permission `realtime:write` · effect `write`
    ///
    /// Errors: `UNAUTHENTICATED`, `PERMISSION_DENIED`, `INVALID_FIELD`, `RESOURCE_NOT_FOUND`.
    pub async fn create(
        &self,
        request: BindSubscriptionRequest,
    ) -> Result<BindSubscriptionResponse, crate::runtime::Error> {
        let path = "/v1/subscription-bindings".to_string();
        let query = crate::runtime::Query::default();
        let http = crate::runtime::HttpRequest {
            method: "POST",
            path,
            query: query.0,
            body: Some(crate::runtime::body_without(&request, &[])?),
            mutation: true,
            origin: Some("https://api.realtime.sylphx.com"),
            effect_ids: true,
        };
        self.client.call(http).await
    }
}