Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add full method name in generated code #252

Merged
merged 1 commit into from
Oct 22, 2024
Merged
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
46 changes: 34 additions & 12 deletions cmd/kod/internal/generate_generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,9 @@ func newGenerator(opt Options, pkg *packages.Package, fset *token.FileSet) (*gen
// kod.AutoMarshal struct.
tset := newTypeSet(pkg)

// Find and process all components.
components := map[string]*component{}
// Find and process all seen.
seen := map[string]*component{}
components := []*component{}
for _, file := range pkg.Syntax {
filename := fset.Position(file.Package).Filename
if filepath.Base(filename) == generatedCodeFile {
Expand All @@ -179,25 +180,28 @@ func newGenerator(opt Options, pkg *packages.Package, fset *token.FileSet) (*gen
// This code relies on the fact that a component
// interface and component implementation have to be in the same
// package. If we lift this requirement, then this code will break.
if existing, ok := components[c.fullIntfName()]; ok {
if existing, ok := seen[c.fullIntfName()]; ok {
errs = append(errs, errorf(pkg.Fset, c.impl.Obj().Pos(),
"Duplicate implementation for component %s, other declaration: %v",
c.fullIntfName(), fset.Position(existing.impl.Obj().Pos())))
continue
}
components[c.fullIntfName()] = c
seen[c.fullIntfName()] = c
components = append(components, c)
}
}
if err := errors.Join(errs...); err != nil {
return nil, err
}

// slices.Reverse(components)

return &generator{
opt: opt,
pkg: pkg,
tset: tset,
fileset: fset,
components: lo.Values(components),
components: components,
}, nil
}

Expand Down Expand Up @@ -393,6 +397,10 @@ func (c *component) intfName() string {
return c.intf.Obj().Name()
}

func (c *component) fullMethodNameVar(methodName string) string {
return fmt.Sprintf("%s_%s_FullMethodName", c.intfName(), methodName)
}

// implName returns the component implementation name.
func (c *component) implName() string {
return c.impl.Obj().Name()
Expand Down Expand Up @@ -549,10 +557,10 @@ func (g *generator) generate() error {
return nil
}

// Process components in deterministic order.
sort.Slice(g.components, func(i, j int) bool {
return g.components[i].intfName() < g.components[j].intfName()
})
// // Process components in deterministic order.
// sort.Slice(g.components, func(i, j int) bool {
// return g.components[i].intfName() < g.components[j].intfName()
// })

// Generate the file body.
var body bytes.Buffer
Expand All @@ -574,7 +582,9 @@ func (g *generator) generate() error {
fn := func(format string, args ...interface{}) {
fmt.Fprintln(&header, fmt.Sprintf(format, args...))
}

g.generateImports(fn)
g.generateFullMethodNames(fn)
}

// Create a generated file.
Expand Down Expand Up @@ -643,6 +653,19 @@ func (g *generator) generateImports(p printFn) {
p(`)`)
}

func (g *generator) generateFullMethodNames(p printFn) {
p(``)
p(`// Full method names for components.`)
p(`const (`)
for _, comp := range g.components {
for _, m := range comp.methods() {
p(`// %s is the full name of the method [%s.%s].`, comp.fullMethodNameVar(m.Name()), comp.implName(), m.Name())
p(`%s = %q`, comp.fullMethodNameVar(m.Name()), comp.fullIntfName())
}
}
p(`)`)
}

// generateInstanceChecks generates code that checks that every component
// implementation type implements kod.InstanceOf[T] for the appropriate T.
func (g *generator) generateInstanceChecks(p printFn) {
Expand Down Expand Up @@ -798,10 +821,9 @@ func (g *generator) generateLocalStubs(p printFn) {
p(`info := interceptor.CallInfo {
Impl: s.impl,
Component: s.name,
FullMethod: "%s.%s",
Method: "%s",
FullMethod: %s,
}
`, comp.fullIntfName(), m.Name(), m.Name())
`, comp.fullMethodNameVar(m.Name()))

p(`%s = s.interceptor(ctx, info, []any{%s}, []any{%s}, call)`,
lo.If(haveError(mt), "err").Else("_"),
Expand Down
106 changes: 56 additions & 50 deletions examples/helloworld/kod_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 1 addition & 3 deletions interceptor/interceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ type CallInfo struct {
Component string
// The full name of the called method, in the format of "package/service.method".
FullMethod string
// The name of the method.
Method string
}

// HandleFunc is the type of the function invoked by Components.
Expand Down Expand Up @@ -102,6 +100,6 @@ func Not(condition Condition) Condition {
// IsMethod returns a condition that checks if the method name matches the given method.
func IsMethod(method string) Condition {
return func(_ context.Context, info CallInfo) bool {
return info.Method == method
return info.FullMethod == method
}
}
4 changes: 2 additions & 2 deletions interceptor/interceptor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,15 +272,15 @@ func TestIsMethod(t *testing.T) {
name: "Method matches",
method: "test",
info: CallInfo{
Method: "test",
FullMethod: "test",
},
expected: true,
},
{
name: "Method does not match",
method: "test",
info: CallInfo{
Method: "other",
FullMethod: "other",
},
expected: false,
},
Expand Down
2 changes: 1 addition & 1 deletion interceptor/kaccesslog/accesslog.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ func Interceptor() interceptor.Interceptor {
attrs := []slog.Attr{
slog.Any("req", req),
slog.Any("reply", reply),
slog.String("method", info.Method),
slog.String("method", info.FullMethod),
slog.Int64("cost", time.Since(now).Milliseconds()),
}

Expand Down
2 changes: 1 addition & 1 deletion interceptor/kmetric/metric.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func Interceptor() interceptor.Interceptor {

as := attribute.NewSet(
attribute.String("component", info.Component),
attribute.String("method", info.Method),
attribute.String("method", info.FullMethod),
)

if err != nil {
Expand Down
Loading
Loading