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

docs: add comments for funcs #22276

Closed
wants to merge 1 commit into from
Closed
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
2 changes: 2 additions & 0 deletions collections/codec/string.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func (stringKey[T]) Size(key T) int {
return len(key)
}

// EncodeNonTerminal writes the string key to the provided buffer in non-terminal encoding format.
func (stringKey[T]) EncodeNonTerminal(buffer []byte, key T) (int, error) {
for i := range key {
c := key[i]
Expand All @@ -49,6 +50,7 @@ func (stringKey[T]) EncodeNonTerminal(buffer []byte, key T) (int, error) {
return len(key) + 1, nil
}

// DecodeNonTerminal reads a string key from the provided buffer in non-terminal encoding format.
func (stringKey[T]) DecodeNonTerminal(buffer []byte) (int, T, error) {
i := bytes.IndexByte(buffer, StringDelimiter)
if i == -1 {
Expand Down
7 changes: 6 additions & 1 deletion crypto/keyring/autocli.go
Wukingbow marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ type autoCLIKeyring interface {
KeyInfo(name string) (string, string, uint, error)
}

// NewAutoCLIKeyring wraps the SDK keyring and make it compatible with the AutoCLI keyring interfaces.
// NewAutoCLIKeyring wraps the SDK keyring and makes it compatible with the AutoCLI keyring interfaces.
func NewAutoCLIKeyring(kr Keyring, ac address.Codec) (autoCLIKeyring, error) {
return &autoCLIKeyringAdapter{kr, ac}, nil
}
Expand All @@ -40,6 +40,7 @@ type autoCLIKeyringAdapter struct {
ac address.Codec
}

// List returns the names of all keys stored in the keyring.
func (a *autoCLIKeyringAdapter) List() ([]string, error) {
list, err := a.Keyring.List()
if err != nil {
Expand Down Expand Up @@ -69,6 +70,7 @@ func (a *autoCLIKeyringAdapter) LookupAddressByKeyName(name string) ([]byte, err
return addr, nil
}

// GetPubKey returns the public key of the key with the given name.
func (a *autoCLIKeyringAdapter) GetPubKey(name string) (cryptotypes.PubKey, error) {
record, err := a.Keyring.Key(name)
if err != nil {
Expand All @@ -78,6 +80,7 @@ func (a *autoCLIKeyringAdapter) GetPubKey(name string) (cryptotypes.PubKey, erro
return record.GetPubKey()
}

// Sign signs the given bytes with the key with the given name.
func (a *autoCLIKeyringAdapter) Sign(name string, msg []byte, signMode signingv1beta1.SignMode) ([]byte, error) {
record, err := a.Keyring.Key(name)
if err != nil {
Expand All @@ -93,6 +96,7 @@ func (a *autoCLIKeyringAdapter) Sign(name string, msg []byte, signMode signingv1
return signBytes, err
}

// KeyType returns the type of the key with the given name.
func (a *autoCLIKeyringAdapter) KeyType(name string) (uint, error) {
record, err := a.Keyring.Key(name)
if err != nil {
Expand All @@ -102,6 +106,7 @@ func (a *autoCLIKeyringAdapter) KeyType(name string) (uint, error) {
return uint(record.GetType()), nil
}

// KeyInfo returns key name, key address, and key type given a key name or address.
func (a *autoCLIKeyringAdapter) KeyInfo(nameOrAddr string) (string, string, uint, error) {
addr, err := a.ac.StringToBytes(nameOrAddr)
if err != nil {
Expand Down
8 changes: 8 additions & 0 deletions crypto/keys/bcrypt/bcrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ func Cost(hashedPassword []byte) (uint32, error) {
return p.cost, nil
}

// newFromPassword creates a new hashed structure from the given password and salt.
func newFromPassword(salt, password []byte, cost uint32) (*hashed, error) {
if cost < MinCost {
cost = DefaultCost
Expand All @@ -153,6 +154,7 @@ func newFromPassword(salt, password []byte, cost uint32) (*hashed, error) {
return p, err
}

// newFromHash creates a new hashed structure from the given hashed password.
func newFromHash(hashedSecret []byte) (*hashed, error) {
if len(hashedSecret) < minHashSize {
return nil, ErrHashTooShort
Expand Down Expand Up @@ -181,6 +183,7 @@ func newFromHash(hashedSecret []byte) (*hashed, error) {
return p, nil
}

// bcrypt generates a hash using the Blowfish algorithm with the given password, cost, and salt.
func bcrypt(password []byte, cost uint32, salt []byte) ([]byte, error) {
cipherData := make([]byte, len(magicCipherData))
copy(cipherData, magicCipherData)
Expand All @@ -202,6 +205,7 @@ func bcrypt(password []byte, cost uint32, salt []byte) ([]byte, error) {
return hsh, nil
}

// expensiveBlowfishSetup sets up the Blowfish cipher with the given password, cost, and salt.
func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cipher, error) {
csalt, err := base64Decode(salt)
if err != nil {
Expand All @@ -228,6 +232,7 @@ func expensiveBlowfishSetup(key []byte, cost uint32, salt []byte) (*blowfish.Cip
return c, nil
}

// Hash returns the encoded bcrypt hash.
func (p *hashed) Hash() []byte {
arr := make([]byte, 60)
arr[0] = '$'
Expand All @@ -250,6 +255,7 @@ func (p *hashed) Hash() []byte {
return arr[:n]
}

// decodeVersion decodes the version information from the hashed password.
func (p *hashed) decodeVersion(sbytes []byte) (int, error) {
if sbytes[0] != '$' {
return -1, InvalidHashPrefixError(sbytes[0])
Expand Down Expand Up @@ -280,10 +286,12 @@ func (p *hashed) decodeCost(sbytes []byte) (int, error) {
return 3, nil
}

// String returns a string representation of the hashed structure.
func (p *hashed) String() string {
return fmt.Sprintf("&{hash: %#v, salt: %#v, cost: %d, major: %c, minor: %c}", string(p.hash), p.salt, p.cost, p.major, p.minor)
}

// checkCost checks if the given cost is within the allowed range.
func checkCost(cost uint32) error {
if cost < MinCost || cost > MaxCost {
return InvalidCostError(cost)
Expand Down
11 changes: 11 additions & 0 deletions depinject/appconfig/dynamic_resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ type dynamicTypeResolver struct {
resolver protodesc.Resolver
}

// FindExtensionByName finds an extension type by its full name.
// It first tries to find the extension in the global protobuf registry.
// If not found, it uses the custom resolver to find the descriptor and creates a new extension type.
func (r dynamicTypeResolver) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) {
ext, err := protoregistry.GlobalTypes.FindExtensionByName(field)
if err == nil {
Expand All @@ -30,6 +33,9 @@ func (r dynamicTypeResolver) FindExtensionByName(field protoreflect.FullName) (p
return dynamicpb.NewExtensionType(desc.(protoreflect.ExtensionTypeDescriptor)), nil
}

// FindExtensionByNumber finds an extension type by its message name and field number.
// It first tries to find the extension in the global protobuf registry.
// If not found, it uses the custom resolver to find the message descriptor and searches for the extension.
func (r dynamicTypeResolver) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) {
ext, err := protoregistry.GlobalTypes.FindExtensionByNumber(message, field)
if err == nil {
Expand All @@ -54,6 +60,9 @@ func (r dynamicTypeResolver) FindExtensionByNumber(message protoreflect.FullName
return nil, protoregistry.NotFound
}

// FindMessageByName finds a message type by its full name.
// It first tries to find the message in the global protobuf registry.
// If not found, it uses the custom resolver to find the descriptor and creates a new message type.
func (r dynamicTypeResolver) FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) {
typ, err := protoregistry.GlobalTypes.FindMessageByName(message)
if err == nil {
Expand All @@ -68,6 +77,8 @@ func (r dynamicTypeResolver) FindMessageByName(message protoreflect.FullName) (p
return dynamicpb.NewMessageType(desc.(protoreflect.MessageDescriptor)), nil
}

// FindMessageByURL finds a message type by its URL.
// It extracts the full name from the URL and delegates the search to FindMessageByName.
func (r dynamicTypeResolver) FindMessageByURL(url string) (protoreflect.MessageType, error) {
if i := strings.LastIndexByte(url, '/'); i >= 0 {
url = url[i+1:]
Expand Down
16 changes: 15 additions & 1 deletion depinject/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ type interfaceBinding struct {
resolver resolver
}

// newContainer creates a new dependency injection container.
func newContainer(cfg *debugConfig) *container {
return &container{
debugConfig: cfg,
Expand All @@ -54,6 +55,7 @@ func newContainer(cfg *debugConfig) *container {
}
}

// call invokes a provider function and resolves its dependencies.
func (c *container) call(provider *providerDescriptor, moduleKey *moduleKey) ([]reflect.Value, error) {
loc := provider.Location
graphNode := c.locationGraphNode(loc, moduleKey)
Expand Down Expand Up @@ -93,6 +95,7 @@ func (c *container) call(provider *providerDescriptor, moduleKey *moduleKey) ([]
return out, nil
}

// getResolver retrieves a resolver for the given type.
func (c *container) getResolver(typ reflect.Type, key *moduleKey) (resolver, error) {
pr, err := c.getExplicitResolver(typ, key)
if err != nil {
Expand Down Expand Up @@ -171,6 +174,7 @@ func (c *container) getResolver(typ reflect.Type, key *moduleKey) (resolver, err
return res, nil
}

// getExplicitResolver retrieves an explicitly bound resolver.
func (c *container) getExplicitResolver(typ reflect.Type, key *moduleKey) (resolver, error) {
var pref interfaceBinding
var found bool
Expand Down Expand Up @@ -204,6 +208,7 @@ func (c *container) getExplicitResolver(typ reflect.Type, key *moduleKey) (resol

var stringType = reflect.TypeOf("")

// addNode adds a provider to the container and registers resolvers for its outputs.
func (c *container) addNode(provider *providerDescriptor, key *moduleKey) (interface{}, error) {
providerGraphNode := c.locationGraphNode(provider.Location, key)
hasModuleKeyParam := false
Expand Down Expand Up @@ -334,6 +339,7 @@ func (c *container) addNode(provider *providerDescriptor, key *moduleKey) (inter
return node, nil
}

// supply registers a value directly in the container.
func (c *container) supply(value reflect.Value, location Location) error {
typ := value.Type()
locGrapNode := c.locationGraphNode(location, nil)
Expand All @@ -355,6 +361,7 @@ func (c *container) supply(value reflect.Value, location Location) error {
return nil
}

// addInvoker registers an invoker function in the container.
func (c *container) addInvoker(provider *providerDescriptor, key *moduleKey) error {
// make sure there are no outputs
if len(provider.Outputs) > 0 {
Expand All @@ -369,6 +376,9 @@ func (c *container) addInvoker(provider *providerDescriptor, key *moduleKey) err
return nil
}

// resolve resolves a dependency for a given provider input.
// It checks if the type is a module key or an optional dependency,
// and then tries to resolve it using the registered resolvers.
func (c *container) resolve(in providerInput, moduleKey *moduleKey, caller Location) (reflect.Value, error) {
c.resolveStack = append(c.resolveStack, resolveFrame{loc: caller, typ: in.Type})

Expand Down Expand Up @@ -421,6 +431,8 @@ func (c *container) resolve(in providerInput, moduleKey *moduleKey, caller Locat
return res, nil
}

// build constructs the dependency injection container by resolving and setting the provided outputs.
// It also calls all registered invokers after the container is built.
func (c *container) build(loc Location, outputs ...interface{}) error {
var providerIn []providerInput
for _, output := range outputs {
Expand Down Expand Up @@ -494,7 +506,8 @@ func (c *container) build(loc Location, outputs ...interface{}) error {
return nil
}

func (c container) formatResolveStack() string {
// formatResolveStack formats the current resolve stack into a human-readable string.
func (c *container) formatResolveStack() string {
buf := &bytes.Buffer{}
_, _ = fmt.Fprintf(buf, "\twhile resolving:\n")
n := len(c.resolveStack)
Expand All @@ -505,6 +518,7 @@ func (c container) formatResolveStack() string {
return buf.String()
}

// fullyQualifiedTypeName returns the fully qualified name of a type, including the package path.
func fullyQualifiedTypeName(typ reflect.Type) string {
pkgType := typ
if typ.Kind() == reflect.Pointer || typ.Kind() == reflect.Slice || typ.Kind() == reflect.Map || typ.Kind() == reflect.Array {
Expand Down
5 changes: 5 additions & 0 deletions depinject/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ type ErrMultipleImplicitInterfaceBindings struct {
Matches []reflect.Type
}

// newErrMultipleImplicitInterfaceBindings creates a new ErrMultipleImplicitInterfaceBindings error.
func newErrMultipleImplicitInterfaceBindings(i reflect.Type, matches map[reflect.Type]reflect.Type) ErrMultipleImplicitInterfaceBindings {
var ms []reflect.Type
for k := range matches {
Expand All @@ -21,6 +22,7 @@ func newErrMultipleImplicitInterfaceBindings(i reflect.Type, matches map[reflect
return ErrMultipleImplicitInterfaceBindings{Interface: i, Matches: ms}
}

// Error returns the error message for ErrMultipleImplicitInterfaceBindings.
func (err ErrMultipleImplicitInterfaceBindings) Error() string {
matchesStr := ""
for _, m := range err.Matches {
Expand All @@ -37,6 +39,7 @@ type ErrNoTypeForExplicitBindingFound struct {
ModuleName string
}

// newErrNoTypeForExplicitBindingFound creates a new ErrNoTypeForExplicitBindingFound error.
func newErrNoTypeForExplicitBindingFound(p interfaceBinding) ErrNoTypeForExplicitBindingFound {
var moduleName string
if p.moduleKey != nil {
Expand All @@ -50,6 +53,7 @@ func newErrNoTypeForExplicitBindingFound(p interfaceBinding) ErrNoTypeForExplici
}
}

// Error returns the error message for ErrNoTypeForExplicitBindingFound.
func (err ErrNoTypeForExplicitBindingFound) Error() string {
if err.ModuleName != "" {
return fmt.Sprintf("No type for explicit binding found. Given the explicit interface binding %s in module %s, a provider of type %s was not found.",
Expand All @@ -60,6 +64,7 @@ func (err ErrNoTypeForExplicitBindingFound) Error() string {
err.Interface, err.Implementation)
}

// duplicateDefinitionError returns an error indicating that a type has been provided multiple times.
func duplicateDefinitionError(typ reflect.Type, duplicateLoc Location, existingLoc string) error {
return fmt.Errorf("duplicate provision of type %v by %s\n\talready provided by %s",
typ, duplicateLoc, existingLoc)
Expand Down
6 changes: 6 additions & 0 deletions depinject/provider_desc.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ type providerOutput struct {
Type reflect.Type
}

// extractProviderDescriptor extracts a provider descriptor from a given provider function.
func extractProviderDescriptor(provider interface{}) (providerDescriptor, error) {
rctr, err := doExtractProviderDescriptor(provider)
if err != nil {
Expand All @@ -46,6 +47,8 @@ func extractProviderDescriptor(provider interface{}) (providerDescriptor, error)
return postProcessProvider(rctr)
}

// extractInvokerDescriptor extracts an invoker descriptor from a given provider function.
// It marks all inputs as optional.
func extractInvokerDescriptor(provider interface{}) (providerDescriptor, error) {
rctr, err := doExtractProviderDescriptor(provider)
if err != nil {
Expand All @@ -61,6 +64,7 @@ func extractInvokerDescriptor(provider interface{}) (providerDescriptor, error)
return postProcessProvider(rctr)
}

// doExtractProviderDescriptor performs the core extraction logic for provider descriptors.
func doExtractProviderDescriptor(ctr interface{}) (providerDescriptor, error) {
val := reflect.ValueOf(ctr)
typ := val.Type()
Expand Down Expand Up @@ -136,6 +140,7 @@ func doExtractProviderDescriptor(ctr interface{}) (providerDescriptor, error) {

var errType = reflect.TypeOf((*error)(nil)).Elem()

// postProcessProvider performs additional processing on the provider descriptor.
func postProcessProvider(descriptor providerDescriptor) (providerDescriptor, error) {
descriptor, err := expandStructArgsProvider(descriptor)
if err != nil {
Expand All @@ -145,6 +150,7 @@ func postProcessProvider(descriptor providerDescriptor) (providerDescriptor, err
return descriptor, err
}

// checkInputAndOutputTypes checks if the input and output types are exported.
func checkInputAndOutputTypes(descriptor providerDescriptor) error {
for _, input := range descriptor.Inputs {
err := isExportedType(input.Type)
Expand Down
9 changes: 9 additions & 0 deletions depinject/struct_args.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ type isOut interface{ isOut() }

var isOutType = reflect.TypeOf((*isOut)(nil)).Elem()

// expandStructArgsProvider expands the inputs and outputs of a provider descriptor
// if they are structs that implement the In or Out interfaces.
func expandStructArgsProvider(provider providerDescriptor) (providerDescriptor, error) {
var structArgsInInput bool
var newIn []providerInput
Expand Down Expand Up @@ -65,6 +67,8 @@ func expandStructArgsProvider(provider providerDescriptor) (providerDescriptor,
return provider, nil
}

// expandStructArgsFn returns a new function that handles struct arguments
// for both inputs and outputs of the provider.
func expandStructArgsFn(provider providerDescriptor) func(inputs []reflect.Value) ([]reflect.Value, error) {
fn := provider.Fn
inParams := provider.Inputs
Expand Down Expand Up @@ -104,6 +108,7 @@ func expandStructArgsFn(provider providerDescriptor) func(inputs []reflect.Value
}
}

// structArgsInTypes extracts the input types from a struct that implements the In interface.
func structArgsInTypes(typ reflect.Type) ([]providerInput, error) {
n := typ.NumField()
var res []providerInput
Expand Down Expand Up @@ -131,6 +136,7 @@ func structArgsInTypes(typ reflect.Type) ([]providerInput, error) {
return res, nil
}

// expandStructArgsOutTypes expands the output types from a struct that implements the Out interface.
func expandStructArgsOutTypes(outputs []providerOutput) ([]providerOutput, bool) {
foundStructArgs := false
var newOut []providerOutput
Expand All @@ -145,6 +151,7 @@ func expandStructArgsOutTypes(outputs []providerOutput) ([]providerOutput, bool)
return newOut, foundStructArgs
}

// structArgsOutTypes extracts the output types from a struct that implements the Out interface.
func structArgsOutTypes(typ reflect.Type) []providerOutput {
n := typ.NumField()
var res []providerOutput
Expand All @@ -161,6 +168,7 @@ func structArgsOutTypes(typ reflect.Type) []providerOutput {
return res
}

// buildIn constructs a struct from the given reflect.Values for inputs.
func buildIn(typ reflect.Type, values []reflect.Value) (reflect.Value, int, error) {
numFields := typ.NumField()
j := 0
Expand All @@ -183,6 +191,7 @@ func buildIn(typ reflect.Type, values []reflect.Value) (reflect.Value, int, erro
return res.Elem(), j, nil
}

// extractFromOut extracts the fields from a struct that implements the Out interface.
func extractFromOut(typ reflect.Type, value reflect.Value) []reflect.Value {
numFields := typ.NumField()
var res []reflect.Value
Expand Down
Loading