Skip to content

feat(httpweb): negotiate DTP2 capability with JWT dtp claim - #859

Open
re2zero wants to merge 1 commit into
develop/snipefrom
feat/v25-pr5-dtp2-negotiation
Open

re2zero wants to merge 1 commit into
develop/snipefrom
feat/v25-pr5-dtp2-negotiation

Conversation

@re2zero

@re2zero re2zero commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

PMS: TASK-398999
multica: V-8994
前置: PR4(V-8993)已合并
验证: lib_logic_tests - TokenCacheTest.:HttpWebIntegrationTest. 全部通过(23/23)

文件范围

  • src/lib/common/httpweb/fileclient.cpp
  • src/lib/common/httpweb/fileserver.cpp
  • src/lib/common/httpweb/tokencache.cpp
  • src/lib/common/httpweb/tokencache.h
  • tests/logic/httpweb_fork_test.cpp
  • tests/logic/tokencache_test.cpp

Summary by Sourcery

Enable capability-aware HTTPWeb streaming with JWT-based DTP2 negotiation and seamless legacy fallback.

New Features:

  • Add DTP2 capability negotiation to HTTPWeb JWTs, including protocol version and supported codecs.
  • Select the best mutually supported stream codec and skip streaming when the peer does not advertise DTP2 support.

Bug Fixes:

  • Fall back to the legacy HTTPWeb transfer protocol when streaming is unavailable or the server stream endpoint returns disabled status.

Enhancements:

  • Add rollout controls for advertising DTP2 tokens and enabling the server stream endpoint without requiring a binary downgrade.
  • Parse optional DTP capability claims safely while preserving compatibility with legacy and malformed tokens.

Tests:

  • Add token-cache and HTTPWeb integration coverage for DTP2 claims, legacy compatibility, codec negotiation, and stream-disable fallback scenarios.

@deepin-ci-robot

Copy link
Copy Markdown

Skipping CI for Draft Pull Request.
If you want CI signal for your change, please convert it to an actual PR.
You can still manually trigger a test run with /test all

@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: re2zero

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@github-actions

Copy link
Copy Markdown
  • 检测到敏感词unset变动
详情
    {
    "unset": {
        "tests/logic/httpweb_fork_test.cpp": {
            "b": [
                "        ::unsetenv(\"DDE_COOPERATION_HTTPWEB_TOKEN_DTP\");",
                "        ::unsetenv(\"DDE_COOPERATION_HTTPWEB_STREAM\");",
                "        ::unsetenv(\"DDE_COOPERATION_HTTPWEB_SERVER_STREAM\");",
                "    ::unsetenv(\"DDE_COOPERATION_HTTPWEB_TOKEN_DTP\");",
                "    ::unsetenv(\"DDE_COOPERATION_HTTPWEB_STREAM\");",
                "    ::unsetenv(\"DDE_COOPERATION_HTTPWEB_SERVER_STREAM\");",
                "    ::unsetenv(\"DDE_COOPERATION_HTTPWEB_SERVER_STREAM\");"
            ]
        },
        "tests/logic/tokencache_test.cpp": {
            "b": [
                "        ::unsetenv(\"DDE_COOPERATION_HTTPWEB_TOKEN_DTP\");",
                "    ::unsetenv(\"DDE_COOPERATION_HTTPWEB_TOKEN_DTP\");"
            ]
        }
    }
}

1. 在新签发的 token 中声明 DTP2 协议版本与编解码器列表;
   客户端解析该 claim 并据此协商传输路径。
2. 旧 token(无 dtp claim)或旧客户端直接跳过流式路径,
   回退到逐文件传输,保证向后兼容。
3. 新增 server/client 侧 rollout 开关,
   覆盖 legacy-token、legacy-client 和 server-disabled 三类回退路径。

Advertise protocol version and codec list in new tokens, parse the claim on
the client, and skip the stream path entirely for legacy tokens. Add
server/client rollout switches and cover legacy-token, legacy-client and
server-disabled fallback paths.

Influence:
1. 对端 token 携带 dtp claim 时使用协商后的编解码器进行流式传输;
2. 旧 token 或流式端点被禁用时回退到逐文件协议,不影响现有功能。

Log: negotiate DTP2 capability with JWT dtp claim
PMS: TASK-398999
multica: V-8994
@re2zero
re2zero force-pushed the feat/v25-pr5-dtp2-negotiation branch from 0124b75 to 6fa2007 Compare November 24, 2026 12:50
@re2zero
re2zero marked this pull request as ready for review November 24, 2026 13:03
@sourcery-ai

sourcery-ai Bot commented Nov 24, 2026

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Define the parsed DTP capability structure that callers use to decide whether streaming is supported.

  • src/lib/common/httpweb/tokencache.h L16, L23-33

API

Expose token generation with optional DTP advertisement and a non-throwing capability lookup.

  • src/lib/common/httpweb/tokencache.h L34-36, L42-45

Uses of the API

Use the token capability to skip streaming for legacy peers and select a codec the server advertises.

  • src/lib/common/httpweb/fileclient.cpp L63-72, L645-649 (+2 small edits)

Implementation

Generate JWT DTP claims and parse their version and codec list while treating absent or malformed claims as unsupported.

  • src/lib/common/httpweb/tokencache.cpp L18-39, L106-115, L212-242 (+1 small edits)

Reject stream requests when the endpoint is disabled and issue tokens without a DTP claim in that mode.

  • src/lib/common/httpweb/fileserver.cpp L533-536, L781-783

Configuration

Add the server-side environment switch that controls stream endpoint availability and DTP advertisement.

  • src/lib/common/httpweb/fileserver.cpp L20, L30-37

Tests

Exercise legacy-token, legacy-client, and server-disabled fallback behavior in HTTP integration tests.

  • tests/logic/httpweb_fork_test.cpp L17, L68-70, L130-286

Test DTP claim creation, omission, compatibility mode, and handling of invalid tokens.

  • tests/logic/tokencache_test.cpp L8-10, L16-20, L101-138

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai 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.

Hey - I've found 5 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/lib/common/httpweb/tokencache.cpp" line_range="227-228" />
<code_context>
+
+        const auto &object = value.get<picojson::object>();
+        auto version = object.find("v");
+        if (version != object.end() && version->second.is<double>())
+            capability.version = static_cast<int>(version->second.get<double>());
+
+        auto codecs = object.find("codecs");
</code_context>
<issue_to_address>
**Malformed versions trigger undefined behavior**

When the `dtp.v` claim contains a number outside the `int` range, `getDtpFromToken()` casts that number to `int` without checking its range, triggering undefined behavior while parsing the optional capability claim and producing an unpredictable stream decision.

Check that the parsed version is within the `int` range before casting, and handle out-of-range claims without performing the cast.
</issue_to_address>

### Comment 2
<location path="src/lib/common/httpweb/tokencache.h" line_range="31" />
<code_context>
+        int version {0};
+        std::vector<std::string> codecs;
+
+        bool supportsStream() const { return present && version >= 2; }
+    };
+
</code_context>
<issue_to_address>
**Future versions fail instead of falling back**

When a peer advertises a version above 2 whose stream framing is not backward-compatible, `supportsStream()` accepts the future version, so `downloadStream()` attempts the DTP2 stream protocol; when the preamble parser rejects or misreads the incompatible stream, the consumer reports an error and the transfer ends instead of falling back to legacy transfer.

Make `supportsStream()` accept only protocol versions this client implements, rather than every version greater than or equal to 2.
</issue_to_address>

### Comment 3
<location path="src/lib/common/httpweb/fileclient.cpp" line_range="648" />
<code_context>
+    // Tokens issued before DTP2 (or tokens generated with the compatibility
+    // switch) carry no `dtp` claim: go straight to legacy instead of paying a
+    // failed stream request.
+    if (!TokenCache::GetInstance().getDtpFromToken(_token).supportsStream())
+        return StreamAttempt::Fallback;

</code_context>
<issue_to_address>
**Concurrent downloads corrupt resume state**

When two FileClient jobs use the same token and selection concurrently, especially with different save directories, both clients load and save the same checkpoint, whose path is derived from token and name but not the destination; one client can overwrite or clear the other’s checkpoint, leaving the other to resume against the wrong root or restart its transfer.

Make checkpoint state destination-specific and synchronize updates and clears for each checkpoint, or otherwise isolate concurrent transfers.
</issue_to_address>

### Comment 4
<location path="src/lib/common/httpweb/fileclient.cpp" line_range="70" />
<code_context>
+            != capability.codecs.end();
+    if (serverZstd && dtp::codecSupported(dtp::Codec::Zstd))
+        return dtp::Codec::Zstd;
+    return dtp::Codec::Deflate;
+}
+
</code_context>
<issue_to_address>
**Unadvertised codec causes failed request**

When a valid v2 token advertises only zstd and the client lacks zstd support, `negotiatedStreamCodec()` falls back to Deflate even though the peer did not advertise it, so the server rejects the stream request and the client pays for a failed request before falling back to legacy transfer.

Do not select Deflate unless the token advertises it, and use legacy transfer when no advertised codec is supported.
</issue_to_address>

### Comment 5
<location path="tests/logic/httpweb_fork_test.cpp" line_range="178-179" />
<code_context>
+    // path would have used one download request and zero info requests.
+    EXPECT_GE(counters.infoRequests, 1u);
+    EXPECT_GE(counters.downloadRequests, 2u);
+    EXPECT_TRUE(std::filesystem::exists(cliDir / "files" / "test.txt"));
+    EXPECT_TRUE(std::filesystem::exists(cliDir / "files" / "second.txt"));
+}
+
</code_context>
<issue_to_address>
**Empty downloads still pass**

When the legacy response completes without delivering file bytes, `LegacyTokenUsesLegacyProtocol`, `StreamDisabledByEnvUsesLegacyProtocol`, and `ServerStreamDisabledFallsBackToLegacy` accept empty files as successful downloads: their existence assertions pass even when no payload was written.

Read each downloaded file and assert its expected contents, as `FullDownloadRoundTrip` does.

Also at `tests/logic/httpweb_fork_test.cpp:227-228`, `tests/logic/httpweb_fork_test.cpp:285-286`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment on lines +227 to +228
if (version != object.end() && version->second.is<double>())
capability.version = static_cast<int>(version->second.get<double>());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Malformed versions trigger undefined behavior

When the dtp.v claim contains a number outside the int range, getDtpFromToken() casts that number to int without checking its range, triggering undefined behavior while parsing the optional capability claim and producing an unpredictable stream decision.

Check that the parsed version is within the int range before casting, and handle out-of-range claims without performing the cast.

Prompt for AI agents
In `src/lib/common/httpweb/tokencache.cpp` at lines 227-228:

**Malformed versions trigger undefined behavior**

When the `dtp.v` claim contains a number outside the `int` range, `getDtpFromToken()` casts that number to `int` without checking its range, triggering undefined behavior while parsing the optional capability claim and producing an unpredictable stream decision.

Check that the parsed version is within the `int` range before casting, and handle out-of-range claims without performing the cast.

int version {0};
std::vector<std::string> codecs;

bool supportsStream() const { return present && version >= 2; }

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Future versions fail instead of falling back

When a peer advertises a version above 2 whose stream framing is not backward-compatible, supportsStream() accepts the future version, so downloadStream() attempts the DTP2 stream protocol; when the preamble parser rejects or misreads the incompatible stream, the consumer reports an error and the transfer ends instead of falling back to legacy transfer.

Make supportsStream() accept only protocol versions this client implements, rather than every version greater than or equal to 2.

Prompt for AI agents
In `src/lib/common/httpweb/tokencache.h` at line 31:

**Future versions fail instead of falling back**

When a peer advertises a version above 2 whose stream framing is not backward-compatible, `supportsStream()` accepts the future version, so `downloadStream()` attempts the DTP2 stream protocol; when the preamble parser rejects or misreads the incompatible stream, the consumer reports an error and the transfer ends instead of falling back to legacy transfer.

Make `supportsStream()` accept only protocol versions this client implements, rather than every version greater than or equal to 2.

// Tokens issued before DTP2 (or tokens generated with the compatibility
// switch) carry no `dtp` claim: go straight to legacy instead of paying a
// failed stream request.
if (!TokenCache::GetInstance().getDtpFromToken(_token).supportsStream())

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Concurrent downloads corrupt resume state

When two FileClient jobs use the same token and selection concurrently, especially with different save directories, both clients load and save the same checkpoint, whose path is derived from token and name but not the destination; one client can overwrite or clear the other’s checkpoint, leaving the other to resume against the wrong root or restart its transfer.

Make checkpoint state destination-specific and synchronize updates and clears for each checkpoint, or otherwise isolate concurrent transfers.

Prompt for AI agents
In `src/lib/common/httpweb/fileclient.cpp` at line 648:

**Concurrent downloads corrupt resume state**

When two FileClient jobs use the same token and selection concurrently, especially with different save directories, both clients load and save the same checkpoint, whose path is derived from token and name but not the destination; one client can overwrite or clear the other’s checkpoint, leaving the other to resume against the wrong root or restart its transfer.

Make checkpoint state destination-specific and synchronize updates and clears for each checkpoint, or otherwise isolate concurrent transfers.

!= capability.codecs.end();
if (serverZstd && dtp::codecSupported(dtp::Codec::Zstd))
return dtp::Codec::Zstd;
return dtp::Codec::Deflate;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Unadvertised codec causes failed request

When a valid v2 token advertises only zstd and the client lacks zstd support, negotiatedStreamCodec() falls back to Deflate even though the peer did not advertise it, so the server rejects the stream request and the client pays for a failed request before falling back to legacy transfer.

Do not select Deflate unless the token advertises it, and use legacy transfer when no advertised codec is supported.

Prompt for AI agents
In `src/lib/common/httpweb/fileclient.cpp` at line 70:

**Unadvertised codec causes failed request**

When a valid v2 token advertises only zstd and the client lacks zstd support, `negotiatedStreamCodec()` falls back to Deflate even though the peer did not advertise it, so the server rejects the stream request and the client pays for a failed request before falling back to legacy transfer.

Do not select Deflate unless the token advertises it, and use legacy transfer when no advertised codec is supported.

Comment on lines +178 to +179
EXPECT_TRUE(std::filesystem::exists(cliDir / "files" / "test.txt"));
EXPECT_TRUE(std::filesystem::exists(cliDir / "files" / "second.txt"));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 Medium · Empty downloads still pass

When the legacy response completes without delivering file bytes, LegacyTokenUsesLegacyProtocol, StreamDisabledByEnvUsesLegacyProtocol, and ServerStreamDisabledFallsBackToLegacy accept empty files as successful downloads: their existence assertions pass even when no payload was written.

Read each downloaded file and assert its expected contents, as FullDownloadRoundTrip does.

Also at tests/logic/httpweb_fork_test.cpp:227-228, tests/logic/httpweb_fork_test.cpp:285-286.

Prompt for AI agents
In `tests/logic/httpweb_fork_test.cpp` at lines 178-179:

**Empty downloads still pass**

When the legacy response completes without delivering file bytes, `LegacyTokenUsesLegacyProtocol`, `StreamDisabledByEnvUsesLegacyProtocol`, and `ServerStreamDisabledFallsBackToLegacy` accept empty files as successful downloads: their existence assertions pass even when no payload was written.

Read each downloaded file and assert its expected contents, as `FullDownloadRoundTrip` does.

Also at `tests/logic/httpweb_fork_test.cpp:227-228`, `tests/logic/httpweb_fork_test.cpp:285-286`.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants