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
121 changes: 121 additions & 0 deletions events/mail/mail_message_received.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT

package mail

import (
"context"
"encoding/json"
"fmt"
"net/url"
"strings"

"github.com/larksuite/cli/internal/event"
)

const mailEventType = "mail.user_mailbox.event.message_received_v1"

// MailMessageReceivedOutput is the flat shape; `desc` tags drive the reflected schema.
type MailMessageReceivedOutput struct {
Type string `json:"type" desc:"Event type; always mail.user_mailbox.event.message_received_v1"`
EventID string `json:"event_id,omitempty" desc:"Globally unique event ID; safe for deduplication"`
Timestamp string `json:"timestamp,omitempty" desc:"Event delivery time (ms timestamp string)" kind:"timestamp_ms"`
Mailbox string `json:"mailbox,omitempty" desc:"Mailbox address that received this message" kind:"email"`
MessageID string `json:"message_id,omitempty" desc:"Message ID (mail.open.access scoped)"`
Sender string `json:"sender,omitempty" desc:"Sender email address" kind:"email"`
Subject string `json:"subject,omitempty" desc:"Message subject"`
BodyExcerpt string `json:"body_excerpt,omitempty" desc:"Body excerpt (first ~140 chars, plain text)"`
}

func processMailMessageReceived(_ context.Context, _ event.APIClient, raw *event.RawEvent, _ map[string]string) (json.RawMessage, error) {
var envelope struct {
Header struct {
EventID string `json:"event_id"`
EventType string `json:"event_type"`
CreateTime string `json:"create_time"`
} `json:"header"`
Event struct {
MailAddress string `json:"mail_address"`
MessageID string `json:"message_id"`
Sender string `json:"sender"`
Subject string `json:"subject"`
Body string `json:"body"`
} `json:"event"`
}
if err := json.Unmarshal(raw.Payload, &envelope); err != nil {
return raw.Payload, nil //nolint:nilerr // passthrough on malformed payload
}
body := envelope.Event.Body
if len(body) > 140 {
body = body[:140]
}
Comment on lines +49 to +51
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

In Go, does slicing a string by byte index (e.g., s[:140]) risk splitting UTF-8 runes, and what is the idiomatic way to truncate to N characters?

💡 Result:

Yes—slicing a Go string by byte index like s[:140] can split a UTF-8 encoded rune, because Go strings are byte sequences and slicing/indexing operates on byte offsets rather than characters/runes [1]. If you slice in the middle of a multi-byte UTF-8 sequence, the resulting string may contain invalid UTF-8 or partial characters when interpreted as text [1]. Idiomatic ways to truncate to N characters (runes) in Go: 1) Truncate to N runes by converting to []rune (simplest/idiomatic when you mean “characters”): r:= []rune(s) if len(r) > N { s = string(r[:N]) } This works because range over strings and rune-based operations treat UTF-8 correctly; the indices from range are byte positions [1]. 2) If you instead have an N-byte limit (not asked, but commonly confused with N “characters”), use utf8 helpers to avoid cutting mid-rune. The unicode/utf8 package provides RuneStart(b byte) to detect rune boundary bytes [2]. For example, after choosing an approximate byte index i, move left until s[i] is a valid rune start, then slice at that boundary (as illustrated by solutions using utf8.RuneStart) [3]. If you truly mean “truncate to N characters/runes”, use option (1).

Citations:


🏁 Script executed:

# First, locate and examine the actual file
find . -name "mail_message_received.go" -type f

Repository: larksuite/cli

Length of output: 96


🏁 Script executed:

# Read the file to understand the context around lines 49-51
cat -n events/mail/mail_message_received.go | head -70

Repository: larksuite/cli

Length of output: 3327


Use rune-safe truncation for BodyExcerpt at lines 49–51.

The field is documented as "Body excerpt (first ~140 chars, plain text)" but truncates by byte index. This can split UTF-8 runes if the email body contains non-ASCII characters, producing corrupted text in the excerpt.

Suggested fix
 	body := envelope.Event.Body
-	if len(body) > 140 {
-		body = body[:140]
+	runes := []rune(body)
+	if len(runes) > 140 {
+		body = string(runes[:140])
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if len(body) > 140 {
body = body[:140]
}
body := envelope.Event.Body
runes := []rune(body)
if len(runes) > 140 {
body = string(runes[:140])
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@events/mail/mail_message_received.go` around lines 49 - 51, The current
byte-slicing of the email body can split multi-byte UTF-8 runes when building
BodyExcerpt; change the truncation to be rune-safe by converting body to runes
(e.g., []rune(body)) and slicing to at most 140 runes before converting back to
string so BodyExcerpt contains up to ~140 characters without corrupting
non-ASCII text (update the truncation at the place that currently checks
len(body) > 140 and assigns body = body[:140]).

return json.Marshal(&MailMessageReceivedOutput{
Type: envelope.Header.EventType,
EventID: envelope.Header.EventID,
Timestamp: envelope.Header.CreateTime,
Mailbox: envelope.Event.MailAddress,
MessageID: envelope.Event.MessageID,
Sender: envelope.Event.Sender,
Subject: envelope.Event.Subject,
BodyExcerpt: body,
})
}

// parseMailboxes reads comma-separated `mailbox` param, trims whitespace, drops empties,
// dedupes preserving first-seen order, and defaults to []string{"me"} when empty.
// Order matters: PreConsume subscribes sequentially and rolls back in reverse.
func parseMailboxes(raw string) []string {
seen := map[string]struct{}{}
out := []string{}
for _, mb := range strings.Split(raw, ",") {
mb = strings.TrimSpace(mb)
if mb == "" {
continue
}
if _, dup := seen[mb]; dup {
continue
}
seen[mb] = struct{}{}
out = append(out, mb)
}
if len(out) == 0 {
return []string{"me"}
}
return out
}

// mailMessageReceivedPreConsume runs once per (appID, EventKey) on the FirstForKey
// consumer (consume.Run:86-95). It sequentially calls the mailbox business
// subscribe API for each parsed mailbox; on any failure it rolls back the
// already-subscribed mailboxes in reverse order (best-effort) and returns the
// wrapped error. On full success it returns a cleanup closure that consume.Run
// will invoke on lastForKey exit (or unconditionally on panic).
func mailMessageReceivedPreConsume(ctx context.Context, rt event.APIClient, params map[string]string) (func(), error) {
mailboxes := parseMailboxes(params["mailbox"])
var subscribed []string
for _, mb := range mailboxes {
if _, err := rt.CallAPI(ctx, "POST",
"/open-apis/mail/v1/user_mailboxes/"+url.PathEscape(mb)+"/event/subscribe",
map[string]interface{}{"event_type": 1}); err != nil {
for i := len(subscribed) - 1; i >= 0; i-- {
_, _ = rt.CallAPI(ctx, "POST",
"/open-apis/mail/v1/user_mailboxes/"+url.PathEscape(subscribed[i])+"/event/unsubscribe",
map[string]interface{}{"event_type": 1})
}
return nil, fmt.Errorf("mail event subscribe failed for %s: %w "+
"(hint: ensure (1) you are logged in as user with required mail scopes, "+
"(2) the app has subscribed to %s in the developer console, "+
"(3) the user has access to the target mailbox)",
mb, err, mailEventType)
}
subscribed = append(subscribed, mb)
}
cleanup := func() {
for i := len(subscribed) - 1; i >= 0; i-- {
_, _ = rt.CallAPI(ctx, "POST",
"/open-apis/mail/v1/user_mailboxes/"+url.PathEscape(subscribed[i])+"/event/unsubscribe",
map[string]interface{}{"event_type": 1})
}
Comment on lines +113 to +118
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Avoid using the captured request context in cleanup at Lines 113-118.

cleanup currently reuses ctx from pre-consume. If that context is canceled on shutdown, unsubscribe calls can fail immediately, leaving stale subscriptions.

#!/bin/bash
# Verify whether cleanup is invoked after cancellation in consume lifecycle.
# Expected: call flow should show whether cleanup executes with canceled ctx.
rg -n -C4 'PreConsume|cleanup|lastForKey|context\.Cancel|cancel\(' --type go
Suggested fix
 import (
 	"context"
 	"encoding/json"
 	"fmt"
 	"net/url"
 	"strings"
+	"time"
@@
 	cleanup := func() {
+		cleanupCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+		defer cancel()
 		for i := len(subscribed) - 1; i >= 0; i-- {
-			_, _ = rt.CallAPI(ctx, "POST",
+			_, _ = rt.CallAPI(cleanupCtx, "POST",
 				"/open-apis/mail/v1/user_mailboxes/"+url.PathEscape(subscribed[i])+"/event/unsubscribe",
 				map[string]interface{}{"event_type": 1})
 		}
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@events/mail/mail_message_received.go` around lines 113 - 118, The cleanup
closure should not reuse the pre-consume captured ctx because it may be
canceled; update cleanup (the function literal that iterates subscribed and
calls rt.CallAPI) to create and use a fresh context (e.g. context.Background()
or context.WithTimeout) for its unsubscribe POST calls to
"/open-apis/mail/v1/user_mailboxes/"+url.PathEscape(subscribed[i])+"/event/unsubscribe"
via rt.CallAPI, so unsubscribes run even if the original ctx is canceled; ensure
you cancel any timeout context you create and keep the loop over subscribed and
the rt.CallAPI call site unchanged except for replacing ctx with the new local
context.

}
return cleanup, nil
}
Loading
Loading