forked from tinode/chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datamodel.go
1636 lines (1465 loc) · 49.2 KB
/
datamodel.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
/******************************************************************************
*
* Description :
*
* Wire protocol structures
*
*****************************************************************************/
import (
"encoding/json"
"net/http"
"strconv"
"strings"
"time"
"github.com/tinode/chat/server/store/types"
)
// MsgGetOpts defines Get query parameters.
type MsgGetOpts struct {
// Optional User ID to return result(s) for one user.
User string `json:"user,omitempty"`
// Optional topic name to return result(s) for one topic.
Topic string `json:"topic,omitempty"`
// Return results modified since this timespamp.
IfModifiedSince *time.Time `json:"ims,omitempty"`
// Load messages/ranges with IDs equal or greater than this (inclusive or closed)
SinceId int `json:"since,omitempty"`
// Load messages/ranges with IDs lower than this (exclusive or open)
BeforeId int `json:"before,omitempty"`
// Limit the number of messages loaded
Limit int `json:"limit,omitempty"`
}
// MsgGetQuery is a topic metadata or data query.
type MsgGetQuery struct {
What string `json:"what"`
// Parameters of "desc" request: IfModifiedSince
Desc *MsgGetOpts `json:"desc,omitempty"`
// Parameters of "sub" request: User, Topic, IfModifiedSince, Limit.
Sub *MsgGetOpts `json:"sub,omitempty"`
// Parameters of "data" request: Since, Before, Limit.
Data *MsgGetOpts `json:"data,omitempty"`
// Parameters of "del" request: Since, Before, Limit.
Del *MsgGetOpts `json:"del,omitempty"`
}
// MsgSetSub is a payload in set.sub request to update current subscription or invite another user, {sub.what} == "sub".
type MsgSetSub struct {
// User affected by this request. Default (empty): current user
User string `json:"user,omitempty"`
// Access mode change, either Given or Want depending on context
Mode string `json:"mode,omitempty"`
}
// MsgSetDesc is a C2S in set.what == "desc", acc, sub message.
type MsgSetDesc struct {
DefaultAcs *MsgDefaultAcsMode `json:"defacs,omitempty"` // default access mode
Public interface{} `json:"public,omitempty"`
Private interface{} `json:"private,omitempty"` // Per-subscription private data
}
// MsgCredClient is an account credential such as email or phone number.
type MsgCredClient struct {
// Credential type, i.e. `email` or `tel`.
Method string `json:"meth,omitempty"`
// Value to verify, i.e. `user@example.com` or `+18003287448`
Value string `json:"val,omitempty"`
// Verification response
Response string `json:"resp,omitempty"`
// Request parameters, such as preferences. Passed to valiator without interpretation.
Params map[string]interface{} `json:"params,omitempty"`
}
// MsgSetQuery is an update to topic metadata: Desc, subscriptions, or tags.
type MsgSetQuery struct {
// Topic metadata, new topic & new subscriptions only
Desc *MsgSetDesc `json:"desc,omitempty"`
// Subscription parameters
Sub *MsgSetSub `json:"sub,omitempty"`
// Indexable tags for user discovery
Tags []string `json:"tags,omitempty"`
// Update to account credentials.
Cred *MsgCredClient `json:"cred,omitempty"`
}
// MsgDelRange is either an individual ID (HiId=0) or a randge of deleted IDs, low end inclusive (closed),
// high-end exclusive (open): [LowId .. HiId), e.g. 1..5 -> 1, 2, 3, 4.
type MsgDelRange struct {
LowId int `json:"low,omitempty"`
HiId int `json:"hi,omitempty"`
}
/****************************************************************
* Client to Server (C2S) messages.
****************************************************************/
// MsgClientHi is a handshake {hi} message.
type MsgClientHi struct {
// Message Id
Id string `json:"id,omitempty"`
// User agent
UserAgent string `json:"ua,omitempty"`
// Protocol version, i.e. "0.13"
Version string `json:"ver,omitempty"`
// Client's unique device ID
DeviceID string `json:"dev,omitempty"`
// ISO 639-1 human language of the connected device
Lang string `json:"lang,omitempty"`
// Platform code: ios, android, web.
Platform string `json:"platf,omitempty"`
// Session is initially in non-iteractive, i.e. issued by a service. Presence notifications are delayed.
Background bool `json:"bkg,omitempty"`
}
// MsgClientAcc is an {acc} message for creating or updating a user account.
type MsgClientAcc struct {
// Message Id
Id string `json:"id,omitempty"`
// "newXYZ" to create a new user or UserId to update a user; default: current user.
User string `json:"user,omitempty"`
// Account state: normal, suspended.
State string `json:"status,omitempty"`
// Authentication level of the user when UserID is set and not equal to the current user.
// Either "", "auth" or "anon". Default: ""
AuthLevel string
// Authentication token for resetting the password and maybe other one-time actions.
Token []byte `json:"token,omitempty"`
// The initial authentication scheme the account can use
Scheme string `json:"scheme,omitempty"`
// Shared secret
Secret []byte `json:"secret,omitempty"`
// Authenticate session with the newly created account
Login bool `json:"login,omitempty"`
// Indexable tags for user discovery
Tags []string `json:"tags,omitempty"`
// User initialization data when creating a new user, otherwise ignored
Desc *MsgSetDesc `json:"desc,omitempty"`
// Credentials to verify (email or phone or captcha)
Cred []MsgCredClient `json:"cred,omitempty"`
}
// MsgClientLogin is a login {login} message.
type MsgClientLogin struct {
// Message Id
Id string `json:"id,omitempty"`
// Authentication scheme
Scheme string `json:"scheme,omitempty"`
// Shared secret
Secret []byte `json:"secret"`
// Credntials being verified (email or phone or captcha etc.)
Cred []MsgCredClient `json:"cred,omitempty"`
}
// MsgClientSub is a subscription request {sub} message.
type MsgClientSub struct {
Id string `json:"id,omitempty"`
Topic string `json:"topic"`
// Mirrors {set}.
Set *MsgSetQuery `json:"set,omitempty"`
// Mirrors {get}.
Get *MsgGetQuery `json:"get,omitempty"`
// Intra-cluster fields.
// True if this subscription created a new topic.
// In case of p2p topics, it's true if the other user's subscription was
// created (as a part of new topic creation or just alone).
Created bool `json:"-"`
// True if this is a new subscription.
Newsub bool `json:"-"`
}
const (
constMsgMetaDesc = 1 << iota
constMsgMetaSub
constMsgMetaData
constMsgMetaTags
constMsgMetaDel
constMsgMetaCred
)
const (
constMsgDelTopic = iota + 1
constMsgDelMsg
constMsgDelSub
constMsgDelUser
constMsgDelCred
)
func parseMsgClientMeta(params string) int {
var bits int
parts := strings.SplitN(params, " ", 8)
for _, p := range parts {
switch p {
case "desc":
bits |= constMsgMetaDesc
case "sub":
bits |= constMsgMetaSub
case "data":
bits |= constMsgMetaData
case "tags":
bits |= constMsgMetaTags
case "del":
bits |= constMsgMetaDel
case "cred":
bits |= constMsgMetaCred
default:
// ignore unknown
}
}
return bits
}
func parseMsgClientDel(params string) int {
switch params {
case "", "msg":
return constMsgDelMsg
case "topic":
return constMsgDelTopic
case "sub":
return constMsgDelSub
case "user":
return constMsgDelUser
case "cred":
return constMsgDelCred
default:
// ignore
}
return 0
}
// MsgDefaultAcsMode is a topic default access mode.
type MsgDefaultAcsMode struct {
Auth string `json:"auth,omitempty"`
Anon string `json:"anon,omitempty"`
}
// MsgClientLeave is an unsubscribe {leave} request message.
type MsgClientLeave struct {
Id string `json:"id,omitempty"`
Topic string `json:"topic"`
Unsub bool `json:"unsub,omitempty"`
}
// MsgClientPub is client's request to publish data to topic subscribers {pub}.
type MsgClientPub struct {
Id string `json:"id,omitempty"`
Topic string `json:"topic"`
NoEcho bool `json:"noecho,omitempty"`
Head map[string]interface{} `json:"head,omitempty"`
Content interface{} `json:"content"`
}
// MsgClientGet is a query of topic state {get}.
type MsgClientGet struct {
Id string `json:"id,omitempty"`
Topic string `json:"topic"`
MsgGetQuery
}
// MsgClientSet is an update of topic state {set}.
type MsgClientSet struct {
Id string `json:"id,omitempty"`
Topic string `json:"topic"`
MsgSetQuery
}
// MsgClientDel delete messages or topic {del}.
type MsgClientDel struct {
Id string `json:"id,omitempty"`
Topic string `json:"topic,omitempty"`
// What to delete:
// * "msg" to delete messages (default)
// * "topic" to delete the topic
// * "sub" to delete a subscription to topic.
// * "user" to delete or disable user.
// * "cred" to delete credential (email or phone)
What string `json:"what"`
// Delete messages with these IDs (either one by one or a set of ranges)
DelSeq []MsgDelRange `json:"delseq,omitempty"`
// User ID of the user or subscription to delete
User string `json:"user,omitempty"`
// Credential to delete
Cred *MsgCredClient `json:"cred,omitempty"`
// Request to hard-delete objects (i.e. delete messages for all users), if such option is available.
Hard bool `json:"hard,omitempty"`
}
// MsgClientNote is a client-generated notification for topic subscribers {note}.
type MsgClientNote struct {
// There is no Id -- server will not akn {ping} packets, they are "fire and forget"
Topic string `json:"topic"`
// what is being reported: "recv" - message received, "read" - message read, "kp" - typing notification
What string `json:"what"`
// Server-issued message ID being reported
SeqId int `json:"seq,omitempty"`
// Client's count of unread messages to report back to the server. Used in push notifications on iOS.
Unread int `json:"unread,omitempty"`
}
// ClientComMessage is a wrapper for client messages.
type ClientComMessage struct {
Hi *MsgClientHi `json:"hi"`
Acc *MsgClientAcc `json:"acc"`
Login *MsgClientLogin `json:"login"`
Sub *MsgClientSub `json:"sub"`
Leave *MsgClientLeave `json:"leave"`
Pub *MsgClientPub `json:"pub"`
Get *MsgClientGet `json:"get"`
Set *MsgClientSet `json:"set"`
Del *MsgClientDel `json:"del"`
Note *MsgClientNote `json:"note"`
// Internal fields, routed only within the cluster.
// Message ID denormalized
Id string `json:"-"`
// Un-routable (original) topic name denormalized from XXX.Topic.
Original string `json:"-"`
// Routable (expanded) topic name.
RcptTo string `json:"-"`
// Sender's UserId as string.
AsUser string `json:"-"`
// Sender's authentication level.
AuthLvl int `json:"-"`
// Denormalized 'what' field of meta messages (set, get, del).
MetaWhat int `json:"-"`
// Timestamp when this message was received by the server.
Timestamp time.Time `json:"-"`
}
/****************************************************************
* Server to client messages.
****************************************************************/
// MsgLastSeenInfo contains info on user's appearance online - when & user agent.
type MsgLastSeenInfo struct {
// Timestamp of user's last appearance online.
When *time.Time `json:"when,omitempty"`
// User agent of the device when the user was last online.
UserAgent string `json:"ua,omitempty"`
}
func (src *MsgLastSeenInfo) describe() string {
return "'" + src.UserAgent + "' @ " + src.When.String()
}
// MsgCredServer is an account credential such as email or phone number.
type MsgCredServer struct {
// Credential type, i.e. `email` or `tel`.
Method string `json:"meth,omitempty"`
// Credential value, i.e. `user@example.com` or `+18003287448`
Value string `json:"val,omitempty"`
// Indicates that the credential is validated.
Done bool `json:"done,omitempty"`
}
// MsgAccessMode is a definition of access mode.
type MsgAccessMode struct {
// Access mode requested by the user
Want string `json:"want,omitempty"`
// Access mode granted to the user by the admin
Given string `json:"given,omitempty"`
// Cumulative access mode want & given
Mode string `json:"mode,omitempty"`
}
func (src *MsgAccessMode) describe() string {
var s string
if src.Want != "" {
s = "w=" + src.Want
}
if src.Given != "" {
s += " g=" + src.Given
}
if src.Mode != "" {
s += " m=" + src.Mode
}
return strings.TrimSpace(s)
}
// MsgTopicDesc is a topic description, S2C in Meta message.
type MsgTopicDesc struct {
CreatedAt *time.Time `json:"created,omitempty"`
UpdatedAt *time.Time `json:"updated,omitempty"`
// Timestamp of the last message
TouchedAt *time.Time `json:"touched,omitempty"`
// Account state, 'me' topic only.
State string `json:"state,omitempty"`
// If the group topic is online.
Online bool `json:"online,omitempty"`
// P2P other user's last online timestamp & user agent
LastSeen *MsgLastSeenInfo `json:"seen,omitempty"`
DefaultAcs *MsgDefaultAcsMode `json:"defacs,omitempty"`
// Actual access mode
Acs *MsgAccessMode `json:"acs,omitempty"`
// Max message ID
SeqId int `json:"seq,omitempty"`
ReadSeqId int `json:"read,omitempty"`
RecvSeqId int `json:"recv,omitempty"`
// Id of the last delete operation as seen by the requesting user
DelId int `json:"clear,omitempty"`
Public interface{} `json:"public,omitempty"`
// Per-subscription private data
Private interface{} `json:"private,omitempty"`
}
func (src *MsgTopicDesc) describe() string {
var s string
if src.State != "" {
s = " state=" + src.State
}
s += " online=" + strconv.FormatBool(src.Online)
if src.Acs != nil {
s += " acs={" + src.Acs.describe() + "}"
}
if src.SeqId != 0 {
s += " seq=" + strconv.Itoa(src.SeqId)
}
if src.ReadSeqId != 0 {
s += " read=" + strconv.Itoa(src.ReadSeqId)
}
if src.RecvSeqId != 0 {
s += " recv=" + strconv.Itoa(src.RecvSeqId)
}
if src.DelId != 0 {
s += " clear=" + strconv.Itoa(src.DelId)
}
if src.Public != nil {
s += " pub='...'"
}
if src.Private != nil {
s += " priv='...'"
}
return s
}
// MsgTopicSub is topic subscription details, sent in Meta message.
type MsgTopicSub struct {
// Fields common to all subscriptions
// Timestamp when the subscription was last updated
UpdatedAt *time.Time `json:"updated,omitempty"`
// Timestamp when the subscription was deleted
DeletedAt *time.Time `json:"deleted,omitempty"`
// If the subscriber/topic is online
Online bool `json:"online,omitempty"`
// Access mode. Topic admins receive the full info, non-admins receive just the cumulative mode
// Acs.Mode = want & given. The field is not a pointer because at least one value is always assigned.
Acs MsgAccessMode `json:"acs,omitempty"`
// ID of the message reported by the given user as read
ReadSeqId int `json:"read,omitempty"`
// ID of the message reported by the given user as received
RecvSeqId int `json:"recv,omitempty"`
// Topic's public data
Public interface{} `json:"public,omitempty"`
// User's own private data per topic
Private interface{} `json:"private,omitempty"`
// Response to non-'me' topic
// Uid of the subscribed user
User string `json:"user,omitempty"`
// The following sections makes sense only in context of getting
// user's own subscriptions ('me' topic response)
// Topic name of this subscription
Topic string `json:"topic,omitempty"`
// Timestamp of the last message in the topic.
TouchedAt *time.Time `json:"touched,omitempty"`
// ID of the last {data} message in a topic
SeqId int `json:"seq,omitempty"`
// Id of the latest Delete operation
DelId int `json:"clear,omitempty"`
// P2P topics in 'me' {get subs} response:
// Other user's last online timestamp & user agent
LastSeen *MsgLastSeenInfo `json:"seen,omitempty"`
}
func (src *MsgTopicSub) describe() string {
s := src.Topic + ":" + src.User + " online=" + strconv.FormatBool(src.Online) + " acs=" + src.Acs.describe()
if src.SeqId != 0 {
s += " seq=" + strconv.Itoa(src.SeqId)
}
if src.ReadSeqId != 0 {
s += " read=" + strconv.Itoa(src.ReadSeqId)
}
if src.RecvSeqId != 0 {
s += " recv=" + strconv.Itoa(src.RecvSeqId)
}
if src.DelId != 0 {
s += " clear=" + strconv.Itoa(src.DelId)
}
if src.Public != nil {
s += " pub='...'"
}
if src.Private != nil {
s += " priv='...'"
}
if src.LastSeen != nil {
s += " seen={" + src.LastSeen.describe() + "}"
}
return s
}
// MsgDelValues describes request to delete messages.
type MsgDelValues struct {
DelId int `json:"clear,omitempty"`
DelSeq []MsgDelRange `json:"delseq,omitempty"`
}
// MsgServerCtrl is a server control message {ctrl}.
type MsgServerCtrl struct {
Id string `json:"id,omitempty"`
Topic string `json:"topic,omitempty"`
Params interface{} `json:"params,omitempty"`
Code int `json:"code"`
Text string `json:"text,omitempty"`
Timestamp time.Time `json:"ts"`
}
// Deep-shallow copy.
func (src *MsgServerCtrl) copy() *MsgServerCtrl {
if src == nil {
return nil
}
dst := *src
return &dst
}
func (src *MsgServerCtrl) describe() string {
return src.Topic + " id=" + src.Id + " code=" + strconv.Itoa(src.Code) + " txt=" + src.Text
}
// MsgServerData is a server {data} message.
type MsgServerData struct {
Topic string `json:"topic"`
// ID of the user who originated the message as {pub}, could be empty if sent by the system
From string `json:"from,omitempty"`
Timestamp time.Time `json:"ts"`
DeletedAt *time.Time `json:"deleted,omitempty"`
SeqId int `json:"seq"`
Head map[string]interface{} `json:"head,omitempty"`
Content interface{} `json:"content"`
}
// Deep-shallow copy.
func (src *MsgServerData) copy() *MsgServerData {
if src == nil {
return nil
}
dst := *src
return &dst
}
func (src *MsgServerData) describe() string {
s := src.Topic + " from=" + src.From + " seq=" + strconv.Itoa(src.SeqId)
if src.DeletedAt != nil {
s += " deleted"
} else {
if src.Head != nil {
s += " head=..."
}
s += " content='...'"
}
return s
}
// MsgServerPres is presence notification {pres} (authoritative update).
type MsgServerPres struct {
Topic string `json:"topic"`
Src string `json:"src,omitempty"`
What string `json:"what"`
UserAgent string `json:"ua,omitempty"`
SeqId int `json:"seq,omitempty"`
DelId int `json:"clear,omitempty"`
DelSeq []MsgDelRange `json:"delseq,omitempty"`
AcsTarget string `json:"tgt,omitempty"`
AcsActor string `json:"act,omitempty"`
// Acs or a delta Acs. Need to marshal it to json under a name different than 'acs'
// to allow different handling on the client
Acs *MsgAccessMode `json:"dacs,omitempty"`
// UNroutable params. All marked with `json:"-"` to exclude from json marshaling.
// They are still serialized for intra-cluster communication.
// Flag to break the reply loop
WantReply bool `json:"-"`
// Additional access mode filters when sending to topic's online members. Both filter conditions must be true.
// send only to those who have this access mode.
FilterIn int `json:"-"`
// skip those who have this access mode.
FilterOut int `json:"-"`
// When sending to 'me', skip sessions subscribed to this topic.
SkipTopic string `json:"-"`
// Send to sessions of a single user only.
SingleUser string `json:"-"`
// Exclude sessions of a single user.
ExcludeUser string `json:"-"`
}
// Deep-shallow copy.
func (src *MsgServerPres) copy() *MsgServerPres {
if src == nil {
return nil
}
dst := *src
return &dst
}
func (src *MsgServerPres) describe() string {
s := src.Topic
if src.Src != "" {
s += " src=" + src.Src
}
if src.What != "" {
s += " what=" + src.What
}
if src.UserAgent != "" {
s += " ua=" + src.UserAgent
}
if src.SeqId != 0 {
s += " seq=" + strconv.Itoa(src.SeqId)
}
if src.DelId != 0 {
s += " clear=" + strconv.Itoa(src.DelId)
}
if src.DelSeq != nil {
s += " delseq"
}
if src.AcsTarget != "" {
s += " tgt=" + src.AcsTarget
}
if src.AcsActor != "" {
s += " actor=" + src.AcsActor
}
if src.Acs != nil {
s += " dacs=" + src.Acs.describe()
}
return s
}
// MsgServerMeta is a topic metadata {meta} update.
type MsgServerMeta struct {
Id string `json:"id,omitempty"`
Topic string `json:"topic"`
Timestamp *time.Time `json:"ts,omitempty"`
// Topic description
Desc *MsgTopicDesc `json:"desc,omitempty"`
// Subscriptions as an array of objects
Sub []MsgTopicSub `json:"sub,omitempty"`
// Delete ID and the ranges of IDs of deleted messages
Del *MsgDelValues `json:"del,omitempty"`
// User discovery tags
Tags []string `json:"tags,omitempty"`
// Account credentials, 'me' only.
Cred []*MsgCredServer `json:"cred,omitempty"`
}
// Deep-shallow copy of meta message. Deep copy of Id and Topic fields, shallow copy of payload.
func (src *MsgServerMeta) copy() *MsgServerMeta {
if src == nil {
return nil
}
dst := *src
return &dst
}
func (src *MsgServerMeta) describe() string {
s := src.Topic + " id=" + src.Id
if src.Desc != nil {
s += " desc={" + src.Desc.describe() + "}"
}
if src.Sub != nil {
var x []string
for _, sub := range src.Sub {
x = append(x, sub.describe())
}
s += " sub=[{" + strings.Join(x, "},{") + "}]"
}
if src.Del != nil {
x, _ := json.Marshal(src.Del)
s += " del={" + string(x) + "}"
}
if src.Tags != nil {
s += " tags=[" + strings.Join(src.Tags, ",") + "]"
}
if src.Cred != nil {
x, _ := json.Marshal(src.Cred)
s += " cred=[" + string(x) + "]"
}
return s
}
// MsgServerInfo is the server-side copy of MsgClientNote with From and optionally Src added (non-authoritative).
type MsgServerInfo struct {
// Topic to send event to.
Topic string `json:"topic"`
// Topic where the even has occurred (set only when Topic='me').
Src string `json:"src,omitempty"`
// ID of the user who originated the message.
From string `json:"from"`
// The event being reported: "rcpt" - message received, "read" - message read, "kp" - typing notification.
What string `json:"what"`
// Server-issued message ID being reported.
SeqId int `json:"seq,omitempty"`
// UNroutable params. All marked with `json:"-"` to exclude from json marshaling.
// They are still serialized for intra-cluster communication.
// When sending to 'me', skip sessions subscribed to this topic.
SkipTopic string `json:"-"`
}
// Deep copy.
func (src *MsgServerInfo) copy() *MsgServerInfo {
if src == nil {
return nil
}
dst := *src
return &dst
}
// Basic description.
func (src *MsgServerInfo) describe() string {
s := src.Topic
if src.Src != "" {
s += " src=" + src.Src
}
s += " what=" + src.What + " from=" + src.From
if src.SeqId > 0 {
s += " seq=" + strconv.Itoa(src.SeqId)
}
return s
}
// ServerComMessage is a wrapper for server-side messages.
type ServerComMessage struct {
Ctrl *MsgServerCtrl `json:"ctrl,omitempty"`
Data *MsgServerData `json:"data,omitempty"`
Meta *MsgServerMeta `json:"meta,omitempty"`
Pres *MsgServerPres `json:"pres,omitempty"`
Info *MsgServerInfo `json:"info,omitempty"`
// Internal fields.
// MsgServerData has no Id field, copying it here for use in {ctrl} aknowledgements
Id string `json:"-"`
// Routable (expanded) name of the topic.
RcptTo string `json:"-"`
// User ID of the sender of the original message.
AsUser string `json:"-"`
// Timestamp for consistency of timestamps in {ctrl} messages
// (corresponds to originating client message receipt timestamp).
Timestamp time.Time `json:"-"`
// Originating session to send an aknowledgement to. Could be nil.
sess *Session
// Session ID to skip when sendng packet to sessions. Used to skip sending to original session.
// Could be either empty.
SkipSid string `json:"-"`
// User id affected by this message.
uid types.Uid
}
// Deep-shallow copy of ServerComMessage. Deep copy of service fields,
// shallow copy of session and payload.
func (src *ServerComMessage) copy() *ServerComMessage {
if src == nil {
return nil
}
dst := &ServerComMessage{
Id: src.Id,
RcptTo: src.RcptTo,
AsUser: src.AsUser,
Timestamp: src.Timestamp,
sess: src.sess,
SkipSid: src.SkipSid,
uid: src.uid,
}
dst.Ctrl = src.Ctrl.copy()
dst.Data = src.Data.copy()
dst.Meta = src.Meta.copy()
dst.Pres = src.Pres.copy()
dst.Info = src.Info.copy()
return dst
}
func (src *ServerComMessage) describe() string {
if src == nil {
return "-"
}
switch {
case src.Ctrl != nil:
return "{ctrl " + src.Ctrl.describe() + "}"
case src.Data != nil:
return "{data " + src.Data.describe() + "}"
case src.Meta != nil:
return "{meta " + src.Meta.describe() + "}"
case src.Pres != nil:
return "{pres " + src.Pres.describe() + "}"
case src.Info != nil:
return "{info " + src.Info.describe() + "}"
default:
return "{nil}"
}
}
// Generators of server-side error messages {ctrl}.
// NoErr indicates successful completion (200).
func NoErr(id, topic string, ts time.Time) *ServerComMessage {
return NoErrParams(id, topic, ts, nil)
}
// NoErrExplicitTs indicates successful completion with explicit server and incoming request timestamps (200).
func NoErrExplicitTs(id, topic string, serverTs, incomingReqTs time.Time) *ServerComMessage {
return NoErrParamsExplicitTs(id, topic, serverTs, incomingReqTs, nil)
}
// NoErrReply indicates successful completion as a reply to a client message (200).
func NoErrReply(msg *ClientComMessage, ts time.Time) *ServerComMessage {
return NoErrExplicitTs(msg.Id, msg.Original, ts, msg.Timestamp)
}
// NoErrParams indicates successful completion with additional parameters (200).
func NoErrParams(id, topic string, ts time.Time, params interface{}) *ServerComMessage {
return NoErrParamsExplicitTs(id, topic, ts, ts, params)
}
// NoErrParamsExplicitTs indicates successful completion with additional parameters
// and explicit server and incoming request timestamps (200).
func NoErrParamsExplicitTs(id, topic string, serverTs, incomingReqTs time.Time, params interface{}) *ServerComMessage {
return &ServerComMessage{
Ctrl: &MsgServerCtrl{
Id: id,
Code: http.StatusOK, // 200
Text: "ok",
Topic: topic,
Params: params,
Timestamp: serverTs,
},
Id: id,
Timestamp: incomingReqTs,
}
}
// NoErrParamsReply indicates successful completion with additional parameters
// and explicit server and incoming request timestamps (200).
func NoErrParamsReply(msg *ClientComMessage, ts time.Time, params interface{}) *ServerComMessage {
return NoErrParamsExplicitTs(msg.Id, msg.Original, ts, msg.Timestamp, params)
}
// NoErrCreated indicated successful creation of an object (201).
func NoErrCreated(id, topic string, ts time.Time) *ServerComMessage {
return &ServerComMessage{
Ctrl: &MsgServerCtrl{
Id: id,
Code: http.StatusCreated, // 201
Text: "created",
Topic: topic,
Timestamp: ts,
},
Id: id,
Timestamp: ts,
}
}
// NoErrAccepted indicates request was accepted but not perocessed yet (202).
func NoErrAccepted(id, topic string, ts time.Time) *ServerComMessage {
return NoErrAcceptedExplicitTs(id, topic, ts, ts)
}
// NoErrAcceptedExplicitTs indicates request was accepted but not perocessed yet
// with explicit server and incoming request timestamps (202).
func NoErrAcceptedExplicitTs(id, topic string, serverTs, incomingReqTs time.Time) *ServerComMessage {
return &ServerComMessage{
Ctrl: &MsgServerCtrl{
Id: id,
Code: http.StatusAccepted, // 202
Text: "accepted",
Topic: topic,
Timestamp: serverTs,
}, Id: id,
Timestamp: incomingReqTs,
}
}
// NoContentParams indicates request was processed but resulted in no content (204).
func NoContentParams(id, topic string, serverTs, incomingReqTs time.Time, params interface{}) *ServerComMessage {
return &ServerComMessage{
Ctrl: &MsgServerCtrl{
Id: id,
Code: http.StatusNoContent, // 204
Text: "no content",
Topic: topic,
Params: params,
Timestamp: serverTs,
},
Id: id,
Timestamp: incomingReqTs,
}
}
// NoContentParamsReply indicates request was processed but resulted in no content
// in response to a client request (204).
func NoContentParamsReply(msg *ClientComMessage, ts time.Time, params interface{}) *ServerComMessage {
return NoContentParams(msg.Id, msg.Original, ts, msg.Timestamp, params)
}
// NoErrEvicted indicates that the user was disconnected from topic for no fault of the user (205).
func NoErrEvicted(id, topic string, ts time.Time) *ServerComMessage {
return &ServerComMessage{
Ctrl: &MsgServerCtrl{
Id: id,
Code: http.StatusResetContent, // 205
Text: "evicted",
Topic: topic,
Timestamp: ts,
}, Id: id,
}
}
// NoErrShutdown means user was disconnected from topic because system shutdown is in progress (205).
func NoErrShutdown(ts time.Time) *ServerComMessage {
return &ServerComMessage{
Ctrl: &MsgServerCtrl{
Code: http.StatusResetContent, // 205
Text: "server shutdown",
Timestamp: ts,
},
}
}
// NoErrDeliveredParams means requested content has been delivered (208).
func NoErrDeliveredParams(id, topic string, ts time.Time, params interface{}) *ServerComMessage {
return &ServerComMessage{
Ctrl: &MsgServerCtrl{
Id: id,
Code: http.StatusAlreadyReported, // 208
Text: "delivered",
Topic: topic,
Params: params,
Timestamp: ts,
},
Id: id,
}
}
// 3xx
// InfoValidateCredentials requires user to confirm credentials before going forward (300).
func InfoValidateCredentials(id string, ts time.Time) *ServerComMessage {
return InfoValidateCredentialsExplicitTs(id, ts, ts)
}
// InfoValidateCredentialsExplicitTs requires user to confirm credentials before going forward
// with explicit server and incoming request timestamps (300).
func InfoValidateCredentialsExplicitTs(id string, serverTs, incomingReqTs time.Time) *ServerComMessage {
return &ServerComMessage{
Ctrl: &MsgServerCtrl{
Id: id,
Code: http.StatusMultipleChoices, // 300
Text: "validate credentials",
Timestamp: serverTs,
},
Id: id,
Timestamp: incomingReqTs,
}
}
// InfoChallenge requires user to respond to presented challenge before login can be completed (300).