Skip to content

Commit

Permalink
fix(grpc-gateway) map grpc-status to HTTP status code (#25)
Browse files Browse the repository at this point in the history
Fix #24
  • Loading branch information
fffonion authored and gszr committed Jun 17, 2021
1 parent b605ada commit b99dd8c
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 1 deletion.
32 changes: 32 additions & 0 deletions kong/plugins/grpc-gateway/handler.lua
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,28 @@ function grpc_gateway:access(conf)
end


-- https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
local grpc_status_map = {
[0] = 200, -- OK
[1] = 499, -- CANCELLED
[2] = 500, -- UNKNOWN
[3] = 400, -- INVALID_ARGUMENT
[4] = 504, -- DEADLINE_EXCEEDED
[5] = 404, -- NOT_FOUND
[6] = 409, -- ALREADY_EXISTS
[7] = 403, -- PERMISSION_DENIED
[16] = 401, -- UNAUTHENTICATED
[8] = 429, -- RESOURCE_EXHAUSTED
[9] = 400, -- FAILED_PRECONDITION
[10] = 409, -- ABORTED
[11] = 400, -- OUT_OF_RANGE
[12] = 500, -- UNIMPLEMENTED
[13] = 500, -- INTERNAL
[14] = 503, -- UNAVAILABLE
[15] = 500, -- DATA_LOSS
}


function grpc_gateway:header_filter(conf)
if kong_request_get_method() == "OPTIONS" then
return
Expand All @@ -76,6 +98,16 @@ function grpc_gateway:header_filter(conf)
if dec then
kong_response_set_header("Content-Type", "application/json")
end

local grpc_status = tonumber(ngx.header['grpc-status'])
if grpc_status then
local http_status = grpc_status_map[grpc_status]
if not http_status then
kong.log.warn("Unable to map grpc-status ", ngx.header['grpc-status'], " to HTTP status code")
http_status = 500
end
ngx.status = http_status
end
end


Expand Down
10 changes: 9 additions & 1 deletion spec/01-proxy_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -91,9 +91,17 @@ for _, strategy in helpers.each_strategy() do

test("unknown path", function()
local res, _ = proxy_client:get("/v1/messages/john_doe/bai")
assert.not_equal(200, res.status)
assert.equal(400, res.status)
assert.equal("Bad Request", res.reason)
end)

test("transforms grpc-status to HTTP status code", function()
local res, _ = proxy_client:get("/v1/unknown/john_doe")
-- per ttps://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
-- grpc-status: 12: UNIMPLEMENTED are mapped to http code 500
assert.equal(500, res.status)
assert.equal('12', res.headers['grpc-status'])
end)

end)
end
7 changes: 7 additions & 0 deletions spec/fixtures/grpc/helloworld.proto
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ service HelloService {
body: "*"
}
};

// define a gRPC method that's not implemented in grpcbin
rpc UnknownMethod(HelloRequest) returns (HelloResponse) {
option (google.api.http) = {
get: "/v1/unknown/{greeting}"
}
};
}

message HelloRequest {
Expand Down

0 comments on commit b99dd8c

Please sign in to comment.