bytelazy commented on code in PR #12391:
URL: https://github.com/apache/apisix/pull/12391#discussion_r2328757087
##########
apisix/plugins/grpc-transcode/response.lua:
##########
@@ -23,6 +23,48 @@ local string = string
local ngx_decode_base64 = ngx.decode_base64
local ipairs = ipairs
local pcall = pcall
+local type = type
+local pairs = pairs
+local setmetatable = setmetatable
+
+pb.option "decode_default_array"
+-- Protobuf repeated field label value
+local PROTOBUF_REPEATED_LABEL = 3
+local repeated_label = PROTOBUF_REPEATED_LABEL
+
+local function fetch_proto_array_names(proto_obj)
+ local names = {}
+ if type(proto_obj) == "table" then
+ for k,v in pairs(proto_obj) do
+ if type(v) == "table" then
+ local sub_names = fetch_proto_array_names(v)
+ for sub_name,_ in pairs(sub_names) do
+ names[sub_name] = 1
+ end
+ end
+ end
+ if proto_obj["label"] == repeated_label then
+ if proto_obj["name"] then
+ names[proto_obj["name"]] = 1
+ end
+ end
+ end
+ return names
+end
+
+local function set_default_array(tab, array_names)
+ if type(tab) ~= "table" then
+ return
+ end
+ for k, v in pairs(tab) do
+ if type(v) == "table" then
+ if array_names[k] == 1 then
+ setmetatable(v, core.json.array_mt)
+ end
+ set_default_array(v, array_names)
+ end
+ end
+end
Review Comment:
hi @nic-6443
In APISIX, empty repeated fields are decoded by lua-protobuf as plain Lua
tables ({}). By default, cjson encodes an empty table as {} rather than [].
pb.option("decode_default_array") ensures the field is always a table, but
it does not mark it as an array for JSON encoding.
Only tables with cjson.empty_array_mt (or core.json.array_mt) serialize as
[].
There’s no way to make empty repeated fields encode as [] purely via
lua-protobuf configuration. Handling this in response.lua (setting array_mt) is
the reliable solution with the current APISIX setup.
--
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]