fiberplane-models 1.0.0-beta.14

Core models used across Fiberplane
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
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
use crate::comments::{Thread, ThreadItem, UserSummary};
use crate::events::Event;
use crate::labels::LabelValidationError;
use crate::notebooks::front_matter::FrontMatterValidationError;
use crate::notebooks::operations::Operation;
use crate::timestamps::Timestamp;
use base64uuid::Base64Uuid;
#[cfg(feature = "fp-bindgen")]
use fp_bindgen::prelude::*;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::fmt::Debug;
use typed_builder::TypedBuilder;

/// Real-time message sent by the client over a WebSocket connection.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ClientRealtimeMessage {
    /// Authenticate this client
    Authenticate(AuthenticateMessage),

    /// Subscribe to changes from a specific Notebook.
    Subscribe(SubscribeMessage),

    /// Unsubscribe to changes from a specific Notebook.
    Unsubscribe(UnsubscribeMessage),

    /// Apply an operation to a specific Notebook.
    ApplyOperation(Box<ApplyOperationMessage>),

    /// Apply multiple operations to a specific Notebook.
    ApplyOperationBatch(Box<ApplyOperationBatchMessage>),

    /// Request a DebugResponse from the server.
    DebugRequest(DebugRequestMessage),

    FocusInfo(FocusInfoMessage),

    /// User started typing a comment.
    UserTypingComment(UserTypingCommentClientMessage),

    /// Subscribe to workspace activities
    SubscribeWorkspace(SubscribeWorkspaceMessage),

    /// Unsubscribe from workspace activities
    UnsubscribeWorkspace(UnsubscribeWorkspaceMessage),
}

impl ClientRealtimeMessage {
    pub fn op_id(&self) -> &Option<String> {
        use ClientRealtimeMessage::*;
        match self {
            Authenticate(msg) => &msg.op_id,
            Subscribe(msg) => &msg.op_id,
            Unsubscribe(msg) => &msg.op_id,
            ApplyOperation(msg) => &msg.op_id,
            ApplyOperationBatch(msg) => &msg.op_id,
            DebugRequest(msg) => &msg.op_id,
            FocusInfo(msg) => &msg.op_id,
            UserTypingComment(msg) => &msg.op_id,
            SubscribeWorkspace(msg) => &msg.op_id,
            UnsubscribeWorkspace(msg) => &msg.op_id,
        }
    }
}

/// Real-time message sent by the server over a WebSocket connection.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ServerRealtimeMessage {
    /// Apply an operation to a specific Notebook.
    ApplyOperation(Box<ApplyOperationMessage>),

    /// An Ack message will be sent once an operation is received and processed.
    /// No Ack message will sent if the op_id of the original message was empty.
    Ack(AckMessage),

    /// An Err message will be sent once an operation is received, but could not
    /// be processed. It includes the op_id if that was present.
    Err(ErrMessage),

    /// Response from a DebugRequest. Contains some useful data regarding the
    /// connection.
    DebugResponse(DebugResponseMessage),

    /// New event was added to the workspace
    EventAdded(EventAddedMessage),

    /// Event was updated in the workspace
    EventUpdated(EventUpdatedMessage),

    /// Event was deleted from the workspace
    EventDeleted(EventDeletedMessage),

    /// Notifies a mentioned user of the fact they've been mentioned by someone
    /// else.
    Mention(MentionMessage),

    /// An apply operation got rejected by the server, see message for the
    /// reason.
    Rejected(RejectedMessage),

    /// A user has joined as a subscriber to a notebook.
    SubscriberAdded(SubscriberAddedMessage),

    /// A previously subscribed user has left a notebook.
    SubscriberRemoved(SubscriberRemovedMessage),

    SubscriberChangedFocus(SubscriberChangedFocusMessage),

    /// A new comment thread was added to the notebook.
    ThreadAdded(ThreadAddedMessage),

    /// A new item was added to a comment thread (e.g. a comment or a thread status change).
    ThreadItemAdded(ThreadItemAddedMessage),

    /// A new item was added to a comment thread (e.g. a comment or a thread status change).
    ThreadItemUpdated(ThreadItemUpdatedMessage),

    /// A comment thread was deleted
    ThreadDeleted(ThreadDeletedMessage),

    /// A user started typing a comment
    UserTypingComment(UserTypingCommentServerMessage),
}

#[derive(Clone, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct AuthenticateMessage {
    /// Bearer token.
    #[builder(setter(into))]
    pub token: String,

    /// Operation ID.
    ///
    /// Only messages with an operation ID will receive an `Ack` from the
    /// server.
    #[builder(default, setter(into, strip_option))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub op_id: Option<String>,
}

impl Debug for AuthenticateMessage {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AuthenticateMessage")
            .field("token", &"[REDACTED]")
            .field("op_id", &self.op_id)
            .finish()
    }
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct SubscribeMessage {
    /// ID of the notebook.
    #[builder(setter(into))]
    pub notebook_id: String,

    /// The current revision that the client knows about. If this is not the
    /// current revision according to the server, than the server will sent
    /// all operations starting from this revision.
    #[builder(default, setter(into, strip_option))]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub revision: Option<u32>,

    /// Operation ID.
    ///
    /// Only messages with an operation ID will receive an `Ack` from the
    /// server.
    #[builder(default, setter(into, strip_option))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub op_id: Option<String>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct UnsubscribeMessage {
    /// ID of the notebook.
    #[builder(setter(into))]
    pub notebook_id: String,

    /// Operation ID.
    ///
    /// Only messages with an operation ID will receive an `Ack` from the
    /// server.
    #[builder(default, setter(into, strip_option))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub op_id: Option<String>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct ApplyOperationMessage {
    /// ID of the notebook.
    #[builder(setter(into))]
    pub notebook_id: String,

    /// The operation to apply.
    pub operation: Operation,

    /// The revision assigned to the operation.
    ///
    /// If a client sends this message, it *requests* this revision to be
    /// assigned and the operation may be rejected if the revision is already
    /// assigned.
    ///
    /// When a client receives this message, it is the actual revision.
    pub revision: u32,

    /// Operation ID.
    ///
    /// Only messages with an operation ID will receive an `Ack` from the
    /// server.
    #[builder(default, setter(into, strip_option))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub op_id: Option<String>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct ApplyOperationBatchMessage {
    /// ID of the notebook.
    #[builder(setter(into))]
    pub notebook_id: String,

    /// The operations to apply.
    pub operations: Vec<Operation>,

    /// The revision assigned to the operation.
    ///
    /// If a client sends this message, it *requests* this revision to be
    /// assigned and the operations may be rejected if the revision is already
    /// assigned.
    ///
    /// When a client receives this message, it is the actual revision.
    pub revision: u32,

    /// Operation ID.
    ///
    /// Only messages with an operation ID will receive an `Ack` from the
    /// server.
    #[builder(default, setter(into, strip_option))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub op_id: Option<String>,
}

/// Acknowledgement that the server has received and successfully processed an
/// operation sent by the client.
///
/// Acknowledgement are only sent for client message that include some `op_id`.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct AckMessage {
    /// ID of the operation being acknowledged. This matches the `op_id` sent by
    /// the client.
    pub op_id: String,
}

impl AckMessage {
    pub fn new(op_id: String) -> Self {
        Self { op_id }
    }
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct ErrMessage {
    /// Error message.
    pub error_message: String,

    /// Operation ID.
    ///
    /// This will match the operation ID of the client message that triggered
    /// the error.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub op_id: Option<String>,
}

impl ErrMessage {
    /// Creates a new error with the given message.
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            error_message: message.into(),
            op_id: None,
        }
    }

    /// Assigns the optional operation ID to the message.
    pub fn with_optional_op_id(self, op_id: Option<String>) -> Self {
        Self { op_id, ..self }
    }
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct DebugRequestMessage {
    /// Operation ID.
    ///
    /// Only messages with an operation ID will receive an `Ack` from the
    /// server.
    #[builder(default, setter(into, strip_option))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub op_id: Option<String>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct DebugResponseMessage {
    /// Session ID.
    #[builder(setter(into))]
    pub sid: String,

    /// Notebooks that the user is subscribed to.
    #[builder(default)]
    pub subscribed_notebooks: Vec<String>,

    /// Operation ID.
    ///
    /// Only messages with an operation ID will receive an `Ack` from the
    /// server.
    #[builder(default, setter(into, strip_option))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub op_id: Option<String>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct EventAddedMessage {
    /// ID of workspace in which the event was added.
    #[builder(setter(into))]
    pub workspace_id: Base64Uuid,

    /// The event that was added.
    pub event: Event,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct EventUpdatedMessage {
    /// ID of workspace in which the event was updated.
    #[builder(setter(into))]
    pub workspace_id: Base64Uuid,

    /// The event that was updated.
    pub event: Event,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct EventDeletedMessage {
    /// ID of workspace in which the event was deleted.
    #[builder(setter(into))]
    pub workspace_id: Base64Uuid,

    /// ID of the event that was deleted.
    pub event_id: String,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct MentionMessage {
    /// ID of the notebook in which the user was mentioned.
    #[builder(setter(into))]
    pub notebook_id: String,

    /// ID of the cell in which the user was mentioned.
    #[builder(setter(into))]
    pub cell_id: String,

    /// Who mentioned the user?
    pub mentioned_by: MentionedBy,
}

#[derive(Debug, Clone, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct MentionedBy {
    #[builder(setter(into))]
    pub name: String,
}

/// Message sent when an apply operation was rejected by the server.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct RejectedMessage {
    /// The reason why the operation was rejected.
    pub reason: Box<RejectReason>,

    /// Operation ID.
    ///
    /// Only messages with an operation ID will receive an `Ack` from the
    /// server.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub op_id: Option<String>,
}

impl RejectedMessage {
    pub fn new(reason: RejectReason, op_id: Option<String>) -> Self {
        Self {
            reason: Box::new(reason),
            op_id,
        }
    }
}

/// Reason why the apply operation was rejected.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum RejectReason {
    /// The operation referenced an invalid cell index.
    CellIndexOutOfBounds,

    /// The operation referenced a non-existing cell.
    #[serde(rename_all = "camelCase")]
    CellNotFound { cell_id: String },

    /// The operation tried to insert a cell with a non-unique ID.
    #[serde(rename_all = "camelCase")]
    DuplicateCellId { cell_id: String },

    /// A label was submitted for already exists for the notebook.
    DuplicateLabel(DuplicateLabelRejectReason),

    /// The operation tried to insert a table row or column with a non-unique ID.
    #[serde(rename_all = "camelCase")]
    DuplicateTableId { table_id: String },

    /// The operation failed some miscellaneous precondition.
    #[serde(rename_all = "camelCase")]
    FailedPrecondition { message: String },

    /// A label was submitted that was invalid.
    InvalidLabel(InvalidLabelRejectReason),

    /// Current notebook state does not match old state in operation.
    InconsistentState,

    /// A table operation specified a column index that is out of bounds.
    InvalidTableColumnIndex,

    /// A table operation specified a row index that is out of bounds.
    InvalidTableRowIndex,

    /// A table operation specified values that didn't match the expected amount
    /// of columns or rows.
    InvalidTableDimensions,

    /// A table operation tried to reference a row or column with a non-existing
    /// ID.
    InvalidTableId { table_id: String },

    /// Current notebook state does not match old state in operation.
    #[serde(rename_all = "camelCase")]
    InconsistentFrontMatter { message: String },

    /// The front matter updates in the operation does not apply cleanly to the notebook.
    ///
    /// The most common occurrence of this will be trying to insert/modify values that don’t
    /// match the schema given in the operation.
    #[serde(rename_all = "camelCase")]
    InvalidFrontMatterUpdate(InvalidFrontMatterRejectReason),

    /// Attempted to perform a table operation on a non-table cell.
    #[serde(rename_all = "camelCase")]
    NoTableCell { cell_id: String },

    /// Attempted to perform a text operation on a non-text cell.
    #[serde(rename_all = "camelCase")]
    NoTextCell { cell_id: String },

    /// The requested apply operation was for an old version.
    Outdated(OutdatedRejectReason),

    /// The operation is unknown, and cannot be validated.
    #[serde(rename_all = "camelCase")]
    UnknownOperation { operation_summary: String },
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct InvalidFrontMatterRejectReason {
    /// The front matter key that has an issue
    pub problem_key: String,
    /// The inner problem encountered
    pub error: FrontMatterValidationError,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct OutdatedRejectReason {
    /// The current revision for the notebook.
    pub current_revision: u32,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct InvalidLabelRejectReason {
    /// The key of the label that was invalid.
    pub key: String,

    /// The specific reason why the label was invalid.
    pub validation_error: LabelValidationError,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct DuplicateLabelRejectReason {
    /// The key of the label that was already present.
    pub key: String,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct SubscriberAddedMessage {
    /// The ID of the notebook that the user subscribed to.
    #[builder(setter(into))]
    pub notebook_id: String,

    /// ID associated with the newly connected session. There can be multiple
    /// sessions for a single (notebook|user) pair. The ID can be used multiple
    /// times for different (notebook|user) pairs. The combination of notebook,
    /// user and session will be unique.
    #[builder(setter(into))]
    pub session_id: String,

    /// The moment the session was created.
    #[builder(setter(into))]
    pub created_at: Timestamp,

    /// The last time the user was active in this session.
    #[builder(setter(into))]
    pub updated_at: Timestamp,

    /// User details associated with the session.
    pub user: User,

    /// User's focus within the notebook.
    #[builder(default)]
    #[serde(default)]
    pub focus: NotebookFocus,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct SubscriberRemovedMessage {
    /// The ID of the notebook that the user unsubscribed from.
    #[builder(setter(into))]
    pub notebook_id: String,

    /// ID of the session that was removed.
    #[builder(setter(into))]
    pub session_id: String,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct User {
    /// The ID of the user. Will always be the same for the same user, so can be
    /// used for de-dupping or input for color generation.
    #[builder(setter(into))]
    pub id: String,

    /// Name of the user
    #[builder(setter(into))]
    pub name: String,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct FocusInfoMessage {
    /// ID of the notebook.
    #[builder(setter(into))]
    pub notebook_id: String,

    /// User's focus within the notebook.
    #[builder(default)]
    #[serde(default)]
    pub focus: NotebookFocus,

    /// Operation ID.
    ///
    /// Only messages with an operation ID will receive an `Ack` from the
    /// server.
    #[builder(default, setter(into, strip_option))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub op_id: Option<String>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct UserTypingCommentClientMessage {
    #[builder(setter(into))]
    pub notebook_id: Base64Uuid,

    #[builder(setter(into))]
    pub thread_id: Base64Uuid,

    /// Operation ID.
    ///
    /// Only messages with an operation ID will receive an `Ack` from the
    /// server.
    #[builder(default, setter(into, strip_option))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub op_id: Option<String>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct SubscribeWorkspaceMessage {
    /// ID of the workspace.
    #[builder(setter(into))]
    pub workspace_id: Base64Uuid,

    /// Operation ID.
    ///
    /// Only messages with an operation ID will receive an `Ack` from the
    /// server.
    #[builder(default, setter(into, strip_option))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub op_id: Option<String>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct UnsubscribeWorkspaceMessage {
    /// ID of the workspace.
    #[builder(setter(into))]
    pub workspace_id: Base64Uuid,

    /// Operation ID.
    ///
    /// Only messages with an operation ID will receive an `Ack` from the
    /// server.
    #[builder(default, setter(into, strip_option))]
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub op_id: Option<String>,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct SubscriberChangedFocusMessage {
    /// ID of the session.
    #[builder(setter(into))]
    pub session_id: String,

    /// ID of the notebook.
    #[builder(setter(into))]
    pub notebook_id: String,

    /// User's focus within the notebook.
    #[serde(default)]
    pub focus: NotebookFocus,

    #[builder(setter(into))]
    pub updated_at: Timestamp,
}

/// A single focus position within a notebook.
///
/// Focus can be placed within a cell, and optionally within separate fields
/// within the cell. An offset can be specified to indicate the exact position
/// of the cursor within a text field.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct FocusPosition {
    /// ID of the focused cell.
    ///
    /// May be the ID of an actual cell, or a so-called "surrogate ID", such as
    /// the ID that indicates focus is on the title field.
    #[builder(setter(into))]
    pub cell_id: String,

    /// Key to identify which field inside a cell has focus.
    /// May be `None` for cells that have only one (or no) text field.
    /// E.g.: For time range cells, “to” or “from” could be used.
    ///
    /// Note that fields do not necessarily have to be text fields. For example,
    /// we could also use this to indicate the user has focused a button for
    /// graph navigation.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub field: Option<String>,

    /// Offset within the text field.
    /// May be `None` if the focus is not inside a text field.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub offset: Option<u32>,
}

/// Specifies the user's focus and optional selection within the notebook.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "snake_case", tag = "type")]
pub enum NotebookFocus {
    /// The user has no focus within the notebook.
    #[default]
    None,
    /// The user focus is within the notebook and the focus is on a single
    /// position. I.e. there is no selection.
    Collapsed(FocusPosition),
    /// The user has a selection within the notebook that started at the given
    /// anchor position and ends at the given focus position.
    Selection {
        anchor: FocusPosition,
        focus: FocusPosition,
    },
}

impl NotebookFocus {
    pub fn anchor_cell_id(&self) -> Option<&str> {
        match self {
            Self::None => None,
            Self::Collapsed(collapsed) => Some(&collapsed.cell_id),
            Self::Selection { anchor, .. } => Some(&anchor.cell_id),
        }
    }

    pub fn anchor_cell_index(&self, cell_ids: &[&str]) -> Option<usize> {
        cell_ids
            .iter()
            .position(|cell_id| Some(*cell_id) == self.anchor_cell_id())
    }

    pub fn anchor_field(&self) -> Option<&str> {
        match self {
            Self::None => None,
            Self::Collapsed(collapsed) => collapsed.field.as_deref(),
            Self::Selection { anchor, .. } => anchor.field.as_deref(),
        }
    }

    pub fn anchor_offset(&self) -> u32 {
        match self {
            Self::None => 0,
            Self::Collapsed(position) => position.offset.unwrap_or_default(),
            Self::Selection { anchor, .. } => anchor.offset.unwrap_or_default(),
        }
    }

    pub fn anchor_position(&self) -> Option<&FocusPosition> {
        match self {
            Self::None => None,
            Self::Collapsed(position) => Some(position),
            Self::Selection { anchor, .. } => Some(anchor),
        }
    }

    pub fn end_cell_id(&self, cell_ids: &[&str]) -> Option<&str> {
        match self {
            Self::None => None,
            Self::Collapsed(position) => Some(&position.cell_id),
            Self::Selection { anchor, focus } => {
                let anchor_cell_index = self.anchor_cell_index(cell_ids).unwrap_or_default();
                let focus_cell_index = self.focus_cell_index(cell_ids).unwrap_or_default();
                if anchor_cell_index > focus_cell_index {
                    Some(&anchor.cell_id)
                } else {
                    Some(&focus.cell_id)
                }
            }
        }
    }

    pub fn end_offset(&self, cell_ids: &[&str]) -> u32 {
        match self {
            Self::None => 0,
            Self::Collapsed(position) => position.offset.unwrap_or_default(),
            Self::Selection { anchor, focus } => {
                let anchor_cell_index = self.anchor_cell_index(cell_ids).unwrap_or_default();
                let anchor_offset = anchor.offset.unwrap_or_default();
                let focus_cell_index = self.focus_cell_index(cell_ids).unwrap_or_default();
                let focus_offset = focus.offset.unwrap_or_default();
                match anchor_cell_index.cmp(&focus_cell_index) {
                    Ordering::Greater => anchor_offset,
                    Ordering::Equal => std::cmp::max(anchor_offset, focus_offset),
                    Ordering::Less => focus_offset,
                }
            }
        }
    }

    pub fn focus_cell_id(&self) -> Option<&str> {
        match self {
            Self::None => None,
            Self::Collapsed(collapsed) => Some(&collapsed.cell_id),
            Self::Selection { focus, .. } => Some(&focus.cell_id),
        }
    }

    pub fn focus_cell_index(&self, cell_ids: &[&str]) -> Option<usize> {
        cell_ids
            .iter()
            .position(|cell_id| Some(*cell_id) == self.focus_cell_id())
    }

    pub fn focus_field(&self) -> Option<&str> {
        match self {
            Self::None => None,
            Self::Collapsed(collapsed) => collapsed.field.as_deref(),
            Self::Selection { focus, .. } => focus.field.as_deref(),
        }
    }

    pub fn focus_offset(&self) -> u32 {
        match self {
            Self::None => 0,
            Self::Collapsed(position) => position.offset.unwrap_or_default(),
            Self::Selection { focus, .. } => focus.offset.unwrap_or_default(),
        }
    }

    pub fn focus_position(&self) -> Option<&FocusPosition> {
        match self {
            Self::None => None,
            Self::Collapsed(position) => Some(position),
            Self::Selection { focus, .. } => Some(focus),
        }
    }

    pub fn has_selection(&self) -> bool {
        !self.is_collapsed()
    }

    /// Returns whether the cursor position is collapsed, ie. the opposite of
    /// `has_selection()`.
    pub fn is_collapsed(&self) -> bool {
        match self {
            Self::None | Self::Collapsed(_) => true,
            Self::Selection { focus, anchor } => *focus == *anchor,
        }
    }

    pub fn is_none(&self) -> bool {
        matches!(self, Self::None)
    }

    pub fn start_cell_id(&self, cell_ids: &[&str]) -> Option<&str> {
        match self {
            Self::None => None,
            Self::Collapsed(position) => Some(&position.cell_id),
            Self::Selection { anchor, focus } => {
                if self.anchor_cell_index(cell_ids).unwrap_or_default()
                    < self.focus_cell_index(cell_ids).unwrap_or_default()
                {
                    Some(&anchor.cell_id)
                } else {
                    Some(&focus.cell_id)
                }
            }
        }
    }

    pub fn start_offset(&self, cell_ids: &[&str]) -> u32 {
        match self {
            Self::None => 0,
            Self::Collapsed(position) => position.offset.unwrap_or_default(),
            Self::Selection { anchor, focus } => {
                let anchor_cell_index = self.anchor_cell_index(cell_ids).unwrap_or_default();
                let anchor_offset = anchor.offset.unwrap_or_default();
                let focus_cell_index = self.focus_cell_index(cell_ids).unwrap_or_default();
                let focus_offset = focus.offset.unwrap_or_default();
                match anchor_cell_index.cmp(&focus_cell_index) {
                    Ordering::Less => anchor_offset,
                    Ordering::Equal => std::cmp::min(anchor_offset, focus_offset),
                    Ordering::Greater => focus_offset,
                }
            }
        }
    }
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct ThreadAddedMessage {
    #[builder(setter(into))]
    pub notebook_id: String,

    pub thread: Thread,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct ThreadItemAddedMessage {
    #[builder(setter(into))]
    pub notebook_id: String,

    #[builder(setter(into))]
    pub thread_id: String,

    pub thread_item: ThreadItem,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct ThreadItemUpdatedMessage {
    #[builder(setter(into))]
    pub notebook_id: String,

    #[builder(setter(into))]
    pub thread_id: String,

    pub thread_item: ThreadItem,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct ThreadDeletedMessage {
    #[builder(setter(into))]
    pub notebook_id: String,

    #[builder(setter(into))]
    pub thread_id: String,
}

#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize, TypedBuilder)]
#[cfg_attr(
    feature = "fp-bindgen",
    derive(Serializable),
    fp(rust_module = "fiberplane_models::realtime")
)]
#[non_exhaustive]
#[serde(rename_all = "camelCase")]
pub struct UserTypingCommentServerMessage {
    #[builder(setter(into))]
    pub notebook_id: String,

    #[builder(setter(into))]
    pub thread_id: String,

    pub user: UserSummary,

    #[builder(setter(into))]
    pub updated_at: Timestamp,
}

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

    #[test]
    fn serialize_reject_reason() {
        let reason = OutdatedRejectReason {
            current_revision: 1,
        };
        let reason = RejectReason::Outdated(reason);
        let result = serde_json::to_string(&reason);
        if let Err(err) = result {
            panic!("Unexpected error occurred: {err:?}");
        }
    }
}