Repository navigation
Expand file tree
/
Copy pathexample_test.go
More file actions
1123 lines (969 loc) · 30.1 KB
/
Copy pathexample_test.go
File metadata and controls
1123 lines (969 loc) · 30.1 KB
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 mailbox_test
import (
"context"
"fmt"
"log"
"net/http"
"net/http/httptest"
"sort"
"sync"
"time"
"github.com/rbaliyan/event/v3"
"github.com/rbaliyan/event/v3/transport/channel"
"crypto/rand"
"github.com/rbaliyan/mailbox"
"github.com/rbaliyan/mailbox/compress"
"github.com/rbaliyan/mailbox/crypto"
"github.com/rbaliyan/mailbox/notify"
notifymem "github.com/rbaliyan/mailbox/notify/memory"
"github.com/rbaliyan/mailbox/store"
"github.com/rbaliyan/mailbox/store/memory"
"golang.org/x/crypto/curve25519"
)
// newTestService creates a connected service for examples using in-memory backends.
// Channel transport enables synchronous event delivery without Redis.
func newTestService() mailbox.Service {
svc, err := mailbox.New(mailbox.Config{},
mailbox.WithStore(memory.New()),
mailbox.WithEventTransport(channel.New()),
)
if err != nil {
log.Fatal(err)
}
if err := svc.Connect(context.Background()); err != nil {
log.Fatal(err)
}
return svc
}
// newTestServiceWithNotifications creates a connected service with notification support.
func newTestServiceWithNotifications() mailbox.Service {
notifier := notify.NewNotifier(
notify.WithStore(notifymem.New()),
notify.WithPollInterval(50*time.Millisecond),
)
svc, err := mailbox.New(mailbox.Config{},
mailbox.WithStore(memory.New()),
mailbox.WithEventTransport(channel.New()),
mailbox.WithNotifier(notifier),
)
if err != nil {
log.Fatal(err)
}
if err := svc.Connect(context.Background()); err != nil {
log.Fatal(err)
}
return svc
}
// ExampleNew demonstrates creating and connecting a mailbox service.
func ExampleNew() {
svc, err := mailbox.New(mailbox.Config{},
mailbox.WithStore(memory.New()),
// Production: use mailbox.WithRedisClient(redisClient) for events
// Production: use mongostore.New(mongoClient) for storage
)
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
if err := svc.Connect(ctx); err != nil {
log.Fatal(err)
}
defer svc.Close(ctx)
fmt.Println("connected:", svc.IsConnected())
// Output:
// connected: true
}
// ExampleNew_withConfig demonstrates all major configuration options.
func ExampleNew_withConfig() {
svc, err := mailbox.New(mailbox.Config{
// Message limits
MaxBodySize: 5 * 1024 * 1024, // 5 MB
MaxSubjectLength: 200, // 200 chars
MaxRecipientCount: 50, // 50 recipients
MaxAttachmentCount: 10, // 10 attachments
MaxAttachmentSize: 50 * 1024 * 1024, // 50 MB per attachment
// Query limits
MaxQueryLimit: 200,
DefaultQueryLimit: 25,
// Trash and retention
TrashRetention: 7 * 24 * time.Hour, // 7 days
MessageRetention: 90 * 24 * time.Hour, // 90 days
// Concurrency
MaxConcurrentSends: 20,
ShutdownTimeout: 60 * time.Second,
},
mailbox.WithStore(memory.New()),
)
if err != nil {
log.Fatal(err)
}
ctx := context.Background()
if err := svc.Connect(ctx); err != nil {
log.Fatal(err)
}
defer svc.Close(ctx)
fmt.Println("connected:", svc.IsConnected())
// Output:
// connected: true
}
// ExampleMailbox_SendMessage demonstrates sending a message directly.
func ExampleMailbox_SendMessage() {
ctx := context.Background()
svc := newTestService()
defer svc.Close(ctx)
alice := svc.Client("alice")
msg, err := alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob", "charlie"},
Subject: "Team sync",
Body: "Let's meet at 3pm.",
Headers: map[string]string{"Content-Type": "text/plain"},
Metadata: map[string]any{"priority": "high"},
})
if err != nil {
log.Fatal(err)
}
fmt.Println("sent:", msg.GetSubject())
fmt.Println("to:", msg.GetRecipientIDs())
// Bob sees the message in his inbox.
bob := svc.Client("bob")
inbox, _ := bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
fmt.Println("bob inbox:", len(inbox.All()))
// Output:
// sent: Team sync
// to: [bob charlie]
// bob inbox: 1
}
// ExampleMailbox_Compose demonstrates the draft workflow: compose, save, edit, send.
func ExampleMailbox_Compose() {
ctx := context.Background()
svc := newTestService()
defer svc.Close(ctx)
alice := svc.Client("alice")
// Step 1: Compose a draft.
draft, err := alice.Compose()
if err != nil {
log.Fatal(err)
}
draft.SetSubject("Draft message").
SetBody("Work in progress...").
SetRecipients("bob")
// Step 2: Save the draft for later.
saved, err := draft.Save(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("draft saved:", saved.Subject())
// Step 3: List drafts.
drafts, _ := alice.Drafts(ctx, store.ListOptions{})
fmt.Println("drafts:", len(drafts.All()))
// Step 4: Edit and send the draft.
saved.SetBody("Final version.")
msg, err := saved.Send(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Println("sent:", msg.GetSubject())
// Draft is gone after sending.
drafts, _ = alice.Drafts(ctx, store.ListOptions{})
fmt.Println("drafts after send:", len(drafts.All()))
// Output:
// draft saved: Draft message
// drafts: 1
// sent: Draft message
// drafts after send: 0
}
// ExampleMailbox_Folder demonstrates listing messages in different folders.
func ExampleMailbox_Folder() {
ctx := context.Background()
svc := newTestService()
defer svc.Close(ctx)
alice := svc.Client("alice")
// Send 3 messages to bob.
for i := 1; i <= 3; i++ {
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: fmt.Sprintf("Message %d", i),
Body: "body",
})
}
bob := svc.Client("bob")
// List inbox with pagination.
page1, _ := bob.Folder(ctx, store.FolderInbox, store.ListOptions{Limit: 2})
fmt.Println("page 1:", len(page1.All()), "has_more:", page1.HasMore())
// Alice's sent folder.
sent, _ := alice.Folder(ctx, store.FolderSent, store.ListOptions{})
fmt.Println("alice sent:", len(sent.All()))
// Output:
// page 1: 2 has_more: true
// alice sent: 3
}
// ExampleMailbox_UpdateFlags demonstrates marking messages as read/unread.
func ExampleMailbox_UpdateFlags() {
ctx := context.Background()
svc := newTestService()
defer svc.Close(ctx)
alice := svc.Client("alice")
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "Important",
Body: "Read this!",
})
bob := svc.Client("bob")
inbox, _ := bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
msg := inbox.All()[0]
fmt.Println("is_read:", msg.GetIsRead())
// Mark as read.
bob.UpdateFlags(ctx, msg.GetID(), mailbox.MarkRead())
updated, _ := bob.Get(ctx, msg.GetID())
fmt.Println("after mark read:", updated.GetIsRead())
// Mark as unread.
bob.UpdateFlags(ctx, msg.GetID(), mailbox.MarkUnread())
updated, _ = bob.Get(ctx, msg.GetID())
fmt.Println("after mark unread:", updated.GetIsRead())
// Mark all read in inbox.
count, _ := bob.MarkAllRead(ctx, store.FolderInbox)
fmt.Println("marked read:", count)
// Output:
// is_read: false
// after mark read: true
// after mark unread: false
// marked read: 1
}
// ExampleMailbox_Delete demonstrates soft delete, restore, and permanent delete.
func ExampleMailbox_Delete() {
ctx := context.Background()
svc := newTestService()
defer svc.Close(ctx)
alice := svc.Client("alice")
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "Delete me",
Body: "body",
})
bob := svc.Client("bob")
inbox, _ := bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
msgID := inbox.All()[0].GetID()
// Soft delete — moves to trash.
bob.Delete(ctx, msgID)
inbox, _ = bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
trash, _ := bob.Folder(ctx, store.FolderTrash, store.ListOptions{})
fmt.Println("inbox:", len(inbox.All()), "trash:", len(trash.All()))
// Restore from trash.
bob.Restore(ctx, msgID)
inbox, _ = bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
trash, _ = bob.Folder(ctx, store.FolderTrash, store.ListOptions{})
fmt.Println("after restore - inbox:", len(inbox.All()), "trash:", len(trash.All()))
// Permanent delete (must be in trash first).
bob.Delete(ctx, msgID)
bob.PermanentlyDelete(ctx, msgID)
trash, _ = bob.Folder(ctx, store.FolderTrash, store.ListOptions{})
fmt.Println("after permanent delete - trash:", len(trash.All()))
// Output:
// inbox: 0 trash: 1
// after restore - inbox: 1 trash: 0
// after permanent delete - trash: 0
}
// ExampleMailbox_MoveToFolder demonstrates moving messages between folders.
func ExampleMailbox_MoveToFolder() {
ctx := context.Background()
svc := newTestService()
defer svc.Close(ctx)
alice := svc.Client("alice")
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "Archive this",
Body: "body",
})
bob := svc.Client("bob")
inbox, _ := bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
msgID := inbox.All()[0].GetID()
// Move to archive.
bob.MoveToFolder(ctx, msgID, store.FolderArchived)
inbox, _ = bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
archived, _ := bob.Folder(ctx, store.FolderArchived, store.ListOptions{})
fmt.Println("inbox:", len(inbox.All()), "archived:", len(archived.All()))
// Move to a custom folder.
bob.MoveToFolder(ctx, msgID, "work")
work, _ := bob.Folder(ctx, "work", store.ListOptions{})
fmt.Println("work folder:", len(work.All()))
// Output:
// inbox: 0 archived: 1
// work folder: 1
}
// ExampleMailbox_AddTag demonstrates tag management.
func ExampleMailbox_AddTag() {
ctx := context.Background()
svc := newTestService()
defer svc.Close(ctx)
alice := svc.Client("alice")
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "Tagged message",
Body: "body",
})
bob := svc.Client("bob")
inbox, _ := bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
msgID := inbox.All()[0].GetID()
// Add tags.
bob.AddTag(ctx, msgID, "important")
bob.AddTag(ctx, msgID, "project-x")
msg, _ := bob.Get(ctx, msgID)
fmt.Println("tags:", msg.GetTags())
// Remove a tag.
bob.RemoveTag(ctx, msgID, "project-x")
msg, _ = bob.Get(ctx, msgID)
fmt.Println("after remove:", msg.GetTags())
// Output:
// tags: [important project-x]
// after remove: [important]
}
// ExampleMailbox_threads demonstrates thread-based messaging.
func Example_threads() {
ctx := context.Background()
svc := newTestService()
defer svc.Close(ctx)
alice := svc.Client("alice")
// Start a thread.
msg, _ := alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "Thread starter",
Body: "Let's discuss.",
ThreadID: "thread-001",
})
// Reply in the same thread.
bob := svc.Client("bob")
bobInbox, _ := bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
bobMsgID := bobInbox.All()[0].GetID()
bob.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"alice"},
Subject: "Re: Thread starter",
Body: "Sounds good!",
ThreadID: "thread-001",
ReplyToID: bobMsgID,
})
// Get all messages in the thread.
thread, _ := alice.GetThread(ctx, "thread-001", store.ListOptions{})
fmt.Println("thread messages:", len(thread.All()))
// Get replies to the original message.
replies, _ := bob.GetReplies(ctx, msg.GetID(), store.ListOptions{})
fmt.Println("replies:", len(replies.All()))
// Output:
// thread messages: 2
// replies: 0
}
// ExampleMailbox_Search demonstrates full-text search.
func ExampleMailbox_Search() {
ctx := context.Background()
svc := newTestService()
defer svc.Close(ctx)
alice := svc.Client("alice")
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "Project Alpha update",
Body: "The deployment is complete.",
})
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "Lunch plans",
Body: "Pizza or sushi?",
})
bob := svc.Client("bob")
// Search for "deployment".
results, _ := bob.Search(ctx, store.SearchQuery{Query: "deployment"})
fmt.Println("found:", len(results.All()))
if len(results.All()) > 0 {
fmt.Println("subject:", results.All()[0].GetSubject())
}
// Output:
// found: 1
// subject: Project Alpha update
}
// ExampleMailbox_Stream demonstrates memory-efficient streaming iteration.
func ExampleMailbox_Stream() {
ctx := context.Background()
svc := newTestService()
defer svc.Close(ctx)
alice := svc.Client("alice")
for i := 1; i <= 5; i++ {
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: fmt.Sprintf("Msg %d", i),
Body: "body",
})
}
bob := svc.Client("bob")
// Stream all inbox messages in batches of 2.
iter, _ := bob.Stream(ctx, []store.Filter{
store.InFolder(store.FolderInbox),
}, mailbox.StreamOptions{BatchSize: 2})
var count int
for {
ok, err := iter.Next(ctx)
if err != nil {
log.Fatal(err)
}
if !ok {
break
}
count++
}
fmt.Println("streamed:", count)
// Output:
// streamed: 5
}
// ExampleMailbox_BulkDelete demonstrates bulk operations.
func ExampleMailbox_BulkDelete() {
ctx := context.Background()
svc := newTestService()
defer svc.Close(ctx)
alice := svc.Client("alice")
var ids []string
for i := 1; i <= 3; i++ {
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: fmt.Sprintf("Bulk %d", i),
Body: "body",
})
}
bob := svc.Client("bob")
inbox, _ := bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
for _, m := range inbox.All() {
ids = append(ids, m.GetID())
}
// Bulk delete all messages.
result, _ := bob.BulkDelete(ctx, ids)
fmt.Println("deleted:", result.SuccessCount())
trash, _ := bob.Folder(ctx, store.FolderTrash, store.ListOptions{})
fmt.Println("trash:", len(trash.All()))
// Output:
// deleted: 3
// trash: 3
}
// Example_systemMessages demonstrates sending messages from a system user.
func Example_systemMessages() {
ctx := context.Background()
svc := newTestService()
defer svc.Close(ctx)
// System sends a notification to bob.
system := svc.Client("system")
system.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "Welcome to the platform",
Body: "<h1>Welcome!</h1><p>Your account is ready.</p>",
Headers: map[string]string{"Content-Type": "text/html"},
Metadata: map[string]any{
"template": "welcome",
"deep_link": "/onboarding",
},
})
bob := svc.Client("bob")
inbox, _ := bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
msg := inbox.All()[0]
fmt.Println("from:", msg.GetSenderID())
fmt.Println("subject:", msg.GetSubject())
fmt.Println("content-type:", msg.GetHeaders()["Content-Type"])
fmt.Println("template:", msg.GetMetadata()["template"])
// Output:
// from: system
// subject: Welcome to the platform
// content-type: text/html
// template: welcome
}
// Example_eventSubscription demonstrates subscribing to mailbox events.
func Example_eventSubscription() {
ctx := context.Background()
svc := newTestService()
defer svc.Close(ctx)
// Track events.
var mu sync.Mutex
var received []string
svc.Events().MessageSent.Subscribe(ctx,
func(ctx context.Context, _ event.Event[mailbox.MessageSentEvent], data mailbox.MessageSentEvent) error {
mu.Lock()
received = append(received, "sent:"+data.Subject)
mu.Unlock()
return nil
},
)
svc.Events().MessageReceived.Subscribe(ctx,
func(ctx context.Context, _ event.Event[mailbox.MessageReceivedEvent], data mailbox.MessageReceivedEvent) error {
mu.Lock()
received = append(received, "received:"+data.RecipientID)
mu.Unlock()
return nil
},
)
// Send a message (events fire synchronously with channel transport).
alice := svc.Client("alice")
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "Hello",
Body: "body",
})
// Block until both events (sent + received) have been delivered, rather
// than sleeping for a fixed duration. The handlers append under mu, so the
// count is read under the same lock. A deadline bounds the wait so a
// delivery regression fails fast instead of hanging.
deadline := time.Now().Add(5 * time.Second)
for {
mu.Lock()
done := len(received) == 2
mu.Unlock()
if done || time.Now().After(deadline) {
break
}
}
mu.Lock()
sort.Strings(received)
for _, e := range received {
fmt.Println(e)
}
mu.Unlock()
// Output:
// received:bob
// sent:Hello
}
// Example_notifications demonstrates real-time notification delivery.
// This example uses the in-memory notify store with channel-based delivery.
// In production, use Redis Streams (notifyredis.New) for cross-instance delivery.
func Example_notifications() {
ctx := context.Background()
svc := newTestServiceWithNotifications()
defer svc.Close(ctx)
// Open notification stream for bob BEFORE sending the message.
stream, err := svc.Notifications(ctx, "bob", "")
if err != nil {
log.Fatal(err)
}
defer stream.Close()
// Send a message to bob. The stream's store poller backfills persisted
// events, so no artificial delay is needed before reading.
alice := svc.Client("alice")
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "Real-time!",
Body: "body",
})
// Block on Next until we get the received event.
// Multiple events may fire (sent, received) — find the one for bob.
readCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
for {
evt, err := stream.Next(readCtx)
if err != nil {
log.Fatal(err)
}
if evt.Type == "mailbox.message.received" {
fmt.Println("type:", evt.Type)
break
}
}
// Output:
// type: mailbox.message.received
}
// Example_sseServer demonstrates a complete HTTP server with SSE notifications
// and a client that consumes the stream. This is a self-contained server+client
// example that runs in-process using httptest.
func Example_sseServer() {
ctx := context.Background()
svc := newTestServiceWithNotifications()
defer svc.Close(ctx)
// --- Server side: SSE endpoint ---
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming not supported", http.StatusInternalServerError)
return
}
userID := r.URL.Query().Get("user_id")
lastEventID := r.Header.Get("Last-Event-ID")
stream, err := svc.Notifications(r.Context(), userID, lastEventID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer stream.Close()
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("X-Accel-Buffering", "no")
w.WriteHeader(http.StatusOK)
flusher.Flush()
for {
evt, err := stream.Next(r.Context())
if err != nil {
return
}
fmt.Fprintf(w, "id: %s\nevent: %s\ndata: %s\n\n", evt.ID, evt.Type, string(evt.Payload))
flusher.Flush()
}
})
ts := httptest.NewServer(handler)
defer ts.Close()
// --- Client side: consume SSE ---
done := make(chan bool, 1)
go func() {
resp, err := http.Get(ts.URL + "?user_id=bob")
if err != nil {
done <- false
return
}
defer resp.Body.Close()
buf := make([]byte, 4096)
n, _ := resp.Body.Read(buf)
done <- n > 0
}()
// Send a message to trigger an SSE event. No connect delay is needed: the
// notification is persisted, and the SSE handler's stream poller backfills
// it from the store regardless of connection ordering.
alice := svc.Client("alice")
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "SSE test",
Body: "body",
})
select {
case ok := <-done:
fmt.Println("received:", ok)
case <-time.After(5 * time.Second):
fmt.Println("received: false")
}
// Output:
// received: true
}
// Example_partialDelivery demonstrates handling partial delivery errors.
func Example_partialDelivery() {
ctx := context.Background()
// Set up with a small quota so one recipient hits the limit.
svc, _ := mailbox.New(mailbox.Config{},
mailbox.WithStore(memory.New()),
mailbox.WithGlobalQuota(mailbox.QuotaPolicy{
MaxMessages: 2,
ExceedAction: mailbox.QuotaActionReject,
}),
)
svc.Connect(ctx)
defer svc.Close(ctx)
// Fill bob's quota.
for i := 0; i < 2; i++ {
svc.Client(fmt.Sprintf("sender%d", i)).SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "fill",
Body: "body",
})
}
// Try to send to both bob (over quota) and charlie (fine).
alice := svc.Client("alice")
msg, err := alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob", "charlie"},
Subject: "Partial",
Body: "body",
})
if pde, ok := mailbox.IsPartialDelivery(err); ok {
fmt.Println("delivered to:", pde.DeliveredTo)
fmt.Println("failed:", len(pde.FailedRecipients))
fmt.Println("message sent:", msg != nil)
}
// Output:
// delivered to: [charlie]
// failed: 1
// message sent: true
}
// Example_stats demonstrates aggregate statistics.
func Example_stats() {
ctx := context.Background()
// Use a plain service (no event transport) to avoid stats cache interference
// from other examples running in the same process.
svc, _ := mailbox.New(mailbox.Config{}, mailbox.WithStore(memory.New()))
svc.Connect(ctx)
defer svc.Close(ctx)
alice := svc.Client("alice")
for i := 0; i < 3; i++ {
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: fmt.Sprintf("Msg %d", i),
Body: "body",
})
}
bob := svc.Client("bob")
// Stats returns total messages and unread count.
stats, _ := bob.Stats(ctx)
fmt.Println("total:", stats.TotalMessages)
fmt.Println("unread:", stats.UnreadCount)
// UnreadCount is a convenience method.
unread, _ := bob.UnreadCount(ctx)
fmt.Println("unread count:", unread)
// Output:
// total: 3
// unread: 3
// unread count: 3
}
// Example_filters demonstrates type-safe message filters.
func Example_filters() {
ctx := context.Background()
svc := newTestService()
defer svc.Close(ctx)
alice := svc.Client("alice")
for i := 1; i <= 5; i++ {
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: fmt.Sprintf("Msg %d", i),
Body: "body",
})
}
bob := svc.Client("bob")
// Mark first 2 messages as read.
inbox, _ := bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
for i, m := range inbox.All() {
if i < 2 {
bob.UpdateFlags(ctx, m.GetID(), mailbox.MarkRead())
}
}
// Stream only unread messages using filters.
iter, _ := bob.Stream(ctx, []store.Filter{
store.InFolder(store.FolderInbox),
store.IsReadFilter(false),
}, mailbox.StreamOptions{})
var count int
for {
ok, _ := iter.Next(ctx)
if !ok {
break
}
count++
}
fmt.Println("unread messages:", count)
// Output:
// unread messages: 3
}
// Example_cleanupTrash demonstrates scheduled trash cleanup.
func Example_cleanupTrash() {
ctx := context.Background()
memStore := memory.New()
svc, _ := mailbox.New(mailbox.Config{TrashRetention: 24 * time.Hour},
mailbox.WithStore(memStore),
)
svc.Connect(ctx)
defer svc.Close(ctx)
// Send and delete a message.
alice := svc.Client("alice")
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "Old message",
Body: "body",
})
bob := svc.Client("bob")
inbox, _ := bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
bob.Delete(ctx, inbox.All()[0].GetID())
// Age messages past retention period.
memStore.AgeMessages(48 * time.Hour)
// Run cleanup.
result, _ := svc.CleanupTrash(ctx)
fmt.Println("cleaned:", result.DeletedCount)
// Output:
// cleaned: 1
}
// Example_cleanupExpiredMessages demonstrates message retention cleanup.
func Example_cleanupExpiredMessages() {
ctx := context.Background()
memStore := memory.New()
svc, _ := mailbox.New(mailbox.Config{MessageRetention: 24 * time.Hour},
mailbox.WithStore(memStore),
)
svc.Connect(ctx)
defer svc.Close(ctx)
alice := svc.Client("alice")
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "Old message",
Body: "body",
})
// Age messages past retention period.
memStore.AgeMessages(48 * time.Hour)
// Send a fresh message that should survive.
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "Fresh message",
Body: "body",
})
result, _ := svc.CleanupExpiredMessages(ctx)
fmt.Println("expired:", result.DeletedCount)
bob := svc.Client("bob")
inbox, _ := bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
fmt.Println("surviving:", len(inbox.All()))
// Output:
// expired: 2
// surviving: 1
}
// Example_listFolders demonstrates discovering folders.
func Example_listFolders() {
ctx := context.Background()
svc := newTestService()
defer svc.Close(ctx)
alice := svc.Client("alice")
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "test",
Body: "body",
})
bob := svc.Client("bob")
// Move to a custom folder.
inbox, _ := bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
bob.MoveToFolder(ctx, inbox.All()[0].GetID(), "work-queue")
// List all folders with counts.
folders, _ := bob.ListFolders(ctx)
for _, f := range folders {
if f.MessageCount > 0 {
fmt.Printf("%s: %d messages (%d unread)\n", f.ID, f.MessageCount, f.UnreadCount)
}
}
// Output:
// work-queue: 1 messages (1 unread)
}
// Example_encryptedMessage demonstrates E2E encryption: send encrypted, receive and decrypt.
func Example_encryptedMessage() {
ctx := context.Background()
// Generate X25519 keypairs for sender and recipient.
keys := crypto.NewStaticKeyResolver()
for _, user := range []string{"alice", "bob"} {
priv := make([]byte, 32)
rand.Read(priv)
pub, _ := curve25519.X25519(priv, curve25519.Basepoint)
keys.AddUser(user, pub, priv)
}
// Create service with compression + encryption plugins.
svc, _ := mailbox.New(mailbox.Config{},
mailbox.WithStore(memory.New()),
mailbox.WithPlugins(
compress.NewPlugin(compress.Gzip), // compress first
crypto.NewEncryptionPlugin(keys), // then encrypt
),
)
svc.Connect(ctx)
defer svc.Close(ctx)
// Alice sends an encrypted message — subject stays searchable.
alice := svc.Client("alice")
alice.SendMessage(ctx, mailbox.SendRequest{
RecipientIDs: []string{"bob"},
Subject: "Confidential report",
Body: "Q3 revenue: $1.2M",
Metadata: map[string]any{"department": "finance"},
})
// Bob receives and decrypts.
bob := svc.Client("bob")
inbox, _ := bob.Folder(ctx, store.FolderInbox, store.ListOptions{})
msg := inbox.All()[0]
// Subject is plaintext (searchable).
fmt.Println("subject:", msg.GetSubject())
fmt.Println("encrypted:", crypto.IsEncrypted(msg))
fmt.Println("compressed:", compress.IsCompressed(msg))
// Body is encrypted — decrypt with Open.
plaintext, _ := crypto.Open(ctx, msg, "bob", keys)
fmt.Println("body:", string(plaintext))