Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
767 lines (668 loc) · 20.2 KB
/
Copy pathmain.go
File metadata and controls
767 lines (668 loc) · 20.2 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
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"html/template"
"log/slog"
"maps"
"net/mail"
"net/url"
"os"
"slices"
"strings"
"time"
"github.com/YoRyan/turbogmailify/internal/mocks"
"github.com/emersion/go-imap/v2"
"github.com/emersion/go-imap/v2/imapclient"
"github.com/pelletier/go-toml/v2"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/gmail/v1"
"google.golang.org/api/googleapi"
"google.golang.org/api/option"
)
const (
maxPollTime = 5 * time.Minute
networkRetryTime = maxPollTime
numMessagesBatch = 32
)
func main() {
var (
doAuth bool
useToml bool
logLevel int
)
flag.BoolVar(&doAuth, "auth", false, "Request access and refresh tokens from Google instead of processing mail.")
flag.BoolVar(&useToml, "toml", false, "Process the configuration file as a TOML file, with the Secrets and Tokens sections as strings.")
flag.IntVar(&logLevel, "log", int(slog.LevelInfo), "Change the log level, which defaults to INFO (0). See https://pkg.go.dev/log/slog#Level.")
flag.Parse()
// Use TextHandler to filter out control codes and avoid console logging attacks.
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.Level(logLevel)})))
if flag.NArg() < 1 {
slog.Error("Did not pass path to configuration file.")
os.Exit(1)
}
path := flag.Arg(0)
cfg := &config{}
b, err := os.ReadFile(path)
if err != nil {
slog.Error("Failed to open config file", "err", err)
os.Exit(1)
}
if useToml {
tomlCfg := &tomlConfig{}
if err := toml.Unmarshal(b, tomlCfg); err != nil {
slog.Error("Failed to parse config file", "err", err)
os.Exit(1)
}
cfg.Imap = tomlCfg.Imap
if tomlCfg.Secrets != "" {
if err := json.NewDecoder(strings.NewReader(tomlCfg.Secrets)).Decode(&cfg.Secrets); err != nil {
slog.Error("Unable to decode embedded JSON 'Secrets' section", "err", err)
os.Exit(1)
}
} else {
slog.Error("Failed to parse config file",
"err", "Google credentials ('Secrets') are missing")
os.Exit(1)
}
if tomlCfg.Tokens != "" {
if err := json.NewDecoder(strings.NewReader(tomlCfg.Tokens)).Decode(&cfg.Tokens); err != nil {
slog.Error("Unable to decode embedded JSON 'Tokens' section", "err", err)
os.Exit(1)
}
}
} else {
if err := json.Unmarshal(b, cfg); err != nil {
slog.Error("Failed to parse config file", "err", err)
os.Exit(1)
}
}
if len(cfg.Imap) <= 0 {
slog.Error("Failed to parse config file",
"err", "IMAP credentials section is empty or not a JSON list")
os.Exit(1)
}
if cfg.Secrets == nil {
slog.Error("Failed to parse config file",
"err", "Google credentials ('Secrets') are missing")
os.Exit(1)
}
if doAuth {
doRequestAuth(cfg)
} else {
doForwarding(cfg)
}
}
// Configuration file loaded from TOML.
type tomlConfig struct {
Imap []configImap
Secrets string
Tokens string
}
// Configuration file loaded from JSON.
type config struct {
Imap []configImap
Secrets any
Tokens *oauth2.Token
}
type configImap struct {
Address string
Username string
Password string
Folders map[string][]string
ArchiveFolders map[string]string
FailedFolders map[string]string
NeverMarkSpam map[string]bool
ProcessForCalendar map[string]bool
IdleFolder string // folder to IDLE on; defaults to "INBOX" if empty
}
func (c *config) getOAuthConfig() (oa *oauth2.Config) {
// Need to submit the client secret as JSON bytes, leading to this silly
// re-encode step.
secrets, err := json.Marshal(c.Secrets)
if err != nil {
return
}
oa, err = google.ConfigFromJSON(secrets, gmail.GmailInsertScope)
if err != nil {
slog.Error("Unable to create Google OAuth2 client", "err", err)
os.Exit(1)
}
return
}
// Run in request tokens mode.
func doRequestAuth(c *config) {
oa := c.getOAuthConfig()
authURL := oa.AuthCodeURL("", oauth2.AccessTypeOffline)
fmt.Println("Navigate to the following URL in your browser:")
fmt.Println(authURL)
var redirectURL string
fmt.Println("")
fmt.Println("Once you've authorized the request, your browser will redirect to an http://localhost URL that will fail to load. Paste the entire URL here:")
if _, err := fmt.Scan(&redirectURL); err != nil {
slog.Error("Unable to read redirected URL", "err", err)
os.Exit(1)
}
parsedURL, err := url.Parse(redirectURL)
if err != nil {
slog.Error("Unable to parse redirected URL", "err", err)
os.Exit(1)
}
authCode := parsedURL.Query().Get("code")
if authCode == "" {
slog.Error("URL does not look like it contains a Google code", "err", "missing 'code' value in query string")
os.Exit(1)
}
tokens, err := oa.Exchange(context.Background(), authCode)
if err != nil {
slog.Error("Unable to retrieve tokens from Google", "err", err)
os.Exit(1)
}
fmt.Println("")
fmt.Println("Your 'Tokens' section is as follows:")
if err := json.NewEncoder(os.Stdout).Encode(tokens); err != nil {
slog.Error("Error converting tokens to JSON", "err", err)
os.Exit(1)
}
}
// Run in mail forwarding mode.
func doForwarding(c *config) {
if c.Tokens == nil {
slog.Error("Authorization tokens ('Tokens') are missing. Obtain them with -auth mode.")
os.Exit(1)
}
oa := c.getOAuthConfig()
ctx := context.Background()
gmService, err := gmail.NewService(ctx, option.WithHTTPClient(oa.Client(ctx, c.Tokens)))
if err != nil {
slog.Error("Unable to create Gmail client", "err", err)
os.Exit(1)
}
gmInbox := (*gmailInboxReal)(gmService)
// Spin up a goroutine for each IMAP connection.
for _, ic := range c.Imap {
go doForwardingForImap(&ic, gmInbox)
}
// Put the main goroutine to sleep.
slog.Info("Startup complete; waiting for mail")
select {}
}
// Forward mail indefinitely for a configured IMAP account.
func doForwardingForImap(c *configImap, in gmailInbox) {
forwardConfig := createForwardConfig(c)
importFailedUids := forwardConfig.createUidMap[struct{}]()
for {
func() {
s, err := connectSession(c, &forwardConfig, importFailedUids)
if err != nil {
time.Sleep(networkRetryTime)
return
}
defer s.close()
for {
cooldown, err := s.forwardForServer(in)
time.Sleep(cooldown)
if err != nil {
return
}
cooldown, err = s.doIdle()
time.Sleep(cooldown)
if err != nil {
return
}
}
}()
}
}
type forwardConfig struct {
id string
folderToLabels map[string][]string
folderToArchive map[string]string
folderToFailed map[string]string
folderToNeverMarkSpam map[string]bool
folderToProcessForCalendar map[string]bool
folderOrderIdleLast []string
}
func createForwardConfig(c *configImap) forwardConfig {
var folders map[string][]string
if len(c.Folders) > 0 {
folders = c.Folders
} else {
folders = map[string][]string{
"INBOX": {"INBOX"},
"Junk": {"SPAM"},
}
}
// Determine which folder to IDLE on. It must always be the last folder
// selected before IDLE — an extra SELECT between the drain loop and IDLE
// causes some servers (e.g. free.fr) to stop sending push notifications.
// We achieve this by draining all other folders first and the idle folder
// last, so no additional SELECT is needed after the loop.
var idle string
if c.IdleFolder != "" {
idle = c.IdleFolder
} else {
idle = "INBOX"
}
if _, exists := folders[idle]; !exists {
// Well, we need to idle on some folder, so just pick one...
for folder := range folders {
idle = folder
break
}
}
ordered := slices.SortedStableFunc(maps.Keys(folders), func(a, b string) int {
// Force the idle folder to be last.
if a == idle {
return 1
} else if b == idle {
return -1
} else {
return 0
}
})
return forwardConfig{
id: c.Username + "/" + c.Address,
folderToLabels: folders,
// Reusing ordered is more convenient than iterating through all the
// keys in folders just to produce a slice.
folderToArchive: folderMap[string]{m: c.ArchiveFolders, folders: ordered}.wildcard().done(),
folderToFailed: folderMap[string]{m: c.FailedFolders, folders: ordered}.wildcard().done(),
folderToNeverMarkSpam: folderMap[bool]{m: c.NeverMarkSpam, folders: ordered}.def(map[string]bool{
"Junk": true,
}).wildcard().fallback(false).done(),
folderToProcessForCalendar: folderMap[bool]{m: c.ProcessForCalendar, folders: ordered}.def(map[string]bool{
"Junk": false,
}).wildcard().fallback(true).done(),
folderOrderIdleLast: ordered,
}
}
// Initialize a nested map that accepts (mailbox, uid) tuples. For now, we
// ignore UID validity, as no use case of this structure survives restarts.
func (f forwardConfig) createUidMap[V any]() map[string]map[imap.UID]V {
m := make(map[string]map[imap.UID]V, len(f.folderOrderIdleLast))
for _, folder := range f.folderOrderIdleLast {
m[folder] = make(map[imap.UID]V, 0)
}
return m
}
// A map of IMAP folders to configuration values that includes a list of all
// possible keys (folders).
type folderMap[V any] struct {
m map[string]V
folders []string
}
// Specifies a default map if the user has not already configured one.
func (fm folderMap[V]) def(def map[string]V) folderMap[V] {
var m map[string]V
if len(fm.m) <= 0 {
m = def
} else {
m = fm.m
}
folders := fm.folders
return folderMap[V]{m, folders}
}
// Adds the wildcard (*) value to the map, which populates a value for all
// folders that do not already have explicit values.
func (fm folderMap[V]) wildcard() folderMap[V] {
wildcard, isWildcard := fm.m["*"]
m := make(map[string]V, len(fm.folders))
for _, k := range fm.folders {
if v, ok := fm.m[k]; ok {
m[k] = v
} else if isWildcard {
m[k] = wildcard
}
}
folders := fm.folders
return folderMap[V]{m, folders}
}
// Specifies a fallback value so that every folder is mapped to something.
func (fm folderMap[V]) fallback(fb V) folderMap[V] {
m := make(map[string]V, len(fm.folders))
for _, k := range fm.folders {
if v, ok := fm.m[k]; ok {
m[k] = v
} else {
m[k] = fb
}
}
folders := fm.folders
return folderMap[V]{m, folders}
}
// Finalizes this structure into an ordinary map.
func (fm folderMap[V]) done() map[string]V {
return fm.m
}
type session struct {
client *imapclient.Client
config *forwardConfig
mailboxUpdate <-chan *imapclient.UnilateralDataMailbox
idleDeadline time.Duration
importFailedUids map[string]map[imap.UID]struct{}
}
func connectSession(c *configImap, f *forwardConfig, importFailedUids map[string]map[imap.UID]struct{}) (*session, error) {
// Make a handler and channel to receive mailbox status updates.
var (
mailboxUpdate = make(chan *imapclient.UnilateralDataMailbox)
dataHandler = &imapclient.UnilateralDataHandler{
Mailbox: func(data *imapclient.UnilateralDataMailbox) {
select {
case mailboxUpdate <- data:
default:
}
}}
)
// Open the connection.
client, err := imapclient.DialTLS(c.Address, &imapclient.Options{UnilateralDataHandler: dataHandler})
if err != nil {
slog.Error("Error connecting to IMAP server", "account", f.id, "err", err)
return nil, err
}
// Provide credentials.
if err := client.
Login(c.Username, c.Password).
Wait(); err != nil {
slog.Error("LOGIN error", "account", f.id, "err", err)
client.Close()
return nil, err
}
return &session{client, f, mailboxUpdate, maxPollTime, importFailedUids}, nil
}
// Make a new connection to the IMAP server and retrieve and process messages.
func (s *session) forwardForServer(gm gmailInbox) (cooldown time.Duration, err error) {
fc := s.config
// Interrogate each folder and retrieve and process everything inside.
// Idle folder is always last so it remains selected when we enter IDLE.
for _, folder := range fc.folderOrderIdleLast {
// Batch transactions so that we do not attempt to forward too many messages in a single operation.
for {
// SELECT picks the desired folder and also comes with a message count.
inbox, err := s.client.
Select(folder, nil).
Wait()
if err != nil {
slog.Error("SELECT error", "account", fc.id, "folder", folder, "err", err)
return networkRetryTime, err
}
if inbox.NumMessages <= 0 {
break
}
batch := min(inbox.NumMessages, numMessagesBatch)
if cooldown, err := s.forwardOneBatch(gm, folder, batch); err != nil {
return cooldown, err
}
remainder := inbox.NumMessages - batch
if remainder <= 0 {
break
}
}
}
return
}
func (s *session) forwardOneBatch(gm gmailInbox, folder string, numMessages uint32) (cooldown time.Duration, err error) {
fc := s.config
labels := fc.folderToLabels[folder]
// Finish all imports as a single step before moving or expunging any
// messages. These operations affect the sequence numbers.
var (
successUids = make([]imap.UID, 0)
failUids = make([]imap.UID, 0)
)
failFolder, failFolderOk := fc.folderToFailed[folder]
for i := range numMessages {
uid, envelope, err := s.fetchMessage(i + 1)
if err != nil {
return networkRetryTime, err
}
if _, failed := s.importFailedUids[folder][uid]; failed {
// Skip anything on the in-memory blacklist.
continue
}
sum := messageSummary(envelope)
logMeta := []any{"account", fc.id, "folder", folder, "subject", sum.subject, "messageId", sum.messageId, "size", sum.size}
slog.Info("Importing message", logMeta...)
if err := gm.DoImport(envelope, fc.folderToNeverMarkSpam[folder], fc.folderToProcessForCalendar[folder], labels...); err != nil {
slog.Error("Error importing message", slices.AppendSeq([]any{"err", err}, slices.Values(logMeta))...)
if isImportRetryable(err) {
// Leave it alone; try again next cycle.
} else {
failUids = append(failUids, uid)
var disposition string
if failFolderOk {
disposition = fmt.Sprintf("The message has been moved to %s, the configured IMAP folder for failed messages.", failFolder)
} else {
disposition = "The message will not be uploaded again until the next restart of the service. It is recommended that you designate an IMAP folder to move failed messages into so they will not be retried again. This can be accomplished with the FailedFolders option."
}
body := executeTemplate(
template.Must(template.New("body").Parse(`<table>
<tr><td>Error:</td><td>{{ .Error }}</td></tr>
<tr><td>Account:</td><td>{{ .Account }}</td></tr>
<tr><td>Folder:</td><td>{{ .Folder }}</td></tr>
<tr><td>Subject:</td><td>{{ .Subject }}</td></tr>
<tr><td>Message-ID:</td><td>{{ .MessageID }}</td></tr>
<tr><td>Size:</td><td>{{ .Size }}</td></tr>
</table>
<p>{{ .Disposition }}</p>`)),
map[string]string{
"Error": err.Error(),
"Account": fc.id,
"Folder": folder,
"Size": sum.size,
"Disposition": disposition,
// Make sure to escape these values properly. They come directly from raw email headers.
"Subject": sum.subject,
"MessageID": sum.messageId,
})
sendHtmlNotification(gm, fmt.Sprintf("Message Import Failure: %s (%s)", fc.id, folder), body)
}
} else {
successUids = append(successUids, uid)
}
}
if len(successUids) > 0 {
if dest, ok := fc.folderToArchive[folder]; ok {
// Move to the configured archive folder.
if err := s.moveMessages(successUids, dest); err != nil {
return networkRetryTime, err
}
} else {
// Expunge
if err := s.deleteMessages(successUids); err != nil {
return networkRetryTime, err
}
}
}
if len(failUids) > 0 {
if failFolderOk {
// Move to the configured failed folder.
if err := s.moveMessages(failUids, failFolder); err != nil {
return networkRetryTime, err
}
} else {
// Add to the in-memory blacklist.
for _, uid := range failUids {
s.importFailedUids[folder][uid] = struct{}{}
}
}
}
return
}
// Retrieve one message from an inbox by sequence number.
func (s *session) fetchMessage(seq uint32) (uid imap.UID, data []byte, err error) {
var (
// Set an empty body section to request the raw contents of the entire
// message.
entireMessage = []*imap.FetchItemBodySection{{}}
fetch = s.client.Fetch(
imap.SeqSetNum(seq), &imap.FetchOptions{BodySection: entireMessage, UID: true})
)
defer fetch.Close()
messages, err := fetch.Collect()
if err != nil {
slog.Error("FETCH error", "err", err)
return
}
nMessages := len(messages)
if nMessages != 1 {
err = fmt.Errorf("invalid number of fetch message buffers: %d", nMessages)
return
}
data = make([]byte, 0)
msg := messages[0]
uid = msg.UID
for _, buffer := range msg.BodySection {
data = append(data, buffer.Bytes...)
}
return
}
type summary struct {
size string
subject string
messageId string
}
func messageSummary(envelope []byte) summary {
size := fmt.Sprintf("%.1fK", float32(len(envelope))/1024)
msg, err := mail.ReadMessage(bytes.NewReader(envelope))
if err == nil {
return summary{
size: size,
subject: msg.Header.Get("Subject"),
messageId: msg.Header.Get("Message-ID"),
}
} else {
return summary{
size: size,
}
}
}
// Fully close out the session's resources.
func (s *session) close() (err error) {
if err = s.client.Close(); err != nil {
return
}
return
}
// A Gmail target that can accept imported messages. This is an interface for
// testing purposes.
type gmailInbox interface {
DoImport(envelope []byte, neverMarkSpam, processForCalendar bool, labels ...string) error
}
type gmailInboxReal gmail.Service
// Import this message to Gmail via media upload.
func (gm *gmailInboxReal) DoImport(envelope []byte, neverMarkSpam, processForCalendar bool, labels ...string) error {
r, err := gm.Users.Messages.
Import("me", &gmail.Message{LabelIds: append(labels, "UNREAD")}).
InternalDateSource("dateHeader").
NeverMarkSpam(neverMarkSpam).
ProcessForCalendar(processForCalendar).
Deleted(false).
Media(
bytes.NewReader(envelope),
googleapi.ContentType("message/rfc822")).
Do()
if err != nil {
return err
}
if r.HTTPStatusCode != 200 {
return fmt.Errorf("gmail returned status code: %v", r.HTTPStatusCode)
}
return nil
}
func isImportRetryable(err error) bool {
if gerr, ok := errors.AsType[*googleapi.Error](err); ok {
// The following API errors are known:
// 400: Invalid attachment (prohibited .exe attachment)
return gerr.Code != 400
}
if errors.Is(err, mocks.ErrNonRetryable) {
return false
}
return true
}
func executeTemplate(tmpl *template.Template, data any) string {
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
return err.Error()
} else {
return buf.String()
}
}
func sendHtmlNotification(gm gmailInbox, subject, body string) error {
envelope := fmt.Sprintf(`From: Turbogmailify <me>
To: me
Subject: %s
Content-Type: text/html
<html><body>
%s
</body></html>
`, subject, body)
return gm.DoImport([]byte(envelope), true, false, "INBOX")
}
// Move a message into another mailbox using IMAP MOVE or, if that command is
// not available, COPY/STORE/EXPUNGE.
func (s *session) moveMessages(uids []imap.UID, mailbox string) error {
if _, err := s.client.
Move(imap.UIDSetNum(uids...), mailbox).
Wait(); err != nil {
slog.Error("MOVE error", "err", err)
return err
}
return nil
}
// Expunge a message from the inbox by UID.
func (s *session) deleteMessages(uids []imap.UID) error {
var (
setNum = imap.UIDSetNum(uids...)
addDeleted = &imap.StoreFlags{
Op: imap.StoreFlagsAdd,
Silent: true,
Flags: []imap.Flag{imap.FlagDeleted}}
)
if err := s.client.
Store(setNum, addDeleted, nil).
Close(); err != nil {
slog.Error("STORE error", "err", err)
return err
}
if err := s.client.
Expunge().
Close(); err != nil {
slog.Error("EXPUNGE error", "err", err)
return err
}
return nil
}
// Block until the next mailbox status update, or until the deadline has
// elapsed.
func (s *session) doIdle() (cooldown time.Duration, err error) {
idle, err := s.client.Idle()
if err != nil {
// Probably means the server doesn't support IDLE.
slog.Debug("IDLE error", "err", err)
return s.idleDeadline, nil
}
timer := time.NewTimer(s.idleDeadline)
select {
case <-s.mailboxUpdate:
timer.Stop()
case <-timer.C:
}
// Any errors past this point should have occurred after idling or waiting,
// so no need for a cooldown.
if err = idle.Close(); err != nil {
slog.Debug("IDLE Close error", "err", err)
return
}
if err = idle.Wait(); err != nil {
slog.Debug("IDLE Wait error", "err", err)
return
}
return
}