-
Notifications
You must be signed in to change notification settings - Fork 767
feat(event): implement mail event domain package and mail +watch improvements #899
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
bubbmon233
wants to merge
1
commit into
larksuite:main
Choose a base branch
from
bubbmon233:feat/5b0c64b
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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] | ||
| } | ||
| 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Avoid using the captured request context in cleanup at Lines 113-118.
#!/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 goSuggested 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 |
||
| } | ||
| return cleanup, nil | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 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:
Repository: larksuite/cli
Length of output: 96
🏁 Script executed:
Repository: larksuite/cli
Length of output: 3327
Use rune-safe truncation for
BodyExcerptat 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
📝 Committable suggestion
🤖 Prompt for AI Agents