Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions cbt.go
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,14 @@ var commands = []struct {
Usage: "cbt getappprofile <instance-id> <profile-id>",
Required: ProjectAndInstanceRequired,
},
{
Name: "getfunction",
Desc: "Read metadata for a user-defined function in the configured instance",
do: doGetFunction,
Usage: "cbt getfunction <function-id>\n\n" +
" Example: cbt getfunction doc_has_keyword",
Required: ProjectAndInstanceRequired,
},
// {
// Name: "getsnapshot",
// Desc: "Get backups info (deprecated)",
Expand Down
9 changes: 9 additions & 0 deletions cbtdoc.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ The commands are:
deletetable Delete a table
doc Print godoc-suitable documentation for cbt
getappprofile Read app profile for an instance
getfunction Read metadata for a user-defined function in the configured instance
help Print help text
import Batch write many rows based on the input file
listappprofile Lists app profile for an instance
Expand Down Expand Up @@ -248,6 +249,14 @@ Usage:

cbt getappprofile <instance-id> <profile-id>

# Read metadata for a user-defined function in the configured instance

Usage:

cbt getfunction <function-id>

Example: cbt getfunction doc_has_keyword

# Print help text

Usage:
Expand Down
65 changes: 65 additions & 0 deletions functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,18 +38,21 @@ import (
)

const (
maxFunctionIdentifierLen = 128
googleCloudResourcePrefixHeader = "google-cloud-resource-prefix"
xGoogRequestParamsHeader = "x-goog-request-params"
)

var (
functionIdentifierRE = regexp.MustCompile(`^[a-z_][a-z0-9_]*$`)
emulatorSchemeRE = regexp.MustCompile(`^(http://|https://|passthrough:///)`)
functionAdminConnPool gtransport.ConnPool
)

// functionAdminAPI abstracts the BigtableInstanceAdmin Function RPCs so CLI
// commands can be tested hermetically without package-level globals.
type functionAdminAPI interface {
GetFunction(ctx context.Context, req *btapb.GetFunctionRequest) (*btapb.Function, error)
ListFunctions(ctx context.Context, req *btapb.ListFunctionsRequest) (*btapb.ListFunctionsResponse, error)
}

Expand Down Expand Up @@ -112,10 +115,24 @@ func withRequestParams(ctx context.Context, key, val string) context.Context {
return metadata.AppendToOutgoingContext(ctx, xGoogRequestParamsHeader, fmt.Sprintf("%s=%s", key, url.QueryEscape(val)))
}

func (c *grpcFunctionAdminClient) GetFunction(ctx context.Context, req *btapb.GetFunctionRequest) (*btapb.Function, error) {
return c.admin.GetFunction(withRequestParams(ctx, "name", req.GetName()), req)
}

func (c *grpcFunctionAdminClient) ListFunctions(ctx context.Context, req *btapb.ListFunctionsRequest) (*btapb.ListFunctionsResponse, error) {
return c.admin.ListFunctions(withRequestParams(ctx, "parent", req.GetParent()), req)
}

func validateFunctionIdentifier(id, label string) error {
if len(id) > maxFunctionIdentifierLen {
return fmt.Errorf("%s %q exceeds maximum length of %d characters", label, id, maxFunctionIdentifierLen)
}
if !functionIdentifierRE.MatchString(id) {
return fmt.Errorf("invalid %s %q: must match [a-z_][a-z0-9_]*", label, id)
}
return nil
}

// formatAdminType is a total, non-panicking formatter across all Bigtable Admin
// Type variants so listfunctions and getfunction render both WasmFunction and
// SqlScalarFunction definitions cleanly.
Expand Down Expand Up @@ -194,6 +211,10 @@ func instanceResourceName(project, instance string) string {
return fmt.Sprintf("projects/%s/instances/%s", project, instance)
}

func functionResourceName(project, instance, functionID string) string {
return fmt.Sprintf("projects/%s/instances/%s/functions/%s", project, instance, functionID)
}

func runListFunctions(ctx context.Context, api functionAdminAPI, project, instance string, w io.Writer, args ...string) error {
if len(args) != 0 {
return errors.New("usage: cbt listfunctions")
Expand Down Expand Up @@ -230,8 +251,52 @@ func runListFunctions(ctx context.Context, api functionAdminAPI, project, instan
return tw.Flush()
}

func runGetFunction(ctx context.Context, api functionAdminAPI, project, instance string, w io.Writer, args ...string) error {
if len(args) != 1 {
return errors.New("usage: cbt getfunction <function-id>")
}
functionID := args[0]
if err := validateFunctionIdentifier(functionID, "function-id"); err != nil {
return err
}
baseCtx := withResourcePrefix(ctx, project)
fn, err := api.GetFunction(baseCtx, &btapb.GetFunctionRequest{
Name: functionResourceName(project, instance, functionID),
})
if err != nil {
return fmt.Errorf("getting function %q: %w", functionID, err)
}

kind, _ := describeFunctionKindAndSignature(fn)
fmt.Fprintf(w, "Name: %s\n", fn.GetName())
fmt.Fprintf(w, "Type: %s\n", kind)
if fn.GetEtag() != "" {
fmt.Fprintf(w, "Etag: %s\n", fn.GetEtag())
}
fmt.Fprintf(w, "DeletionProtection: %t\n", fn.GetDeletionProtection())
switch ft := fn.GetFunctionType().(type) {
case *btapb.Function_WasmFunction_:
fmt.Fprintf(w, "Arguments: %s\n", formatArgumentList(ft.WasmFunction.GetArguments()))
fmt.Fprintf(w, "ReturnType: %s\n", formatAdminType(ft.WasmFunction.GetReturnType()))
if ft.WasmFunction.GetSourceSha256() != "" {
fmt.Fprintf(w, "SourceSha256: %s\n", ft.WasmFunction.GetSourceSha256())
}
case *btapb.Function_SqlScalarFunction_:
fmt.Fprintf(w, "Arguments: %s\n", formatArgumentList(ft.SqlScalarFunction.GetArguments()))
fmt.Fprintf(w, "ReturnType: %s\n", formatAdminType(ft.SqlScalarFunction.GetReturnType()))
fmt.Fprintf(w, "FunctionBody: %s\n", ft.SqlScalarFunction.GetFunctionBody())
}
return nil
}

func doListFunctions(ctx context.Context, args ...string) {
if err := runListFunctions(ctx, defaultFunctionAdminAPI(), config.Project, config.Instance, os.Stdout, args...); err != nil {
log.Fatal(err)
}
}

func doGetFunction(ctx context.Context, args ...string) {
if err := runGetFunction(ctx, defaultFunctionAdminAPI(), config.Project, config.Instance, os.Stdout, args...); err != nil {
log.Fatal(err)
}
}
198 changes: 198 additions & 0 deletions functions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,10 @@ type fakeFunctionAdminServer struct {

mu sync.Mutex
calls []recordedAdminCall
getReqs []*btapb.GetFunctionRequest
listReqs []*btapb.ListFunctionsRequest

getFn func(context.Context, *btapb.GetFunctionRequest) (*btapb.Function, error)
listFn func(context.Context, *btapb.ListFunctionsRequest) (*btapb.ListFunctionsResponse, error)
}

Expand Down Expand Up @@ -75,6 +77,19 @@ func (s *fakeFunctionAdminServer) callsFor(method string) []recordedAdminCall {
return out
}

func (s *fakeFunctionAdminServer) GetFunction(ctx context.Context, req *btapb.GetFunctionRequest) (*btapb.Function, error) {
s.record(ctx, "GetFunction")
cloned := proto.Clone(req).(*btapb.GetFunctionRequest)
s.mu.Lock()
s.getReqs = append(s.getReqs, cloned)
fn := s.getFn
s.mu.Unlock()
if fn != nil {
return fn(ctx, req)
}
return nil, status.Error(codes.Unimplemented, "unexpected GetFunction")
}

func (s *fakeFunctionAdminServer) ListFunctions(ctx context.Context, req *btapb.ListFunctionsRequest) (*btapb.ListFunctionsResponse, error) {
s.record(ctx, "ListFunctions")
cloned := proto.Clone(req).(*btapb.ListFunctionsRequest)
Expand Down Expand Up @@ -173,6 +188,188 @@ func TestFormatAdminType_AllSQLVariants(t *testing.T) {
}
}

// Verify getfunction argument and identifier rejections fail fast with zero outbound gRPC calls.
func TestRunGetFunction_ValidationErrors_ZeroRPCs(t *testing.T) {
srv := &fakeFunctionAdminServer{}
api := startFakeFunctionAdminGRPC(t, srv)

errCases := []struct {
name string
args []string
wantSub string
}{
{
name: "get_no_args_rejected",
args: nil,
wantSub: "usage: cbt getfunction",
},
{
name: "get_too_many_args_rejected",
args: []string{"doc_fn", "extra"},
wantSub: "usage: cbt getfunction",
},
{
name: "get_invalid_function_id_rejected",
args: []string{"BadFunc"},
wantSub: "invalid function-id",
},
{
name: "get_overlong_function_id_rejected",
args: []string{strings.Repeat("f", maxFunctionIdentifierLen+1)},
wantSub: "exceeds maximum length",
},
}

for _, tc := range errCases {
t.Run(tc.name, func(t *testing.T) {
before := srv.totalCalls()
err := runGetFunction(t.Context(), api, "p", "i", io.Discard, tc.args...)
if err == nil {
t.Fatalf("runGetFunction(%v) = nil, want error containing %q", tc.args, tc.wantSub)
}
if !strings.Contains(err.Error(), tc.wantSub) {
t.Errorf("runGetFunction(%v) error = %q, want substring %q", tc.args, err.Error(), tc.wantSub)
}
if got := srv.totalCalls() - before; got != 0 {
t.Errorf("runGetFunction(%v) outbound gRPC calls = %d, want 0", tc.args, got)
}
})
}
}

// UT-9 & UT-10a: Verify getfunction WASM metadata rendering with lowercase hex
// SourceSha256 digest and Etag.
func TestRunGetFunction_WASMWithSHA256AndEtag(t *testing.T) {
fnPrefix := "projects/my-proj/instances/my-inst/functions/"
const fnID = "doc_extract_snippet"
const sourceSHA256 = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"

srv := &fakeFunctionAdminServer{
getFn: func(_ context.Context, req *btapb.GetFunctionRequest) (*btapb.Function, error) {
return &btapb.Function{
Name: req.GetName(),
Etag: `W/"v2"`,
DeletionProtection: true,
FunctionType: &btapb.Function_WasmFunction_{
WasmFunction: &btapb.Function_WasmFunction{
Arguments: []*btapb.Function_Argument{{Name: "doc", DataType: &btapb.Type{Kind: &btapb.Type_BytesType{BytesType: &btapb.Type_Bytes{}}}}},
ReturnType: &btapb.Type{Kind: &btapb.Type_StringType{StringType: &btapb.Type_String{}}},
SourceSha256: sourceSHA256,
},
},
}, nil
},
}
api := startFakeFunctionAdminGRPC(t, srv)

var out bytes.Buffer
if err := runGetFunction(t.Context(), api, "my-proj", "my-inst", &out, fnID); err != nil {
t.Fatalf("runGetFunction(%q) unexpected error: %v", fnID, err)
}
wantName := fnPrefix + fnID
if gotName := srv.getReqs[0].GetName(); gotName != wantName {
t.Errorf("GetFunction(%q) Request.Name = %q, want %q", fnID, gotName, wantName)
}
getCalls := srv.callsFor("GetFunction")
if diff := cmp.Diff([]string{"name=" + url.QueryEscape(wantName)}, getCalls[0].md.Get(xGoogRequestParamsHeader)); diff != "" {
t.Errorf("GetFunction(%q) x-goog-request-params mismatch (-want +got):\n%s", fnID, diff)
}
if diff := cmp.Diff([]string{"projects/my-proj"}, getCalls[0].md.Get(googleCloudResourcePrefixHeader)); diff != "" {
t.Errorf("GetFunction(%q) google-cloud-resource-prefix mismatch (-want +got):\n%s", fnID, diff)
}
wantOut := strings.Join([]string{
"Name: " + wantName,
"Type: WASM",
`Etag: W/"v2"`,
"DeletionProtection: true",
"Arguments: doc:BYTES",
"ReturnType: STRING",
"SourceSha256: " + sourceSHA256,
"",
}, "\n")
if diff := cmp.Diff(wantOut, out.String()); diff != "" {
t.Errorf("runGetFunction(%q) output mismatch (-want +got):\n%s", fnID, diff)
}
}

// UT-9b: Verify getfunction omits optional Etag and SourceSha256 lines when empty.
func TestRunGetFunction_WASMWithoutSHA256OrEtag(t *testing.T) {
srv := &fakeFunctionAdminServer{
getFn: func(_ context.Context, req *btapb.GetFunctionRequest) (*btapb.Function, error) {
return &btapb.Function{
Name: req.GetName(),
FunctionType: &btapb.Function_WasmFunction_{
WasmFunction: &btapb.Function_WasmFunction{
Arguments: []*btapb.Function_Argument{{Name: "x", DataType: &btapb.Type{Kind: &btapb.Type_Int32Type{Int32Type: &btapb.Type_Int32{}}}}},
ReturnType: &btapb.Type{Kind: &btapb.Type_Int32Type{Int32Type: &btapb.Type_Int32{}}},
},
},
}, nil
},
}
api := startFakeFunctionAdminGRPC(t, srv)

var out bytes.Buffer
if err := runGetFunction(t.Context(), api, "my-proj", "my-inst", &out, "no_sha"); err != nil {
t.Fatalf("runGetFunction unexpected error: %v", err)
}
if strings.Contains(out.String(), "SourceSha256:") || strings.Contains(out.String(), "Etag:") {
t.Errorf("runGetFunction output = %q, should omit empty SourceSha256 and Etag", out.String())
}
}

// UT-9c: Verify getfunction formats SqlScalarFunction definitions with ANY and DATE types.
func TestRunGetFunction_SQLScalarFunction(t *testing.T) {
fnPrefix := "projects/my-proj/instances/my-inst/functions/"
srv := &fakeFunctionAdminServer{
getFn: func(_ context.Context, req *btapb.GetFunctionRequest) (*btapb.Function, error) {
return &btapb.Function{
Name: req.GetName(),
FunctionType: &btapb.Function_SqlScalarFunction_{
SqlScalarFunction: &btapb.Function_SqlScalarFunction{
Arguments: []*btapb.Function_Argument{{Name: "x", DataType: nil}},
ReturnType: &btapb.Type{Kind: &btapb.Type_DateType{DateType: &btapb.Type_Date{}}},
FunctionBody: "DATE_FROM_UNIX_DATE(x)",
},
},
}, nil
},
}
api := startFakeFunctionAdminGRPC(t, srv)

var out bytes.Buffer
if err := runGetFunction(t.Context(), api, "my-proj", "my-inst", &out, "sql_fn"); err != nil {
t.Fatalf("runGetFunction unexpected error: %v", err)
}
wantOut := strings.Join([]string{
"Name: " + fnPrefix + "sql_fn",
"Type: SQL",
"DeletionProtection: false",
"Arguments: x:ANY",
"ReturnType: DATE",
"FunctionBody: DATE_FROM_UNIX_DATE(x)",
"",
}, "\n")
if diff := cmp.Diff(wantOut, out.String()); diff != "" {
t.Errorf("runGetFunction SQL output mismatch (-want +got):\n%s", diff)
}
}

// UT-10c: Verify NotFound gRPC error propagation on GetFunction.
func TestRunGetFunction_StatusErrorPropagation(t *testing.T) {
srv := &fakeFunctionAdminServer{
getFn: func(_ context.Context, _ *btapb.GetFunctionRequest) (*btapb.Function, error) {
return nil, status.Error(codes.NotFound, "function not found")
},
}
api := startFakeFunctionAdminGRPC(t, srv)

err := runGetFunction(t.Context(), api, "my-proj", "my-inst", io.Discard, "fn_err")
if gotCode := status.Code(err); gotCode != codes.NotFound {
t.Errorf("status.Code(err) = %v, want %v (err: %v)", gotCode, codes.NotFound, err)
}
}

// UT-8 & UT-9: Verify listfunctions pagination, single non-duplicated routing headers per page,
// unexpected positional argument rejection, and formatting of WASM and SQL functions.
func TestRunListFunctions_PaginationHeadersAndSQLTypes(t *testing.T) {
Expand Down Expand Up @@ -319,6 +516,7 @@ func TestRunListFunctions_PaginationHeadersAndSQLTypes(t *testing.T) {
}

var allFunctionCommandNames = []string{
"getfunction",
"listfunctions",
}

Expand Down
Loading