Skip to content

feat(markdown): harden create upload failures#1325

Merged
fangshuyu-768 merged 2 commits into
mainfrom
feat/markdown-create-upload-hardening
Jun 8, 2026
Merged

feat(markdown): harden create upload failures#1325
fangshuyu-768 merged 2 commits into
mainfrom
feat/markdown-create-upload-hardening

Conversation

@fangshuyu-768

@fangshuyu-768 fangshuyu-768 commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • switch markdown upload helpers from legacy API parsing to typed error classification
  • retry only transient markdown upload failures (upload_all, multipart prepare/part, finish, and metadata lookup)
  • add upload-specific hints for scope, access, target-not-found, and document version-limit failures

Testing

  • go test ./shortcuts/markdown ./shortcuts/common
  • go test ./... (fails on current main baseline in cmd/schema: Unknown service: im)

Summary by CodeRabbit

  • New Features
    • Unified single- and multipart markdown upload flow with shared retry/backoff and clearer retry logging.
  • Bug Fixes
    • Stricter validation of upload responses; missing fields now surface as consistent internal errors with action-prefixed messages.
    • Improved handling for overwrite and metadata lookup failures with clearer, actionable hints.
  • Tests
    • Expanded unit tests covering retry behavior, error classification, hinting, and upload edge cases.

@coderabbitai

coderabbitai Bot commented Jun 8, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6671e26b-330d-41da-a206-4dd7f6d68609

📥 Commits

Reviewing files that changed from the base of the PR and between bbfcab6 and ca8f404.

📒 Files selected for processing (2)
  • shortcuts/markdown/helpers.go
  • shortcuts/markdown/markdown_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • shortcuts/markdown/markdown_test.go
  • shortcuts/markdown/helpers.go

📝 Walkthrough

Walkthrough

Markdown upload helpers now use typed API calls with retry wrappers and backoff. Single- and multipart flows share a callback-based reader lifecycle; multipart parts rebuild form-data per retry. Validation now returns internal invalid-response errors for missing fields. Tests assert typed-problem mapping and retry behavior.

Changes

Markdown Upload Retry & Typed API Flow

Layer / File(s) Summary
Retry infrastructure, constants, and error context helpers
shortcuts/markdown/helpers.go
Adds backoff schedule, action name constants, and core retry helpers (withMarkdownUploadRetryResult, withMarkdownUploadRetryData, withMarkdownUploadRetryVoid) plus markdownUploadProblem and hint-appending logic.
Single-part upload refactoring to callback-based reader
shortcuts/markdown/helpers.go
Single-part upload paths refactored to accept openReader() io.ReadCloser and route upload_all through retry-result wrapper with typed API response classification.
Multipart prepare, orchestration, and parts migration
shortcuts/markdown/helpers.go
upload_prepare, per-chunk upload_part, and upload_finish now use CallAPITyped wrapped by retry helpers; multipart orchestration opens/defers the reader, rebuilds form-data per part retry, and maps classified failures. Invalid session parsing returns internal invalid-response errors.
Upload result validation tightening and file-name fetch
shortcuts/markdown/helpers.go
parseMarkdownUploadResult returns internal invalid-response errors when file_token (or overwrite version) is missing. fetchMarkdownFileName migrated to typed API calling wrapped by retry-data helper.
Test coverage for error handling and retry behavior
shortcuts/markdown/markdown_test.go
Imports errs. Adds tests verifying typed-problem conversion for upload_all scope-denial and metas/batch_query metadata lookup failures, plus rate-limit retry/log assertions and unit tests covering retry helper branches and hint appending.

Sequence Diagram(s)

sequenceDiagram
  participant CLI as CLI
  participant Runtime as runtime.CallAPITyped / retry helpers
  participant API as Remote API
  CLI->>Runtime: upload_prepare (withMarkdownUploadRetryData)
  Runtime->>API: upload_prepare request
  API-->>Runtime: response (classified)
  CLI->>Runtime: upload_part (withMarkdownUploadRetryVoid) [per chunk]
  Runtime->>API: upload_part request (form-data rebuilt each retry)
  API-->>Runtime: part response (classified)
  CLI->>Runtime: upload_finish (withMarkdownUploadRetryData)
  Runtime->>API: upload_finish request
  API-->>Runtime: finish response (file_token)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested labels

domain/ccm

Suggested reviewers

  • wittam-01
  • SunPeiYang996

Poem

🐰 I nibble bytes and stitch each part with care,
Retries bounce softly through backoffs in the air,
Typed problems hum where missing tokens hide,
Readers close gently, no leaks left inside,
A rabbit cheers uploads now steady and fair.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

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.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(markdown): harden create upload failures' is clear, specific, and accurately reflects the main change: improving error handling and retry logic for markdown upload operations.
Description check ✅ Passed The description covers the key changes (typed error classification, retry logic, hints), provides a test plan with specific commands, and matches the repository template structure.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/markdown-create-upload-hardening

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 the size/M Single-domain feat or fix with limited business impact label Jun 8, 2026
@codecov

codecov Bot commented Jun 8, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 85.97561% with 23 lines in your changes missing coverage. Please review.
✅ Project coverage is 71.47%. Comparing base (add079e) to head (ca8f404).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
shortcuts/markdown/helpers.go 85.97% 16 Missing and 7 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1325      +/-   ##
==========================================
+ Coverage   71.42%   71.47%   +0.04%     
==========================================
  Files         688      688              
  Lines       65313    65477     +164     
==========================================
+ Hits        46653    46801     +148     
- Misses      15021    15031      +10     
- Partials     3639     3645       +6     

☔ View full report in Codecov by Harness.
📢 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.

@github-actions

github-actions Bot commented Jun 8, 2026

Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

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

🧩 Skill update

npx skills add larksuite/cli#feat/markdown-create-upload-hardening -y -g

@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: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
shortcuts/markdown/helpers.go (1)

530-546: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Keep impossible upload_prepare chunk plans on the typed invalid-response path.

The earlier prepare parser now returns errs.NewInternalError(...), but these later validations still fall back to legacy output.Errorf(...). Impossible block_num / block_size values are the same invalid-response class, so this reintroduces the old untyped path for a subset of malformed prepare responses.

Suggested change
 	if session.BlockNum != expectedBlocks {
-		return output.Errorf(
-			output.ExitAPI,
-			"api_error",
+		return errs.NewInternalError(
+			errs.SubtypeInvalidResponse,
 			"upload_prepare returned inconsistent chunk plan: block_size=%d, block_num=%d, expected_block_num=%d, payload_size=%d",
 			session.BlockSize,
 			session.BlockNum,
 			expectedBlocks,
 			payloadSize,
 		)
 	}
@@
 	if session.BlockSize > maxInt {
-		return output.Errorf(output.ExitAPI, "api_error", "upload prepare failed: invalid block_size returned")
+		return errs.NewInternalError(errs.SubtypeInvalidResponse, "upload_prepare returned invalid block_size: %d", session.BlockSize)
 	}

Based on the PR objective to move malformed upload responses onto typed internal-error handling.

🤖 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/markdown/helpers.go` around lines 530 - 546, The validations after
computing expectedBlocks currently return legacy untyped errors via
output.Errorf (in the checks comparing session.BlockNum to expectedBlocks and
session.BlockSize to maxInt); change both to return the typed internal-error
path used earlier (errs.NewInternalError or the package's internal error
constructor) with the same diagnostic message text so malformed upload_prepare
responses are classified as typed internal errors rather than the old
output.Errorf path. Target the checks referencing session.BlockSize,
session.BlockNum, expectedBlocks, payloadSize and maxInt and replace the
output.Errorf returns with errs.NewInternalError(...) (or the project's
internal-error helper) preserving the message content.
🤖 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/markdown/helpers.go`:
- Around line 450-455: The parseMarkdownUploadResult and
parseMarkdownMultipartSession call sites must wrap any returned parse errors
with the step-specific markdownUploadProblem so the action-prefixed message is
preserved; change the return paths that currently return
parseMarkdownUploadResult(...) or parseMarkdownMultipartSession(...) directly to
detect a non-nil error result and return markdownUploadResult{} (or the
appropriate zero) together with markdownUploadProblem(err, <action>), using
markdownUploadAllAction for upload_all call sites, markdownUploadPrepareAction
for upload_prepare, and markdownUploadFinishAction for upload_finish so
malformed-success parse errors include the correct action context.
- Around line 713-725: In markdownUploadProblem, add a switch branch for the
scope-denied upload error(s) so scope failures get an upload-specific hint:
locate the switch on p.Code inside markdownUploadProblem and add a case for the
scope-denied error code(s) used by your system (the same code(s) used elsewhere
to indicate missing scopes), and call appendMarkdownProblemHint(err, "The
current token or identity lacks the required document upload scope/capability —
grant the document upload scope or use a token with the appropriate permissions
and retry.") so scope-denied errors receive the same contextual guidance as the
other cases; keep the existing p.Message prefixing behavior and use
appendMarkdownProblemHint as in the other cases.

---

Outside diff comments:
In `@shortcuts/markdown/helpers.go`:
- Around line 530-546: The validations after computing expectedBlocks currently
return legacy untyped errors via output.Errorf (in the checks comparing
session.BlockNum to expectedBlocks and session.BlockSize to maxInt); change both
to return the typed internal-error path used earlier (errs.NewInternalError or
the package's internal error constructor) with the same diagnostic message text
so malformed upload_prepare responses are classified as typed internal errors
rather than the old output.Errorf path. Target the checks referencing
session.BlockSize, session.BlockNum, expectedBlocks, payloadSize and maxInt and
replace the output.Errorf returns with errs.NewInternalError(...) (or the
project's internal-error helper) preserving the message content.
🪄 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: 9f9cfd84-d658-4b64-80ff-16f352a14027

📥 Commits

Reviewing files that changed from the base of the PR and between 281cdbd and 937a8c1.

📒 Files selected for processing (2)
  • shortcuts/markdown/helpers.go
  • shortcuts/markdown/markdown_test.go

Comment thread shortcuts/markdown/helpers.go
Comment thread shortcuts/markdown/helpers.go
@fangshuyu-768 fangshuyu-768 force-pushed the feat/markdown-create-upload-hardening branch from 937a8c1 to bbfcab6 Compare June 8, 2026 09:38
@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 Jun 8, 2026
@fangshuyu-768 fangshuyu-768 merged commit 99ceb22 into main Jun 8, 2026
21 checks passed
@fangshuyu-768 fangshuyu-768 deleted the feat/markdown-create-upload-hardening branch June 8, 2026 10:17
SunPeiYang996 pushed a commit that referenced this pull request Jun 8, 2026
* feat(markdown): harden create upload failures

* test(markdown): address AI review follow-ups
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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