CAICAIIs commented on code in PR #1054:
URL: https://github.com/apache/dubbo-go-pixiu/pull/1054#discussion_r4505197834


##########
pkg/filter/http/remote/dubbo_handler.go:
##########
@@ -109,13 +111,18 @@ func (h *DubboHandler) newState(req *http.Request, api 
router.API) (*outboundBui
        }
 
        ir := api.IntegrationRequest
+       generic, err := clientdubbo.NormalizeGenericMode(ir.Generic)
+       if err != nil {
+               return nil, err
+       }

Review Comment:
   Fixed in 523e076. `newState` resolves the generic mode first and then 
`readRequestBody` decodes the body with `decoder.UseNumber()` when the mode is 
`gson` or `protobuf-json`, so an object value is re-encoded from `json.Number` 
and keeps every digit. The map mode keeps the previous `float64` decoding. 
`readRequestBody` also rejects a body that contains more than one JSON value.
   
   Regression tests: `TestReadRequestBody/JSON text mode keeps integers exact` 
(`{"id":9007199254740993}` stays exact), `TestReadRequestBody/map mode decodes 
numbers as float64`, and `TestBuildOutboundJSONTextGenericMode/integer above 
the float64 range keeps every digit`.
   



##########
pkg/client/dubbo/generic.go:
##########
@@ -0,0 +1,97 @@
+/*
+ * 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 dubbo
+
+import (
+       "encoding/json"
+       "strings"
+)
+
+import (
+       "github.com/pkg/errors"
+)
+
+import (
+       cst "github.com/apache/dubbo-go-pixiu/pkg/common/constant"
+)
+
+// supportedGenericModes lists the generic invocation modes accepted in
+// integrationRequest.generic. Values outside this set are rejected instead of
+// falling back to the map mode, because a silent fallback would change the
+// request contract without telling the caller.
+var supportedGenericModes = []string{
+       cst.GenericModeMap,
+       cst.GenericModeGson,
+       cst.GenericModeProtobufJSON,
+       cst.GenericModeBean,
+}
+
+// NormalizeGenericMode canonicalizes the configured generic invocation mode.
+// An empty value selects the map mode, which is what dubbo-go applies when a
+// reference does not request a specific mode.
+func NormalizeGenericMode(mode string) (string, error) {
+       normalized := strings.ToLower(strings.TrimSpace(mode))
+       if normalized == "" {
+               return cst.GenericModeMap, nil
+       }
+       for _, supported := range supportedGenericModes {
+               if normalized == supported {
+                       return normalized, nil
+               }
+       }
+       return "", errors.Errorf("generic mode %q is not supported, expected 
one of %s",
+               mode, strings.Join(supportedGenericModes, ", "))
+}
+
+// IsJSONTextGenericMode reports whether the mode carries the request as JSON
+// text instead of a list of typed arguments. The provider realizes that text
+// into its own request type, which is what lets a caller without generated
+// code invoke a protobuf defined service.
+func IsJSONTextGenericMode(mode string) bool {
+       switch strings.ToLower(strings.TrimSpace(mode)) {
+       case cst.GenericModeGson, cst.GenericModeProtobufJSON:
+               return true
+       default:
+               return false
+       }
+}
+
+// EncodeJSONTextArgument renders one mapped value as the JSON text that a JSON
+// text mode sends. Values that are already text are passed through so a caller
+// can hand over the exact payload.
+func EncodeJSONTextArgument(value any) (string, error) {
+       if text, ok := value.(string); ok {

Review Comment:
   采纳 A:严格校验。`EncodeJSONTextArgument` 现在要求字符串本身是合法 JSON 文本,否则返回 `generic JSON 
argument is not valid JSON text: %q`;对象等其它类型照旧 `json.Marshal`,`json.Number` 
保持精度。这样 `{"values":"hello"}` 在构建出站参数时就报错,不会把非法文本送到 provider。
   
   契约写进了两份 universality 文档:字符串映射值会被当作已经序列化好的 JSON 文档,查询参数这类普通字符串必须自己先序列化成 
JSON。测试见 `TestEncodeJSONTextArgumentRejectsPlainText` 与 
`TestBuildOutboundJSONTextGenericMode/plain text value is rejected`。
   



##########
pkg/client/dubbo/generic.go:
##########
@@ -0,0 +1,97 @@
+/*
+ * 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 dubbo
+
+import (
+       "encoding/json"
+       "strings"
+)
+
+import (
+       "github.com/pkg/errors"
+)
+
+import (
+       cst "github.com/apache/dubbo-go-pixiu/pkg/common/constant"
+)
+
+// supportedGenericModes lists the generic invocation modes accepted in
+// integrationRequest.generic. Values outside this set are rejected instead of
+// falling back to the map mode, because a silent fallback would change the
+// request contract without telling the caller.
+var supportedGenericModes = []string{
+       cst.GenericModeMap,
+       cst.GenericModeGson,
+       cst.GenericModeProtobufJSON,
+       cst.GenericModeBean,
+}
+
+// NormalizeGenericMode canonicalizes the configured generic invocation mode.
+// An empty value selects the map mode, which is what dubbo-go applies when a
+// reference does not request a specific mode.
+func NormalizeGenericMode(mode string) (string, error) {
+       normalized := strings.ToLower(strings.TrimSpace(mode))
+       if normalized == "" {
+               return cst.GenericModeMap, nil
+       }
+       for _, supported := range supportedGenericModes {
+               if normalized == supported {
+                       return normalized, nil
+               }
+       }
+       return "", errors.Errorf("generic mode %q is not supported, expected 
one of %s",
+               mode, strings.Join(supportedGenericModes, ", "))
+}
+
+// IsJSONTextGenericMode reports whether the mode carries the request as JSON
+// text instead of a list of typed arguments. The provider realizes that text
+// into its own request type, which is what lets a caller without generated
+// code invoke a protobuf defined service.
+func IsJSONTextGenericMode(mode string) bool {
+       switch strings.ToLower(strings.TrimSpace(mode)) {
+       case cst.GenericModeGson, cst.GenericModeProtobufJSON:
+               return true
+       default:
+               return false
+       }
+}
+
+// EncodeJSONTextArgument renders one mapped value as the JSON text that a JSON
+// text mode sends. Values that are already text are passed through so a caller
+// can hand over the exact payload.
+func EncodeJSONTextArgument(value any) (string, error) {
+       if text, ok := value.(string); ok {
+               return text, nil
+       }
+       encoded, err := json.Marshal(value)
+       if err != nil {
+               return "", errors.Wrap(err, "encode generic JSON argument")
+       }
+       return string(encoded), nil
+}
+
+// UnwrapJSONTextResult turns the JSON text a JSON text mode returns into raw
+// bytes, so the HTTP layer writes it as a JSON body instead of a quoted 
string.
+// Values that are not valid JSON text stay untouched.
+func UnwrapJSONTextResult(value any) any {
+       text, ok := value.(string)
+       if !ok || !json.Valid([]byte(text)) {

Review Comment:
   这里不需要改:`[]byte` 会原样写出,`"hello"` 的引号不会丢。
   
   `pkg/common/http/manager.go:254-261` 的 `case []byte:` 把字节直接包成 
`client.NewUnaryResponse(res)`,只根据 `json.Valid(res)` 设置 
Content-Type;`pkg/common/http/manager.go:147-148` 的 `writeResponse` 对 
`*client.UnaryResponse` 执行 `c.Writer.Write(res.Data)`,不再做 JSON 编码。所以 
`UnwrapJSONTextResult` 返回的 `[]byte("\"hello\"")` 到客户端就是 `"hello"`,与 provider 
返回值一致。
   
   如果按建议只解包 `{` / `[`,字符串结果会以 Go 字符串 `"hello"`(带引号)进入 `util.NewDubboResponse` 的 
`default` 分支,被 `json.Marshal` 再编码一次,客户端收到 `"\"hello\""`。标量结果同理:gson 与 
protobuf-json 的 `Generalize` 返回的是 JSON 文档文本,`123` 原样写出仍是合法 JSON。
   
   已加回归 `TestDecodeUnwrapsJSONTextResult`,断言 `SourceResp` 分别是 
`[]byte("\"hello\"")` 与 `[]byte("{\"greeting\":\"hello\"}")`。
   



##########
pkg/common/constant/key.go:
##########
@@ -115,3 +115,17 @@ const (
        // GRPCRequest represents the grpc request
        GRPCRequest = "grpc"
 )
+
+// Generic invocation modes accepted by integrationRequest.generic.
+const (
+       // GenericModeMap is the default map based mode: values are sent as 
typed
+       // arguments and the provider returns a map.
+       GenericModeMap = "true"

Review Comment:
   两个都处理了。
   
   1. 新增 `GenericModeMapAlias = "map"`,`NormalizeGenericMode` 把 
`map`、`true`、空串都归一到 dubbo-go 认识的 `"true"`,配置里可以写 `generic: map`。
   2. `DubboBackendConfig.Generic` 的类型改为 `config.GenericMode`,实现 
`UnmarshalYAML` 与 `UnmarshalJSON`:裸 `true` 解析为 `"true"`,`false` 直接报 `generic: 
false does not select a mode, use "true" or "map" for the map mode`,字符串原样保留。这样 
`generic: true` 不用加引号。
   
   测试见 `TestNormalizeGenericMode` 的 `map` 用例与 
`TestAPIConfigDecodesGenericMode`(`true`、`map`、`gson`、`false` 四种输入)。文档的模式表也补了 
`map` 别名与裸 `true` 的写法。
   



##########
pkg/filter/http/remote/dubbo_handler.go:
##########
@@ -146,9 +153,17 @@ func (h *DubboHandler) applyMapping(state 
*outboundBuildState, req *http.Request
                return errors.Errorf("Parameter mapping %v incorrect", mp)
        }
 
-       converted, err := clientdubbo.MapTypes(mp.MapType, value)
-       if err != nil {
-               return err
+       // JSON text modes carry the request as text, so the declared type of a
+       // positional mapping describes the message instead of a scalar to 
convert.
+       var converted any
+       if clientdubbo.IsJSONTextGenericMode(state.generic) {

Review Comment:
   是刻意的,已补说明。`applyMapping` 的注释现在写明:JSON 文本模式下位置映射的 `mapType` 
只声明请求消息类型,不参与标量转换;两份 universality 文档的模式小节也写了同一条,并说明 `generic` 从 map 切到 
gson/protobuf-json 时 `mapType` 不再做类型转换。
   
   不改成报错的原因:这两种模式下请求消息整体作为文本发送,`mapType` 没有可作用的对象,报错会把合法的消息类型声明也一并拒掉。
   



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to