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
93 changes: 93 additions & 0 deletions docs/generic-invoke.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
# Generic invocation: Go Provider verification

The fixture in [go-v330](../testdata/generic-invoke/go-v330/README.md) is an independent module pinned to the released dubbo-go v3.3.0. It provides real RPC checks and authenticated discovery verification against an isolated Go Provider.

## L2: real RPC with deterministic catalog fixtures

Start the isolated ZooKeeper and Provider as described in the fixture README. The service test uses existing `genericServiceE2EContext` / `genericServiceE2ERouter`; the handler test directly uses `genericHTTPTestContext` / `genericHTTPTestRouter`. Both seed memory Instance, ServiceProviderMetadata and RPCInstance resources following the Java test structure. These are L2 tests: catalog fixtures are in memory, RPC transport is real, and the RPC function is never replaced.

```sh
go test -mod=readonly ./pkg/console/service ./pkg/console/handler
RUN_DUBBO_GO_E2E=1 go test -mod=readonly -p 1 -count=1 -v -run 'GenericInvoke.*GoProvider' ./pkg/console/service ./pkg/console/handler
```

The first command skips Go E2E by default and starts no containers. Once enabled, unreachable Provider/observation endpoints fail the tests. Run packages sequentially (`-p 1`) because count assertions require an isolated Provider. Environment overrides: `GO_PROVIDER_DUBBO_ADDR=127.0.0.1:20880`, `GO_PROVIDER_TRIPLE_ADDR=127.0.0.1:50051`, `GO_PROVIDER_OBSERVATION_URL=http://127.0.0.1:18090`. These also work with loopback Kubernetes port-forwards. Neither test changes metadata to hide a failing protocol.

By default, `RUN_DUBBO_GO_E2E=1` verifies Dubbo string/integer/nested-integer/no-argument/array echo, inbound attachments, and signature rejection with an unchanged Provider count in both layers. Because released `dubbo-go v3.3.0` does not implement the Triple `$invoke` generic handler, the `tri` subtest is explicitly skipped unless `RUN_DUBBO_GO_E2E_TRIPLE=1` is set to probe it. Likewise, the `timeout` subtest (`delay(1000)` with `timeoutMs=100`) is explicitly skipped until per-request Dubbo timeout propagation is enabled (set `RUN_DUBBO_GO_E2E_TIMEOUT=1` to run the strict assertion). Large-integer overflow, nested-integer overflow, and fine-grained business exception classification remain marked with TODO placeholders in the tests.

PowerShell:

```powershell
$env:RUN_DUBBO_GO_E2E='1'
$env:GO_PROVIDER_DUBBO_ADDR='127.0.0.1:20880'
$env:GO_PROVIDER_TRIPLE_ADDR='127.0.0.1:50051'
$env:GO_PROVIDER_OBSERVATION_URL='http://127.0.0.1:18090'
go test -mod=readonly -p 1 -count=1 -v -run 'GenericInvoke.*GoProvider' ./pkg/console/service ./pkg/console/handler
Remove-Item Env:RUN_DUBBO_GO_E2E
```

## L3: authenticated real discovery (experimental against v3.3.0)

> **Status note**: Against released `dubbo-go v3.3.0`, isolated ZooKeeper discovery currently returns 0 provider instances and methods (consistent with missing v3.3.0 metadata publication later addressed on `dubbo-go` `develop`), so the L3 positive invocation sequence below has not yet passed end-to-end against `v3.3.0` and should be treated as experimental until Provider metadata discovery aligns.

Admin must discover the same isolated ZooKeeper used by the Provider. Configure a zookeeper discovery with ID `generic-go`, registry `zookeeper://127.0.0.1:2181` (or the isolated service DNS inside a cluster), memory store, and mock engine for standalone discovery. The engine is independent of registry discovery; no cluster RBAC is required. Use an independently built Admin from the reviewed current branch and a deployment-specific session secret of at least 32 bytes. Supply your own user/password at runtime; never commit credentials or deployment-specific configuration.

For an already running Admin/Provider:

```sh
export ADMIN_URL=http://127.0.0.1:8888
export ZOOKEEPER_ADDR=127.0.0.1:2181
export MESH=generic-go
export ADMIN_USER=<runtime-user>
read -rsp 'Admin password: ' ADMIN_PASSWORD; echo; export ADMIN_PASSWORD
SKIP_LOCAL_START=1 bash testdata/generic-invoke/run-discovery-e2e.sh
unset ADMIN_PASSWORD
```

`ZOOKEEPER_ADDR` configures locally launched Provider/Admin; external mode never reconfigures an existing Admin. `MESH` must equal its discovery ID. The Provider's advertised IP must be reachable from the Admin process. L2 port-forward overrides do not rewrite the L3 discovered target.

For local startup, leave `SKIP_LOCAL_START` unset and set `ADMIN_BIN` to the absolute path of your freshly built branch Admin binary. The runner starts isolated ZooKeeper, compiles/starts the independent Provider and starts the supplied Admin at port 8888, writes runtime configuration/logs only in a private system temporary directory, then stops only its own processes/container and removes that directory on exit. Go/Docker may require network access for initial dependencies/images. Keep custom `ZOOKEEPER_PORT` and `ZOOKEEPER_ADDR` consistent. `PYTHON` defaults to `python3` and can point to a Python 3 executable. When the script owns local startup, use default `ADMIN_URL` or a URL pointing to that same local port 8888.

The verifier sends `POST /api/v1/auth/login` as form fields `user` and `password`, retains the session cookie only in memory, polls real provider instances and method signatures for up to 90 seconds (retrying transient HTTP/API errors while discovery warms up), fetches method detail and invokes the API. Matching L2, the `delay(1000)` / `timeoutMs=100` check is skipped by default unless `RUN_DUBBO_GO_E2E_TIMEOUT=1` is set; when enabled, it also checks `GO_PROVIDER_OBSERVATION_URL/count` (default `http://127.0.0.1:18090/count`) to ensure the timed-out call reached the Provider. No cookie, token, config or logs are written to the repository. Normal API failures exit nonzero. Negative cases deliberately return exit 42 only for the exact expected API error; the driver rejects any other exit code.

## HTTP sequence

Requests require the authenticated session cookie. The following PowerShell equivalent keeps cookies in memory; run from the repository root. The bundled Python verifier automates these steps with stronger assertions and all method cases.

```powershell
$base='http://127.0.0.1:8888'
$credential=Get-Credential -Message 'Isolated test Admin'
$login=Invoke-RestMethod -Method Post "$base/api/v1/auth/login" -Body @{user=$credential.UserName;password=$credential.GetNetworkCredential().Password} -SessionVariable session
if($login.code -ne 'Success'){throw 'Login failed'}
$q='mesh=generic-go&serviceName=example.GoEchoService'
$instances=Invoke-RestMethod "$base/api/v1/service/provider-instances?$q" -WebSession $session
$methods=Invoke-RestMethod "$base/api/v1/service/methods?$q" -WebSession $session
if($instances.code -ne 'Success' -or @($instances.data).Count -eq 0){throw 'Wait for real discovery'}
$method=@($methods.data | Where-Object methodName -eq 'echoArray')[0]
$sig=[uri]::EscapeDataString($method.signature)
$detail=Invoke-RestMethod "$base/api/v1/service/method/detail?$q&methodName=echoArray&signature=$sig" -WebSession $session
$body=@{mesh='generic-go';serviceName='example.GoEchoService';instanceName=$instances.data[0].name;methodName='echoArray';signature=$method.signature;args=@(,@(1,2));timeoutMs=3000;attachments=@{traceId='go-e2e'}} | ConvertTo-Json -Depth 10
$result=Invoke-RestMethod -Method Post "$base/api/v1/service/generic/invoke" -WebSession $session -ContentType application/json -Body $body
if($result.code -ne 'Success'){throw $result.code}
# Or run the complete L3 verifier with the same runtime credentials:
$env:ADMIN_URL=$base; $env:ADMIN_USER=$credential.UserName
$env:ADMIN_PASSWORD=$credential.GetNetworkCredential().Password
try {
python testdata/generic-invoke/go-v330/discovery.py
if($LASTEXITCODE -ne 0){throw 'L3 failed'}
foreach($case in @('bad-signature','bad-args','unreachable','admin-unreachable')) {
python testdata/generic-invoke/go-v330/discovery.py --case $case
if($LASTEXITCODE -ne 42){throw "Negative self-check failed: $case"}
}
} finally {Remove-Item Env:ADMIN_PASSWORD; $credential=$null; $session=$null}
```

The invoke body has `mesh`, `serviceName`, `instanceName`, `methodName`, the discovered `signature`, `args`, `timeoutMs` and `attachments`. No arguments use `args: []`; one string uses `args: ["hello"]`; one array uses `args: [[1,2]]` (the outer array is the argument list). Never flatten the array into two arguments. `attachments()` must return `go-e2e`. `delay` accepts `[1000]`; the 100 ms timeout check is opt-in via `RUN_DUBBO_GO_E2E_TIMEOUT=1` (matching L2 until per-request Dubbo timeout propagation lands) and verifies both `InternalError` within 3 s and an incremented Provider `/count`. A nested echo input is `[{"item":{"value":42}}]`; the integer field is declared in the Provider contract. Overflow rejection is not yet enforced by this suite.

Success is HTTP 200 with `code: "Success"`, `data.rawResult` and nonnegative `data.elapsedMs`. Business API errors may also use HTTP 200: always inspect `code`. An unknown signature/target yields `NotFoundError`; argument count/type validation yields `InvalidArgument`; current RPC failure/timeout yields `InternalError` with a generic message. Authentication failure is HTTP 401. Do not infer business exception classification from `InternalError`.

The deterministic `unreachable` negative case selects a nonexistent instance, testing target-resolution failure without stopping an externally owned Provider. `admin-unreachable` also verifies an actual connection failure against a closed loopback HTTP port and requires exit 42. To verify an actual RPC transport outage, set `UNREACHABLE_INSTANCE_NAME` to a discovered, unavailable Provider instance: the `unreachable` case then requires `InternalError` instead of `NotFoundError`. Do not claim that the missing-instance check proves RPC transport failure. L2 enabled tests independently fail fast on real unreachable RPC listeners. Cluster transport-outage injection is out of scope for this automated check.

## Cleanup

The local bash runner cleans its own temporary files, child processes and exact Docker container ID, including on failure. It leaves externally running components untouched. Manually started fixtures must be stopped explicitly as documented in the Provider README. Stop only the port-forward PIDs belonging to your test session. Cluster rebuild/cleanup scripts and kubeconfig belong outside this repository; cluster cleanup must use the recorded names, labels and UIDs, never a prefix-only delete.
234 changes: 234 additions & 0 deletions pkg/console/handler/service_generic_invoke_go_provider_e2e_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package handler

import (
"bytes"
"encoding/json"
meshproto "github.com/apache/dubbo-admin/api/mesh/v1alpha1"
"github.com/apache/dubbo-admin/pkg/core/manager"
meshresource "github.com/apache/dubbo-admin/pkg/core/resource/apis/mesh/v1alpha1"
coremodel "github.com/apache/dubbo-admin/pkg/core/resource/model"
"github.com/apache/dubbo-admin/pkg/core/store"
memoryst "github.com/apache/dubbo-admin/pkg/store/memory"
"github.com/gin-gonic/gin"
"net"
"net/http"
"net/http/httptest"
"os"
"strconv"
"testing"
"time"
)

func goProviderEnv(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}

func TestGenericInvokeGoProvider(t *testing.T) {
if os.Getenv("RUN_DUBBO_GO_E2E") != "1" {
t.Skip("set RUN_DUBBO_GO_E2E=1 and start go-v330 Provider")
}
// This test intentionally runs sequentially: observation counts require an isolated Provider.
for _, protocol := range []string{"dubbo", "tri"} {
t.Run(protocol, func(t *testing.T) {
address := goProviderEnv("GO_PROVIDER_DUBBO_ADDR", "127.0.0.1:20880")
if protocol == "tri" {
if os.Getenv("RUN_DUBBO_GO_E2E_TRIPLE") != "1" {
t.Skip("dubbo-go v3.3.0 does not implement the Triple $invoke generic handler; set RUN_DUBBO_GO_E2E_TRIPLE=1 to probe")
}
address = goProviderEnv("GO_PROVIDER_TRIPLE_ADDR", "127.0.0.1:50051")
}
host, p, err := net.SplitHostPort(address)
if err != nil {
t.Fatal(err)
}
port, err := strconv.ParseInt(p, 10, 32)
if err != nil {
t.Fatal(err)
}
conn, err := net.DialTimeout("tcp", address, 3*time.Second)
if err != nil {
t.Fatalf("enabled GoProvider unreachable at %s: %v", address, err)
}
conn.Close()
stores := make(map[coremodel.ResourceKind]store.ResourceStore)
for _, kind := range []coremodel.ResourceKind{meshresource.InstanceKind, meshresource.ServiceProviderMetadataKind, meshresource.RPCInstanceKind} {
s := memoryst.NewMemoryResourceStore(kind)
if err := s.Init(nil); err != nil {
t.Fatal(err)
}
stores[kind] = s
}
instance := meshresource.NewInstanceResourceWithAttributes("go-provider", "test-mesh")
instance.Spec.AppName = "generic-go-v330"
instance.Spec.Ip = host
instance.Spec.RpcPort = port
if err := stores[meshresource.InstanceKind].Add(instance); err != nil {
t.Fatal(err)
}
metadata := meshresource.NewServiceProviderMetadataResourceWithAttributes("go-metadata", "test-mesh")
metadata.Spec.ServiceName = "example.GoEchoService"
metadata.Spec.Methods = []*meshproto.Method{
{Name: "echo", ParameterTypes: []string{"java.lang.String"}, ReturnType: "java.lang.String"},
{Name: "echoInt", ParameterTypes: []string{"int"}, ReturnType: "int"},
{Name: "echoNested", ParameterTypes: []string{"example.Envelope"}, ReturnType: "example.Envelope"},
{Name: "noArgs", ReturnType: "java.lang.String"},
{Name: "echoArray", ParameterTypes: []string{"int[]"}, ReturnType: "int[]"},
{Name: "attachments", ReturnType: "java.lang.String"},
{Name: "delay", ParameterTypes: []string{"int"}, ReturnType: "java.lang.String"},
}
if err := stores[meshresource.ServiceProviderMetadataKind].Add(metadata); err != nil {
t.Fatal(err)
}
rpcName := meshresource.BuildInstanceResName("generic-go-v330", host, port)
rpc := meshresource.NewRPCInstanceResourceWithAttributes(rpcName, "test-mesh")
rpc.Spec.Name = rpcName
rpc.Spec.AppName = "generic-go-v330"
rpc.Spec.Ip = host
rpc.Spec.Port = port
rpc.Spec.Endpoints = []*meshproto.Endpoint{{Protocol: protocol, Port: port}}
if err := stores[meshresource.RPCInstanceKind].Add(rpc); err != nil {
t.Fatal(err)
}
ctx := &genericHTTPTestContext{rm: manager.NewResourceManager(&genericHTTPTestRouter{stores: stores}, nil)}
router := gin.New()
router.POST("/test/invoke", ServiceGenericInvoke(ctx))
invoke := func(method, signature string, args string, timeout int64) (string, any) {
t.Helper()
payload := map[string]any{"mesh": "test-mesh", "serviceName": "example.GoEchoService", "instanceName": "go-provider", "methodName": method, "signature": signature, "args": json.RawMessage(args), "timeoutMs": timeout, "attachments": map[string]string{"traceId": "go-e2e"}}
body, err := json.Marshal(payload)
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequest(http.MethodPost, "/test/invoke", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, req)
if recorder.Code != http.StatusOK {
t.Fatalf("HTTP %d: %s", recorder.Code, recorder.Body.String())
}
var response struct {
Code string `json:"code"`
Data struct {
RawResult any `json:"rawResult"`
} `json:"data"`
}
decoder := json.NewDecoder(bytes.NewReader(recorder.Body.Bytes()))
decoder.UseNumber()
if err := decoder.Decode(&response); err != nil {
t.Fatal(err)
}
return response.Code, response.Data.RawResult
}
for _, tc := range []struct{ method, signature, args, want string }{
{"echo", "java.lang.String->java.lang.String", `["hello"]`, `"hello"`},
{"echoInt", "int->int", `[42]`, `42`},
{"noArgs", "->java.lang.String", `[]`, `"no-args"`},
{"echoArray", "int[]->int[]", `[[1,2]]`, `[1,2]`},
{"attachments", "->java.lang.String", `[]`, `"go-e2e"`},
} {
t.Run(tc.method, func(t *testing.T) {
code, value := invoke(tc.method, tc.signature, tc.args, 3000)
if code != "Success" {
t.Fatalf("RPC failed: %s", code)
}
got, err := json.Marshal(value)
if err != nil {
t.Fatal(err)
}
if string(got) != tc.want {
t.Fatalf("want %s, got %s", tc.want, got)
}
})
}
t.Run("echoNested", func(t *testing.T) {
code, value := invoke("echoNested", "example.Envelope->example.Envelope", `[{"item":{"value":42}}]`, 3000)
if code != "Success" {
t.Fatalf("nested RPC failed: %s", code)
}
envelope, ok := value.(map[string]any)
if !ok {
t.Fatalf("nested result: want object, got %T (%#v)", value, value)
}
item, ok := envelope["item"].(map[string]any)
if !ok {
t.Fatalf("nested item: want object, got %T (%#v)", envelope["item"], envelope["item"])
}

number, ok := item["value"].(json.Number)
if !ok {
t.Fatalf("nested value: want JSON integer, got %T (%#v)", item["value"], item["value"])
}
integer, err := number.Int64()
if err != nil || integer != 42 {
t.Fatalf("nested value: want integer 42, got %q (%v)", number, err)
}
})
count := func() int64 {
t.Helper()
client := &http.Client{Timeout: 3 * time.Second}
resp, err := client.Get(goProviderEnv("GO_PROVIDER_OBSERVATION_URL", "http://127.0.0.1:18090") + "/count")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("observation HTTP %d", resp.StatusCode)
}
var value struct {
Count int64 `json:"count"`
}
if err := json.NewDecoder(resp.Body).Decode(&value); err != nil {
t.Fatal(err)
}
return value.Count
}
before := count()
code, _ := invoke("echo", "int->java.lang.String", `[1]`, 3000)
if code != "NotFoundError" {
t.Fatalf("wrong signature: want NotFoundError, got %s", code)
}
if after := count(); after != before {
t.Fatalf("signature rejection reached Provider: %d -> %d", before, after)
}
t.Run("timeout", func(t *testing.T) {
if os.Getenv("RUN_DUBBO_GO_E2E_TIMEOUT") != "1" {
t.Skip("per-request Dubbo timeout propagation is not yet enabled on current develop; set RUN_DUBBO_GO_E2E_TIMEOUT=1 once fixed")
}
started := time.Now()
beforeTimeout := count()
timeoutCode, _ := invoke("delay", "int->java.lang.String", `[1000]`, 100)
if timeoutCode == "Success" {
t.Fatal("timeout unexpectedly succeeded")
}
if elapsed := time.Since(started); elapsed > 3*time.Second {
t.Fatalf("timeout took %s", elapsed)
}
if after := count(); after <= beforeTimeout {
t.Fatal("timeout did not reach Provider; transport failure cannot pass as timeout")
}
})
// TODO(#1631/#1647): assert large-integer overflow rejection, including nested integer fields, once fixed. Do not accept rounded values.
// TODO(#1632): assert business exception classification once defined; do not accept a transport error as a business exception.
})
}
}
Loading
Loading