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
106 changes: 100 additions & 6 deletions cmd/service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -425,12 +425,8 @@ func serviceMethodRun(opts *ServiceMethodOptions) error {
fmt.Fprintf(f.IOStreams.ErrOut, "warning: unknown format %q, falling back to json\n", opts.Format)
}

// Scope-insufficient (99991679) and all other Lark API codes route through
// errclass.BuildAPIError via ac.CheckResponse, producing *errs.PermissionError
// with MissingScopes / Identity / ConsoleURL populated from the response.
checkErr := ac.CheckResponse

if opts.PageAll {
checkErr := classifyServiceAPIError(ac.CheckResponse, opts, request)
return servicePaginate(opts.Ctx, ac, request, format, opts.JqExpr, out, f.IOStreams.ErrOut, opts.Cmd.CommandPath(),
client.PaginationOptions{PageLimit: opts.PageLimit, PageDelay: opts.PageDelay}, checkErr)
}
Expand All @@ -448,10 +444,108 @@ func serviceMethodRun(opts *ServiceMethodOptions) error {
FileIO: f.ResolveFileIO(opts.Ctx),
CommandPath: opts.Cmd.CommandPath(),
Identity: opts.As,
CheckError: checkErr,
CheckError: classifyServiceAPIError(ac.CheckResponse, opts, request),
})
}

const userAllowBlockCachePreparingSemantic = "UserAllowBlockCachePreparing"

const userAllowBlockCachePreparingHint = "Search cache is preparing. Retry later; or run the same list command without keyword to initialize the cache, then retry the keyword search."

func classifyServiceAPIError(base func(interface{}, core.Identity) error, opts *ServiceMethodOptions, request client.RawApiRequest) func(interface{}, core.Identity) error {
return func(result interface{}, identity core.Identity) error {
err := base(result, identity)
return annotateUserAllowBlockCachePreparing(err, result, opts, request)
}
}

func annotateUserAllowBlockCachePreparing(err error, result interface{}, opts *ServiceMethodOptions, request client.RawApiRequest) error {
if err == nil || opts == nil || !isUserAllowBlockSenderListMethod(opts.Method.ID) || !serviceRequestHasKeyword(request) || !isUserAllowBlockCachePreparingResult(result) {
return err
}
p, ok := errs.ProblemOf(err)
if !ok {
return err
}
p.Subtype = errs.SubtypeUserAllowBlockCachePreparing
if !strings.Contains(p.Message, userAllowBlockCachePreparingSemantic) {
p.Message = fmt.Sprintf("%s: %s", userAllowBlockCachePreparingSemantic, p.Message)
}
p.Hint = appendUserAllowBlockCachePreparingHint(p.Hint)
p.Retryable = true
Comment thread
coderabbitai[bot] marked this conversation as resolved.
return err
}

func appendUserAllowBlockCachePreparingHint(existing string) string {
existing = strings.TrimSpace(existing)
if existing == "" {
return userAllowBlockCachePreparingHint
}
if strings.Contains(existing, userAllowBlockCachePreparingHint) {
return existing
}
return existing + " " + userAllowBlockCachePreparingHint
}

func isUserAllowBlockSenderListMethod(methodID string) bool {
switch methodID {
case "user_mailbox.allow_sender.list", "user_mailbox.blocked_sender.list":
return true
default:
return false
}
}

func serviceRequestHasKeyword(request client.RawApiRequest) bool {
keyword, ok := request.Params["keyword"].(string)
return ok && strings.TrimSpace(keyword) != ""
}

func isUserAllowBlockCachePreparingResult(result interface{}) bool {
resultMap, ok := result.(map[string]interface{})
if !ok || !serviceNumberEquals(resultMap["code"], 456) {
return false
}
message := strings.Join(serviceCachePreparingText(resultMap), " ")
return strings.Contains(message, "15190000") && strings.Contains(message, "ErrCacheEmpty")
}

func serviceCachePreparingText(resultMap map[string]interface{}) []string {
var parts []string
for _, key := range []string{"msg", "message"} {
if value, ok := resultMap[key].(string); ok && strings.TrimSpace(value) != "" {
parts = append(parts, value)
}
}
if errBlock, ok := resultMap["error"].(map[string]interface{}); ok {
for _, key := range []string{"msg", "message"} {
if value, ok := errBlock[key].(string); ok && strings.TrimSpace(value) != "" {
parts = append(parts, value)
}
}
}
return parts
}

func serviceNumberEquals(value interface{}, want int) bool {
wantStr := fmt.Sprint(want)
switch v := value.(type) {
case int:
return v == want
case int32:
return int(v) == want
case int64:
return v == int64(want)
case float64:
return v == float64(want)
case string:
got := strings.TrimSpace(v)
return got == wantStr || got == wantStr+".0"
default:
return false
}
}

// checkServiceScopes pre-checks user scopes before making the API call.
func checkServiceScopes(ctx context.Context, cred *credential.CredentialProvider, identity core.Identity, config *core.CliConfig, method meta.Method) error {
if ctx.Err() != nil {
Expand Down
171 changes: 171 additions & 0 deletions cmd/service/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ import (

"github.com/larksuite/cli/errs"
extcs "github.com/larksuite/cli/extension/contentsafety"
"github.com/larksuite/cli/internal/client"
"github.com/larksuite/cli/internal/cmdutil"
"github.com/larksuite/cli/internal/core"
"github.com/larksuite/cli/internal/errclass"
"github.com/larksuite/cli/internal/httpmock"
"github.com/larksuite/cli/internal/meta"
"github.com/spf13/cobra"
Expand Down Expand Up @@ -201,6 +203,175 @@ func TestNewCmdServiceMethod_RunFCallback(t *testing.T) {
}
}

func TestClassifyServiceAPIError_UserAllowBlockCachePreparing(t *testing.T) {
opts := &ServiceMethodOptions{
Method: meta.FromMap(map[string]interface{}{
"id": "user_mailbox.blocked_sender.list",
"httpMethod": "GET",
}),
}
request := client.RawApiRequest{
Params: map[string]interface{}{
"user_mailbox_id": "me",
"page_size": 10,
"keyword": "cache-cli@example.test",
},
}
result := map[string]interface{}{
"code": 456,
"msg": "[15190000] ErrCacheEmpty",
"log_id": "2026071610521332E0FBDFB331EE0E73F5",
"error": map[string]interface{}{
"details": []interface{}{map[string]interface{}{"value": "backend hint"}},
"troubleshooter": "https://open.feishu.cn/document/troubleshoot/cache",
},
}
check := classifyServiceAPIError(func(result interface{}, identity core.Identity) error {
resultMap, _ := result.(map[string]interface{})
return errclass.BuildAPIError(resultMap, errclass.ClassifyContext{Identity: string(identity)})
}, opts, request)

err := check(result, core.AsUser)
if err == nil {
t.Fatal("expected cache preparing error")
}
p, ok := errs.ProblemOf(err)
if !ok {
t.Fatalf("ProblemOf returned !ok for %T", err)
}
if p.Subtype != errs.SubtypeUserAllowBlockCachePreparing {
t.Fatalf("Subtype = %q, want %q", p.Subtype, errs.SubtypeUserAllowBlockCachePreparing)
}
if p.Code != 456 {
t.Fatalf("Code = %d, want 456", p.Code)
}
if p.LogID != "2026071610521332E0FBDFB331EE0E73F5" {
t.Fatalf("LogID = %q, want preserved", p.LogID)
}
if p.Troubleshooter != "https://open.feishu.cn/document/troubleshoot/cache" {
t.Fatalf("Troubleshooter = %q, want preserved", p.Troubleshooter)
}
if !strings.Contains(p.Message, "UserAllowBlockCachePreparing") || !strings.Contains(p.Message, "ErrCacheEmpty") {
t.Fatalf("Message = %q, want semantic and raw cache-empty detail", p.Message)
}
for _, want := range []string{"Retry later", "without keyword", "initialize the cache"} {
if !strings.Contains(p.Hint, want) {
t.Fatalf("Hint = %q, want %q", p.Hint, want)
}
}
if !strings.Contains(p.Hint, "backend hint") {
t.Fatalf("Hint = %q, want server-provided hint preserved", p.Hint)
}
if !p.Retryable {
t.Fatal("Retryable = false, want true")
}
}

func TestClassifyServiceAPIError_UserAllowBlockCachePreparingScope(t *testing.T) {
result := map[string]interface{}{"code": 456, "msg": "[15190000] ErrCacheEmpty"}
base := func(result interface{}, identity core.Identity) error {
resultMap, _ := result.(map[string]interface{})
return errclass.BuildAPIError(resultMap, errclass.ClassifyContext{Identity: string(identity)})
}

cases := []struct {
name string
method string
result map[string]interface{}
request client.RawApiRequest
}{
{
name: "allow sender list positive",
method: "user_mailbox.allow_sender.list",
result: map[string]interface{}{"code": 456, "msg": "[15190000] ErrCacheEmpty"},
request: client.RawApiRequest{Params: map[string]interface{}{
"keyword": "cache-cli@example.test",
}},
},
{
name: "different method",
method: "user_mailbox.blocked_sender.batch_create",
result: result,
request: client.RawApiRequest{Params: map[string]interface{}{
"keyword": "cache-cli@example.test",
}},
},
{
name: "no keyword",
method: "user_mailbox.blocked_sender.list",
result: result,
request: client.RawApiRequest{Params: map[string]interface{}{
"user_mailbox_id": "me",
}},
},
{
name: "empty keyword",
method: "user_mailbox.allow_sender.list",
result: result,
request: client.RawApiRequest{Params: map[string]interface{}{
"keyword": " ",
}},
},
{
name: "non string keyword",
method: "user_mailbox.allow_sender.list",
result: result,
request: client.RawApiRequest{Params: map[string]interface{}{
"keyword": 123,
}},
},
{
name: "wrong code",
method: "user_mailbox.allow_sender.list",
result: map[string]interface{}{"code": 500, "msg": "[15190000] ErrCacheEmpty"},
request: client.RawApiRequest{Params: map[string]interface{}{
"keyword": "cache-cli@example.test",
}},
},
{
name: "missing pb code marker",
method: "user_mailbox.allow_sender.list",
result: map[string]interface{}{"code": 456, "msg": "ErrCacheEmpty"},
request: client.RawApiRequest{Params: map[string]interface{}{
"keyword": "cache-cli@example.test",
}},
},
{
name: "missing cache marker",
method: "user_mailbox.allow_sender.list",
result: map[string]interface{}{"code": 456, "msg": "[15190000] other error"},
request: client.RawApiRequest{Params: map[string]interface{}{
"keyword": "cache-cli@example.test",
}},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
opts := &ServiceMethodOptions{Method: meta.FromMap(map[string]interface{}{
"id": tc.method,
"httpMethod": "GET",
})}
err := classifyServiceAPIError(base, opts, tc.request)(tc.result, core.AsUser)
p, ok := errs.ProblemOf(err)
if !ok {
t.Fatalf("ProblemOf returned !ok for %T", err)
}
if tc.name == "allow sender list positive" {
if p.Subtype != errs.SubtypeUserAllowBlockCachePreparing {
t.Fatalf("Subtype = %q, want %q", p.Subtype, errs.SubtypeUserAllowBlockCachePreparing)
}
return
}
if p.Subtype == errs.SubtypeUserAllowBlockCachePreparing {
t.Fatalf("Subtype = %q, want generic API classification outside scoped keyword search", p.Subtype)
}
if p.Hint == userAllowBlockCachePreparingHint {
t.Fatalf("Hint = %q, want no cache-preparing hint outside scoped keyword search", p.Hint)
}
})
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

// ── dry-run / buildServiceRequest ──

func TestServiceMethod_DryRun_PathParam(t *testing.T) {
Expand Down
3 changes: 3 additions & 0 deletions errs/subtypes.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ const (
SubtypeServerError Subtype = "server_error" // upstream server-side transient error (HTTP 5xx alignment, retryable)
SubtypeQuotaExceeded Subtype = "quota_exceeded" // resource quota / collection size limit reached (assignees, followers, members, etc.)
SubtypeAlreadyExists Subtype = "already_exists" // idempotency violation: resource already exists in target state
// SubtypeUserAllowBlockCachePreparing preserves the mail OpenAPI business
// code spelling for user allow/block sender keyword search cache warm-up.
SubtypeUserAllowBlockCachePreparing Subtype = "UserAllowBlockCachePreparing"
)

// CategoryPolicy subtypes (security-policy envelope shape)
Expand Down
53 changes: 52 additions & 1 deletion internal/registry/remote.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,12 +314,63 @@ func shouldRefresh(cm CacheMeta) bool {
}

// overlayMergedServices merges remote services into the in-memory map.
// Remote entries override embedded entries with the same name.
// Remote entries override embedded entries with the same name, but a remote
// service snapshot must not delete resources or methods compiled into this
// binary. That keeps MR-built commands visible even when the published remote
// cache has a newer version string but an older resource set.
func overlayMergedServices(reg *MergedRegistry) {
for _, svc := range reg.Services {
if svc.Name == "" {
continue
}
if existing, ok := mergedServices[svc.Name]; ok {
mergedServices[svc.Name] = mergeService(existing, svc)
continue
}
mergedServices[svc.Name] = svc
}
}

func mergeService(base, overlay meta.Service) meta.Service {
merged := overlay
merged.Resources = mergeResourceMaps(base.Resources, overlay.Resources)
return merged
}

func mergeResourceMaps(base, overlay map[string]meta.Resource) map[string]meta.Resource {
if len(base) == 0 {
return overlay
}
if len(overlay) == 0 {
return base
}
merged := make(map[string]meta.Resource, len(base)+len(overlay))
for name, resource := range base {
merged[name] = resource
}
for name, resource := range overlay {
if existing, ok := merged[name]; ok {
resource.Methods = mergeMethodMaps(existing.Methods, resource.Methods)
resource.Resources = mergeResourceMaps(existing.Resources, resource.Resources)
}
merged[name] = resource
}
return merged
}

func mergeMethodMaps(base, overlay map[string]meta.Method) map[string]meta.Method {
if len(base) == 0 {
return overlay
}
if len(overlay) == 0 {
return base
}
merged := make(map[string]meta.Method, len(base)+len(overlay))
for name, method := range base {
merged[name] = method
}
for name, method := range overlay {
merged[name] = method
}
return merged
}
Loading
Loading