diff --git a/.licenserc.yaml b/.licenserc.yaml index 7164223ce39f..a71fc5c1beb7 100644 --- a/.licenserc.yaml +++ b/.licenserc.yaml @@ -47,6 +47,8 @@ header: - 'go.sum' # Exclude non-Apache licensed files - 'apisix/balancer/ewma.lua' + # Vendored from googleapis, Apache 2.0 under Google's copyright + - 't/grpc_server_example/proto/google/' # Exclude plugin-specific configuration files - 't/plugin/authz-casbin' - 't/coredns' diff --git a/LICENSE b/LICENSE index 5cadce448d62..472818119b69 100644 --- a/LICENSE +++ b/LICENSE @@ -217,3 +217,4 @@ The text of each license is the standard Apache 2.0 license. ewma.lua file from kubernetes/ingress-nginx: https://github.com/kubernetes/ingress-nginx Apache 2.0 hello.go file from OpenFunction/samples: https://github.com/OpenFunction/samples Apache 2.0 + google/api/annotations.proto and google/api/http.proto files from googleapis/googleapis: https://github.com/googleapis/googleapis Apache 2.0 diff --git a/apisix/plugins/grpc-transcode.lua b/apisix/plugins/grpc-transcode.lua index 3b5d58046eef..64a239aeb963 100644 --- a/apisix/plugins/grpc-transcode.lua +++ b/apisix/plugins/grpc-transcode.lua @@ -20,6 +20,7 @@ local schema_def = require("apisix.schema_def") local proto = require("apisix.plugins.grpc-transcode.proto") local request = require("apisix.plugins.grpc-transcode.request") local response = require("apisix.plugins.grpc-transcode.response") +local http_rule = require("apisix.plugins.grpc-transcode.http_rule") local plugin_name = "grpc-transcode" @@ -56,13 +57,20 @@ local schema = { }, proto_id = schema_def.id_schema, service = { - description = "the grpc service name", + description = "the grpc service name, not required with use_http_annotations", type = "string" }, method = { - description = "the method name in the grpc service.", + description = "the grpc method name, not required with use_http_annotations", type = "string" }, + use_http_annotations = { + description = "resolve the service and method from the google.api.http " + .. "annotations in the proto; needs a proto compiled with " + .. "`protoc --include_imports --descriptor_set_out`", + type = "boolean", + default = false + }, deadline = { description = "deadline for grpc, millisecond", type = "number", @@ -93,9 +101,13 @@ local schema = { }, }, additionalProperties = true, - required = { "proto_id", "service", "method" }, + required = { "proto_id" }, } +-- service/method required unless use_http_annotations. +local schema_with_method = core.table.deepcopy(schema) +schema_with_method.required = { "proto_id", "service", "method" } + -- Based on https://cloud.google.com/apis/design/errors#handling_errors local status_rel = { ["1"] = 499, -- CANCELLED @@ -135,7 +147,8 @@ end function _M.check_schema(conf) - local ok, err = core.schema.check(schema, conf) + local ok, err = core.schema.check( + conf.use_http_annotations and schema or schema_with_method, conf) if not ok then return false, err end @@ -154,18 +167,54 @@ function _M.access(conf, ctx) end local proto_obj, err = proto.fetch(proto_id) - if err then - core.log.error("proto load error: ", err) - return + if not proto_obj then + -- Proto missing or mid-sync: fail closed. + core.log.error("proto load error: ", err or "proto not available") + return 503 end - local ok, err, err_code = request(proto_obj, conf.service, - conf.method, conf.pb_option, conf.deadline) + local service, method = conf.service, conf.method + local binding + if conf.use_http_annotations then + local rules, err = http_rule.fetch(proto_obj) + if not rules then + core.log.error("failed to build the google.api.http routing table: ", err) + return 503 + end + + -- Use ngx.var.uri: ctx.var is cached before proxy-rewrite runs. + local uri = ngx.var.uri + local http_method = core.request.get_method() + local rule, path_params = http_rule.match(rules, http_method, uri) + if not rule then + -- The path may still be bound, just not for this method. + local allowed = http_rule.allowed_methods(rules, uri) + if allowed then + core.log.warn("no google.api.http binding matches ", http_method, " ", uri, + ", allowed: ", core.table.concat(allowed, ", ")) + core.response.set_header("Allow", core.table.concat(allowed, ", ")) + return 405 + end + + core.log.warn("no google.api.http binding matches ", http_method, " ", uri) + return 404 + end + + core.log.info("google.api.http matched ", rule.service, "/", rule.method) + service, method = rule.service, rule.method + binding = {body = rule.body, path_params = path_params} + end + + local ok, err, err_code = request(proto_obj, service, method, + conf.pb_option, conf.deadline, nil, binding) if not ok then core.log.error("transform request error: ", err) return err_code end + -- response transcoding needs the same service/method that the request used + ctx.grpc_transcode_service = service + ctx.grpc_transcode_method = method ctx.proto_obj = proto_obj end @@ -206,7 +255,10 @@ function _M.body_filter(conf, ctx) return end - local err = response(ctx, proto_obj, conf.service, conf.method, conf.pb_option, + local service = ctx.grpc_transcode_service or conf.service + local method = ctx.grpc_transcode_method or conf.method + + local err = response(ctx, proto_obj, service, method, conf.pb_option, conf.show_status_in_body, conf.status_detail_type, conf.max_resp_body_size) if err then diff --git a/apisix/plugins/grpc-transcode/http_rule.lua b/apisix/plugins/grpc-transcode/http_rule.lua new file mode 100644 index 000000000000..6f52bc031e73 --- /dev/null +++ b/apisix/plugins/grpc-transcode/http_rule.lua @@ -0,0 +1,410 @@ +-- +-- 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. +-- +-- Build a routing table from google.api.http on the compiled proto. +-- lua-protobuf resolves the extension as `method.options.http` when the +-- descriptor set was built with --include_imports. +-- +local core = require("apisix.core") +local proto_fake_file = require("apisix.plugins.grpc-transcode.proto").proto_fake_file +local ipairs = ipairs +local pairs = pairs +local type = type +local table = table +local string = string +local re_match = ngx.re.match + + +local _M = {version = 0.1} + + +-- `custom` is left out: its free-form `kind` has no fixed HTTP verb to match on. +local supported_patterns = { + get = "GET", + put = "PUT", + post = "POST", + delete = "DELETE", + patch = "PATCH", +} + + +local function escape_literal(s) + return (string.gsub(s, "[%^%$%(%)%.%[%]%*%+%-%?%{%}|\\]", "\\%0")) +end + + +-- Split on "/", but treat a `{...}` variable as opaque: its own sub-template +-- may contain slashes, as in `{name=shelves/*/books/*}`. +local function split_segments(path) + local segments = {} + local buf = {} + local depth = 0 + + for i = 1, #path do + local c = string.sub(path, i, i) + if c == "{" then + depth = depth + 1 + buf[#buf + 1] = c + elseif c == "}" then + depth = depth - 1 + buf[#buf + 1] = c + elseif c == "/" and depth == 0 then + segments[#segments + 1] = table.concat(buf) + core.table.clear(buf) + else + buf[#buf + 1] = c + end + end + segments[#segments + 1] = table.concat(buf) + + return segments +end + + +-- `FieldPath = IDENT { "." IDENT }`; nil for anything else, which also catches +-- an empty name, a stray "=", and leading, trailing or doubled dots. +local function parse_field_path(field_path) + local path = {} + for part in string.gmatch(field_path, "[^.]+") do + if not string.match(part, "^[%a_][%w_]*$") then + return nil + end + path[#path + 1] = part + end + + if #path == 0 or table.concat(path, ".") ~= field_path then + return nil + end + + return path +end + + +-- Convert the segments inside a variable into a regex fragment. +local function segments_to_regex(segments) + local out = {} + + for i, seg in ipairs(segments) do + local sep = i > 1 and "/" or "" + + if seg == "*" then + out[#out + 1] = sep .. "[^/]+" + elseif seg == "**" then + -- Zero or more segments, so the separator in front goes with it. + out[#out + 1] = i > 1 and "(?:/.*)?" or ".*" + elseif string.sub(seg, 1, 1) == "{" then + return nil, "nested variable in path template" + else + out[#out + 1] = sep .. escape_literal(seg) + end + end + + return table.concat(out) +end + + +-- Parse a path template to a PCRE plus ordered field paths. Captures are +-- positional because `{user.id}` is not a legal PCRE group name. +function _M.parse_path_template(tmpl) + if type(tmpl) ~= "string" or string.sub(tmpl, 1, 1) ~= "/" then + return nil, "path template must start with '/'" + end + + -- A trailing ":verb" is part of the last segment, not a path separator. + local path, verb = string.match(tmpl, "^(.-):([^/:{}]+)$") + if not path then + path = tmpl + end + + local segments = split_segments(path) + -- `path` starts with "/", so the first segment is always empty. + table.remove(segments, 1) + + local buf = {"^"} + local vars = {} + local literal_count = 0 + -- `**` spans segments, so the spec only allows it in the final one. + local multi_at + + for i, seg in ipairs(segments) do + -- `**` is zero or more segments, so `/v1/{name=**}` matches a bare `/v1`. + local last = i == #segments + + if string.sub(seg, 1, 1) == "{" then + if string.sub(seg, -1) ~= "}" then + return nil, "unbalanced '{' in path template" + end + + local inner = string.sub(seg, 2, -2) + local field_path, sub_tmpl = string.match(inner, "^([^=]+)=(.+)$") + if not field_path then + -- `{id}` is shorthand for `{id=*}` + field_path, sub_tmpl = inner, "*" + end + + local parsed_field = parse_field_path(field_path) + if not parsed_field then + return nil, "invalid field path in path template" + end + + local sub_segments = split_segments(sub_tmpl) + local frag, err = segments_to_regex(sub_segments) + if not frag then + return nil, err + end + + if sub_segments[#sub_segments] == "**" then + multi_at = i + end + + if last and sub_tmpl == "**" then + buf[#buf + 1] = "(?:/(" .. frag .. "))?" + else + buf[#buf + 1] = "/(" .. frag .. ")" + end + vars[#vars + 1] = parsed_field + elseif seg == "*" then + buf[#buf + 1] = "/[^/]+" + elseif seg == "**" then + multi_at = i + if last then + buf[#buf + 1] = "(?:/.*)?" + else + buf[#buf + 1] = "/.*" + end + else + buf[#buf + 1] = "/" .. escape_literal(seg) + literal_count = literal_count + 1 + end + end + + if multi_at and multi_at < #segments then + return nil, "'**' must be the last segment in a path template" + end + + buf[#buf + 1] = "$" + + -- Verb is compared outside the regex. + return table.concat(buf), vars, literal_count, verb +end + + +-- `Template = "/" Segments [ Verb ]`; a colon outside the final segment is +-- an ordinary character. +local function split_verb(uri) + local path, verb = string.match(uri, "^(.*):([^/:]+)$") + if path then + return path, verb + end + + return uri, nil +end + + +-- Prefer more literals, then fewer vars, then name. +local function cmp_rule(a, b) + if a.literal_count ~= b.literal_count then + return a.literal_count > b.literal_count + end + + if #a.vars ~= #b.vars then + return #a.vars < #b.vars + end + + if a.service ~= b.service then + return a.service < b.service + end + + if a.method ~= b.method then + return a.method < b.method + end + + return a.regex < b.regex +end + + +local function add_rule(rules, service, method, http) + local pattern = http.pattern + local http_method = pattern and supported_patterns[pattern] + if not http_method then + return + end + + local tmpl = http[pattern] + if type(tmpl) ~= "string" or tmpl == "" then + return + end + + local regex, vars, literal_count, verb = _M.parse_path_template(tmpl) + if not regex then + -- `vars` carries the error message on failure. + core.log.warn("ignoring google.api.http rule for ", service, "/", method, + ": ", vars) + return + end + + local bucket = rules[http_method] + if not bucket then + bucket = {} + rules[http_method] = bucket + end + + bucket[#bucket + 1] = { + service = service, + method = method, + regex = regex, + vars = vars, + literal_count = literal_count, + verb = verb, + body = http.body, + } +end + + +function _M.build(proto_obj) + local loaded = proto_obj[proto_fake_file] + if type(loaded) ~= "table" or type(loaded.index) ~= "table" then + return nil, "compiled proto not found" + end + + local rules = {} + local count = 0 + + for service, methods in pairs(loaded.index) do + for method, descriptor in pairs(methods) do + local http = descriptor.options and descriptor.options.http + if type(http) == "table" then + add_rule(rules, service, method, http) + + for _, binding in ipairs(http.additional_bindings or {}) do + add_rule(rules, service, method, binding) + end + end + end + end + + for _, bucket in pairs(rules) do + table.sort(bucket, cmp_rule) + count = count + #bucket + end + + if count == 0 then + return nil, "no google.api.http annotation found in the proto, make sure it " + .. "was compiled with `protoc --include_imports --descriptor_set_out`" + end + + return rules +end + + +-- Cache the table on the proto object: `proto.fetch` holds it in an lrucache +-- keyed by config version, so it is dropped when the proto changes. +function _M.fetch(proto_obj) + if proto_obj.http_rules then + return proto_obj.http_rules + end + + if proto_obj.http_rules_err then + return nil, proto_obj.http_rules_err + end + + local rules, err = _M.build(proto_obj) + if not rules then + proto_obj.http_rules_err = err + return nil, err + end + + proto_obj.http_rules = rules + return rules +end + + +local function set_nested(tbl, field_path, value) + local node = tbl + for i = 1, #field_path - 1 do + local key = field_path[i] + if type(node[key]) ~= "table" then + node[key] = {} + end + node = node[key] + end + + node[field_path[#field_path]] = value +end + + +-- Methods bound to this uri, sorted. Tells 405 apart from 404. +function _M.allowed_methods(rules, uri) + local allowed + local path, verb = split_verb(uri) + + for http_method, bucket in pairs(rules) do + for _, rule in ipairs(bucket) do + if rule.verb == verb and re_match(path, rule.regex, "jo") then + allowed = allowed or {} + allowed[#allowed + 1] = http_method + break + end + end + end + + if allowed then + table.sort(allowed) + end + + return allowed +end + + +-- Returns the matched rule and the captured values, keyed by field path. +-- `uri` is already percent-decoded, so captures are used as-is and %2F has +-- become a real '/'. +function _M.match(rules, http_method, uri) + local bucket = rules[http_method] + if not bucket then + return nil + end + + local path, verb = split_verb(uri) + + for _, rule in ipairs(bucket) do + -- Verb must match, absent included. + local captures, err + if rule.verb == verb then + captures, err = re_match(path, rule.regex, "jo") + end + + if err then + core.log.error("failed to match uri ", uri, " against ", rule.regex, ": ", err) + elseif captures then + local params + if #rule.vars > 0 then + params = {} + for i, field_path in ipairs(rule.vars) do + -- Missing `**` capture means an empty value. + set_nested(params, field_path, captures[i] or "") + end + end + + return rule, params + end + end + + return nil +end + + +return _M diff --git a/apisix/plugins/grpc-transcode/request.lua b/apisix/plugins/grpc-transcode/request.lua index 934a1c95657c..c29f27faa9af 100644 --- a/apisix/plugins/grpc-transcode/request.lua +++ b/apisix/plugins/grpc-transcode/request.lua @@ -26,7 +26,8 @@ local pcall = pcall local tonumber = tonumber local req_read_body = ngx.req.read_body -return function (proto, service, method, pb_option, deadline, default_values) +-- `binding` is the google.api.http match, if any. +return function (proto, service, method, pb_option, deadline, default_values, binding) core.log.info("proto: ", core.json.delay_encode(proto, true)) local m = util.find_method(proto, service, method) if not m then @@ -39,7 +40,17 @@ return function (proto, service, method, pb_option, deadline, default_values) local pb_old_state = pb.state(proto.pb_state) util.set_options(proto, pb_option) - local map_message = util.map_message(m.input_type, default_values or {}) + local request_table + if binding then + local err + request_table, err = util.get_annotated_request_table(binding) + if err then + pb.state(pb_old_state) + return false, err, 400 + end + end + + local map_message = util.map_message(m.input_type, default_values or {}, request_table) local ok, encoded = pcall(pb.encode, m.input_type, map_message) pb.state(pb_old_state) diff --git a/apisix/plugins/grpc-transcode/util.lua b/apisix/plugins/grpc-transcode/util.lua index a95cb8202041..f78f98fe2fbd 100644 --- a/apisix/plugins/grpc-transcode/util.lua +++ b/apisix/plugins/grpc-transcode/util.lua @@ -110,6 +110,88 @@ local function get_request_table() end +-- Body/form only; no query fallback. +local function get_body_table() + local method = ngx.req.get_method() + if method ~= "POST" and method ~= "PUT" and method ~= "PATCH" then + return nil + end + + local content_type = ngx.req.get_headers()["Content-Type"] or "" + + if string.find(content_type, "application/json", 1, true) then + local req_body = core.request.get_body() + if not req_body then + return nil + end + + local data = json.decode(req_body) + if data == nil then + return nil, "failed to decode the request body as JSON" + end + + return data + end + + if string.find(content_type, "application/x-www-form-urlencoded", 1, true) then + return ngx.req.get_post_args() + end + + return nil +end + + +-- Fields a google.api.http binding may draw on: +-- absent path and query only, body not read +-- "*" body is the whole message, query not read +-- "" body becomes that field, siblings from query +function _M.get_annotated_request_table(binding) + local body_field = binding.body + local request_table + + if body_field == "*" then + local body, err = get_body_table() + if err then + return nil, err + end + request_table = body or {} + else + request_table = ngx.req.get_uri_args() + if body_field and body_field ~= "" then + local body, err = get_body_table() + if err then + return nil, err + end + request_table[body_field] = body + end + end + + if binding.path_params then + request_table = _M.merge_path_params(request_table, binding.path_params) + end + + return request_table +end + + +-- Path params override body/query. Values stay strings; map_message coerces. +function _M.merge_path_params(request_table, path_params) + if type(request_table) ~= "table" then + request_table = {} + end + + for name, value in pairs(path_params) do + if type(value) == "table" then + request_table[name] = _M.merge_path_params(request_table[name], value) + else + request_table[name] = value + end + end + + return request_table +end + + local function get_from_request(request_table, name, kind) if not request_table then return nil diff --git a/docs/en/latest/plugins/grpc-transcode.md b/docs/en/latest/plugins/grpc-transcode.md index 4b756d363b1d..7f866e5a09eb 100644 --- a/docs/en/latest/plugins/grpc-transcode.md +++ b/docs/en/latest/plugins/grpc-transcode.md @@ -44,8 +44,9 @@ With this Plugin enabled, APISIX accepts an HTTP request from the client, transc |----------------------|--------------------------------------------------------|----------|-----------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | max_resp_body_size | integer | False | 67108864 | >= 1 | Maximum response body size in bytes buffered into memory for transcoding. Larger responses are truncated. | | proto_id | string/integer | True | | ID of the proto resource, which contains the protocol buffer definitions. | -| service | string | True | | Name of the gRPC service. | -| method | string | True | | Method name of the gRPC service. | +| service | string | False | | Name of the gRPC service. Required unless `use_http_annotations` is `true`. | +| method | string | False | | Method name of the gRPC service. Required unless `use_http_annotations` is `true`. | +| use_http_annotations | boolean | False | false | If `true`, resolve the service and method from the `google.api.http` annotations declared in the proto instead of from `service` and `method`. See [Route by google.api.http annotations](#route-by-googleapihttp-annotations). | | deadline | number | False | 0 | Deadline for the gRPC service in ms. This is the time APISIX will wait for a gRPC call to complete. | | pb_option | array[string([pb_option_def](#options-for-pb_option))] | False | `["enum_as_name","int64_as_number","auto_default_values","disable_hooks"]` | Encoder and decoder [options](https://github.com/starwing/lua-protobuf?tab=readme-ov-file#options). | | show_status_in_body | boolean | False | false | If `true`, display the parsed `grpc-status-details-bin` in the response body. | @@ -212,6 +213,136 @@ You should receive the following response: {"msg":"Hello"} ``` +### Route by google.api.http Annotations + +Configuring `service` and `method` binds a Route to one gRPC method, so a service with ten methods needs ten Routes. If your proto already declares [`google.api.http`](https://github.com/googleapis/googleapis/blob/master/google/api/http.proto) annotations, set `use_http_annotations` to `true` instead. The Plugin then reads the annotations and picks the method matching the request path and HTTP method, so a single Route serves the whole service. + +:::note + +This mode requires a `.pb` descriptor set generated with `--include_imports`, since the annotations are only preserved there. A plain text `.proto` uploaded to the `/apisix/admin/protos` endpoint cannot be used, because its `import "google/api/annotations.proto"` cannot be resolved. + +::: + +Save the following annotated definition to `item.proto`: + +```proto title="item.proto" +syntax = "proto3"; + +package item; + +import "google/api/annotations.proto"; + +service ItemService { + rpc GetItem(GetItemRequest) returns (Item) { + option (google.api.http) = { + get: "/api/v1/items/{id}" + }; + } + + rpc CreateItem(CreateItemRequest) returns (Item) { + option (google.api.http) = { + post: "/api/v1/items" + body: "item" + }; + } +} + +message Item { + string id = 1; + string title = 2; +} + +message GetItemRequest { + string id = 1; +} + +message CreateItemRequest { + Item item = 1; +} +``` + +Generate the `.pb` file, with `google/api/annotations.proto` and `google/api/http.proto` reachable from your include path: + +```shell +protoc --include_imports --descriptor_set_out=item.pb item.proto +``` + +Configure it in APISIX: + +```shell +curl "http://127.0.0.1:9180/apisix/admin/protos/item-proto" -H "X-API-KEY: $admin_key" -X PUT -d ' +{ + "content" : "'"$(base64 -w0 /path/to/item.pb)"'" +}' +``` + +Create a single Route covering every annotated method of the service: + +```shell +curl "http://127.0.0.1:9180/apisix/admin/routes/item-route" -H "X-API-KEY: $admin_key" -X PUT -d ' +{ + "uri": "/api/v1/*", + "plugins": { + "grpc-transcode": { + "proto_id": "item-proto", + "use_http_annotations": true + } + }, + "upstream": { + "scheme": "grpc", + "type": "roundrobin", + "nodes": { + "127.0.0.1:50051": 1 + } + } +}' +``` + +Send a request that matches the annotation on `GetItem`: + +```shell +curl "http://127.0.0.1:9080/api/v1/items/42" +``` + +The `{id}` segment is bound to the `id` field of `GetItemRequest`, so you should receive: + +```text +{"id":"42","title":"widget"} +``` + +The same Route also serves `CreateItem`, because its annotation declares a different method and path: + +```shell +curl "http://127.0.0.1:9080/api/v1/items" -X POST \ + -H "Content-Type: application/json" \ + -d '{"id":"43","title":"gadget"}' +``` + +That annotation sets `body: "item"`, so the payload maps to the `item` field, not to the whole request message. + +#### Scope of a Route + +The Route's URI pattern bounds what it exposes. `/api/v1/*` reaches every annotation beginning with `/api/v1/`, including ones added to the proto later, so keep the pattern as narrow as the set of methods you mean to publish. A method with no annotation stays unreachable. + +Authentication Plugins run at a higher priority than `grpc-transcode`, so `key-auth`, `jwt-auth` and similar reject an unauthenticated request before any annotation is consulted. + +#### Behavior and Limitations + +* Matching uses the request URI as it stands when the Plugin runs, so a rewrite applied earlier by a Plugin such as `proxy-rewrite` is what gets matched against the annotations. +* Values captured from the path take precedence over query string or body values bound to the same field. +* `body` decides whether the payload is read at all. When it is omitted the payload is ignored entirely and fields come only from the path and the query string. `body: "*"` makes the whole payload the message and the query string is not consulted. `body: ""` maps the payload to that field and leaves its siblings to the query string. Only a top-level field name is supported here; a dotted path such as `body: "item.nested"` is not. +* When several annotations could match, the one with more literal path segments is tried first, so `/api/v1/items/active` wins over `/api/v1/items/{id}`; then the one with fewer variables. Ties are broken by service and method name, not by the order methods appear in the descriptor. +* `additional_bindings` are supported and route to the same method. +* `**` matches zero or more segments, so `/v1/{name=**}` also matches a bare `/v1`. +* If no annotation matches the path, the Plugin returns `404`. If the path is bound but not for the request's method, it returns `405` with an `Allow` header listing the methods that are. Methods declaring no annotation are unreachable in this mode. +* A trailing `:verb` is matched as its own part of the path: a template without one does not accept a request carrying one, and vice versa. +* A request body that is declared but cannot be decoded as JSON is rejected with `400`. +* `custom` HTTP patterns are ignored, as they carry no fixed HTTP method. +* `response_body` is not supported; the full message is always returned. +* Streaming methods are not supported, as with the rest of the Plugin. +* An escaped separator (`%2F`) is decoded by NGINX before the Plugin runs, so it acts as a real separator and will not match a single-segment variable. +* `service` and `method` are ignored while this mode is enabled. + ### Display Error Details in Response Body The following example demonstrates how to configure the `grpc-transcode` Plugin to include the `grpc-status-details-bin` field in the response header for error reporting, when made available by the gRPC server; and decode the message to be displayed in the response body. diff --git a/docs/zh/latest/plugins/grpc-transcode.md b/docs/zh/latest/plugins/grpc-transcode.md index a44c3e97c6ef..babc13abeb2c 100644 --- a/docs/zh/latest/plugins/grpc-transcode.md +++ b/docs/zh/latest/plugins/grpc-transcode.md @@ -43,8 +43,9 @@ description: grpc-transcode 插件在 HTTP 请求与 gRPC 请求及其对应响 | 名称 | 类型 | 必选项 | 默认值 | 描述 | |----------------------|--------------------------------------------------------|--------|----------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | proto_id | string/integer | 是 | | proto 资源的 ID,包含 Protocol Buffer 定义。 | -| service | string | 是 | | gRPC 服务名称。 | -| method | string | 是 | | gRPC 服务的方法名称。 | +| service | string | 否 | | gRPC 服务名称。当 `use_http_annotations` 为 `true` 时不需要配置。 | +| method | string | 否 | | gRPC 服务的方法名称。当 `use_http_annotations` 为 `true` 时不需要配置。 | +| use_http_annotations | boolean | 否 | false | 当设置为 `true` 时,从 proto 中声明的 `google.api.http` 注解解析 gRPC 服务与方法,而不再使用 `service` 与 `method`。详见[根据 google.api.http 注解路由](#根据-googleapihttp-注解路由)。 | | deadline | number | 否 | 0 | gRPC 服务的超时时间,单位为毫秒。即 APISIX 等待 gRPC 调用完成的时间。 | | pb_option | array[string([pb_option_def](#pb_option-的选项))] | 否 | `["enum_as_name","int64_as_number","auto_default_values","disable_hooks"]` | 编码器和解码器[选项](https://github.com/starwing/lua-protobuf?tab=readme-ov-file#options)。 | | show_status_in_body | boolean | 否 | false | 若为 `true`,则在响应体中展示解析后的 `grpc-status-details-bin`。 | @@ -211,6 +212,136 @@ curl "http://127.0.0.1:9080/echo?msg=Hello" {"msg":"Hello"} ``` +### 根据 google.api.http 注解路由 + +配置 `service` 与 `method` 会把一条路由绑定到一个 gRPC 方法,因此包含十个方法的服务需要十条路由。如果 proto 中已声明 [`google.api.http`](https://github.com/googleapis/googleapis/blob/master/google/api/http.proto) 注解,可改为将 `use_http_annotations` 设置为 `true`。插件会读取注解并选出与请求路径和 HTTP 方法匹配的方法,一条路由即可服务整个服务。 + +:::note + +该模式要求使用 `--include_imports` 生成的 `.pb` 描述符文件,因为注解只在其中保留。直接上传到 `/apisix/admin/protos` 的纯文本 `.proto` 无法使用,因为其中的 `import "google/api/annotations.proto"` 无法被解析。 + +::: + +将下面带注解的定义保存为 `item.proto`: + +```proto title="item.proto" +syntax = "proto3"; + +package item; + +import "google/api/annotations.proto"; + +service ItemService { + rpc GetItem(GetItemRequest) returns (Item) { + option (google.api.http) = { + get: "/api/v1/items/{id}" + }; + } + + rpc CreateItem(CreateItemRequest) returns (Item) { + option (google.api.http) = { + post: "/api/v1/items" + body: "item" + }; + } +} + +message Item { + string id = 1; + string title = 2; +} + +message GetItemRequest { + string id = 1; +} + +message CreateItemRequest { + Item item = 1; +} +``` + +在 `google/api/annotations.proto` 与 `google/api/http.proto` 可被 protoc 找到的前提下生成 `.pb` 文件: + +```shell +protoc --include_imports --descriptor_set_out=item.pb item.proto +``` + +在 APISIX 中配置该文件: + +```shell +curl "http://127.0.0.1:9180/apisix/admin/protos/item-proto" -H "X-API-KEY: $admin_key" -X PUT -d ' +{ + "content" : "'"$(base64 -w0 /path/to/item.pb)"'" +}' +``` + +创建一条覆盖该服务全部带注解方法的路由: + +```shell +curl "http://127.0.0.1:9180/apisix/admin/routes/item-route" -H "X-API-KEY: $admin_key" -X PUT -d ' +{ + "uri": "/api/v1/*", + "plugins": { + "grpc-transcode": { + "proto_id": "item-proto", + "use_http_annotations": true + } + }, + "upstream": { + "scheme": "grpc", + "type": "roundrobin", + "nodes": { + "127.0.0.1:50051": 1 + } + } +}' +``` + +发送一个与 `GetItem` 注解匹配的请求: + +```shell +curl "http://127.0.0.1:9080/api/v1/items/42" +``` + +路径中的 `{id}` 会绑定到 `GetItemRequest` 的 `id` 字段,因此你会收到: + +```text +{"id":"42","title":"widget"} +``` + +同一条路由也会服务 `CreateItem`,因为它的注解声明了不同的方法与路径: + +```shell +curl "http://127.0.0.1:9080/api/v1/items" -X POST \ + -H "Content-Type: application/json" \ + -d '{"id":"43","title":"gadget"}' +``` + +由于该注解设置了 `body: "item"`,请求体会映射到 `item` 字段,而不是整个请求消息。 + +#### 路由的作用范围 + +路由的 URI 模式决定了暴露面。`/api/v1/*` 会覆盖所有以 `/api/v1/` 开头的注解,包括之后才加入 proto 的注解,因此请将 URI 模式收敛到确实希望对外提供的方法集合。没有注解的方法始终不可访问。 + +认证插件的优先级高于 `grpc-transcode`,因此 `key-auth`、`jwt-auth` 等会在读取任何注解之前拒绝未认证的请求。 + +#### 行为与限制 + +* 匹配使用插件执行时的请求 URI,因此先前插件(如 `proxy-rewrite`)所做的改写会参与注解匹配。 +* 从路径中提取的值优先于查询字符串或请求体中绑定到同一字段的值。 +* `body` 的取值决定请求体的读取方式:省略时完全不读取请求体,字段只来自路径与查询字符串;`body: "*"` 时整个请求体即为消息,且不再读取查询字符串;`body: ""` 时请求体映射到该字段,其余字段来自查询字符串;此处仅支持顶层字段名,不支持 `body: "item.nested"` 这样的嵌套路径。 +* 当多个注解都能匹配同一请求时,字面量片段更多的优先,其次是变量更少的。仍然相同时按服务名与方法名排序,因此匹配顺序不依赖方法在描述符中出现的次序。 +* 支持 `additional_bindings`,它们会路由到同一个方法。 +* `**` 匹配零个或多个片段,因此 `/v1/{name=**}` 也能匹配 `/v1`。 +* 当路径没有匹配到任何注解时,插件返回 `404`;当路径已被绑定但请求方法不在其中时,返回 `405` 并通过 `Allow` 响应头列出被允许的方法。 +* 结尾的 `:verb` 会作为独立的部分参与匹配,因此不带 verb 的模板不会接受带 verb 的请求,反之亦然。 +* 声明了请求体但无法按 JSON 解析时,返回 `400`。 +* 忽略 `custom` 类型的 HTTP 规则,因为它没有固定的 HTTP 方法。 +* 不支持 `response_body`:响应始终是完整的消息。 +* 与插件的其余部分一样,不支持流式方法。 +* 路径参数中被转义的分隔符(`%2F`)会在插件执行前由 NGINX 解码,因此会被当作真正的路径分隔符,无法匹配单片段变量。 +* 启用该模式后,配置中的 `service` 与 `method` 会被忽略。 + ### 在响应体中显示错误详情 以下示例演示了如何配置 `grpc-transcode` 插件,使其在 gRPC 服务器提供 `grpc-status-details-bin` 字段时,将其包含在响应头中用于错误报告,并将消息解码后展示在响应体中。 diff --git a/t/grpc_server_example/go.mod b/t/grpc_server_example/go.mod index a46c40e63959..8a58457f53a1 100644 --- a/t/grpc_server_example/go.mod +++ b/t/grpc_server_example/go.mod @@ -5,6 +5,7 @@ go 1.25.0 require ( github.com/golang/protobuf v1.5.2 golang.org/x/net v0.55.0 + google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f google.golang.org/grpc v1.53.0 google.golang.org/protobuf v1.33.0 ) @@ -13,5 +14,4 @@ require ( github.com/google/go-cmp v0.6.0 // indirect golang.org/x/sys v0.45.0 // indirect golang.org/x/text v0.37.0 // indirect - google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f // indirect ) diff --git a/t/grpc_server_example/http_binding.pb b/t/grpc_server_example/http_binding.pb new file mode 100644 index 000000000000..96603531bad7 Binary files /dev/null and b/t/grpc_server_example/http_binding.pb differ diff --git a/t/grpc_server_example/main.go b/t/grpc_server_example/main.go index 54bceb4dac42..0e188ae3a2e2 100644 --- a/t/grpc_server_example/main.go +++ b/t/grpc_server_example/main.go @@ -20,6 +20,8 @@ //go:generate protoc --include_imports --descriptor_set_out=proto.pb --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative proto/src.proto //go:generate protoc --descriptor_set_out=echo.pb --include_imports --proto_path=$PWD/proto echo.proto //go:generate protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative proto/echo.proto +//go:generate protoc -I . -I proto --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative proto/http_binding.proto +//go:generate protoc -I proto --include_imports --descriptor_set_out=http_binding.pb proto/http_binding.proto // Package main implements a server for Greeter service. package main @@ -79,6 +81,66 @@ type server struct { pb.UnimplementedGreeterServer pb.UnimplementedTestImportServer pb.UnimplementedEchoServer + pb.UnimplementedItemServiceServer +} + +// ItemService handlers for tests. + +func (s *server) GetItem(ctx context.Context, in *pb.GetItemRequest) (*pb.Reply, error) { + return &pb.Reply{Message: fmt.Sprintf("GetItem id=%s", in.GetId())}, nil +} + +func (s *server) ListItems(ctx context.Context, in *pb.ListItemsRequest) (*pb.Reply, error) { + return &pb.Reply{Message: fmt.Sprintf("ListItems page_size=%d", in.GetPageSize())}, nil +} + +func (s *server) CreateItem(ctx context.Context, in *pb.CreateItemRequest) (*pb.Reply, error) { + item := in.GetItem() + if item == nil { + return &pb.Reply{Message: "CreateItem item=nil"}, nil + } + return &pb.Reply{Message: fmt.Sprintf("CreateItem id=%s title=%s amount=%d request_id=%s", + item.GetId(), item.GetTitle(), item.GetAmount(), in.GetRequestId())}, nil +} + +func (s *server) GetActiveItem(ctx context.Context, in *pb.ListItemsRequest) (*pb.Reply, error) { + return &pb.Reply{Message: "GetActiveItem"}, nil +} + +func (s *server) GetItemNote(ctx context.Context, in *pb.GetItemNoteRequest) (*pb.Reply, error) { + return &pb.Reply{Message: fmt.Sprintf("GetItemNote item_id=%s note_id=%s", + in.GetItemId(), in.GetNoteId())}, nil +} + +func (s *server) UpdateItem(ctx context.Context, in *pb.UpdateItemRequest) (*pb.Reply, error) { + return &pb.Reply{Message: fmt.Sprintf("UpdateItem id=%s title=%s", + in.GetId(), in.GetTitle())}, nil +} + +func (s *server) ReplaceItem(ctx context.Context, in *pb.CreateItemRequest) (*pb.Reply, error) { + item := in.GetItem() + if item == nil { + return &pb.Reply{Message: "ReplaceItem item=nil"}, nil + } + return &pb.Reply{Message: fmt.Sprintf("ReplaceItem id=%s title=%s", + item.GetId(), item.GetTitle())}, nil +} + +func (s *server) CancelItem(ctx context.Context, in *pb.UpdateItemRequest) (*pb.Reply, error) { + return &pb.Reply{Message: fmt.Sprintf("CancelItem id=%s title=%s", + in.GetId(), in.GetTitle())}, nil +} + +func (s *server) DeleteItem(ctx context.Context, in *pb.GetItemRequest) (*pb.Reply, error) { + return &pb.Reply{Message: fmt.Sprintf("DeleteItem id=%s", in.GetId())}, nil +} + +func (s *server) ReportItem(ctx context.Context, in *pb.GetItemRequest) (*pb.Reply, error) { + return &pb.Reply{Message: fmt.Sprintf("ReportItem id=%s", in.GetId())}, nil +} + +func (s *server) UnannotatedItem(ctx context.Context, in *pb.GetItemRequest) (*pb.Reply, error) { + return &pb.Reply{Message: "UnannotatedItem"}, nil } // SayHello implements helloworld.GreeterServer @@ -261,6 +323,7 @@ func main() { pb.RegisterGreeterServer(s, &server{}) pb.RegisterTestImportServer(s, &server{}) pb.RegisterEchoServer(s, &server{}) + pb.RegisterItemServiceServer(s, &server{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) diff --git a/t/grpc_server_example/proto/google/api/annotations.proto b/t/grpc_server_example/proto/google/api/annotations.proto new file mode 100644 index 000000000000..417edd8fa19d --- /dev/null +++ b/t/grpc_server_example/proto/google/api/annotations.proto @@ -0,0 +1,31 @@ +// Copyright 2025 Google LLC +// +// Licensed 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. + +syntax = "proto3"; + +package google.api; + +import "google/api/http.proto"; +import "google/protobuf/descriptor.proto"; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "AnnotationsProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +extend google.protobuf.MethodOptions { + // See `HttpRule`. + HttpRule http = 72295728; +} diff --git a/t/grpc_server_example/proto/google/api/http.proto b/t/grpc_server_example/proto/google/api/http.proto new file mode 100644 index 000000000000..bb3af8e56a05 --- /dev/null +++ b/t/grpc_server_example/proto/google/api/http.proto @@ -0,0 +1,370 @@ +// Copyright 2026 Google LLC +// +// Licensed 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. + +syntax = "proto3"; + +package google.api; + +option go_package = "google.golang.org/genproto/googleapis/api/annotations;annotations"; +option java_multiple_files = true; +option java_outer_classname = "HttpProto"; +option java_package = "com.google.api"; +option objc_class_prefix = "GAPI"; + +// Defines the HTTP configuration for an API service. It contains a list of +// [HttpRule][google.api.HttpRule], each specifying the mapping of an RPC method +// to one or more HTTP REST API methods. +message Http { + // A list of HTTP configuration rules that apply to individual API methods. + // + // **NOTE:** All service configuration rules follow "last one wins" order. + repeated HttpRule rules = 1; + + // When set to true, URL path parameters will be fully URI-decoded except in + // cases of single segment matches in reserved expansion, where "%2F" will be + // left encoded. + // + // The default behavior is to not decode RFC 6570 reserved characters in multi + // segment matches. + bool fully_decode_reserved_expansion = 2; +} + +// gRPC Transcoding +// +// gRPC Transcoding is a feature for mapping between a gRPC method and one or +// more HTTP REST endpoints. It allows developers to build a single API service +// that supports both gRPC APIs and REST APIs. Many systems, including [Google +// APIs](https://github.com/googleapis/googleapis), +// [Cloud Endpoints](https://cloud.google.com/endpoints), [gRPC +// Gateway](https://github.com/grpc-ecosystem/grpc-gateway), +// and [Envoy](https://github.com/envoyproxy/envoy) proxy support this feature +// and use it for large scale production services. +// +// `HttpRule` defines the schema of the gRPC/REST mapping. The mapping specifies +// how different portions of the gRPC request message are mapped to the URL +// path, URL query parameters, and HTTP request body. It also controls how the +// gRPC response message is mapped to the HTTP response body. `HttpRule` is +// typically specified as an `google.api.http` annotation on the gRPC method. +// +// Each mapping specifies a URL path template and an HTTP method. The path +// template may refer to one or more fields in the gRPC request message, as long +// as each field is a non-repeated field with a primitive (non-message) type. +// The path template controls how fields of the request message are mapped to +// the URL path. +// +// Example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get: "/v1/{name=messages/*}" +// }; +// } +// } +// message GetMessageRequest { +// string name = 1; // Mapped to URL path. +// } +// message Message { +// string text = 1; // The resource content. +// } +// +// This enables an HTTP REST to gRPC mapping as below: +// +// - HTTP: `GET /v1/messages/123456` +// - gRPC: `GetMessage(name: "messages/123456")` +// +// Any fields in the request message which are not bound by the path template +// automatically become HTTP query parameters if there is no HTTP request body. +// For example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get:"/v1/messages/{message_id}" +// }; +// } +// } +// message GetMessageRequest { +// message SubMessage { +// string subfield = 1; +// } +// string message_id = 1; // Mapped to URL path. +// int64 revision = 2; // Mapped to URL query parameter `revision`. +// SubMessage sub = 3; // Mapped to URL query parameter `sub.subfield`. +// } +// +// This enables a HTTP JSON to RPC mapping as below: +// +// - HTTP: `GET /v1/messages/123456?revision=2&sub.subfield=foo` +// - gRPC: `GetMessage(message_id: "123456" revision: 2 sub: +// SubMessage(subfield: "foo"))` +// +// Note that fields which are mapped to URL query parameters must have a +// primitive type or a repeated primitive type or a non-repeated message type. +// In the case of a repeated type, the parameter can be repeated in the URL +// as `...?param=A¶m=B`. In the case of a message type, each field of the +// message is mapped to a separate parameter, such as +// `...?foo.a=A&foo.b=B&foo.c=C`. +// +// For HTTP methods that allow a request body, the `body` field +// specifies the mapping. Consider a REST update method on the +// message resource collection: +// +// service Messaging { +// rpc UpdateMessage(UpdateMessageRequest) returns (Message) { +// option (google.api.http) = { +// patch: "/v1/messages/{message_id}" +// body: "message" +// }; +// } +// } +// message UpdateMessageRequest { +// string message_id = 1; // mapped to the URL +// Message message = 2; // mapped to the body +// } +// +// The following HTTP JSON to RPC mapping is enabled, where the +// representation of the JSON in the request body is determined by +// protos JSON encoding: +// +// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` +// - gRPC: `UpdateMessage(message_id: "123456" message { text: "Hi!" })` +// +// The special name `*` can be used in the body mapping to define that +// every field not bound by the path template should be mapped to the +// request body. This enables the following alternative definition of +// the update method: +// +// service Messaging { +// rpc UpdateMessage(Message) returns (Message) { +// option (google.api.http) = { +// patch: "/v1/messages/{message_id}" +// body: "*" +// }; +// } +// } +// message Message { +// string message_id = 1; +// string text = 2; +// } +// +// +// The following HTTP JSON to RPC mapping is enabled: +// +// - HTTP: `PATCH /v1/messages/123456 { "text": "Hi!" }` +// - gRPC: `UpdateMessage(message_id: "123456" text: "Hi!")` +// +// Note that when using `*` in the body mapping, it is not possible to +// have HTTP parameters, as all fields not bound by the path end in +// the body. This makes this option more rarely used in practice when +// defining REST APIs. The common usage of `*` is in custom methods +// which don't use the URL at all for transferring data. +// +// It is possible to define multiple HTTP methods for one RPC by using +// the `additional_bindings` option. Example: +// +// service Messaging { +// rpc GetMessage(GetMessageRequest) returns (Message) { +// option (google.api.http) = { +// get: "/v1/messages/{message_id}" +// additional_bindings { +// get: "/v1/users/{user_id}/messages/{message_id}" +// } +// }; +// } +// } +// message GetMessageRequest { +// string message_id = 1; +// string user_id = 2; +// } +// +// This enables the following two alternative HTTP JSON to RPC mappings: +// +// - HTTP: `GET /v1/messages/123456` +// - gRPC: `GetMessage(message_id: "123456")` +// +// - HTTP: `GET /v1/users/me/messages/123456` +// - gRPC: `GetMessage(user_id: "me" message_id: "123456")` +// +// Rules for HTTP mapping +// +// 1. Leaf request fields (recursive expansion nested messages in the request +// message) are classified into three categories: +// - Fields referred by the path template. They are passed via the URL path. +// - Fields referred by the [HttpRule.body][google.api.HttpRule.body]. They +// are passed via the HTTP +// request body. +// - All other fields are passed via the URL query parameters, and the +// parameter name is the field path in the request message. A repeated +// field can be represented as multiple query parameters under the same +// name. +// 2. If [HttpRule.body][google.api.HttpRule.body] is "*", there is no URL +// query parameter, all fields +// are passed via URL path and HTTP request body. +// 3. If [HttpRule.body][google.api.HttpRule.body] is omitted, there is no HTTP +// request body, all +// fields are passed via URL path and URL query parameters. +// +// Path template syntax +// +// Template = "/" Segments [ Verb ] ; +// Segments = Segment { "/" Segment } ; +// Segment = "*" | "**" | LITERAL | Variable ; +// Variable = "{" FieldPath [ "=" Segments ] "}" ; +// FieldPath = IDENT { "." IDENT } ; +// Verb = ":" LITERAL ; +// +// The syntax `*` matches a single URL path segment. The syntax `**` matches +// zero or more URL path segments, which must be the last part of the URL path +// except the `Verb`. +// +// The syntax `Variable` matches part of the URL path as specified by its +// template. A variable template must not contain other variables. If a variable +// matches a single path segment, its template may be omitted, e.g. `{var}` +// is equivalent to `{var=*}`. +// +// The syntax `LITERAL` matches literal text in the URL path. If the `LITERAL` +// contains any reserved character, such characters should be percent-encoded +// before the matching. +// +// If a variable contains exactly one path segment, such as `"{var}"` or +// `"{var=*}"`, when such a variable is expanded into a URL path on the client +// side, all characters except `[-_.~0-9a-zA-Z]` are percent-encoded. The +// server side does the reverse decoding. Such variables show up in the +// [Discovery +// Document](https://developers.google.com/discovery/v1/reference/apis) as +// `{var}`. +// +// If a variable contains multiple path segments, such as `"{var=foo/*}"` +// or `"{var=**}"`, when such a variable is expanded into a URL path on the +// client side, all characters except `[-_.~/0-9a-zA-Z]` are percent-encoded. +// The server side does the reverse decoding, except "%2F" and "%2f" are left +// unchanged. Such variables show up in the +// [Discovery +// Document](https://developers.google.com/discovery/v1/reference/apis) as +// `{+var}`. +// +// Using gRPC API Service Configuration +// +// gRPC API Service Configuration (service config) is a configuration language +// for configuring a gRPC service to become a user-facing product. The +// service config is simply the YAML representation of the `google.api.Service` +// proto message. +// +// As an alternative to annotating your proto file, you can configure gRPC +// transcoding in your service config YAML files. You do this by specifying a +// `HttpRule` that maps the gRPC method to a REST endpoint, achieving the same +// effect as the proto annotation. This can be particularly useful if you +// have a proto that is reused in multiple services. Note that any transcoding +// specified in the service config will override any matching transcoding +// configuration in the proto. +// +// The following example selects a gRPC method and applies an `HttpRule` to it: +// +// http: +// rules: +// - selector: example.v1.Messaging.GetMessage +// get: /v1/messages/{message_id}/{sub.subfield} +// +// Special notes +// +// When gRPC Transcoding is used to map a gRPC to JSON REST endpoints, the +// proto to JSON conversion must follow the [proto3 +// specification](https://developers.google.com/protocol-buffers/docs/proto3#json). +// +// While the single segment variable follows the semantics of +// [RFC 6570](https://tools.ietf.org/html/rfc6570) Section 3.2.2 Simple String +// Expansion, the multi segment variable **does not** follow RFC 6570 Section +// 3.2.3 Reserved Expansion. The reason is that the Reserved Expansion +// does not expand special characters like `?` and `#`, which would lead +// to invalid URLs. As the result, gRPC Transcoding uses a custom encoding +// for multi segment variables. +// +// The path variables **must not** refer to any repeated or mapped field, +// because client libraries are not capable of handling such variable expansion. +// +// The path variables **must not** capture the leading "/" character. The reason +// is that the most common use case "{var}" does not capture the leading "/" +// character. For consistency, all path variables must share the same behavior. +// +// Repeated message fields must not be mapped to URL query parameters, because +// no client library can support such complicated mapping. +// +// If an API needs to use a JSON array for request or response body, it can map +// the request or response body to a repeated field. However, some gRPC +// Transcoding implementations may not support this feature. +message HttpRule { + // Selects a method to which this rule applies. + // + // Refer to [selector][google.api.DocumentationRule.selector] for syntax + // details. + string selector = 1; + + // Determines the URL pattern is matched by this rules. This pattern can be + // used with any of the {get|put|post|delete|patch} methods. A custom method + // can be defined using the 'custom' field. + oneof pattern { + // Maps to HTTP GET. Used for listing and getting information about + // resources. + string get = 2; + + // Maps to HTTP PUT. Used for replacing a resource. + string put = 3; + + // Maps to HTTP POST. Used for creating a resource or performing an action. + string post = 4; + + // Maps to HTTP DELETE. Used for deleting a resource. + string delete = 5; + + // Maps to HTTP PATCH. Used for updating a resource. + string patch = 6; + + // The custom pattern is used for specifying an HTTP method that is not + // included in the `pattern` field, such as HEAD, or "*" to leave the + // HTTP method unspecified for this rule. The wild-card rule is useful + // for services that provide content to Web (HTML) clients. + CustomHttpPattern custom = 8; + } + + // The name of the request field whose value is mapped to the HTTP request + // body, or `*` for mapping all request fields not captured by the path + // pattern to the HTTP body, or omitted for not having any HTTP request body. + // + // NOTE: the referred field must be present at the top-level of the request + // message type. + string body = 7; + + // Optional. The name of the response field whose value is mapped to the HTTP + // response body. When omitted, the entire response message will be used + // as the HTTP response body. + // + // NOTE: The referred field must be present at the top-level of the response + // message type. + string response_body = 12; + + // Additional HTTP bindings for the selector. Nested bindings must + // not contain an `additional_bindings` field themselves (that is, + // the nesting may only be one level deep). + repeated HttpRule additional_bindings = 11; +} + +// A custom pattern is used for defining custom HTTP verb. +message CustomHttpPattern { + // The name of this custom HTTP verb. + string kind = 1; + + // The path matched by this custom verb. + string path = 2; +} diff --git a/t/grpc_server_example/proto/http_binding.pb.go b/t/grpc_server_example/proto/http_binding.pb.go new file mode 100644 index 000000000000..20872751819f --- /dev/null +++ b/t/grpc_server_example/proto/http_binding.pb.go @@ -0,0 +1,681 @@ +// +// 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. +// + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.27.1 +// protoc v7.35.1 +// source: proto/http_binding.proto + +package proto + +import ( + _ "google.golang.org/genproto/googleapis/api/annotations" + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// Single field keeps assertions independent of JSON key order. +type Reply struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Message string `protobuf:"bytes,1,opt,name=message,proto3" json:"message,omitempty"` +} + +func (x *Reply) Reset() { + *x = Reply{} + if protoimpl.UnsafeEnabled { + mi := &file_proto_http_binding_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Reply) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Reply) ProtoMessage() {} + +func (x *Reply) ProtoReflect() protoreflect.Message { + mi := &file_proto_http_binding_proto_msgTypes[0] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Reply.ProtoReflect.Descriptor instead. +func (*Reply) Descriptor() ([]byte, []int) { + return file_proto_http_binding_proto_rawDescGZIP(), []int{0} +} + +func (x *Reply) GetMessage() string { + if x != nil { + return x.Message + } + return "" +} + +type Item struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"` + Amount int64 `protobuf:"varint,3,opt,name=amount,proto3" json:"amount,omitempty"` +} + +func (x *Item) Reset() { + *x = Item{} + if protoimpl.UnsafeEnabled { + mi := &file_proto_http_binding_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *Item) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Item) ProtoMessage() {} + +func (x *Item) ProtoReflect() protoreflect.Message { + mi := &file_proto_http_binding_proto_msgTypes[1] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Item.ProtoReflect.Descriptor instead. +func (*Item) Descriptor() ([]byte, []int) { + return file_proto_http_binding_proto_rawDescGZIP(), []int{1} +} + +func (x *Item) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *Item) GetTitle() string { + if x != nil { + return x.Title + } + return "" +} + +func (x *Item) GetAmount() int64 { + if x != nil { + return x.Amount + } + return 0 +} + +type GetItemRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` +} + +func (x *GetItemRequest) Reset() { + *x = GetItemRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_proto_http_binding_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetItemRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetItemRequest) ProtoMessage() {} + +func (x *GetItemRequest) ProtoReflect() protoreflect.Message { + mi := &file_proto_http_binding_proto_msgTypes[2] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetItemRequest.ProtoReflect.Descriptor instead. +func (*GetItemRequest) Descriptor() ([]byte, []int) { + return file_proto_http_binding_proto_rawDescGZIP(), []int{2} +} + +func (x *GetItemRequest) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +type ListItemsRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + PageSize int32 `protobuf:"varint,1,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"` +} + +func (x *ListItemsRequest) Reset() { + *x = ListItemsRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_proto_http_binding_proto_msgTypes[3] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *ListItemsRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListItemsRequest) ProtoMessage() {} + +func (x *ListItemsRequest) ProtoReflect() protoreflect.Message { + mi := &file_proto_http_binding_proto_msgTypes[3] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListItemsRequest.ProtoReflect.Descriptor instead. +func (*ListItemsRequest) Descriptor() ([]byte, []int) { + return file_proto_http_binding_proto_rawDescGZIP(), []int{3} +} + +func (x *ListItemsRequest) GetPageSize() int32 { + if x != nil { + return x.PageSize + } + return 0 +} + +type CreateItemRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Item *Item `protobuf:"bytes,1,opt,name=item,proto3" json:"item,omitempty"` + // Outside body: "item", so it comes from the query. + RequestId string `protobuf:"bytes,2,opt,name=request_id,json=requestId,proto3" json:"request_id,omitempty"` +} + +func (x *CreateItemRequest) Reset() { + *x = CreateItemRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_proto_http_binding_proto_msgTypes[4] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *CreateItemRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CreateItemRequest) ProtoMessage() {} + +func (x *CreateItemRequest) ProtoReflect() protoreflect.Message { + mi := &file_proto_http_binding_proto_msgTypes[4] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CreateItemRequest.ProtoReflect.Descriptor instead. +func (*CreateItemRequest) Descriptor() ([]byte, []int) { + return file_proto_http_binding_proto_rawDescGZIP(), []int{4} +} + +func (x *CreateItemRequest) GetItem() *Item { + if x != nil { + return x.Item + } + return nil +} + +func (x *CreateItemRequest) GetRequestId() string { + if x != nil { + return x.RequestId + } + return "" +} + +type UpdateItemRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"` + Title string `protobuf:"bytes,2,opt,name=title,proto3" json:"title,omitempty"` +} + +func (x *UpdateItemRequest) Reset() { + *x = UpdateItemRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_proto_http_binding_proto_msgTypes[5] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *UpdateItemRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateItemRequest) ProtoMessage() {} + +func (x *UpdateItemRequest) ProtoReflect() protoreflect.Message { + mi := &file_proto_http_binding_proto_msgTypes[5] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateItemRequest.ProtoReflect.Descriptor instead. +func (*UpdateItemRequest) Descriptor() ([]byte, []int) { + return file_proto_http_binding_proto_rawDescGZIP(), []int{5} +} + +func (x *UpdateItemRequest) GetId() string { + if x != nil { + return x.Id + } + return "" +} + +func (x *UpdateItemRequest) GetTitle() string { + if x != nil { + return x.Title + } + return "" +} + +type GetItemNoteRequest struct { + state protoimpl.MessageState + sizeCache protoimpl.SizeCache + unknownFields protoimpl.UnknownFields + + ItemId string `protobuf:"bytes,1,opt,name=item_id,json=itemId,proto3" json:"item_id,omitempty"` + NoteId string `protobuf:"bytes,2,opt,name=note_id,json=noteId,proto3" json:"note_id,omitempty"` +} + +func (x *GetItemNoteRequest) Reset() { + *x = GetItemNoteRequest{} + if protoimpl.UnsafeEnabled { + mi := &file_proto_http_binding_proto_msgTypes[6] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) + } +} + +func (x *GetItemNoteRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetItemNoteRequest) ProtoMessage() {} + +func (x *GetItemNoteRequest) ProtoReflect() protoreflect.Message { + mi := &file_proto_http_binding_proto_msgTypes[6] + if protoimpl.UnsafeEnabled && x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetItemNoteRequest.ProtoReflect.Descriptor instead. +func (*GetItemNoteRequest) Descriptor() ([]byte, []int) { + return file_proto_http_binding_proto_rawDescGZIP(), []int{6} +} + +func (x *GetItemNoteRequest) GetItemId() string { + if x != nil { + return x.ItemId + } + return "" +} + +func (x *GetItemNoteRequest) GetNoteId() string { + if x != nil { + return x.NoteId + } + return "" +} + +var File_proto_http_binding_proto protoreflect.FileDescriptor + +var file_proto_http_binding_proto_rawDesc = []byte{ + 0x0a, 0x18, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, 0x6e, + 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0c, 0x68, 0x74, 0x74, 0x70, + 0x5f, 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x1a, 0x1c, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, + 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, + 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x21, 0x0a, 0x05, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x12, + 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x44, 0x0a, 0x04, 0x49, 0x74, 0x65, + 0x6d, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, + 0x64, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x05, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x12, 0x16, 0x0a, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, + 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x03, 0x52, 0x06, 0x61, 0x6d, 0x6f, 0x75, 0x6e, 0x74, 0x22, + 0x20, 0x0a, 0x0e, 0x47, 0x65, 0x74, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, + 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x02, 0x69, + 0x64, 0x22, 0x2f, 0x0a, 0x10, 0x4c, 0x69, 0x73, 0x74, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x52, 0x65, + 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1b, 0x0a, 0x09, 0x70, 0x61, 0x67, 0x65, 0x5f, 0x73, 0x69, + 0x7a, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x70, 0x61, 0x67, 0x65, 0x53, 0x69, + 0x7a, 0x65, 0x22, 0x5a, 0x0a, 0x11, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x26, 0x0a, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x18, + 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x12, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, 0x6e, + 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x04, 0x69, 0x74, 0x65, 0x6d, 0x12, + 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, + 0x01, 0x28, 0x09, 0x52, 0x09, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x49, 0x64, 0x22, 0x39, + 0x0a, 0x11, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x12, 0x0e, 0x0a, 0x02, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, + 0x02, 0x69, 0x64, 0x12, 0x14, 0x0a, 0x05, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x18, 0x02, 0x20, 0x01, + 0x28, 0x09, 0x52, 0x05, 0x74, 0x69, 0x74, 0x6c, 0x65, 0x22, 0x46, 0x0a, 0x12, 0x47, 0x65, 0x74, + 0x49, 0x74, 0x65, 0x6d, 0x4e, 0x6f, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, + 0x17, 0x0a, 0x07, 0x69, 0x74, 0x65, 0x6d, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, + 0x52, 0x06, 0x69, 0x74, 0x65, 0x6d, 0x49, 0x64, 0x12, 0x17, 0x0a, 0x07, 0x6e, 0x6f, 0x74, 0x65, + 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x6e, 0x6f, 0x74, 0x65, 0x49, + 0x64, 0x32, 0xe9, 0x08, 0x0a, 0x0b, 0x49, 0x74, 0x65, 0x6d, 0x53, 0x65, 0x72, 0x76, 0x69, 0x63, + 0x65, 0x12, 0x58, 0x0a, 0x07, 0x47, 0x65, 0x74, 0x49, 0x74, 0x65, 0x6d, 0x12, 0x1c, 0x2e, 0x68, + 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x47, 0x65, 0x74, 0x49, + 0x74, 0x65, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x13, 0x2e, 0x68, 0x74, 0x74, + 0x70, 0x5f, 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, + 0x1a, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x14, 0x12, 0x12, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x76, 0x31, + 0x2f, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x2f, 0x7b, 0x69, 0x64, 0x7d, 0x12, 0x57, 0x0a, 0x09, 0x4c, + 0x69, 0x73, 0x74, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x12, 0x1e, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, + 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x49, 0x74, 0x65, 0x6d, + 0x73, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x13, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, + 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x15, 0x82, + 0xd3, 0xe4, 0x93, 0x02, 0x0f, 0x12, 0x0d, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x76, 0x31, 0x2f, 0x69, + 0x74, 0x65, 0x6d, 0x73, 0x12, 0x5f, 0x0a, 0x0a, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x49, 0x74, + 0x65, 0x6d, 0x12, 0x1f, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, + 0x67, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x13, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, 0x6e, 0x64, 0x69, + 0x6e, 0x67, 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x1b, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x15, + 0x22, 0x0d, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x76, 0x31, 0x2f, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x3a, + 0x04, 0x69, 0x74, 0x65, 0x6d, 0x12, 0x62, 0x0a, 0x0d, 0x47, 0x65, 0x74, 0x41, 0x63, 0x74, 0x69, + 0x76, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x12, 0x1e, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, + 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x13, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, + 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x1c, 0x82, 0xd3, 0xe4, + 0x93, 0x02, 0x16, 0x12, 0x14, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x76, 0x31, 0x2f, 0x69, 0x74, 0x65, + 0x6d, 0x73, 0x2f, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x12, 0x98, 0x01, 0x0a, 0x0b, 0x47, 0x65, + 0x74, 0x49, 0x74, 0x65, 0x6d, 0x4e, 0x6f, 0x74, 0x65, 0x12, 0x20, 0x2e, 0x68, 0x74, 0x74, 0x70, + 0x5f, 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x47, 0x65, 0x74, 0x49, 0x74, 0x65, 0x6d, + 0x4e, 0x6f, 0x74, 0x65, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x13, 0x2e, 0x68, 0x74, + 0x74, 0x70, 0x5f, 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x79, + 0x22, 0x52, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x4c, 0x12, 0x27, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x76, + 0x31, 0x2f, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x2f, 0x7b, 0x69, 0x74, 0x65, 0x6d, 0x5f, 0x69, 0x64, + 0x7d, 0x2f, 0x6e, 0x6f, 0x74, 0x65, 0x73, 0x2f, 0x7b, 0x6e, 0x6f, 0x74, 0x65, 0x5f, 0x69, 0x64, + 0x7d, 0x5a, 0x21, 0x12, 0x1f, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x76, 0x31, 0x2f, 0x69, 0x2f, 0x7b, + 0x69, 0x74, 0x65, 0x6d, 0x5f, 0x69, 0x64, 0x7d, 0x2f, 0x6e, 0x2f, 0x7b, 0x6e, 0x6f, 0x74, 0x65, + 0x5f, 0x69, 0x64, 0x7d, 0x12, 0x61, 0x0a, 0x0a, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x49, 0x74, + 0x65, 0x6d, 0x12, 0x1f, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, + 0x67, 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x13, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, 0x6e, 0x64, 0x69, + 0x6e, 0x67, 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x1d, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x17, + 0x32, 0x12, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x76, 0x31, 0x2f, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x2f, + 0x7b, 0x69, 0x64, 0x7d, 0x3a, 0x01, 0x2a, 0x12, 0x6a, 0x0a, 0x0b, 0x52, 0x65, 0x70, 0x6c, 0x61, + 0x63, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x12, 0x1f, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, + 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, + 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x13, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, + 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x25, 0x82, 0xd3, + 0xe4, 0x93, 0x02, 0x1f, 0x1a, 0x17, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x76, 0x31, 0x2f, 0x69, 0x74, + 0x65, 0x6d, 0x73, 0x2f, 0x7b, 0x69, 0x74, 0x65, 0x6d, 0x2e, 0x69, 0x64, 0x7d, 0x3a, 0x04, 0x69, + 0x74, 0x65, 0x6d, 0x12, 0x65, 0x0a, 0x0a, 0x43, 0x61, 0x6e, 0x63, 0x65, 0x6c, 0x49, 0x74, 0x65, + 0x6d, 0x12, 0x1f, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, + 0x2e, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x71, 0x75, 0x65, + 0x73, 0x74, 0x1a, 0x13, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, + 0x67, 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x21, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x1b, 0x22, + 0x19, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x76, 0x31, 0x2f, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x2f, 0x7b, + 0x69, 0x64, 0x7d, 0x3a, 0x63, 0x61, 0x6e, 0x63, 0x65, 0x6c, 0x12, 0x5b, 0x0a, 0x0a, 0x44, 0x65, + 0x6c, 0x65, 0x74, 0x65, 0x49, 0x74, 0x65, 0x6d, 0x12, 0x1c, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, + 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x47, 0x65, 0x74, 0x49, 0x74, 0x65, 0x6d, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x13, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, + 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x1a, 0x82, 0xd3, 0xe4, + 0x93, 0x02, 0x14, 0x2a, 0x12, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x76, 0x31, 0x2f, 0x69, 0x74, 0x65, + 0x6d, 0x73, 0x2f, 0x7b, 0x69, 0x64, 0x7d, 0x12, 0x6c, 0x0a, 0x0a, 0x52, 0x65, 0x70, 0x6f, 0x72, + 0x74, 0x49, 0x74, 0x65, 0x6d, 0x12, 0x1c, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, 0x6e, + 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x47, 0x65, 0x74, 0x49, 0x74, 0x65, 0x6d, 0x52, 0x65, 0x71, 0x75, + 0x65, 0x73, 0x74, 0x1a, 0x13, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, 0x6e, 0x64, 0x69, + 0x6e, 0x67, 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x2b, 0x82, 0xd3, 0xe4, 0x93, 0x02, 0x25, + 0x42, 0x23, 0x0a, 0x06, 0x52, 0x45, 0x50, 0x4f, 0x52, 0x54, 0x12, 0x19, 0x2f, 0x61, 0x70, 0x69, + 0x2f, 0x76, 0x31, 0x2f, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x2f, 0x7b, 0x69, 0x64, 0x7d, 0x3a, 0x72, + 0x65, 0x70, 0x6f, 0x72, 0x74, 0x12, 0x46, 0x0a, 0x0f, 0x55, 0x6e, 0x61, 0x6e, 0x6e, 0x6f, 0x74, + 0x61, 0x74, 0x65, 0x64, 0x49, 0x74, 0x65, 0x6d, 0x12, 0x1c, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, + 0x62, 0x69, 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x47, 0x65, 0x74, 0x49, 0x74, 0x65, 0x6d, 0x52, + 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x13, 0x2e, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x62, 0x69, + 0x6e, 0x64, 0x69, 0x6e, 0x67, 0x2e, 0x52, 0x65, 0x70, 0x6c, 0x79, 0x22, 0x00, 0x42, 0x09, 0x5a, + 0x07, 0x2e, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, +} + +var ( + file_proto_http_binding_proto_rawDescOnce sync.Once + file_proto_http_binding_proto_rawDescData = file_proto_http_binding_proto_rawDesc +) + +func file_proto_http_binding_proto_rawDescGZIP() []byte { + file_proto_http_binding_proto_rawDescOnce.Do(func() { + file_proto_http_binding_proto_rawDescData = protoimpl.X.CompressGZIP(file_proto_http_binding_proto_rawDescData) + }) + return file_proto_http_binding_proto_rawDescData +} + +var file_proto_http_binding_proto_msgTypes = make([]protoimpl.MessageInfo, 7) +var file_proto_http_binding_proto_goTypes = []interface{}{ + (*Reply)(nil), // 0: http_binding.Reply + (*Item)(nil), // 1: http_binding.Item + (*GetItemRequest)(nil), // 2: http_binding.GetItemRequest + (*ListItemsRequest)(nil), // 3: http_binding.ListItemsRequest + (*CreateItemRequest)(nil), // 4: http_binding.CreateItemRequest + (*UpdateItemRequest)(nil), // 5: http_binding.UpdateItemRequest + (*GetItemNoteRequest)(nil), // 6: http_binding.GetItemNoteRequest +} +var file_proto_http_binding_proto_depIdxs = []int32{ + 1, // 0: http_binding.CreateItemRequest.item:type_name -> http_binding.Item + 2, // 1: http_binding.ItemService.GetItem:input_type -> http_binding.GetItemRequest + 3, // 2: http_binding.ItemService.ListItems:input_type -> http_binding.ListItemsRequest + 4, // 3: http_binding.ItemService.CreateItem:input_type -> http_binding.CreateItemRequest + 3, // 4: http_binding.ItemService.GetActiveItem:input_type -> http_binding.ListItemsRequest + 6, // 5: http_binding.ItemService.GetItemNote:input_type -> http_binding.GetItemNoteRequest + 5, // 6: http_binding.ItemService.UpdateItem:input_type -> http_binding.UpdateItemRequest + 4, // 7: http_binding.ItemService.ReplaceItem:input_type -> http_binding.CreateItemRequest + 5, // 8: http_binding.ItemService.CancelItem:input_type -> http_binding.UpdateItemRequest + 2, // 9: http_binding.ItemService.DeleteItem:input_type -> http_binding.GetItemRequest + 2, // 10: http_binding.ItemService.ReportItem:input_type -> http_binding.GetItemRequest + 2, // 11: http_binding.ItemService.UnannotatedItem:input_type -> http_binding.GetItemRequest + 0, // 12: http_binding.ItemService.GetItem:output_type -> http_binding.Reply + 0, // 13: http_binding.ItemService.ListItems:output_type -> http_binding.Reply + 0, // 14: http_binding.ItemService.CreateItem:output_type -> http_binding.Reply + 0, // 15: http_binding.ItemService.GetActiveItem:output_type -> http_binding.Reply + 0, // 16: http_binding.ItemService.GetItemNote:output_type -> http_binding.Reply + 0, // 17: http_binding.ItemService.UpdateItem:output_type -> http_binding.Reply + 0, // 18: http_binding.ItemService.ReplaceItem:output_type -> http_binding.Reply + 0, // 19: http_binding.ItemService.CancelItem:output_type -> http_binding.Reply + 0, // 20: http_binding.ItemService.DeleteItem:output_type -> http_binding.Reply + 0, // 21: http_binding.ItemService.ReportItem:output_type -> http_binding.Reply + 0, // 22: http_binding.ItemService.UnannotatedItem:output_type -> http_binding.Reply + 12, // [12:23] is the sub-list for method output_type + 1, // [1:12] is the sub-list for method input_type + 1, // [1:1] is the sub-list for extension type_name + 1, // [1:1] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name +} + +func init() { file_proto_http_binding_proto_init() } +func file_proto_http_binding_proto_init() { + if File_proto_http_binding_proto != nil { + return + } + if !protoimpl.UnsafeEnabled { + file_proto_http_binding_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Reply); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_proto_http_binding_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*Item); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_proto_http_binding_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetItemRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_proto_http_binding_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*ListItemsRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_proto_http_binding_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*CreateItemRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_proto_http_binding_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*UpdateItemRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + file_proto_http_binding_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { + switch v := v.(*GetItemNoteRequest); i { + case 0: + return &v.state + case 1: + return &v.sizeCache + case 2: + return &v.unknownFields + default: + return nil + } + } + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: file_proto_http_binding_proto_rawDesc, + NumEnums: 0, + NumMessages: 7, + NumExtensions: 0, + NumServices: 1, + }, + GoTypes: file_proto_http_binding_proto_goTypes, + DependencyIndexes: file_proto_http_binding_proto_depIdxs, + MessageInfos: file_proto_http_binding_proto_msgTypes, + }.Build() + File_proto_http_binding_proto = out.File + file_proto_http_binding_proto_rawDesc = nil + file_proto_http_binding_proto_goTypes = nil + file_proto_http_binding_proto_depIdxs = nil +} diff --git a/t/grpc_server_example/proto/http_binding.proto b/t/grpc_server_example/proto/http_binding.proto new file mode 100644 index 000000000000..d83243004732 --- /dev/null +++ b/t/grpc_server_example/proto/http_binding.proto @@ -0,0 +1,139 @@ +// +// 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. +// + +syntax = "proto3"; + +package http_binding; +option go_package = "./proto"; + +import "google/api/annotations.proto"; + +// Fixture for use_http_annotations. +service ItemService { + rpc GetItem(GetItemRequest) returns (Reply) { + option (google.api.http) = { + get: "/api/v1/items/{id}" + }; + } + + rpc ListItems(ListItemsRequest) returns (Reply) { + option (google.api.http) = { + get: "/api/v1/items" + }; + } + + // body: "item" + rpc CreateItem(CreateItemRequest) returns (Reply) { + option (google.api.http) = { + post: "/api/v1/items" + body: "item" + }; + } + + // Conflicts with GetItem; static path should win. + rpc GetActiveItem(ListItemsRequest) returns (Reply) { + option (google.api.http) = { + get: "/api/v1/items/active" + }; + } + + rpc GetItemNote(GetItemNoteRequest) returns (Reply) { + option (google.api.http) = { + get: "/api/v1/items/{item_id}/notes/{note_id}" + additional_bindings { + get: "/api/v1/i/{item_id}/n/{note_id}" + } + }; + } + + // Path-bound field plus a body: path wins. + rpc UpdateItem(UpdateItemRequest) returns (Reply) { + option (google.api.http) = { + patch: "/api/v1/items/{id}" + body: "*" + }; + } + + // Same, bound field inside the body sub-message. + rpc ReplaceItem(CreateItemRequest) returns (Reply) { + option (google.api.http) = { + put: "/api/v1/items/{item.id}" + body: "item" + }; + } + + // No body; also covers the :verb suffix. + rpc CancelItem(UpdateItemRequest) returns (Reply) { + option (google.api.http) = { + post: "/api/v1/items/{id}:cancel" + }; + } + + rpc DeleteItem(GetItemRequest) returns (Reply) { + option (google.api.http) = { + delete: "/api/v1/items/{id}" + }; + } + + // custom pattern: no fixed HTTP method, ignored. + rpc ReportItem(GetItemRequest) returns (Reply) { + option (google.api.http) = { + custom: { + kind: "REPORT" + path: "/api/v1/items/{id}:report" + } + }; + } + + // No annotation: unreachable in this mode. + rpc UnannotatedItem(GetItemRequest) returns (Reply) {} +} + +// Single field keeps assertions independent of JSON key order. +message Reply { + string message = 1; +} + +message Item { + string id = 1; + string title = 2; + int64 amount = 3; +} + +message GetItemRequest { + string id = 1; +} + +message ListItemsRequest { + int32 page_size = 1; +} + +message CreateItemRequest { + Item item = 1; + // Outside body: "item", so it comes from the query. + string request_id = 2; +} + +message UpdateItemRequest { + string id = 1; + string title = 2; +} + +message GetItemNoteRequest { + string item_id = 1; + string note_id = 2; +} diff --git a/t/grpc_server_example/proto/http_binding_grpc.pb.go b/t/grpc_server_example/proto/http_binding_grpc.pb.go new file mode 100644 index 000000000000..c9dfa44df39d --- /dev/null +++ b/t/grpc_server_example/proto/http_binding_grpc.pb.go @@ -0,0 +1,479 @@ +// Code generated by protoc-gen-go-grpc. DO NOT EDIT. +// versions: +// - protoc-gen-go-grpc v1.2.0 +// - protoc v7.35.1 +// source: proto/http_binding.proto + +package proto + +import ( + context "context" + grpc "google.golang.org/grpc" + codes "google.golang.org/grpc/codes" + status "google.golang.org/grpc/status" +) + +// This is a compile-time assertion to ensure that this generated file +// is compatible with the grpc package it is being compiled against. +// Requires gRPC-Go v1.32.0 or later. +const _ = grpc.SupportPackageIsVersion7 + +// ItemServiceClient is the client API for ItemService service. +// +// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream. +type ItemServiceClient interface { + GetItem(ctx context.Context, in *GetItemRequest, opts ...grpc.CallOption) (*Reply, error) + ListItems(ctx context.Context, in *ListItemsRequest, opts ...grpc.CallOption) (*Reply, error) + // body: "item" + CreateItem(ctx context.Context, in *CreateItemRequest, opts ...grpc.CallOption) (*Reply, error) + // Conflicts with GetItem; static path should win. + GetActiveItem(ctx context.Context, in *ListItemsRequest, opts ...grpc.CallOption) (*Reply, error) + GetItemNote(ctx context.Context, in *GetItemNoteRequest, opts ...grpc.CallOption) (*Reply, error) + // Path-bound field plus a body: path wins. + UpdateItem(ctx context.Context, in *UpdateItemRequest, opts ...grpc.CallOption) (*Reply, error) + // Same, bound field inside the body sub-message. + ReplaceItem(ctx context.Context, in *CreateItemRequest, opts ...grpc.CallOption) (*Reply, error) + // No body; also covers the :verb suffix. + CancelItem(ctx context.Context, in *UpdateItemRequest, opts ...grpc.CallOption) (*Reply, error) + DeleteItem(ctx context.Context, in *GetItemRequest, opts ...grpc.CallOption) (*Reply, error) + // custom pattern: no fixed HTTP method, ignored. + ReportItem(ctx context.Context, in *GetItemRequest, opts ...grpc.CallOption) (*Reply, error) + // No annotation: unreachable in this mode. + UnannotatedItem(ctx context.Context, in *GetItemRequest, opts ...grpc.CallOption) (*Reply, error) +} + +type itemServiceClient struct { + cc grpc.ClientConnInterface +} + +func NewItemServiceClient(cc grpc.ClientConnInterface) ItemServiceClient { + return &itemServiceClient{cc} +} + +func (c *itemServiceClient) GetItem(ctx context.Context, in *GetItemRequest, opts ...grpc.CallOption) (*Reply, error) { + out := new(Reply) + err := c.cc.Invoke(ctx, "/http_binding.ItemService/GetItem", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *itemServiceClient) ListItems(ctx context.Context, in *ListItemsRequest, opts ...grpc.CallOption) (*Reply, error) { + out := new(Reply) + err := c.cc.Invoke(ctx, "/http_binding.ItemService/ListItems", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *itemServiceClient) CreateItem(ctx context.Context, in *CreateItemRequest, opts ...grpc.CallOption) (*Reply, error) { + out := new(Reply) + err := c.cc.Invoke(ctx, "/http_binding.ItemService/CreateItem", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *itemServiceClient) GetActiveItem(ctx context.Context, in *ListItemsRequest, opts ...grpc.CallOption) (*Reply, error) { + out := new(Reply) + err := c.cc.Invoke(ctx, "/http_binding.ItemService/GetActiveItem", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *itemServiceClient) GetItemNote(ctx context.Context, in *GetItemNoteRequest, opts ...grpc.CallOption) (*Reply, error) { + out := new(Reply) + err := c.cc.Invoke(ctx, "/http_binding.ItemService/GetItemNote", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *itemServiceClient) UpdateItem(ctx context.Context, in *UpdateItemRequest, opts ...grpc.CallOption) (*Reply, error) { + out := new(Reply) + err := c.cc.Invoke(ctx, "/http_binding.ItemService/UpdateItem", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *itemServiceClient) ReplaceItem(ctx context.Context, in *CreateItemRequest, opts ...grpc.CallOption) (*Reply, error) { + out := new(Reply) + err := c.cc.Invoke(ctx, "/http_binding.ItemService/ReplaceItem", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *itemServiceClient) CancelItem(ctx context.Context, in *UpdateItemRequest, opts ...grpc.CallOption) (*Reply, error) { + out := new(Reply) + err := c.cc.Invoke(ctx, "/http_binding.ItemService/CancelItem", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *itemServiceClient) DeleteItem(ctx context.Context, in *GetItemRequest, opts ...grpc.CallOption) (*Reply, error) { + out := new(Reply) + err := c.cc.Invoke(ctx, "/http_binding.ItemService/DeleteItem", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *itemServiceClient) ReportItem(ctx context.Context, in *GetItemRequest, opts ...grpc.CallOption) (*Reply, error) { + out := new(Reply) + err := c.cc.Invoke(ctx, "/http_binding.ItemService/ReportItem", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *itemServiceClient) UnannotatedItem(ctx context.Context, in *GetItemRequest, opts ...grpc.CallOption) (*Reply, error) { + out := new(Reply) + err := c.cc.Invoke(ctx, "/http_binding.ItemService/UnannotatedItem", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +// ItemServiceServer is the server API for ItemService service. +// All implementations must embed UnimplementedItemServiceServer +// for forward compatibility +type ItemServiceServer interface { + GetItem(context.Context, *GetItemRequest) (*Reply, error) + ListItems(context.Context, *ListItemsRequest) (*Reply, error) + // body: "item" + CreateItem(context.Context, *CreateItemRequest) (*Reply, error) + // Conflicts with GetItem; static path should win. + GetActiveItem(context.Context, *ListItemsRequest) (*Reply, error) + GetItemNote(context.Context, *GetItemNoteRequest) (*Reply, error) + // Path-bound field plus a body: path wins. + UpdateItem(context.Context, *UpdateItemRequest) (*Reply, error) + // Same, bound field inside the body sub-message. + ReplaceItem(context.Context, *CreateItemRequest) (*Reply, error) + // No body; also covers the :verb suffix. + CancelItem(context.Context, *UpdateItemRequest) (*Reply, error) + DeleteItem(context.Context, *GetItemRequest) (*Reply, error) + // custom pattern: no fixed HTTP method, ignored. + ReportItem(context.Context, *GetItemRequest) (*Reply, error) + // No annotation: unreachable in this mode. + UnannotatedItem(context.Context, *GetItemRequest) (*Reply, error) + mustEmbedUnimplementedItemServiceServer() +} + +// UnimplementedItemServiceServer must be embedded to have forward compatible implementations. +type UnimplementedItemServiceServer struct { +} + +func (UnimplementedItemServiceServer) GetItem(context.Context, *GetItemRequest) (*Reply, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetItem not implemented") +} +func (UnimplementedItemServiceServer) ListItems(context.Context, *ListItemsRequest) (*Reply, error) { + return nil, status.Errorf(codes.Unimplemented, "method ListItems not implemented") +} +func (UnimplementedItemServiceServer) CreateItem(context.Context, *CreateItemRequest) (*Reply, error) { + return nil, status.Errorf(codes.Unimplemented, "method CreateItem not implemented") +} +func (UnimplementedItemServiceServer) GetActiveItem(context.Context, *ListItemsRequest) (*Reply, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetActiveItem not implemented") +} +func (UnimplementedItemServiceServer) GetItemNote(context.Context, *GetItemNoteRequest) (*Reply, error) { + return nil, status.Errorf(codes.Unimplemented, "method GetItemNote not implemented") +} +func (UnimplementedItemServiceServer) UpdateItem(context.Context, *UpdateItemRequest) (*Reply, error) { + return nil, status.Errorf(codes.Unimplemented, "method UpdateItem not implemented") +} +func (UnimplementedItemServiceServer) ReplaceItem(context.Context, *CreateItemRequest) (*Reply, error) { + return nil, status.Errorf(codes.Unimplemented, "method ReplaceItem not implemented") +} +func (UnimplementedItemServiceServer) CancelItem(context.Context, *UpdateItemRequest) (*Reply, error) { + return nil, status.Errorf(codes.Unimplemented, "method CancelItem not implemented") +} +func (UnimplementedItemServiceServer) DeleteItem(context.Context, *GetItemRequest) (*Reply, error) { + return nil, status.Errorf(codes.Unimplemented, "method DeleteItem not implemented") +} +func (UnimplementedItemServiceServer) ReportItem(context.Context, *GetItemRequest) (*Reply, error) { + return nil, status.Errorf(codes.Unimplemented, "method ReportItem not implemented") +} +func (UnimplementedItemServiceServer) UnannotatedItem(context.Context, *GetItemRequest) (*Reply, error) { + return nil, status.Errorf(codes.Unimplemented, "method UnannotatedItem not implemented") +} +func (UnimplementedItemServiceServer) mustEmbedUnimplementedItemServiceServer() {} + +// UnsafeItemServiceServer may be embedded to opt out of forward compatibility for this service. +// Use of this interface is not recommended, as added methods to ItemServiceServer will +// result in compilation errors. +type UnsafeItemServiceServer interface { + mustEmbedUnimplementedItemServiceServer() +} + +func RegisterItemServiceServer(s grpc.ServiceRegistrar, srv ItemServiceServer) { + s.RegisterService(&ItemService_ServiceDesc, srv) +} + +func _ItemService_GetItem_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetItemRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ItemServiceServer).GetItem(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/http_binding.ItemService/GetItem", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ItemServiceServer).GetItem(ctx, req.(*GetItemRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ItemService_ListItems_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ListItemsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ItemServiceServer).ListItems(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/http_binding.ItemService/ListItems", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ItemServiceServer).ListItems(ctx, req.(*ListItemsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ItemService_CreateItem_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(CreateItemRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ItemServiceServer).CreateItem(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/http_binding.ItemService/CreateItem", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ItemServiceServer).CreateItem(ctx, req.(*CreateItemRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ItemService_GetActiveItem_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ListItemsRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ItemServiceServer).GetActiveItem(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/http_binding.ItemService/GetActiveItem", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ItemServiceServer).GetActiveItem(ctx, req.(*ListItemsRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ItemService_GetItemNote_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetItemNoteRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ItemServiceServer).GetItemNote(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/http_binding.ItemService/GetItemNote", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ItemServiceServer).GetItemNote(ctx, req.(*GetItemNoteRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ItemService_UpdateItem_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdateItemRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ItemServiceServer).UpdateItem(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/http_binding.ItemService/UpdateItem", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ItemServiceServer).UpdateItem(ctx, req.(*UpdateItemRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ItemService_ReplaceItem_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(CreateItemRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ItemServiceServer).ReplaceItem(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/http_binding.ItemService/ReplaceItem", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ItemServiceServer).ReplaceItem(ctx, req.(*CreateItemRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ItemService_CancelItem_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdateItemRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ItemServiceServer).CancelItem(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/http_binding.ItemService/CancelItem", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ItemServiceServer).CancelItem(ctx, req.(*UpdateItemRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ItemService_DeleteItem_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetItemRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ItemServiceServer).DeleteItem(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/http_binding.ItemService/DeleteItem", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ItemServiceServer).DeleteItem(ctx, req.(*GetItemRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ItemService_ReportItem_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetItemRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ItemServiceServer).ReportItem(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/http_binding.ItemService/ReportItem", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ItemServiceServer).ReportItem(ctx, req.(*GetItemRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _ItemService_UnannotatedItem_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetItemRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ItemServiceServer).UnannotatedItem(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/http_binding.ItemService/UnannotatedItem", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ItemServiceServer).UnannotatedItem(ctx, req.(*GetItemRequest)) + } + return interceptor(ctx, in, info, handler) +} + +// ItemService_ServiceDesc is the grpc.ServiceDesc for ItemService service. +// It's only intended for direct use with grpc.RegisterService, +// and not to be introspected or modified (even as a copy) +var ItemService_ServiceDesc = grpc.ServiceDesc{ + ServiceName: "http_binding.ItemService", + HandlerType: (*ItemServiceServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "GetItem", + Handler: _ItemService_GetItem_Handler, + }, + { + MethodName: "ListItems", + Handler: _ItemService_ListItems_Handler, + }, + { + MethodName: "CreateItem", + Handler: _ItemService_CreateItem_Handler, + }, + { + MethodName: "GetActiveItem", + Handler: _ItemService_GetActiveItem_Handler, + }, + { + MethodName: "GetItemNote", + Handler: _ItemService_GetItemNote_Handler, + }, + { + MethodName: "UpdateItem", + Handler: _ItemService_UpdateItem_Handler, + }, + { + MethodName: "ReplaceItem", + Handler: _ItemService_ReplaceItem_Handler, + }, + { + MethodName: "CancelItem", + Handler: _ItemService_CancelItem_Handler, + }, + { + MethodName: "DeleteItem", + Handler: _ItemService_DeleteItem_Handler, + }, + { + MethodName: "ReportItem", + Handler: _ItemService_ReportItem_Handler, + }, + { + MethodName: "UnannotatedItem", + Handler: _ItemService_UnannotatedItem_Handler, + }, + }, + Streams: []grpc.StreamDesc{}, + Metadata: "proto/http_binding.proto", +} diff --git a/t/plugin/grpc-transcode-http-annotations.t b/t/plugin/grpc-transcode-http-annotations.t new file mode 100644 index 000000000000..f0e4de1ae138 --- /dev/null +++ b/t/plugin/grpc-transcode-http-annotations.t @@ -0,0 +1,596 @@ +# +# 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. +# +use t::APISIX 'no_plan'; + +repeat_each(1); +no_long_string(); +no_shuffle(); +no_root_location(); +log_level('info'); + +# Shared config: avoids an nginx restart, and the etcd re-sync, between blocks. +my $config = <<'_EOC_'; + location /parse_ok { + content_by_lua_block { + local http_rule = require("apisix.plugins.grpc-transcode.http_rule") + + local cases = { + "/api/v1/items", + "/api/v1/items/{id}", + "/api/v1/items/{item_id}/notes/{note_id}", + "/v1/{name=shelves/*/books/*}", + "/v1/{path=**}", + "/v1/items/*", + "/v1/{id}:cancel", + "/v1/{name=shelves/**}", + "/v1/a.b/{id}", + } + + for _, tmpl in ipairs(cases) do + local regex, vars = http_rule.parse_path_template(tmpl) + ngx.say(tmpl, " -> ", regex, " vars=", #vars) + end + + local _, nested = http_rule.parse_path_template("/v1/{user.id}/x") + ngx.say("nested field path: ", table.concat(nested[1], "|")) + + -- `**` is zero or more segments. + local proto_fake_file = + require("apisix.plugins.grpc-transcode.proto").proto_fake_file + local rules = http_rule.build({[proto_fake_file] = {index = {["t.S"] = { + M = {options = {http = {pattern = "get", get = "/v1/{path=**}"}}}, + }}}}) + for _, uri in ipairs({"/v1", "/v1/", "/v1/a", "/v1/a/b"}) do + local rule, params = http_rule.match(rules, "GET", uri) + ngx.say(uri, " -> ", rule and "match" or "no match", + " path=", params and string.format("%q", params.path) or "-") + end + } + } + + location /parse_reject { + content_by_lua_block { + local http_rule = require("apisix.plugins.grpc-transcode.http_rule") + + local cases = { + "v1/no-leading-slash", + "/v1/{unbalanced", + "/v1/{a={b}}", + "/v1/{}", + "/v1/{=*}", + "/v1/{a-b}", + "/v1/{a..b}", + "/v1/**/more", + "/v1/{a=**}/more", + } + + for _, tmpl in ipairs(cases) do + local _, err = http_rule.parse_path_template(tmpl) + ngx.say(tmpl, " -> ", err) + end + } + } + + location /verb_precedence { + content_by_lua_block { + local http_rule = require("apisix.plugins.grpc-transcode.http_rule") + local proto_fake_file = + require("apisix.plugins.grpc-transcode.proto").proto_fake_file + + -- Each template takes only the uri carrying its own verb. + local index = {["t.S"] = { + Plain = {options = {http = {pattern = "get", get = "/v1/{id}"}}}, + Cancel = {options = {http = {pattern = "get", get = "/v1/{id}:cancel"}}}, + }} + local rules = http_rule.build({[proto_fake_file] = {index = index}}) + + local rule = http_rule.match(rules, "GET", "/v1/42:cancel") + ngx.say("with verb: ", rule and rule.method) + rule = http_rule.match(rules, "GET", "/v1/42") + ngx.say("without verb: ", rule and rule.method) + + -- A custom pattern names no HTTP method, so it yields no rule. + local custom_only = {["t.S"] = { + R = {options = {http = {pattern = "custom", + custom = {kind = "REPORT", + path = "/v1/{id}:report"}}}}, + }} + local built = http_rule.build({[proto_fake_file] = {index = custom_only}}) + ngx.say("custom only: ", built and "built a table" or "no rules") + } + } + + location /setup { + content_by_lua_block { + local t = require("lib.test_admin") + local json = require("toolkit.json") + + local content = t.read_file("t/grpc_server_example/http_binding.pb") + local code = t.test('/apisix/admin/protos/1', ngx.HTTP_PUT, + json.encode({content = ngx.encode_base64(content)})) + if code >= 300 then + ngx.status = code + ngx.say("failed to set the proto") + return + end + + local upstream = [[ + "upstream": { + "scheme": "grpc", + "type": "roundrobin", + "nodes": { + "127.0.0.1:10051": 1 + } + } + ]] + + local routes = { + -- one route for the whole annotated service + {"1", [[{ + "uri": "/api/v1/*", + "plugins": { + "grpc-transcode": { + "proto_id": "1", + "use_http_annotations": true + } + },]] .. upstream .. "}"}, + -- legacy service/method route + {"3", [[{ + "uri": "/legacy", + "plugins": { + "grpc-transcode": { + "proto_id": "1", + "service": "http_binding.ItemService", + "method": "GetItem" + } + },]] .. upstream .. "}"}, + -- a uri rewritten before this plugin runs + {"4", [[{ + "uri": "/shop/*", + "plugins": { + "proxy-rewrite": { + "regex_uri": ["^/shop/(.*)", "/api/v1/items/$1"] + }, + "grpc-transcode": { + "proto_id": "1", + "use_http_annotations": true + } + },]] .. upstream .. "}"}, + } + + for _, route in ipairs(routes) do + local c, body = t.test('/apisix/admin/routes/' .. route[1], + ngx.HTTP_PUT, route[2]) + if c >= 300 then + ngx.status = c + ngx.say("failed to set route ", route[1], ": ", body) + return + end + end + + -- Wait for the watcher to deliver the write: 404 means the route + -- has not landed, 503 means the proto has not. + local http = require("resty.http") + local url = "http://127.0.0.1:" .. ngx.var.server_port .. "/api/v1/items/ready" + local ready + for _ = 1, 100 do + local res = http.new():request_uri(url, {keepalive = false}) + if res and res.status == 200 then + ready = true + break + end + ngx.sleep(0.05) + end + + if not ready then + ngx.say("routes did not become available") + return + end + + ngx.say("passed") + } + } + + location /schema_requires_method { + content_by_lua_block { + local t = require("lib.test_admin").test + + local code, body = t('/apisix/admin/routes/2', + ngx.HTTP_PUT, + [[{ + "uri": "/bad", + "plugins": { + "grpc-transcode": { + "proto_id": "1" + } + }, + "upstream": { + "scheme": "grpc", + "type": "roundrobin", + "nodes": { + "127.0.0.1:10051": 1 + } + } + }]] + ) + + ngx.status = code + ngx.print(body) + } + } + + location /replace_proto { + content_by_lua_block { + local t = require("lib.test_admin") + local json = require("toolkit.json") + + -- echo.pb has no annotation, so nothing is left to route with. + local content = t.read_file("t/grpc_server_example/echo.pb") + local code = t.test('/apisix/admin/protos/1', ngx.HTTP_PUT, + json.encode({content = ngx.encode_base64(content)})) + if code >= 300 then + ngx.status = code + ngx.say("failed to update the proto") + return + end + + -- Poll so a slow watcher shows up as a timeout, not a stale 200. + local http = require("resty.http") + local url = "http://127.0.0.1:" .. ngx.var.server_port .. "/api/v1/items/42" + local status + for _ = 1, 100 do + local res = http.new():request_uri(url, {keepalive = false}) + status = res and res.status + if status ~= 200 then + break + end + ngx.sleep(0.05) + end + + ngx.say("after update: ", status) + } + } +_EOC_ + +add_block_preprocessor(sub { + my ($block) = @_; + $block->set_value("config", $config); +}); + +run_tests; + +__DATA__ + +=== TEST 1: parse path templates +--- request +GET /parse_ok +--- response_body +/api/v1/items -> ^/api/v1/items$ vars=0 +/api/v1/items/{id} -> ^/api/v1/items/([^/]+)$ vars=1 +/api/v1/items/{item_id}/notes/{note_id} -> ^/api/v1/items/([^/]+)/notes/([^/]+)$ vars=2 +/v1/{name=shelves/*/books/*} -> ^/v1/(shelves/[^/]+/books/[^/]+)$ vars=1 +/v1/{path=**} -> ^/v1(?:/(.*))?$ vars=1 +/v1/items/* -> ^/v1/items/[^/]+$ vars=0 +/v1/{id}:cancel -> ^/v1/([^/]+)$ vars=1 +/v1/{name=shelves/**} -> ^/v1/(shelves(?:/.*)?)$ vars=1 +/v1/a.b/{id} -> ^/v1/a\.b/([^/]+)$ vars=1 +nested field path: user|id +/v1 -> match path="" +/v1/ -> match path="" +/v1/a -> match path="a" +/v1/a/b -> match path="a/b" + + + +=== TEST 2: reject malformed path templates +--- request +GET /parse_reject +--- response_body +v1/no-leading-slash -> path template must start with '/' +/v1/{unbalanced -> unbalanced '{' in path template +/v1/{a={b}} -> nested variable in path template +/v1/{} -> invalid field path in path template +/v1/{=*} -> invalid field path in path template +/v1/{a-b} -> invalid field path in path template +/v1/{a..b} -> invalid field path in path template +/v1/**/more -> '**' must be the last segment in a path template +/v1/{a=**}/more -> '**' must be the last segment in a path template + + + +=== TEST 3: verb binding vs bare variable +--- request +GET /verb_precedence +--- response_body +with verb: Cancel +without verb: Plain +custom only: no rules + + + +=== TEST 4: set proto(id: 1) and routes +--- request +GET /setup +--- response_body +passed +--- wait: 1 + + + +=== TEST 5: hit route with path param +--- request +GET /api/v1/items/42 +--- response_body chomp +{"message":"GetItem id=42"} + + + +=== TEST 6: hit route by query string +--- request +GET /api/v1/items?page_size=5 +--- response_body chomp +{"message":"ListItems page_size=5"} + + + +=== TEST 7: static segment wins over variable +--- request +GET /api/v1/items/active +--- response_body chomp +{"message":"GetActiveItem"} + + + +=== TEST 8: multiple path params +--- request +GET /api/v1/items/i1/notes/n9 +--- response_body chomp +{"message":"GetItemNote item_id=i1 note_id=n9"} + + + +=== TEST 9: additional_bindings +--- request +GET /api/v1/i/i2/n/n3 +--- response_body chomp +{"message":"GetItemNote item_id=i2 note_id=n3"} + + + +=== TEST 10: body: field wraps the payload +--- request +POST /api/v1/items +{"id":"9","title":"widget","amount":50} +--- more_headers +Content-Type: application/json +--- response_body chomp +{"message":"CreateItem id=9 title=widget amount=50 request_id="} + + + +=== TEST 11: path wins over query param +--- request +GET /api/v1/items/42?id=99 +--- response_body chomp +{"message":"GetItem id=42"} + + + +=== TEST 12: path wins over body field +--- request +PATCH /api/v1/items/42 +{"id":"victim","title":"x"} +--- more_headers +Content-Type: application/json +--- response_body chomp +{"message":"UpdateItem id=42 title=x"} + + + +=== TEST 13: path wins over nested body field +--- request +PUT /api/v1/items/42 +{"id":"victim","title":"x"} +--- more_headers +Content-Type: application/json +--- response_body chomp +{"message":"ReplaceItem id=42 title=x"} + + + +=== TEST 14: path wins over body and query +--- request +PATCH /api/v1/items/42?id=victim2 +{"id":"victim","title":"x"} +--- more_headers +Content-Type: application/json +--- response_body chomp +{"message":"UpdateItem id=42 title=x"} + + + +=== TEST 15: captured value is not double decoded +--- request +GET /api/v1/items/a%2520b +--- response_body chomp +{"message":"GetItem id=a%20b"} + + + +=== TEST 16: escaped separator spans two segments +--- request +GET /api/v1/items/a%2Fb +--- error_code: 404 +--- error_log +no google.api.http binding matches GET /api/v1/items/a/b + + + +=== TEST 17: unmatched path +--- request +GET /api/v1/nonexistent +--- error_code: 404 +--- error_log +no google.api.http binding matches GET /api/v1/nonexistent + + + +=== TEST 18: wrong method +--- request +POST /api/v1/items/42 +--- error_code: 405 +--- response_headers +Allow: DELETE, GET, PATCH, PUT +--- error_log +no google.api.http binding matches POST /api/v1/items/42 + + + +=== TEST 19: method without annotation +--- request +GET /api/v1/unannotated +--- error_code: 404 + + + +=== TEST 20: proxy-rewrite uri is matched +--- request +GET /shop/77 +--- response_body chomp +{"message":"GetItem id=77"} + + + +=== TEST 21: explicit service/method still works +--- request +GET /legacy?id=legacy-7 +--- response_body chomp +{"message":"GetItem id=legacy-7"} + + + +=== TEST 22: template without verb ignores verb uri +--- request +GET /api/v1/items/42:cancel +--- error_code: 405 +--- response_headers +Allow: POST +--- error_log +no google.api.http binding matches GET /api/v1/items/42:cancel + + + +=== TEST 23: verb binding strips the verb +--- request +POST /api/v1/items/42:cancel +--- response_body chomp +{"message":"CancelItem id=42 title="} + + + +=== TEST 24: unknown verb +--- request +GET /api/v1/items/42:report +--- error_code: 404 +--- error_log +no google.api.http binding matches GET /api/v1/items/42:report + + + +=== TEST 25: colon outside the final segment +--- request +GET /api/v1/items/a:b/x +--- error_code: 404 + + + +=== TEST 26: undecodable json body +--- request +PATCH /api/v1/items/42 +{"title": broken +--- more_headers +Content-Type: application/json +--- error_code: 400 +--- error_log +failed to decode the request body as JSON + + + +=== TEST 27: omitted body is not read +--- request +POST /api/v1/items/42:cancel +{"title":"injected"} +--- more_headers +Content-Type: application/json +--- response_body chomp +{"message":"CancelItem id=42 title="} + + + +=== TEST 28: omitted body reads query +--- request +POST /api/v1/items/42:cancel?title=fromquery +{"title":"injected"} +--- more_headers +Content-Type: application/json +--- response_body chomp +{"message":"CancelItem id=42 title=fromquery"} + + + +=== TEST 29: body: field reads siblings from query +--- request +POST /api/v1/items?request_id=r1 +{"id":"9","title":"widget","amount":50} +--- more_headers +Content-Type: application/json +--- response_body chomp +{"message":"CreateItem id=9 title=widget amount=50 request_id=r1"} + + + +=== TEST 30: delete binding +--- request +DELETE /api/v1/items/42 +--- response_body chomp +{"message":"DeleteItem id=42"} + + + +=== TEST 31: custom pattern is not routable +--- request +POST /api/v1/items/42:report +--- error_code: 404 + + + +=== TEST 32: service and method required without the flag +--- request +GET /schema_requires_method +--- error_code: 400 +--- response_body eval +qr/property \\"(service|method)\\" is required/ + + + +=== TEST 33: replacing the proto rebuilds the table +--- request +GET /replace_proto +--- response_body +after update: 503 +--- error_log +no google.api.http annotation found in the proto