Skip to content

feat(router): add Console UI and E2E coverage - #1555

Open
xiaobaicai66695 wants to merge 23 commits into
apache:developfrom
xiaobaicai66695:feat/affinity-script-frontend
Open

xiaobaicai66695 wants to merge 23 commits into
apache:developfrom
xiaobaicai66695:feat/affinity-script-frontend

Conversation

@xiaobaicai66695

@xiaobaicai66695 xiaobaicai66695 commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Scope

Consolidates the Console UI in #1555 with the E2E coverage from #1556. This branch is intentionally stacked on #1553.

  • Adds Affinity Rule and Script Rule traffic views, API clients, and YAML editor coverage.
  • Adds a standalone Go 1.25 / Dubbo-Go v3.3.2 E2E module and Make target.
  • Runs real Admin runtime authentication and public Console HTTP APIs rather than calling services directly.
  • Verifies create, update, and delete through Console API → governor → ZooKeeper/Nacos → discovery/store → Dubbo-Go RouterChain.

Merge order

  1. Merge feat(router): add affinity and script rule management #1553 first.
  2. Rebase feat(router): add Console UI and E2E coverage #1555 onto the updated develop branch after feat(router): add affinity and script rule management #1553 merges. Until then, this PR includes feat(router): add affinity and script rule management #1553's backend commits in its diff; after rebasing, the diff should contain only the UI and E2E changes.

Verification

  • go test ./...
  • go test -modfile ./go.router-e2e.mod -mod=mod -tags=e2e -count=1 ./e2e/router-rule-chain
    • passed against local ZooKeeper and Nacos containers
  • vitest run src/views/traffic/_shared/RouterRuleYamlEditor.spec.ts
  • vite build

The E2E command accepts DUBBO_ADMIN_E2E_ZK_ADDR and DUBBO_ADMIN_E2E_NACOS_ADDR as either host:port or complete URLs.

Supersedes #1556.

@sonarqubecloud

Copy link
Copy Markdown

@xiaobaicai66695
xiaobaicai66695 force-pushed the feat/affinity-script-frontend branch from da159e6 to 024e0e9 Compare October 19, 2026 06:05
@xiaobaicai66695 xiaobaicai66695 changed the title feat(frontend): manage affinity and script router rules feat(router): add Console UI and E2E coverage Oct 19, 2026
@xiaobaicai66695
xiaobaicai66695 force-pushed the feat/affinity-script-frontend branch from c391449 to 51afd88 Compare October 21, 2026 08:42

@AlexStocks AlexStocks 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.

结论:Draft 阶段,UI 部分没有发现阻断问题

当前 Base 为 develop@f1c3f3a7,但分支是基于 #1553 堆叠的,所以比较 develop...head 会包含 #1553 的 25 个后端文件(合计 43 个文件)。真正属于本 PR 的增量是 ui-vue3/src/views/traffic/**、ui-vue3/src/api/service/traffic.ts、i18n、路由,以及独立的 E2E 模块。

已核对

  • 没有引入 v-html、innerHTML、eval、localStorage 等常见风险点;YAML 编辑器走的是原有组件封装,没有绕过。
  • 路由挂在 traffic 分组下,与既有 condition / tag rule 页面结构一致。
  • E2E 模块要求外部 ZooKeeper 与 Nacos,通过 DUBBO_ADMIN_E2E_ZK_ADDR / DUBBO_ADMIN_E2E_NACOS_ADDR 注入,.github/workflows 中不会执行——这与 PR 描述的本地验证方式一致,但意味着这条链路目前没有 CI 保护。

P3 · 依赖 #1553 的合并顺序没有写进 PR 描述

PR 描述说「stacked on #1553」,但没有像 #1610/#1611 那样给出明确的 merge order,也没有转 Draft 之外的阻塞说明。建议补一句「#1553 合并后需 rebase,届时 diff 会缩减到 UI + E2E」,减少维护者判断成本。

P3 · E2E 的地址解析支持两种格式

DUBBO_ADMIN_E2E_ZK_ADDR 同时接受 host:port 与完整 URL。建议在 README 或 Makefile 注释里给出一个可直接复制的示例,否则首次运行的人需要读代码才知道该填什么。

P3 · 页面级错误处理

新增的规则列表 / 编辑器在请求失败时是否统一走既有 message.error,建议与 condition rule 页面保持一致;本次没有看到明显的未捕获 Promise,但建议在 vitest 中补一个「保存失败时保留用户输入」的用例,避免 YAML 编辑器在失败后被清空。

@xiaobaicai66695
xiaobaicai66695 force-pushed the feat/affinity-script-frontend branch from 51afd88 to 3b5e040 Compare October 26, 2026 12:56
@xiaobaicai66695
xiaobaicai66695 marked this pull request as ready for review October 28, 2026 09:40
@robocanic

Copy link
Copy Markdown
Contributor

@xiaobaicai66695 please resolve the conflicts.

@sonarqubecloud

sonarqubecloud Bot commented Nov 2, 2026

Copy link
Copy Markdown

@xiaobaicai66695

Copy link
Copy Markdown
Contributor Author

@xiaobaicai66695 please resolve the conflicts.

done.

@robocanic

Copy link
Copy Markdown
Contributor

@xiaobaicai66695 能否录制一个端到端的demo?

@xiaobaicai66695

Copy link
Copy Markdown
Contributor Author

@xiaobaicai66695 能否录制一个端到端的demo?

ok,今晚找时间录一下

@xiaobaicai66695

xiaobaicai66695 commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Admin 前端路由端到端测试留痕

测试拓扑

flowchart LR
    PS[PowerShell 请求脚本] --> F[shop-frontend]
    F -->|GET /login: UserService/login| U[shop-user]
    F -->|GET /login: DetailService/getItem| D[shop-detail]
    D -->|CommentService/getComment:亲和路由被测调用| C[shop-comment]
    F -->|POST /order: OrderService/submitOrder:脚本路由被测调用| O[shop-order]
Loading
场景 请求入口 被测 Dubbo 调用 消费者 提供者 验证内容
亲和路由 GET /login CommentService/getComment shop-detail Pod shop-comment Pod 比较这两个 Pod 的 region。前端到 shop-detail 的 DetailService/getItem 只负责进入该调用链。
脚本路由 POST /order OrderService/submitOrder shop-frontend Pod shop-order Pod 核对脚本筛选后实际命中的 Order Pod。

/login 还会调用 shop-user 完成登录,但 shop-user 不参与本次亲和判断。校验脚本通过 Jaeger span 的父子关系确认同一条 shop-detail → shop-comment 调用,再读取对应 Pod 的区域配置。Admin 前端负责保存 YAML;PowerShell 负责发出 HTTP 请求并保存 trace ID;Jaeger 提供实际 Dubbo 调用链和命中的实例。

端到端测试的主要思路和代码如下;
在admin前端分别写入亲和性路由或脚本路由的规则,
通过对应的ps脚本发送请求,然后拿到jaeger中的对应的链路,判断路由是否生效
亲和性路由的测试接口是/login,
使用的yaml配置如下:

configVersion: v3.1
scope: service
key: "org.apache.dubbo.samples.CommentService::"
runtime: true
enabled: true
affinityAware:
  key: region
  ratio: 1

亲和性路由的脚本如下:

param(
    [int]$Count = 20,
    [string]$BaseUrl = 'http://127.0.0.1:18082',
    [string]$OutputDir = (Join-Path $PSScriptRoot 'runs')
)

$ErrorActionPreference = 'Stop'
if ($Count -lt 1) { throw 'Count must be positive.' }
if (-not (Test-Path -LiteralPath $OutputDir -PathType Container)) { New-Item -ItemType Directory -Path $OutputDir | Out-Null }

$runId = [guid]::NewGuid().ToString('N').Substring(0, 8)
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$outputFile = Join-Path $OutputDir "pr1547-login-run-$stamp-$runId.json"
$base = $BaseUrl.TrimEnd('/')
$requests = [System.Collections.Generic.List[object]]::new()

for ($i = 1; $i -le $Count; $i++) {
    $traceId = [guid]::NewGuid().ToString('N')
    $parentId = [guid]::NewGuid().ToString('N').Substring(0, 16)
    $username = 'pr1547-' + $runId + '-' + $i.ToString('00')
    $url = $base + '/login?username=' + [uri]::EscapeDataString($username) + '&password=pr1547-test'
    $status = 0
    $errorText = ''
    try {
        $response = Invoke-WebRequest -Uri $url -Method Get -Headers @{ traceparent = "00-$traceId-$parentId-01" } -UseBasicParsing -TimeoutSec 20
        $status = [int]$response.StatusCode
    } catch {
        if ($_.Exception.Response) { $status = [int]$_.Exception.Response.StatusCode }
        $errorText = $_.Exception.Message
    }
    $requests.Add([pscustomobject]@{ index = $i; traceId = $traceId; username = $username; httpStatus = $status; error = $errorText })
    Write-Host ("{0,2}/{1}  HTTP {2}  trace={3}" -f $i, $Count, $status, $traceId)
}

[pscustomobject]@{
    kind = 'login'
    createdAt = (Get-Date).ToString('o')
    baseUrl = $base
    requests = $requests
} | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $outputFile -Encoding utf8

Write-Output "Run file: $outputFile"
Write-Host "Next: & '$PSScriptRoot\pr1547-check-login-20.ps1' -RunFile '$outputFile'"

使用的校验脚本如下:

param(
    [string]$RunFile,
    [string]$JaegerUrl = 'http://127.0.0.1:16687',
    [string]$KubeConfig = 'C:\Users\57512\.kube\dubbo-admin-rke2.yaml',
    [string]$Namespace = 'dubbo-samples-shop',
    [int]$WaitSeconds = 45
)

$ErrorActionPreference = 'Stop'
if (-not $RunFile) {
    $latest = Get-ChildItem -LiteralPath (Join-Path $PSScriptRoot 'runs') -Filter 'pr1547-login-run-*.json' -File -ErrorAction SilentlyContinue |
        Sort-Object LastWriteTime -Descending | Select-Object -First 1
    if (-not $latest) { throw 'No login run file found. Run pr1547-login-20.ps1 first.' }
    $RunFile = $latest.FullName
}
$run = Get-Content -LiteralPath $RunFile -Raw | ConvertFrom-Json
if ($run.kind -ne 'login') { throw "Not a login run file: $RunFile" }
$requests = @($run.requests)
$jaeger = $JaegerUrl.TrimEnd('/')
$null = Invoke-RestMethod -Uri ($jaeger + '/api/services') -TimeoutSec 10
$podJson = & kubectl --kubeconfig $KubeConfig -n $Namespace get pods -o json
if ($LASTEXITCODE -ne 0) { throw "Cannot read Pods in namespace $Namespace" }
$pods = ($podJson -join "`n") | ConvertFrom-Json
$regionByPod = @{}
foreach ($pod in $pods.items) {
    $labels = $pod.spec.containers[0].env | Where-Object { $_.name -eq 'DUBBO_LABELS' } | Select-Object -First 1
    $region = [regex]::Match([string]$labels.value, '(?:^|;)\s*region\s*=\s*([^;\s]+)')
    $regionByPod[[string]$pod.metadata.name] = if ($region.Success) { $region.Groups[1].Value } else { 'UNSET' }
}

function Get-PodRegion([string]$PodName) {
    if ($regionByPod.ContainsKey($PodName)) { return $regionByPod[$PodName] }
    return 'NOT_FOUND'
}

function Find-Spans($trace, [string]$service, [string]$operation) {
    foreach ($span in $trace.spans) {
        $process = $trace.processes.($span.processID)
        if ($process.serviceName -eq $service -and $span.operationName -eq $operation) { $span }
    }
}
function Get-PodName($trace, $span) {
    if (-not $span) { return '' }
    $process = $trace.processes.($span.processID)
    $tag = $process.tags | Where-Object { $_.key -eq 'k8s.pod.name' } | Select-Object -First 1
    if ($tag) { return [string]$tag.value }
    return ''
}
function Has-Parent($child, $parent) {
    if (-not $child -or -not $parent) { return $false }
    foreach ($reference in $child.references) {
        if ($reference.spanID -eq $parent.spanID) { return $true }
    }
    return $false
}
function Test-Complete($trace) {
    $root = $trace.spans | Where-Object { $_.operationName -eq 'http get /login' } | Select-Object -First 1
    $detail = @(Find-Spans $trace 'shop-detail' 'org.apache.dubbo.samples.DetailService/getItem')
    $client = @(Find-Spans $trace 'shop-detail' 'org.apache.dubbo.samples.CommentService/getComment')
    $comment = @(Find-Spans $trace 'shop-comment' 'org.apache.dubbo.samples.CommentService/getComment')
    return [bool]($root -and $detail.Count -gt 0 -and $client.Count -gt 0 -and $comment.Count -gt 0)
}

$traces = @{}
$pending = @{}
$lastCount = @{}
$stableCount = @{}
foreach ($request in $requests) {
    if ($request.httpStatus -ge 200 -and $request.httpStatus -lt 300) { $pending[$request.traceId] = $true }
}
$runAgeSeconds = ([datetimeoffset]::Now - [datetimeoffset]::Parse($run.createdAt)).TotalSeconds
if ($runAgeSeconds -lt 8) { Start-Sleep -Seconds ([math]::Ceiling(8 - $runAgeSeconds)) }
$deadline = (Get-Date).AddSeconds($WaitSeconds)
do {
    foreach ($traceId in @($pending.Keys)) {
        try {
            $response = Invoke-RestMethod -Uri ($jaeger + '/api/traces/' + $traceId) -TimeoutSec 10
            if (@($response.data).Count -gt 0) {
                $trace = $response.data[0]
                $traces[$traceId] = $trace
                $count = @($trace.spans).Count
                if ($lastCount.ContainsKey($traceId) -and $lastCount[$traceId] -eq $count) {
                    $stableCount[$traceId] = [int]$stableCount[$traceId] + 1
                } else { $stableCount[$traceId] = 0 }
                $lastCount[$traceId] = $count
                if ((Test-Complete $trace) -and $stableCount[$traceId] -ge 2) {
                    [void]$pending.Remove($traceId)
                }
            }
        } catch { }
    }
    if ($pending.Count -gt 0 -and (Get-Date) -lt $deadline) { Start-Sleep -Seconds 2 }
} while ($pending.Count -gt 0 -and (Get-Date) -lt $deadline)

$rows = foreach ($request in $requests) {
    $trace = $traces[$request.traceId]
    $details = if ($trace) { @(Find-Spans $trace 'shop-detail' 'org.apache.dubbo.samples.DetailService/getItem') } else { @() }
    $clients = if ($trace) { @(Find-Spans $trace 'shop-detail' 'org.apache.dubbo.samples.CommentService/getComment') } else { @() }
    $comments = if ($trace) { @(Find-Spans $trace 'shop-comment' 'org.apache.dubbo.samples.CommentService/getComment') } else { @() }
    $pairs = foreach ($comment in $comments) {
        $client = $clients | Where-Object { Has-Parent $comment $_ } | Select-Object -First 1
        $detail = $details | Where-Object { Has-Parent $client $_ } | Select-Object -First 1
        if (-not $client -or -not $detail) { continue }
        $detailPod = Get-PodName $trace $detail
        $commentPod = Get-PodName $trace $comment
        $detailRegion = Get-PodRegion $detailPod
        $commentRegion = Get-PodRegion $commentPod
        $pairStatus = 'MATCH'
        $isGray = ($detailPod -match '-gray-' -or $commentPod -match '-gray-')
        $inferred = ($detailRegion -in @('UNSET', 'NOT_FOUND') -or $commentRegion -in @('UNSET', 'NOT_FOUND'))
        if (-not $inferred) {
            if ($detailRegion -ne $commentRegion) { $pairStatus = 'MISMATCH' }
        } elseif ($detailPod -notmatch '^shop-detail-(v[12])-' -or $commentPod -notmatch '^shop-comment-(v[12])-') {
            $pairStatus = 'UNKNOWN_POD'
        } else {
            # In this shop fixture, v1 maps to beijing and v2 to hangzhou, including v1-gray Pods.
            $detailVersion = [regex]::Match($detailPod, '^shop-detail-(v[12])-').Groups[1].Value
            $commentVersion = [regex]::Match($commentPod, '^shop-comment-(v[12])-').Groups[1].Value
            if ($detailVersion -ne $commentVersion) { $pairStatus = 'MISMATCH' }
        }
        [pscustomobject]@{
            DetailPod = $detailPod
            DetailRegion = $detailRegion
            CommentPod = $commentPod
            CommentRegion = $commentRegion
            Gray = $isGray
            Inferred = $inferred
            Result = $pairStatus
        }
    }
    $pairs = @($pairs)
    $status = 'MATCH'
    if ($request.httpStatus -lt 200 -or $request.httpStatus -ge 300) { $status = 'HTTP_ERROR' }
    elseif (-not $trace) { $status = 'NO_TRACE' }
    elseif ($details.Count -eq 0 -or $clients.Count -eq 0 -or $comments.Count -eq 0) { $status = 'INCOMPLETE' }
    elseif ($pairs.Count -eq 0) { $status = 'UNLINKED' }
    elseif (@($pairs | Where-Object { $_.Result -eq 'MISMATCH' }).Count -gt 0) { $status = 'MISMATCH' }
    elseif (@($pairs | Where-Object { $_.Result -eq 'UNKNOWN_POD' }).Count -gt 0) { $status = 'UNKNOWN_POD' }
    [pscustomobject]@{
        No = $request.index
        HTTP = $request.httpStatus
        DetailPod = (($pairs | ForEach-Object { $_.DetailPod }) -join ',')
        DetailRegion = (($pairs | ForEach-Object { $_.DetailRegion }) -join ',')
        CommentPod = (($pairs | ForEach-Object { $_.CommentPod }) -join ',')
        CommentRegion = (($pairs | ForEach-Object { $_.CommentRegion }) -join ',')
        Pairs = $pairs.Count
        GrayPairs = @($pairs | Where-Object { $_.Gray }).Count
        InferredPairs = @($pairs | Where-Object { $_.Inferred }).Count
        Result = $status
        TraceId = $request.traceId
    }
}

Write-Host "Run file: $RunFile"
$rows | Select-Object No, HTTP, DetailRegion, CommentRegion, InferredPairs, Result, TraceId |
    Format-Table -AutoSize | Out-String -Width 170 | Write-Host
$rows | Select-Object No, DetailPod, CommentPod |
    Format-Table -AutoSize | Out-String -Width 170 | Write-Host
$rows | Group-Object Result | Sort-Object Name | ForEach-Object { Write-Host ("{0}: {1}" -f $_.Name, $_.Count) }
$grayRows = @($rows | Where-Object { $_.GrayPairs -gt 0 })
$normalRows = @($rows | Where-Object { $_.GrayPairs -eq 0 })
Write-Host ("Gray matched: {0}/{1}; UNSET means no region in DUBBO_LABELS." -f @($grayRows | Where-Object { $_.Result -eq 'MATCH' }).Count, $grayRows.Count)
Write-Host ("Pairs inferred from Pod names because region is unavailable: {0}" -f @($rows | Measure-Object -Property InferredPairs -Sum).Sum)
Write-Host ("Non-gray matched: {0}/{1}" -f @($normalRows | Where-Object { $_.Result -eq 'MATCH' }).Count, $normalRows.Count)
Write-Host ("Matched: {0}/{1}" -f @($rows | Where-Object { $_.Result -eq 'MATCH' }).Count, $requests.Count)
Write-Host "Open a trace: $jaeger/trace/<TraceId>"
$bad = @($rows | Where-Object { $_.Result -ne 'MATCH' })
$normal = @($rows | Where-Object { $_.Result -eq 'MATCH' })
if ($bad.Count -gt 0 -or $normal.Count -eq 0) { exit 1 }

脚本路由

脚本路由的测试接口是 POST /order。规则由人工在 Admin 前端页面保存到 Nacos;请求脚本向商城前端发送订单请求,并为每次请求生成 trace ID。校验脚本按 trace ID 查询 Jaeger 中的 OrderService/submitOrder 提供者 span,核对实际命中的 Pod 和重试次数。

Nacos group 为 dubbo,DataID 为 shop-order.script-router。v1 和 v2 是同一条规则的两次内容:先在 Admin 中创建 v1,再编辑为 v2;不应创建两条并存的脚本规则。

选择 shop-order-v1 的 YAML

configVersion: v3.0
scope: application
key: shop-order
enabled: true
type: javascript
script: |
  (function route(invokers, invocation, context) {
    var result = new java.util.ArrayList(invokers.size());
    for (var i = 0; i < invokers.size(); i++) {
      if (invokers.get(i).getUrl().getPort() == 20882) {
        result.add(invokers.get(i));
      }
    }
    return result.isEmpty() ? invokers : result;
  })(invokers, invocation, context);

端口 20882 对应 shop-order-v1。

编辑为选择 shop-order-v2 的 YAML

configVersion: v3.0
scope: application
key: shop-order
enabled: true
type: javascript
script: |
  (function route(invokers, invocation, context) {
    var result = new java.util.ArrayList(invokers.size());
    for (var i = 0; i < invokers.size(); i++) {
      if (invokers.get(i).getUrl().getPort() == 20883) {
        result.add(invokers.get(i));
      }
    }
    return result.isEmpty() ? invokers : result;
  })(invokers, invocation, context);

端口 20883 对应 shop-order-v2。两份脚本在目标端口不存在时都会回退到全部候选实例,因此“只命中目标实例”的结论以目标实例在线为前提。

发送请求的 PowerShell 脚本

文件名:pr1547-order-20.ps1。默认发送 20 次;也可显式指定 -Count 20。脚本提交测试订单,并将每次请求的 HTTP 状态和 trace ID 保存到 runs 目录中的 JSON。

param(
    [int]$Count = 20,
    [string]$BaseUrl = 'http://127.0.0.1:18082',
    [string]$OutputDir = (Join-Path $PSScriptRoot 'runs')
)

$ErrorActionPreference = 'Stop'
if ($Count -lt 1) { throw 'Count must be positive.' }
if (-not (Test-Path -LiteralPath $OutputDir -PathType Container)) { New-Item -ItemType Directory -Path $OutputDir | Out-Null }

$runId = [guid]::NewGuid().ToString('N').Substring(0, 8)
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$outputFile = Join-Path $OutputDir "pr1547-order-run-$stamp-$runId.json"
$base = $BaseUrl.TrimEnd('/')
$requests = [System.Collections.Generic.List[object]]::new()

for ($i = 1; $i -le $Count; $i++) {
    $traceId = [guid]::NewGuid().ToString('N')
    $parentId = [guid]::NewGuid().ToString('N').Substring(0, 16)
    $username = 'pr1547-' + $runId + '-' + $i.ToString('00')
    $status = 0
    $errorText = ''
    try {
        # This matches the shop page's Buy Now request: POST /order?username= with form fields username and sku.
        $response = Invoke-WebRequest -Uri ($base + '/order?username=') -Method Post `
            -Body @{ username = $username; sku = '1' } -ContentType 'application/x-www-form-urlencoded' `
            -Headers @{ traceparent = "00-$traceId-$parentId-01" } -UseBasicParsing -TimeoutSec 20
        $status = [int]$response.StatusCode
    } catch {
        if ($_.Exception.Response) { $status = [int]$_.Exception.Response.StatusCode }
        $errorText = $_.Exception.Message
    }
    $requests.Add([pscustomobject]@{ index = $i; traceId = $traceId; username = $username; httpStatus = $status; error = $errorText })
    Write-Host ("{0,2}/{1}  HTTP {2}  trace={3}" -f $i, $Count, $status, $traceId)
}

[pscustomobject]@{
    kind = 'order'
    createdAt = (Get-Date).ToString('o')
    baseUrl = $base
    requests = $requests
} | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath $outputFile -Encoding utf8

Write-Output "Run file: $outputFile"
Write-Host "Next: & '$PSScriptRoot\pr1547-check-order-20.ps1' -RunFile '$outputFile'"

Jaeger 校验 PowerShell 脚本

文件名:pr1547-check-order-20.ps1。脚本从 Jaeger 客户端 span 的 net.peer.port 读取每次 RPC 的实际目标端口,并输出 LastPod、LastPort。ExpectedVersion=any 用于观察无规则阶段的落点;v1 或 v2 同时校验所有调用的 Pod 版本和端口(v1 为 20882,v2 为 20883)。还需检查 Attempts 是否为 1,以排除同版本重试。

param(
    [string]$RunFile,
    [string]$JaegerUrl = 'http://127.0.0.1:16687',
    [ValidateSet('any', 'v1', 'v2')][string]$ExpectedVersion = 'any',
    [int]$WaitSeconds = 45
)

$ErrorActionPreference = 'Stop'
if (-not $RunFile) {
    $latest = Get-ChildItem -LiteralPath (Join-Path $PSScriptRoot 'runs') -Filter 'pr1547-order-run-*.json' -File -ErrorAction SilentlyContinue |
        Sort-Object LastWriteTime -Descending | Select-Object -First 1
    if (-not $latest) { throw 'No order run file found. Run pr1547-order-20.ps1 first.' }
    $RunFile = $latest.FullName
}
$run = Get-Content -LiteralPath $RunFile -Raw | ConvertFrom-Json
if ($run.kind -ne 'order') { throw "Not an order run file: $RunFile" }
$requests = @($run.requests)
$jaeger = $JaegerUrl.TrimEnd('/')
$null = Invoke-RestMethod -Uri ($jaeger + '/api/services') -TimeoutSec 10

function Find-OrderSpans($trace) {
    foreach ($span in $trace.spans) {
        $process = $trace.processes.($span.processID)
        if ($process.serviceName -eq 'shop-order' -and
            $span.operationName -eq 'org.apache.dubbo.samples.OrderService/submitOrder') { $span }
    }
}
function Get-PodName($trace, $span) {
    if (-not $span) { return '' }
    $process = $trace.processes.($span.processID)
    $tag = $process.tags | Where-Object { $_.key -eq 'k8s.pod.name' } | Select-Object -First 1
    if ($tag) { return [string]$tag.value }
    return ''
}
function Get-OrderPort($trace, $providerSpan) {
    foreach ($reference in $providerSpan.references) {
        $clientSpan = $trace.spans | Where-Object { $_.spanID -eq $reference.spanID } | Select-Object -First 1
        if (-not $clientSpan) { continue }
        $tag = $clientSpan.tags | Where-Object { $_.key -eq 'net.peer.port' } | Select-Object -First 1
        if ($tag) { return [string]$tag.value }
    }
    return 'UNKNOWN'
}

$traces = @{}
$pending = @{}
$lastCount = @{}
$stableCount = @{}
foreach ($request in $requests) {
    if ($request.httpStatus -ge 200 -and $request.httpStatus -lt 300) { $pending[$request.traceId] = $true }
}
$runAgeSeconds = ([datetimeoffset]::Now - [datetimeoffset]::Parse($run.createdAt)).TotalSeconds
if ($runAgeSeconds -lt 8) { Start-Sleep -Seconds ([math]::Ceiling(8 - $runAgeSeconds)) }
$deadline = (Get-Date).AddSeconds($WaitSeconds)
do {
    foreach ($traceId in @($pending.Keys)) {
        try {
            $response = Invoke-RestMethod -Uri ($jaeger + '/api/traces/' + $traceId) -TimeoutSec 10
            if (@($response.data).Count -gt 0) {
                $trace = $response.data[0]
                $traces[$traceId] = $trace
                $count = @($trace.spans).Count
                if ($lastCount.ContainsKey($traceId) -and $lastCount[$traceId] -eq $count) {
                    $stableCount[$traceId] = [int]$stableCount[$traceId] + 1
                } else { $stableCount[$traceId] = 0 }
                $lastCount[$traceId] = $count
                $root = $trace.spans | Where-Object { $_.operationName -eq 'http post /order' } | Select-Object -First 1
                if ($root -and @(Find-OrderSpans $trace).Count -gt 0 -and $stableCount[$traceId] -ge 2) {
                    [void]$pending.Remove($traceId)
                }
            }
        } catch { }
    }
    if ($pending.Count -gt 0 -and (Get-Date) -lt $deadline) { Start-Sleep -Seconds 2 }
} while ($pending.Count -gt 0 -and (Get-Date) -lt $deadline)

$rows = foreach ($request in $requests) {
    $trace = $traces[$request.traceId]
    $spans = if ($trace) { @(Find-OrderSpans $trace | Sort-Object startTime) } else { @() }
    $targets = @($spans | ForEach-Object {
        [pscustomobject]@{ Pod = (Get-PodName $trace $_); Port = (Get-OrderPort $trace $_) }
    })
    $pods = @($targets | ForEach-Object { $_.Pod })
    $ports = @($targets | ForEach-Object { $_.Port })
    $pod = if ($pods.Count -gt 0) { $pods[-1] } else { '' }
    $port = if ($ports.Count -gt 0) { $ports[-1] } else { '' }
    $versions = @($pods | ForEach-Object {
        if ($_ -match '-gray-') { 'gray' }
        elseif ($_ -match '^shop-order-(v[12])-') { [regex]::Match($_, '^shop-order-(v[12])-').Groups[1].Value }
        else { 'unknown' }
    })
    $expectedPort = switch ($ExpectedVersion) { 'v1' { '20882' } 'v2' { '20883' } default { '' } }
    $status = 'OBSERVED'
    if ($request.httpStatus -lt 200 -or $request.httpStatus -ge 300) { $status = 'HTTP_ERROR' }
    elseif (-not $trace) { $status = 'NO_TRACE' }
    elseif ($spans.Count -eq 0 -or -not $pod) { $status = 'INCOMPLETE' }
    elseif ($ExpectedVersion -ne 'any' -and @($versions | Where-Object { $_ -ne $ExpectedVersion }).Count -eq 0 -and
            @($ports | Where-Object { $_ -ne $expectedPort }).Count -eq 0) { $status = 'MATCH' }
    elseif ($ExpectedVersion -ne 'any' -and @($versions | Where-Object { $_ -ne $ExpectedVersion }).Count -eq 0) { $status = 'WRONG_PORT' }
    elseif ($ExpectedVersion -ne 'any') { $status = 'WRONG_POD' }
    elseif ($pods.Count -gt 1) { $status = 'MULTI_POD' }
    [pscustomobject]@{
        No = $request.index
        HTTP = $request.httpStatus
        LastPod = $pod
        LastPort = $port
        AllPods = ($pods -join ' -> ')
        AllTargets = (($targets | ForEach-Object { "$($_.Pod):$($_.Port)" }) -join ' -> ')
        Attempts = $pods.Count
        Result = $status
        TraceId = $request.traceId
    }
}

Write-Host "Run file: $RunFile"
Write-Host "Expected version: $ExpectedVersion"
$rows | Format-Table No, HTTP, LastPod, LastPort, Attempts, Result, TraceId -AutoSize | Out-String -Width 230 | Write-Host
$rows | Where-Object { $_.Attempts -gt 1 } | ForEach-Object { Write-Host ("Request {0} all order targets: {1}" -f $_.No, $_.AllTargets) }
$rows | Group-Object Result | Sort-Object Name | ForEach-Object { Write-Host ("{0}: {1}" -f $_.Name, $_.Count) }
Write-Host "Open a trace: $jaeger/trace/<TraceId>"
if ($ExpectedVersion -eq 'any') {
    if (@($rows | Where-Object { $_.Result -in @('HTTP_ERROR', 'NO_TRACE', 'INCOMPLETE') }).Count -gt 0) { exit 1 }
} elseif (@($rows | Where-Object { $_.Result -ne 'MATCH' }).Count -gt 0) {
    exit 1
}

发送 20 次并校验

Admin 页面保存选择 v1 的规则后,直接执行:

& 'D:\environment\pr1555-e2e-test\pr1547-order-20.ps1' -Count 20
& 'D:\environment\pr1555-e2e-test\pr1547-check-order-20.ps1' -ExpectedVersion v1

@xiaobaicai66695

Copy link
Copy Markdown
Contributor Author

这是脚本路由的端到端测试demo

2026-11-15.22-08-58.mp4

@xiaobaicai66695

Copy link
Copy Markdown
Contributor Author

亲和性路由因为是dubbo最新的3.3.6版本的新增的功能dubbo 3.3.6 release note,dubbo官网上没有更新,下边解释一下测试用的yaml

configVersion: v3.1
scope: service
key: "org.apache.dubbo.samples.CommentService::"
runtime: true
enabled: true
affinityAware:
  key: region
  ratio: 1

ratio 的判定逻辑基于一个实时计算的比例:
当前可用比例 = (满足亲和条件的实例数 / 集群总可用实例数) × 100
在配置中 ratio: 1,其行为可以解读为:

正常工作:只要与消费者同 region 的提供者实例占比 大于 1%,Dubbo 就会优先将请求路由到这些“亲和的”实例上。
触发降级:如果因故障等原因,同 region 的可用实例占比下降到 ≤ 1%,亲和路由会认为继续只访问这些实例风险过高,从而自动降级,将请求路由回所有可用实例,以保证服务的整体可用性。
ratio 是 Dubbo 亲和路由中一个用于控制“就近访问”降级行为的百分比阈值。它的核心作用是:当满足亲和条件(如同 region)的提供者实例数量,在总实例数中占比过低时,为了避免因少数节点故障导致流量拥塞,自动降级为访问全部实例。

以下是亲和路由的端到端测试的demo:

1_compressed.mp4

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.

3 participants