-
Notifications
You must be signed in to change notification settings - Fork 27
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Implement concurrent safe WASM GRPC query handler. (#1034)
- Loading branch information
1 parent
e64bdaa
commit 28bc015
Showing
5 changed files
with
225 additions
and
62 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -12,7 +12,7 @@ concurrency: | |
|
||
jobs: | ||
ci: | ||
timeout-minutes: 60 | ||
timeout-minutes: 90 | ||
strategy: | ||
fail-fast: false | ||
matrix: | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,129 @@ | ||
package handler | ||
|
||
import ( | ||
"fmt" | ||
"sync" | ||
|
||
msgv1 "cosmossdk.io/api/cosmos/msg/v1" | ||
queryv1 "cosmossdk.io/api/cosmos/query/v1" | ||
nfttypes "cosmossdk.io/x/nft" | ||
wasmvmtypes "github.com/CosmWasm/wasmvm/v2/types" | ||
abci "github.com/cometbft/cometbft/abci/types" | ||
"github.com/cosmos/cosmos-sdk/baseapp" | ||
"github.com/cosmos/cosmos-sdk/codec" | ||
sdk "github.com/cosmos/cosmos-sdk/types" | ||
gogoproto "github.com/cosmos/gogoproto/proto" | ||
"google.golang.org/protobuf/proto" | ||
"google.golang.org/protobuf/reflect/protodesc" | ||
"google.golang.org/protobuf/reflect/protoreflect" | ||
"google.golang.org/protobuf/types/dynamicpb" | ||
) | ||
|
||
// GRPCQuerier is a WASM grpc querier. | ||
type GRPCQuerier struct { | ||
gRPCQueryRouter *baseapp.GRPCQueryRouter | ||
codec codec.Codec | ||
// map[query proto URL]proto response type | ||
acceptedQueries map[string]func() gogoproto.Message | ||
mu sync.Mutex | ||
} | ||
|
||
// NewGRPCQuerier returns a new instance of GRPCQuerier. | ||
func NewGRPCQuerier(gRPCQueryRouter *baseapp.GRPCQueryRouter, codec codec.Codec) *GRPCQuerier { | ||
acceptedQueries := newModuleQuerySafeAllowList() | ||
// "/cosmos.nft.v1beta1.Query/Owner" is not marked as module_query_safe in cosmos, but we need it | ||
acceptedQueries["/cosmos.nft.v1beta1.Query/Owner"] = func() gogoproto.Message { | ||
return &nfttypes.QueryOwnerResponse{} | ||
} | ||
|
||
return &GRPCQuerier{ | ||
gRPCQueryRouter: gRPCQueryRouter, | ||
codec: codec, | ||
acceptedQueries: acceptedQueries, | ||
mu: sync.Mutex{}, | ||
} | ||
} | ||
|
||
// Query returns WASM GRPC query handler. | ||
func (q *GRPCQuerier) Query(ctx sdk.Context, request *wasmvmtypes.GrpcQuery) (gogoproto.Message, error) { | ||
protoResponseBuilder, accepted := q.acceptedQueries[request.Path] | ||
if !accepted { | ||
return nil, wasmvmtypes.UnsupportedRequest{ | ||
Kind: fmt.Sprintf("'%s' path is not allowed from the contract", request.Path), | ||
} | ||
} | ||
protoResponse := protoResponseBuilder() | ||
|
||
handler := q.gRPCQueryRouter.Route(request.Path) | ||
if handler == nil { | ||
return nil, wasmvmtypes.UnsupportedRequest{Kind: fmt.Sprintf("No route to query '%s'", request.Path)} | ||
} | ||
|
||
q.mu.Lock() | ||
res, err := handler(ctx, &abci.RequestQuery{ | ||
Data: request.Data, | ||
Path: request.Path, | ||
}) | ||
q.mu.Unlock() | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
// decode the query response into the expected protobuf message | ||
err = q.codec.Unmarshal(res.Value, protoResponse) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return protoResponse, nil | ||
} | ||
|
||
// newModuleQuerySafeAllowList returns a map of all query paths labeled with module_query_safe in the proto files to | ||
// their response proto. | ||
func newModuleQuerySafeAllowList() map[string]func() gogoproto.Message { | ||
fds, err := gogoproto.MergedGlobalFileDescriptors() | ||
if err != nil { | ||
panic(err) | ||
} | ||
// create the files using 'AllowUnresolvable' to avoid | ||
// unnecessary panic: https://github.com/cosmos/ibc-go/issues/6435 | ||
protoFiles, err := protodesc.FileOptions{ | ||
AllowUnresolvable: true, | ||
}.NewFiles(fds) | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
allowList := make(map[string]func() gogoproto.Message) | ||
protoFiles.RangeFiles(func(fd protoreflect.FileDescriptor) bool { | ||
for i := range fd.Services().Len() { | ||
// Get the service descriptor | ||
sd := fd.Services().Get(i) | ||
|
||
// Skip services that are annotated with the "cosmos.msg.v1.service" option. | ||
if ext := proto.GetExtension(sd.Options(), msgv1.E_Service); ext != nil && ext.(bool) { | ||
continue | ||
} | ||
|
||
for j := range sd.Methods().Len() { | ||
// Get the method descriptor | ||
md := sd.Methods().Get(j) | ||
|
||
// Skip methods that are not annotated with the "cosmos.query.v1.module_query_safe" option. | ||
if ext := proto.GetExtension(md.Options(), queryv1.E_ModuleQuerySafe); ext == nil || !ext.(bool) { | ||
continue | ||
} | ||
|
||
// Add the method to the whitelist | ||
path := fmt.Sprintf("/%s/%s", sd.FullName(), md.Name()) | ||
out := md.Output() | ||
allowList[path] = func() gogoproto.Message { | ||
return dynamicpb.NewMessage(out) | ||
} | ||
} | ||
} | ||
return true | ||
}) | ||
|
||
return allowList | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
package handler_test | ||
|
||
import ( | ||
"context" | ||
"reflect" | ||
"testing" | ||
"time" | ||
|
||
sdkmath "cosmossdk.io/math" | ||
wasmvmtypes "github.com/CosmWasm/wasmvm/v2/types" | ||
tmproto "github.com/cometbft/cometbft/proto/tendermint/types" | ||
gogoproto "github.com/cosmos/gogoproto/proto" | ||
"github.com/pkg/errors" | ||
"github.com/stretchr/testify/require" | ||
"golang.org/x/sync/errgroup" | ||
|
||
"github.com/CoreumFoundation/coreum/v5/testutil/simapp" | ||
assetfttypes "github.com/CoreumFoundation/coreum/v5/x/asset/ft/types" | ||
"github.com/CoreumFoundation/coreum/v5/x/wasm/handler" | ||
) | ||
|
||
func TestGRPCQuerier_Query(t *testing.T) { | ||
ctx, cancel := context.WithCancel(context.Background()) | ||
t.Cleanup(cancel) | ||
|
||
testApp := simapp.New() | ||
sdkCtx := testApp.BaseApp.NewContextLegacy(false, tmproto.Header{ | ||
Time: time.Now(), | ||
AppHash: []byte("some-hash"), | ||
}) | ||
|
||
issuer, _ := testApp.GenAccount(sdkCtx) | ||
settingsWithExtension := assetfttypes.IssueSettings{ | ||
Issuer: issuer, | ||
Symbol: "DEFEXT", | ||
Subunit: "defext", | ||
Precision: 6, | ||
InitialAmount: sdkmath.NewIntWithDecimal(1, 10), | ||
} | ||
denom, err := testApp.AssetFTKeeper.Issue(sdkCtx, settingsWithExtension) | ||
require.NoError(t, err) | ||
|
||
q := handler.NewGRPCQuerier(testApp.GRPCQueryRouter(), testApp.AppCodec()) | ||
queryTokenReq := &assetfttypes.QueryTokenRequest{ | ||
Denom: denom, | ||
} | ||
wasmGrpcData, err := testApp.AppCodec().Marshal(queryTokenReq) | ||
require.NoError(t, err) | ||
|
||
eg, _ := errgroup.WithContext(ctx) | ||
for range 1000 { | ||
eg.Go(func() error { | ||
wasmGrpcReq := &wasmvmtypes.GrpcQuery{ | ||
Data: wasmGrpcData, | ||
// url which corresponds query token | ||
Path: "/coreum.asset.ft.v1.Query/Token", | ||
} | ||
wasmGrpcRes, err := q.Query(sdkCtx, wasmGrpcReq) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
queryTokenResData, err := gogoproto.Marshal(wasmGrpcRes) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
queryTokenRes := &assetfttypes.QueryTokenResponse{} | ||
if err := testApp.AppCodec().Unmarshal(queryTokenResData, queryTokenRes); err != nil { | ||
return err | ||
} | ||
|
||
want := assetfttypes.Token{ | ||
Denom: denom, | ||
Issuer: issuer.String(), | ||
Symbol: settingsWithExtension.Symbol, | ||
Subunit: settingsWithExtension.Subunit, | ||
Precision: settingsWithExtension.Precision, | ||
BurnRate: sdkmath.LegacyNewDec(0), | ||
SendCommissionRate: sdkmath.LegacyNewDec(0), | ||
Version: assetfttypes.CurrentTokenVersion, | ||
Admin: issuer.String(), | ||
} | ||
if !reflect.DeepEqual(want, queryTokenRes.Token) { | ||
return errors.Errorf("unexpected token, want:%v, got:%v", want, queryTokenRes.Token) | ||
} | ||
return nil | ||
}) | ||
} | ||
|
||
require.NoError(t, eg.Wait()) | ||
} |