Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions shortcuts/mail/mail_watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,9 @@ var MailWatch = common.Shortcut{
larkws.WithLogger(sdkLogger),
)

watchCtx, cancelWatch := context.WithCancel(ctx)
defer cancelWatch()

sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
go func() {
Expand All @@ -433,26 +436,34 @@ var MailWatch = common.Shortcut{
}
}()
<-sigCh
signal.Stop(sigCh)
info(fmt.Sprintf("\nShutting down... (received %d events)", eventCount))
info("Unsubscribing mailbox events...")
if unsubErr := unsubscribe(); unsubErr != nil {
fmt.Fprintf(errOut, "Warning: unsubscribe failed: %v\n", unsubErr)
} else {
info("Mailbox unsubscribed.")
}
signal.Stop(sigCh)
os.Exit(0)
cancelWatch()
}()

info("Connected. Waiting for mail events... (Ctrl+C to stop)")
if err := cli.Start(ctx); err != nil {
unsubscribe() //nolint:errcheck // best-effort cleanup
return output.ErrNetwork("WebSocket connection failed: %v", err)
if err := cli.Start(watchCtx); err != nil {
return handleMailWatchStartError(err, watchCtx, unsubscribe)
}
return nil
},
}

func handleMailWatchStartError(err error, watchCtx context.Context, unsubscribe func() error) error {
if watchCtx.Err() != nil {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

watchCtx.Err() != nil is broader than "graceful shutdown via SIGINT/SIGTERM" here. watchCtx is derived from the parent ctx, so external cancellation from the caller/runtime will also hit this branch and return nil immediately, even though only the signal path actually performs unsubscribe() before canceling the watch. That means non-signal context cancellation can now skip mailbox cleanup entirely. Please distinguish signal-triggered shutdown from generic context cancellation instead of using watchCtx.Err() != nil as the only condition.

// Graceful shutdown via signal cancellation; not an error.
return nil
}
unsubscribe() //nolint:errcheck // best-effort cleanup
return output.ErrNetwork("WebSocket connection failed: %v", err)
}

// extractMailEventBody extracts the event body from the Lark event envelope.
func extractMailEventBody(data map[string]interface{}) map[string]interface{} {
// V2 envelope: { header: {...}, event: { mail_address, message_id, ... } }
Expand Down
34 changes: 34 additions & 0 deletions shortcuts/mail/mail_watch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,40 @@ func TestWrapWatchSubscribeErrorExitError(t *testing.T) {
}
}

func TestHandleMailWatchStartErrorGracefulShutdownSkipsCleanup(t *testing.T) {
watchCtx, cancel := context.WithCancel(context.Background())
cancel()

unsubscribeCalled := false
err := handleMailWatchStartError(assertErr("context canceled"), watchCtx, func() error {
unsubscribeCalled = true
return nil
})
if err != nil {
t.Fatalf("expected nil error, got %v", err)
}
if unsubscribeCalled {
t.Fatal("unsubscribe should not be called for graceful shutdown")
}
}

func TestHandleMailWatchStartErrorNetworkFailureCleansUp(t *testing.T) {
unsubscribeCalled := false
err := handleMailWatchStartError(assertErr("boom"), context.Background(), func() error {
unsubscribeCalled = true
return nil
})
if err == nil {
t.Fatal("expected error")
}
if !unsubscribeCalled {
t.Fatal("expected unsubscribe to be called for startup failure")
}
if !strings.Contains(err.Error(), "WebSocket connection failed: boom") {
t.Fatalf("unexpected error: %v", err)
}
}

// --- watchFetchFormat ---

func TestWatchFetchFormat(t *testing.T) {
Expand Down
Loading