Skip to content

fix: include log_id in base attachment media errors#1133

Merged
zgz2048 merged 1 commit into
larksuite:mainfrom
zgz2048:codex/base-download-logid
May 28, 2026
Merged

fix: include log_id in base attachment media errors#1133
zgz2048 merged 1 commit into
larksuite:mainfrom
zgz2048:codex/base-download-logid

Conversation

@zgz2048

@zgz2048 zgz2048 commented May 27, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • include Base attachment download x-tt-logid as error.detail.log_id on HTTP failures
  • include Drive media upload x-tt-logid as error.detail.log_id on upload_all/upload_part API failures
  • keep Base shortcut downloads on the shared SDK request path

Tests

  • go test ./shortcuts/common ./shortcuts/base
  • go vet ./...
  • go run github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.1.6 run --new-from-rev=upstream/main

Summary by CodeRabbit

  • Bug Fixes

    • Error reporting for downloads and uploads now includes request tracking IDs (log_id) in structured error details and preserves original error codes/messages where appropriate.
    • Download progress failures now report preserved progress details alongside clearer failure messages.
  • Tests

    • Added/updated tests to verify progress reporting and inclusion of tracking identifiers in error responses.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 27, 2026

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR extracts backend correlation ids (X-Tt-Logid / Request-Id) from HTTP responses and injects them as log_id into structured output.ExitError details for DoStream, Base attachment download flows, and Drive media upload error handling; tests assert the presence of detail["log_id"].

Changes

Logid Propagation in Attachment and Media Error Details

Layer / File(s) Summary
API client DoStream log_id attachment
internal/client/client.go, internal/client/client_test.go
DoStream enriches *output.ExitError returned for HTTP >=400 responses with log_id taken from X-Tt-Logid (or fallback Request-Id) via attachStreamLogID; test verifies log_id is present for a 403 response.
Base attachment download error wrapping & propagation
shortcuts/base/record_upload_attachment.go, shortcuts/base/base_execute_test.go
downloadBaseAttachment now returns the original stream error; attachmentDownloadProgressError constructs progress detail with downloaded/failed and appends nested log_id when present via baseAttachmentDownloadLogID; tests updated to stub 403 + X-Tt-Logid and assert detail["log_id"].
Drive media upload error detail enrichment
shortcuts/common/drive_media_upload.go, shortcuts/common/drive_media_upload_test.go
ParseDriveMediaUploadResponse wraps API error detail using driveMediaUploadErrorDetail, which trims apiResp.LogId() and injects log_id into the error-detail map (creating or wrapping the original detail as needed); test asserts ExitError.Detail.Detail["log_id"].

Sequence Diagram(s)

sequenceDiagram
  participant CLI as Test/Caller
  participant APIClient as APIClient.DoStream
  participant BaseDownload as downloadBaseAttachment
  participant HTTP as HTTP Response
  participant Wrapper as wrap/attach helpers
  CLI->>APIClient: request stream/download
  APIClient->>HTTP: receive response (2xx or >=400 + headers)
  alt HTTP >= 400
    APIClient->>Wrapper: create/receive ExitError
    Wrapper->>Wrapper: extract X-Tt-Logid / Request-Id
    Wrapper->>APIClient: inject Detail.Detail["log_id"]
    APIClient-->>CLI: return ExitError with log_id in detail
  else 2xx
    APIClient-->>CLI: stream data / success
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Possibly related PRs

  • larksuite/cli#887: Introduces Base attachment download/remove APIs that this PR extends by adding log_id diagnostics to error paths.

Suggested reviewers

  • kongenpei
  • timzhong1024

"🐰 I hopped through headers, sniffed a logid bright,
When downloads fail I tuck it tight,
In error maps it now will stay,
So debuggers chase the right pathway,
Hooray for traces in the night!"

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The PR description includes a clear summary and test commands, but omits the required 'Changes' section listing modifications and deviates from the template structure. Add a 'Changes' section with bullet points listing the main modifications, and reformat to match the template with proper 'Test Plan' section and 'Related Issues' link to #1122.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: including log_id in base attachment media errors across multiple error paths.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot added domain/base PR touches the base domain size/M Single-domain feat or fix with limited business impact labels May 27, 2026
@zgz2048
zgz2048 force-pushed the codex/base-download-logid branch 2 times, most recently from 46536a4 to 58e6caf Compare May 27, 2026 10:04
@github-actions github-actions Bot added size/L Large or sensitive change across domains or core paths and removed size/M Single-domain feat or fix with limited business impact labels May 27, 2026
@zgz2048 zgz2048 changed the title fix: include logid in base attachment download errors fix: include logid in base attachment media errors May 27, 2026
@zgz2048
zgz2048 marked this pull request as ready for review May 27, 2026 10:05
@github-actions

github-actions Bot commented May 27, 2026

Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

npm i -g https://pkg.pr.new/larksuite/cli/@larksuite/cli@197db82c078595834c6c8556bd0d5f75c094bfa5

🧩 Skill update

npx skills add zgz2048/cli#codex/base-download-logid -y -g

kongenpei
kongenpei previously approved these changes May 27, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with 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.

Inline comments:
In `@shortcuts/base/record_upload_attachment.go`:
- Around line 785-787: The wrapper around downloadBaseAttachmentResponse
currently rewraps every error as a network error; instead preserve
already-classified pre-request failures by returning them unchanged. Update the
error handling where downloadBaseAttachmentResponse(...) is called (the
occurrences around resp, err := downloadBaseAttachmentResponse in
record_upload_attachment.go) to check the error type first (use errors.As or a
type assertion for *output.ExitError or whatever concrete classified error type
your code uses) and if it matches return nil, err directly; only call
wrapBaseAttachmentDownloadError(err) for genuine transport/network errors. Apply
the same change to the other call site mentioned (the block around lines
831–846).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 94343a90-c1ac-44d4-a504-78c9eacb6a84

📥 Commits

Reviewing files that changed from the base of the PR and between 58e6caf and d4ac47b.

📒 Files selected for processing (4)
  • shortcuts/base/base_execute_test.go
  • shortcuts/base/record_upload_attachment.go
  • shortcuts/common/drive_media_upload.go
  • shortcuts/common/drive_media_upload_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • shortcuts/common/drive_media_upload_test.go
  • shortcuts/base/base_execute_test.go

Comment thread shortcuts/base/record_upload_attachment.go Outdated
@codecov

codecov Bot commented May 27, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 63.04348% with 17 lines in your changes missing coverage. Please review.
✅ Project coverage is 68.63%. Comparing base (30327ab) to head (197db82).
⚠️ Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
internal/client/client.go 40.00% 6 Missing and 3 partials ⚠️
shortcuts/base/record_upload_attachment.go 75.00% 2 Missing and 2 partials ⚠️
shortcuts/common/drive_media_upload.go 73.33% 3 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1133      +/-   ##
==========================================
+ Coverage   68.25%   68.63%   +0.37%     
==========================================
  Files         618      625       +7     
  Lines       57305    58386    +1081     
==========================================
+ Hits        39116    40071     +955     
- Misses      14953    15027      +74     
- Partials     3236     3288      +52     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@zgz2048
zgz2048 force-pushed the codex/base-download-logid branch from d4ac47b to 14a236b Compare May 27, 2026 10:24
@zgz2048 zgz2048 changed the title fix: include logid in base attachment media errors fix: include log_id in base attachment media errors May 27, 2026
@zgz2048
zgz2048 force-pushed the codex/base-download-logid branch 2 times, most recently from faf1c24 to 15dd833 Compare May 27, 2026 10:37

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
shortcuts/base/record_upload_attachment.go (1)

839-847: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Preserve the full structured error payload when rewrapping download failures.

This wrapper keeps only a subset of ErrDetail fields, so downstream consumers can lose existing structured metadata on classified errors.

Suggested fix
 return &output.ExitError{
 	Code: exitErr.Code,
+	Raw:  exitErr.Raw,
 	Detail: &output.ErrDetail{
-		Type:    exitErr.Detail.Type,
-		Code:    exitErr.Detail.Code,
-		Message: fmt.Sprintf("download failed: %v", err),
-		Hint:    exitErr.Detail.Hint,
-		Detail:  exitErr.Detail.Detail,
+		Type:       exitErr.Detail.Type,
+		Code:       exitErr.Detail.Code,
+		Message:    fmt.Sprintf("download failed: %v", err),
+		Hint:       exitErr.Detail.Hint,
+		ConsoleURL: exitErr.Detail.ConsoleURL,
+		Risk:       exitErr.Detail.Risk,
+		Detail:     exitErr.Detail.Detail,
 	},
 	Err: err,
 }
🤖 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 `@shortcuts/base/record_upload_attachment.go` around lines 839 - 847, The
current rewrap builds a new output.ErrDetail manually and drops any extra fields
from the original exitErr.Detail; update the Download failure rewrap to preserve
the full structured payload by cloning exitErr.Detail (check for nil), then only
update or prepend the Message (e.g., set newDetail.Message =
fmt.Sprintf("download failed: %v", err) or combine with existing message) and
assign Detail: &newDetail on the returned *output.ExitError (keeping
ExitError.Code as exitErr.Code); reference the existing symbols exitErr, err,
output.ExitError and output.ErrDetail when making this change.
🤖 Prompt for all review comments with 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.

Inline comments:
In `@internal/client/client_test.go`:
- Around line 431-443: The test TestDoStream_HTTPErrorIncludesLogID is not using
the standard test factory or isolating config state; replace the manual setup
with cmdutil.TestFactory(t, config) to create the test factory and call
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir()) before creating runtime/client
state, then use that factory to obtain the runtime/clients used by APIClient (or
pass the factory's config) so the test uses the standard test harness instead of
constructing APIClient directly; update references around the APIClient
instantiation in TestDoStream_HTTPErrorIncludesLogID to use the factory-created
config/runtime.

---

Duplicate comments:
In `@shortcuts/base/record_upload_attachment.go`:
- Around line 839-847: The current rewrap builds a new output.ErrDetail manually
and drops any extra fields from the original exitErr.Detail; update the Download
failure rewrap to preserve the full structured payload by cloning exitErr.Detail
(check for nil), then only update or prepend the Message (e.g., set
newDetail.Message = fmt.Sprintf("download failed: %v", err) or combine with
existing message) and assign Detail: &newDetail on the returned
*output.ExitError (keeping ExitError.Code as exitErr.Code); reference the
existing symbols exitErr, err, output.ExitError and output.ErrDetail when making
this change.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c7e51677-1e89-4944-bc2b-8c0eb82c6c81

📥 Commits

Reviewing files that changed from the base of the PR and between 14a236b and faf1c24.

📒 Files selected for processing (6)
  • internal/client/client.go
  • internal/client/client_test.go
  • shortcuts/base/base_execute_test.go
  • shortcuts/base/record_upload_attachment.go
  • shortcuts/common/drive_media_upload.go
  • shortcuts/common/drive_media_upload_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • shortcuts/common/drive_media_upload.go
  • shortcuts/base/base_execute_test.go
  • shortcuts/common/drive_media_upload_test.go

Comment thread internal/client/client_test.go Outdated
@zgz2048
zgz2048 force-pushed the codex/base-download-logid branch from 15dd833 to 197db82 Compare May 28, 2026 03:04
@zgz2048
zgz2048 merged commit b91f6a2 into larksuite:main May 28, 2026
17 checks passed
tuxedomm pushed a commit to zhumiaoxin/cli that referenced this pull request Jun 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

domain/base PR touches the base domain size/L Large or sensitive change across domains or core paths

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants