-
Function `WriteToFile` has 5 return statements (exceeds 4 allowed).
// WriteToFile writes data to a file. func WriteToFile(fs afero.Fs, data []byte, filePath string) (string, error) { if err := fs.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil { return "", fmt.Errorf("failed to open path: %w", err) } file, err := fs.Create(filePath) if err != nil { return "", fmt.Errorf("failed to create path: %w", err) } defer file.Close() n, err := file.Write(data) if err != nil { return "", fmt.Errorf("failed to write data to path: %w", err) }
Found in utils/file_system.go by structure -
Method `HTTPClient.MakeRequest` has 5 return statements (exceeds 4 allowed).
// MakeRequest performs an HTTP request with the given method, path, and body // It returns the response body, status code, and an error if any func (c *HTTPClient) MakeRequest(method, relativePath string, body []byte) ([]byte, int, error) { url, err := url.Parse(c.BaseURL) if err != nil { return nil, 0, fmt.Errorf("failed to parse base URL: %v", err) } url.Path = path.Join(c.APIVersion, relativePath) req, err := http.NewRequest(method, url.String(), bytes.NewBuffer(body)) if err != nil { return nil, 0, fmt.Errorf("failed to create request: %v", err) }
Found in utils/http.go by structure -
Method `Token.Delegate` has 5 arguments (exceeds 4 allowed). Consider refactoring.
} func (t *Token) Delegate(provider did.Provider, subject, audience did.DID, topics []Capability, expire uint64, c []Capability) (*Token, error) { switch { case t.DMS != nil:
Found in lib/ucan/token.go by structure -
Method `DMSToken.Delegate` has 5 arguments (exceeds 4 allowed). Consider refactoring.
} func (t *DMSToken) Delegate(provider did.Provider, subject, audience did.DID, topics []Capability, expire uint64, c []Capability) (*DMSToken, error) { return t.delegate(Delegate, provider, subject, audience, topics, expire, c) }
Found in lib/ucan/token.go by structure -
Method `DMSToken.delegate` has 6 arguments (exceeds 4 allowed). Consider refactoring.
} func (t *DMSToken) delegate(action Action, provider did.Provider, subject, audience did.DID, topics []Capability, expire uint64, c []Capability) (*DMSToken, error) { if t.Action != Delegate { return nil, ErrNotAuthorized
Found in lib/ucan/token.go by structure -
Method `Token.DelegateBroadcast` has 5 arguments (exceeds 4 allowed). Consider refactoring.
} func (t *Token) DelegateBroadcast(provider did.Provider, subject did.DID, topic Capability, expire uint64, c []Capability) (*Token, error) { switch { case t.DMS != nil:
Found in lib/ucan/token.go by structure -
Method `DMSToken.DelegateBroadcast` has 5 arguments (exceeds 4 allowed). Consider refactoring.
} func (t *DMSToken) DelegateBroadcast(provider did.Provider, subject did.DID, topic Capability, expire uint64, c []Capability) (*DMSToken, error) { return t.delegate(Broadcast, provider, subject, did.DID{}, []Capability{topic}, expire, c) }
Found in lib/ucan/token.go by structure -
File `token.go` has 521 lines of code (exceeds 500 allowed). Consider refactoring.
package ucan import ( "crypto/rand" "encoding/json" "fmt" "slices" "time" "gitlab.com/nunet/device-management-service/lib/did" ) type Action string
Found in lib/ucan/token.go by structure -
Method `DMSToken.Verify` has a Cognitive Complexity of 24 (exceeds 20 allowed). Consider refactoring.
} func (t *DMSToken) Verify(trust did.TrustContext, now uint64) error { if t.ExpireBefore(now) { return ErrCapabilityExpired } if t.Chain != nil { if t.Chain.Action() != Delegate { return ErrNotAuthorized } if t.Chain.ExpireBefore(t.Expire) { return ErrCapabilityExpired }
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in lib/ucan/token.go by structure -
Method `DMSToken.AllowAction` has a Cognitive Complexity of 21 (exceeds 20 allowed). Consider refactoring.
} func (t *DMSToken) AllowAction(ot *Token) bool { if t.Action != Delegate { return false } if t.ExpireBefore(ot.Expire()) { return false } if !ot.Anchor(t.Subject) { return false }
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in lib/ucan/token.go by structure -
`Token` has 23 methods (exceeds 20 allowed). Consider refactoring.
var signaturePrefix = []byte("dms:token:") type Token struct { // DMS tokens DMS *DMSToken `json:"dms,omitempty"` // UCAN standard (when it is done) envelope for BYO anhcors UCAN *BYOToken `json:"ucan,omitempty"` } type DMSToken struct {
Found in lib/ucan/token.go by structure -
Method `DMSToken.Verify` has 11 return statements (exceeds 4 allowed).
} func (t *DMSToken) Verify(trust did.TrustContext, now uint64) error { if t.ExpireBefore(now) { return ErrCapabilityExpired } if t.Chain != nil { if t.Chain.Action() != Delegate { return ErrNotAuthorized } if t.Chain.ExpireBefore(t.Expire) { return ErrCapabilityExpired }
Found in lib/ucan/token.go by structure -
Method `DMSToken.AllowAction` has 7 return statements (exceeds 4 allowed).
} func (t *DMSToken) AllowAction(ot *Token) bool { if t.Action != Delegate { return false } if t.ExpireBefore(ot.Expire()) { return false } if !ot.Anchor(t.Subject) { return false }
Found in lib/ucan/token.go by structure -
Method `DMSToken.AllowInvocation` has 5 return statements (exceeds 4 allowed).
} func (t *DMSToken) AllowInvocation(subject, audience did.DID, c Capability) bool { if t.Action != Invoke { return false } if !t.Subject.Equal(subject) { return false } if !t.Audience.Empty() && !t.Audience.Equal(audience) { return false }
Found in lib/ucan/token.go by structure -
Method `DMSToken.AllowBroadcast` has 6 return statements (exceeds 4 allowed).
} func (t *DMSToken) AllowBroadcast(subject did.DID, topic Capability, c Capability) bool { if t.Action != Broadcast { return false } if !t.Subject.Equal(subject) { return false } if !t.Audience.Empty() { return false }
Found in lib/ucan/token.go by structure -
Method `DMSToken.AllowDelegation` has 7 return statements (exceeds 4 allowed).
} func (t *DMSToken) AllowDelegation(issuer, audience did.DID, topics []Capability, expire uint64, c Capability) bool { if t.Action != Delegate { return false } if t.ExpireBefore(expire) { return false } if !t.Subject.Equal(issuer) { return false }
Found in lib/ucan/token.go by structure -
Method `DMSToken.delegate` has 5 return statements (exceeds 4 allowed).
} func (t *DMSToken) delegate(action Action, provider did.Provider, subject, audience did.DID, topics []Capability, expire uint64, c []Capability) (*DMSToken, error) { if t.Action != Delegate { return nil, ErrNotAuthorized } nonce := make([]byte, nonceLength) _, err := rand.Read(nonce) if err != nil { return nil, fmt.Errorf("nonce: %w", err) } result := &DMSToken{ Action: action,
Found in lib/ucan/token.go by structure -
Method `BasicCapabilityContext.Grant` has 5 arguments (exceeds 4 allowed). Consider refactoring.
} func (ctx *BasicCapabilityContext) Grant(action Action, subject, audience did.DID, topics []string, expire uint64, provide []Capability) (TokenList, error) { nonce := make([]byte, nonceLength) _, err := rand.Read(nonce)
Found in lib/ucan/context.go by structure -
Method `BasicCapabilityContext.Delegate` has 5 arguments (exceeds 4 allowed). Consider refactoring.
} func (ctx *BasicCapabilityContext) Delegate(subject, audience did.DID, topics []string, expire uint64, provide []Capability, selfSignOnly bool) (TokenList, error) { if len(provide) == 0 { return TokenList{}, nil
Found in lib/ucan/context.go by structure -
Method `BasicCapabilityContext.delegateBroadcast` has 6 arguments (exceeds 4 allowed). Consider refactoring.
} func (ctx *BasicCapabilityContext) delegateBroadcast(tokenList []*Token, anchor did.DID, subject did.DID, topic string, expire uint64, provide []Capability) []*Token { topicCap := Capability(topic) var result []*Token //nolint
Found in lib/ucan/context.go by structure -
Method `BasicCapabilityContext.Provide` has 6 arguments (exceeds 4 allowed). Consider refactoring.
} func (ctx *BasicCapabilityContext) Provide(target did.DID, subject crypto.ID, audience crypto.ID, expire uint64, invoke []Capability, provide []Capability) ([]byte, error) { if len(invoke) == 0 && len(provide) == 0 { return nil, fmt.Errorf("no capabilities: %w", ErrNotAuthorized)
Found in lib/ucan/context.go by structure -
File `context.go` has 603 lines of code (exceeds 500 allowed). Consider refactoring.
package ucan import ( "bytes" "context" "crypto/rand" "encoding/json" "fmt" "slices" "sync" "time" "gitlab.com/nunet/device-management-service/lib/crypto"
Found in lib/ucan/context.go by structure -
Method `BasicCapabilityContext.Delegate` has a Cognitive Complexity of 25 (exceeds 20 allowed). Consider refactoring.
} func (ctx *BasicCapabilityContext) Delegate(subject, audience did.DID, topics []string, expire uint64, provide []Capability, selfSignOnly bool) (TokenList, error) { if len(provide) == 0 { return TokenList{}, nil } topicCap := make([]Capability, 0, len(topics)) for _, topic := range topics { topicCap = append(topicCap, Capability(topic)) } var result []*Token if selfSignOnly {
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in lib/ucan/context.go by structure -
Method `BasicCapabilityContext.Consume` has a Cognitive Complexity of 38 (exceeds 20 allowed). Consider refactoring.
} func (ctx *BasicCapabilityContext) Consume(origin did.DID, data []byte) error { if len(data) > maxCapabilitySize { return ErrTooBig } var tokens TokenList if err := json.Unmarshal(data, &tokens); err != nil { return fmt.Errorf("unmarshaling payload: %w", err) } rootAnchors := ctx.getRoots() requireAnchors := ctx.getRequireAnchors() now := uint64(time.Now().UnixNano())
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in lib/ucan/context.go by structure -
Method `BasicCapabilityContext.Require` has a Cognitive Complexity of 31 (exceeds 20 allowed). Consider refactoring.
} func (ctx *BasicCapabilityContext) Require(anchor did.DID, subject crypto.ID, audience crypto.ID, cap []Capability) error { if len(cap) == 0 { return fmt.Errorf("no capabilities: %w", ErrNotAuthorized) } subjectDID, err := did.FromID(subject) if err != nil { return fmt.Errorf("DID for subject: %w", err) } audienceDID, err := did.FromID(audience) if err != nil { return fmt.Errorf("DID for audience: %w", err)
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in lib/ucan/context.go by structure -
Method `BasicCapabilityContext.RequireBroadcast` has a Cognitive Complexity of 30 (exceeds 20 allowed). Consider refactoring.
} func (ctx *BasicCapabilityContext) RequireBroadcast(anchor did.DID, subject crypto.ID, topic string, require []Capability) error { if len(require) == 0 { return fmt.Errorf("no capabilities: %w", ErrNotAuthorized) } subjectDID, err := did.FromID(subject) if err != nil { return fmt.Errorf("DID for subject: %w", err) } tokenList := ctx.getSubjectTokens(subjectDID) roots := ctx.getRoots() requireAnchors := ctx.getRequireAnchors()
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in lib/ucan/context.go by structure -
`BasicCapabilityContext` has 32 methods (exceeds 20 allowed). Consider refactoring.
} type BasicCapabilityContext struct { mx sync.Mutex provider did.Provider trust did.TrustContext roots map[did.DID]struct{} // our root anchors of trust require map[did.DID][]*Token // our acceptance side-roots provide map[did.DID][]*Token // root capabilities -> tokens tokens map[did.DID][]*Token // our context dependent capabilities; subject -> tokens stop func() } var _ CapabilityContext = (*BasicCapabilityContext)(nil)
Found in lib/ucan/context.go by structure -
Method `BasicCapabilityContext.Require` has 7 return statements (exceeds 4 allowed).
} func (ctx *BasicCapabilityContext) Require(anchor did.DID, subject crypto.ID, audience crypto.ID, cap []Capability) error { if len(cap) == 0 { return fmt.Errorf("no capabilities: %w", ErrNotAuthorized) } subjectDID, err := did.FromID(subject) if err != nil { return fmt.Errorf("DID for subject: %w", err) } audienceDID, err := did.FromID(audience) if err != nil { return fmt.Errorf("DID for audience: %w", err)
Found in lib/ucan/context.go by structure -
Method `BasicCapabilityContext.RequireBroadcast` has 6 return statements (exceeds 4 allowed).
} func (ctx *BasicCapabilityContext) RequireBroadcast(anchor did.DID, subject crypto.ID, topic string, require []Capability) error { if len(require) == 0 { return fmt.Errorf("no capabilities: %w", ErrNotAuthorized) } subjectDID, err := did.FromID(subject) if err != nil { return fmt.Errorf("DID for subject: %w", err) } tokenList := ctx.getSubjectTokens(subjectDID) roots := ctx.getRoots() requireAnchors := ctx.getRequireAnchors()
Found in lib/ucan/context.go by structure -
Method `BasicCapabilityContext.Provide` has 10 return statements (exceeds 4 allowed).
} func (ctx *BasicCapabilityContext) Provide(target did.DID, subject crypto.ID, audience crypto.ID, expire uint64, invoke []Capability, provide []Capability) ([]byte, error) { if len(invoke) == 0 && len(provide) == 0 { return nil, fmt.Errorf("no capabilities: %w", ErrNotAuthorized) } subjectDID, err := did.FromID(subject) if err != nil { return nil, fmt.Errorf("DID for subject: %w", err) } audienceDID, err := did.FromID(audience) if err != nil { return nil, fmt.Errorf("DID for audience: %w", err)
Found in lib/ucan/context.go by structure -
Method `BasicCapabilityContext.ProvideBroadcast` has 6 return statements (exceeds 4 allowed).
} func (ctx *BasicCapabilityContext) ProvideBroadcast(subject crypto.ID, topic string, expire uint64, provide []Capability) ([]byte, error) { if len(provide) == 0 { return nil, fmt.Errorf("no capabilities: %w", ErrNotAuthorized) } subjectDID, err := did.FromID(subject) if err != nil { return nil, fmt.Errorf("DID for subject: %w", err) } broadcast, err := ctx.DelegateBroadcast(subjectDID, topic, expire, provide) if err != nil { return nil, fmt.Errorf("cannot provide broadcast tokens: %w", err)
Found in lib/ucan/context.go by structure -
Method `Key.MarshalToJSON` has 55 lines of code (exceeds 50 allowed). Consider refactoring.
// MarshalToJSON encrypts and marshals a key to json byte array. func (key *Key) MarshalToJSON(passphrase string) ([]byte, error) { if passphrase == "" { return nil, ErrEmptyPassphrase } salt, err := crypto.RandomEntropy(64) if err != nil { return nil, err } dk, err := scrypt.Key([]byte(passphrase), salt, scryptN, scryptR, scryptP, scryptKeyLen) if err != nil { return nil, err } iv, err := crypto.RandomEntropy(aes.BlockSize)
Found in lib/crypto/keystore/key.go by structure -
Function `UnmarshalKey` has 51 lines of code (exceeds 50 allowed). Consider refactoring.
// UnmarshalKey decrypts and unmarhals the private key func UnmarshalKey(data []byte, passphrase string) (*Key, error) { if passphrase == "" { return nil, ErrEmptyPassphrase } encjson := encryptedKeyJSON{} if err := json.Unmarshal(data, &encjson); err != nil { return nil, fmt.Errorf("failed to unmarshal key data: %w", err) } if encjson.Version != ksVersion { return nil, ErrVersionMismatch } if encjson.Crypto.Cipher != ksCipher { return nil, ErrCipherMismatch
Found in lib/crypto/keystore/key.go by structure -
Method `Key.MarshalToJSON` has 8 return statements (exceeds 4 allowed).
// MarshalToJSON encrypts and marshals a key to json byte array. func (key *Key) MarshalToJSON(passphrase string) ([]byte, error) { if passphrase == "" { return nil, ErrEmptyPassphrase } salt, err := crypto.RandomEntropy(64) if err != nil { return nil, err } dk, err := scrypt.Key([]byte(passphrase), salt, scryptN, scryptR, scryptP, scryptKeyLen) if err != nil { return nil, err } iv, err := crypto.RandomEntropy(aes.BlockSize)
Found in lib/crypto/keystore/key.go by structure -
Function `UnmarshalKey` has 13 return statements (exceeds 4 allowed).
// UnmarshalKey decrypts and unmarhals the private key func UnmarshalKey(data []byte, passphrase string) (*Key, error) { if passphrase == "" { return nil, ErrEmptyPassphrase } encjson := encryptedKeyJSON{} if err := json.Unmarshal(data, &encjson); err != nil { return nil, fmt.Errorf("failed to unmarshal key data: %w", err) } if encjson.Version != ksVersion { return nil, ErrVersionMismatch } if encjson.Crypto.Cipher != ksCipher { return nil, ErrCipherMismatch
Found in lib/crypto/keystore/key.go by structure -
Function `ParseKeyURI` has 6 return statements (exceeds 4 allowed).
} func ParseKeyURI(uri string) (crypto.PubKey, error) { if !strings.HasPrefix(uri, keyPrefix) { return nil, fmt.Errorf("decentralized identifier is not a 'key' type") } uri = strings.TrimPrefix(uri, keyPrefix+":") enc, data, err := mb.Decode(uri) if err != nil { return nil, fmt.Errorf("decoding multibase: %w", err) } if enc != mb.Base58BTC {
Found in lib/did/key.go by structure -
Function `GPUsComparator` has 5 return statements (exceeds 4 allowed).
) func GPUsComparator(lraw, rraw interface{}, _ ...Preference) types.Comparison { // comparator for GPUs type which is just a slice of GPU types: // left represent machine capabilities; // right represent required capabilities; // we need to check if for ech GPU on the right there exist a matching GPU on the left... // (since given slices are not ordered...) // validate input type _, lrawok := lraw.([]types.GPU) _, rrawok := rraw.([]types.GPU) if !lrawok || !rrawok { return types.Error }
Found in dms/orchestrator/matching/GPUsComparator.go by structure -
Function `KYCsComparator` has 5 return statements (exceeds 4 allowed).
) func KYCsComparator(lraw interface{}, rraw interface{}, _ ...Preference) types.Comparison { // simplified version of (placeholder) // left represent machine capabilities; // right represent required capabilities; // validate input type _, lrawok := lraw.([]types.KYC) _, rrawok := rraw.([]types.KYC) if !lrawok || !rrawok { return types.Error } l := lraw.([]types.KYC)
Found in dms/orchestrator/matching/kycs_comparator.go by structure -
Function `ExecutionResourcesComparator` has 5 return statements (exceeds 4 allowed).
) func ExecutionResourcesComparator(l, r interface{}, _ ...Preference) types.Comparison { // comparator for types.ExecutionResources type // Current implementation of the type has four fields: CPU, Memory, Disk, GPUs // we consider that all fields have to be 'Better' or 'Equal' // for the comparison to be 'Better' or 'Equal' // else we return 'Worse' // validate input type _, lok := l.(types.ExecutionResources) _, rok := r.(types.ExecutionResources) if !lok || !rok { return types.Error }
Found in dms/orchestrator/matching/ExecutionResourcesComparator.go by structure -
Function `returnBestMatch` has 5 return statements (exceeds 4 allowed).
} func returnBestMatch(dimension []types.Comparison) (types.Comparison, int) { // while i feel that there could be some weird matrix sorting algorithm that could be used here // i can't think of any right now, so i will just iterate over the matrix and return matches // in somewhat manual way for i, v := range dimension { if v == types.Equal { return v, i // selecting an equal match is the most efficient match } } for i, v := range dimension { if v == types.Better { return v, i // selecting a better is also not bad
Found in dms/orchestrator/matching/utils.go by structure -
Function `LocalitiesComparator` has 5 return statements (exceeds 4 allowed).
) func LocalitiesComparator(lraw interface{}, rraw interface{}, _ ...Preference) types.Comparison { // simplified version of Localities comparator // which is simply a slice of Locality type; // we do not have separate type defined for Localities // it takes preference variable where comparison Preference is defined // this is the first method that is used to take Preference variable into account // left represent machine capabilities; // right represent required capabilities; // validate input type _, lrawok := lraw.([]types.Locality) _, rrawok := rraw.([]types.Locality) if !lrawok || !rrawok {
Found in dms/orchestrator/matching/LocalitiesComparator.go by structure -
Function `LibraryComparator` has 7 return statements (exceeds 4 allowed).
) func LibraryComparator(lraw, rraw interface{}, _ ...Preference) types.Comparison { // comparator for single Library type: // left represent machine capabilities; // right represent required capabilities; // validate input type _, lrawok := lraw.(types.Library) _, rrawok := rraw.(types.Library) if !lrawok || !rrawok { return types.Error } l := lraw.(types.Library)
Found in dms/orchestrator/matching/LibraryComparator.go by structure -
Function `StorageComparator` has 9 return statements (exceeds 4 allowed).
import "gitlab.com/nunet/device-management-service/types" func StorageComparator(lraw interface{}, rraw interface{}, _ ...Preference) types.Comparison { // simplified version of (placeholder) // left represent machine capabilities; // right represent required capabilities; // validate input type _, lrawok := lraw.(types.Storage) _, rrawok := rraw.(types.Storage) if !lrawok || !rrawok { return types.Error } l := lraw.(types.Storage)
Found in dms/orchestrator/matching/storage_comparator.go by structure -
Function `StoragesComparator` has 58 lines of code (exceeds 50 allowed). Consider refactoring.
) func StoragesComparator(lraw interface{}, rraw interface{}, _ ...Preference) types.Comparison { // simplified version of (placeholder) // left represent machine capabilities; // right represent required capabilities; // validate input type _, lrawok := lraw.([]types.Storage) _, rrawok := rraw.([]types.Storage) if !lrawok || !rrawok { return types.Error } l := lraw.([]types.Storage)
Found in dms/orchestrator/matching/storages_comparator.go by structure -
Function `StoragesComparator` has 7 return statements (exceeds 4 allowed).
) func StoragesComparator(lraw interface{}, rraw interface{}, _ ...Preference) types.Comparison { // simplified version of (placeholder) // left represent machine capabilities; // right represent required capabilities; // validate input type _, lrawok := lraw.([]types.Storage) _, rrawok := rraw.([]types.Storage) if !lrawok || !rrawok { return types.Error } l := lraw.([]types.Storage)
Found in dms/orchestrator/matching/storages_comparator.go by structure -
Function `GpuComparator` has 6 return statements (exceeds 4 allowed).
) func GpuComparator(l, r interface{}, _ ...Preference) types.Comparison { // comparator for GPU type // we want to reason about the inner fields of the GPU type and how they compare between left and right // in the future we may want to pass custom preference parameters to the ComplexComparator // for now it is probably best to hardcode them; // validate input type _, lok := l.(types.GPU) _, rok := r.(types.GPU) if !lok || !rok { return types.Error }
Found in dms/orchestrator/matching/GpuComparator.go by structure -
Avoid deeply nested control flow statements.
if l.CurrencyPerHour == r.CurrencyPerHour { return types.Equal } else if l.CurrencyPerHour < r.CurrencyPerHour { return types.Better } else { return types.Worse } } else if l.TotalPerJob < r.TotalPerJob { if l.CurrencyPerHour <= r.CurrencyPerHour {
Found in dms/orchestrator/matching/price_comparator.go by structure -
Avoid deeply nested control flow statements.
} } else if l.TotalPerJob < r.TotalPerJob { if l.CurrencyPerHour <= r.CurrencyPerHour { return types.Better } else { return types.Worse } } else { return types.Worse
Found in dms/orchestrator/matching/price_comparator.go by structure -
Function `PriceInformationComparator` has 9 return statements (exceeds 4 allowed).
) func PriceInformationComparator(lraw interface{}, rraw interface{}, _ ...Preference) types.Comparison { // simplified version of (placeholder) // left represent machine capabilities; // right represent required capabilities; // validate input type _, lrawok := lraw.(types.PriceInformation) _, rrawok := rraw.(types.PriceInformation) if !lrawok || !rrawok { return types.Error } l := lraw.(types.PriceInformation)
Found in dms/orchestrator/matching/price_comparator.go by structure -
Function `LibrariesComparator` has 5 return statements (exceeds 4 allowed).
) func LibrariesComparator(lraw, rraw interface{}, _ ...Preference) types.Comparison { // comparator for Libraries slices (of different lengths) of Library types: // left represent machine capabilities; // right represent required capabilities; // validate input type _, lrawok := lraw.([]types.Library) _, rrawok := rraw.([]types.Library) if !lrawok || !rrawok { return types.Error } l := lraw.([]types.Library)
Found in dms/orchestrator/matching/LibrariesComparator.go by structure -
Function `TimeInformationComparator` has 5 return statements (exceeds 4 allowed).
) func TimeInformationComparator(lraw interface{}, rraw interface{}, _ ...Preference) types.Comparison { // simplified version of (placeholder) // left represent machine capabilities; // right represent required capabilities; // validate input type _, lrawok := lraw.(types.TimeInformation) _, rrawok := rraw.(types.TimeInformation) if !lrawok || !rrawok { return types.Error } l := lraw.(types.TimeInformation)
Found in dms/orchestrator/matching/time_comparator.go by structure -
Function `Run` has a Cognitive Complexity of 25 (exceeds 20 allowed). Consider refactoring.
// QUESTION(dms-initialization): should the db instance be constructed here? func Run(ksPassphrase string) error { ctx := context.Background() fs := afero.NewOsFs() keyStoreDir := filepath.Join(config.GetConfig().General.WorkDir, KeystoreDir) keyStore, err := keystore.New(fs, keyStoreDir) if err != nil { return fmt.Errorf("unable to create keystore: %w", err) } var priv crypto.PrivKey ksPrivKey, err := keyStore.Get(KeyIDPrivKey, ksPassphrase) if err != nil {
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in dms/dms.go by structure -
Function `Run` has 129 lines of code (exceeds 50 allowed). Consider refactoring.
// QUESTION(dms-initialization): should the db instance be constructed here? func Run(ksPassphrase string) error { ctx := context.Background() fs := afero.NewOsFs() keyStoreDir := filepath.Join(config.GetConfig().General.WorkDir, KeystoreDir) keyStore, err := keystore.New(fs, keyStoreDir) if err != nil { return fmt.Errorf("unable to create keystore: %w", err) } var priv crypto.PrivKey ksPrivKey, err := keyStore.Get(KeyIDPrivKey, ksPassphrase) if err != nil {
Found in dms/dms.go by structure -
Function `Run` has 12 return statements (exceeds 4 allowed).
// QUESTION(dms-initialization): should the db instance be constructed here? func Run(ksPassphrase string) error { ctx := context.Background() fs := afero.NewOsFs() keyStoreDir := filepath.Join(config.GetConfig().General.WorkDir, KeystoreDir) keyStore, err := keystore.New(fs, keyStoreDir) if err != nil { return fmt.Errorf("unable to create keystore: %w", err) } var priv crypto.PrivKey ksPrivKey, err := keyStore.Get(KeyIDPrivKey, ksPassphrase) if err != nil {
Found in dms/dms.go by structure -
Function `New` has 5 arguments (exceeds 4 allowed). Consider refactoring.
// New creates a new node, attaches an actor to the node. func New(rootCap ucan.CapabilityContext, hostID string, net network.Network, resourceManager resources.Manager, scheduler *bt.Scheduler) (*Node, error) { if rootCap == nil { return nil, errors.New("root capability context is nil")
Found in dms/node/node.go by structure -
Function `createActor` has 5 arguments (exceeds 4 allowed). Consider refactoring.
// createActor creates an actor. func createActor(sctx *actor.BasicSecurityContext, limiter actor.RateLimiter, hostID, inboxAddress string, net network.Network, scheduler *bt.Scheduler) (*actor.BasicActor, error) { self := actor.Handle{ ID: sctx.ID(),
Found in dms/node/node.go by structure -
Function `New` has 54 lines of code (exceeds 50 allowed). Consider refactoring.
// New creates a new node, attaches an actor to the node. func New(rootCap ucan.CapabilityContext, hostID string, net network.Network, resourceManager resources.Manager, scheduler *bt.Scheduler) (*Node, error) { if rootCap == nil { return nil, errors.New("root capability context is nil") } if hostID == "" { return nil, errors.New("host id is nil") } if net == nil { return nil, errors.New("network is nil") }
Found in dms/node/node.go by structure -
Function `New` has 13 return statements (exceeds 4 allowed).
// New creates a new node, attaches an actor to the node. func New(rootCap ucan.CapabilityContext, hostID string, net network.Network, resourceManager resources.Manager, scheduler *bt.Scheduler) (*Node, error) { if rootCap == nil { return nil, errors.New("root capability context is nil") } if hostID == "" { return nil, errors.New("host id is nil") } if net == nil { return nil, errors.New("network is nil") }
Found in dms/node/node.go by structure -
Method `Node.CreateAllocation` has 7 return statements (exceeds 4 allowed).
// CreateAllocation creates an allocation func (n *Node) CreateAllocation(job jobs.Job) (*jobs.Allocation, error) { // generate random keypair priv, pub, err := crypto.GenerateKeyPair(crypto.Ed25519) if err != nil { return nil, fmt.Errorf("failed to generate random keypair for allocation job %s: %w", job.ID, err) } security, err := actor.NewBasicSecurityContext(pub, priv, n.rootCap) if err != nil { return nil, fmt.Errorf("failed to create security context: %w", err) } allocationInbox, err := uuid.NewUUID()
Found in dms/node/node.go by structure -
Method `DefaultManager.UpdateFreeResources` has 5 return statements (exceeds 4 allowed).
// UpdateFreeResources calculates, updates db and returns the free resources of the machine in the database func (d DefaultManager) UpdateFreeResources(ctx context.Context) (types.FreeResources, error) { usage, err := d.usageMonitor.GetUsage(ctx) if err != nil { return types.FreeResources{}, fmt.Errorf("getting usage: %w", err) } onboardedResources, err := d.GetOnboardedResources(ctx) if err != nil { return types.FreeResources{}, fmt.Errorf("getting total resources: %w", err) } freeResources, err := onboardedResources.Subtract(usage) if err != nil {
Found in dms/resources/resource_manager.go by structure -
Method `linuxSystemSpecs.GetGPUVendors` has a Cognitive Complexity of 23 (exceeds 20 allowed). Consider refactoring.
// GetGPUVendors returns the GPU vendors for the system func (l linuxSystemSpecs) GetGPUVendors() ([]types.GPUVendor, error) { var vendors []types.GPUVendor gpu, err := ghw.GPU() if err != nil { return nil, err } for _, card := range gpu.GraphicsCards { if card.DeviceInfo != nil { class := card.DeviceInfo.Class if class != nil { className := strings.ToLower(class.Name) if strings.Contains(className, "display controller") ||
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in dms/resources/system_specs_linux.go by structure -
Method `linuxSystemSpecs.getIntelGPUInfo` has 62 lines of code (exceeds 50 allowed). Consider refactoring.
// getIntelGPUInfo returns the GPU information for Intel GPUs func (l linuxSystemSpecs) getIntelGPUInfo(metadata []gpuMetadata) ([]types.GPU, error) { // Determine the number of discrete Intel GPUs cmd := exec.Command("xpu-smi", "health", "-l") output, err := cmd.CombinedOutput() if err != nil { return nil, fmt.Errorf("xpu-smi not installed, initialized, or configured: %s", err) } outputStr := string(output) // fmt.Println("xpu-smi health -l output:\n", outputStr) // Print the output for debugging // Use regex to find all instances of Device ID deviceIDRegex := regexp.MustCompile(`(?i)\| Device ID\s+\|\s+(\d+)\s+\|`)
Found in dms/resources/system_specs_linux.go by structure -
Avoid deeply nested control flow statements.
vendor := card.DeviceInfo.Vendor if vendor != nil { switch { case strings.Contains(strings.ToLower(vendor.Name), "nvidia"): vendors = append(vendors, types.GPUVendorNvidia) case strings.Contains(strings.ToLower(vendor.Name), "amd"): vendors = append(vendors, types.GPUVendorAMDATI) case strings.Contains(strings.ToLower(vendor.Name), "intel"): vendors = append(vendors, types.GPUVendorIntel) default: vendors = append(vendors, types.GPUVendorUnknown) } } }
Found in dms/resources/system_specs_linux.go by structure -
Method `linuxSystemSpecs.GetProvisionedResources` has 5 return statements (exceeds 4 allowed).
// GetProvisionedResources returns the total resources available on the system func (l linuxSystemSpecs) GetProvisionedResources() (types.Resources, error) { cpuInfo, err := l.GetCPUInfo() if err != nil { return types.Resources{}, fmt.Errorf("failed to get CPU info: %s", err) } totalMemory, err := l.GetTotalMemory() if err != nil { return types.Resources{}, fmt.Errorf("failed to get total memory: %s", err) } gpus, err := l.GetGPUs() if err != nil {
Found in dms/resources/system_specs_linux.go by structure -
Method `linuxSystemSpecs.getAMDGPUInfo` has 6 return statements (exceeds 4 allowed).
// getAMDGPUInfo returns the GPU information for AMD GPUs func (l linuxSystemSpecs) getAMDGPUInfo(metadata []gpuMetadata) ([]types.GPU, error) { cmd := exec.Command("rocm-smi", "--showid", "--showproductname", "--showmeminfo", "vram") output, err := cmd.CombinedOutput() if err != nil { return nil, fmt.Errorf("AMD ROCm not installed, initialized, or configured (reboot recommended for newly installed AMD GPU Drivers): %s", err) } outputStr := string(output) // fmt.Println("rocm-smi vram output:\n", outputStr) // Print the output for debugging gpuNameRegex := regexp.MustCompile(`GPU\[\d+\]\s+: Card Series:\s+([^\n]+)`) totalRegex := regexp.MustCompile(`GPU\[\d+\]\s+: VRAM Total Memory \(B\):\s+(\d+)`)
Found in dms/resources/system_specs_linux.go by structure -
Method `linuxSystemSpecs.getNVIDIAGPUInfo` has 7 return statements (exceeds 4 allowed).
// getNVIDIAGPUInfo returns the GPU information for NVIDIA GPUs func (l linuxSystemSpecs) getNVIDIAGPUInfo(metadata []gpuMetadata) ([]types.GPU, error) { // Initialize NVML ret := nvml.Init() if !errors.Is(ret, nvml.SUCCESS) { return nil, fmt.Errorf("NVIDIA Management Library not installed, initialized or configured (reboot recommended for newly installed NVIDIA GPU drivers): %s", nvml.ErrorString(ret)) } defer func() { _ = nvml.Shutdown() }() // Get the number of GPU devices deviceCount, ret := nvml.DeviceGetCount()
Found in dms/resources/system_specs_linux.go by structure -
Method `linuxSystemSpecs.getIntelGPUInfo` has 10 return statements (exceeds 4 allowed).
// getIntelGPUInfo returns the GPU information for Intel GPUs func (l linuxSystemSpecs) getIntelGPUInfo(metadata []gpuMetadata) ([]types.GPU, error) { // Determine the number of discrete Intel GPUs cmd := exec.Command("xpu-smi", "health", "-l") output, err := cmd.CombinedOutput() if err != nil { return nil, fmt.Errorf("xpu-smi not installed, initialized, or configured: %s", err) } outputStr := string(output) // fmt.Println("xpu-smi health -l output:\n", outputStr) // Print the output for debugging // Use regex to find all instances of Device ID deviceIDRegex := regexp.MustCompile(`(?i)\| Device ID\s+\|\s+(\d+)\s+\|`)
Found in dms/resources/system_specs_linux.go by structure -
Method `Allocation.Run` has 7 return statements (exceeds 4 allowed).
// Run creates the executor based on the execution engine configuration. func (a *Allocation) Run(ctx context.Context) error { a.mx.Lock() defer a.mx.Unlock() if a.status == running { return nil } freeResources, err := a.resourceManager.UpdateFreeResources(ctx) if err != nil { return fmt.Errorf("failed to get free resources: %w", err) }
Found in dms/jobs/allocation.go by structure -
Method `TransformerImpl.transform` has 6 return statements (exceeds 4 allowed).
// transform is a recursive function that applies the transformers to the configuration. func (t TransformerImpl) transform(root *map[string]interface{}, data any, path tree.Path, transformers map[tree.Path]TransformerFunc) (interface{}, error) { var err error // Apply transformers that match the current path. for pattern, transformer := range transformers { if path.Matches(pattern) { data, err = transformer(root, data, path) if err != nil { return nil, err } } } // Recursively apply transformers to children. if result, ok := data.(map[string]interface{}); ok {
Found in dms/jobs/parser/transform/transform.go by structure -
Function `TransformNetwork` has 51 lines of code (exceeds 50 allowed). Consider refactoring.
// TransformNetwork transforms the network configuration func TransformNetwork(_ *map[string]interface{}, data any, _ tree.Path) (any, error) { if data == nil { return nil, nil } config, ok := data.(map[string]any) if !ok { return nil, fmt.Errorf("invalid network configuration: %v", data) } ports, _ := transform.ToAnySlice(config["ports"]) portMap := []map[string]any{} for _, port := range ports { protocol, host, container := "tcp", 0, 0 switch v := port.(type) {
Found in dms/jobs/parser/nunet/transform.go by structure -
Function `matchParts` has a Cognitive Complexity of 26 (exceeds 20 allowed). Consider refactoring.
// matchParts checks if the path parts match the pattern parts func matchParts(pathParts, patternParts []string) bool { // If the pattern is longer than the path, it can't match if len(pathParts) < len(patternParts) { return false } for i, part := range patternParts { switch part { case configPathMatchAnyMultiple: // if it is the last part of the pattern, it matches if i == len(patternParts)-1 { return true } // Otherwise, try to match the rest of the path
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in dms/jobs/parser/tree/path.go by structure -
Function `matchParts` has 7 return statements (exceeds 4 allowed).
// matchParts checks if the path parts match the pattern parts func matchParts(pathParts, patternParts []string) bool { // If the pattern is longer than the path, it can't match if len(pathParts) < len(patternParts) { return false } for i, part := range patternParts { switch part { case configPathMatchAnyMultiple: // if it is the last part of the pattern, it matches if i == len(patternParts)-1 { return true } // Otherwise, try to match the rest of the path
Found in dms/jobs/parser/tree/path.go by structure -
Method `BasicSecurityContext.RequireBroadcast` has 5 return statements (exceeds 4 allowed).
} func (s *BasicSecurityContext) RequireBroadcast(msg Envelope, topic string, broadcast []Capability) error { if !msg.IsBroadcast() { return fmt.Errorf("not a broadcast message: %w", ErrInvalidMessage) } if topic != msg.Options.Topic { return fmt.Errorf("broadcast topic mismatch: %w", ErrInvalidMessage) } // first consume the capability tokens in the envelope if err := s.cap.Consume(msg.From.DID, msg.Capability); err != nil { return fmt.Errorf("consuming capabilities: %w", err) }
Found in dms/actor/security.go by structure -
Method `BasicSecurityContext.Verify` has 6 return statements (exceeds 4 allowed).
} func (s *BasicSecurityContext) Verify(msg Envelope) error { if msg.Expired() { return ErrMessageExpired } pubk, err := crypto.PublicKeyFromID(msg.From.ID) if err != nil { return fmt.Errorf("public key from id: %w", err) } data, err := msg.SignatureData() if err != nil { return fmt.Errorf("signature data: %w", err)
Found in dms/actor/security.go by structure -
Method `Dispatch.dispatch` has a Cognitive Complexity of 23 (exceeds 20 allowed). Consider refactoring.
} func (k *Dispatch) dispatch() { for { select { case msg := <-k.vq: k.mx.Lock() b, ok := k.behaviors[msg.Behavior] if !ok { k.mx.Unlock() log.Debugf("unknown behavior %s", msg.Behavior) continue }
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in dms/actor/dispatch.go by structure -
Function `New` has 7 arguments (exceeds 4 allowed). Consider refactoring.
// New creates a new basic actor. func New(scheduler *bt.Scheduler, net network.Network, security *BasicSecurityContext, limiter RateLimiter, params BasicActorParams, self Handle, opt ...DispatchOption) (*BasicActor, error) { if scheduler == nil { return nil, errors.New("scheduler is nil")
Found in dms/actor/basic.go by structure -
Method `BasicActor.Send` has 6 return statements (exceeds 4 allowed).
} func (a *BasicActor) Send(msg Envelope) error { if msg.To.ID.Equal(a.self.ID) { return a.Receive(msg) } if msg.Signature == nil { if msg.Nonce == 0 { msg.Nonce = a.security.Nonce() } invoke := []Capability{Capability(msg.Behavior)} var delegate []Capability if msg.Options.ReplyTo != "" {
Found in dms/actor/basic.go by structure -
Method `BasicActor.Publish` has 5 return statements (exceeds 4 allowed).
} func (a *BasicActor) Publish(msg Envelope) error { if !msg.IsBroadcast() { return ErrInvalidMessage } if msg.Signature == nil { if msg.Nonce == 0 { msg.Nonce = a.security.Nonce() } broadcast := []Capability{Capability(msg.Behavior)} if err := a.security.ProvideBroadcast(&msg, msg.Options.Topic, broadcast); err != nil { return fmt.Errorf("providing behavior capability for %s: %w", msg.Behavior, err)
Found in dms/actor/basic.go by structure -
Method `BasicActor.validateBroadcast` has 9 return statements (exceeds 4 allowed).
} func (a *BasicActor) validateBroadcast(topic string, data []byte, validatorData interface{}) (network.ValidationResult, interface{}) { var msg Envelope if validatorData != nil { if _, ok := validatorData.(Envelope); !ok { log.Warnf("bogus pubsub validation data: %v", validatorData) return network.ValidationReject, nil } // we have already validated the message, just short-circuit return network.ValidationAccept, validatorData } else if err := json.Unmarshal(data, &msg); err != nil { return network.ValidationReject, nil }
Found in dms/actor/basic.go by structure -
Function `Message` has 5 arguments (exceeds 4 allowed). Consider refactoring.
// Message constructs a new message envelope and applies the options func Message(src Handle, dest Handle, behavior string, payload interface{}, opt ...MessageOption) (Envelope, error) { data, err := json.Marshal(payload) if err != nil {
Found in dms/actor/msg.go by structure -
Function `NewConfig` has 7 arguments (exceeds 4 allowed). Consider refactoring.
// NewConfig is a constructor for Config func NewConfig( fs afero.Afero, workDir, dbPath string, onboardingRepo repositories.OnboardingParams, p2pRepo repositories.Libp2pInfo, avResourceRepo repositories.AvailableResources, uuidRepo repositories.MachineUUID, channels []string, ) *Config { return &Config{
Found in dms/onboarding/onboarding.go by structure -
Method `Onboarding.Onboard` has 9 return statements (exceeds 4 allowed).
// Onboard validates the onboarding params and onboards the machine to the network // It returns a *types.OnboardingConfig and any error if encountered func (o *Onboarding) Onboard(ctx context.Context, capacity types.CapacityForNunet) (*types.OnboardingConfig, error) { if err := o.validateOnboardingPrerequisites(capacity); err != nil { return nil, err } hostname, err := os.Hostname() if err != nil { return nil, fmt.Errorf("unable to get hostname: %v", err) } provisionedResources, err := o.ResourceManager.SystemSpecs().GetProvisionedResources() if err != nil { return nil, fmt.Errorf("cannot get provisioned resources: %w", err)
Found in dms/onboarding/onboarding.go by structure -
Method `Onboarding.ResourceConfig` has 9 return statements (exceeds 4 allowed).
// ResourceConfig allows changing onboarding parameters func (o *Onboarding) ResourceConfig(ctx context.Context, capacity types.CapacityForNunet) (*types.OnboardingConfig, error) { onboarded, err := o.IsOnboarded(ctx) if err != nil { return nil, fmt.Errorf("could not check onboard status: %w", err) } if !onboarded { return nil, ErrMachineNotOnboarded } if err := o.validateCapacityForNunet(capacity); err != nil { return nil, fmt.Errorf("could not validate capacity data: %w", err) }
Found in dms/onboarding/onboarding.go by structure -
Method `Onboarding.Offboard` has 5 return statements (exceeds 4 allowed).
// Offboard deletes all onboarding information if already set // It returns an error func (o *Onboarding) Offboard(ctx context.Context, force bool) error { onboarded, err := o.IsOnboarded(ctx) if err != nil && !force { return fmt.Errorf("could not retrieve onboard status: %w", err) } else if err != nil && force { zlog.Sugar().Errorf("problem with onboarding state: %w", err) zlog.Info("continuing with offboarding because forced") } if !onboarded { return fmt.Errorf("machine is not onboarded") }
Found in dms/onboarding/onboarding.go by structure -
Method `Onboarding.validateOnboardingPrerequisites` has 6 return statements (exceeds 4 allowed).
} func (o *Onboarding) validateOnboardingPrerequisites(capacity types.CapacityForNunet) error { ok, err := o.Fs.DirExists(o.WorkDir) if err != nil { return fmt.Errorf("could not check if config directory exists: %w", err) } if !ok { return fmt.Errorf("config directory does not exist") } if err := utils.ValidateAddress(capacity.PaymentAddress); err != nil { return fmt.Errorf("could not validate payment address: %w", err) }
Found in dms/onboarding/onboarding.go by structure -
Method `executionHandler.run` has 75 lines of code (exceeds 50 allowed). Consider refactoring.
// run starts the container and handles its execution lifecycle. func (h *executionHandler) run(ctx context.Context) { h.running.Store(true) defer func() { if err := h.destroy(DestroyTimeout); err != nil { zlog.Sugar().Warnf("failed to destroy container: %v\n", err) } h.running.Store(false) close(h.waitCh) }() if err := h.client.StartContainer(ctx, h.containerID); err != nil { h.result = types.NewFailedExecutionResult(fmt.Errorf("failed to start container: %v", err)) return
Found in executor/docker/handler.go by structure -
Method `executionHandler.run` has 6 return statements (exceeds 4 allowed).
// run starts the container and handles its execution lifecycle. func (h *executionHandler) run(ctx context.Context) { h.running.Store(true) defer func() { if err := h.destroy(DestroyTimeout); err != nil { zlog.Sugar().Warnf("failed to destroy container: %v\n", err) } h.running.Store(false) close(h.waitCh) }() if err := h.client.StartContainer(ctx, h.containerID); err != nil { h.result = types.NewFailedExecutionResult(fmt.Errorf("failed to start container: %v", err)) return
Found in executor/docker/handler.go by structure -
Function `DecodeSpec` has 5 return statements (exceeds 4 allowed).
// DecodeSpec decodes a spec config into a docker engine spec // It converts the params into a docker EngineSpec struct and validates it func DecodeSpec(spec *types.SpecConfig) (EngineSpec, error) { if !spec.IsType(types.ExecutorTypeDocker) { return EngineSpec{}, fmt.Errorf( "invalid docker engine type. expected %s, but received: %s", types.ExecutorTypeDocker, spec.Type, ) } inputParams := spec.Params if inputParams == nil { return EngineSpec{}, fmt.Errorf("invalid docker engine params: params cannot be nil") }
Found in executor/docker/types.go by structure -
Method `Client.CreateContainer` has 6 arguments (exceeds 4 allowed). Consider refactoring.
// CreateContainer creates a new Docker container with the specified configuration. func (c *Client) CreateContainer( ctx context.Context, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig, platform *v1.Platform, name string, ) (string, error) { _, err := c.PullImage(ctx, config.Image)
Found in executor/docker/client.go by structure -
Function `DecodeSpec` has 5 return statements (exceeds 4 allowed).
// DecodeSpec decodes a spec config into a firecracker engine spec // It converts the params into a firecracker EngineSpec struct and validates it func DecodeSpec(spec *types.SpecConfig) (EngineSpec, error) { if !spec.IsType(types.ExecutorTypeFirecracker) { return EngineSpec{}, fmt.Errorf( "invalid firecracker engine type. expected %s, but received: %s", types.ExecutorTypeFirecracker, spec.Type, ) } inputParams := spec.Params if inputParams == nil { return EngineSpec{}, fmt.Errorf("invalid firecracker engine params: params cannot be nil") }
Found in executor/firecracker/types.go by structure -
Method `Client.DestroyVM` has 6 return statements (exceeds 4 allowed).
// DestroyVM destroys the Firecracker VM. func (c *Client) DestroyVM( ctx context.Context, m *firecracker.Machine, timeout time.Duration, ) error { // Get the PID of the Firecracker process and shut down the VM. // If the process is still running after the timeout, kill it. err := c.ShutdownVM(ctx, m) if err != nil { return fmt.Errorf("failed to shutdown vm: %w", err) } pid, _ := m.PID()
Found in executor/firecracker/client.go by structure -
Method `Client.FindVM` has 5 return statements (exceeds 4 allowed).
// FindVM finds a Firecracker VM by its socket path. // This implementation checks if the VM is running by sending a request to the Firecracker API. func (c *Client) FindVM(ctx context.Context, socketPath string) (*firecracker.Machine, error) { // Check if the socket file exists. if _, err := os.Stat(socketPath); err != nil { return nil, fmt.Errorf("VM with socket path %v not found", socketPath) } // Create a new Firecracker machine instance. cmd := firecracker.VMCommandBuilder{}.WithSocketPath(socketPath).Build(ctx) machine, err := firecracker.NewMachine( ctx, firecracker.Config{SocketPath: socketPath}, firecracker.WithProcessRunner(cmd), )
Found in executor/firecracker/client.go by structure -
Function `newOnboardMLCmd` has a Cognitive Complexity of 27 (exceeds 20 allowed). Consider refactoring.
} func newOnboardMLCmd(afs afero.Afero, dockerClient *docker.Client) *cobra.Command { return &cobra.Command{ Use: "onboard-ml", Short: "Setup for Machine Learning with GPU", Long: ``, RunE: func(cmd *cobra.Command, _ []string) error { wsl, err := utils.CheckWSL(afs) if err != nil { return fmt.Errorf("could not check WSL: %w", err) } vendors, err := resources.ManagerInstance.SystemSpecs().GetGPUVendors() if err != nil {
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in cmd/onboard-ml.go by structure -
Function `newGPUStatusCmd` has a Cognitive Complexity of 128 (exceeds 20 allowed). Consider refactoring.
) func newGPUStatusCmd() *cobra.Command { return &cobra.Command{ Use: "status", Short: "Check GPU status in real time", Long: ``, Run: func(_ *cobra.Command, _ []string) { vendors, err := resources.ManagerInstance.SystemSpecs().GetGPUVendors() if err != nil { fmt.Println("Error trying to detect GPU(s):", err) return } hasAMD := containsVendor(vendors, types.GPUVendorAMDATI)
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in cmd/gpu_status.go by structure -
Function `newGPUStatusCmd` has 137 lines of code (exceeds 50 allowed). Consider refactoring.
) func newGPUStatusCmd() *cobra.Command { return &cobra.Command{ Use: "status", Short: "Check GPU status in real time", Long: ``, Run: func(_ *cobra.Command, _ []string) { vendors, err := resources.ManagerInstance.SystemSpecs().GetGPUVendors() if err != nil { fmt.Println("Error trying to detect GPU(s):", err) return } hasAMD := containsVendor(vendors, types.GPUVendorAMDATI)
Found in cmd/gpu_status.go by structure -
Function `newOffboardCmd` has 8 return statements (exceeds 4 allowed).
// NewOffboardCmd is a constructor for `offboard` command func newOffboardCmd(client *utils.HTTPClient) *cobra.Command { fnForce := "force" cmd := &cobra.Command{ Use: "offboard", Short: "Offboard the device from NuNet", Long: ``, RunE: func(cmd *cobra.Command, _ []string) error { onboarded, err := checkOnboarded(client) if err != nil { return fmt.Errorf("could not check onboard status: %w", err) } if !onboarded { return fmt.Errorf("machine is not onboarded")
Found in cmd/offboard.go by structure -
Function `promptForPassphrase` has 5 return statements (exceeds 4 allowed).
} func promptForPassphrase() (string, error) { maxTries := 3 sigChan := make(chan os.Signal, 1) signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM) done := make(chan bool) var passphrase string var err error // Start a goroutine to handle passphrase input go func() { defer close(done)
Found in cmd/prompts.go by structure -
Function `newGPUOnboardCmd` has a Cognitive Complexity of 46 (exceeds 20 allowed). Consider refactoring.
) func newGPUOnboardCmd(afs afero.Afero) *cobra.Command { return &cobra.Command{ Use: "onboard", Short: "Install GPU drivers and Container Runtime", Long: ``, RunE: func(cmd *cobra.Command, _ []string) error { wsl, err := utils.CheckWSL(afs) if err != nil { return fmt.Errorf("could not check WSL: %w", err) } mining, err := checkMiningOS(afs) if err != nil {
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in cmd/gpu_onboard.go by structure -
Function `newGPUOnboardCmd` has 65 lines of code (exceeds 50 allowed). Consider refactoring.
) func newGPUOnboardCmd(afs afero.Afero) *cobra.Command { return &cobra.Command{ Use: "onboard", Short: "Install GPU drivers and Container Runtime", Long: ``, RunE: func(cmd *cobra.Command, _ []string) error { wsl, err := utils.CheckWSL(afs) if err != nil { return fmt.Errorf("could not check WSL: %w", err) } mining, err := checkMiningOS(afs) if err != nil {
Found in cmd/gpu_onboard.go by structure -
Function `newOnboardCmd` has a Cognitive Complexity of 29 (exceeds 20 allowed). Consider refactoring.
// NewOnboardCmd is a constructor for `onboard` command func newOnboardCmd(client *utils.HTTPClient) *cobra.Command { fnCPU := "cpu" fnMemory := "memory" fnChannel := "nunet-channel" fnAddr := "address" fnPlugin := "plugin" fnNTXPrice := "ntx-price" fnLocal := "local-enable" fnCardano := "cardano" fnUnavailable := "unavailable" cmd := &cobra.Command{ Use: "onboard",
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in cmd/onboard.go by structure -
Function `newOnboardCmd` has 93 lines of code (exceeds 50 allowed). Consider refactoring.
// NewOnboardCmd is a constructor for `onboard` command func newOnboardCmd(client *utils.HTTPClient) *cobra.Command { fnCPU := "cpu" fnMemory := "memory" fnChannel := "nunet-channel" fnAddr := "address" fnPlugin := "plugin" fnNTXPrice := "ntx-price" fnLocal := "local-enable" fnCardano := "cardano" fnUnavailable := "unavailable" cmd := &cobra.Command{ Use: "onboard",
Found in cmd/onboard.go by structure -
Function `newOnboardCmd` has 7 return statements (exceeds 4 allowed).
// NewOnboardCmd is a constructor for `onboard` command func newOnboardCmd(client *utils.HTTPClient) *cobra.Command { fnCPU := "cpu" fnMemory := "memory" fnChannel := "nunet-channel" fnAddr := "address" fnPlugin := "plugin" fnNTXPrice := "ntx-price" fnLocal := "local-enable" fnCardano := "cardano" fnUnavailable := "unavailable" cmd := &cobra.Command{ Use: "onboard",
Found in cmd/onboard.go by structure -
Function `newPeerListCmd` has 6 return statements (exceeds 4 allowed).
// NewPeerListCmd is a constructor for `peer list` subcommand func newPeerListCmd(client *utils.HTTPClient) *cobra.Command { fnDHT := "dht" cmd := &cobra.Command{ Use: "list", Short: "Display list of peers in the network", Long: ``, RunE: func(cmd *cobra.Command, _ []string) error { onboarded, err := checkOnboarded(client) if err != nil { return fmt.Errorf("could not check onboard status: %w", err) } if !onboarded { return fmt.Errorf("machine is not onboarded")
Found in cmd/peer_list.go by structure -
Function `newWalletNewCmd` has 5 return statements (exceeds 4 allowed).
// NewWalletNewCmd is a constructor for `wallet new` command func newWalletNewCmd(client *utils.HTTPClient) *cobra.Command { fnEth := "ethereum" fnCardano := "cardano" cmd := &cobra.Command{ Use: "new", Short: "Create new wallet", RunE: func(cmd *cobra.Command, _ []string) error { eth, _ := cmd.Flags().GetBool(fnEth) var ( pair *types.BlockchainAddressPrivKey query string
Found in cmd/wallet_new.go by structure -
Function `newResourceConfigCmd` has 7 return statements (exceeds 4 allowed).
// NewResourceConfigCmd is a constructor for `resource-config` command func newResourceConfigCmd(client *utils.HTTPClient) *cobra.Command { fnMemory := "memory" fnCPU := "cpu" fnNTXPrice := "ntx-price" cmd := &cobra.Command{ Use: "resource-config", Short: "Update configuration of onboarded device", RunE: func(cmd *cobra.Command, _ []string) error { onboarded, err := checkOnboarded(client) if err != nil { return fmt.Errorf("could not check onboard status: %w", err) }
Found in cmd/resource-config.go by structure -
Function `newCapacityCmd` has 6 return statements (exceeds 4 allowed).
// NewCapacityCmd is a constructor for `capacity` command func newCapacityCmd(client *utils.HTTPClient) *cobra.Command { fnAvailable := "available" fnOnboarded := "onboarded" fnFull := "full" cmd := &cobra.Command{ Use: "capacity", Short: "Display capacity of device resources", Long: `Retrieve capacity of the machine, onboarded or available amount of resources`, RunE: func(cmd *cobra.Command, _ []string) error { table := setupTable(cmd.OutOrStdout()) defer table.Render()
Found in cmd/capacity.go by structure -
Consider simplifying this complex logical expression.
func (g *GPU) Equal(gpu *GPU) bool { if g.Model == gpu.Model && g.TotalVRAM == gpu.TotalVRAM && g.UsedVRAM == gpu.UsedVRAM && g.FreeVRAM == gpu.FreeVRAM && g.Index == gpu.Index && g.Vendor == gpu.Vendor && g.PCIAddress == gpu.PCIAddress { return true }
Found in types/resource.go by structure -
Method `Capability.Add` has a Cognitive Complexity of 35 (exceeds 20 allowed). Consider refactoring.
// Add adds the resources of the given Capability to the current Capability func (c *Capability) Add(cap Capability) error { // Executors for _, executor := range cap.Executors { if !c.Executors.Contains(executor) { c.Executors = append(c.Executors, executor) } } // JobTypes for _, jobType := range cap.JobTypes { if !c.JobTypes.Contains(jobType) { c.JobTypes = append(c.JobTypes, jobType) }
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in types/capability.go by structure -
Method `Capability.Subtract` has a Cognitive Complexity of 26 (exceeds 20 allowed). Consider refactoring.
// Subtract subtracts the resources of the given Capability from the current Capability func (c *Capability) Subtract(cap Capability) error { // Executors // No Subtract operation for Executors // JobTypes // No Subtract operation for JobTypes // Resources if c.Resources.CPU.Cores < cap.Resources.CPU.Cores || c.Resources.CPU.ClockSpeedHz < cap.Resources.CPU.ClockSpeedHz { return errors.New("cpu resources are not enough") } if c.Resources.Memory.Size < cap.Resources.Memory.Size {
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in types/capability.go by structure -
Method `Capability.Add` has 67 lines of code (exceeds 50 allowed). Consider refactoring.
// Add adds the resources of the given Capability to the current Capability func (c *Capability) Add(cap Capability) error { // Executors for _, executor := range cap.Executors { if !c.Executors.Contains(executor) { c.Executors = append(c.Executors, executor) } } // JobTypes for _, jobType := range cap.JobTypes { if !c.JobTypes.Contains(jobType) { c.JobTypes = append(c.JobTypes, jobType) }
Found in types/capability.go by structure -
Function `makeAddrsFactory` has a Cognitive Complexity of 22 (exceeds 20 allowed). Consider refactoring.
} func makeAddrsFactory(announce []string, appendAnnouce []string, noAnnounce []string) func([]multiaddr.Multiaddr) []multiaddr.Multiaddr { var err error // To assign to the slice in the for loop existing := make(map[string]bool) // To avoid duplicates annAddrs := make([]multiaddr.Multiaddr, len(announce)) for i, addr := range announce { annAddrs[i], err = multiaddr.NewMultiaddr(addr) if err != nil { return nil } existing[addr] = true }
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in network/libp2p/filter.go by structure -
Function `makeAddrsFactory` has 52 lines of code (exceeds 50 allowed). Consider refactoring.
} func makeAddrsFactory(announce []string, appendAnnouce []string, noAnnounce []string) func([]multiaddr.Multiaddr) []multiaddr.Multiaddr { var err error // To assign to the slice in the for loop existing := make(map[string]bool) // To avoid duplicates annAddrs := make([]multiaddr.Multiaddr, len(announce)) for i, addr := range announce { annAddrs[i], err = multiaddr.NewMultiaddr(addr) if err != nil { return nil } existing[addr] = true }
Found in network/libp2p/filter.go by structure -
Function `NewHost` has a Cognitive Complexity of 21 (exceeds 20 allowed). Consider refactoring.
// NewHost returns a new libp2p host with dht and other related settings. func NewHost(ctx context.Context, config *types.Libp2pConfig) (host.Host, *dht.IpfsDHT, *pubsub.PubSub, error) { var idht *dht.IpfsDHT connmgr, err := connmgr.NewConnManager( 100, 400, connmgr.WithGracePeriod(time.Duration(config.GracePeriodMs)*time.Millisecond), ) if err != nil { return nil, nil, nil, err } filter := multiaddr.NewFilters() for _, s := range defaultServerFilters {
Details
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Found in network/libp2p/host.go by structure -
Function `NewHost` has 108 lines of code (exceeds 50 allowed). Consider refactoring.
// NewHost returns a new libp2p host with dht and other related settings. func NewHost(ctx context.Context, config *types.Libp2pConfig) (host.Host, *dht.IpfsDHT, *pubsub.PubSub, error) { var idht *dht.IpfsDHT connmgr, err := connmgr.NewConnManager( 100, 400, connmgr.WithGracePeriod(time.Duration(config.GracePeriodMs)*time.Millisecond), ) if err != nil { return nil, nil, nil, err } filter := multiaddr.NewFilters() for _, s := range defaultServerFilters {
Found in network/libp2p/host.go by structure -
Function `NewHost` has 9 return statements (exceeds 4 allowed).
// NewHost returns a new libp2p host with dht and other related settings. func NewHost(ctx context.Context, config *types.Libp2pConfig) (host.Host, *dht.IpfsDHT, *pubsub.PubSub, error) { var idht *dht.IpfsDHT connmgr, err := connmgr.NewConnManager( 100, 400, connmgr.WithGracePeriod(time.Duration(config.GracePeriodMs)*time.Millisecond), ) if err != nil { return nil, nil, nil, err } filter := multiaddr.NewFilters() for _, s := range defaultServerFilters {
Found in network/libp2p/host.go by structure -
File `libp2p.go` has 596 lines of code (exceeds 500 allowed). Consider refactoring.
package libp2p import ( "bufio" "bytes" "context" "crypto/sha256" "encoding/binary" "errors" "fmt" "io" "strings" "sync"
Found in network/libp2p/libp2p.go by structure -
`Libp2p` has 30 methods (exceeds 20 allowed). Consider refactoring.
// TODO-suggestion: maybe we should call it something else like Libp2pPeer, // Libp2pHost or just Peer (callers would use libp2p.Peer...) type Libp2p struct { Host host.Host DHT *dht.IpfsDHT PS peerstore.Peerstore pubsub *pubsub.PubSub pubsubTopics map[string]*pubsub.Topic topicValidators map[string]map[uint64]Validator topicSubscription map[string]map[uint64]*pubsub.Subscription nextTopicSubID uint64 topicMux sync.RWMutex // a list of peers discovered by discovery discoveredPeers []peer.AddrInfo
Found in network/libp2p/libp2p.go by structure -
Method `Libp2p.OpenStream` has 5 return statements (exceeds 4 allowed).
// OpenStream opens a stream to a remote address and returns the stream for the caller to handle. func (l *Libp2p) OpenStream(ctx context.Context, addr string, messageType types.MessageType) (network.Stream, error) { maddr, err := multiaddr.NewMultiaddr(addr) if err != nil { return nil, fmt.Errorf("invalid multiaddress: %w", err) } peerInfo, err := peer.AddrInfoFromP2pAddr(maddr) if err != nil { return nil, fmt.Errorf("could not resolve peer info: %w", err) } if err := l.Host.Connect(ctx, *peerInfo); err != nil { return nil, fmt.Errorf("failed to connect to peer: %w", err)
Found in network/libp2p/libp2p.go by structure -
Method `Libp2p.Ping` has 5 return statements (exceeds 4 allowed).
// TODO (Return error once): something that was confusing me when using this method is that the error is // returned twice if any. Once as a field of PingResult and one as a return value. func (l *Libp2p) Ping(ctx context.Context, peerIDAddress string, timeout time.Duration) (types.PingResult, error) { // avoid dial to self attempt if peerIDAddress == l.Host.ID().String() { err := errors.New("can't ping self") return types.PingResult{Success: false, Error: err}, err } pingCtx, cancel := context.WithTimeout(ctx, timeout) defer cancel() remotePeer, err := peer.Decode(peerIDAddress) if err != nil { return types.PingResult{}, err
Found in network/libp2p/libp2p.go by structure -
Method `Libp2p.ResolveAddress` has 6 return statements (exceeds 4 allowed).
// ResolveAddress resolves the address by given a peer id. func (l *Libp2p) ResolveAddress(ctx context.Context, id string) ([]string, error) { pid, err := peer.Decode(id) if err != nil { return nil, fmt.Errorf("failed to resolve invalid peer: %w", err) } // resolve ourself if l.Host.ID().String() == id { multiAddrs, err := l.GetMultiaddr() if err != nil { return nil, fmt.Errorf("failed to resolve self: %w", err) } resolved := make([]string, len(multiAddrs))
Found in network/libp2p/libp2p.go by structure -
Method `Libp2p.Query` has 5 return statements (exceeds 4 allowed).
// Query return all the advertisements in the network related to a key. // The network is queried to find providers for the given key, and peers which we aren't connected to can be retrieved. func (l *Libp2p) Query(ctx context.Context, key string) ([]*commonproto.Advertisement, error) { if key == "" { return nil, errors.New("advertisement key is empty") } customCID, err := createCIDFromKey(key) if err != nil { return nil, fmt.Errorf("failed to create cid for key %s: %w", key, err) } addrInfo, err := l.DHT.FindProviders(ctx, customCID) if err != nil { return nil, fmt.Errorf("failed to find providers for key %s: %w", key, err)
Found in network/libp2p/libp2p.go by structure -
Method `Libp2p.Advertise` has 8 return statements (exceeds 4 allowed).
// Advertise given data and a key pushes the data to the dht. func (l *Libp2p) Advertise(ctx context.Context, key string, data []byte) error { if key == "" { return errors.New("advertisement key is empty") } pubKeyBytes, err := l.getPublicKey() if err != nil { return fmt.Errorf("failed to get public key: %w", err) } envelope := &commonproto.Advertisement{ PeerId: l.Host.ID().String(), Timestamp: time.Now().Unix(),
Found in network/libp2p/libp2p.go by structure -
Method `Libp2p.sendMessage` has 8 return statements (exceeds 4 allowed).
} func (l *Libp2p) sendMessage(ctx context.Context, addr string, msg types.MessageEnvelope) error { peerAddr, err := multiaddr.NewMultiaddr(addr) if err != nil { return fmt.Errorf("invalid multiaddr %s: %v", addr, err) } peerInfo, err := peer.AddrInfoFromP2pAddr(peerAddr) if err != nil { return fmt.Errorf("failed to get peer info %s: %v", addr, err) } // we are delivering a message to ourself // we should use the handler to send the message to the handler directly which has been previously registered.
Found in network/libp2p/libp2p.go by structure -
Method `dhtValidator.Validate` has 7 return statements (exceeds 4 allowed).
// Validate validates an item placed into the dht. func (d dhtValidator) Validate(key string, value []byte) error { // empty value is considered deleting an item from the dht if len(value) == 0 { return nil } if !strings.HasPrefix(key, d.customNamespace) { return errors.New("invalid key namespace") } // verify signature var envelope commonproto.Advertisement err := proto.Unmarshal(value, &envelope)
Found in network/libp2p/dht.go by structure -
Method `RESTServer.ActorInvoke` has 6 return statements (exceeds 4 allowed).
// @Failure 500 {object} object "failed to send message to destination" // @Router /actor/invoke [post] func (rs RESTServer) ActorInvoke(c *gin.Context) { var msg actor.Envelope if err := c.ShouldBindJSON(&msg); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } p2p := rs.config.P2P if p2p != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "host node hasn't yet been initialized"}) } // Register a message handler for the responseCh
Found in api/actor.go by structure -
Method `RESTServer.ActorBroadcast` has 5 return statements (exceeds 4 allowed).
// @Failure 500 {object} object "failed to publish message" // @Router /actor/broadcast [post] func (rs RESTServer) ActorBroadcast(c *gin.Context) { var msg actor.Envelope if err := c.ShouldBindJSON(&msg); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } p2p := rs.config.P2P if p2p != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "host node hasn't yet been initialized"}) } if !msg.IsBroadcast() {
Found in api/actor.go by structure -
File `docs.go` has 888 lines of code (exceeds 500 allowed). Consider refactoring.
// Package docs Code generated by swaggo/swag. DO NOT EDIT package docs import "github.com/swaggo/swag" const docTemplate = `{ "schemes": {{ marshal .Schemes }}, "swagger": "2.0", "info": { "description": "{{escape .Description}}", "title": "{{.Title}}", "termsOfService": "https://nunet.io/tos", "contact": {
Found in api/docs/docs.go by structure -
Method `Storage.Upload` has 60 lines of code (exceeds 50 allowed). Consider refactoring.
// be careful if managing files with `os` (the volume controller might be // using an in-memory one) func (s *Storage) Upload(ctx context.Context, vol types.StorageVolume, destinationSpecs *types.SpecConfig) error { ctx, cancel := st.SpanContext(ctx, "s3", "s3_upload_duration", "opentelemetry", "log") defer cancel() target, err := DecodeInputSpec(destinationSpecs) if err != nil { ctx = context.WithValue(ctx, errorKey, err.Error()) st.Error(ctx, "s3_upload_decode_spec_failure", nil) return fmt.Errorf("failed to decode input spec: %v", err) } sanitizedKey := sanitizeKey(target.Key)
Found in storage/s3/upload.go by structure -
Method `Storage.Upload` has 9 return statements (exceeds 4 allowed).
// be careful if managing files with `os` (the volume controller might be // using an in-memory one) func (s *Storage) Upload(ctx context.Context, vol types.StorageVolume, destinationSpecs *types.SpecConfig) error { ctx, cancel := st.SpanContext(ctx, "s3", "s3_upload_duration", "opentelemetry", "log") defer cancel() target, err := DecodeInputSpec(destinationSpecs) if err != nil { ctx = context.WithValue(ctx, errorKey, err.Error()) st.Error(ctx, "s3_upload_decode_spec_failure", nil) return fmt.Errorf("failed to decode input spec: %v", err) } sanitizedKey := sanitizeKey(target.Key)
Found in storage/s3/upload.go by structure -
Function `DecodeInputSpec` has 5 return statements (exceeds 4 allowed).
} func DecodeInputSpec(spec *types.SpecConfig) (InputSource, error) { ctx, cancel := st.SpanContext(context.Background(), "s3", "decode_input_spec_duration", "opentelemetry", "log") defer cancel() if !spec.IsType(types.StorageProviderS3) { err := fmt.Errorf("invalid storage source type. Expected %s but received %s", types.StorageProviderS3, spec.Type) ctx = context.WithValue(ctx, errorKey, err.Error()) st.Error(ctx, "decode_input_spec_invalid_type_failure", nil) return InputSource{}, err } inputParams := spec.Params if inputParams == nil {
Found in storage/s3/specs_decoder.go by structure -
TODO found
Delegate Action = "delegate" Broadcast Action = "broadcast" // Revoke Action = "revoke" // TODO nonceLength = 12 // 96 bits
Found in lib/ucan/token.go by fixme -
TODO found
type BYOToken struct { // TODO followup }
Found in lib/ucan/token.go by fixme -
TODO found
return t.DMS.SignatureData() case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
return t.DMS.Issuer case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
return t.DMS.Subject case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
return t.DMS.Audience case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
return t.DMS.Capability case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
return t.DMS.Topic case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
return t.DMS.Expire case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
return t.DMS.Nonce case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
return t.DMS.Action case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
return t.DMS.Verify(trust, now) case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
return t.DMS.AllowAction(ot) case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
return t.DMS.Subsumes(ot) case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
return t.DMS.AllowInvocation(subject, audience, c) case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
return t.DMS.AllowBroadcast(subject, topic, c) case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
case t.UCAN != nil: // TODO UCAN envelopes for BYO trust; followup fallthrough default:
Found in lib/ucan/token.go by fixme -
TODO found
func SaveCapabilityContext(_ CapabilityContext, _ io.Writer) (int, error) { // TODO return 0, ErrTODO }
Found in lib/ucan/store.go by fixme -
TODO found
func LoadCapabilityContext(_ io.Reader, _ did.TrustContext) (CapabilityContext, error) { // TODO return nil, ErrTODO }
Found in lib/ucan/store.go by fixme -
TODO found
ErrTooBig = errors.New("capability blob too big") ErrTODO = errors.New("TODO") )
Found in lib/ucan/errors.go by fixme -
TODO found
// ReadVault func ReadVault(path string, passphrase string) ([]byte, error) { //nolint:revive // its a todo // TODO return nil, ErrTODO }
Found in lib/crypto/vault.go by fixme -
TODO found
// WriteVault func WriteVault(path string, passphrase string, data []byte) error { //nolint:revive // its a todo // TODO return ErrTODO }
Found in lib/crypto/vault.go by fixme -
TODO found
// BasicKeyStore handles keypair storage. // TODO: add cache? type BasicKeyStore struct { fs afero.Fs
Found in lib/crypto/keystore/keystore.go by fixme -
TODO found
ErrUnsupportedKeyType = errors.New("unsupported key type") ErrTODO = errors.New("TODO") )
Found in lib/crypto/errors.go by fixme -
TODO found
} // TODO other supported key types (secp?) t := multicodecKindEd25519PubKey size := varint.UvarintSize(t)
Found in lib/did/key.go by fixme -
TODO found
} // TODO validate parts according to spec: https://www.w3.org/TR/did-core/ }
Found in lib/did/did.go by fixme -
TODO found
func SaveTrustContext(_ TrustContext, _ io.Writer) (int, error) { // TODO follow up return 0, ErrTODO }
Found in lib/did/store.go by fixme -
TODO found
func LoadTrustContext(_ io.Reader) (TrustContext, error) { // TODO follow up return nil, ErrTODO }
Found in lib/did/store.go by fixme -
TODO found
ErrNoAnchorMethod = errors.New("no anchor method") ErrTODO = errors.New("TODO") )
Found in lib/did/errors.go by fixme -
TODO found
result = types.Worse // TODO: this comparator does not take into account options when several job types are available and several job types are required // in the same data structure; this is why the test fails; }
Found in dms/orchestrator/matching/JobTypesComparator.go by fixme -
TODO found
func Compare(l, r interface{}, _ ...Preference) types.Comparison { // TODO: it would be better to pass a pointer as this is a global structure comparatorMap := initComparatorMap()
Found in dms/orchestrator/matching/comparator.go by fixme -
TODO found
p2pNet = p2p // TODO: load the capability context, given the trust context and root did rootDID := did.FromPublicKey(pubKey) trustCtx := did.NewTrustContext()
Found in dms/dms.go by fixme -
TODO found
// GetSpecInfo returns the detailed specifications of the system // TODO: implement the method // https://gitlab.com/nunet/device-management-service/-/issues/537 func (d darwinSystemSpecs) GetSpecInfo() (types.SpecInfo, error) {
Found in dms/resources/system_specs_arm64_darwin.go by fixme -
TODO found
// https://gitlab.com/nunet/device-management-service/-/issues/537 func (d darwinSystemSpecs) GetSpecInfo() (types.SpecInfo, error) { // TODO implement me panic("implement me") }
Found in dms/resources/system_specs_arm64_darwin.go by fixme -
TODO found
) // TODO: This needs to be initialized in `dms` package and removed from here // https://gitlab.com/nunet/device-management-service/-/issues/536 // it is being initialized in `dms` package now but there is usage in executor
Found in dms/resources/init.go by fixme -
TODO found
// DefaultManager implements the Manager interface // TODO: do we want to have an in-memory cache for the resources instead of querying the DB every time? // TODO: Add telemetry for the methods https://gitlab.com/nunet/device-management-service/-/issues/535 type DefaultManager struct {
Found in dms/resources/resource_manager.go by fixme -
TODO found
// DefaultManager implements the Manager interface // TODO: do we want to have an in-memory cache for the resources instead of querying the DB every time? // TODO: Add telemetry for the methods https://gitlab.com/nunet/device-management-service/-/issues/535 type DefaultManager struct { usageMonitor UsageMonitor
Found in dms/resources/resource_manager.go by fixme -
TODO found
// GetSpecInfo returns the detailed specifications of the system // TODO: implement the method // https://gitlab.com/nunet/device-management-service/-/issues/537 func (d darwinSystemSpecs) GetSpecInfo() (types.SpecInfo, error) {
Found in dms/resources/system_specs_amd64_darwin.go by fixme -
TODO found
// https://gitlab.com/nunet/device-management-service/-/issues/537 func (d darwinSystemSpecs) GetSpecInfo() (types.SpecInfo, error) { // TODO implement me panic("implement me") }
Found in dms/resources/system_specs_amd64_darwin.go by fixme -
TODO found
// GetSpecInfo returns the detailed specifications of the system // TODO: implement the method // https://gitlab.com/nunet/device-management-service/-/issues/537 func (l linuxSystemSpecs) GetSpecInfo() (types.SpecInfo, error) {
Found in dms/resources/system_specs_linux.go by fixme -
TODO found
// https://gitlab.com/nunet/device-management-service/-/issues/537 func (l linuxSystemSpecs) GetSpecInfo() (types.SpecInfo, error) { // TODO implement me panic("implement me") }
Found in dms/resources/system_specs_linux.go by fixme -
TODO found
// fetchGPUMetadata fetches the GPU metadata for the system using `ghw.GPU()` // TODO: Use one single library to fetch GPU information or improve the match criteria // https://gitlab.com/nunet/device-management-service/-/issues/548 // TODO: write tests by mocking the gpu snapshot
Found in dms/resources/system_specs_linux.go by fixme -
TODO found
// TODO: Use one single library to fetch GPU information or improve the match criteria // https://gitlab.com/nunet/device-management-service/-/issues/548 // TODO: write tests by mocking the gpu snapshot // https://gitlab.com/nunet/device-management-service/-/issues/534 func (l linuxSystemSpecs) fetchGPUMetadata() (map[types.GPUVendor][]gpuMetadata, error) {
Found in dms/resources/system_specs_linux.go by fixme -
TODO found
} // TODO: disk usage var totalVCPU, totalMemSizeMib uint for _, vm := range vms {
Found in dms/resources/usage_monitor.go by fixme -
TODO found
} // TODO: disk usage for _, service := range services { resourcesReq := requirements[service.ResourceRequirements]
Found in dms/resources/usage_monitor.go by fixme -
TODO found
EngineSpec: &a.Job.Execution, Resources: &a.Job.Resources, // TODO add the following Inputs: []*types.StorageVolumeExecutor{}, Outputs: []*types.StorageVolumeExecutor{},
Found in dms/jobs/allocation.go by fixme -
TODO found
} // TODO: ExecutionResources and FreeResources should be compatible func availableResources(jobResources types.ExecutionResources, fr types.FreeResources) bool { return fr.RAM >= uint64(jobResources.Memory.Size) && fr.Disk >= jobResources.Disk.Size && fr.CPU > float64(jobResources.CPU.Cores)
Found in dms/jobs/allocation.go by fixme -
TODO found
// Deleted now because dependencies such as the docker package have been replaced with executor/docker func SanityCheck(_ *gorm.DB) { // TODO: sanity check of DMS last exit and correction of invalid states // resources.CalcFreeResAndUpdateDB()
Found in dms/sanity_check.go by fixme -
TODO found
func HandleFromString(_ string) (Handle, error) { // TODO return Handle{}, ErrTODO }
Found in dms/actor/handle.go by fixme -
TODO found
func AddressFromString(_ string) (Address, error) { // TODO return Address{}, ErrTODO }
Found in dms/actor/handle.go by fixme -
TODO found
ErrRateLimitExceeded = errors.New("rate limited exceeded") ErrTODO = errors.New("TODO") )
Found in dms/actor/errors.go by fixme -
TODO found
return false, nil } // TODO: validate onboarding params return true, nil }
Found in dms/onboarding/onboarding.go by fixme -
TODO found
oConf.Name = hostname oConf.UpdateTimestamp = time.Now().Unix() // TODO: 553 oConf.TotalResources.RAM = provisionedResources.RAM oConf.TotalResources.NumCores = provisionedResources.NumCores
Found in dms/onboarding/onboarding.go by fixme -
TODO found
oConf.OnboardedResources.RAM = capacity.Memory oConf.OnboardedResources.CPU = float64(capacity.CPU) // TODO: 553 oConf.Network = capacity.Channel oConf.PublicKey = capacity.PaymentAddress
Found in dms/onboarding/onboarding.go by fixme -
TODO found
} // TODO: shutdown routine to stop networking etc... here err = o.ParamsRepo.Clear(ctx)
Found in dms/onboarding/onboarding.go by fixme -
TODO found
} //nolint:gosec // to be fixed in TODO: 553 if capacity.Memory > provisionedResources.RAM*9/10 || capacity.Memory < provisionedResources.RAM/10 { return fmt.Errorf("memory should be between 10%% and 90%% of the available memory (%d and %d)", int64(provisionedResources.RAM/10), int64(provisionedResources.RAM*9/10))
Found in dms/onboarding/onboarding.go by fixme -
TODO found
CPUNo: totalProvisioned.NumCores, CPUHz: cpuInfo.MHzPerCore, PriceCPU: 0, // TODO: Get price of CPU RAM: capacity.Memory, PriceRAM: 0, // TODO: Get price of RAM
Found in dms/onboarding/onboarding.go by fixme -
TODO found
PriceCPU: 0, // TODO: Get price of CPU RAM: capacity.Memory, PriceRAM: 0, // TODO: Get price of RAM Vcpu: int(math.Floor((float64(capacity.CPU)) / cpuInfo.MHzPerCore)), Disk: 0,
Found in dms/onboarding/onboarding.go by fixme -
TODO found
// CreatePaymentAddress generates a keypair based on the wallet type. Currently supported types: ethereum, cardano. // TODO: This should be moved to utils-related package. It's a utility function independent of onboarding func CreatePaymentAddress(wallet string) (*types.BlockchainAddressPrivKey, error) { var (
Found in dms/onboarding/onboarding.go by fixme -
TODO found
} // TODO: Move this code block ( L263-272) to the allocator in future // Select the GPU with the highest available free VRAM and choose the GPU vendor for container's host config gpus, err := resources.ManagerInstance.SystemSpecs().GetGPUs()
Found in executor/docker/executor.go by fixme -
TODO found
} // TODO:what to do with the response body? fmt.Fprintf(cmd.OutOrStdout(), "%s\n", resBody) return nil
Found in cmd/offboard.go by fixme -
TODO found
} // TODO: Define API endpoint for this vendors, err := resources.ManagerInstance.SystemSpecs().GetGPUVendors() if err != nil {
Found in cmd/gpu_onboard.go by fixme -
TODO found
Cardano: cardano, ServerMode: local, IsAvailable: unavailable, // TODO: Update this }
Found in cmd/onboard.go by fixme -
TODO found
} // TODO: what to do with the response body? fmt.Fprintf(cmd.OutOrStdout(), "%s\n", resBody)
Found in cmd/onboard.go by fixme -
TODO found
} // TODO: validate passphrase (minimum x characters) if passphrase == "" { return fmt.Errorf("invalid passphrase")
Found in cmd/run.go by fixme -
TODO found
MessageHashAction string Action string // TODO: Add ContainerType field }
Found in types/README.md by fixme -
TODO found
// Warning: this is just a draft. And it might be moved to an Encryption package // // TODO: it must support encryption of files/directories, otherwise we have to // create another interface for the usecase type Encryptor interface {
Found in types/encryption.go by fixme -
TODO found
// Warning: this is just a draft. And it might be moved to an Encryption package // // TODO: it must support decryption of files/directories, otherwise we have to // create another interface for the usecase type Decryptor interface {
Found in types/encryption.go by fixme -
TODO found
// ResourceOps defines the operations on resources // TODO: Check how to handle GPU resources type ResourceOps interface { // Add returns the sum of the resources
Found in types/resource.go by fixme -
TODO found
// Add returns the sum of the resources func (r Resources) Add(r2 Resources) Resources { // TODO: GPU addition return Resources{ CPU: r.CPU + r2.CPU,
Found in types/resource.go by fixme -
TODO found
} // TODO: GPU subtraction if r.RAM < r2.RAM {
Found in types/resource.go by fixme -
TODO found
// RequiredResources represents the resources required by the jobs running on the machine // TODO: this is a replacement for ServiceResourceRequirements. Check with the team on this. type RequiredResources struct { BaseDBModel
Found in types/resource.go by fixme -
TODO found
// SpecInfo represents the machine specifications // TODO: Finalise the fields required in this struct // https://gitlab.com/nunet/device-management-service/-/issues/533 type SpecInfo struct {
Found in types/resource.go by fixme -
TODO found
type Disk struct { // Model represents the disk model, e.g., "Samsung 970 EVO Plus", "Western Digital Blue SN550" // TODO: may be removed as Disk models will be usually irrelevant, right? Model string
Found in types/resource.go by fixme -
TODO found
// Vendor represents the disk manufacturer, e.g., "Samsung", "Western Digital" // TODO: may be removed as Disk vendors will be usually irrelevant, right? Vendor string
Found in types/resource.go by fixme -
TODO found
// Read speed in bytes per second // TODO: may be removed as it may be too specific for our case ReadSpeed uint64 // Write speed in bytes per second
Found in types/resource.go by fixme -
TODO found
ReadSpeed uint64 // Write speed in bytes per second // TODO: may be removed as it may be too specific for our case WriteSpeed uint64 }
Found in types/resource.go by fixme -
TODO found
MessageHashAction string Action string // TODO: Add ContainerType field }
Found in types/machine.go by fixme -
TODO found
// created using the VolumeController, there will be no data in it by default. // // TODO-maybe [job]: should volumes be related to a job or []job? // // TODO-maybe: most of the fields should be private, callers shouldn't be able to altere
Found in types/storage.go by fixme -
TODO found
// TODO-maybe [job]: should volumes be related to a job or []job? // // TODO-maybe: most of the fields should be private, callers shouldn't be able to altere // the state of the volume except when using certain methods type StorageVolume struct {
Found in types/storage.go by fixme -
TODO found
// EncryptionType might be checked first if needed) // // TODO-maybe [type]: maybe it should be of type cid.CID CID string
Found in types/storage.go by fixme -
TODO found
// Size is the size of the storage volume // // TODO-maybe: if relying on a size field, we would have to be more careful // how state is being mutated (and they shouldn't be by the caller) // - Size might be calculated only when locking the volume also
Found in types/storage.go by fixme -
TODO found
) // TODO: Consider comments in this thread: https://gitlab.com/nunet/device-management-service/-/merge_requests/356#note_1997854443 // TODO: Consider comments in this thread: https://gitlab.com/nunet/device-management-service/-/merge_requests/356#note_1997875361
Found in types/comparison.go by fixme -
TODO found
// TODO: Consider comments in this thread: https://gitlab.com/nunet/device-management-service/-/merge_requests/356#note_1997854443 // TODO: Consider comments in this thread: https://gitlab.com/nunet/device-management-service/-/merge_requests/356#note_1997875361 // 'left' means 'this object' and 'right' means 'the supplied other object';
Found in types/comparison.go by fixme -
TODO found
) // TODO: pass the logger to the constructor and remove from here var ( zlog *otelzap.Logger
Found in network/libp2p/init.go by fixme -
TODO found
// Libp2p contains the configuration for a Libp2p instance. // // TODO-suggestion: maybe we should call it something else like Libp2pPeer, // Libp2pHost or just Peer (callers would use libp2p.Peer...) type Libp2p struct {
Found in network/libp2p/libp2p.go by fixme -
TODO found
// New creates a libp2p instance. // // TODO-Suggestion: move types.Libp2pConfig to here for better readability. // Unless there is a reason to keep within types. func New(config *types.Libp2pConfig, fs afero.Fs) (*Libp2p, error) {
Found in network/libp2p/libp2p.go by fixme -
TODO found
err = l.advertiseForRendezvousDiscovery(context) if err != nil { // TODO: the error might be misleading as a peer can normally work well if an error // is returned here (e.g.: the error is yielded in tests even though all tests pass). zlog.Sugar().Errorf("failed to start network with randevouz discovery: %v", err)
Found in network/libp2p/libp2p.go by fixme -
TODO found
// Ping the remote address. The remote address is the encoded peer id which will be decoded and used here. // // TODO (Return error once): something that was confusing me when using this method is that the error is // returned twice if any. Once as a field of PingResult and one as a return value. func (l *Libp2p) Ping(ctx context.Context, peerIDAddress string, timeout time.Duration) (types.PingResult, error) {
Found in network/libp2p/libp2p.go by fixme -
TODO found
advertisements := make([]*commonproto.Advertisement, 0) for _, v := range addrInfo { // TODO: use go routines to get the values in parallel. bytesAdvertisement, err := l.DHT.GetValue(ctx, l.getCustomNamespace(key, v.ID.String())) if err != nil {
Found in network/libp2p/libp2p.go by fixme -
TODO found
func (dhtValidator) Select(_ string, _ [][]byte) (int, error) { return 0, nil } // TODO remove the below when network package is fully implemented // UpdateKadDHT is a stub func (l *Libp2p) UpdateKadDHT() {
Found in network/libp2p/dht.go by fixme -
TODO found
// NewNetwork returns a new network given the configuration. func NewNetwork(netConfig *types.NetworkConfig, fs afero.Fs) (Network, error) { // TODO: probable additional params to receive: DB, FileSystem if netConfig == nil { return nil, errors.New("network configuration is nil")
Found in network/network.go by fixme -
FIXME found
func getCustomCorsConfig() cors.Config { config := defaultConfig() // FIXME: This is a security concern. config.AllowOrigins = []string{"http://localhost:9991", "http://localhost:9992"} return config
Found in api/api.go by fixme -
TODO found
// @Router /device/status [get] func (rs RESTServer) DeviceStatus(c *gin.Context) { // TODO: handle this after refactor // status, err := libp2p.DeviceStatus() // if err != nil {
Found in api/device.go by fixme -
TODO found
} // TODO: handle this after refactor // err = libp2p.ChangeDeviceStatus(status.IsAvailable) // if err != nil {
Found in api/device.go by fixme -
XXX found
type Job struct { LogUpdateInterval int `mapstructure:"log_update_interval"` // in minutes TargetPeer string `mapstructure:"target_peer"` // specific peer to send deployment requests to - XXX probably not a good idea. Remove after testing stage. CleanupInterval int `mapstructure:"cleanup_interval"` // docker container and images clean up interval in days }
Found in internal/config/README.md by fixme -
TODO found
} // TODO: add error handling!!! func LoadConfig() { paths := []string{
Found in internal/config/load.go by fixme -
XXX found
type Job struct { LogUpdateInterval int `mapstructure:"log_update_interval"` // in minutes TargetPeer string `mapstructure:"target_peer"` // specific peer to send deployment requests to - XXX probably not a good idea. Remove after testing stage. CleanupInterval int `mapstructure:"cleanup_interval"` // docker container and images clean up interval in days }
Found in internal/config/config.go by fixme -
TODO found
// NewDefaultVolumeController returns a new instance of BasicVolumeController // // TODO-BugFix [path]: volBasePath might not end with `/`, causing errors when calling methods. // We need to validate it using the `path` library or just verifying the string. func NewDefaultVolumeController(repo repositories.StorageVolume, volBasePath string, fs afero.Fs) (*BasicVolumeController, error) {
Found in storage/basic_controller/basic_controller.go by fixme -
TODO found
// where `name` is random. // // TODO-maybe [withName]: allow callers to specify custom name for path func (vc *BasicVolumeController) CreateVolume(volSource storage.VolumeSource, opts ...storage.CreateVolOpt) (types.StorageVolume, error) { ctx, cancel := st.SpanContext(context.Background(), "controller", "volume_create_duration", "opentelemetry", "log")
Found in storage/basic_controller/basic_controller.go by fixme -
TODO found
// It optionally can also set the CID and mark the volume as private. // // TODO-maybe [CID]: maybe calculate CID of every volume in case WithCID opt is not provided func (vc *BasicVolumeController) LockVolume(pathToVol string, opts ...storage.LockVolOpt) error { ctx, cancel := st.SpanContext(context.Background(), "controller", "volume_lock_duration", "opentelemetry", "log")
Found in storage/basic_controller/basic_controller.go by fixme -
TODO found
// WithCID sets the CID of a given volume if already calculated // // TODO [validate]: check if CID provided is valid func WithCID(cid string) storage.LockVolOpt { return func(v *types.StorageVolume) {
Found in storage/basic_controller/basic_controller.go by fixme -
TODO found
// ListVolumes returns a list of all storage volumes stored on the database // // TODO [filter]: maybe add opts to filter results by certain values func (vc *BasicVolumeController) ListVolumes() ([]types.StorageVolume, error) { ctx, cancel := st.SpanContext(context.Background(), "controller", "volume_list_duration", "opentelemetry", "log")
Found in storage/basic_controller/basic_controller.go by fixme -
TODO found
// GetSize returns the size of a volume // TODO-minor: identify which measurement type will be used func (vc *BasicVolumeController) GetSize(identifier string, idType storage.IDType) (int64, error) { ctx, cancel := st.SpanContext(context.Background(), "controller", "volume_get_size_duration", "opentelemetry", "log")
Found in storage/basic_controller/basic_controller.go by fixme -
TODO found
} // TODO-minor: compiler-time check for interface implementation var _ storage.VolumeController = (*BasicVolumeController)(nil)
Found in storage/basic_controller/basic_controller.go by fixme -
TODO found
// VolumeController is used to manage storage volumes. // // TODO-maybe: is the interface too big? We may have to split it? type VolumeController interface { // CreateVolume creates a directory where data can be stored, and returns a StorageVolume
Found in storage/volumes.go by fixme -
TODO found
// One of the opts may be a CID. Or the implementation might handle the CID calculation // // TODO-maybe: after volume is locked, callers should not be able to write data to it. LockVolume(pathToVol string, opts ...LockVolOpt) error
Found in storage/volumes.go by fixme -
TODO found
// GetSize returns the size of a volume // TODO-minor: identify which measurement type will be used GetSize(identifier string, idType IDType) (int64, error)
Found in storage/volumes.go by fixme -
TODO found
GetSize(identifier string, idType IDType) (int64, error) // TODO-maybe: encrypt/decrypt method might move to an unique EncryptVolume/DecryptVolume interfaces // or something else. // - Warning: if moved, EncryptionType field of StorageVolume must be updated somehow by the new interface
Found in storage/volumes.go by fixme -
XXX found
echo "Looking for old versions of nunet-dms ..." # XXX this can be removed once the new "nunet" binary has been in use for sometime if [ -f "/usr/bin/nunet-dms" ];then rm -f /usr/bin/nunet-dms
Found in maint-scripts/nunet-dms/DEBIAN/preinst by fixme