diff --git a/certificate/authorization/authorizations.go b/certificate/authorization/authorizations.go index 2697f4b69..b219cc936 100644 --- a/certificate/authorization/authorizations.go +++ b/certificate/authorization/authorizations.go @@ -167,7 +167,7 @@ func (a Authorization) String() string { return fmt.Sprintf("%."+fmtLen+"s..", a.Token.String()) } -// Equal checks if two tokens have equal user IDs and data +// Equal checks if two tokens have equal user IDs and data. func (t *Token) Equal(cmpToken *Token) bool { return t.UserID == cmpToken.UserID && bytes.Equal(t.Data[:], cmpToken.Data[:]) } diff --git a/certificate/certificateclient/client.go b/certificate/certificateclient/client.go index 16ebcb937..9f221e855 100644 --- a/certificate/certificateclient/client.go +++ b/certificate/certificateclient/client.go @@ -24,7 +24,7 @@ type Config struct { TLS tlsopts.Config } -// Client implements pb.DRPCCertificatesClient +// Client implements pb.DRPCCertificatesClient. type Client struct { conn *rpc.Conn client pb.DRPCCertificatesClient diff --git a/certificate/peer_test.go b/certificate/peer_test.go index e20a432c6..ef92f46ec 100644 --- a/certificate/peer_test.go +++ b/certificate/peer_test.go @@ -29,7 +29,7 @@ import ( "storj.io/storj/pkg/server" ) -// TODO: test sad path +// TODO: test sad path. func TestCertificateSigner_Sign_E2E(t *testing.T) { testidentity.SignerVersionsTest(t, func(t *testing.T, _ storj.IDVersion, signer *identity.FullCertificateAuthority) { testidentity.CompleteIdentityVersionsTest(t, func(t *testing.T, _ storj.IDVersion, serverIdent *identity.FullIdentity) { diff --git a/cmd/inspector/main.go b/cmd/inspector/main.go index 536096399..0f4d37949 100644 --- a/cmd/inspector/main.go +++ b/cmd/inspector/main.go @@ -119,7 +119,7 @@ func NewInspector(ctx context.Context, address, path string) (*Inspector, error) // Close closes the inspector. func (i *Inspector) Close() error { return i.conn.Close() } -// ObjectHealth gets information about the health of an object on the network +// ObjectHealth gets information about the health of an object on the network. func ObjectHealth(cmd *cobra.Command, args []string) (err error) { ctx, _ := process.Ctx(cmd) i, err := NewInspector(ctx, *Addr, *IdentityPath) @@ -201,7 +201,7 @@ func ObjectHealth(cmd *cobra.Command, args []string) (err error) { return nil } -// SegmentHealth gets information about the health of a segment on the network +// SegmentHealth gets information about the health of a segment on the network. func SegmentHealth(cmd *cobra.Command, args []string) (err error) { ctx, _ := process.Ctx(cmd) i, err := NewInspector(ctx, *Addr, *IdentityPath) @@ -415,7 +415,7 @@ func getSegments(cmd *cobra.Command, args []string) error { return nil } -// sortSegments by the object they belong to +// sortSegments by the object they belong to. func sortSegments(segments []*pb.IrreparableSegment) map[string][]*pb.IrreparableSegment { objects := make(map[string][]*pb.IrreparableSegment) for _, seg := range segments { diff --git a/cmd/internal/asset/asset.go b/cmd/internal/asset/asset.go index 20a3176ae..141ae7b57 100644 --- a/cmd/internal/asset/asset.go +++ b/cmd/internal/asset/asset.go @@ -105,7 +105,7 @@ func ReadFile(path string) (*Asset, error) { return asset, nil } -// readFiles adds all nested files to asset +// readFiles adds all nested files to asset. func (asset *Asset) readFiles(dir string, infos []os.FileInfo) error { for _, info := range infos { child, err := ReadFile(filepath.Join(dir, info.Name())) diff --git a/cmd/internal/asset/inmemory.go b/cmd/internal/asset/inmemory.go index b3c437a9f..96420c38a 100644 --- a/cmd/internal/asset/inmemory.go +++ b/cmd/internal/asset/inmemory.go @@ -14,13 +14,13 @@ import ( var _ http.FileSystem = (*InmemoryFileSystem)(nil) -// InmemoryFileSystem defines an inmemory http.FileSystem +// InmemoryFileSystem defines an inmemory http.FileSystem. type InmemoryFileSystem struct { Root *Asset Index map[string]*Asset } -// Inmemory creates an InmemoryFileSystem from +// Inmemory creates an InmemoryFileSystem from. func Inmemory(root *Asset) *InmemoryFileSystem { fs := &InmemoryFileSystem{} fs.Root = root @@ -29,7 +29,7 @@ func Inmemory(root *Asset) *InmemoryFileSystem { return fs } -// reindex inserts a node to the index +// reindex inserts a node to the index. func (fs *InmemoryFileSystem) reindex(prefix, name string, file *Asset) { fs.Index[path.Join(prefix, name)] = file for _, child := range file.Children { @@ -51,7 +51,7 @@ func (asset *Asset) File() *File { return &File{*bytes.NewReader(asset.Data), asset} } -// File defines a readable file +// File defines a readable file. type File struct { bytes.Reader *Asset @@ -98,20 +98,20 @@ type FileInfo struct { modTime time.Time } -// Name implements os.FileInfo +// Name implements os.FileInfo. func (info FileInfo) Name() string { return info.name } -// Size implements os.FileInfo +// Size implements os.FileInfo. func (info FileInfo) Size() int64 { return info.size } -// Mode implements os.FileInfo +// Mode implements os.FileInfo. func (info FileInfo) Mode() os.FileMode { return info.mode } -// ModTime implements os.FileInfo +// ModTime implements os.FileInfo. func (info FileInfo) ModTime() time.Time { return info.modTime } -// IsDir implements os.FileInfo +// IsDir implements os.FileInfo. func (info FileInfo) IsDir() bool { return info.mode.IsDir() } -// Sys implements os.FileInfo +// Sys implements os.FileInfo. func (info FileInfo) Sys() interface{} { return nil } diff --git a/cmd/internal/wizard/wizard.go b/cmd/internal/wizard/wizard.go index 85841f330..d8c786aa6 100644 --- a/cmd/internal/wizard/wizard.go +++ b/cmd/internal/wizard/wizard.go @@ -17,7 +17,7 @@ import ( "storj.io/common/storj" ) -// PromptForAccessName handles user input for access name to be used with wizards +// PromptForAccessName handles user input for access name to be used with wizards. func PromptForAccessName() (string, error) { _, err := fmt.Printf("Choose an access name (use lowercase letters) [\"default\"]: ") if err != nil { @@ -41,7 +41,7 @@ func PromptForAccessName() (string, error) { return accessName, nil } -// PromptForSatellite handles user input for a satellite address to be used with wizards +// PromptForSatellite handles user input for a satellite address to be used with wizards. func PromptForSatellite(cmd *cobra.Command) (string, error) { satellites := []string{ "12EayRS2V1kEsWESU9QMRseFhdxYxKicsiFmxrsLZHeLUtdps3S@us-central-1.tardigrade.io:7777", @@ -115,7 +115,7 @@ func PromptForSatellite(cmd *cobra.Command) (string, error) { return satelliteAddress, nil } -// PromptForAPIKey handles user input for an API key to be used with wizards +// PromptForAPIKey handles user input for an API key to be used with wizards. func PromptForAPIKey() (string, error) { _, err := fmt.Print("Enter your API key: ") if err != nil { @@ -134,7 +134,7 @@ func PromptForAPIKey() (string, error) { return apiKey, nil } -// PromptForEncryptionPassphrase handles user input for an encryption passphrase to be used with wizards +// PromptForEncryptionPassphrase handles user input for an encryption passphrase to be used with wizards. func PromptForEncryptionPassphrase() (string, error) { _, err := fmt.Print("Enter your encryption passphrase: ") if err != nil { diff --git a/cmd/satellite/gracefulexit.go b/cmd/satellite/gracefulexit.go index ea03434a2..3d4e39d0a 100644 --- a/cmd/satellite/gracefulexit.go +++ b/cmd/satellite/gracefulexit.go @@ -25,7 +25,7 @@ import ( "storj.io/storj/satellite/satellitedb" ) -// generateGracefulExitCSV creates a report with graceful exit data for exiting or exited nodes in a given period +// generateGracefulExitCSV creates a report with graceful exit data for exiting or exited nodes in a given period. func generateGracefulExitCSV(ctx context.Context, completed bool, start time.Time, end time.Time, output io.Writer) error { db, err := satellitedb.New(zap.L().Named("db"), gracefulExitCfg.Database, satellitedb.Options{}) if err != nil { diff --git a/cmd/satellite/main.go b/cmd/satellite/main.go index e2cdae14c..ec14e922b 100644 --- a/cmd/satellite/main.go +++ b/cmd/satellite/main.go @@ -37,7 +37,7 @@ import ( "storj.io/storj/satellite/satellitedb/dbx" ) -// Satellite defines satellite configuration +// Satellite defines satellite configuration. type Satellite struct { Database string `help:"satellite database connection string" releaseDefault:"postgres://" devDefault:"postgres://"` @@ -55,7 +55,7 @@ type Satellite struct { satellite.Config } -// APIKeysLRUOptions returns a cache.Options based on the APIKeys LRU config +// APIKeysLRUOptions returns a cache.Options based on the APIKeys LRU config. func (s *Satellite) APIKeysLRUOptions() cache.Options { return cache.Options{ Expiration: s.DatabaseOptions.APIKeysCache.Expiration, @@ -63,7 +63,7 @@ func (s *Satellite) APIKeysLRUOptions() cache.Options { } } -// RevocationLRUOptions returns a cache.Options based on the Revocations LRU config +// RevocationLRUOptions returns a cache.Options based on the Revocations LRU config. func (s *Satellite) RevocationLRUOptions() cache.Options { return cache.Options{ Expiration: s.DatabaseOptions.RevocationsCache.Expiration, diff --git a/cmd/satellite/reports/attribution.go b/cmd/satellite/reports/attribution.go index a6fc53d46..3ad15aed7 100644 --- a/cmd/satellite/reports/attribution.go +++ b/cmd/satellite/reports/attribution.go @@ -29,7 +29,7 @@ var headers = []string{ "bytes:BWEgress", } -// GenerateAttributionCSV creates a report with +// GenerateAttributionCSV creates a report with. func GenerateAttributionCSV(ctx context.Context, database string, partnerID uuid.UUID, start time.Time, end time.Time, output io.Writer) error { log := zap.L().Named("db") db, err := satellitedb.New(log, database, satellitedb.Options{}) diff --git a/cmd/satellite/usage.go b/cmd/satellite/usage.go index 1b508e46c..16720b244 100644 --- a/cmd/satellite/usage.go +++ b/cmd/satellite/usage.go @@ -19,7 +19,7 @@ import ( "storj.io/storj/satellite/satellitedb" ) -// generateNodeUsageCSV creates a report with node usage data for all nodes in a given period which can be used for payments +// generateNodeUsageCSV creates a report with node usage data for all nodes in a given period which can be used for payments. func generateNodeUsageCSV(ctx context.Context, start time.Time, end time.Time, output io.Writer) error { db, err := satellitedb.New(zap.L().Named("db"), nodeUsageCfg.Database, satellitedb.Options{}) if err != nil { diff --git a/cmd/segment-reaper/observer_test.go b/cmd/segment-reaper/observer_test.go index c861d22c0..c8ff15d4b 100644 --- a/cmd/segment-reaper/observer_test.go +++ b/cmd/segment-reaper/observer_test.go @@ -573,7 +573,7 @@ func TestObserver_findZombieSegments(t *testing.T) { } // segmentRef is an object segment reference to be used for simulating calls to -// observer.processSegment +// observer.processSegment. type segmentRef struct { path metainfo.ScopedPath pointer *pb.Pointer diff --git a/cmd/storagenode/dashboard.go b/cmd/storagenode/dashboard.go index 0a34fc38a..22465478c 100644 --- a/cmd/storagenode/dashboard.go +++ b/cmd/storagenode/dashboard.go @@ -145,7 +145,7 @@ func printDashboard(data *pb.DashboardResponse) error { return nil } -// clearScreen clears the screen so it can be redrawn +// clearScreen clears the screen so it can be redrawn. func clearScreen() { switch runtime.GOOS { case "linux", "darwin": diff --git a/cmd/storagenode/deprecated.go b/cmd/storagenode/deprecated.go index f73ee5125..81f1e3607 100644 --- a/cmd/storagenode/deprecated.go +++ b/cmd/storagenode/deprecated.go @@ -12,7 +12,7 @@ import ( "go.uber.org/zap" ) -// Deprecated contains deprecated config structs +// Deprecated contains deprecated config structs. type Deprecated struct { Kademlia struct { ExternalAddress string `default:"" hidden:"true"` @@ -23,7 +23,7 @@ type Deprecated struct { } } -// maps deprecated config values to new values if applicable +// maps deprecated config values to new values if applicable. func mapDeprecatedConfigs(log *zap.Logger) { type migration struct { newValue interface{} diff --git a/cmd/storagenode/main.go b/cmd/storagenode/main.go index 6df1d2b4e..58c42d020 100644 --- a/cmd/storagenode/main.go +++ b/cmd/storagenode/main.go @@ -27,7 +27,7 @@ import ( "storj.io/storj/storagenode/storagenodedb" ) -// StorageNodeFlags defines storage node configuration +// StorageNodeFlags defines storage node configuration. type StorageNodeFlags struct { EditConf bool `default:"false" help:"open config in default editor"` diff --git a/cmd/storj-admin/main.go b/cmd/storj-admin/main.go index 04833893f..ad3adbf11 100644 --- a/cmd/storj-admin/main.go +++ b/cmd/storj-admin/main.go @@ -39,7 +39,7 @@ var ( setupCfg AdminConf ) -// AdminConf defines necessary configuration to run the storj-admin UI +// AdminConf defines necessary configuration to run the storj-admin UI. type AdminConf struct { AuthKey string `help:"API authorization key" default:""` Address string `help:"address to start the web server on" default:":8080"` diff --git a/cmd/storj-sim/cancelable.go b/cmd/storj-sim/cancelable.go index 1993f40ff..db9df104b 100644 --- a/cmd/storj-sim/cancelable.go +++ b/cmd/storj-sim/cancelable.go @@ -9,7 +9,7 @@ import ( "os/signal" ) -// NewCLIContext creates a context that can be canceled with Ctrl-C +// NewCLIContext creates a context that can be canceled with Ctrl-C. func NewCLIContext(root context.Context) (context.Context, func()) { // trap Ctrl+C and call cancel on the context ctx, cancel := context.WithCancel(root) diff --git a/cmd/storj-sim/main.go b/cmd/storj-sim/main.go index e1f365e49..654c27db2 100644 --- a/cmd/storj-sim/main.go +++ b/cmd/storj-sim/main.go @@ -11,7 +11,7 @@ import ( "storj.io/common/fpath" ) -// Flags contains different flags for commands +// Flags contains different flags for commands. type Flags struct { Directory string Host string diff --git a/cmd/storj-sim/network.go b/cmd/storj-sim/network.go index f668518d7..b990bdd7f 100644 --- a/cmd/storj-sim/network.go +++ b/cmd/storj-sim/network.go @@ -203,7 +203,7 @@ func networkDestroy(flags *Flags, args []string) error { return os.RemoveAll(flags.Directory) } -// newNetwork creates a default network +// newNetwork creates a default network. func newNetwork(flags *Flags) (*Processes, error) { _, filename, _, ok := runtime.Caller(0) if !ok { @@ -667,7 +667,7 @@ func identitySetup(network *Processes) (*Processes, error) { return processes, nil } -// readConfigString reads from dir/config.yaml flagName returns the value in `into` +// readConfigString reads from dir/config.yaml flagName returns the value in `into`. func readConfigString(into *string, dir, flagName string) error { vip := viper.New() vip.AddConfigPath(dir) diff --git a/cmd/storj-sim/prefix.go b/cmd/storj-sim/prefix.go index 401856287..38d5063b5 100644 --- a/cmd/storj-sim/prefix.go +++ b/cmd/storj-sim/prefix.go @@ -69,7 +69,7 @@ func (writer *PrefixWriter) Write(data []byte) (int, error) { return writer.root.Write(data) } -// Write implements io.Writer that prefixes lines +// Write implements io.Writer that prefixes lines. func (writer *prefixWriter) Write(data []byte) (int, error) { if len(data) == 0 { return 0, nil diff --git a/cmd/storj-sim/process.go b/cmd/storj-sim/process.go index f0b5be02a..b21a41532 100644 --- a/cmd/storj-sim/process.go +++ b/cmd/storj-sim/process.go @@ -23,7 +23,7 @@ import ( "storj.io/common/sync2" ) -// Processes contains list of processes +// Processes contains list of processes. type Processes struct { Output *PrefixWriter Directory string @@ -32,7 +32,7 @@ type Processes struct { MaxStartupWait time.Duration } -// NewProcesses returns a group of processes +// NewProcesses returns a group of processes. func NewProcesses(dir string) *Processes { return &Processes{ Output: NewPrefixWriter("sim", os.Stdout), @@ -42,14 +42,14 @@ func NewProcesses(dir string) *Processes { } } -// Exec executes a command on all processes +// Exec executes a command on all processes. func (processes *Processes) Exec(ctx context.Context, command string) error { var group errgroup.Group processes.Start(ctx, &group, command) return group.Wait() } -// Start executes all processes using specified errgroup.Group +// Start executes all processes using specified errgroup.Group. func (processes *Processes) Start(ctx context.Context, group *errgroup.Group, command string) { for _, p := range processes.List { process := p @@ -59,7 +59,7 @@ func (processes *Processes) Start(ctx context.Context, group *errgroup.Group, co } } -// Env returns environment flags for other nodes +// Env returns environment flags for other nodes. func (processes *Processes) Env() []string { var env []string for _, process := range processes.List { @@ -68,7 +68,7 @@ func (processes *Processes) Env() []string { return env } -// Close closes all the processes and their resources +// Close closes all the processes and their resources. func (processes *Processes) Close() error { var errlist errs.Group for _, process := range processes.List { @@ -77,7 +77,7 @@ func (processes *Processes) Close() error { return errlist.Err() } -// Info represents public information about the process +// Info represents public information about the process. type Info struct { Name string Executable string @@ -88,7 +88,7 @@ type Info struct { Extra []EnvVar } -// EnvVar represents an environment variable like Key=Value +// EnvVar represents an environment variable like Key=Value. type EnvVar struct { Key string Value string @@ -99,7 +99,7 @@ func (info *Info) AddExtra(key, value string) { info.Extra = append(info.Extra, EnvVar{Key: key, Value: value}) } -// Env returns process flags +// Env returns process flags. func (info *Info) Env() []string { name := strings.ToUpper(info.Name) @@ -135,10 +135,10 @@ func (info *Info) Env() []string { return env } -// Arguments contains arguments based on the main command +// Arguments contains arguments based on the main command. type Arguments map[string][]string -// Process is a type for monitoring the process +// Process is a type for monitoring the process. type Process struct { processes *Processes @@ -158,7 +158,7 @@ type Process struct { stderr io.Writer } -// New creates a process which can be run in the specified directory +// New creates a process which can be run in the specified directory. func (processes *Processes) New(info Info) *Process { output := processes.Output.Prefixed(info.Name) @@ -187,7 +187,7 @@ func (process *Process) WaitForExited(dependency *Process) { process.Wait = append(process.Wait, &dependency.Status.Exited) } -// Exec runs the process using the arguments for a given command +// Exec runs the process using the arguments for a given command. func (process *Process) Exec(ctx context.Context, command string) (err error) { // ensure that we always release all status fences defer process.Status.Started.Release() @@ -318,7 +318,7 @@ func (process *Process) waitForAddress(maxStartupWait time.Duration) error { return nil } -// tryConnect will try to connect to the process public address +// tryConnect will try to connect to the process public address. func (process *Process) tryConnect() bool { conn, err := net.Dial("tcp", process.Info.Address) if err != nil { @@ -331,5 +331,5 @@ func (process *Process) tryConnect() bool { return true } -// Close closes process resources +// Close closes process resources. func (process *Process) Close() error { return nil } diff --git a/cmd/uplink/cmd/cat.go b/cmd/uplink/cmd/cat.go index 3f4e35487..c4cee4394 100644 --- a/cmd/uplink/cmd/cat.go +++ b/cmd/uplink/cmd/cat.go @@ -20,7 +20,7 @@ func init() { }, RootCmd) } -// catMain is the function executed when catCmd is called +// catMain is the function executed when catCmd is called. func catMain(cmd *cobra.Command, args []string) (err error) { if len(args) == 0 { return fmt.Errorf("no object specified for copy") diff --git a/cmd/uplink/cmd/config.go b/cmd/uplink/cmd/config.go index 8464ff4ef..018cb02d3 100644 --- a/cmd/uplink/cmd/config.go +++ b/cmd/uplink/cmd/config.go @@ -20,7 +20,7 @@ type ClientConfig struct { DialTimeout time.Duration `help:"timeout for dials" default:"0h2m00s"` } -// Config uplink configuration +// Config uplink configuration. type Config struct { AccessConfig Client ClientConfig diff --git a/cmd/uplink/cmd/cp.go b/cmd/uplink/cmd/cp.go index ed16464dd..bea9435c5 100644 --- a/cmd/uplink/cmd/cp.go +++ b/cmd/uplink/cmd/cp.go @@ -42,7 +42,7 @@ func init() { setBasicFlags(cpCmd.Flags(), "progress", "expires", "metadata") } -// upload transfers src from local machine to s3 compatible object dst +// upload transfers src from local machine to s3 compatible object dst. func upload(ctx context.Context, src fpath.FPath, dst fpath.FPath, showProgress bool) (err error) { if !src.IsLocal() { return fmt.Errorf("source must be local path: %s", src) @@ -151,7 +151,7 @@ func upload(ctx context.Context, src fpath.FPath, dst fpath.FPath, showProgress return nil } -// download transfers s3 compatible object src to dst on local machine +// download transfers s3 compatible object src to dst on local machine. func download(ctx context.Context, src fpath.FPath, dst fpath.FPath, showProgress bool) (err error) { if src.IsLocal() { return fmt.Errorf("source must be Storj URL: %s", src) @@ -218,7 +218,7 @@ func download(ctx context.Context, src fpath.FPath, dst fpath.FPath, showProgres return nil } -// copy copies s3 compatible object src to s3 compatible object dst +// copy copies s3 compatible object src to s3 compatible object dst. func copyObject(ctx context.Context, src fpath.FPath, dst fpath.FPath) (err error) { if src.IsLocal() { return fmt.Errorf("source must be Storj URL: %s", src) diff --git a/cmd/uplink/cmd/import.go b/cmd/uplink/cmd/import.go index 1452f8d65..5d1b93e32 100644 --- a/cmd/uplink/cmd/import.go +++ b/cmd/uplink/cmd/import.go @@ -48,7 +48,7 @@ func init() { cfgstruct.SetBoolAnnotation(importCmd.Flags(), "access", cfgstruct.BasicHelpAnnotationName, false) } -// importMain is the function executed when importCmd is called +// importMain is the function executed when importCmd is called. func importMain(cmd *cobra.Command, args []string) (err error) { if cmd.Flag("access").Changed { return ErrAccessFlag diff --git a/cmd/uplink/cmd/put.go b/cmd/uplink/cmd/put.go index d14efb241..dcaa71df9 100644 --- a/cmd/uplink/cmd/put.go +++ b/cmd/uplink/cmd/put.go @@ -20,7 +20,7 @@ func init() { }, RootCmd) } -// putMain is the function executed when putCmd is called +// putMain is the function executed when putCmd is called. func putMain(cmd *cobra.Command, args []string) (err error) { if len(args) == 0 { return fmt.Errorf("no object specified for copy") diff --git a/cmd/uplink/cmd/root.go b/cmd/uplink/cmd/root.go index b3995ad82..9a6b4b50a 100644 --- a/cmd/uplink/cmd/root.go +++ b/cmd/uplink/cmd/root.go @@ -31,7 +31,7 @@ import ( const advancedFlagName = "advanced" -// UplinkFlags configuration flags +// UplinkFlags configuration flags. type UplinkFlags struct { Config @@ -66,7 +66,7 @@ func init() { var cpuProfile = flag.String("profile.cpu", "", "file path of the cpu profile to be created") var memoryProfile = flag.String("profile.mem", "", "file path of the memory profile to be created") -// RootCmd represents the base CLI command when called without any subcommands +// RootCmd represents the base CLI command when called without any subcommands. var RootCmd = &cobra.Command{ Use: "uplink", Short: "The Storj client-side CLI", diff --git a/cmd/uplink/cmd/share.go b/cmd/uplink/cmd/share.go index 667014bd5..11e057d08 100644 --- a/cmd/uplink/cmd/share.go +++ b/cmd/uplink/cmd/share.go @@ -71,7 +71,7 @@ func parseHumanDate(date string, now time.Time) (time.Time, error) { } } -// shareMain is the function executed when shareCmd is called +// shareMain is the function executed when shareCmd is called. func shareMain(cmd *cobra.Command, args []string) (err error) { now := time.Now() notBefore, err := parseHumanDate(shareCfg.NotBefore, now) diff --git a/examples/eestream/serve-collected/main.go b/examples/eestream/serve-collected/main.go index fd021cc8e..45d6e9dcb 100644 --- a/examples/eestream/serve-collected/main.go +++ b/examples/eestream/serve-collected/main.go @@ -38,7 +38,7 @@ func main() { } } -// Main is the exported CLI executable function +// Main is the exported CLI executable function. func Main() error { ctx := context.Background() encKey := storj.Key(sha256.Sum256([]byte(*key))) diff --git a/examples/eestream/serve-pieces/main.go b/examples/eestream/serve-pieces/main.go index 55f9b62b1..8ec51180b 100644 --- a/examples/eestream/serve-pieces/main.go +++ b/examples/eestream/serve-pieces/main.go @@ -27,7 +27,7 @@ func main() { } } -// Main is the exported CLI executable function +// Main is the exported CLI executable function. func Main() error { pieces, err := ioutil.ReadDir(flag.Arg(0)) if err != nil { diff --git a/examples/eestream/serve/main.go b/examples/eestream/serve/main.go index 6ef81b90d..61e4d1831 100644 --- a/examples/eestream/serve/main.go +++ b/examples/eestream/serve/main.go @@ -47,7 +47,7 @@ func main() { } } -// Main is the exported CLI executable function +// Main is the exported CLI executable function. func Main() error { encKey := storj.Key(sha256.Sum256([]byte(*key))) fc, err := infectious.NewFEC(*rsk, *rsn) diff --git a/examples/eestream/store/main.go b/examples/eestream/store/main.go index aa8328ca7..a7cfc049e 100644 --- a/examples/eestream/store/main.go +++ b/examples/eestream/store/main.go @@ -40,7 +40,7 @@ func main() { } } -// Main is the exported CLI executable function +// Main is the exported CLI executable function. func Main() error { err := os.MkdirAll(flag.Arg(0), 0755) if err != nil { diff --git a/pkg/auth/apikey.go b/pkg/auth/apikey.go index edba6e44b..4edf845df 100644 --- a/pkg/auth/apikey.go +++ b/pkg/auth/apikey.go @@ -11,12 +11,12 @@ import ( // other packages. type apikey struct{} -// WithAPIKey creates context with api key +// WithAPIKey creates context with api key. func WithAPIKey(ctx context.Context, key []byte) context.Context { return context.WithValue(ctx, apikey{}, key) } -// GetAPIKey returns api key from context is exists +// GetAPIKey returns api key from context is exists. func GetAPIKey(ctx context.Context) ([]byte, bool) { key, ok := ctx.Value(apikey{}).([]byte) return key, ok diff --git a/pkg/revocation/common.go b/pkg/revocation/common.go index a1525fae7..145b5ec58 100644 --- a/pkg/revocation/common.go +++ b/pkg/revocation/common.go @@ -21,7 +21,7 @@ func NewDBFromCfg(cfg tlsopts.Config) (*DB, error) { return NewDB(cfg.RevocationDBURL) } -// NewDB returns a new revocation database given the URL +// NewDB returns a new revocation database given the URL. func NewDB(dbURL string) (*DB, error) { driver, source, _, err := dbutil.SplitConnStr(dbURL) if err != nil { @@ -45,7 +45,7 @@ func NewDB(dbURL string) (*DB, error) { return db, nil } -// newDBBolt creates a bolt-backed DB +// newDBBolt creates a bolt-backed DB. func newDBBolt(path string) (*DB, error) { client, err := boltdb.New(path, extensions.RevocationBucket) if err != nil { diff --git a/pkg/revocation/db.go b/pkg/revocation/db.go index 57ccf0270..5d1720791 100644 --- a/pkg/revocation/db.go +++ b/pkg/revocation/db.go @@ -100,7 +100,7 @@ func (db *DB) Put(ctx context.Context, chain []*x509.Certificate, revExt pkix.Ex return nil } -// List lists all revocations in the store +// List lists all revocations in the store. func (db *DB) List(ctx context.Context) (revs []*extensions.Revocation, err error) { defer mon.Task()(&ctx)(&err) @@ -134,7 +134,7 @@ func (db *DB) TestGetStore() storage.KeyValueStore { return db.store } -// Close closes the underlying store +// Close closes the underlying store. func (db *DB) Close() error { if db.store == nil { return nil diff --git a/pkg/server/server.go b/pkg/server/server.go index 2efed3a46..151f1b739 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -23,7 +23,7 @@ import ( "storj.io/storj/pkg/listenmux" ) -// Config holds server specific configuration parameters +// Config holds server specific configuration parameters. type Config struct { tlsopts.Config Address string `user:"true" help:"public address to listen on" default:":7777"` @@ -99,22 +99,22 @@ func New(log *zap.Logger, tlsOptions *tlsopts.Options, publicAddr, privateAddr s return server, nil } -// Identity returns the server's identity +// Identity returns the server's identity. func (p *Server) Identity() *identity.FullIdentity { return p.tlsOptions.Ident } -// Addr returns the server's public listener address +// Addr returns the server's public listener address. func (p *Server) Addr() net.Addr { return p.public.listener.Addr() } -// PrivateAddr returns the server's private listener address +// PrivateAddr returns the server's private listener address. func (p *Server) PrivateAddr() net.Addr { return p.private.listener.Addr() } -// DRPC returns the server's dRPC mux for registration purposes +// DRPC returns the server's dRPC mux for registration purposes. func (p *Server) DRPC() *drpcmux.Mux { return p.public.mux } -// PrivateDRPC returns the server's dRPC mux for registration purposes +// PrivateDRPC returns the server's dRPC mux for registration purposes. func (p *Server) PrivateDRPC() *drpcmux.Mux { return p.private.mux } -// Close shuts down the server +// Close shuts down the server. func (p *Server) Close() error { p.mu.Lock() defer p.mu.Unlock() @@ -132,7 +132,7 @@ func (p *Server) Close() error { return nil } -// Run will run the server and all of its services +// Run will run the server and all of its services. func (p *Server) Run(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) diff --git a/private/cui/screen.go b/private/cui/screen.go index cf44e617b..ec2417ebf 100644 --- a/private/cui/screen.go +++ b/private/cui/screen.go @@ -22,10 +22,10 @@ const padding = 2 // Y is the row type Point struct{ X, Y int } -// Rect is a 2D rectangle in console, excluding Max edge +// Rect is a 2D rectangle in console, excluding Max edge. type Rect struct{ Min, Max Point } -// Screen is a writable area on screen +// Screen is a writable area on screen. type Screen struct { rendering sync.Mutex @@ -81,7 +81,7 @@ func (screen *Screen) Close() error { return nil } -// Run runs the event loop +// Run runs the event loop. func (screen *Screen) Run() error { defer screen.markClosed() @@ -124,10 +124,10 @@ func (screen *Screen) Size() (width, height int) { return width, height } -// Lock screen for exclusive rendering +// Lock screen for exclusive rendering. func (screen *Screen) Lock() { screen.rendering.Lock() } -// Unlock screen +// Unlock screen. func (screen *Screen) Unlock() { screen.rendering.Unlock() } // Write writes to the screen. @@ -152,7 +152,7 @@ func (screen *Screen) Flush() error { return err } -// blit writes content to the console +// blit writes content to the console. func (screen *Screen) blit(frame *frame) error { screen.flushed.content = frame.content size := screen.flushed.size @@ -191,7 +191,7 @@ var lightStyle = rectStyle{ {'└', '─', '┘'}, } -// drawRect draws a rectangle using termbox +// drawRect draws a rectangle using termbox. func drawRect(r Rect, style rectStyle) { attr := termbox.ColorDefault diff --git a/private/date/utils.go b/private/date/utils.go index 5221c16b5..f00607341 100644 --- a/private/date/utils.go +++ b/private/date/utils.go @@ -6,14 +6,14 @@ package date import "time" -// MonthBoundary extract month from the provided date and returns its edges +// MonthBoundary extract month from the provided date and returns its edges. func MonthBoundary(t time.Time) (time.Time, time.Time) { startDate := time.Date(t.Year(), t.Month(), 1, 0, 0, 0, 0, t.Location()) endDate := time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, -1, t.Location()) return startDate, endDate } -// DayBoundary returns start and end of the provided day +// DayBoundary returns start and end of the provided day. func DayBoundary(t time.Time) (time.Time, time.Time) { return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, t.Location()), time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, -1, t.Location()) @@ -36,7 +36,7 @@ func MonthsCountSince(from time.Time) int { return MonthsBetweenDates(from, time.Now()) } -// MonthsBetweenDates calculates amount of months between two dates +// MonthsBetweenDates calculates amount of months between two dates. func MonthsBetweenDates(from time.Time, to time.Time) int { // we need UTC here before its the only sensible way to say what day it is y1, M1, _ := from.UTC().Date() @@ -47,7 +47,7 @@ func MonthsBetweenDates(from time.Time, to time.Time) int { return months } -// TruncateToHourInNano returns the time truncated to the hour in nanoseconds +// TruncateToHourInNano returns the time truncated to the hour in nanoseconds. func TruncateToHourInNano(t time.Time) int64 { return t.Truncate(1 * time.Hour).UnixNano() } diff --git a/private/dbutil/dbimplementation.go b/private/dbutil/dbimplementation.go index 810f5c175..dd2764d82 100644 --- a/private/dbutil/dbimplementation.go +++ b/private/dbutil/dbimplementation.go @@ -3,7 +3,7 @@ package dbutil -// Implementation type of valid DBs +// Implementation type of valid DBs. type Implementation int const ( diff --git a/private/dbutil/dbschema/data.go b/private/dbutil/dbschema/data.go index 885bd59d0..0071845aa 100644 --- a/private/dbutil/dbschema/data.go +++ b/private/dbutil/dbschema/data.go @@ -13,12 +13,12 @@ import ( "github.com/zeebo/errs" ) -// Data is the database content formatted as strings +// Data is the database content formatted as strings. type Data struct { Tables []*TableData } -// TableData is content of a sql table +// TableData is content of a sql table. type TableData struct { Name string Columns []string @@ -36,7 +36,7 @@ func (c ColumnData) String() string { return fmt.Sprintf("%s:%s", c.Column, c.Value) } -// RowData is content of a single row +// RowData is content of a single row. type RowData []ColumnData // Less returns true if one row is less than the other. @@ -74,7 +74,7 @@ func (table *TableData) AddRow(row RowData) error { return nil } -// FindTable finds a table by name +// FindTable finds a table by name. func (data *Data) FindTable(tableName string) (*TableData, bool) { for _, table := range data.Tables { if table.Name == tableName { @@ -103,7 +103,7 @@ func (row RowData) Clone() RowData { return append(RowData{}, row...) } -// QueryData loads all data from tables +// QueryData loads all data from tables. func QueryData(ctx context.Context, db Queryer, schema *Schema, quoteColumn func(string) string) (*Data, error) { data := &Data{} diff --git a/private/dbutil/dbschema/snapshot.go b/private/dbutil/dbschema/snapshot.go index 85ae5d89d..d99e3c87c 100644 --- a/private/dbutil/dbschema/snapshot.go +++ b/private/dbutil/dbschema/snapshot.go @@ -9,7 +9,7 @@ import ( "strings" ) -// Snapshots defines a collection of snapshot +// Snapshots defines a collection of snapshot. type Snapshots struct { List []*Snapshot } @@ -37,7 +37,7 @@ func (snapshots *Snapshots) FindVersion(version int) (*Snapshot, bool) { return nil, false } -// Sort sorts the snapshots by version +// Sort sorts the snapshots by version. func (snapshots *Snapshots) Sort() { sort.Slice(snapshots.List, func(i, k int) bool { return snapshots.List[i].Version < snapshots.List[k].Version diff --git a/private/dbutil/defaults.go b/private/dbutil/defaults.go index 7d37fa99c..27ff6d941 100644 --- a/private/dbutil/defaults.go +++ b/private/dbutil/defaults.go @@ -25,7 +25,7 @@ type ConfigurableDB interface { Stats() sql.DBStats } -// Configure Sets Connection Boundaries and adds db_stats monitoring to monkit +// Configure Sets Connection Boundaries and adds db_stats monitoring to monkit. func Configure(db ConfigurableDB, dbName string, mon *monkit.Scope) { if *maxIdleConns >= 0 { db.SetMaxIdleConns(*maxIdleConns) diff --git a/private/dbutil/pgtest/flag.go b/private/dbutil/pgtest/flag.go index 51f82174c..0acf9a8d3 100644 --- a/private/dbutil/pgtest/flag.go +++ b/private/dbutil/pgtest/flag.go @@ -28,13 +28,13 @@ func getenv(priority ...string) string { // postgres is the test database connection string. var postgres = flag.String("postgres-test-db", getenv("STORJ_TEST_POSTGRES", "STORJ_POSTGRES_TEST"), "PostgreSQL test database connection string (semicolon delimited for multiple), \"omit\" is used to omit the tests from output") -// cockroach is the test database connection string for CockroachDB +// cockroach is the test database connection string for CockroachDB. var cockroach = flag.String("cockroach-test-db", getenv("STORJ_TEST_COCKROACH", "STORJ_COCKROACH_TEST"), "CockroachDB test database connection string (semicolon delimited for multiple), \"omit\" is used to omit the tests from output") -// DefaultPostgres is expected to work under the storj-test docker-compose instance +// DefaultPostgres is expected to work under the storj-test docker-compose instance. const DefaultPostgres = "postgres://storj:storj-pass@test-postgres/teststorj?sslmode=disable" -// DefaultCockroach is expected to work when a local cockroachDB instance is running +// DefaultCockroach is expected to work when a local cockroachDB instance is running. const DefaultCockroach = "cockroach://root@localhost:26257/master?sslmode=disable" // Database defines a postgres compatible database. diff --git a/private/dbutil/pgutil/data.go b/private/dbutil/pgutil/data.go index 5b08b2118..0a22eae50 100644 --- a/private/dbutil/pgutil/data.go +++ b/private/dbutil/pgutil/data.go @@ -10,7 +10,7 @@ import ( "storj.io/storj/private/dbutil/dbschema" ) -// QueryData loads all data from tables +// QueryData loads all data from tables. func QueryData(ctx context.Context, db dbschema.Queryer, schema *dbschema.Schema) (*dbschema.Data, error) { return dbschema.QueryData(ctx, db, schema, func(columnName string) string { quoted := strconv.Quote(columnName) diff --git a/private/dbutil/pgutil/db.go b/private/dbutil/pgutil/db.go index e70af5d6a..499ca1738 100644 --- a/private/dbutil/pgutil/db.go +++ b/private/dbutil/pgutil/db.go @@ -72,7 +72,7 @@ func OpenUnique(ctx context.Context, connstr string, schemaPrefix string) (*dbut }, nil } -// QuerySnapshot loads snapshot from database +// QuerySnapshot loads snapshot from database. func QuerySnapshot(ctx context.Context, db dbschema.Queryer) (*dbschema.Snapshot, error) { schema, err := QuerySchema(ctx, db) if err != nil { @@ -91,7 +91,7 @@ func QuerySnapshot(ctx context.Context, db dbschema.Queryer) (*dbschema.Snapshot }, err } -// CheckApplicationName ensures that the Connection String contains an application name +// CheckApplicationName ensures that the Connection String contains an application name. func CheckApplicationName(s string) (r string) { if !strings.Contains(s, "application_name") { if !strings.Contains(s, "?") { @@ -105,7 +105,7 @@ func CheckApplicationName(s string) (r string) { return s } -// IsConstraintError checks if given error is about constraint violation +// IsConstraintError checks if given error is about constraint violation. func IsConstraintError(err error) bool { errCode := ErrorCode(err) return strings.HasPrefix(errCode, pgErrorClassConstraintViolation) diff --git a/private/dbutil/pgutil/query.go b/private/dbutil/pgutil/query.go index 4ceacd003..d9cef96cd 100644 --- a/private/dbutil/pgutil/query.go +++ b/private/dbutil/pgutil/query.go @@ -184,7 +184,7 @@ func QuerySchema(ctx context.Context, db dbschema.Queryer) (*dbschema.Schema, er return schema, nil } -// matches FOREIGN KEY (project_id) REFERENCES projects(id) ON UPDATE CASCADE ON DELETE CASCADE +// matches FOREIGN KEY (project_id) REFERENCES projects(id) ON UPDATE CASCADE ON DELETE CASCADE. var rxPostgresForeignKey = regexp.MustCompile( `^FOREIGN KEY \([[:word:]]+\) ` + `REFERENCES ([[:word:]]+)\(([[:word:]]+)\)` + diff --git a/private/dbutil/pgutil/schema.go b/private/dbutil/pgutil/schema.go index f6eb191f4..77bdb74af 100644 --- a/private/dbutil/pgutil/schema.go +++ b/private/dbutil/pgutil/schema.go @@ -23,7 +23,7 @@ func CreateRandomTestingSchemaName(n int) string { return hex.EncodeToString(data) } -// ConnstrWithSchema adds schema to a connection string +// ConnstrWithSchema adds schema to a connection string. func ConnstrWithSchema(connstr, schema string) string { if strings.Contains(connstr, "?") { connstr += "&options=" @@ -34,7 +34,7 @@ func ConnstrWithSchema(connstr, schema string) string { } // ParseSchemaFromConnstr returns the name of the schema parsed from the -// connection string if one is provided +// connection string if one is provided. func ParseSchemaFromConnstr(connstr string) (string, error) { url, err := url.Parse(connstr) if err != nil { @@ -56,12 +56,12 @@ func ParseSchemaFromConnstr(connstr string) (string, error) { return "", nil } -// QuoteSchema quotes schema name for +// QuoteSchema quotes schema name for. func QuoteSchema(schema string) string { return QuoteIdentifier(schema) } -// Execer is for executing sql +// Execer is for executing sql. type Execer interface { ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error) } @@ -84,7 +84,7 @@ func CreateSchema(ctx context.Context, db Execer, schema string) (err error) { return err } -// DropSchema drops the named schema +// DropSchema drops the named schema. func DropSchema(ctx context.Context, db Execer, schema string) error { _, err := db.ExecContext(ctx, `DROP SCHEMA `+QuoteSchema(schema)+` CASCADE;`) return err diff --git a/private/dbutil/sqliteutil/db.go b/private/dbutil/sqliteutil/db.go index 3776ac89d..667d3ac70 100644 --- a/private/dbutil/sqliteutil/db.go +++ b/private/dbutil/sqliteutil/db.go @@ -53,7 +53,7 @@ func LoadSnapshotFromSQL(ctx context.Context, script string) (_ *dbschema.Snapsh return snapshot, nil } -// QuerySnapshot loads snapshot from database +// QuerySnapshot loads snapshot from database. func QuerySnapshot(ctx context.Context, db dbschema.Queryer) (*dbschema.Snapshot, error) { schema, err := QuerySchema(ctx, db) if err != nil { @@ -72,7 +72,7 @@ func QuerySnapshot(ctx context.Context, db dbschema.Queryer) (*dbschema.Snapshot }, err } -// QueryData loads all data from tables +// QueryData loads all data from tables. func QueryData(ctx context.Context, db dbschema.Queryer, schema *dbschema.Schema) (*dbschema.Data, error) { return dbschema.QueryData(ctx, db, schema, func(columnName string) string { quoted := strconv.Quote(columnName) @@ -80,7 +80,7 @@ func QueryData(ctx context.Context, db dbschema.Queryer, schema *dbschema.Schema }) } -// IsConstraintError checks if given error is about constraint violation +// IsConstraintError checks if given error is about constraint violation. func IsConstraintError(err error) bool { return errs.IsFunc(err, func(err error) bool { if e, ok := err.(sqlite3.Error); ok { diff --git a/private/dbutil/sqliteutil/migrator.go b/private/dbutil/sqliteutil/migrator.go index ca9aab181..777156f51 100644 --- a/private/dbutil/sqliteutil/migrator.go +++ b/private/dbutil/sqliteutil/migrator.go @@ -172,7 +172,7 @@ func KeepTables(ctx context.Context, db tagsql.DB, tablesToKeep ...string) (err return err } -// dropTables performs the table drops in a single transaction +// dropTables performs the table drops in a single transaction. func dropTables(ctx context.Context, db tagsql.DB, tablesToKeep ...string) (err error) { err = txutil.WithTx(ctx, db, nil, func(ctx context.Context, tx tagsql.Tx) error { // Get a list of tables excluding sqlite3 system tables. diff --git a/private/dbutil/utccheck/db_test.go b/private/dbutil/utccheck/db_test.go index 6f24b73f9..5f1ee7706 100644 --- a/private/dbutil/utccheck/db_test.go +++ b/private/dbutil/utccheck/db_test.go @@ -91,5 +91,5 @@ func (emptyStmt) Close() error { return nil } func (emptyStmt) Exec(args []driver.Value) (driver.Result, error) { return nil, nil } func (emptyStmt) Query(args []driver.Value) (driver.Rows, error) { return nil, nil } -// must be 1 so that we can pass 1 argument +// must be 1 so that we can pass 1 argument. func (emptyStmt) NumInput() int { return 1 } diff --git a/private/debugging/certificates.go b/private/debugging/certificates.go index cfeabf60d..5766c727a 100644 --- a/private/debugging/certificates.go +++ b/private/debugging/certificates.go @@ -18,12 +18,12 @@ var ( diffOpts = jsondiff.DefaultConsoleOptions() ) -// DebugCert is a subset of the most relevant fields from an x509.Certificate for debugging +// DebugCert is a subset of the most relevant fields from an x509.Certificate for debugging. type DebugCert struct { Cert *x509.Certificate } -// NewDebugCert converts an *x509.Certificate into a DebugCert +// NewDebugCert converts an *x509.Certificate into a DebugCert. func NewDebugCert(cert x509.Certificate) DebugCert { return DebugCert{ Cert: &cert, @@ -31,7 +31,7 @@ func NewDebugCert(cert x509.Certificate) DebugCert { } // PrintJSON uses a json marshaler to pretty-print arbitrary data for debugging -// with special considerations for certain, specific types +// with special considerations for certain, specific types. func PrintJSON(data interface{}, label string) { var ( jsonBytes []byte @@ -89,7 +89,7 @@ func PrintJSON(data interface{}, label string) { fmt.Println("") } -// Cmp is used to compare 2 DebugCerts against each other and print the diff +// Cmp is used to compare 2 DebugCerts against each other and print the diff. func (c DebugCert) Cmp(c2 DebugCert, label string) error { fmt.Println("diff " + label + " ---================================================================---") cJSON, err := c.JSON() @@ -107,7 +107,7 @@ func (c DebugCert) Cmp(c2 DebugCert, label string) error { return nil } -// JSON serializes the certificate to JSON +// JSON serializes the certificate to JSON. func (c DebugCert) JSON() ([]byte, error) { return json.Marshal(c.Cert) } diff --git a/private/migrate/create.go b/private/migrate/create.go index fe7ce5918..d7b473a81 100644 --- a/private/migrate/create.go +++ b/private/migrate/create.go @@ -14,10 +14,10 @@ import ( "storj.io/storj/private/tagsql" ) -// Error is the default migrate errs class +// Error is the default migrate errs class. var Error = errs.Class("migrate") -// Create with a previous schema check +// Create with a previous schema check. func Create(ctx context.Context, identifier string, db DBX) error { // is this necessary? it's not immediately obvious why we roll back the transaction // when the schemas match. diff --git a/private/migrate/versions.go b/private/migrate/versions.go index 7ab98af13..fc519e90e 100644 --- a/private/migrate/versions.go +++ b/private/migrate/versions.go @@ -53,7 +53,7 @@ Scenarios it doesn't handle properly. 4. Figuring out what the exact executed steps are. */ -// Migration describes a migration steps +// Migration describes a migration steps. type Migration struct { // Table is the table name to register the applied migration version. // NOTE: Always validates its value with the ValidTableName method before it's @@ -74,12 +74,12 @@ type Step struct { SeparateTx bool } -// Action is something that needs to be done +// Action is something that needs to be done. type Action interface { Run(ctx context.Context, log *zap.Logger, db tagsql.DB, tx tagsql.Tx) error } -// TargetVersion returns migration with steps upto specified version +// TargetVersion returns migration with steps upto specified version. func (migration *Migration) TargetVersion(version int) *Migration { m := *migration m.Steps = nil @@ -105,7 +105,7 @@ func (migration *Migration) ValidTableName() error { return nil } -// ValidateSteps checks that the version for each migration step increments in order +// ValidateSteps checks that the version for each migration step increments in order. func (migration *Migration) ValidateSteps() error { sorted := sort.SliceIsSorted(migration.Steps, func(i, j int) bool { return migration.Steps[i].Version <= migration.Steps[j].Version @@ -116,7 +116,7 @@ func (migration *Migration) ValidateSteps() error { return nil } -// ValidateVersions checks that the version of the migration matches the state of the database +// ValidateVersions checks that the version of the migration matches the state of the database. func (migration *Migration) ValidateVersions(ctx context.Context, log *zap.Logger) error { for _, step := range migration.Steps { dbVersion, err := migration.getLatestVersion(ctx, log, step.DB) @@ -139,7 +139,7 @@ func (migration *Migration) ValidateVersions(ctx context.Context, log *zap.Logge return nil } -// Run runs the migration steps +// Run runs the migration steps. func (migration *Migration) Run(ctx context.Context, log *zap.Logger) error { err := migration.ValidateSteps() if err != nil { @@ -238,7 +238,7 @@ func (migration *Migration) getLatestVersion(ctx context.Context, log *zap.Logge return int(version.Int64), Error.Wrap(err) } -// addVersion adds information about a new migration +// addVersion adds information about a new migration. func (migration *Migration) addVersion(ctx context.Context, tx tagsql.Tx, db tagsql.DB, version int) error { err := migration.ValidTableName() if err != nil { @@ -254,7 +254,7 @@ func (migration *Migration) addVersion(ctx context.Context, tx tagsql.Tx, db tag return err } -// CurrentVersion finds the latest version for the db +// CurrentVersion finds the latest version for the db. func (migration *Migration) CurrentVersion(ctx context.Context, log *zap.Logger, db tagsql.DB) (int, error) { err := migration.ensureVersionTable(ctx, log, db) if err != nil { @@ -263,10 +263,10 @@ func (migration *Migration) CurrentVersion(ctx context.Context, log *zap.Logger, return migration.getLatestVersion(ctx, log, db) } -// SQL statements that are executed on the database +// SQL statements that are executed on the database. type SQL []string -// Run runs the SQL statements +// Run runs the SQL statements. func (sql SQL) Run(ctx context.Context, log *zap.Logger, db tagsql.DB, tx tagsql.Tx) (err error) { for _, query := range sql { _, err := tx.Exec(ctx, rebind(db, query)) @@ -277,10 +277,10 @@ func (sql SQL) Run(ctx context.Context, log *zap.Logger, db tagsql.DB, tx tagsql return nil } -// Func is an arbitrary operation +// Func is an arbitrary operation. type Func func(ctx context.Context, log *zap.Logger, db tagsql.DB, tx tagsql.Tx) error -// Run runs the migration +// Run runs the migration. func (fn Func) Run(ctx context.Context, log *zap.Logger, db tagsql.DB, tx tagsql.Tx) error { return fn(ctx, log, db, tx) } diff --git a/private/post/login.go b/private/post/login.go index 4fd541412..8d998a8bb 100644 --- a/private/post/login.go +++ b/private/post/login.go @@ -9,13 +9,13 @@ import ( "github.com/zeebo/errs" ) -// LoginAuth implements LOGIN authentication mechanism +// LoginAuth implements LOGIN authentication mechanism. type LoginAuth struct { Username string Password string } -// Start begins an authentication with a server +// Start begins an authentication with a server. func (auth LoginAuth) Start(server *smtp.ServerInfo) (proto string, toServer []byte, err error) { if !server.TLS { return "", nil, errs.New("unencrypted connection") @@ -24,7 +24,7 @@ func (auth LoginAuth) Start(server *smtp.ServerInfo) (proto string, toServer []b } // Next continues the authentication with server response and flag representing -// if server expects more data from client +// if server expects more data from client. func (auth LoginAuth) Next(fromServer []byte, more bool) (toServer []byte, err error) { if more { switch string(fromServer) { diff --git a/private/post/message.go b/private/post/message.go index 0093163d9..c425b7657 100644 --- a/private/post/message.go +++ b/private/post/message.go @@ -16,7 +16,7 @@ import ( "github.com/zeebo/errs" ) -// Message is RFC compliant email message +// Message is RFC compliant email message. type Message struct { From Address To []Address @@ -29,7 +29,7 @@ type Message struct { Parts []Part } -// Part represent one part of multipart message +// Part represent one part of multipart message. type Part struct { Type string Encoding string @@ -37,10 +37,10 @@ type Part struct { Content string } -// Error is the default message errs class +// Error is the default message errs class. var Error = errs.Class("Email message error") -// Bytes builds message and returns result as bytes +// Bytes builds message and returns result as bytes. func (msg *Message) Bytes() (data []byte, err error) { // always returns nil error on read and write, so most of the errors can be ignored var body bytes.Buffer diff --git a/private/post/oauth2/auth.go b/private/post/oauth2/auth.go index de0eeb723..124311be2 100644 --- a/private/post/oauth2/auth.go +++ b/private/post/oauth2/auth.go @@ -22,14 +22,14 @@ var ( mon = monkit.Package() ) -// Auth is XOAUTH2 implementation of smtp.Auth interface +// Auth is XOAUTH2 implementation of smtp.Auth interface. type Auth struct { UserEmail string Storage *TokenStore } -// Start returns proto and auth credentials for first auth msg +// Start returns proto and auth credentials for first auth msg. func (auth *Auth) Start(server *smtp.ServerInfo) (proto string, toServer []byte, err error) { ctx := context.TODO() defer mon.Task()(&ctx)(&err) @@ -46,7 +46,7 @@ func (auth *Auth) Start(server *smtp.ServerInfo) (proto string, toServer []byte, return "XOAUTH2", []byte(format), nil } -// Next sends empty response to solve SASL challenge if response code is 334 +// Next sends empty response to solve SASL challenge if response code is 334. func (auth *Auth) Next(fromServer []byte, more bool) (toServer []byte, err error) { if more { return make([]byte, 0), nil @@ -55,7 +55,7 @@ func (auth *Auth) Next(fromServer []byte, more bool) (toServer []byte, err error return nil, nil } -// Token represents OAuth2 token +// Token represents OAuth2 token. type Token struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` @@ -63,21 +63,21 @@ type Token struct { Expiry time.Time `json:"expiry"` } -// Credentials represents OAuth2 credentials +// Credentials represents OAuth2 credentials. type Credentials struct { ClientID string `json:"client_id"` ClientSecret string `json:"client_secret"` TokenURI string `json:"token_uri"` } -// TokenStore is a thread safe storage for OAuth2 token and credentials +// TokenStore is a thread safe storage for OAuth2 token and credentials. type TokenStore struct { mu sync.Mutex token Token creds Credentials } -// NewTokenStore creates new instance of token storage +// NewTokenStore creates new instance of token storage. func NewTokenStore(creds Credentials, token Token) *TokenStore { return &TokenStore{ token: token, @@ -85,7 +85,7 @@ func NewTokenStore(creds Credentials, token Token) *TokenStore { } } -// Token retrieves token in a thread safe way and refreshes it if needed +// Token retrieves token in a thread safe way and refreshes it if needed. func (s *TokenStore) Token(ctx context.Context) (_ *Token, err error) { defer mon.Task()(&ctx)(&err) s.mu.Lock() @@ -105,7 +105,7 @@ func (s *TokenStore) Token(ctx context.Context) (_ *Token, err error) { return token, nil } -// RefreshToken is a helper method that refreshes token with given credentials and OUATH2 refresh token +// RefreshToken is a helper method that refreshes token with given credentials and OUATH2 refresh token. func RefreshToken(ctx context.Context, creds Credentials, refreshToken string) (_ *Token, err error) { defer mon.Task()(&ctx)(&err) diff --git a/private/post/sender.go b/private/post/sender.go index 6b88229fa..c569b72e5 100644 --- a/private/post/sender.go +++ b/private/post/sender.go @@ -15,12 +15,12 @@ import ( "github.com/zeebo/errs" ) -// Address is alias of net/mail.Address +// Address is alias of net/mail.Address. type Address = mail.Address var mon = monkit.Package() -// SMTPSender is smtp sender +// SMTPSender is smtp sender. type SMTPSender struct { ServerAddress string @@ -28,12 +28,12 @@ type SMTPSender struct { Auth smtp.Auth } -// FromAddress implements satellite/mail.SMTPSender +// FromAddress implements satellite/mail.SMTPSender. func (sender *SMTPSender) FromAddress() Address { return sender.From } -// SendEmail sends email message to the given recipient +// SendEmail sends email message to the given recipient. func (sender *SMTPSender) SendEmail(ctx context.Context, msg *Message) (err error) { defer mon.Task()(&ctx)(&err) @@ -49,7 +49,7 @@ func (sender *SMTPSender) SendEmail(ctx context.Context, msg *Message) (err erro return nil } -// communicate sends mail via SMTP using provided client and message +// communicate sends mail via SMTP using provided client and message. func (sender *SMTPSender) communicate(ctx context.Context, client *smtp.Client, msg *Message) error { // suppress error because address should be validated // before creating SMTPSender @@ -98,7 +98,7 @@ func (sender *SMTPSender) communicate(ctx context.Context, client *smtp.Client, return client.Quit() } -// writeData ensures that writer will be closed after data is written +// writeData ensures that writer will be closed after data is written. func writeData(writer io.WriteCloser, data []byte) (err error) { defer func() { err = errs.Combine(err, writer.Close()) diff --git a/private/testblobs/bad.go b/private/testblobs/bad.go index 09a10dab7..de3cec28e 100644 --- a/private/testblobs/bad.go +++ b/private/testblobs/bad.go @@ -106,7 +106,7 @@ func (bad *BadBlobs) RestoreTrash(ctx context.Context, namespace []byte) ([][]by return bad.blobs.RestoreTrash(ctx, namespace) } -// EmptyTrash empties the trash +// EmptyTrash empties the trash. func (bad *BadBlobs) EmptyTrash(ctx context.Context, namespace []byte, trashedBefore time.Time) (int64, [][]byte, error) { if bad.err != nil { return 0, nil, bad.err diff --git a/private/testblobs/slow.go b/private/testblobs/slow.go index 96a7d75e9..d440ad9fe 100644 --- a/private/testblobs/slow.go +++ b/private/testblobs/slow.go @@ -89,13 +89,13 @@ func (slow *SlowBlobs) Trash(ctx context.Context, ref storage.BlobRef) error { return slow.blobs.Trash(ctx, ref) } -// RestoreTrash restores all files in the trash +// RestoreTrash restores all files in the trash. func (slow *SlowBlobs) RestoreTrash(ctx context.Context, namespace []byte) ([][]byte, error) { slow.sleep() return slow.blobs.RestoreTrash(ctx, namespace) } -// EmptyTrash empties the trash +// EmptyTrash empties the trash. func (slow *SlowBlobs) EmptyTrash(ctx context.Context, namespace []byte, trashedBefore time.Time) (int64, [][]byte, error) { slow.sleep() return slow.blobs.EmptyTrash(ctx, namespace, trashedBefore) @@ -107,7 +107,7 @@ func (slow *SlowBlobs) Delete(ctx context.Context, ref storage.BlobRef) error { return slow.blobs.Delete(ctx, ref) } -// DeleteWithStorageFormat deletes the blob with the namespace, key, and format version +// DeleteWithStorageFormat deletes the blob with the namespace, key, and format version. func (slow *SlowBlobs) DeleteWithStorageFormat(ctx context.Context, ref storage.BlobRef, formatVer storage.FormatVersion) error { slow.sleep() return slow.blobs.DeleteWithStorageFormat(ctx, ref, formatVer) @@ -119,7 +119,7 @@ func (slow *SlowBlobs) DeleteNamespace(ctx context.Context, ref []byte) (err err return slow.blobs.DeleteNamespace(ctx, ref) } -// Stat looks up disk metadata on the blob file +// Stat looks up disk metadata on the blob file. func (slow *SlowBlobs) Stat(ctx context.Context, ref storage.BlobRef) (storage.BlobInfo, error) { slow.sleep() return slow.blobs.Stat(ctx, ref) @@ -152,19 +152,19 @@ func (slow *SlowBlobs) FreeSpace() (int64, error) { return slow.blobs.FreeSpace() } -// SpaceUsedForBlobs adds up how much is used in all namespaces +// SpaceUsedForBlobs adds up how much is used in all namespaces. func (slow *SlowBlobs) SpaceUsedForBlobs(ctx context.Context) (int64, error) { slow.sleep() return slow.blobs.SpaceUsedForBlobs(ctx) } -// SpaceUsedForBlobsInNamespace adds up how much is used in the given namespace +// SpaceUsedForBlobsInNamespace adds up how much is used in the given namespace. func (slow *SlowBlobs) SpaceUsedForBlobsInNamespace(ctx context.Context, namespace []byte) (int64, error) { slow.sleep() return slow.blobs.SpaceUsedForBlobsInNamespace(ctx, namespace) } -// SpaceUsedForTrash adds up how much is used in all namespaces +// SpaceUsedForTrash adds up how much is used in all namespaces. func (slow *SlowBlobs) SpaceUsedForTrash(ctx context.Context) (int64, error) { slow.sleep() return slow.blobs.SpaceUsedForTrash(ctx) @@ -176,7 +176,7 @@ func (slow *SlowBlobs) SetLatency(delay time.Duration) { atomic.StoreInt64(&slow.delay, int64(delay)) } -// sleep sleeps for the duration set to slow.delay +// sleep sleeps for the duration set to slow.delay. func (slow *SlowBlobs) sleep() { delay := time.Duration(atomic.LoadInt64(&slow.delay)) time.Sleep(delay) diff --git a/private/testplanet/planet.go b/private/testplanet/planet.go index 1c43ef5e6..9b2d36800 100644 --- a/private/testplanet/planet.go +++ b/private/testplanet/planet.go @@ -32,7 +32,7 @@ import ( const defaultInterval = 15 * time.Second -// Peer represents one of StorageNode or Satellite +// Peer represents one of StorageNode or Satellite. type Peer interface { ID() storj.NodeID Addr() string @@ -43,7 +43,7 @@ type Peer interface { Close() error } -// Config describes planet configuration +// Config describes planet configuration. type Config struct { SatelliteCount int StorageNodeCount int @@ -224,7 +224,7 @@ func (planet *Planet) Start(ctx context.Context) { planet.started = true } -// StopPeer stops a single peer in the planet +// StopPeer stops a single peer in the planet. func (planet *Planet) StopPeer(peer Peer) error { if peer == nil { return errors.New("peer is nil") @@ -265,7 +265,7 @@ func (planet *Planet) StopNodeAndUpdate(ctx context.Context, node *StorageNode) return nil } -// Size returns number of nodes in the network +// Size returns number of nodes in the network. func (planet *Planet) Size() int { return len(planet.uplinks) + len(planet.peers) } // FindNode is a helper to retrieve a storage node record by its node ID. @@ -336,12 +336,12 @@ func (planet *Planet) Identities() *testidentity.Identities { return planet.identities } -// NewIdentity creates a new identity for a node +// NewIdentity creates a new identity for a node. func (planet *Planet) NewIdentity() (*identity.FullIdentity, error) { return planet.identities.NewIdentity() } -// NewListener creates a new listener +// NewListener creates a new listener. func (planet *Planet) NewListener() (net.Listener, error) { return net.Listen("tcp", "127.0.0.1:0") } diff --git a/private/testplanet/planet_test.go b/private/testplanet/planet_test.go index 55571c75e..006ee1a9d 100644 --- a/private/testplanet/planet_test.go +++ b/private/testplanet/planet_test.go @@ -54,7 +54,7 @@ func TestBasic(t *testing.T) { } } -// test that nodes get put into each satellite's overlay cache +// test that nodes get put into each satellite's overlay cache. func TestContact(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 2, StorageNodeCount: 5, UplinkCount: 0, diff --git a/private/testplanet/reconfigure.go b/private/testplanet/reconfigure.go index 93b28a9b7..965d0e098 100644 --- a/private/testplanet/reconfigure.go +++ b/private/testplanet/reconfigure.go @@ -17,7 +17,7 @@ import ( "storj.io/storj/storagenode" ) -// Reconfigure allows to change node configurations +// Reconfigure allows to change node configurations. type Reconfigure struct { SatelliteDB func(log *zap.Logger, index int, db satellite.DB) (satellite.DB, error) SatellitePointerDB func(log *zap.Logger, index int, db metainfo.PointerDB) (metainfo.PointerDB, error) @@ -44,7 +44,7 @@ var DisablePeerCAWhitelist = Reconfigure{ } // ShortenOnlineWindow returns a `Reconfigure` that sets the NodeSelection -// OnlineWindow to 1 second, meaning a connection failure leads to marking the nodes as offline +// OnlineWindow to 1 second, meaning a connection failure leads to marking the nodes as offline. var ShortenOnlineWindow = Reconfigure{ Satellite: func(log *zap.Logger, index int, config *satellite.Config) { config.Overlay.Node.OnlineWindow = 1 * time.Second @@ -60,7 +60,7 @@ var Combine = func(elements ...func(log *zap.Logger, index int, config *satellit } } -// ReconfigureRS returns function to change satellite redundancy scheme values +// ReconfigureRS returns function to change satellite redundancy scheme values. var ReconfigureRS = func(minThreshold, repairThreshold, successThreshold, totalThreshold int) func(log *zap.Logger, index int, config *satellite.Config) { return func(log *zap.Logger, index int, config *satellite.Config) { config.Metainfo.RS.MinThreshold = minThreshold diff --git a/private/testplanet/referralmanager.go b/private/testplanet/referralmanager.go index df1afcda0..eebe184b3 100644 --- a/private/testplanet/referralmanager.go +++ b/private/testplanet/referralmanager.go @@ -15,12 +15,12 @@ import ( "storj.io/storj/pkg/server" ) -// DefaultReferralManagerServer implements the default behavior of a mock referral manager +// DefaultReferralManagerServer implements the default behavior of a mock referral manager. type DefaultReferralManagerServer struct { tokenCount int } -// newReferralManager initializes a referral manager server +// newReferralManager initializes a referral manager server. func (planet *Planet) newReferralManager() (*server.Server, error) { prefix := "referralmanager" log := planet.log.Named(prefix) diff --git a/private/testplanet/satellite.go b/private/testplanet/satellite.go index ef7a9099a..eec4db8ce 100644 --- a/private/testplanet/satellite.go +++ b/private/testplanet/satellite.go @@ -64,7 +64,7 @@ import ( "storj.io/storj/storage/redis/redisserver" ) -// Satellite contains all the processes needed to run a full Satellite setup +// Satellite contains all the processes needed to run a full Satellite setup. type Satellite struct { Config satellite.Config @@ -271,7 +271,7 @@ func (system *Satellite) authenticatedContext(ctx context.Context, userID uuid.U return console.WithAuth(ctx, auth), nil } -// Close closes all the subsystems in the Satellite system +// Close closes all the subsystems in the Satellite system. func (system *Satellite) Close() error { return errs.Combine( system.API.Close(), @@ -282,7 +282,7 @@ func (system *Satellite) Close() error { ) } -// Run runs all the subsystems in the Satellite system +// Run runs all the subsystems in the Satellite system. func (system *Satellite) Run(ctx context.Context) (err error) { group, ctx := errgroup.WithContext(ctx) @@ -307,7 +307,7 @@ func (system *Satellite) Run(ctx context.Context) (err error) { // PrivateAddr returns the private address from the Satellite system API. func (system *Satellite) PrivateAddr() string { return system.API.Server.PrivateAddr().String() } -// newSatellites initializes satellites +// newSatellites initializes satellites. func (planet *Planet) newSatellites(count int, satelliteDatabases satellitedbtest.SatelliteDatabases) ([]*Satellite, error) { var xs []*Satellite defer func() { diff --git a/private/testplanet/uplink.go b/private/testplanet/uplink.go index 06a801a17..85ef6d500 100644 --- a/private/testplanet/uplink.go +++ b/private/testplanet/uplink.go @@ -27,7 +27,7 @@ import ( "storj.io/uplink/private/testuplink" ) -// Uplink is a general purpose +// Uplink is a general purpose. type Uplink struct { Log *zap.Logger Identity *identity.FullIdentity @@ -156,16 +156,16 @@ func (planet *Planet) newUplink(name string) (*Uplink, error) { return planetUplink, nil } -// ID returns uplink id +// ID returns uplink id. func (client *Uplink) ID() storj.NodeID { return client.Identity.ID } -// Addr returns uplink address +// Addr returns uplink address. func (client *Uplink) Addr() string { return "" } -// Shutdown shuts down all uplink dependencies +// Shutdown shuts down all uplink dependencies. func (client *Uplink) Shutdown() error { return nil } -// DialMetainfo dials destination with apikey and returns metainfo Client +// DialMetainfo dials destination with apikey and returns metainfo Client. func (client *Uplink) DialMetainfo(ctx context.Context, destination Peer, apikey *macaroon.APIKey) (*metainfo.Client, error) { return metainfo.DialNodeURL(ctx, client.Dialer, destination.NodeURL().String(), apikey, "Test/1.0") } @@ -175,12 +175,12 @@ func (client *Uplink) DialPiecestore(ctx context.Context, destination Peer) (*pi return piecestore.DialNodeURL(ctx, client.Dialer, destination.NodeURL(), client.Log.Named("uplink>piecestore"), piecestore.DefaultConfig) } -// Upload data to specific satellite +// Upload data to specific satellite. func (client *Uplink) Upload(ctx context.Context, satellite *Satellite, bucket string, path storj.Path, data []byte) error { return client.UploadWithExpiration(ctx, satellite, bucket, path, data, time.Time{}) } -// UploadWithExpiration data to specific satellite and expiration time +// UploadWithExpiration data to specific satellite and expiration time. func (client *Uplink) UploadWithExpiration(ctx context.Context, satellite *Satellite, bucketName string, path storj.Path, data []byte, expiration time.Time) error { _, found := testuplink.GetMaxSegmentSize(ctx) if !found { @@ -215,7 +215,7 @@ func (client *Uplink) UploadWithExpiration(ctx context.Context, satellite *Satel return upload.Commit() } -// Download data from specific satellite +// Download data from specific satellite. func (client *Uplink) Download(ctx context.Context, satellite *Satellite, bucketName string, path storj.Path) ([]byte, error) { project, err := client.GetProject(ctx, satellite) if err != nil { @@ -236,7 +236,7 @@ func (client *Uplink) Download(ctx context.Context, satellite *Satellite, bucket return data, nil } -// DownloadStream returns stream for downloading data +// DownloadStream returns stream for downloading data. func (client *Uplink) DownloadStream(ctx context.Context, satellite *Satellite, bucketName string, path storj.Path) (_ io.ReadCloser, cleanup func() error, err error) { project, err := client.GetProject(ctx, satellite) if err != nil { @@ -254,7 +254,7 @@ func (client *Uplink) DownloadStream(ctx context.Context, satellite *Satellite, return downloader, cleanup, err } -// DownloadStreamRange returns stream for downloading data +// DownloadStreamRange returns stream for downloading data. func (client *Uplink) DownloadStreamRange(ctx context.Context, satellite *Satellite, bucketName string, path storj.Path, start, limit int64) (_ io.ReadCloser, cleanup func() error, err error) { project, err := client.GetProject(ctx, satellite) if err != nil { @@ -275,7 +275,7 @@ func (client *Uplink) DownloadStreamRange(ctx context.Context, satellite *Satell return downloader, cleanup, err } -// DeleteObject deletes an object at the path in a bucket +// DeleteObject deletes an object at the path in a bucket. func (client *Uplink) DeleteObject(ctx context.Context, satellite *Satellite, bucketName string, path storj.Path) error { project, err := client.GetProject(ctx, satellite) if err != nil { @@ -290,7 +290,7 @@ func (client *Uplink) DeleteObject(ctx context.Context, satellite *Satellite, bu return err } -// CreateBucket creates a new bucket +// CreateBucket creates a new bucket. func (client *Uplink) CreateBucket(ctx context.Context, satellite *Satellite, bucketName string) error { project, err := client.GetProject(ctx, satellite) if err != nil { diff --git a/private/testplanet/versioning.go b/private/testplanet/versioning.go index abcc8e425..2215831f7 100644 --- a/private/testplanet/versioning.go +++ b/private/testplanet/versioning.go @@ -14,7 +14,7 @@ import ( "storj.io/storj/versioncontrol" ) -// newVersionControlServer initializes the Versioning Server +// newVersionControlServer initializes the Versioning Server. func (planet *Planet) newVersionControlServer() (peer *versioncontrol.Peer, err error) { prefix := "versioncontrol" diff --git a/private/teststorj/node.go b/private/teststorj/node.go index 1f3e80e15..d6a22802b 100644 --- a/private/teststorj/node.go +++ b/private/teststorj/node.go @@ -9,20 +9,20 @@ import ( ) // NodeIDFromBytes returns a node ID consisting of the bytes -// and padding to the node ID length +// and padding to the node ID length. func NodeIDFromBytes(b []byte) storj.NodeID { id, _ := storj.NodeIDFromBytes(fit(b)) return id } // NodeIDFromString returns node ID consisting of the strings -// and padding to the node ID length +// and padding to the node ID length. func NodeIDFromString(s string) storj.NodeID { return NodeIDFromBytes([]byte(s)) } // NodeIDsFromBytes returns node IDs consisting of the byte slices -// and padding to the node ID length +// and padding to the node ID length. func NodeIDsFromBytes(bs ...[]byte) (ids storj.NodeIDList) { for _, b := range bs { ids = append(ids, NodeIDFromBytes(b)) @@ -31,7 +31,7 @@ func NodeIDsFromBytes(bs ...[]byte) (ids storj.NodeIDList) { } // NodeIDsFromStrings returns node IDs consisting of the strings -// and padding to the node ID length +// and padding to the node ID length. func NodeIDsFromStrings(strs ...string) (ids storj.NodeIDList) { for _, s := range strs { ids = append(ids, NodeIDFromString(s)) @@ -39,7 +39,7 @@ func NodeIDsFromStrings(strs ...string) (ids storj.NodeIDList) { return ids } -// used to pad node IDs +// used to pad node IDs. func fit(b []byte) []byte { l := len(storj.NodeID{}) if len(b) < l { @@ -50,7 +50,7 @@ func fit(b []byte) []byte { } // MockNode returns a pb node with an ID consisting of the string -// and padding to the node ID length +// and padding to the node ID length. func MockNode(s string) *pb.Node { id := NodeIDFromString(s) var node pb.Node diff --git a/private/teststorj/pieceid.go b/private/teststorj/pieceid.go index 1dd76265b..89cb74fd1 100644 --- a/private/teststorj/pieceid.go +++ b/private/teststorj/pieceid.go @@ -7,13 +7,13 @@ import ( "storj.io/common/storj" ) -// PieceIDFromBytes converts a byte slice into a piece ID +// PieceIDFromBytes converts a byte slice into a piece ID. func PieceIDFromBytes(b []byte) storj.PieceID { id, _ := storj.PieceIDFromBytes(fit(b)) return id } -// PieceIDFromString decodes a hex encoded piece ID string +// PieceIDFromString decodes a hex encoded piece ID string. func PieceIDFromString(s string) storj.PieceID { return PieceIDFromBytes([]byte(s)) } diff --git a/private/version/checker/chore.go b/private/version/checker/chore.go index ee89cdfd9..29f58e66d 100644 --- a/private/version/checker/chore.go +++ b/private/version/checker/chore.go @@ -25,7 +25,7 @@ func NewChore(service *Service, checkInterval time.Duration) *Chore { } } -// Run logs the current version information +// Run logs the current version information. func (chore *Chore) Run(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) if !chore.service.Checked() { diff --git a/private/version/checker/service.go b/private/version/checker/service.go index 9e06fa9a6..d66577d9f 100644 --- a/private/version/checker/service.go +++ b/private/version/checker/service.go @@ -15,7 +15,7 @@ import ( "storj.io/private/version" ) -// Config contains the necessary Information to check the Software Version +// Config contains the necessary Information to check the Software Version. type Config struct { ClientConfig @@ -38,7 +38,7 @@ type Service struct { acceptedVersion version.SemVer } -// NewService creates a Version Check Client with default configuration +// NewService creates a Version Check Client with default configuration. func NewService(log *zap.Logger, config Config, info version.Info, service string) (client *Service) { return &Service{ log: log, @@ -51,7 +51,7 @@ func NewService(log *zap.Logger, config Config, info version.Info, service strin } // CheckProcessVersion is not meant to be used for peers but is meant to be -// used for other utilities +// used for other utilities. func CheckProcessVersion(ctx context.Context, log *zap.Logger, config Config, info version.Info, service string) (err error) { defer mon.Task()(&ctx)(&err) _, err = NewService(log, config, info, service).CheckVersion(ctx) @@ -141,7 +141,7 @@ func (service *Service) Checked() bool { return service.checked.Released() } -// isAcceptedVersion compares and checks if the passed version is greater/equal than the minimum required version +// isAcceptedVersion compares and checks if the passed version is greater/equal than the minimum required version. func isAcceptedVersion(test version.SemVer, target version.OldSemVer) bool { return test.Major > uint64(target.Major) || (test.Major == uint64(target.Major) && (test.Minor > uint64(target.Minor) || (test.Minor == uint64(target.Minor) && test.Patch >= uint64(target.Patch)))) } diff --git a/satellite/accounting/bucketstats.go b/satellite/accounting/bucketstats.go index 449f5e209..f0eea8d76 100644 --- a/satellite/accounting/bucketstats.go +++ b/satellite/accounting/bucketstats.go @@ -7,7 +7,7 @@ import ( "storj.io/common/uuid" ) -// BucketTally contains information about aggregate data stored in a bucket +// BucketTally contains information about aggregate data stored in a bucket. type BucketTally struct { ProjectID uuid.UUID BucketName []byte @@ -23,7 +23,7 @@ type BucketTally struct { MetadataSize int64 } -// Combine aggregates all the tallies +// Combine aggregates all the tallies. func (s *BucketTally) Combine(o *BucketTally) { s.ObjectCount += o.ObjectCount diff --git a/satellite/accounting/bucketusage.go b/satellite/accounting/bucketusage.go index 5752021a0..17211775e 100644 --- a/satellite/accounting/bucketusage.go +++ b/satellite/accounting/bucketusage.go @@ -9,7 +9,7 @@ import ( "storj.io/common/uuid" ) -// BucketStorageTally holds data about a bucket tally +// BucketStorageTally holds data about a bucket tally. type BucketStorageTally struct { BucketName string ProjectID uuid.UUID diff --git a/satellite/accounting/common.go b/satellite/accounting/common.go index 46fe41970..34422ca86 100644 --- a/satellite/accounting/common.go +++ b/satellite/accounting/common.go @@ -9,7 +9,7 @@ import ( "storj.io/common/storj" ) -// Constants for accounting_raw, accounting_rollup, and accounting_timestamps +// Constants for accounting_raw, accounting_rollup, and accounting_timestamps. const ( // LastAtRestTally represents the accounting timestamp for the at-rest data calculation LastAtRestTally = "LastAtRestTally" @@ -19,7 +19,7 @@ const ( LastRollup = "LastRollup" ) -// CSVRow represents data from QueryPaymentInfo without exposing dbx +// CSVRow represents data from QueryPaymentInfo without exposing dbx. type CSVRow struct { NodeID storj.NodeID NodeCreationDate time.Time diff --git a/satellite/accounting/db.go b/satellite/accounting/db.go index e67b15bc3..a2df4579e 100644 --- a/satellite/accounting/db.go +++ b/satellite/accounting/db.go @@ -13,10 +13,10 @@ import ( "storj.io/storj/satellite/compensation" ) -// RollupStats is a convenience alias +// RollupStats is a convenience alias. type RollupStats map[time.Time]map[storj.NodeID]*Rollup -// StoragenodeStorageTally mirrors dbx.StoragenodeStorageTally, allowing us to use that struct without leaking dbx +// StoragenodeStorageTally mirrors dbx.StoragenodeStorageTally, allowing us to use that struct without leaking dbx. type StoragenodeStorageTally struct { ID int64 NodeID storj.NodeID @@ -24,7 +24,7 @@ type StoragenodeStorageTally struct { DataTotal float64 } -// StoragenodeBandwidthRollup mirrors dbx.StoragenodeBandwidthRollup, allowing us to use the struct without leaking dbx +// StoragenodeBandwidthRollup mirrors dbx.StoragenodeBandwidthRollup, allowing us to use the struct without leaking dbx. type StoragenodeBandwidthRollup struct { NodeID storj.NodeID IntervalStart time.Time @@ -32,7 +32,7 @@ type StoragenodeBandwidthRollup struct { Settled uint64 } -// Rollup mirrors dbx.AccountingRollup, allowing us to use that struct without leaking dbx +// Rollup mirrors dbx.AccountingRollup, allowing us to use that struct without leaking dbx. type Rollup struct { ID int64 NodeID storj.NodeID @@ -45,7 +45,7 @@ type Rollup struct { AtRestTotal float64 } -// StorageNodePeriodUsage represents a statement for a node for a compensation period +// StorageNodePeriodUsage represents a statement for a node for a compensation period. type StorageNodePeriodUsage struct { NodeID storj.NodeID AtRestTotal float64 @@ -56,7 +56,7 @@ type StorageNodePeriodUsage struct { GetAuditTotal int64 } -// StorageNodeUsage is node at rest space usage over a period of time +// StorageNodeUsage is node at rest space usage over a period of time. type StorageNodeUsage struct { NodeID storj.NodeID StorageUsed float64 @@ -65,7 +65,7 @@ type StorageNodeUsage struct { } // ProjectUsage consist of period total storage, egress -// and objects count per hour for certain Project in bytes +// and objects count per hour for certain Project in bytes. type ProjectUsage struct { Storage float64 `json:"storage"` Egress int64 `json:"egress"` @@ -75,7 +75,7 @@ type ProjectUsage struct { Before time.Time `json:"before"` } -// BucketUsage consist of total bucket usage for period +// BucketUsage consist of total bucket usage for period. type BucketUsage struct { ProjectID uuid.UUID BucketName string @@ -89,14 +89,14 @@ type BucketUsage struct { } // BucketUsageCursor holds info for bucket usage -// cursor pagination +// cursor pagination. type BucketUsageCursor struct { Search string Limit uint Page uint } -// BucketUsagePage represents bucket usage page result +// BucketUsagePage represents bucket usage page result. type BucketUsagePage struct { BucketUsages []BucketUsage @@ -110,7 +110,7 @@ type BucketUsagePage struct { } // BucketUsageRollup is total bucket usage info -// for certain period +// for certain period. type BucketUsageRollup struct { ProjectID uuid.UUID BucketName []byte diff --git a/satellite/accounting/rollup/rollup.go b/satellite/accounting/rollup/rollup.go index 5ee156443..315e47548 100644 --- a/satellite/accounting/rollup/rollup.go +++ b/satellite/accounting/rollup/rollup.go @@ -15,7 +15,7 @@ import ( "storj.io/storj/satellite/accounting" ) -// Config contains configurable values for rollup +// Config contains configurable values for rollup. type Config struct { Interval time.Duration `help:"how frequently rollup should run" releaseDefault:"24h" devDefault:"120s"` DeleteTallies bool `help:"option for deleting tallies after they are rolled up" default:"true"` @@ -31,7 +31,7 @@ type Service struct { deleteTallies bool } -// New creates a new rollup service +// New creates a new rollup service. func New(logger *zap.Logger, sdb accounting.StoragenodeAccounting, interval time.Duration, deleteTallies bool) *Service { return &Service{ logger: logger, @@ -41,7 +41,7 @@ func New(logger *zap.Logger, sdb accounting.StoragenodeAccounting, interval time } } -// Run the Rollup loop +// Run the Rollup loop. func (r *Service) Run(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) return r.Loop.Run(ctx, func(ctx context.Context) error { @@ -59,7 +59,7 @@ func (r *Service) Close() error { return nil } -// Rollup aggregates storage and bandwidth amounts for the time interval +// Rollup aggregates storage and bandwidth amounts for the time interval. func (r *Service) Rollup(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) // only Rollup new things - get LastRollup @@ -102,7 +102,7 @@ func (r *Service) Rollup(ctx context.Context) (err error) { return nil } -// RollupStorage rolls up storage tally, modifies rollupStats map +// RollupStorage rolls up storage tally, modifies rollupStats map. func (r *Service) RollupStorage(ctx context.Context, lastRollup time.Time, rollupStats accounting.RollupStats) (latestTally time.Time, err error) { defer mon.Task()(&ctx)(&err) tallies, err := r.sdb.GetTalliesSince(ctx, lastRollup) @@ -136,7 +136,7 @@ func (r *Service) RollupStorage(ctx context.Context, lastRollup time.Time, rollu return latestTally, nil } -// RollupBW aggregates the bandwidth rollups, modifies rollupStats map +// RollupBW aggregates the bandwidth rollups, modifies rollupStats map. func (r *Service) RollupBW(ctx context.Context, lastRollup time.Time, rollupStats accounting.RollupStats) (err error) { defer mon.Task()(&ctx)(&err) var latestTally time.Time diff --git a/satellite/accounting/rollup/rollup_test.go b/satellite/accounting/rollup/rollup_test.go index f50b1a2ee..725197038 100644 --- a/satellite/accounting/rollup/rollup_test.go +++ b/satellite/accounting/rollup/rollup_test.go @@ -178,7 +178,7 @@ func TestRollupDeletes(t *testing.T) { }) } -// expectedTotals sums test data up to, but not including the current day's +// expectedTotals sums test data up to, but not including the current day's. func expectedTotals(data []testData, id storj.NodeID, currentDay int) []float64 { totals := make([]float64, 5) for i := 0; i < currentDay; i++ { @@ -206,7 +206,7 @@ func createData(planet *testplanet.Planet, days int) []testData { return data } -// dqNodes disqualifies half the nodes in the testplanet and returns a map of dqed nodes +// dqNodes disqualifies half the nodes in the testplanet and returns a map of dqed nodes. func dqNodes(ctx *testcontext.Context, planet *testplanet.Planet) (map[storj.NodeID]bool, error) { dqed := make(map[storj.NodeID]bool) diff --git a/satellite/accounting/tally/tally.go b/satellite/accounting/tally/tally.go index e89c418d7..e448f4cde 100644 --- a/satellite/accounting/tally/tally.go +++ b/satellite/accounting/tally/tally.go @@ -25,7 +25,7 @@ var ( mon = monkit.Package() ) -// Config contains configurable values for the tally service +// Config contains configurable values for the tally service. type Config struct { Interval time.Duration `help:"how frequently the tally service should run" releaseDefault:"1h" devDefault:"30s"` } @@ -44,7 +44,7 @@ type Service struct { nowFn func() time.Time } -// New creates a new tally Service +// New creates a new tally Service. func New(log *zap.Logger, sdb accounting.StoragenodeAccounting, pdb accounting.ProjectAccounting, liveAccounting accounting.Cache, metainfoLoop *metainfo.Loop, interval time.Duration) *Service { return &Service{ log: log, @@ -58,7 +58,7 @@ func New(log *zap.Logger, sdb accounting.StoragenodeAccounting, pdb accounting.P } } -// Run the tally service loop +// Run the tally service loop. func (service *Service) Run(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) @@ -83,7 +83,7 @@ func (service *Service) SetNow(now func() time.Time) { service.nowFn = now } -// Tally calculates data-at-rest usage once +// Tally calculates data-at-rest usage once. func (service *Service) Tally(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) @@ -190,7 +190,7 @@ func (service *Service) Tally(ctx context.Context) (err error) { var _ metainfo.Observer = (*Observer)(nil) -// Observer observes metainfo and adds up tallies for nodes and buckets +// Observer observes metainfo and adds up tallies for nodes and buckets. type Observer struct { Now time.Time Log *zap.Logger @@ -213,7 +213,7 @@ func (observer *Observer) pointerExpired(pointer *pb.Pointer) bool { return !pointer.ExpirationDate.IsZero() && pointer.ExpirationDate.Before(observer.Now) } -// ensureBucket returns bucket corresponding to the passed in path +// ensureBucket returns bucket corresponding to the passed in path. func (observer *Observer) ensureBucket(ctx context.Context, path metainfo.ScopedPath) *accounting.BucketTally { bucketID := storj.JoinPaths(path.ProjectIDString, path.BucketName) @@ -290,5 +290,5 @@ func projectTotalsFromBuckets(buckets map[string]*accounting.BucketTally) map[uu return projectTallyTotals } -// using custom name to avoid breaking monitoring +// using custom name to avoid breaking monitoring. var monAccounting = monkit.ScopeNamed("storj.io/storj/satellite/accounting") diff --git a/satellite/accounting/tally/tally_test.go b/satellite/accounting/tally/tally_test.go index f9645c444..25f96b07e 100644 --- a/satellite/accounting/tally/tally_test.go +++ b/satellite/accounting/tally/tally_test.go @@ -314,7 +314,7 @@ func TestTallyEmptyProjectUpdatesLiveAccounting(t *testing.T) { } // addBucketTally creates a new expected bucket tally based on the -// pointer that was just created for the test case +// pointer that was just created for the test case. func addBucketTally(existingTally *accounting.BucketTally, inline, last bool) *accounting.BucketTally { // if there is already an existing tally for this project and bucket, then // add the new pointer data to the existing tally @@ -349,7 +349,7 @@ func addBucketTally(existingTally *accounting.BucketTally, inline, last bool) *a return newRemoteTally } -// makePointer creates a pointer +// makePointer creates a pointer. func makePointer(storageNodes []*testplanet.StorageNode, rs storj.RedundancyScheme, segmentSize int64, inline bool) *pb.Pointer { if inline { inlinePointer := &pb.Pointer{ diff --git a/satellite/api.go b/satellite/api.go index 19221b316..7222550ce 100644 --- a/satellite/api.go +++ b/satellite/api.go @@ -161,7 +161,7 @@ type API struct { } } -// NewAPI creates a new satellite API process +// NewAPI creates a new satellite API process. func NewAPI(log *zap.Logger, full *identity.FullIdentity, db DB, pointerDB metainfo.PointerDB, revocationDB extensions.RevocationDB, liveAccounting accounting.Cache, rollupsWriteCache *orders.RollupsWriteCache, config *Config, versionInfo version.Info, atomicLogLevel *zap.AtomicLevel) (*API, error) { diff --git a/satellite/attribution/db.go b/satellite/attribution/db.go index 746577d6b..de8449eaf 100644 --- a/satellite/attribution/db.go +++ b/satellite/attribution/db.go @@ -13,10 +13,10 @@ import ( "storj.io/common/uuid" ) -// ErrBucketNotAttributed is returned if a requested bucket not attributed(entry not found) +// ErrBucketNotAttributed is returned if a requested bucket not attributed(entry not found). var ErrBucketNotAttributed = errs.Class("bucket not attributed") -// Info describing value attribution from partner to bucket +// Info describing value attribution from partner to bucket. type Info struct { ProjectID uuid.UUID BucketName []byte @@ -24,7 +24,7 @@ type Info struct { CreatedAt time.Time } -// CSVRow represents data from QueryAttribution without exposing dbx +// CSVRow represents data from QueryAttribution without exposing dbx. type CSVRow struct { PartnerID []byte ProjectID []byte diff --git a/satellite/audit/containment.go b/satellite/audit/containment.go index 87dc553f4..d54b6f339 100644 --- a/satellite/audit/containment.go +++ b/satellite/audit/containment.go @@ -23,7 +23,7 @@ var ( ErrContainDelete = errs.Class("unable to delete pending audit") ) -// PendingAudit contains info needed for retrying an audit for a contained node +// PendingAudit contains info needed for retrying an audit for a contained node. type PendingAudit struct { NodeID storj.NodeID PieceID storj.PieceID diff --git a/satellite/audit/cryptosource.go b/satellite/audit/cryptosource.go index cf1d1c485..0becac71a 100644 --- a/satellite/audit/cryptosource.go +++ b/satellite/audit/cryptosource.go @@ -8,7 +8,7 @@ import ( "encoding/binary" ) -// cryptoSource implements the math/rand Source interface using crypto/rand +// cryptoSource implements the math/rand Source interface using crypto/rand. type cryptoSource struct{} func (s cryptoSource) Seed(seed int64) {} diff --git a/satellite/audit/pathcollector.go b/satellite/audit/pathcollector.go index 7fdef8e82..35b11e63a 100644 --- a/satellite/audit/pathcollector.go +++ b/satellite/audit/pathcollector.go @@ -23,7 +23,7 @@ type PathCollector struct { rand *rand.Rand } -// NewPathCollector instantiates a path collector +// NewPathCollector instantiates a path collector. func NewPathCollector(reservoirSlots int, r *rand.Rand) *PathCollector { return &PathCollector{ Reservoirs: make(map[storj.NodeID]*Reservoir), @@ -32,7 +32,7 @@ func NewPathCollector(reservoirSlots int, r *rand.Rand) *PathCollector { } } -// RemoteSegment takes a remote segment found in metainfo and creates a reservoir for it if it doesn't exist already +// RemoteSegment takes a remote segment found in metainfo and creates a reservoir for it if it doesn't exist already. func (collector *PathCollector) RemoteSegment(ctx context.Context, path metainfo.ScopedPath, pointer *pb.Pointer) (err error) { for _, piece := range pointer.GetRemote().GetRemotePieces() { if _, ok := collector.Reservoirs[piece.NodeId]; !ok { @@ -43,12 +43,12 @@ func (collector *PathCollector) RemoteSegment(ctx context.Context, path metainfo return nil } -// Object returns nil because the audit service does not interact with objects +// Object returns nil because the audit service does not interact with objects. func (collector *PathCollector) Object(ctx context.Context, path metainfo.ScopedPath, pointer *pb.Pointer) (err error) { return nil } -// InlineSegment returns nil because we're only auditing for storage nodes for now +// InlineSegment returns nil because we're only auditing for storage nodes for now. func (collector *PathCollector) InlineSegment(ctx context.Context, path metainfo.ScopedPath, pointer *pb.Pointer) (err error) { return nil } diff --git a/satellite/audit/reporter.go b/satellite/audit/reporter.go index 55bf49ea3..83acc6189 100644 --- a/satellite/audit/reporter.go +++ b/satellite/audit/reporter.go @@ -27,7 +27,7 @@ type Reporter struct { maxReverifyCount int32 } -// Report contains audit result lists for nodes that succeeded, failed, were offline, have pending audits, or failed for unknown reasons +// Report contains audit result lists for nodes that succeeded, failed, were offline, have pending audits, or failed for unknown reasons. type Report struct { Successes storj.NodeIDList Fails storj.NodeIDList @@ -36,7 +36,7 @@ type Report struct { Unknown storj.NodeIDList } -// NewReporter instantiates a reporter +// NewReporter instantiates a reporter. func NewReporter(log *zap.Logger, overlay *overlay.Service, containment Containment, maxRetries int, maxReverifyCount int32) *Reporter { return &Reporter{ log: log, @@ -124,7 +124,7 @@ func (reporter *Reporter) RecordAudits(ctx context.Context, req Report, path sto return Report{}, nil } -// recordAuditFailStatus updates nodeIDs in overlay with isup=true, auditoutcome=fail +// recordAuditFailStatus updates nodeIDs in overlay with isup=true, auditoutcome=fail. func (reporter *Reporter) recordAuditFailStatus(ctx context.Context, failedAuditNodeIDs storj.NodeIDList) (failed storj.NodeIDList, err error) { defer mon.Task()(&ctx)(&err) @@ -144,7 +144,7 @@ func (reporter *Reporter) recordAuditFailStatus(ctx context.Context, failedAudit return nil, nil } -// recordAuditUnknownStatus updates nodeIDs in overlay with isup=true, auditoutcome=unknown +// recordAuditUnknownStatus updates nodeIDs in overlay with isup=true, auditoutcome=unknown. func (reporter *Reporter) recordAuditUnknownStatus(ctx context.Context, unknownAuditNodeIDs storj.NodeIDList) (failed storj.NodeIDList, err error) { defer mon.Task()(&ctx)(&err) @@ -186,7 +186,7 @@ func (reporter *Reporter) recordOfflineStatus(ctx context.Context, offlineNodeID return nil, nil } -// recordAuditSuccessStatus updates nodeIDs in overlay with isup=true, auditoutcome=success +// recordAuditSuccessStatus updates nodeIDs in overlay with isup=true, auditoutcome=success. func (reporter *Reporter) recordAuditSuccessStatus(ctx context.Context, successNodeIDs storj.NodeIDList) (failed storj.NodeIDList, err error) { defer mon.Task()(&ctx)(&err) @@ -207,7 +207,7 @@ func (reporter *Reporter) recordAuditSuccessStatus(ctx context.Context, successN return nil, nil } -// recordPendingAudits updates the containment status of nodes with pending audits +// recordPendingAudits updates the containment status of nodes with pending audits. func (reporter *Reporter) recordPendingAudits(ctx context.Context, pendingAudits []*PendingAudit) (failed []*PendingAudit, err error) { defer mon.Task()(&ctx)(&err) var errlist errs.Group diff --git a/satellite/audit/reservoir.go b/satellite/audit/reservoir.go index 83b8e44ad..da61ebad7 100644 --- a/satellite/audit/reservoir.go +++ b/satellite/audit/reservoir.go @@ -11,14 +11,14 @@ import ( const maxReservoirSize = 3 -// Reservoir holds a certain number of segments to reflect a random sample +// Reservoir holds a certain number of segments to reflect a random sample. type Reservoir struct { Paths [maxReservoirSize]storj.Path size int8 index int64 } -// NewReservoir instantiates a Reservoir +// NewReservoir instantiates a Reservoir. func NewReservoir(size int) *Reservoir { if size < 1 { size = 1 @@ -32,7 +32,7 @@ func NewReservoir(size int) *Reservoir { } // Sample makes sure that for every segment in metainfo from index i=size..n-1, -// pick a random number r = rand(0..i), and if r < size, replace reservoir.Segments[r] with segment +// pick a random number r = rand(0..i), and if r < size, replace reservoir.Segments[r] with segment. func (reservoir *Reservoir) Sample(r *rand.Rand, path storj.Path) { reservoir.index++ if reservoir.index < int64(reservoir.size) { diff --git a/satellite/audit/reverify_test.go b/satellite/audit/reverify_test.go index d1709c1e5..37a4afd1f 100644 --- a/satellite/audit/reverify_test.go +++ b/satellite/audit/reverify_test.go @@ -899,7 +899,7 @@ func TestReverifyDifferentShare(t *testing.T) { }) } -// TestReverifyExpired1 tests the case where the segment passed into Reverify is expired +// TestReverifyExpired1 tests the case where the segment passed into Reverify is expired. func TestReverifyExpired1(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, StorageNodeCount: 4, UplinkCount: 1, @@ -1074,7 +1074,7 @@ func TestReverifyExpired2(t *testing.T) { } // TestReverifySlowDownload checks that a node that times out while sending data to the -// audit service gets put into containment mode +// audit service gets put into containment mode. func TestReverifySlowDownload(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, StorageNodeCount: 4, UplinkCount: 1, diff --git a/satellite/audit/verifier.go b/satellite/audit/verifier.go index 7379b00c5..ada9e30f5 100644 --- a/satellite/audit/verifier.go +++ b/satellite/audit/verifier.go @@ -44,7 +44,7 @@ var ( ErrSegmentModified = errs.Class("segment has been modified") ) -// Share represents required information about an audited share +// Share represents required information about an audited share. type Share struct { Error error PieceNum int @@ -69,7 +69,7 @@ type Verifier struct { OnTestingCheckSegmentAlteredHook func() } -// NewVerifier creates a Verifier +// NewVerifier creates a Verifier. func NewVerifier(log *zap.Logger, metainfo *metainfo.Service, dialer rpc.Dialer, overlay *overlay.Service, containment Containment, orders *orders.Service, id *identity.FullIdentity, minBytesPerSecond memory.Size, minDownloadTimeout time.Duration) *Verifier { return &Verifier{ log: log, @@ -308,7 +308,7 @@ func (verifier *Verifier) Verify(ctx context.Context, path storj.Path, skip map[ }, nil } -// DownloadShares downloads shares from the nodes where remote pieces are located +// DownloadShares downloads shares from the nodes where remote pieces are located. func (verifier *Verifier) DownloadShares(ctx context.Context, limits []*pb.AddressedOrderLimit, piecePrivateKey storj.PiecePrivateKey, stripeIndex int64, shareSize int32) (shares map[int]Share, err error) { defer mon.Task()(&ctx)(&err) @@ -345,7 +345,7 @@ func (verifier *Verifier) DownloadShares(ctx context.Context, limits []*pb.Addre return shares, nil } -// Reverify reverifies the contained nodes in the stripe +// Reverify reverifies the contained nodes in the stripe. func (verifier *Verifier) Reverify(ctx context.Context, path storj.Path) (report Report, err error) { defer mon.Task()(&ctx)(&err) @@ -619,7 +619,7 @@ func (verifier *Verifier) Reverify(ctx context.Context, path storj.Path) (report return report, err } -// GetShare use piece store client to download shares from nodes +// GetShare use piece store client to download shares from nodes. func (verifier *Verifier) GetShare(ctx context.Context, limit *pb.AddressedOrderLimit, piecePrivateKey storj.PiecePrivateKey, stripeIndex int64, shareSize int32, pieceNum int) (share Share, err error) { defer mon.Task()(&ctx)(&err) @@ -729,7 +729,7 @@ func auditShares(ctx context.Context, required, total int, originals map[int]Sha return pieceNums, copies, nil } -// makeCopies takes in a map of audit Shares and deep copies their data to a slice of infectious Shares +// makeCopies takes in a map of audit Shares and deep copies their data to a slice of infectious Shares. func makeCopies(ctx context.Context, originals map[int]Share) (copies []infectious.Share, err error) { defer mon.Task()(&ctx)(&err) copies = make([]infectious.Share, 0, len(originals)) @@ -762,7 +762,7 @@ func getOfflineNodes(pointer *pb.Pointer, limits []*pb.AddressedOrderLimit, skip return offlines } -// getSuccessNodes uses the failed nodes, offline nodes and contained nodes arrays to determine which nodes passed the audit +// getSuccessNodes uses the failed nodes, offline nodes and contained nodes arrays to determine which nodes passed the audit. func getSuccessNodes(ctx context.Context, shares map[int]Share, failedNodes, offlineNodes, unknownNodes storj.NodeIDList, containedNodes map[int]storj.NodeID) (successNodes storj.NodeIDList) { defer mon.Task()(&ctx)(nil) fails := make(map[storj.NodeID]bool) diff --git a/satellite/audit/verifier_test.go b/satellite/audit/verifier_test.go index fe4a31023..8f73d50c3 100644 --- a/satellite/audit/verifier_test.go +++ b/satellite/audit/verifier_test.go @@ -763,7 +763,7 @@ func TestVerifierModifiedSegmentFailsOnce(t *testing.T) { } // TestVerifierSlowDownload checks that a node that times out while sending data to the -// audit service gets put into containment mode +// audit service gets put into containment mode. func TestVerifierSlowDownload(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, StorageNodeCount: 4, UplinkCount: 1, @@ -821,7 +821,7 @@ func TestVerifierSlowDownload(t *testing.T) { } // TestVerifierUnknownError checks that a node that returns an unknown error in response to an audit request -// does not get marked as successful, failed, or contained +// does not get marked as successful, failed, or contained. func TestVerifierUnknownError(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, StorageNodeCount: 4, UplinkCount: 1, diff --git a/satellite/compensation/config.go b/satellite/compensation/config.go index 54c037165..2bb6667b9 100644 --- a/satellite/compensation/config.go +++ b/satellite/compensation/config.go @@ -34,7 +34,7 @@ func (percents Percents) String() string { return strings.Join(s, ",") } -// Set implements pflag.Value by parsing a comma separated list of percents +// Set implements pflag.Value by parsing a comma separated list of percents. func (percents *Percents) Set(value string) error { var entries []string if value != "" { @@ -54,7 +54,7 @@ func (percents *Percents) Set(value string) error { return nil } -// Type returns the type of the pflag.Value +// Type returns the type of the pflag.Value. func (percents Percents) Type() string { return "percents" } diff --git a/satellite/console/apikeys.go b/satellite/console/apikeys.go index 1e31f8396..8af342ee8 100644 --- a/satellite/console/apikeys.go +++ b/satellite/console/apikeys.go @@ -30,7 +30,7 @@ type APIKeys interface { Delete(ctx context.Context, id uuid.UUID) error } -// APIKeyInfo describing api key model in the database +// APIKeyInfo describing api key model in the database. type APIKeyInfo struct { ID uuid.UUID `json:"id"` ProjectID uuid.UUID `json:"projectId"` @@ -40,7 +40,7 @@ type APIKeyInfo struct { CreatedAt time.Time `json:"createdAt"` } -// APIKeyCursor holds info for api keys cursor pagination +// APIKeyCursor holds info for api keys cursor pagination. type APIKeyCursor struct { Search string Limit uint @@ -49,7 +49,7 @@ type APIKeyCursor struct { OrderDirection OrderDirection } -// APIKeyPage represent api key page result +// APIKeyPage represent api key page result. type APIKeyPage struct { APIKeys []APIKeyInfo @@ -64,7 +64,7 @@ type APIKeyPage struct { TotalCount uint64 } -// APIKeyOrder is used for querying api keys in specified order +// APIKeyOrder is used for querying api keys in specified order. type APIKeyOrder uint8 const ( diff --git a/satellite/console/auth.go b/satellite/console/auth.go index 7c4498e4d..bc644a778 100644 --- a/satellite/console/auth.go +++ b/satellite/console/auth.go @@ -14,12 +14,12 @@ import ( //TODO: change to JWT or Macaroon based auth -// Signer creates signature for provided data +// Signer creates signature for provided data. type Signer interface { Sign(data []byte) ([]byte, error) } -// signToken signs token with given signer +// signToken signs token with given signer. func signToken(token *consoleauth.Token, signer Signer) error { encoded := base64.URLEncoding.EncodeToString(token.Payload) @@ -32,32 +32,32 @@ func signToken(token *consoleauth.Token, signer Signer) error { return nil } -// key is a context value key type +// key is a context value key type. type key int -// authKey is context key for Authorization +// authKey is context key for Authorization. const authKey key = 0 -// ErrUnauthorized is error class for authorization related errors +// ErrUnauthorized is error class for authorization related errors. var ErrUnauthorized = errs.Class("unauthorized error") -// Authorization contains auth info of authorized User +// Authorization contains auth info of authorized User. type Authorization struct { User User Claims consoleauth.Claims } -// WithAuth creates new context with Authorization +// WithAuth creates new context with Authorization. func WithAuth(ctx context.Context, auth Authorization) context.Context { return context.WithValue(ctx, authKey, auth) } -// WithAuthFailure creates new context with authorization failure +// WithAuthFailure creates new context with authorization failure. func WithAuthFailure(ctx context.Context, err error) context.Context { return context.WithValue(ctx, authKey, err) } -// GetAuth gets Authorization from context +// GetAuth gets Authorization from context. func GetAuth(ctx context.Context) (Authorization, error) { value := ctx.Value(authKey) diff --git a/satellite/console/consoleauth/claims.go b/satellite/console/consoleauth/claims.go index 2952ea10e..0f022d9a1 100644 --- a/satellite/console/consoleauth/claims.go +++ b/satellite/console/consoleauth/claims.go @@ -13,14 +13,14 @@ import ( //TODO: change to JWT or Macaroon based auth -// Claims represents data signed by server and used for authentication +// Claims represents data signed by server and used for authentication. type Claims struct { ID uuid.UUID `json:"id"` Email string `json:"email,omitempty"` Expiration time.Time `json:"expires,omitempty"` } -// JSON returns json representation of Claims +// JSON returns json representation of Claims. func (c *Claims) JSON() ([]byte, error) { buffer := bytes.NewBuffer(nil) @@ -28,7 +28,7 @@ func (c *Claims) JSON() ([]byte, error) { return buffer.Bytes(), err } -// FromJSON returns Claims instance, parsed from JSON +// FromJSON returns Claims instance, parsed from JSON. func FromJSON(data []byte) (*Claims, error) { claims := new(Claims) diff --git a/satellite/console/consoleauth/hmac.go b/satellite/console/consoleauth/hmac.go index 0d31581f5..6ff670cde 100644 --- a/satellite/console/consoleauth/hmac.go +++ b/satellite/console/consoleauth/hmac.go @@ -10,12 +10,12 @@ import ( //TODO: change to JWT or Macaroon based auth -// Hmac is hmac256 based Signer +// Hmac is hmac256 based Signer. type Hmac struct { Secret []byte } -// Sign implements satellite signer +// Sign implements satellite signer. func (a *Hmac) Sign(data []byte) ([]byte, error) { mac := hmac.New(sha256.New, a.Secret) diff --git a/satellite/console/consoleauth/token.go b/satellite/console/consoleauth/token.go index 1162cae9a..ab6e4589b 100644 --- a/satellite/console/consoleauth/token.go +++ b/satellite/console/consoleauth/token.go @@ -14,7 +14,7 @@ import ( //TODO: change to JWT or Macaroon based auth -// Token represents authentication data structure +// Token represents authentication data structure. type Token struct { Payload []byte Signature []byte @@ -28,7 +28,7 @@ func (t Token) String() string { return strings.Join([]string{payload, signature}, ".") } -// FromBase64URLString creates Token instance from base64URLEncoded string representation +// FromBase64URLString creates Token instance from base64URLEncoded string representation. func FromBase64URLString(token string) (Token, error) { i := strings.Index(token, ".") if i < 0 { diff --git a/satellite/console/consoleweb/consoleql/apikey.go b/satellite/console/consoleweb/consoleql/apikey.go index e29fd77d6..3b5cb19b0 100644 --- a/satellite/console/consoleweb/consoleql/apikey.go +++ b/satellite/console/consoleweb/consoleql/apikey.go @@ -19,7 +19,7 @@ const ( FieldKey = "key" ) -// graphqlAPIKeyInfo creates satellite.APIKeyInfo graphql object +// graphqlAPIKeyInfo creates satellite.APIKeyInfo graphql object. func graphqlAPIKeyInfo() *graphql.Object { return graphql.NewObject(graphql.ObjectConfig{ Name: APIKeyInfoType, @@ -43,7 +43,7 @@ func graphqlAPIKeyInfo() *graphql.Object { }) } -// graphqlCreateAPIKey creates createAPIKey graphql object +// graphqlCreateAPIKey creates createAPIKey graphql object. func graphqlCreateAPIKey(types *TypeCreator) *graphql.Object { return graphql.NewObject(graphql.ObjectConfig{ Name: CreateAPIKeyType, @@ -116,7 +116,7 @@ func graphqlAPIKeysPage(types *TypeCreator) *graphql.Object { }) } -// createAPIKey holds macaroon.APIKey and console.APIKeyInfo +// createAPIKey holds macaroon.APIKey and console.APIKeyInfo. type createAPIKey struct { Key string KeyInfo *console.APIKeyInfo diff --git a/satellite/console/consoleweb/consoleql/mail.go b/satellite/console/consoleweb/consoleql/mail.go index c10fcba50..686b8acd5 100644 --- a/satellite/console/consoleweb/consoleql/mail.go +++ b/satellite/console/consoleweb/consoleql/mail.go @@ -20,7 +20,7 @@ const ( TermsAndConditionsURL = "termsAndConditionsURL" ) -// AccountActivationEmail is mailservice template with activation data +// AccountActivationEmail is mailservice template with activation data. type AccountActivationEmail struct { Origin string ActivationLink string @@ -29,13 +29,13 @@ type AccountActivationEmail struct { UserName string } -// Template returns email template name +// Template returns email template name. func (*AccountActivationEmail) Template() string { return "Welcome" } -// Subject gets email subject +// Subject gets email subject. func (*AccountActivationEmail) Subject() string { return "Activate your email" } -// ForgotPasswordEmail is mailservice template with reset password data +// ForgotPasswordEmail is mailservice template with reset password data. type ForgotPasswordEmail struct { Origin string UserName string @@ -46,13 +46,13 @@ type ForgotPasswordEmail struct { TermsAndConditionsURL string } -// Template returns email template name +// Template returns email template name. func (*ForgotPasswordEmail) Template() string { return "Forgot" } -// Subject gets email subject +// Subject gets email subject. func (*ForgotPasswordEmail) Subject() string { return "Password recovery request" } -// ProjectInvitationEmail is mailservice template for project invitation email +// ProjectInvitationEmail is mailservice template for project invitation email. type ProjectInvitationEmail struct { Origin string UserName string @@ -63,10 +63,10 @@ type ProjectInvitationEmail struct { TermsAndConditionsURL string } -// Template returns email template name +// Template returns email template name. func (*ProjectInvitationEmail) Template() string { return "Invite" } -// Subject gets email subject +// Subject gets email subject. func (email *ProjectInvitationEmail) Subject() string { return "You were invited to join the Project " + email.ProjectName } diff --git a/satellite/console/consoleweb/consoleql/mutation.go b/satellite/console/consoleweb/consoleql/mutation.go index cb21cc3e0..08038b394 100644 --- a/satellite/console/consoleweb/consoleql/mutation.go +++ b/satellite/console/consoleweb/consoleql/mutation.go @@ -53,7 +53,7 @@ const ( ReferrerUserID = "referrerUserId" ) -// rootMutation creates mutation for graphql populated by AccountsClient +// rootMutation creates mutation for graphql populated by AccountsClient. func rootMutation(log *zap.Logger, service *console.Service, mailService *mailservice.Service, types *TypeCreator) *graphql.Object { return graphql.NewObject(graphql.ObjectConfig{ Name: Mutation, diff --git a/satellite/console/consoleweb/consoleql/mutation_test.go b/satellite/console/consoleweb/consoleql/mutation_test.go index 82fc89428..a34319de6 100644 --- a/satellite/console/consoleweb/consoleql/mutation_test.go +++ b/satellite/console/consoleweb/consoleql/mutation_test.go @@ -32,15 +32,15 @@ import ( "storj.io/storj/storage/redis/redisserver" ) -// discardSender discard sending of an actual email +// discardSender discard sending of an actual email. type discardSender struct{} -// SendEmail immediately returns with nil error +// SendEmail immediately returns with nil error. func (*discardSender) SendEmail(ctx context.Context, msg *post.Message) error { return nil } -// FromAddress returns empty post.Address +// FromAddress returns empty post.Address. func (*discardSender) FromAddress() post.Address { return post.Address{} } diff --git a/satellite/console/consoleweb/consoleql/project.go b/satellite/console/consoleweb/consoleql/project.go index 5281f7c23..a2b288078 100644 --- a/satellite/console/consoleweb/consoleql/project.go +++ b/satellite/console/consoleweb/consoleql/project.go @@ -84,7 +84,7 @@ const ( BeforeArg = "before" ) -// graphqlProject creates *graphql.Object type representation of satellite.ProjectInfo +// graphqlProject creates *graphql.Object type representation of satellite.ProjectInfo. func graphqlProject(service *console.Service, types *TypeCreator) *graphql.Object { return graphql.NewObject(graphql.ObjectConfig{ Name: ProjectType, @@ -240,7 +240,7 @@ func graphqlProject(service *console.Service, types *TypeCreator) *graphql.Objec }) } -// graphqlProjectInput creates graphql.InputObject type needed to create/update satellite.Project +// graphqlProjectInput creates graphql.InputObject type needed to create/update satellite.Project. func graphqlProjectInput() *graphql.InputObject { return graphql.NewInputObject(graphql.InputObjectConfig{ Name: ProjectInputType, @@ -255,7 +255,7 @@ func graphqlProjectInput() *graphql.InputObject { }) } -// graphqlBucketUsageCursor creates bucket usage cursor graphql input type +// graphqlBucketUsageCursor creates bucket usage cursor graphql input type. func graphqlBucketUsageCursor() *graphql.InputObject { return graphql.NewInputObject(graphql.InputObjectConfig{ Name: BucketUsageCursorInputType, @@ -273,7 +273,7 @@ func graphqlBucketUsageCursor() *graphql.InputObject { }) } -// graphqlBucketUsage creates bucket usage grapqhl type +// graphqlBucketUsage creates bucket usage grapqhl type. func graphqlBucketUsage() *graphql.Object { return graphql.NewObject(graphql.ObjectConfig{ Name: BucketUsageType, @@ -300,7 +300,7 @@ func graphqlBucketUsage() *graphql.Object { }) } -// graphqlBucketUsagePage creates bucket usage page graphql object +// graphqlBucketUsagePage creates bucket usage page graphql object. func graphqlBucketUsagePage(types *TypeCreator) *graphql.Object { return graphql.NewObject(graphql.ObjectConfig{ Name: BucketUsagePageType, @@ -330,7 +330,7 @@ func graphqlBucketUsagePage(types *TypeCreator) *graphql.Object { }) } -// graphqlProjectUsage creates project usage graphql type +// graphqlProjectUsage creates project usage graphql type. func graphqlProjectUsage() *graphql.Object { return graphql.NewObject(graphql.ObjectConfig{ Name: ProjectUsageType, @@ -354,7 +354,7 @@ func graphqlProjectUsage() *graphql.Object { }) } -// fromMapProjectInfo creates console.ProjectInfo from input args +// fromMapProjectInfo creates console.ProjectInfo from input args. func fromMapProjectInfo(args map[string]interface{}) (project console.ProjectInfo) { project.Name, _ = args[FieldName].(string) project.Description, _ = args[FieldDescription].(string) @@ -362,7 +362,7 @@ func fromMapProjectInfo(args map[string]interface{}) (project console.ProjectInf return } -// fromMapBucketUsageCursor creates console.BucketUsageCursor from input args +// fromMapBucketUsageCursor creates console.BucketUsageCursor from input args. func fromMapBucketUsageCursor(args map[string]interface{}) (cursor accounting.BucketUsageCursor) { limit, _ := args[LimitArg].(int) page, _ := args[PageArg].(int) diff --git a/satellite/console/consoleweb/consoleql/projectmember.go b/satellite/console/consoleweb/consoleql/projectmember.go index a733a6873..ed6bdb733 100644 --- a/satellite/console/consoleweb/consoleql/projectmember.go +++ b/satellite/console/consoleweb/consoleql/projectmember.go @@ -18,7 +18,7 @@ const ( FieldJoinedAt = "joinedAt" ) -// graphqlProjectMember creates projectMember type +// graphqlProjectMember creates projectMember type. func graphqlProjectMember(service *console.Service, types *TypeCreator) *graphql.Object { return graphql.NewObject(graphql.ObjectConfig{ Name: ProjectMemberType, @@ -96,7 +96,7 @@ func graphqlProjectMembersPage(types *TypeCreator) *graphql.Object { }) } -// projectMember encapsulates User and joinedAt +// projectMember encapsulates User and joinedAt. type projectMember struct { User *console.User JoinedAt time.Time diff --git a/satellite/console/consoleweb/consoleql/query.go b/satellite/console/consoleweb/consoleql/query.go index 9575f846d..24d3cea30 100644 --- a/satellite/console/consoleweb/consoleql/query.go +++ b/satellite/console/consoleweb/consoleql/query.go @@ -25,7 +25,7 @@ const ( CreditUsageQuery = "creditUsage" ) -// rootQuery creates query for graphql populated by AccountsClient +// rootQuery creates query for graphql populated by AccountsClient. func rootQuery(service *console.Service, mailService *mailservice.Service, types *TypeCreator) *graphql.Object { return graphql.NewObject(graphql.ObjectConfig{ Name: Query, diff --git a/satellite/console/consoleweb/consoleql/schema.go b/satellite/console/consoleweb/consoleql/schema.go index 462c9d3cc..553a64802 100644 --- a/satellite/console/consoleweb/consoleql/schema.go +++ b/satellite/console/consoleweb/consoleql/schema.go @@ -11,7 +11,7 @@ import ( "storj.io/storj/satellite/mailservice" ) -// CreateSchema creates a schema for satellites console graphql api +// CreateSchema creates a schema for satellites console graphql api. func CreateSchema(log *zap.Logger, service *console.Service, mailService *mailservice.Service) (schema graphql.Schema, err error) { creator := TypeCreator{} diff --git a/satellite/console/consoleweb/consoleql/typecreator.go b/satellite/console/consoleweb/consoleql/typecreator.go index 242e4ba48..12d20493a 100644 --- a/satellite/console/consoleweb/consoleql/typecreator.go +++ b/satellite/console/consoleweb/consoleql/typecreator.go @@ -11,7 +11,7 @@ import ( "storj.io/storj/satellite/mailservice" ) -// TypeCreator handles graphql type creation and error checking +// TypeCreator handles graphql type creation and error checking. type TypeCreator struct { query *graphql.Object mutation *graphql.Object @@ -36,7 +36,7 @@ type TypeCreator struct { apiKeysCursor *graphql.InputObject } -// Create create types and check for error +// Create create types and check for error. func (c *TypeCreator) Create(log *zap.Logger, service *console.Service, mailService *mailservice.Service) error { // inputs c.userInput = graphqlUserInput() @@ -139,12 +139,12 @@ func (c *TypeCreator) Create(log *zap.Logger, service *console.Service, mailServ return nil } -// RootQuery returns instance of query *graphql.Object +// RootQuery returns instance of query *graphql.Object. func (c *TypeCreator) RootQuery() *graphql.Object { return c.query } -// RootMutation returns instance of mutation *graphql.Object +// RootMutation returns instance of mutation *graphql.Object. func (c *TypeCreator) RootMutation() *graphql.Object { return c.mutation } diff --git a/satellite/console/consoleweb/consoleql/user.go b/satellite/console/consoleweb/consoleql/user.go index c1b3348c6..b2024e396 100644 --- a/satellite/console/consoleweb/consoleql/user.go +++ b/satellite/console/consoleweb/consoleql/user.go @@ -28,7 +28,7 @@ const ( FieldPartnerID = "partnerId" ) -// base graphql config for user +// base graphql config for user. func baseUserConfig() graphql.ObjectConfig { return graphql.ObjectConfig{ Name: UserType, @@ -56,12 +56,12 @@ func baseUserConfig() graphql.ObjectConfig { } // graphqlUser creates *graphql.Object type representation of satellite.User -// TODO: simplify +// TODO: simplify. func graphqlUser() *graphql.Object { return graphql.NewObject(baseUserConfig()) } -// graphqlUserInput creates graphql.InputObject type needed to register/update satellite.User +// graphqlUserInput creates graphql.InputObject type needed to register/update satellite.User. func graphqlUserInput() *graphql.InputObject { return graphql.NewInputObject(graphql.InputObjectConfig{ Name: UserInputType, diff --git a/satellite/console/consoleweb/server.go b/satellite/console/consoleweb/server.go index 63c0c7127..0af57fd14 100644 --- a/satellite/console/consoleweb/server.go +++ b/satellite/console/consoleweb/server.go @@ -55,7 +55,7 @@ var ( mon = monkit.Package() ) -// Config contains configuration for console web server +// Config contains configuration for console web server. type Config struct { Address string `help:"server address of the graphql api gateway and frontend app" devDefault:"127.0.0.1:8081" releaseDefault:":10100"` StaticDir string `help:"path to static resources" default:""` @@ -243,12 +243,12 @@ func (server *Server) Run(ctx context.Context) (err error) { return group.Wait() } -// Close closes server and underlying listener +// Close closes server and underlying listener. func (server *Server) Close() error { return server.server.Close() } -// appHandler is web app http handler function +// appHandler is web app http handler function. func (server *Server) appHandler(w http.ResponseWriter, r *http.Request) { header := w.Header() @@ -461,7 +461,7 @@ func (server *Server) populatePromotionalCoupons(w http.ResponseWriter, r *http. } } -// accountActivationHandler is web app http handler function +// accountActivationHandler is web app http handler function. func (server *Server) accountActivationHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() defer mon.Task()(&ctx)(nil) @@ -612,7 +612,7 @@ func (server *Server) projectUsageLimitsHandler(w http.ResponseWriter, r *http.R } } -// grapqlHandler is graphql endpoint http handler function +// grapqlHandler is graphql endpoint http handler function. func (server *Server) grapqlHandler(w http.ResponseWriter, r *http.Request) { ctx := r.Context() defer mon.Task()(&ctx)(nil) @@ -748,7 +748,7 @@ func (server *Server) serveError(w http.ResponseWriter, status int) { } } -// seoHandler used to communicate with web crawlers and other web robots +// seoHandler used to communicate with web crawlers and other web robots. func (server *Server) seoHandler(w http.ResponseWriter, req *http.Request) { header := w.Header() @@ -793,7 +793,7 @@ func (server *Server) gzipMiddleware(fn http.Handler) http.Handler { }) } -// initializeTemplates is used to initialize all templates +// initializeTemplates is used to initialize all templates. func (server *Server) initializeTemplates() (err error) { server.templates.index, err = template.ParseFiles(filepath.Join(server.config.StaticDir, "dist", "index.html")) if err != nil { diff --git a/satellite/console/consoleweb/utils.go b/satellite/console/consoleweb/utils.go index 270808885..089fd1a13 100644 --- a/satellite/console/consoleweb/utils.go +++ b/satellite/console/consoleweb/utils.go @@ -15,7 +15,7 @@ import ( "storj.io/storj/satellite/console/consoleweb/consoleql" ) -// ContentLengthLimit describes 4KB limit +// ContentLengthLimit describes 4KB limit. const ContentLengthLimit = 4 * memory.KB func init() { @@ -30,14 +30,14 @@ func init() { } } -// JSON request from graphql clients +// JSON request from graphql clients. type graphqlJSON struct { Query string OperationName string Variables map[string]interface{} } -// getQuery retrieves graphql query from request +// getQuery retrieves graphql query from request. func getQuery(w http.ResponseWriter, req *http.Request) (query graphqlJSON, err error) { switch req.Method { case http.MethodGet: @@ -50,7 +50,7 @@ func getQuery(w http.ResponseWriter, req *http.Request) (query graphqlJSON, err } } -// queryPOST retrieves graphql query from POST request +// queryPOST retrieves graphql query from POST request. func queryPOST(w http.ResponseWriter, req *http.Request) (query graphqlJSON, err error) { limitedReader := http.MaxBytesReader(w, req.Body, ContentLengthLimit.Int64()) switch typ := req.Header.Get(contentType); typ { diff --git a/satellite/console/projectmembers.go b/satellite/console/projectmembers.go index b70883724..707889ff2 100644 --- a/satellite/console/projectmembers.go +++ b/satellite/console/projectmembers.go @@ -34,7 +34,7 @@ type ProjectMember struct { CreatedAt time.Time } -// ProjectMembersCursor holds info for project members cursor pagination +// ProjectMembersCursor holds info for project members cursor pagination. type ProjectMembersCursor struct { Search string Limit uint @@ -43,7 +43,7 @@ type ProjectMembersCursor struct { OrderDirection OrderDirection } -// ProjectMembersPage represent project members page result +// ProjectMembersPage represent project members page result. type ProjectMembersPage struct { ProjectMembers []ProjectMember @@ -58,7 +58,7 @@ type ProjectMembersPage struct { TotalCount uint64 } -// ProjectMemberOrder is used for querying project members in specified order +// ProjectMemberOrder is used for querying project members in specified order. type ProjectMemberOrder int8 const ( diff --git a/satellite/console/projects.go b/satellite/console/projects.go index 4ded1b1de..d6be27e16 100644 --- a/satellite/console/projects.go +++ b/satellite/console/projects.go @@ -42,7 +42,7 @@ type Projects interface { UpdateBucketLimit(ctx context.Context, id uuid.UUID, newLimit int) error } -// Project is a database object that describes Project entity +// Project is a database object that describes Project entity. type Project struct { ID uuid.UUID `json:"id"` @@ -55,7 +55,7 @@ type Project struct { CreatedAt time.Time `json:"createdAt"` } -// ProjectInfo holds data needed to create/update Project +// ProjectInfo holds data needed to create/update Project. type ProjectInfo struct { Name string `json:"name"` Description string `json:"description"` diff --git a/satellite/console/registrationtoken.go b/satellite/console/registrationtoken.go index b98ad24b0..2e149dac0 100644 --- a/satellite/console/registrationtoken.go +++ b/satellite/console/registrationtoken.go @@ -29,10 +29,10 @@ type RegistrationTokens interface { UpdateOwner(ctx context.Context, secret RegistrationSecret, ownerID uuid.UUID) error } -// RegistrationSecret stores secret of registration token +// RegistrationSecret stores secret of registration token. type RegistrationSecret [32]byte -// RegistrationToken describing api key model in the database +// RegistrationToken describing api key model in the database. type RegistrationToken struct { // Secret is PK of the table and keeps unique value forRegToken Secret RegistrationSecret @@ -45,7 +45,7 @@ type RegistrationToken struct { CreatedAt time.Time `json:"createdAt"` } -// NewRegistrationSecret creates new registration secret +// NewRegistrationSecret creates new registration secret. func NewRegistrationSecret() (RegistrationSecret, error) { var b [32]byte @@ -57,12 +57,12 @@ func NewRegistrationSecret() (RegistrationSecret, error) { return b, nil } -// String implements Stringer +// String implements Stringer. func (secret RegistrationSecret) String() string { return base64.URLEncoding.EncodeToString(secret[:]) } -// IsZero returns if the RegistrationSecret is not set +// IsZero returns if the RegistrationSecret is not set. func (secret RegistrationSecret) IsZero() bool { var zero RegistrationSecret // this doesn't need to be constant-time, because we're explicitly testing @@ -70,7 +70,7 @@ func (secret RegistrationSecret) IsZero() bool { return bytes.Equal(secret[:], zero[:]) } -// RegistrationSecretFromBase64 creates new registration secret from base64 string +// RegistrationSecretFromBase64 creates new registration secret from base64 string. func RegistrationSecretFromBase64(s string) (RegistrationSecret, error) { var secret RegistrationSecret diff --git a/satellite/console/resetpasswordtoken.go b/satellite/console/resetpasswordtoken.go index ba89adea4..9f1bc612b 100644 --- a/satellite/console/resetpasswordtoken.go +++ b/satellite/console/resetpasswordtoken.go @@ -28,10 +28,10 @@ type ResetPasswordTokens interface { Delete(ctx context.Context, secret ResetPasswordSecret) error } -// ResetPasswordSecret stores secret of registration token +// ResetPasswordSecret stores secret of registration token. type ResetPasswordSecret [32]byte -// ResetPasswordToken describing reset password model in the database +// ResetPasswordToken describing reset password model in the database. type ResetPasswordToken struct { // Secret is PK of the table and keeps unique value for reset password token Secret ResetPasswordSecret @@ -41,7 +41,7 @@ type ResetPasswordToken struct { CreatedAt time.Time `json:"createdAt"` } -// NewResetPasswordSecret creates new reset password secret +// NewResetPasswordSecret creates new reset password secret. func NewResetPasswordSecret() (ResetPasswordSecret, error) { var b [32]byte @@ -53,12 +53,12 @@ func NewResetPasswordSecret() (ResetPasswordSecret, error) { return b, nil } -// String implements Stringer +// String implements Stringer. func (secret ResetPasswordSecret) String() string { return base64.URLEncoding.EncodeToString(secret[:]) } -// ResetPasswordSecretFromBase64 creates new reset password secret from base64 string +// ResetPasswordSecretFromBase64 creates new reset password secret from base64 string. func ResetPasswordSecretFromBase64(s string) (ResetPasswordSecret, error) { var secret ResetPasswordSecret diff --git a/satellite/console/service.go b/satellite/console/service.go index 98bf55a53..527bb80b3 100644 --- a/satellite/console/service.go +++ b/satellite/console/service.go @@ -37,7 +37,7 @@ const ( TestPasswordCost = bcrypt.MinCost ) -// Error messages +// Error messages. const ( unauthorizedErrMsg = "You are not authorized to perform this action" emailUsedErrMsg = "This email is already in use, try another" @@ -89,14 +89,14 @@ type Service struct { minCoinPayment int64 } -// Config keeps track of core console service configuration parameters +// Config keeps track of core console service configuration parameters. type Config struct { PasswordCost int `help:"password hashing cost (0=automatic)" internal:"true" default:"0"` OpenRegistrationEnabled bool `help:"enable open registration" default:"false"` DefaultProjectLimit int `help:"default project limits for users" default:"1"` } -// PaymentsService separates all payment related functionality +// PaymentsService separates all payment related functionality. type PaymentsService struct { service *Service } @@ -436,7 +436,7 @@ func (s *Service) checkRegistrationSecret(ctx context.Context, tokenSecret Regis return registrationToken, nil } -// CreateUser gets password hash value and creates new inactive User +// CreateUser gets password hash value and creates new inactive User. func (s *Service) CreateUser(ctx context.Context, user CreateUser, tokenSecret RegistrationSecret, refUserID string) (u *User, err error) { defer mon.Task()(&ctx)(&err) if err := user.IsValid(); err != nil { @@ -551,7 +551,7 @@ func (s *Service) CreateUser(ctx context.Context, user CreateUser, tokenSecret R return u, nil } -// GenerateActivationToken - is a method for generating activation token +// GenerateActivationToken - is a method for generating activation token. func (s *Service) GenerateActivationToken(ctx context.Context, id uuid.UUID, email string) (token string, err error) { defer mon.Task()(&ctx)(&err) @@ -565,7 +565,7 @@ func (s *Service) GenerateActivationToken(ctx context.Context, id uuid.UUID, ema return s.createToken(ctx, claims) } -// GeneratePasswordRecoveryToken - is a method for generating password recovery token +// GeneratePasswordRecoveryToken - is a method for generating password recovery token. func (s *Service) GeneratePasswordRecoveryToken(ctx context.Context, id uuid.UUID) (token string, err error) { defer mon.Task()(&ctx)(&err) @@ -585,7 +585,7 @@ func (s *Service) GeneratePasswordRecoveryToken(ctx context.Context, id uuid.UUI return resetPasswordToken.Secret.String(), nil } -// ActivateAccount - is a method for activating user account after registration +// ActivateAccount - is a method for activating user account after registration. func (s *Service) ActivateAccount(ctx context.Context, activationToken string) (err error) { defer mon.Task()(&ctx)(&err) @@ -629,7 +629,7 @@ func (s *Service) ActivateAccount(ctx context.Context, activationToken string) ( return nil } -// ResetPassword - is a method for reseting user password +// ResetPassword - is a method for reseting user password. func (s *Service) ResetPassword(ctx context.Context, resetPasswordToken, password string) (err error) { defer mon.Task()(&ctx)(&err) @@ -674,7 +674,7 @@ func (s *Service) ResetPassword(ctx context.Context, resetPasswordToken, passwor return nil } -// RevokeResetPasswordToken - is a method to revoke reset password token +// RevokeResetPasswordToken - is a method to revoke reset password token. func (s *Service) RevokeResetPasswordToken(ctx context.Context, resetPasswordToken string) (err error) { defer mon.Task()(&ctx)(&err) @@ -686,7 +686,7 @@ func (s *Service) RevokeResetPasswordToken(ctx context.Context, resetPasswordTok return s.store.ResetPasswordTokens().Delete(ctx, secret) } -// Token authenticates User by credentials and returns auth token +// Token authenticates User by credentials and returns auth token. func (s *Service) Token(ctx context.Context, email, password string) (token string, err error) { defer mon.Task()(&ctx)(&err) @@ -713,7 +713,7 @@ func (s *Service) Token(ctx context.Context, email, password string) (token stri return token, nil } -// GetUser returns User by id +// GetUser returns User by id. func (s *Service) GetUser(ctx context.Context, id uuid.UUID) (u *User, err error) { defer mon.Task()(&ctx)(&err) @@ -725,7 +725,7 @@ func (s *Service) GetUser(ctx context.Context, id uuid.UUID) (u *User, err error return user, nil } -// GetUserByEmail returns User by email +// GetUserByEmail returns User by email. func (s *Service) GetUserByEmail(ctx context.Context, email string) (u *User, err error) { defer mon.Task()(&ctx)(&err) @@ -737,7 +737,7 @@ func (s *Service) GetUserByEmail(ctx context.Context, email string) (u *User, er return result, nil } -// UpdateAccount updates User +// UpdateAccount updates User. func (s *Service) UpdateAccount(ctx context.Context, fullName string, shortName string) (err error) { defer mon.Task()(&ctx)(&err) auth, err := GetAuth(ctx) @@ -766,7 +766,7 @@ func (s *Service) UpdateAccount(ctx context.Context, fullName string, shortName return nil } -// ChangePassword updates password for a given user +// ChangePassword updates password for a given user. func (s *Service) ChangePassword(ctx context.Context, pass, newPass string) (err error) { defer mon.Task()(&ctx)(&err) auth, err := GetAuth(ctx) @@ -797,7 +797,7 @@ func (s *Service) ChangePassword(ctx context.Context, pass, newPass string) (err return nil } -// DeleteAccount deletes User +// DeleteAccount deletes User. func (s *Service) DeleteAccount(ctx context.Context, password string) (err error) { defer mon.Task()(&ctx)(&err) auth, err := GetAuth(ctx) @@ -818,7 +818,7 @@ func (s *Service) DeleteAccount(ctx context.Context, password string) (err error return nil } -// GetProject is a method for querying project by id +// GetProject is a method for querying project by id. func (s *Service) GetProject(ctx context.Context, projectID uuid.UUID) (p *Project, err error) { defer mon.Task()(&ctx)(&err) _, err = GetAuth(ctx) @@ -834,7 +834,7 @@ func (s *Service) GetProject(ctx context.Context, projectID uuid.UUID) (p *Proje return } -// GetUsersProjects is a method for querying all projects +// GetUsersProjects is a method for querying all projects. func (s *Service) GetUsersProjects(ctx context.Context) (ps []Project, err error) { defer mon.Task()(&ctx)(&err) auth, err := GetAuth(ctx) @@ -850,7 +850,7 @@ func (s *Service) GetUsersProjects(ctx context.Context) (ps []Project, err error return } -// GetCurrentRewardByType is a method for querying current active reward offer based on its type +// GetCurrentRewardByType is a method for querying current active reward offer based on its type. func (s *Service) GetCurrentRewardByType(ctx context.Context, offerType rewards.OfferType) (offer *rewards.Offer, err error) { defer mon.Task()(&ctx)(&err) @@ -868,7 +868,7 @@ func (s *Service) GetCurrentRewardByType(ctx context.Context, offerType rewards. return result, nil } -// GetUserCreditUsage is a method for querying users' credit information up until now +// GetUserCreditUsage is a method for querying users' credit information up until now. func (s *Service) GetUserCreditUsage(ctx context.Context) (usage *UserCreditUsage, err error) { defer mon.Task()(&ctx)(&err) auth, err := GetAuth(ctx) @@ -884,7 +884,7 @@ func (s *Service) GetUserCreditUsage(ctx context.Context) (usage *UserCreditUsag return usage, nil } -// CreateProject is a method for creating new project +// CreateProject is a method for creating new project. func (s *Service) CreateProject(ctx context.Context, projectInfo ProjectInfo) (p *Project, err error) { defer mon.Task()(&ctx)(&err) auth, err := GetAuth(ctx) @@ -947,7 +947,7 @@ func (s *Service) CreateProject(ctx context.Context, projectInfo ProjectInfo) (p return p, nil } -// DeleteProject is a method for deleting project by id +// DeleteProject is a method for deleting project by id. func (s *Service) DeleteProject(ctx context.Context, projectID uuid.UUID) (err error) { defer mon.Task()(&ctx)(&err) auth, err := GetAuth(ctx) @@ -967,7 +967,7 @@ func (s *Service) DeleteProject(ctx context.Context, projectID uuid.UUID) (err e return nil } -// UpdateProject is a method for updating project description by id +// UpdateProject is a method for updating project description by id. func (s *Service) UpdateProject(ctx context.Context, projectID uuid.UUID, description string) (p *Project, err error) { defer mon.Task()(&ctx)(&err) auth, err := GetAuth(ctx) @@ -995,7 +995,7 @@ func (s *Service) UpdateProject(ctx context.Context, projectID uuid.UUID, descri return project, nil } -// AddProjectMembers adds users by email to given project +// AddProjectMembers adds users by email to given project. func (s *Service) AddProjectMembers(ctx context.Context, projectID uuid.UUID, emails []string) (users []*User, err error) { defer mon.Task()(&ctx)(&err) auth, err := GetAuth(ctx) @@ -1044,7 +1044,7 @@ func (s *Service) AddProjectMembers(ctx context.Context, projectID uuid.UUID, em return users, nil } -// DeleteProjectMembers removes users by email from given project +// DeleteProjectMembers removes users by email from given project. func (s *Service) DeleteProjectMembers(ctx context.Context, projectID uuid.UUID, emails []string) (err error) { defer mon.Task()(&ctx)(&err) _, err = GetAuth(ctx) @@ -1094,7 +1094,7 @@ func (s *Service) DeleteProjectMembers(ctx context.Context, projectID uuid.UUID, return Error.Wrap(err) } -// GetProjectMembers returns ProjectMembers for given Project +// GetProjectMembers returns ProjectMembers for given Project. func (s *Service) GetProjectMembers(ctx context.Context, projectID uuid.UUID, cursor ProjectMembersCursor) (pmp *ProjectMembersPage, err error) { defer mon.Task()(&ctx)(&err) auth, err := GetAuth(ctx) @@ -1123,7 +1123,7 @@ func (s *Service) GetProjectMembers(ctx context.Context, projectID uuid.UUID, cu return } -// CreateAPIKey creates new api key +// CreateAPIKey creates new api key. func (s *Service) CreateAPIKey(ctx context.Context, projectID uuid.UUID, name string) (_ *APIKeyInfo, _ *macaroon.APIKey, err error) { defer mon.Task()(&ctx)(&err) @@ -1167,7 +1167,7 @@ func (s *Service) CreateAPIKey(ctx context.Context, projectID uuid.UUID, name st return info, key, nil } -// GetAPIKeyInfo retrieves api key by id +// GetAPIKeyInfo retrieves api key by id. func (s *Service) GetAPIKeyInfo(ctx context.Context, id uuid.UUID) (_ *APIKeyInfo, err error) { defer mon.Task()(&ctx)(&err) @@ -1189,7 +1189,7 @@ func (s *Service) GetAPIKeyInfo(ctx context.Context, id uuid.UUID) (_ *APIKeyInf return key, nil } -// DeleteAPIKeys deletes api key by id +// DeleteAPIKeys deletes api key by id. func (s *Service) DeleteAPIKeys(ctx context.Context, ids []uuid.UUID) (err error) { defer mon.Task()(&ctx)(&err) auth, err := GetAuth(ctx) @@ -1230,7 +1230,7 @@ func (s *Service) DeleteAPIKeys(ctx context.Context, ids []uuid.UUID) (err error return Error.Wrap(err) } -// GetAPIKeys returns paged api key list for given Project +// GetAPIKeys returns paged api key list for given Project. func (s *Service) GetAPIKeys(ctx context.Context, projectID uuid.UUID, cursor APIKeyCursor) (page *APIKeyPage, err error) { defer mon.Task()(&ctx)(&err) @@ -1256,7 +1256,7 @@ func (s *Service) GetAPIKeys(ctx context.Context, projectID uuid.UUID, cursor AP return } -// GetProjectUsage retrieves project usage for a given period +// GetProjectUsage retrieves project usage for a given period. func (s *Service) GetProjectUsage(ctx context.Context, projectID uuid.UUID, since, before time.Time) (_ *accounting.ProjectUsage, err error) { defer mon.Task()(&ctx)(&err) @@ -1278,7 +1278,7 @@ func (s *Service) GetProjectUsage(ctx context.Context, projectID uuid.UUID, sinc return projectUsage, nil } -// GetBucketTotals retrieves paged bucket total usages since project creation +// GetBucketTotals retrieves paged bucket total usages since project creation. func (s *Service) GetBucketTotals(ctx context.Context, projectID uuid.UUID, cursor accounting.BucketUsageCursor, before time.Time) (_ *accounting.BucketUsagePage, err error) { defer mon.Task()(&ctx)(&err) @@ -1300,7 +1300,7 @@ func (s *Service) GetBucketTotals(ctx context.Context, projectID uuid.UUID, curs return usage, nil } -// GetBucketUsageRollups retrieves summed usage rollups for every bucket of particular project for a given period +// GetBucketUsageRollups retrieves summed usage rollups for every bucket of particular project for a given period. func (s *Service) GetBucketUsageRollups(ctx context.Context, projectID uuid.UUID, since, before time.Time) (_ []accounting.BucketUsageRollup, err error) { defer mon.Task()(&ctx)(&err) @@ -1357,7 +1357,7 @@ func (s *Service) GetProjectUsageLimits(ctx context.Context, projectID uuid.UUID }, nil } -// Authorize validates token from context and returns authorized Authorization +// Authorize validates token from context and returns authorized Authorization. func (s *Service) Authorize(ctx context.Context) (a Authorization, err error) { defer mon.Task()(&ctx)(&err) tokenS, ok := auth.GetAPIKey(ctx) @@ -1386,7 +1386,7 @@ func (s *Service) Authorize(ctx context.Context) (a Authorization, err error) { }, nil } -// checkProjectLimit is used to check if user is able to create a new project +// checkProjectLimit is used to check if user is able to create a new project. func (s *Service) checkProjectLimit(ctx context.Context, userID uuid.UUID) (err error) { defer mon.Task()(&ctx)(&err) @@ -1410,7 +1410,7 @@ func (s *Service) checkProjectLimit(ctx context.Context, userID uuid.UUID) (err return nil } -// CreateRegToken creates new registration token. Needed for testing +// CreateRegToken creates new registration token. Needed for testing. func (s *Service) CreateRegToken(ctx context.Context, projLimit int) (_ *RegistrationToken, err error) { defer mon.Task()(&ctx)(&err) result, err := s.store.RegistrationTokens().Create(ctx, projLimit) @@ -1421,7 +1421,7 @@ func (s *Service) CreateRegToken(ctx context.Context, projLimit int) (_ *Registr return result, nil } -// createToken creates string representation +// createToken creates string representation. func (s *Service) createToken(ctx context.Context, claims *consoleauth.Claims) (_ string, err error) { defer mon.Task()(&ctx)(&err) @@ -1439,7 +1439,7 @@ func (s *Service) createToken(ctx context.Context, claims *consoleauth.Claims) ( return token.String(), nil } -// authenticate validates token signature and returns authenticated *satelliteauth.Authorization +// authenticate validates token signature and returns authenticated *satelliteauth.Authorization. func (s *Service) authenticate(ctx context.Context, token consoleauth.Token) (_ *consoleauth.Claims, err error) { defer mon.Task()(&ctx)(&err) signature := token.Signature @@ -1461,7 +1461,7 @@ func (s *Service) authenticate(ctx context.Context, token consoleauth.Token) (_ return claims, nil } -// authorize checks claims and returns authorized User +// authorize checks claims and returns authorized User. func (s *Service) authorize(ctx context.Context, claims *consoleauth.Claims) (_ *User, err error) { defer mon.Task()(&ctx)(&err) if !claims.Expiration.IsZero() && claims.Expiration.Before(time.Now()) { @@ -1476,13 +1476,13 @@ func (s *Service) authorize(ctx context.Context, claims *consoleauth.Claims) (_ return user, nil } -// isProjectMember is return type of isProjectMember service method +// isProjectMember is return type of isProjectMember service method. type isProjectMember struct { project *Project membership *ProjectMember } -// isProjectOwner checks if the user is an owner of a project +// isProjectOwner checks if the user is an owner of a project. func (s *Service) isProjectOwner(ctx context.Context, userID uuid.UUID, projectID uuid.UUID) (err error) { defer mon.Task()(&ctx)(&err) project, err := s.store.Projects().Get(ctx, projectID) @@ -1497,7 +1497,7 @@ func (s *Service) isProjectOwner(ctx context.Context, userID uuid.UUID, projectI return nil } -// isProjectMember checks if the user is a member of given project +// isProjectMember checks if the user is a member of given project. func (s *Service) isProjectMember(ctx context.Context, userID uuid.UUID, projectID uuid.UUID) (result isProjectMember, err error) { defer mon.Task()(&ctx)(&err) project, err := s.store.Projects().Get(ctx, projectID) diff --git a/satellite/console/sortdirection.go b/satellite/console/sortdirection.go index cbbdaaf86..3c12f6706 100644 --- a/satellite/console/sortdirection.go +++ b/satellite/console/sortdirection.go @@ -3,7 +3,7 @@ package console -// OrderDirection is used for members in specific order direction +// OrderDirection is used for members in specific order direction. type OrderDirection uint8 const ( diff --git a/satellite/console/usercredits.go b/satellite/console/usercredits.go index 8a6ca0ea6..3e563755e 100644 --- a/satellite/console/usercredits.go +++ b/satellite/console/usercredits.go @@ -14,7 +14,7 @@ import ( "storj.io/storj/satellite/rewards" ) -// NoCreditForUpdateErr is a error message used when no credits are found for update when new users sign up +// NoCreditForUpdateErr is a error message used when no credits are found for update when new users sign up. var NoCreditForUpdateErr = errs.Class("no credit found to update") // UserCredits holds information to interact with database @@ -27,7 +27,7 @@ type UserCredits interface { UpdateAvailableCredits(ctx context.Context, creditsToCharge int, id uuid.UUID, billingStartDate time.Time) (remainingCharge int, err error) } -// CreditType indicates a type of a credit +// CreditType indicates a type of a credit. type CreditType string const ( @@ -37,7 +37,7 @@ const ( Referrer CreditType = "referrer" ) -// UserCredit holds information about an user's credit +// UserCredit holds information about an user's credit. type UserCredit struct { ID int UserID uuid.UUID @@ -50,14 +50,14 @@ type UserCredit struct { CreatedAt time.Time } -// UserCreditUsage holds information about credit usage information +// UserCreditUsage holds information about credit usage information. type UserCreditUsage struct { Referred int64 AvailableCredits currency.USD UsedCredits currency.USD } -// CreateCredit holds information that's needed when create a new record of user credit +// CreateCredit holds information that's needed when create a new record of user credit. type CreateCredit struct { OfferInfo rewards.RedeemOffer UserID uuid.UUID @@ -68,7 +68,7 @@ type CreateCredit struct { ExpiresAt time.Time } -// NewCredit returns a new credit data +// NewCredit returns a new credit data. func NewCredit(currentReward *rewards.Offer, creditType CreditType, userID uuid.UUID, referrerID *uuid.UUID) (*CreateCredit, error) { var creditEarned currency.USD switch creditType { diff --git a/satellite/console/users.go b/satellite/console/users.go index bfcaba08c..1fb9bf7a4 100644 --- a/satellite/console/users.go +++ b/satellite/console/users.go @@ -77,7 +77,7 @@ func (user *CreateUser) IsValid() error { return errs.Combine() } -// UserStatus - is used to indicate status of the users account +// UserStatus - is used to indicate status of the users account. type UserStatus int const ( diff --git a/satellite/console/users_test.go b/satellite/console/users_test.go index 37b09aa9f..ba50fa245 100644 --- a/satellite/console/users_test.go +++ b/satellite/console/users_test.go @@ -17,7 +17,7 @@ import ( "storj.io/storj/satellite/satellitedb/satellitedbtest" ) -//testing constants +//testing constants. const ( lastName = "lastName" email = "email@mail.test" diff --git a/satellite/console/validation.go b/satellite/console/validation.go index a0bc1e48a..f0ff42d02 100644 --- a/satellite/console/validation.go +++ b/satellite/console/validation.go @@ -11,10 +11,10 @@ const ( passMinLength = 6 ) -// ErrValidation validation related error class +// ErrValidation validation related error class. var ErrValidation = errs.Class("validation error") -// validationError is slice of ErrValidation class errors +// validationError is slice of ErrValidation class errors. type validationErrors []error // Addf adds a new ErrValidation error to validation. @@ -22,17 +22,17 @@ func (validation *validationErrors) Addf(format string, args ...interface{}) { *validation = append(*validation, ErrValidation.New(format, args...)) } -// AddWrap adds new ErrValidation wrapped err +// AddWrap adds new ErrValidation wrapped err. func (validation *validationErrors) AddWrap(err error) { *validation = append(*validation, ErrValidation.Wrap(err)) } -// Combine returns combined validation errors +// Combine returns combined validation errors. func (validation *validationErrors) Combine() error { return errs.Combine(*validation...) } -// ValidatePassword validates password +// ValidatePassword validates password. func ValidatePassword(pass string) error { var errs validationErrors diff --git a/satellite/contact/client.go b/satellite/contact/client.go index 0b392a1a1..c982c7311 100644 --- a/satellite/contact/client.go +++ b/satellite/contact/client.go @@ -16,7 +16,7 @@ type client struct { client pb.DRPCContactClient } -// dialNodeURL dials the target contact endpoint +// dialNodeURL dials the target contact endpoint. func dialNodeURL(ctx context.Context, dialer rpc.Dialer, nodeurl storj.NodeURL) (*client, error) { conn, err := dialer.DialNodeURL(ctx, nodeurl) if err != nil { @@ -29,12 +29,12 @@ func dialNodeURL(ctx context.Context, dialer rpc.Dialer, nodeurl storj.NodeURL) }, nil } -// pingNode pings a node +// pingNode pings a node. func (client *client) pingNode(ctx context.Context, req *pb.ContactPingRequest) (*pb.ContactPingResponse, error) { return client.client.PingNode(ctx, req) } -// Close closes the connection +// Close closes the connection. func (client *client) Close() error { return client.conn.Close() } diff --git a/satellite/contact/endpoint.go b/satellite/contact/endpoint.go index 66bc4a2ca..ce5fe326d 100644 --- a/satellite/contact/endpoint.go +++ b/satellite/contact/endpoint.go @@ -104,7 +104,7 @@ func (endpoint *Endpoint) CheckIn(ctx context.Context, req *pb.CheckInRequest) ( }, nil } -// GetTime returns current timestamp +// GetTime returns current timestamp. func (endpoint *Endpoint) GetTime(ctx context.Context, req *pb.GetTimeRequest) (_ *pb.GetTimeResponse, err error) { defer mon.Task()(&ctx)(&err) diff --git a/satellite/contact/service.go b/satellite/contact/service.go index 654532bb9..0555a6bcb 100644 --- a/satellite/contact/service.go +++ b/satellite/contact/service.go @@ -19,7 +19,7 @@ import ( "storj.io/storj/satellite/overlay" ) -// Config contains configurable values for contact service +// Config contains configurable values for contact service. type Config struct { ExternalAddress string `user:"true" help:"the public address of the node, useful for nodes behind NAT" default:""` Timeout time.Duration `help:"timeout for pinging storage nodes" default:"10m0s"` @@ -55,14 +55,14 @@ func NewService(log *zap.Logger, self *overlay.NodeDossier, overlay *overlay.Ser } } -// Local returns the satellite node dossier +// Local returns the satellite node dossier. func (service *Service) Local() overlay.NodeDossier { service.mutex.Lock() defer service.mutex.Unlock() return *service.self } -// Close closes resources +// Close closes resources. func (service *Service) Close() error { return nil } // PingBack pings the node to test connectivity. diff --git a/satellite/core.go b/satellite/core.go index 3eeca6c3d..8c79d4229 100644 --- a/satellite/core.go +++ b/satellite/core.go @@ -144,7 +144,7 @@ type Core struct { } } -// New creates a new satellite +// New creates a new satellite. func New(log *zap.Logger, full *identity.FullIdentity, db DB, pointerDB metainfo.PointerDB, revocationDB extensions.RevocationDB, liveAccounting accounting.Cache, rollupsWriteCache *orders.RollupsWriteCache, diff --git a/satellite/downtime/db.go b/satellite/downtime/db.go index 0f914950c..f1636fd07 100644 --- a/satellite/downtime/db.go +++ b/satellite/downtime/db.go @@ -10,7 +10,7 @@ import ( "storj.io/common/storj" ) -// NodeOfflineTime represents a record in the nodes_offline_time table +// NodeOfflineTime represents a record in the nodes_offline_time table. type NodeOfflineTime struct { NodeID storj.NodeID TrackedAt time.Time diff --git a/satellite/downtime/estimation_chore_test.go b/satellite/downtime/estimation_chore_test.go index cc464ae36..f3fb20622 100644 --- a/satellite/downtime/estimation_chore_test.go +++ b/satellite/downtime/estimation_chore_test.go @@ -20,7 +20,7 @@ import ( // TestEstimationChoreBasic tests the basic functionality of the downtime estimation chore: // 1. Test that when a node that had one failed ping, and one successful ping >1s later does not have recorded downtime -// 2. Test that when a node that had one failed ping, and another failed ping >1s later has at least 1s of recorded downtime +// 2. Test that when a node that had one failed ping, and another failed ping >1s later has at least 1s of recorded downtime. func TestEstimationChoreBasic(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, StorageNodeCount: 2, UplinkCount: 0, diff --git a/satellite/downtime/service.go b/satellite/downtime/service.go index e63c0609d..f2ac70cc5 100644 --- a/satellite/downtime/service.go +++ b/satellite/downtime/service.go @@ -70,5 +70,5 @@ func (service *Service) CheckAndUpdateNodeAvailability(ctx context.Context, node return false, nil } -// Close closes resources +// Close closes resources. func (service *Service) Close() error { return nil } diff --git a/satellite/gc.go b/satellite/gc.go index dae75563e..57f977fb2 100644 --- a/satellite/gc.go +++ b/satellite/gc.go @@ -69,7 +69,7 @@ type GarbageCollection struct { } } -// NewGarbageCollection creates a new satellite garbage collection process +// NewGarbageCollection creates a new satellite garbage collection process. func NewGarbageCollection(log *zap.Logger, full *identity.FullIdentity, db DB, pointerDB metainfo.PointerDB, revocationDB extensions.RevocationDB, versionInfo version.Info, config *Config, atomicLogLevel *zap.AtomicLevel) (*GarbageCollection, error) { diff --git a/satellite/gc/gc_test.go b/satellite/gc/gc_test.go index 444125129..ada73ae0c 100644 --- a/satellite/gc/gc_test.go +++ b/satellite/gc/gc_test.go @@ -31,7 +31,7 @@ import ( // * Delete one object from the metainfo service on the satellite // * Wait for bloom filter generation // * Check that pieces of the deleted object are deleted on the storagenode -// * Check that pieces of the kept object are not deleted on the storagenode +// * Check that pieces of the kept object are not deleted on the storagenode. func TestGarbageCollection(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, StorageNodeCount: 1, UplinkCount: 1, diff --git a/satellite/gc/piecetracker.go b/satellite/gc/piecetracker.go index b952f58dd..8a5242e44 100644 --- a/satellite/gc/piecetracker.go +++ b/satellite/gc/piecetracker.go @@ -31,7 +31,7 @@ type PieceTracker struct { retainInfos map[storj.NodeID]*RetainInfo } -// NewPieceTracker instantiates a new gc piece tracker to be subscribed to the metainfo loop +// NewPieceTracker instantiates a new gc piece tracker to be subscribed to the metainfo loop. func NewPieceTracker(log *zap.Logger, config Config, pieceCounts map[storj.NodeID]int) *PieceTracker { return &PieceTracker{ log: log, @@ -43,7 +43,7 @@ func NewPieceTracker(log *zap.Logger, config Config, pieceCounts map[storj.NodeI } } -// RemoteSegment takes a remote segment found in metainfo and adds pieces to bloom filters +// RemoteSegment takes a remote segment found in metainfo and adds pieces to bloom filters. func (pieceTracker *PieceTracker) RemoteSegment(ctx context.Context, path metainfo.ScopedPath, pointer *pb.Pointer) (err error) { defer mon.Task()(&ctx, path.Raw)(&err) @@ -57,17 +57,17 @@ func (pieceTracker *PieceTracker) RemoteSegment(ctx context.Context, path metain return nil } -// Object returns nil because gc does not interact with remote objects +// Object returns nil because gc does not interact with remote objects. func (pieceTracker *PieceTracker) Object(ctx context.Context, path metainfo.ScopedPath, pointer *pb.Pointer) (err error) { return nil } -// InlineSegment returns nil because we're only doing gc for storage nodes for now +// InlineSegment returns nil because we're only doing gc for storage nodes for now. func (pieceTracker *PieceTracker) InlineSegment(ctx context.Context, path metainfo.ScopedPath, pointer *pb.Pointer) (err error) { return nil } -// adds a pieceID to the relevant node's RetainInfo +// adds a pieceID to the relevant node's RetainInfo. func (pieceTracker *PieceTracker) add(nodeID storj.NodeID, pieceID storj.PieceID) { if _, ok := pieceTracker.retainInfos[nodeID]; !ok { // If we know how many pieces a node should be storing, use that number. Otherwise use default. diff --git a/satellite/gc/service.go b/satellite/gc/service.go index 27610b974..f0d47563d 100644 --- a/satellite/gc/service.go +++ b/satellite/gc/service.go @@ -27,7 +27,7 @@ var ( mon = monkit.Package() ) -// Config contains configurable values for garbage collection +// Config contains configurable values for garbage collection. type Config struct { Interval time.Duration `help:"the time between each send of garbage collection filters to storage nodes" releaseDefault:"120h" devDefault:"10m"` Enabled bool `help:"set if garbage collection is enabled or not" releaseDefault:"true" devDefault:"true"` @@ -53,14 +53,14 @@ type Service struct { metainfoLoop *metainfo.Loop } -// RetainInfo contains info needed for a storage node to retain important data and delete garbage data +// RetainInfo contains info needed for a storage node to retain important data and delete garbage data. type RetainInfo struct { Filter *bloomfilter.Filter CreationDate time.Time Count int } -// NewService creates a new instance of the gc service +// NewService creates a new instance of the gc service. func NewService(log *zap.Logger, config Config, dialer rpc.Dialer, overlay overlay.DB, loop *metainfo.Loop) *Service { return &Service{ log: log, @@ -72,7 +72,7 @@ func NewService(log *zap.Logger, config Config, dialer rpc.Dialer, overlay overl } } -// Run starts the gc loop service +// Run starts the gc loop service. func (service *Service) Run(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) diff --git a/satellite/gracefulexit/common.go b/satellite/gracefulexit/common.go index c6946df0b..86d2c6e12 100644 --- a/satellite/gracefulexit/common.go +++ b/satellite/gracefulexit/common.go @@ -23,7 +23,7 @@ var ( mon = monkit.Package() ) -// Config for the chore +// Config for the chore. type Config struct { Enabled bool `help:"whether or not graceful exit is enabled on the satellite side." default:"true"` diff --git a/satellite/gracefulexit/endpoint.go b/satellite/gracefulexit/endpoint.go index 0f426d2ef..c89a1b588 100644 --- a/satellite/gracefulexit/endpoint.go +++ b/satellite/gracefulexit/endpoint.go @@ -26,7 +26,7 @@ import ( "storj.io/uplink/private/eestream" ) -// millis for the transfer queue building ticker +// millis for the transfer queue building ticker. const buildQueueMillis = 100 var ( @@ -52,7 +52,7 @@ type Endpoint struct { recvTimeout time.Duration } -// connectionsTracker for tracking ongoing connections on this api server +// connectionsTracker for tracking ongoing connections on this api server. type connectionsTracker struct { mu sync.RWMutex data map[storj.NodeID]struct{} @@ -763,7 +763,7 @@ func (endpoint *Endpoint) updatePointer(ctx context.Context, originalPointer *pb // if a node hasn't started graceful exit, it will initialize the process // if a node has finished graceful exit, it will return a finished message // if a node has started graceful exit, but no transfer item is available yet, it will return an not ready message -// otherwise, the returned message will be nil +// otherwise, the returned message will be nil. func (endpoint *Endpoint) checkExitStatus(ctx context.Context, nodeID storj.NodeID) (*pb.SatelliteMessage, error) { exitStatus, err := endpoint.overlaydb.GetExitStatus(ctx, nodeID) if err != nil { diff --git a/satellite/gracefulexit/pathcollector.go b/satellite/gracefulexit/pathcollector.go index 62a855b1e..8f25df86c 100644 --- a/satellite/gracefulexit/pathcollector.go +++ b/satellite/gracefulexit/pathcollector.go @@ -55,7 +55,7 @@ func (collector *PathCollector) Flush(ctx context.Context) (err error) { return collector.flush(ctx, 1) } -// RemoteSegment takes a remote segment found in metainfo and creates a graceful exit transfer queue item if it doesn't exist already +// RemoteSegment takes a remote segment found in metainfo and creates a graceful exit transfer queue item if it doesn't exist already. func (collector *PathCollector) RemoteSegment(ctx context.Context, path metainfo.ScopedPath, pointer *pb.Pointer) (err error) { if len(collector.nodeIDStorage) == 0 { return nil @@ -98,12 +98,12 @@ func (collector *PathCollector) RemoteSegment(ctx context.Context, path metainfo return nil } -// Object returns nil because the audit service does not interact with objects +// Object returns nil because the audit service does not interact with objects. func (collector *PathCollector) Object(ctx context.Context, path metainfo.ScopedPath, pointer *pb.Pointer) (err error) { return nil } -// InlineSegment returns nil because we're only auditing for storage nodes for now +// InlineSegment returns nil because we're only auditing for storage nodes for now. func (collector *PathCollector) InlineSegment(ctx context.Context, path metainfo.ScopedPath, pointer *pb.Pointer) (err error) { return nil } diff --git a/satellite/gracefulexit/pending_test.go b/satellite/gracefulexit/pending_test.go index 943c885d5..fee1df5e9 100644 --- a/satellite/gracefulexit/pending_test.go +++ b/satellite/gracefulexit/pending_test.go @@ -94,7 +94,7 @@ func TestPendingBasic(t *testing.T) { require.NoError(t, err) } -// TestPendingIsFinishedWorkAdded ensures that pending.IsFinished blocks if there is no work, then returns false when new work is added +// TestPendingIsFinishedWorkAdded ensures that pending.IsFinished blocks if there is no work, then returns false when new work is added. func TestPendingIsFinishedWorkAdded(t *testing.T) { ctx := testcontext.New(t) defer ctx.Cleanup() @@ -142,7 +142,7 @@ func TestPendingIsFinishedWorkAdded(t *testing.T) { require.NoError(t, group.Wait()) } -// TestPendingIsFinishedDoneSendingCalled ensures that pending.IsFinished blocks if there is no work, then returns true when DoneSending is called +// TestPendingIsFinishedDoneSendingCalled ensures that pending.IsFinished blocks if there is no work, then returns true when DoneSending is called. func TestPendingIsFinishedDoneSendingCalled(t *testing.T) { ctx := testcontext.New(t) defer ctx.Cleanup() @@ -173,7 +173,7 @@ func TestPendingIsFinishedDoneSendingCalled(t *testing.T) { require.NoError(t, group.Wait()) } -// TestPendingIsFinishedCtxCanceled ensures that pending.IsFinished blocks if there is no work, then returns true when context is canceled +// TestPendingIsFinishedCtxCanceled ensures that pending.IsFinished blocks if there is no work, then returns true when context is canceled. func TestPendingIsFinishedCtxCanceled(t *testing.T) { ctx := testcontext.New(t) defer ctx.Cleanup() @@ -205,7 +205,7 @@ func TestPendingIsFinishedCtxCanceled(t *testing.T) { require.NoError(t, group.Wait()) } -// TestPendingIsFinishedDoneSendingCalledError ensures that pending.IsFinished blocks if there is no work, then returns true with an error when DoneSending is called with an error +// TestPendingIsFinishedDoneSendingCalledError ensures that pending.IsFinished blocks if there is no work, then returns true with an error when DoneSending is called with an error. func TestPendingIsFinishedDoneSendingCalledError(t *testing.T) { ctx := testcontext.New(t) defer ctx.Cleanup() diff --git a/satellite/heldamount/endpoint.go b/satellite/heldamount/endpoint.go index fba9a638d..b3df661bb 100644 --- a/satellite/heldamount/endpoint.go +++ b/satellite/heldamount/endpoint.go @@ -31,7 +31,7 @@ type Endpoint struct { accounting accounting.StoragenodeAccounting } -// NewEndpoint creates new endpoint +// NewEndpoint creates new endpoint. func NewEndpoint(log *zap.Logger, accounting accounting.StoragenodeAccounting, overlay overlay.DB, service *Service) *Endpoint { return &Endpoint{ log: log, diff --git a/satellite/inspector/inspector.go b/satellite/inspector/inspector.go index c7012bfab..6dab1f2bd 100644 --- a/satellite/inspector/inspector.go +++ b/satellite/inspector/inspector.go @@ -35,7 +35,7 @@ type Endpoint struct { metainfo *metainfo.Service } -// NewEndpoint will initialize an Endpoint struct +// NewEndpoint will initialize an Endpoint struct. func NewEndpoint(log *zap.Logger, cache *overlay.Service, metainfo *metainfo.Service) *Endpoint { return &Endpoint{ log: log, @@ -44,7 +44,7 @@ func NewEndpoint(log *zap.Logger, cache *overlay.Service, metainfo *metainfo.Ser } } -// ObjectHealth will check the health of an object +// ObjectHealth will check the health of an object. func (endpoint *Endpoint) ObjectHealth(ctx context.Context, in *pb.ObjectHealthRequest) (resp *pb.ObjectHealthResponse, err error) { defer mon.Task()(&ctx)(&err) @@ -109,7 +109,7 @@ func (endpoint *Endpoint) ObjectHealth(ctx context.Context, in *pb.ObjectHealthR }, nil } -// SegmentHealth will check the health of a segment +// SegmentHealth will check the health of a segment. func (endpoint *Endpoint) SegmentHealth(ctx context.Context, in *pb.SegmentHealthRequest) (resp *pb.SegmentHealthResponse, err error) { defer mon.Task()(&ctx)(&err) diff --git a/satellite/mailservice/service.go b/satellite/mailservice/service.go index e0e6cd042..f406b12d6 100644 --- a/satellite/mailservice/service.go +++ b/satellite/mailservice/service.go @@ -16,7 +16,7 @@ import ( "storj.io/storj/private/post" ) -// Config defines values needed by mailservice service +// Config defines values needed by mailservice service. type Config struct { SMTPServerAddress string `help:"smtp server address" default:""` TemplatePath string `help:"path to email templates source" default:""` @@ -42,7 +42,7 @@ type Sender interface { FromAddress() post.Address } -// Message defines mailservice template-backed message for SendRendered method +// Message defines mailservice template-backed message for SendRendered method. type Message interface { Template() string Subject() string @@ -62,7 +62,7 @@ type Service struct { sending sync.WaitGroup } -// New creates new service +// New creates new service. func New(log *zap.Logger, sender Sender, templatePath string) (*Service, error) { var err error service := &Service{log: log, sender: sender} @@ -87,13 +87,13 @@ func (service *Service) Close() error { return nil } -// Send is generalized method for sending custom email message +// Send is generalized method for sending custom email message. func (service *Service) Send(ctx context.Context, msg *post.Message) (err error) { defer mon.Task()(&ctx)(&err) return service.sender.SendEmail(ctx, msg) } -// SendRenderedAsync renders content from htmltemplate and texttemplate templates then sends it asynchronously +// SendRenderedAsync renders content from htmltemplate and texttemplate templates then sends it asynchronously. func (service *Service) SendRenderedAsync(ctx context.Context, to []post.Address, msg Message) { // TODO: think of a better solution service.sending.Add(1) @@ -118,7 +118,7 @@ func (service *Service) SendRenderedAsync(ctx context.Context, to []post.Address }() } -// SendRendered renders content from htmltemplate and texttemplate templates then sends it +// SendRendered renders content from htmltemplate and texttemplate templates then sends it. func (service *Service) SendRendered(ctx context.Context, to []post.Address, msg Message) (err error) { defer mon.Task()(&ctx)(&err) diff --git a/satellite/mailservice/simulate/linkclicker.go b/satellite/mailservice/simulate/linkclicker.go index bb1c8a90d..b63ac4967 100644 --- a/satellite/mailservice/simulate/linkclicker.go +++ b/satellite/mailservice/simulate/linkclicker.go @@ -26,12 +26,12 @@ var _ mailservice.Sender = (*LinkClicker)(nil) // architecture: Service type LinkClicker struct{} -// FromAddress return empty mail address +// FromAddress return empty mail address. func (clicker *LinkClicker) FromAddress() post.Address { return post.Address{} } -// SendEmail click all links from email html parts +// SendEmail click all links from email html parts. func (clicker *LinkClicker) SendEmail(ctx context.Context, msg *post.Message) (err error) { defer mon.Task()(&ctx)(&err) diff --git a/satellite/marketingweb/server.go b/satellite/marketingweb/server.go index f16a375d7..95cdccc2f 100644 --- a/satellite/marketingweb/server.go +++ b/satellite/marketingweb/server.go @@ -21,10 +21,10 @@ import ( "storj.io/storj/satellite/rewards" ) -// Error is satellite marketing error type +// Error is satellite marketing error type. var Error = errs.Class("satellite marketing error") -// Config contains configuration for marketingweb server +// Config contains configuration for marketingweb server. type Config struct { BaseURL string `help:"base url for marketing Admin GUI" default:""` Address string `help:"server address of the marketing Admin GUI" default:"127.0.0.1:8090"` @@ -63,7 +63,7 @@ func (s *Server) commonPages() []string { } } -// NewServer creates new instance of offersweb server +// NewServer creates new instance of offersweb server. func NewServer(logger *zap.Logger, config Config, rewards rewards.DB, partners *rewards.PartnersService, listener net.Listener) (*Server, error) { s := &Server{ log: logger, @@ -94,7 +94,7 @@ func NewServer(logger *zap.Logger, config Config, rewards rewards.DB, partners * return s, nil } -// GetOffers renders the tables for free credits and referral offers to the UI +// GetOffers renders the tables for free credits and referral offers to the UI. func (s *Server) GetOffers(w http.ResponseWriter, req *http.Request) { if req.URL.Path != "/" { s.serveNotFound(w, req) @@ -113,7 +113,7 @@ func (s *Server) GetOffers(w http.ResponseWriter, req *http.Request) { } } -// parseTemplates parses and stores all templates in server +// parseTemplates parses and stores all templates in server. func (s *Server) parseTemplates() (err error) { homeFiles := append(s.commonPages(), filepath.Join(s.templateDir, "home.html"), @@ -262,7 +262,7 @@ func (s *Server) serveBadRequest(w http.ResponseWriter, req *http.Request, errMs } } -// Run starts the server that host admin web app and api endpoint +// Run starts the server that host admin web app and api endpoint. func (s *Server) Run(ctx context.Context) error { ctx, cancel := context.WithCancel(ctx) var group errgroup.Group @@ -282,7 +282,7 @@ func (s *Server) Run(ctx context.Context) error { return group.Wait() } -// Close closes server and underlying listener +// Close closes server and underlying listener. func (s *Server) Close() error { return Error.Wrap(s.server.Close()) } diff --git a/satellite/metainfo/batch.go b/satellite/metainfo/batch.go index de91456e3..c2eeede27 100644 --- a/satellite/metainfo/batch.go +++ b/satellite/metainfo/batch.go @@ -13,7 +13,7 @@ import ( "storj.io/common/storj" ) -// Batch handle requests sent in batch +// Batch handle requests sent in batch. func (endpoint *Endpoint) Batch(ctx context.Context, req *pb.BatchRequest) (resp *pb.BatchResponse, err error) { defer mon.Task()(&ctx)(&err) diff --git a/satellite/metainfo/config.go b/satellite/metainfo/config.go index 80c953cea..4e407d490 100644 --- a/satellite/metainfo/config.go +++ b/satellite/metainfo/config.go @@ -23,7 +23,7 @@ const ( ) // RSConfig is a configuration struct that keeps details about default -// redundancy strategy information +// redundancy strategy information. type RSConfig struct { MaxBufferMem memory.Size `help:"maximum buffer memory to be allocated for read buffers" default:"4MiB"` ErasureShareSize memory.Size `help:"the size of each new erasure share in bytes" default:"256B"` @@ -38,7 +38,7 @@ type RSConfig struct { Validate bool `help:"validate redundancy scheme configuration" default:"true"` } -// RateLimiterConfig is a configuration struct for endpoint rate limiting +// RateLimiterConfig is a configuration struct for endpoint rate limiting. type RateLimiterConfig struct { Enabled bool `help:"whether rate limiting is enabled." releaseDefault:"true" devDefault:"true"` Rate float64 `help:"request rate per project per second." releaseDefault:"1000" devDefault:"100"` @@ -46,14 +46,14 @@ type RateLimiterConfig struct { CacheExpiration time.Duration `help:"how long to cache the projects limiter." releaseDefault:"10m" devDefault:"10s"` } -// ProjectLimitConfig is a configuration struct for default project limits +// ProjectLimitConfig is a configuration struct for default project limits. type ProjectLimitConfig struct { MaxBuckets int `help:"max bucket count for a project." default:"100"` DefaultMaxUsage memory.Size `help:"the default storage usage limit" releaseDefault:"50GB" devDefault:"200GB"` DefaultMaxBandwidth memory.Size `help:"the default bandwidth usage limit" releaseDefault:"50GB" devDefault:"200GB"` } -// Config is a configuration struct that is everything you need to start a metainfo +// Config is a configuration struct that is everything you need to start a metainfo. type Config struct { DatabaseURL string `help:"the database connection string to use" default:"postgres://"` MinRemoteSegmentSize memory.Size `default:"1240" help:"minimum remote segment size"` diff --git a/satellite/metainfo/expireddeletion/chore.go b/satellite/metainfo/expireddeletion/chore.go index 747e9d70f..82d513d67 100644 --- a/satellite/metainfo/expireddeletion/chore.go +++ b/satellite/metainfo/expireddeletion/chore.go @@ -21,7 +21,7 @@ var ( mon = monkit.Package() ) -// Config contains configurable values for expired segment cleanup +// Config contains configurable values for expired segment cleanup. type Config struct { Interval time.Duration `help:"the time between each attempt to go through the db and clean up expired segments" releaseDefault:"120h" devDefault:"10m"` Enabled bool `help:"set if expired segment cleanup is enabled or not" releaseDefault:"true" devDefault:"true"` @@ -39,7 +39,7 @@ type Chore struct { metainfoLoop *metainfo.Loop } -// NewChore creates a new instance of the expireddeletion chore +// NewChore creates a new instance of the expireddeletion chore. func NewChore(log *zap.Logger, config Config, meta *metainfo.Service, loop *metainfo.Loop) *Chore { return &Chore{ log: log, @@ -50,7 +50,7 @@ func NewChore(log *zap.Logger, config Config, meta *metainfo.Service, loop *meta } } -// Run starts the expireddeletion loop service +// Run starts the expireddeletion loop service. func (chore *Chore) Run(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) diff --git a/satellite/metainfo/expireddeletion/expireddeleter.go b/satellite/metainfo/expireddeletion/expireddeleter.go index 2c280a99b..9f5d672aa 100644 --- a/satellite/metainfo/expireddeletion/expireddeleter.go +++ b/satellite/metainfo/expireddeletion/expireddeleter.go @@ -25,21 +25,21 @@ type expiredDeleter struct { metainfo *metainfo.Service } -// RemoteSegment deletes the segment if it is expired +// RemoteSegment deletes the segment if it is expired. func (ed *expiredDeleter) RemoteSegment(ctx context.Context, path metainfo.ScopedPath, pointer *pb.Pointer) (err error) { defer mon.Task()(&ctx, path.Raw)(&err) return ed.deleteSegmentIfExpired(ctx, path, pointer) } -// InlineSegment deletes the segment if it is expired +// InlineSegment deletes the segment if it is expired. func (ed *expiredDeleter) InlineSegment(ctx context.Context, path metainfo.ScopedPath, pointer *pb.Pointer) (err error) { defer mon.Task()(&ctx, path.Raw)(&err) return ed.deleteSegmentIfExpired(ctx, path, pointer) } -// Object returns nil because the expired deleter only cares about segments +// Object returns nil because the expired deleter only cares about segments. func (ed *expiredDeleter) Object(ctx context.Context, path metainfo.ScopedPath, pointer *pb.Pointer) (err error) { return nil } diff --git a/satellite/metainfo/expireddeletion/expireddeletion_test.go b/satellite/metainfo/expireddeletion/expireddeletion_test.go index 1d21eea22..e373b6fb4 100644 --- a/satellite/metainfo/expireddeletion/expireddeletion_test.go +++ b/satellite/metainfo/expireddeletion/expireddeletion_test.go @@ -28,7 +28,7 @@ import ( // * Verify that all three segments still exist // * Expire one of the segments // * Run the expired segment chore -// * Verify that two segments still exist and the expired one has been deleted +// * Verify that two segments still exist and the expired one has been deleted. func TestExpiredDeletion(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, StorageNodeCount: 1, UplinkCount: 1, diff --git a/satellite/metainfo/loop.go b/satellite/metainfo/loop.go index 9ebf18d13..9a4c58e67 100644 --- a/satellite/metainfo/loop.go +++ b/satellite/metainfo/loop.go @@ -35,20 +35,20 @@ type Observer interface { } // NullObserver is an observer that does nothing. This is useful for joining -// and ensuring the metainfo loop runs once before you use a real observer +// and ensuring the metainfo loop runs once before you use a real observer. type NullObserver struct{} -// Object implements the Observer interface +// Object implements the Observer interface. func (NullObserver) Object(context.Context, ScopedPath, *pb.Pointer) error { return nil } -// RemoteSegment implements the Observer interface +// RemoteSegment implements the Observer interface. func (NullObserver) RemoteSegment(context.Context, ScopedPath, *pb.Pointer) error { return nil } -// InlineSegment implements the Observer interface +// InlineSegment implements the Observer interface. func (NullObserver) InlineSegment(context.Context, ScopedPath, *pb.Pointer) error { return nil } diff --git a/satellite/metainfo/loop_test.go b/satellite/metainfo/loop_test.go index e7c251acc..c7923dd90 100644 --- a/satellite/metainfo/loop_test.go +++ b/satellite/metainfo/loop_test.go @@ -116,7 +116,7 @@ func TestLoop(t *testing.T) { // * let observer 2 return an error from one of its handlers // * let observer 3's context be canceled // * expect observer 1 to see all segments -// * expect observers 2 and 3 to finish with errors +// * expect observers 2 and 3 to finish with errors. func TestLoopObserverCancel(t *testing.T) { segmentSize := 8 * memory.KiB @@ -202,7 +202,7 @@ func TestLoopObserverCancel(t *testing.T) { // * hook two observers up to metainfo loop // * cancel loop context partway through // * expect both observers to exit with an error and see fewer than 3 remote segments -// * expect that a new observer attempting to join at this point receives a loop closed error +// * expect that a new observer attempting to join at this point receives a loop closed error. func TestLoopCancel(t *testing.T) { segmentSize := 8 * memory.KiB diff --git a/satellite/metainfo/metainfo.go b/satellite/metainfo/metainfo.go index fe50f08c2..55d2e1df3 100644 --- a/satellite/metainfo/metainfo.go +++ b/satellite/metainfo/metainfo.go @@ -1257,7 +1257,7 @@ func (endpoint *Endpoint) MakeInlineSegment(ctx context.Context, req *pb.Segment return resp, err } -// MakeInlineSegment makes inline segment on satellite +// MakeInlineSegment makes inline segment on satellite. func (endpoint *Endpoint) makeInlineSegment(ctx context.Context, req *pb.SegmentMakeInlineRequest, savePointer bool) (pointer *pb.Pointer, resp *pb.SegmentMakeInlineResponse, err error) { defer mon.Task()(&ctx)(&err) diff --git a/satellite/metainfo/piecedeletion/queue.go b/satellite/metainfo/piecedeletion/queue.go index 8659d7390..87d225f27 100644 --- a/satellite/metainfo/piecedeletion/queue.go +++ b/satellite/metainfo/piecedeletion/queue.go @@ -28,7 +28,7 @@ func NewLimitedJobs(maxPiecesPerBatch int) *LimitedJobs { // TryPush tries to add a job to the queue. // -// maxPiecesPerBatch < 0, means no limit +// maxPiecesPerBatch < 0, means no limit. func (jobs *LimitedJobs) TryPush(job Job) bool { jobs.mu.Lock() defer jobs.mu.Unlock() diff --git a/satellite/metainfo/service.go b/satellite/metainfo/service.go index ad7093b89..87878a471 100644 --- a/satellite/metainfo/service.go +++ b/satellite/metainfo/service.go @@ -245,7 +245,7 @@ func (s *Service) GetWithBytes(ctx context.Context, path string) (pointerBytes [ return pointerBytes, pointer, nil } -// List returns all Path keys in the pointers bucket +// List returns all Path keys in the pointers bucket. func (s *Service) List(ctx context.Context, prefix string, startAfter string, recursive bool, limit int32, metaFlags uint32) (items []*pb.ListResponse_Item, more bool, err error) { defer mon.Task()(&ctx)(&err) @@ -295,7 +295,7 @@ func (s *Service) createListItem(ctx context.Context, rawItem storage.ListItem, } // getMetadata adds the metadata to the given item pointer according to the -// given metaFlags +// given metaFlags. func (s *Service) setMetadata(item *pb.ListResponse_Item, data []byte, metaFlags uint32) (err error) { if metaFlags == meta.None || len(data) == 0 { return nil @@ -348,25 +348,25 @@ func (s *Service) UnsynchronizedDelete(ctx context.Context, path string) (err er return Error.Wrap(err) } -// CreateBucket creates a new bucket in the buckets db +// CreateBucket creates a new bucket in the buckets db. func (s *Service) CreateBucket(ctx context.Context, bucket storj.Bucket) (_ storj.Bucket, err error) { defer mon.Task()(&ctx)(&err) return s.bucketsDB.CreateBucket(ctx, bucket) } -// GetBucket returns an existing bucket in the buckets db +// GetBucket returns an existing bucket in the buckets db. func (s *Service) GetBucket(ctx context.Context, bucketName []byte, projectID uuid.UUID) (_ storj.Bucket, err error) { defer mon.Task()(&ctx)(&err) return s.bucketsDB.GetBucket(ctx, bucketName, projectID) } -// UpdateBucket returns an updated bucket in the buckets db +// UpdateBucket returns an updated bucket in the buckets db. func (s *Service) UpdateBucket(ctx context.Context, bucket storj.Bucket) (_ storj.Bucket, err error) { defer mon.Task()(&ctx)(&err) return s.bucketsDB.UpdateBucket(ctx, bucket) } -// DeleteBucket deletes a bucket from the bucekts db +// DeleteBucket deletes a bucket from the bucekts db. func (s *Service) DeleteBucket(ctx context.Context, bucketName []byte, projectID uuid.UUID) (err error) { defer mon.Task()(&ctx)(&err) @@ -395,13 +395,13 @@ func (s *Service) IsBucketEmpty(ctx context.Context, projectID uuid.UUID, bucket return len(items) == 0, nil } -// ListBuckets returns a list of buckets for a project +// ListBuckets returns a list of buckets for a project. func (s *Service) ListBuckets(ctx context.Context, projectID uuid.UUID, listOpts storj.BucketListOptions, allowedBuckets macaroon.AllowedBuckets) (bucketList storj.BucketList, err error) { defer mon.Task()(&ctx)(&err) return s.bucketsDB.ListBuckets(ctx, projectID, listOpts, allowedBuckets) } -// CountBuckets returns the number of buckets a project currently has +// CountBuckets returns the number of buckets a project currently has. func (s *Service) CountBuckets(ctx context.Context, projectID uuid.UUID) (count int, err error) { defer mon.Task()(&ctx)(&err) return s.bucketsDB.CountBuckets(ctx, projectID) diff --git a/satellite/metainfo/validation.go b/satellite/metainfo/validation.go index 5368f5cde..d1d9b634f 100644 --- a/satellite/metainfo/validation.go +++ b/satellite/metainfo/validation.go @@ -33,7 +33,7 @@ var ( ipRegexp = regexp.MustCompile(`^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$`) ) -// TTLItem keeps association between serial number and ttl +// TTLItem keeps association between serial number and ttl. type TTLItem struct { serialNumber storj.SerialNumber ttl time.Time diff --git a/satellite/nodestats/endpoint.go b/satellite/nodestats/endpoint.go index 440867ae9..46d43af69 100644 --- a/satellite/nodestats/endpoint.go +++ b/satellite/nodestats/endpoint.go @@ -31,7 +31,7 @@ type Endpoint struct { config paymentsconfig.Config } -// NewEndpoint creates new endpoint +// NewEndpoint creates new endpoint. func NewEndpoint(log *zap.Logger, overlay overlay.DB, accounting accounting.StoragenodeAccounting, config paymentsconfig.Config) *Endpoint { return &Endpoint{ log: log, @@ -41,7 +41,7 @@ func NewEndpoint(log *zap.Logger, overlay overlay.DB, accounting accounting.Stor } } -// GetStats sends node stats for client node +// GetStats sends node stats for client node. func (e *Endpoint) GetStats(ctx context.Context, req *pb.GetStatsRequest) (_ *pb.GetStatsResponse, err error) { defer mon.Task()(&ctx)(&err) @@ -87,7 +87,7 @@ func (e *Endpoint) GetStats(ctx context.Context, req *pb.GetStatsRequest) (_ *pb }, nil } -// DailyStorageUsage returns slice of daily storage usage for given period of time sorted in ASC order by date +// DailyStorageUsage returns slice of daily storage usage for given period of time sorted in ASC order by date. func (e *Endpoint) DailyStorageUsage(ctx context.Context, req *pb.DailyStorageUsageRequest) (_ *pb.DailyStorageUsageResponse, err error) { defer mon.Task()(&ctx)(&err) @@ -128,7 +128,7 @@ func (e *Endpoint) PricingModel(ctx context.Context, req *pb.PricingModelRequest }, nil } -// toProtoDailyStorageUsage converts StorageNodeUsage to PB DailyStorageUsageResponse_StorageUsage +// toProtoDailyStorageUsage converts StorageNodeUsage to PB DailyStorageUsageResponse_StorageUsage. func toProtoDailyStorageUsage(usages []accounting.StorageNodeUsage) []*pb.DailyStorageUsageResponse_StorageUsage { var pbUsages []*pb.DailyStorageUsageResponse_StorageUsage @@ -142,7 +142,7 @@ func toProtoDailyStorageUsage(usages []accounting.StorageNodeUsage) []*pb.DailyS return pbUsages } -// calculateReputationScore is helper method to calculate reputation score value +// calculateReputationScore is helper method to calculate reputation score value. func calculateReputationScore(alpha, beta float64) float64 { return alpha / (alpha + beta) } diff --git a/satellite/orders/endpoint.go b/satellite/orders/endpoint.go index 357d9a47f..c07c9768d 100644 --- a/satellite/orders/endpoint.go +++ b/satellite/orders/endpoint.go @@ -101,7 +101,7 @@ type ConsumedSerial struct { } // PendingSerial is a serial number reported by a storagenode waiting to be -// settled +// settled. type PendingSerial struct { NodeID storj.NodeID BucketID []byte @@ -122,7 +122,7 @@ var ( mon = monkit.Package() ) -// BucketBandwidthRollup contains all the info needed for a bucket bandwidth rollup +// BucketBandwidthRollup contains all the info needed for a bucket bandwidth rollup. type BucketBandwidthRollup struct { ProjectID uuid.UUID BucketName string @@ -132,7 +132,7 @@ type BucketBandwidthRollup struct { Settled int64 } -// SortBucketBandwidthRollups sorts the rollups +// SortBucketBandwidthRollups sorts the rollups. func SortBucketBandwidthRollups(rollups []BucketBandwidthRollup) { sort.SliceStable(rollups, func(i, j int) bool { uuidCompare := bytes.Compare(rollups[i].ProjectID[:], rollups[j].ProjectID[:]) @@ -155,7 +155,7 @@ func SortBucketBandwidthRollups(rollups []BucketBandwidthRollup) { }) } -// StoragenodeBandwidthRollup contains all the info needed for a storagenode bandwidth rollup +// StoragenodeBandwidthRollup contains all the info needed for a storagenode bandwidth rollup. type StoragenodeBandwidthRollup struct { NodeID storj.NodeID Action pb.PieceAction @@ -163,7 +163,7 @@ type StoragenodeBandwidthRollup struct { Settled int64 } -// SortStoragenodeBandwidthRollups sorts the rollups +// SortStoragenodeBandwidthRollups sorts the rollups. func SortStoragenodeBandwidthRollups(rollups []StoragenodeBandwidthRollup) { sort.SliceStable(rollups, func(i, j int) bool { nodeCompare := bytes.Compare(rollups[i].NodeID.Bytes(), rollups[j].NodeID.Bytes()) @@ -182,13 +182,13 @@ func SortStoragenodeBandwidthRollups(rollups []StoragenodeBandwidthRollup) { }) } -// ProcessOrderRequest for batch order processing +// ProcessOrderRequest for batch order processing. type ProcessOrderRequest struct { Order *pb.Order OrderLimit *pb.OrderLimit } -// ProcessOrderResponse for batch order processing responses +// ProcessOrderResponse for batch order processing responses. type ProcessOrderResponse struct { SerialNumber storj.SerialNumber Status pb.SettlementResponse_Status @@ -205,7 +205,7 @@ type Endpoint struct { settlementBatchSize int } -// NewEndpoint new orders receiving endpoint +// NewEndpoint new orders receiving endpoint. func NewEndpoint(log *zap.Logger, satelliteSignee signing.Signee, db DB, nodeAPIVersionDB nodeapiversion.DB, settlementBatchSize int) *Endpoint { return &Endpoint{ log: log, diff --git a/satellite/orders/rollups_write_cache.go b/satellite/orders/rollups_write_cache.go index 6fd7f69e4..4a9093fc0 100644 --- a/satellite/orders/rollups_write_cache.go +++ b/satellite/orders/rollups_write_cache.go @@ -16,24 +16,24 @@ import ( ) // CacheData stores the amount of inline and allocated data -// for a bucket bandwidth rollup +// for a bucket bandwidth rollup. type CacheData struct { Inline int64 Allocated int64 Settled int64 } -// CacheKey is the key information for the cached map below +// CacheKey is the key information for the cached map below. type CacheKey struct { ProjectID uuid.UUID BucketName string Action pb.PieceAction } -// RollupData contains the pending rollups waiting to be flushed to the db +// RollupData contains the pending rollups waiting to be flushed to the db. type RollupData map[CacheKey]CacheData -// RollupsWriteCache stores information needed to update bucket bandwidth rollups +// RollupsWriteCache stores information needed to update bucket bandwidth rollups. type RollupsWriteCache struct { DB batchSize int @@ -49,7 +49,7 @@ type RollupsWriteCache struct { nextFlushCompletion *sync2.Fence } -// NewRollupsWriteCache creates an RollupsWriteCache +// NewRollupsWriteCache creates an RollupsWriteCache. func NewRollupsWriteCache(log *zap.Logger, db DB, batchSize int) *RollupsWriteCache { return &RollupsWriteCache{ DB: db, @@ -60,24 +60,24 @@ func NewRollupsWriteCache(log *zap.Logger, db DB, batchSize int) *RollupsWriteCa } } -// UpdateBucketBandwidthAllocation updates the rollups cache adding allocated data for a bucket bandwidth rollup +// UpdateBucketBandwidthAllocation updates the rollups cache adding allocated data for a bucket bandwidth rollup. func (cache *RollupsWriteCache) UpdateBucketBandwidthAllocation(ctx context.Context, projectID uuid.UUID, bucketName []byte, action pb.PieceAction, amount int64, intervalStart time.Time) error { return cache.updateCacheValue(ctx, projectID, bucketName, action, amount, 0, 0, intervalStart.UTC()) } -// UpdateBucketBandwidthInline updates the rollups cache adding inline data for a bucket bandwidth rollup +// UpdateBucketBandwidthInline updates the rollups cache adding inline data for a bucket bandwidth rollup. func (cache *RollupsWriteCache) UpdateBucketBandwidthInline(ctx context.Context, projectID uuid.UUID, bucketName []byte, action pb.PieceAction, amount int64, intervalStart time.Time) error { return cache.updateCacheValue(ctx, projectID, bucketName, action, 0, amount, 0, intervalStart.UTC()) } -// UpdateBucketBandwidthSettle updates the rollups cache adding settled data for a bucket bandwidth rollup +// UpdateBucketBandwidthSettle updates the rollups cache adding settled data for a bucket bandwidth rollup. func (cache *RollupsWriteCache) UpdateBucketBandwidthSettle(ctx context.Context, projectID uuid.UUID, bucketName []byte, action pb.PieceAction, amount int64, intervalStart time.Time) error { return cache.updateCacheValue(ctx, projectID, bucketName, action, 0, 0, amount, intervalStart.UTC()) } // resetCache should only be called after you have acquired the cache lock. It // will reset the various cache values and return the pendingRollups, -// latestTime, and currentSize +// latestTime, and currentSize. func (cache *RollupsWriteCache) resetCache() (RollupData, time.Time, int) { pendingRollups := cache.pendingRollups cache.pendingRollups = make(RollupData) @@ -88,7 +88,7 @@ func (cache *RollupsWriteCache) resetCache() (RollupData, time.Time, int) { return pendingRollups, latestTime, oldSize } -// Flush resets cache then flushes the everything in the rollups write cache to the database +// Flush resets cache then flushes the everything in the rollups write cache to the database. func (cache *RollupsWriteCache) Flush(ctx context.Context) { defer mon.Task()(&ctx)(nil) cache.mu.Lock() @@ -108,7 +108,7 @@ func (cache *RollupsWriteCache) CloseAndFlush(ctx context.Context) error { return nil } -// flush flushes the everything in the rollups write cache to the database +// flush flushes the everything in the rollups write cache to the database. func (cache *RollupsWriteCache) flush(ctx context.Context, pendingRollups RollupData, latestTime time.Time, oldSize int) { defer mon.Task()(&ctx)(nil) diff --git a/satellite/orders/service.go b/satellite/orders/service.go index 2029fe2a9..336aa0b77 100644 --- a/satellite/orders/service.go +++ b/satellite/orders/service.go @@ -24,7 +24,7 @@ import ( "storj.io/uplink/private/eestream" ) -// ErrDownloadFailedNotEnoughPieces is returned when download failed due to missing pieces +// ErrDownloadFailedNotEnoughPieces is returned when download failed due to missing pieces. var ErrDownloadFailedNotEnoughPieces = errs.Class("not enough pieces for download") // Config is a configuration struct for orders Service. @@ -239,7 +239,7 @@ func (service *Service) CreateGetOrderLimits(ctx context.Context, bucketID []byt return limits, piecePrivateKey, nil } -// RandomSampleOfOrderLimits returns a random sample of the order limits +// RandomSampleOfOrderLimits returns a random sample of the order limits. func (service *Service) RandomSampleOfOrderLimits(limits []*pb.AddressedOrderLimit, sampleSize int) ([]*pb.AddressedOrderLimit, error) { service.rngMu.Lock() perm := service.rng.Perm(len(limits)) @@ -834,7 +834,7 @@ func (service *Service) CreateGracefulExitPutOrderLimit(ctx context.Context, buc return limit, piecePrivateKey, nil } -// UpdateGetInlineOrder updates amount of inline GET bandwidth for given bucket +// UpdateGetInlineOrder updates amount of inline GET bandwidth for given bucket. func (service *Service) UpdateGetInlineOrder(ctx context.Context, projectID uuid.UUID, bucketName []byte, amount int64) (err error) { defer mon.Task()(&ctx)(&err) now := time.Now().UTC() @@ -843,7 +843,7 @@ func (service *Service) UpdateGetInlineOrder(ctx context.Context, projectID uuid return service.orders.UpdateBucketBandwidthInline(ctx, projectID, bucketName, pb.PieceAction_GET, amount, intervalStart) } -// UpdatePutInlineOrder updates amount of inline PUT bandwidth for given bucket +// UpdatePutInlineOrder updates amount of inline PUT bandwidth for given bucket. func (service *Service) UpdatePutInlineOrder(ctx context.Context, projectID uuid.UUID, bucketName []byte, amount int64) (err error) { defer mon.Task()(&ctx)(&err) now := time.Now().UTC() @@ -852,7 +852,7 @@ func (service *Service) UpdatePutInlineOrder(ctx context.Context, projectID uuid return service.orders.UpdateBucketBandwidthInline(ctx, projectID, bucketName, pb.PieceAction_PUT, amount, intervalStart) } -// SplitBucketID takes a bucketID, splits on /, and returns a projectID and bucketName +// SplitBucketID takes a bucketID, splits on /, and returns a projectID and bucketName. func SplitBucketID(bucketID []byte) (projectID uuid.UUID, bucketName []byte, err error) { pathElements := bytes.Split(bucketID, []byte("/")) if len(pathElements) > 1 { diff --git a/satellite/overlay/config.go b/satellite/overlay/config.go index 41928856f..ae1a9ae90 100644 --- a/satellite/overlay/config.go +++ b/satellite/overlay/config.go @@ -26,7 +26,7 @@ type Config struct { } // NodeSelectionConfig is a configuration struct to determine the minimum -// values for nodes to select +// values for nodes to select. type NodeSelectionConfig struct { UptimeCount int64 `help:"the number of times a node's uptime has been checked to not be considered a New Node" releaseDefault:"100" devDefault:"0"` AuditCount int64 `help:"the number of times a node has been audited to not be considered a New Node" releaseDefault:"100" devDefault:"0"` diff --git a/satellite/overlay/inspector.go b/satellite/overlay/inspector.go index d4bd3ef88..bfa358567 100644 --- a/satellite/overlay/inspector.go +++ b/satellite/overlay/inspector.go @@ -18,7 +18,7 @@ type Inspector struct { service *Service } -// NewInspector creates an Inspector +// NewInspector creates an Inspector. func NewInspector(service *Service) *Inspector { return &Inspector{service: service} } diff --git a/satellite/overlay/nodeselectioncache.go b/satellite/overlay/nodeselectioncache.go index 852c9bc8f..7e7be81fe 100644 --- a/satellite/overlay/nodeselectioncache.go +++ b/satellite/overlay/nodeselectioncache.go @@ -43,7 +43,7 @@ type NodeSelectionCache struct { state *nodeselection.State } -// NewNodeSelectionCache creates a new cache that keeps a list of all the storage nodes that are qualified to store data +// NewNodeSelectionCache creates a new cache that keeps a list of all the storage nodes that are qualified to store data. func NewNodeSelectionCache(log *zap.Logger, db CacheDB, staleness time.Duration, config NodeSelectionConfig) *NodeSelectionCache { return &NodeSelectionCache{ log: log, @@ -54,7 +54,7 @@ func NewNodeSelectionCache(log *zap.Logger, db CacheDB, staleness time.Duration, } // Refresh populates the cache with all of the reputableNodes and newNode nodes -// This method is useful for tests +// This method is useful for tests. func (cache *NodeSelectionCache) Refresh(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) _, err = cache.refresh(ctx) @@ -63,7 +63,7 @@ func (cache *NodeSelectionCache) Refresh(ctx context.Context) (err error) { // refresh calls out to the database and refreshes the cache with the most up-to-date // data from the nodes table, then sets time that the last refresh occurred so we know when -// to refresh again in the future +// to refresh again in the future. func (cache *NodeSelectionCache) refresh(ctx context.Context) (state *nodeselection.State, err error) { defer mon.Task()(&ctx)(&err) cache.mu.Lock() @@ -118,7 +118,7 @@ func (cache *NodeSelectionCache) GetNodes(ctx context.Context, req FindStorageNo return convNodesToSelectedNodes(selected), err } -// Size returns how many reputable nodes and new nodes are in the cache +// Size returns how many reputable nodes and new nodes are in the cache. func (cache *NodeSelectionCache) Size() (reputableNodeCount int, newNodeCount int) { cache.mu.RLock() state := cache.state diff --git a/satellite/overlay/selection_test.go b/satellite/overlay/selection_test.go index e1423aeb1..944d9e3d9 100644 --- a/satellite/overlay/selection_test.go +++ b/satellite/overlay/selection_test.go @@ -417,7 +417,7 @@ func testNodeSelection(t *testing.T, ctx *testcontext.Context, planet *testplane } } -// ipToLastNet converts target address to its IP and /24 subnet IPv4 or /64 subnet IPv6 +// ipToLastNet converts target address to its IP and /24 subnet IPv4 or /64 subnet IPv6. func ipToLastNet(target string) (network string, err error) { host, _, err := net.SplitHostPort(target) if err != nil { diff --git a/satellite/overlay/service.go b/satellite/overlay/service.go index fa751d321..0efb9a399 100644 --- a/satellite/overlay/service.go +++ b/satellite/overlay/service.go @@ -17,19 +17,19 @@ import ( "storj.io/storj/storage" ) -// ErrEmptyNode is returned when the nodeID is empty +// ErrEmptyNode is returned when the nodeID is empty. var ErrEmptyNode = errs.New("empty node ID") -// ErrNodeNotFound is returned if a node does not exist in database +// ErrNodeNotFound is returned if a node does not exist in database. var ErrNodeNotFound = errs.Class("node not found") -// ErrNodeOffline is returned if a nodes is offline +// ErrNodeOffline is returned if a nodes is offline. var ErrNodeOffline = errs.Class("node is offline") -// ErrNodeDisqualified is returned if a nodes is disqualified +// ErrNodeDisqualified is returned if a nodes is disqualified. var ErrNodeDisqualified = errs.Class("node is disqualified") -// ErrNotEnoughNodes is when selecting nodes failed with the given parameters +// ErrNotEnoughNodes is when selecting nodes failed with the given parameters. var ErrNotEnoughNodes = errs.Class("not enough nodes") // DB implements the database for overlay.Service @@ -97,7 +97,7 @@ type DB interface { UnsuspendNodeUnknownAudit(ctx context.Context, nodeID storj.NodeID) (err error) } -// NodeCheckInInfo contains all the info that will be updated when a node checkins +// NodeCheckInInfo contains all the info that will be updated when a node checkins. type NodeCheckInInfo struct { NodeID storj.NodeID Address *pb.NodeAddress @@ -124,7 +124,7 @@ type FindStorageNodesRequest struct { MinimumVersion string // semver or empty } -// NodeCriteria are the requirements for selecting nodes +// NodeCriteria are the requirements for selecting nodes. type NodeCriteria struct { FreeDisk int64 AuditCount int64 @@ -183,7 +183,7 @@ type ExitStatusRequest struct { ExitSuccess bool } -// NodeDossier is the complete info that the satellite tracks for a storage node +// NodeDossier is the complete info that the satellite tracks for a storage node. type NodeDossier struct { pb.Node Type pb.NodeType @@ -219,7 +219,7 @@ type NodeStats struct { UnknownAuditSuspended *time.Time } -// NodeLastContact contains the ID, address, and timestamp +// NodeLastContact contains the ID, address, and timestamp. type NodeLastContact struct { URL storj.NodeURL LastIPPort string @@ -258,7 +258,7 @@ type Service struct { SelectionCache *NodeSelectionCache } -// NewService returns a new Service +// NewService returns a new Service. func NewService(log *zap.Logger, db DB, config Config) *Service { return &Service{ log: log, @@ -270,10 +270,10 @@ func NewService(log *zap.Logger, db DB, config Config) *Service { } } -// Close closes resources +// Close closes resources. func (service *Service) Close() error { return nil } -// Inspect lists limited number of items in the cache +// Inspect lists limited number of items in the cache. func (service *Service) Inspect(ctx context.Context) (_ storage.Keys, err error) { defer mon.Task()(&ctx)(&err) // TODO: implement inspection tools @@ -387,7 +387,7 @@ func (service *Service) FindStorageNodesWithPreferences(ctx context.Context, req return nodes, nil } -// KnownOffline filters a set of nodes to offline nodes +// KnownOffline filters a set of nodes to offline nodes. func (service *Service) KnownOffline(ctx context.Context, nodeIds storj.NodeIDList) (offlineNodes storj.NodeIDList, err error) { defer mon.Task()(&ctx)(&err) criteria := &NodeCriteria{ @@ -420,7 +420,7 @@ func (service *Service) Reliable(ctx context.Context) (nodes storj.NodeIDList, e return service.db.Reliable(ctx, criteria) } -// BatchUpdateStats updates multiple storagenode's stats in one transaction +// BatchUpdateStats updates multiple storagenode's stats in one transaction. func (service *Service) BatchUpdateStats(ctx context.Context, requests []*UpdateRequest) (failed storj.NodeIDList, err error) { defer mon.Task()(&ctx)(&err) @@ -476,7 +476,7 @@ func (service *Service) GetSuccesfulNodesNotCheckedInSince(ctx context.Context, return service.db.GetSuccesfulNodesNotCheckedInSince(ctx, duration) } -// GetMissingPieces returns the list of offline nodes +// GetMissingPieces returns the list of offline nodes. func (service *Service) GetMissingPieces(ctx context.Context, pieces []*pb.RemotePiece) (missingPieces []int32, err error) { defer mon.Task()(&ctx)(&err) var nodeIDs storj.NodeIDList @@ -510,7 +510,7 @@ func (service *Service) GetOfflineNodesLimited(ctx context.Context, limit int) ( return service.db.GetOfflineNodesLimited(ctx, limit) } -// ResolveIPAndNetwork resolves the target address and determines its IP and /24 subnet IPv4 or /64 subnet IPv6 +// ResolveIPAndNetwork resolves the target address and determines its IP and /24 subnet IPv4 or /64 subnet IPv6. func ResolveIPAndNetwork(ctx context.Context, target string) (ipPort, network string, err error) { defer mon.Task()(&ctx)(&err) diff --git a/satellite/overlay/service_test.go b/satellite/overlay/service_test.go index 00dd103a2..1257bb3fb 100644 --- a/satellite/overlay/service_test.go +++ b/satellite/overlay/service_test.go @@ -36,7 +36,7 @@ func TestCache_Database(t *testing.T) { }) } -// returns a NodeSelectionConfig with sensible test values +// returns a NodeSelectionConfig with sensible test values. func testNodeSelectionConfig(auditCount int64, newNodeFraction float64, distinctIP bool) overlay.NodeSelectionConfig { return overlay.NodeSelectionConfig{ UptimeCount: 0, @@ -734,7 +734,7 @@ func TestGetSuccesfulNodesNotCheckedInSince(t *testing.T) { }) } -// TestSuspendedSelection ensures that suspended nodes are not selected by SelectStorageNodes +// TestSuspendedSelection ensures that suspended nodes are not selected by SelectStorageNodes. func TestSuspendedSelection(t *testing.T) { totalNodes := 10 diff --git a/satellite/overlay/suspension_test.go b/satellite/overlay/suspension_test.go index 2e6dbcad2..8fde25385 100644 --- a/satellite/overlay/suspension_test.go +++ b/satellite/overlay/suspension_test.go @@ -18,7 +18,7 @@ import ( "storj.io/storj/satellite/overlay" ) -// TestSuspendBasic ensures that we can suspend a node using overlayService.SuspendNode and that we can unsuspend a node using overlayservice.UnsuspendNode +// TestSuspendBasic ensures that we can suspend a node using overlayService.SuspendNode and that we can unsuspend a node using overlayservice.UnsuspendNode. func TestSuspendBasic(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, StorageNodeCount: 1, UplinkCount: 0, @@ -259,7 +259,7 @@ func TestSuspendDQDisabled(t *testing.T) { }) } -// TestSuspendBatchUpdateStats ensures that suspension and alpha/beta fields are properly updated from batch update stats +// TestSuspendBatchUpdateStats ensures that suspension and alpha/beta fields are properly updated from batch update stats. func TestSuspendBatchUpdateStats(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, StorageNodeCount: 1, UplinkCount: 0, diff --git a/satellite/payments/coinpayments/conversionrates.go b/satellite/payments/coinpayments/conversionrates.go index 6c02ad1ba..24c7f9c3b 100644 --- a/satellite/payments/coinpayments/conversionrates.go +++ b/satellite/payments/coinpayments/conversionrates.go @@ -34,7 +34,7 @@ type CurrencyRateInfo struct { LastUpdate time.Time } -// UnmarshalJSON converts JSON string to currency rate info, +// UnmarshalJSON converts JSON string to currency rate info,. func (rateInfo *CurrencyRateInfo) UnmarshalJSON(b []byte) error { var rateRaw struct { IsFiat int `json:"is_fiat"` diff --git a/satellite/payments/stripecoinpayments/transactions.go b/satellite/payments/stripecoinpayments/transactions.go index 1d2c387d8..601def36c 100644 --- a/satellite/payments/stripecoinpayments/transactions.go +++ b/satellite/payments/stripecoinpayments/transactions.go @@ -86,7 +86,7 @@ func (page *TransactionsPage) CreationTimes() map[coinpayments.TransactionID]tim return creationTimes } -// TransactionAndUserList is a composite type for storing userID and txID +// TransactionAndUserList is a composite type for storing userID and txID. type TransactionAndUserList map[coinpayments.TransactionID]uuid.UUID // IDList returns transaction id list. diff --git a/satellite/peer.go b/satellite/peer.go index f794df6c3..b5883ddc0 100644 --- a/satellite/peer.go +++ b/satellite/peer.go @@ -109,7 +109,7 @@ type DB interface { NodeAPIVersion() nodeapiversion.DB } -// Config is the global config satellite +// Config is the global config satellite. type Config struct { Identity identity.Config Server server.Config diff --git a/satellite/referrals/users.go b/satellite/referrals/users.go index 22128ec64..b556dc2fb 100644 --- a/satellite/referrals/users.go +++ b/satellite/referrals/users.go @@ -12,10 +12,10 @@ import ( "storj.io/storj/satellite/console" ) -// ErrValidation validation related error class +// ErrValidation validation related error class. var ErrValidation = errs.Class("validation error") -// CreateUser contains information that's necessary for creating a new user through referral program +// CreateUser contains information that's necessary for creating a new user through referral program. type CreateUser struct { FullName string `json:"fullName"` ShortName string `json:"shortName"` diff --git a/satellite/repair/checker/checker.go b/satellite/repair/checker/checker.go index 41827736a..aacbd4a15 100644 --- a/satellite/repair/checker/checker.go +++ b/satellite/repair/checker/checker.go @@ -28,7 +28,7 @@ var ( mon = monkit.Package() ) -// Config contains configurable values for checker +// Config contains configurable values for checker. type Config struct { Interval time.Duration `help:"how frequently checker should check for bad segments" releaseDefault:"30s" devDefault:"0h0m10s"` IrreparableInterval time.Duration `help:"how frequently irrepairable checker should check for lost pieces" releaseDefault:"30m" devDefault:"0h0m5s"` @@ -37,7 +37,7 @@ type Config struct { RepairOverride int `help:"override value for repair threshold" default:"0"` } -// durabilityStats remote segment information +// durabilityStats remote segment information. type durabilityStats struct { objectsChecked int64 remoteSegmentsChecked int64 @@ -65,7 +65,7 @@ type Checker struct { IrreparableLoop *sync2.Cycle } -// NewChecker creates a new instance of checker +// NewChecker creates a new instance of checker. func NewChecker(logger *zap.Logger, repairQueue queue.RepairQueue, irrdb irreparable.DB, metainfo *metainfo.Service, metaLoop *metainfo.Loop, overlay *overlay.Service, config Config) *Checker { return &Checker{ logger: logger, @@ -82,7 +82,7 @@ func NewChecker(logger *zap.Logger, repairQueue queue.RepairQueue, irrdb irrepar } } -// Run the checker loop +// Run the checker loop. func (checker *Checker) Run(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) @@ -104,7 +104,7 @@ func (checker *Checker) RefreshReliabilityCache(ctx context.Context) error { return checker.nodestate.Refresh(ctx) } -// Close halts the Checker loop +// Close halts the Checker loop. func (checker *Checker) Close() error { checker.Loop.Close() return nil @@ -151,7 +151,7 @@ func (checker *Checker) IdentifyInjuredSegments(ctx context.Context) (err error) return nil } -// checks for a string in slice +// checks for a string in slice. func contains(a []string, x string) bool { for _, n := range a { if x == n { diff --git a/satellite/repair/checker/online.go b/satellite/repair/checker/online.go index 9bde8c71a..050265934 100644 --- a/satellite/repair/checker/online.go +++ b/satellite/repair/checker/online.go @@ -25,7 +25,7 @@ type ReliabilityCache struct { state atomic.Value // contains immutable *reliabilityState } -// reliabilityState +// reliabilityState. type reliabilityState struct { reliable map[storj.NodeID]struct{} created time.Time diff --git a/satellite/repair/irreparable/inspector.go b/satellite/repair/irreparable/inspector.go index d7c8a9c78..0d1204d36 100644 --- a/satellite/repair/irreparable/inspector.go +++ b/satellite/repair/irreparable/inspector.go @@ -22,12 +22,12 @@ type Inspector struct { irrdb DB } -// NewInspector creates an Inspector +// NewInspector creates an Inspector. func NewInspector(irrdb DB) *Inspector { return &Inspector{irrdb: irrdb} } -// ListIrreparableSegments returns a number of irreparable segments by limit and offset +// ListIrreparableSegments returns a number of irreparable segments by limit and offset. func (srv *Inspector) ListIrreparableSegments(ctx context.Context, req *pb.ListIrreparableSegmentsRequest) (_ *pb.ListIrreparableSegmentsResponse, err error) { defer mon.Task()(&ctx)(&err) last := req.GetLastSeenSegmentPath() diff --git a/satellite/repair/repair_test.go b/satellite/repair/repair_test.go index c4c2f6298..66ee809f2 100644 --- a/satellite/repair/repair_test.go +++ b/satellite/repair/repair_test.go @@ -171,7 +171,7 @@ func testDataRepair(t *testing.T, inMemoryRepair bool) { // - On one of the remaining nodes, corrupt the piece data being stored by that node // - Triggers data repair, which attempts to repair the data from the remaining nodes to // the numbers of nodes determined by the upload repair max threshold -// - Expects that the repair failed and the pointer was not updated +// - Expects that the repair failed and the pointer was not updated. func TestCorruptDataRepairInMemory_Failed(t *testing.T) { testCorruptDataRepairFailed(t, true) } @@ -288,7 +288,7 @@ func testCorruptDataRepairFailed(t *testing.T, inMemoryRepair bool) { // - On one of the remaining nodes, corrupt the piece data being stored by that node // - Triggers data repair, which attempts to repair the data from the remaining nodes to // the numbers of nodes determined by the upload repair max threshold -// - Expects that the repair succeed and the pointer should not contain the corrupted piece +// - Expects that the repair succeed and the pointer should not contain the corrupted piece. func TestCorruptDataRepairInMemory_Succeed(t *testing.T) { testCorruptDataRepairSucceed(t, true) } @@ -407,7 +407,7 @@ func testCorruptDataRepairSucceed(t *testing.T, inMemoryRepair bool) { // - Call checker to add segment to the repair queue // - Modify segment to be expired // - Run the repairer -// - Verify segment is no longer in the repair queue +// - Verify segment is no longer in the repair queue. func TestRemoveExpiredSegmentFromQueue(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, @@ -495,7 +495,7 @@ func TestRemoveExpiredSegmentFromQueue(t *testing.T) { // - Call checker to add segment to the repair queue // - Delete segment from the satellite database // - Run the repairer -// - Verify segment is no longer in the repair queue +// - Verify segment is no longer in the repair queue. func TestRemoveDeletedSegmentFromQueue(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, @@ -576,7 +576,7 @@ func TestRemoveDeletedSegmentFromQueue(t *testing.T) { // - Disqualify nodes so that online nodes < minimum threshold // - Run the repairer // - Verify segment is no longer in the repair queue and segment should be the same -// - Verify segment is now in the irreparable db instead +// - Verify segment is now in the irreparable db instead. func TestIrreparableSegmentAccordingToOverlay(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, @@ -681,7 +681,7 @@ func updateNodeCheckIn(ctx context.Context, overlayDB overlay.DB, node *testplan // - Kill (as opposed to disqualifying) nodes so that online nodes < minimum threshold // - Run the repairer // - Verify segment is no longer in the repair queue and segment should be the same -// - Verify segment is now in the irreparable db instead +// - Verify segment is now in the irreparable db instead. func TestIrreparableSegmentNodesOffline(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, @@ -782,7 +782,7 @@ func TestIrreparableSegmentNodesOffline(t *testing.T) { // - Shuts down the 4 nodes from which the data was repaired // - Now we have just the 3 new nodes to which the data was repaired // - Downloads the data from these 3 nodes (succeeds because 3 nodes are enough for download) -// - Expect newly repaired pointer does not contain the disqualified or suspended nodes +// - Expect newly repaired pointer does not contain the disqualified or suspended nodes. func TestRepairMultipleDisqualifiedAndSuspendedInMemory(t *testing.T) { testRepairMultipleDisqualifiedAndSuspended(t, true) } @@ -1249,7 +1249,7 @@ func testDataRepairUploadLimit(t *testing.T, inMemoryRepair bool) { // - Shuts down the 4 nodes from which the data was repaired // - Now we have just the 3 new nodes to which the data was repaired // - Downloads the data from these 3 nodes (succeeds because 3 nodes are enough for download) -// - Expect newly repaired pointer does not contain the gracefully exited nodes +// - Expect newly repaired pointer does not contain the gracefully exited nodes. func TestRepairGracefullyExitedInMemory(t *testing.T) { testRepairGracefullyExited(t, true) } diff --git a/satellite/repair/repairer/repairer.go b/satellite/repair/repairer/repairer.go index c6a2c3406..a26c19a76 100644 --- a/satellite/repair/repairer/repairer.go +++ b/satellite/repair/repairer/repairer.go @@ -26,7 +26,7 @@ var ( mon = monkit.Package() ) -// Config contains configurable values for repairer +// Config contains configurable values for repairer. type Config struct { MaxRepair int `help:"maximum segments that can be repaired concurrently" releaseDefault:"5" devDefault:"1"` Interval time.Duration `help:"how frequently repairer should try and repair more data" releaseDefault:"5m0s" devDefault:"1m0s"` @@ -51,7 +51,7 @@ type Service struct { irrDB irreparable.DB } -// NewService creates repairing service +// NewService creates repairing service. func NewService(log *zap.Logger, queue queue.RepairQueue, config *Config, repairer *SegmentRepairer, irrDB irreparable.DB) *Service { return &Service{ log: log, @@ -64,7 +64,7 @@ func NewService(log *zap.Logger, queue queue.RepairQueue, config *Config, repair } } -// Close closes resources +// Close closes resources. func (service *Service) Close() error { return nil } // WaitForPendingRepairs waits for all ongoing repairs to complete. @@ -81,7 +81,7 @@ func (service *Service) WaitForPendingRepairs() { service.JobLimiter.Release(int64(service.config.MaxRepair)) } -// Run runs the repairer service +// Run runs the repairer service. func (service *Service) Run(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) @@ -106,7 +106,7 @@ func (service *Service) processWhileQueueHasItems(ctx context.Context) error { } } -// process picks items from repair queue and spawns a repair worker +// process picks items from repair queue and spawns a repair worker. func (service *Service) process(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) diff --git a/satellite/repair/repairer/segments.go b/satellite/repair/repairer/segments.go index 9915a5021..1c2b05965 100644 --- a/satellite/repair/repairer/segments.go +++ b/satellite/repair/repairer/segments.go @@ -46,7 +46,7 @@ func (ie *irreparableError) Error() string { return fmt.Sprintf("%d available pieces < %d required", ie.piecesAvailable, ie.piecesRequired) } -// SegmentRepairer for segments +// SegmentRepairer for segments. type SegmentRepairer struct { log *zap.Logger metainfo *metainfo.Service @@ -95,7 +95,7 @@ func NewSegmentRepairer( // Repair retrieves an at-risk segment and repairs and stores lost pieces on new nodes // note that shouldDelete is used even in the case where err is not null -// note that it will update audit status as failed for nodes that failed piece hash verification during repair downloading +// note that it will update audit status as failed for nodes that failed piece hash verification during repair downloading. func (repairer *SegmentRepairer) Repair(ctx context.Context, path storj.Path) (shouldDelete bool, err error) { defer mon.Task()(&ctx, path)(&err) @@ -347,7 +347,7 @@ func (repairer *SegmentRepairer) updateAuditFailStatus(ctx context.Context, fail return 0, nil } -// sliceToSet converts the given slice to a set +// sliceToSet converts the given slice to a set. func sliceToSet(slice []int32) map[int32]bool { set := make(map[int32]bool, len(slice)) for _, value := range slice { diff --git a/satellite/revocation/revocation.go b/satellite/revocation/revocation.go index bc2e2b92c..6980e3ceb 100644 --- a/satellite/revocation/revocation.go +++ b/satellite/revocation/revocation.go @@ -5,7 +5,7 @@ package revocation import "context" -// DB is the interface for a revocation DB +// DB is the interface for a revocation DB. type DB interface { // Revoke is the method to revoke the supplied tail Revoke(ctx context.Context, tail []byte, apiKeyID []byte) error diff --git a/satellite/rewards/partners_service.go b/satellite/rewards/partners_service.go index 7f8270324..906cd99e4 100644 --- a/satellite/rewards/partners_service.go +++ b/satellite/rewards/partners_service.go @@ -54,7 +54,7 @@ func NewPartnersService(log *zap.Logger, db PartnersDB, domains []string) *Partn } } -// parnterIDEncoding is base32 without padding +// parnterIDEncoding is base32 without padding. var parnterIDEncoding = base32.StdEncoding.WithPadding(base32.NoPadding) // GeneratePartnerLink returns partner referral link. diff --git a/satellite/rewards/rewards.go b/satellite/rewards/rewards.go index 21d48c1c1..e57bc15db 100644 --- a/satellite/rewards/rewards.go +++ b/satellite/rewards/rewards.go @@ -29,7 +29,7 @@ type DB interface { Finish(ctx context.Context, offerID int) error } -// NewOffer holds information that's needed for creating a new offer +// NewOffer holds information that's needed for creating a new offer. type NewOffer struct { Name string Description string @@ -48,14 +48,14 @@ type NewOffer struct { Type OfferType } -// UpdateOffer holds fields needed for update an offer +// UpdateOffer holds fields needed for update an offer. type UpdateOffer struct { ID int Status OfferStatus ExpiresAt time.Time } -// RedeemOffer holds field needed for redeem an offer +// RedeemOffer holds field needed for redeem an offer. type RedeemOffer struct { RedeemableCap int Status OfferStatus @@ -65,7 +65,7 @@ type RedeemOffer struct { // Offers contains a slice of offers. type Offers []Offer -// OfferType indicates the type of an offer +// OfferType indicates the type of an offer. type OfferType int const ( @@ -91,7 +91,7 @@ const ( Active ) -// Offer contains info needed for giving users free credits through different offer programs +// Offer contains info needed for giving users free credits through different offer programs. type Offer struct { ID int Name string @@ -122,7 +122,7 @@ func (offer Offer) IsZero() bool { return offer == Offer{} } -// IsDefault checks if a offer's status is default +// IsDefault checks if a offer's status is default. func (status OfferStatus) IsDefault() bool { return status == Default } diff --git a/satellite/satellitedb/apikeys.go b/satellite/satellitedb/apikeys.go index 16c50b261..e5cf5deeb 100644 --- a/satellite/satellitedb/apikeys.go +++ b/satellite/satellitedb/apikeys.go @@ -18,7 +18,7 @@ import ( // ensures that apikeys implements console.APIKeys. var _ console.APIKeys = (*apikeys)(nil) -// apikeys is an implementation of satellite.APIKeys +// apikeys is an implementation of satellite.APIKeys. type apikeys struct { methods dbx.Methods lru *cache.ExpiringLRU @@ -122,7 +122,7 @@ func (keys *apikeys) GetPagedByProjectID(ctx context.Context, projectID uuid.UUI return page, err } -// Get implements satellite.APIKeys +// Get implements satellite.APIKeys. func (keys *apikeys) Get(ctx context.Context, id uuid.UUID) (_ *console.APIKeyInfo, err error) { defer mon.Task()(&ctx)(&err) dbKey, err := keys.methods.Get_ApiKey_By_Id(ctx, dbx.ApiKey_Id(id[:])) @@ -133,7 +133,7 @@ func (keys *apikeys) Get(ctx context.Context, id uuid.UUID) (_ *console.APIKeyIn return fromDBXAPIKey(ctx, dbKey) } -// GetByHead implements satellite.APIKeys +// GetByHead implements satellite.APIKeys. func (keys *apikeys) GetByHead(ctx context.Context, head []byte) (_ *console.APIKeyInfo, err error) { defer mon.Task()(&ctx)(&err) @@ -150,7 +150,7 @@ func (keys *apikeys) GetByHead(ctx context.Context, head []byte) (_ *console.API return fromDBXAPIKey(ctx, dbKey) } -// GetByNameAndProjectID implements satellite.APIKeys +// GetByNameAndProjectID implements satellite.APIKeys. func (keys *apikeys) GetByNameAndProjectID(ctx context.Context, name string, projectID uuid.UUID) (_ *console.APIKeyInfo, err error) { defer mon.Task()(&ctx)(&err) dbKey, err := keys.methods.Get_ApiKey_By_Name_And_ProjectId(ctx, @@ -163,7 +163,7 @@ func (keys *apikeys) GetByNameAndProjectID(ctx context.Context, name string, pro return fromDBXAPIKey(ctx, dbKey) } -// Create implements satellite.APIKeys +// Create implements satellite.APIKeys. func (keys *apikeys) Create(ctx context.Context, head []byte, info console.APIKeyInfo) (_ *console.APIKeyInfo, err error) { defer mon.Task()(&ctx)(&err) id, err := uuid.New() @@ -193,7 +193,7 @@ func (keys *apikeys) Create(ctx context.Context, head []byte, info console.APIKe return fromDBXAPIKey(ctx, dbKey) } -// Update implements satellite.APIKeys +// Update implements satellite.APIKeys. func (keys *apikeys) Update(ctx context.Context, key console.APIKeyInfo) (err error) { defer mon.Task()(&ctx)(&err) return keys.methods.UpdateNoReturn_ApiKey_By_Id( @@ -205,14 +205,14 @@ func (keys *apikeys) Update(ctx context.Context, key console.APIKeyInfo) (err er ) } -// Delete implements satellite.APIKeys +// Delete implements satellite.APIKeys. func (keys *apikeys) Delete(ctx context.Context, id uuid.UUID) (err error) { defer mon.Task()(&ctx)(&err) _, err = keys.methods.Delete_ApiKey_By_Id(ctx, dbx.ApiKey_Id(id[:])) return err } -// fromDBXAPIKey converts dbx.ApiKey to satellite.APIKeyInfo +// fromDBXAPIKey converts dbx.ApiKey to satellite.APIKeyInfo. func fromDBXAPIKey(ctx context.Context, key *dbx.ApiKey) (_ *console.APIKeyInfo, err error) { defer mon.Task()(&ctx)(&err) id, err := uuid.FromBytes(key.Id) @@ -243,7 +243,7 @@ func fromDBXAPIKey(ctx context.Context, key *dbx.ApiKey) (_ *console.APIKeyInfo, return result, nil } -// sanitizedAPIKeyOrderColumnName return valid order by column +// sanitizedAPIKeyOrderColumnName return valid order by column. func sanitizedAPIKeyOrderColumnName(pmo console.APIKeyOrder) string { if pmo == 2 { return "ak.created_at" diff --git a/satellite/satellitedb/attribution.go b/satellite/satellitedb/attribution.go index 2ca4a2dbe..b23150b75 100644 --- a/satellite/satellitedb/attribution.go +++ b/satellite/satellitedb/attribution.go @@ -113,7 +113,7 @@ type attributionDB struct { db *satelliteDB } -// Get reads the partner info +// Get reads the partner info. func (keys *attributionDB) Get(ctx context.Context, projectID uuid.UUID, bucketName []byte) (info *attribution.Info, err error) { defer mon.Task()(&ctx)(&err) @@ -131,7 +131,7 @@ func (keys *attributionDB) Get(ctx context.Context, projectID uuid.UUID, bucketN return attributionFromDBX(dbxInfo) } -// Insert implements create partner info +// Insert implements create partner info. func (keys *attributionDB) Insert(ctx context.Context, info *attribution.Info) (_ *attribution.Info, err error) { defer mon.Task()(&ctx)(&err) @@ -147,7 +147,7 @@ func (keys *attributionDB) Insert(ctx context.Context, info *attribution.Info) ( return attributionFromDBX(dbxInfo) } -// QueryAttribution queries partner bucket attribution data +// QueryAttribution queries partner bucket attribution data. func (keys *attributionDB) QueryAttribution(ctx context.Context, partnerID uuid.UUID, start time.Time, end time.Time) (_ []*attribution.CSVRow, err error) { defer mon.Task()(&ctx)(&err) diff --git a/satellite/satellitedb/compensation.go b/satellite/satellitedb/compensation.go index 482c7e53b..96bc93ec8 100644 --- a/satellite/satellitedb/compensation.go +++ b/satellite/satellitedb/compensation.go @@ -42,7 +42,7 @@ func (comp *compensationDB) QueryPaidInYear(ctx context.Context, nodeID storj.No return currency.NewMicroUnit(sumPaid), nil } -// QueryWithheldAmounts returns withheld data for the given node +// QueryWithheldAmounts returns withheld data for the given node. func (comp *compensationDB) QueryWithheldAmounts(ctx context.Context, nodeID storj.NodeID) (_ compensation.WithheldAmounts, err error) { defer mon.Task()(&ctx)(&err) diff --git a/satellite/satellitedb/containment.go b/satellite/satellitedb/containment.go index d2384c2a5..1ecaaa11d 100644 --- a/satellite/satellitedb/containment.go +++ b/satellite/satellitedb/containment.go @@ -21,7 +21,7 @@ type containment struct { db *satelliteDB } -// Get gets the pending audit by node id +// Get gets the pending audit by node id. func (containment *containment) Get(ctx context.Context, id pb.NodeID) (_ *audit.PendingAudit, err error) { defer mon.Task()(&ctx)(&err) if id.IsZero() { @@ -39,7 +39,7 @@ func (containment *containment) Get(ctx context.Context, id pb.NodeID) (_ *audit return convertDBPending(ctx, pending) } -// IncrementPending creates a new pending audit entry, or increases its reverify count if it already exists +// IncrementPending creates a new pending audit entry, or increases its reverify count if it already exists. func (containment *containment) IncrementPending(ctx context.Context, pendingAudit *audit.PendingAudit) (err error) { defer mon.Task()(&ctx)(&err) err = containment.db.WithTx(ctx, func(ctx context.Context, tx *dbx.Tx) error { @@ -81,7 +81,7 @@ func (containment *containment) IncrementPending(ctx context.Context, pendingAud return audit.ContainError.Wrap(err) } -// Delete deletes the pending audit +// Delete deletes the pending audit. func (containment *containment) Delete(ctx context.Context, id pb.NodeID) (isDeleted bool, err error) { defer mon.Task()(&ctx)(&err) if id.IsZero() { diff --git a/satellite/satellitedb/coupons.go b/satellite/satellitedb/coupons.go index cc62c4f03..f022747a6 100644 --- a/satellite/satellitedb/coupons.go +++ b/satellite/satellitedb/coupons.go @@ -87,7 +87,7 @@ func (coupons *coupons) Get(ctx context.Context, couponID uuid.UUID) (_ payments return fromDBXCoupon(dbxCoupon) } -// Delete removes a coupon from the database by its ID +// Delete removes a coupon from the database by its ID. func (coupons *coupons) Delete(ctx context.Context, couponID uuid.UUID) (err error) { defer mon.Task()(&ctx, couponID)(&err) diff --git a/satellite/satellitedb/database.go b/satellite/satellitedb/database.go index 07d34a9bd..4eda0b168 100644 --- a/satellite/satellitedb/database.go +++ b/satellite/satellitedb/database.go @@ -55,7 +55,7 @@ type satelliteDB struct { revocationDB *revocationDB } -// Options includes options for how a satelliteDB runs +// Options includes options for how a satelliteDB runs. type Options struct { APIKeysLRUOptions cache.Options RevocationLRUOptions cache.Options @@ -67,7 +67,7 @@ type Options struct { var _ dbx.DBMethods = &satelliteDB{} -// New creates instance of database supports postgres +// New creates instance of database supports postgres. func New(log *zap.Logger, databaseURL string, opts Options) (satellite.DB, error) { driver, source, implementation, err := dbutil.SplitConnStr(databaseURL) if err != nil { @@ -104,42 +104,42 @@ func New(log *zap.Logger, databaseURL string, opts Options) (satellite.DB, error // should not be used outside of migration tests. func (db *satelliteDB) TestDBAccess() *dbx.DB { return db.DB } -// PeerIdentities returns a storage for peer identities +// PeerIdentities returns a storage for peer identities. func (db *satelliteDB) PeerIdentities() overlay.PeerIdentities { return &peerIdentities{db: db} } -// Attribution is a getter for value attribution repository +// Attribution is a getter for value attribution repository. func (db *satelliteDB) Attribution() attribution.DB { return &attributionDB{db: db} } -// OverlayCache is a getter for overlay cache repository +// OverlayCache is a getter for overlay cache repository. func (db *satelliteDB) OverlayCache() overlay.DB { return &overlaycache{db: db} } -// RepairQueue is a getter for RepairQueue repository +// RepairQueue is a getter for RepairQueue repository. func (db *satelliteDB) RepairQueue() queue.RepairQueue { return &repairQueue{db: db} } -// StoragenodeAccounting returns database for tracking storagenode usage +// StoragenodeAccounting returns database for tracking storagenode usage. func (db *satelliteDB) StoragenodeAccounting() accounting.StoragenodeAccounting { return &StoragenodeAccounting{db: db} } -// ProjectAccounting returns database for tracking project data use +// ProjectAccounting returns database for tracking project data use. func (db *satelliteDB) ProjectAccounting() accounting.ProjectAccounting { return &ProjectAccounting{db: db} } -// Irreparable returns database for storing segments that failed repair +// Irreparable returns database for storing segments that failed repair. func (db *satelliteDB) Irreparable() irreparable.DB { return &irreparableDB{db: db} } -// Revocation returns the database to deal with macaroon revocation +// Revocation returns the database to deal with macaroon revocation. func (db *satelliteDB) Revocation() revocation.DB { db.revocationDBOnce.Do(func() { db.revocationDB = &revocationDB{ @@ -151,7 +151,7 @@ func (db *satelliteDB) Revocation() revocation.DB { return db.revocationDB } -// Console returns database for storing users, projects and api keys +// Console returns database for storing users, projects and api keys. func (db *satelliteDB) Console() console.DB { db.consoleDBOnce.Do(func() { db.consoleDB = &ConsoleDB{ @@ -167,22 +167,22 @@ func (db *satelliteDB) Console() console.DB { return db.consoleDB } -// Rewards returns database for storing offers +// Rewards returns database for storing offers. func (db *satelliteDB) Rewards() rewards.DB { return &offersDB{db: db} } -// Orders returns database for storing orders +// Orders returns database for storing orders. func (db *satelliteDB) Orders() orders.DB { return &ordersDB{db: db, reportedRollupsReadBatchSize: db.opts.ReportedRollupsReadBatchSize} } -// Containment returns database for storing pending audit info +// Containment returns database for storing pending audit info. func (db *satelliteDB) Containment() audit.Containment { return &containment{db: db} } -// GracefulExit returns database for graceful exit +// GracefulExit returns database for graceful exit. func (db *satelliteDB) GracefulExit() gracefulexit.DB { return &gracefulexitDB{db: db} } @@ -192,17 +192,17 @@ func (db *satelliteDB) StripeCoinPayments() stripecoinpayments.DB { return &stripeCoinPaymentsDB{db: db} } -// DowntimeTracking returns database for downtime tracking +// DowntimeTracking returns database for downtime tracking. func (db *satelliteDB) DowntimeTracking() downtime.DB { return &downtimeTrackingDB{db: db} } -// HeldAmount returns database for storagenode payStubs and payments info +// HeldAmount returns database for storagenode payStubs and payments info. func (db *satelliteDB) HeldAmount() heldamount.DB { return &paymentStubs{db: db} } -// Compenstation returns database for storage node compensation +// Compenstation returns database for storage node compensation. func (db *satelliteDB) Compensation() compensation.DB { return &compensationDB{db: db} } diff --git a/satellite/satellitedb/dbx/gen.go b/satellite/satellitedb/dbx/gen.go index 517506b11..30753a0b0 100644 --- a/satellite/satellitedb/dbx/gen.go +++ b/satellite/satellitedb/dbx/gen.go @@ -62,7 +62,7 @@ func (err *constraintError) Error() string { return fmt.Sprintf("violates constraint %q: %v", err.constraint, err.err) } -// WithTx wraps DB code in a transaction +// WithTx wraps DB code in a transaction. func (db *DB) WithTx(ctx context.Context, fn func(context.Context, *Tx) error) (err error) { return txutil.WithTx(ctx, db, nil, func(ctx context.Context, tx tagsql.Tx) error { return fn(ctx, &Tx{ diff --git a/satellite/satellitedb/dbx/satellitedb.dbx.go b/satellite/satellitedb/dbx/satellitedb.dbx.go index aaefeb576..402c71a9e 100644 --- a/satellite/satellitedb/dbx/satellitedb.dbx.go +++ b/satellite/satellitedb/dbx/satellitedb.dbx.go @@ -23,7 +23,7 @@ import ( "storj.io/storj/private/tagsql" ) -// Prevent conditional imports from causing build failures +// Prevent conditional imports from causing build failures. var _ = strconv.Itoa var _ = strings.LastIndex var _ = fmt.Sprint diff --git a/satellite/satellitedb/invoiceprojectrecords.go b/satellite/satellitedb/invoiceprojectrecords.go index ae9f56834..d6ce3cd39 100644 --- a/satellite/satellitedb/invoiceprojectrecords.go +++ b/satellite/satellitedb/invoiceprojectrecords.go @@ -190,7 +190,7 @@ func (db *invoiceProjectRecords) ListUnapplied(ctx context.Context, offset int64 return page, nil } -// fromDBXInvoiceProjectRecord converts *dbx.StripecoinpaymentsInvoiceProjectRecord to *stripecoinpayments.ProjectRecord +// fromDBXInvoiceProjectRecord converts *dbx.StripecoinpaymentsInvoiceProjectRecord to *stripecoinpayments.ProjectRecord. func fromDBXInvoiceProjectRecord(dbxRecord *dbx.StripecoinpaymentsInvoiceProjectRecord) (*stripecoinpayments.ProjectRecord, error) { id, err := uuid.FromBytes(dbxRecord.Id) if err != nil { diff --git a/satellite/satellitedb/irreparabledb.go b/satellite/satellitedb/irreparabledb.go index 2332e9cdd..0422bbe9c 100644 --- a/satellite/satellitedb/irreparabledb.go +++ b/satellite/satellitedb/irreparabledb.go @@ -16,7 +16,7 @@ type irreparableDB struct { db *satelliteDB } -// IncrementRepairAttempts a db entry for to increment the repair attempts field +// IncrementRepairAttempts a db entry for to increment the repair attempts field. func (db *irreparableDB) IncrementRepairAttempts(ctx context.Context, segmentInfo *pb.IrreparableSegment) (err error) { defer mon.Task()(&ctx)(&err) err = db.db.WithTx(ctx, func(ctx context.Context, tx *dbx.Tx) (err error) { @@ -56,7 +56,7 @@ func (db *irreparableDB) IncrementRepairAttempts(ctx context.Context, segmentInf return Error.Wrap(err) } -// Get a irreparable's segment info from the db +// Get a irreparable's segment info from the db. func (db *irreparableDB) Get(ctx context.Context, segmentPath []byte) (resp *pb.IrreparableSegment, err error) { defer mon.Task()(&ctx)(&err) dbxInfo, err := db.db.Get_Irreparabledb_By_Segmentpath(ctx, dbx.Irreparabledb_Segmentpath(segmentPath)) @@ -80,7 +80,7 @@ func (db *irreparableDB) Get(ctx context.Context, segmentPath []byte) (resp *pb. }, nil } -// GetLimited returns a list of irreparable segment info starting after the last segment info we retrieved +// GetLimited returns a list of irreparable segment info starting after the last segment info we retrieved. func (db *irreparableDB) GetLimited(ctx context.Context, limit int, lastSeenSegmentPath []byte) (resp []*pb.IrreparableSegment, err error) { defer mon.Task()(&ctx)(&err) // the offset is hardcoded to 0 since we are using the lastSeenSegmentPath to @@ -113,7 +113,7 @@ func (db *irreparableDB) GetLimited(ctx context.Context, limit int, lastSeenSegm return resp, err } -// Delete a irreparable's segment info from the db +// Delete a irreparable's segment info from the db. func (db *irreparableDB) Delete(ctx context.Context, segmentPath []byte) (err error) { defer mon.Task()(&ctx)(&err) _, err = db.db.Delete_Irreparabledb_By_Segmentpath(ctx, dbx.Irreparabledb_Segmentpath(segmentPath)) diff --git a/satellite/satellitedb/migrate.go b/satellite/satellitedb/migrate.go index 5b08a9bc4..bacd00129 100644 --- a/satellite/satellitedb/migrate.go +++ b/satellite/satellitedb/migrate.go @@ -132,7 +132,7 @@ func (db *satelliteDB) TestingMigrateToLatest(ctx context.Context) error { } } -// CheckVersion confirms the database is at the desired version +// CheckVersion confirms the database is at the desired version. func (db *satelliteDB) CheckVersion(ctx context.Context) error { switch db.implementation { case dbutil.Postgres, dbutil.Cockroach: diff --git a/satellite/satellitedb/migrate_test.go b/satellite/satellitedb/migrate_test.go index 7b8f5c47c..44e1b2844 100644 --- a/satellite/satellitedb/migrate_test.go +++ b/satellite/satellitedb/migrate_test.go @@ -30,7 +30,7 @@ import ( "storj.io/storj/satellite/satellitedb/dbx" ) -// loadSnapshots loads all the dbschemas from testdata/postgres.* +// loadSnapshots loads all the dbschemas from testdata/postgres.*. func loadSnapshots(ctx context.Context, connstr, dbxscript string) (*dbschema.Snapshots, *dbschema.Schema, error) { snapshots := &dbschema.Snapshots{} diff --git a/satellite/satellitedb/offers.go b/satellite/satellitedb/offers.go index 762a43987..c39c9e2f6 100644 --- a/satellite/satellitedb/offers.go +++ b/satellite/satellitedb/offers.go @@ -26,7 +26,7 @@ type offersDB struct { db *satelliteDB } -// ListAll returns all offersDB from the db +// ListAll returns all offersDB from the db. func (db *offersDB) ListAll(ctx context.Context) (rewards.Offers, error) { offersDbx, err := db.db.All_Offer_OrderBy_Asc_Id(ctx) if err != nil { @@ -36,7 +36,7 @@ func (db *offersDB) ListAll(ctx context.Context) (rewards.Offers, error) { return offersFromDBX(offersDbx) } -// GetCurrent returns offers that has not expired based on offer type +// GetCurrent returns offers that has not expired based on offer type. func (db *offersDB) GetActiveOffersByType(ctx context.Context, offerType rewards.OfferType) (rewards.Offers, error) { var statement string const columns = "id, name, description, award_credit_in_cents, invitee_credit_in_cents, award_credit_duration_days, invitee_credit_duration_days, redeemable_cap, expires_at, created_at, status, type" @@ -96,7 +96,7 @@ func (db *offersDB) GetActiveOffersByType(ctx context.Context, offerType rewards return results, rows.Err() } -// Create inserts a new offer into the db +// Create inserts a new offer into the db. func (db *offersDB) Create(ctx context.Context, o *rewards.NewOffer) (*rewards.Offer, error) { currentTime := time.Now().UTC() if o.ExpiresAt.Before(currentTime) { @@ -169,7 +169,7 @@ func (db *offersDB) Create(ctx context.Context, o *rewards.NewOffer) (*rewards.O }, offerErr.Wrap(err) } -// Finish changes the offer status to be Done and its expiration date to be now based on offer id +// Finish changes the offer status to be Done and its expiration date to be now based on offer id. func (db *offersDB) Finish(ctx context.Context, oID int) error { return offerErr.Wrap( db.db.UpdateNoReturn_Offer_By_Id(ctx, diff --git a/satellite/satellitedb/overlaycache.go b/satellite/satellitedb/overlaycache.go index ee5b4a8c2..0b99ce31d 100644 --- a/satellite/satellitedb/overlaycache.go +++ b/satellite/satellitedb/overlaycache.go @@ -35,7 +35,7 @@ type overlaycache struct { db *satelliteDB } -// SelectAllStorageNodesUpload returns all nodes that qualify to store data, organized as reputable nodes and new nodes +// SelectAllStorageNodesUpload returns all nodes that qualify to store data, organized as reputable nodes and new nodes. func (cache *overlaycache) SelectAllStorageNodesUpload(ctx context.Context, selectionCfg overlay.NodeSelectionConfig) (reputable, new []*overlay.SelectedNode, err error) { defer mon.Task()(&ctx)(&err) @@ -128,7 +128,7 @@ func (cache *overlaycache) GetNodesNetwork(ctx context.Context, nodeIDs []storj. return nodeNets, Error.Wrap(rows.Err()) } -// Get looks up the node by nodeID +// Get looks up the node by nodeID. func (cache *overlaycache) Get(ctx context.Context, id storj.NodeID) (_ *overlay.NodeDossier, err error) { defer mon.Task()(&ctx)(&err) @@ -147,7 +147,7 @@ func (cache *overlaycache) Get(ctx context.Context, id storj.NodeID) (_ *overlay return convertDBNode(ctx, node) } -// GetOnlineNodesForGetDelete returns a map of nodes for the supplied nodeIDs +// GetOnlineNodesForGetDelete returns a map of nodes for the supplied nodeIDs. func (cache *overlaycache) GetOnlineNodesForGetDelete(ctx context.Context, nodeIDs []storj.NodeID, onlineWindow time.Duration) (_ map[storj.NodeID]*overlay.SelectedNode, err error) { defer mon.Task()(&ctx)(&err) @@ -185,7 +185,7 @@ func (cache *overlaycache) GetOnlineNodesForGetDelete(ctx context.Context, nodeI return nodes, Error.Wrap(rows.Err()) } -// KnownOffline filters a set of nodes to offline nodes +// KnownOffline filters a set of nodes to offline nodes. func (cache *overlaycache) KnownOffline(ctx context.Context, criteria *overlay.NodeCriteria, nodeIds storj.NodeIDList) (offlineNodes storj.NodeIDList, err error) { defer mon.Task()(&ctx)(&err) @@ -217,7 +217,7 @@ func (cache *overlaycache) KnownOffline(ctx context.Context, criteria *overlay.N return offlineNodes, Error.Wrap(rows.Err()) } -// KnownUnreliableOrOffline filters a set of nodes to unreliable or offlines node, independent of new +// KnownUnreliableOrOffline filters a set of nodes to unreliable or offlines node, independent of new. func (cache *overlaycache) KnownUnreliableOrOffline(ctx context.Context, criteria *overlay.NodeCriteria, nodeIds storj.NodeIDList) (badNodes storj.NodeIDList, err error) { defer mon.Task()(&ctx)(&err) @@ -325,7 +325,7 @@ func (cache *overlaycache) Reliable(ctx context.Context, criteria *overlay.NodeC return nodes, Error.Wrap(rows.Err()) } -// BatchUpdateStats updates multiple storagenode's stats in one transaction +// BatchUpdateStats updates multiple storagenode's stats in one transaction. func (cache *overlaycache) BatchUpdateStats(ctx context.Context, updateRequests []*overlay.UpdateRequest, batchSize int) (failed storj.NodeIDList, err error) { defer mon.Task()(&ctx)(&err) if len(updateRequests) == 0 { @@ -415,7 +415,7 @@ func (cache *overlaycache) BatchUpdateStats(ctx context.Context, updateRequests return failed, errlist.Err() } -// UpdateStats a single storagenode's stats in the db +// UpdateStats a single storagenode's stats in the db. func (cache *overlaycache) UpdateStats(ctx context.Context, updateReq *overlay.UpdateRequest) (stats *overlay.NodeStats, err error) { defer mon.Task()(&ctx)(&err) nodeID := updateReq.NodeID @@ -463,7 +463,7 @@ func (cache *overlaycache) UpdateStats(ctx context.Context, updateReq *overlay.U } // UpdateNodeInfo updates the following fields for a given node ID: -// wallet, email for node operator, free disk, and version +// wallet, email for node operator, free disk, and version. func (cache *overlaycache) UpdateNodeInfo(ctx context.Context, nodeID storj.NodeID, nodeInfo *overlay.InfoResponse) (stats *overlay.NodeDossier, err error) { defer mon.Task()(&ctx)(&err) @@ -501,7 +501,7 @@ func (cache *overlaycache) UpdateNodeInfo(ctx context.Context, nodeID storj.Node return convertDBNode(ctx, updatedDBNode) } -// UpdateUptime updates a single storagenode's uptime stats in the db +// UpdateUptime updates a single storagenode's uptime stats in the db. func (cache *overlaycache) UpdateUptime(ctx context.Context, nodeID storj.NodeID, isUp bool) (stats *overlay.NodeStats, err error) { defer mon.Task()(&ctx)(&err) diff --git a/satellite/satellitedb/peeridentities.go b/satellite/satellitedb/peeridentities.go index b4f21684a..9b14d1b59 100644 --- a/satellite/satellitedb/peeridentities.go +++ b/satellite/satellitedb/peeridentities.go @@ -21,7 +21,7 @@ type peerIdentities struct { db *satelliteDB } -// Set adds a peer identity entry +// Set adds a peer identity entry. func (idents *peerIdentities) Set(ctx context.Context, nodeID storj.NodeID, ident *identity.PeerIdentity) (err error) { defer mon.Task()(&ctx)(&err) @@ -55,7 +55,7 @@ func (idents *peerIdentities) Set(ctx context.Context, nodeID storj.NodeID, iden return Error.Wrap(err) } -// Get gets the peer identity based on the certificate's nodeID +// Get gets the peer identity based on the certificate's nodeID. func (idents *peerIdentities) Get(ctx context.Context, nodeID storj.NodeID) (_ *identity.PeerIdentity, err error) { defer mon.Task()(&ctx)(&err) dbxIdent, err := idents.db.Get_PeerIdentity_By_NodeId(ctx, dbx.PeerIdentity_NodeId(nodeID.Bytes())) @@ -70,7 +70,7 @@ func (idents *peerIdentities) Get(ctx context.Context, nodeID storj.NodeID) (_ * return ident, Error.Wrap(err) } -// BatchGet gets the peer idenities based on the certificate's nodeID +// BatchGet gets the peer idenities based on the certificate's nodeID. func (idents *peerIdentities) BatchGet(ctx context.Context, nodeIDs storj.NodeIDList) (peerIdents []*identity.PeerIdentity, err error) { defer mon.Task()(&ctx)(&err) if len(nodeIDs) == 0 { diff --git a/satellite/satellitedb/projectmembers.go b/satellite/satellitedb/projectmembers.go index 3d90fbca9..eaea589cf 100644 --- a/satellite/satellitedb/projectmembers.go +++ b/satellite/satellitedb/projectmembers.go @@ -166,7 +166,7 @@ func (pm *projectMembers) Delete(ctx context.Context, memberID, projectID uuid.U return err } -// projectMemberFromDBX is used for creating ProjectMember entity from autogenerated dbx.ProjectMember struct +// projectMemberFromDBX is used for creating ProjectMember entity from autogenerated dbx.ProjectMember struct. func projectMemberFromDBX(ctx context.Context, projectMember *dbx.ProjectMember) (_ *console.ProjectMember, err error) { defer mon.Task()(&ctx)(&err) if projectMember == nil { @@ -190,7 +190,7 @@ func projectMemberFromDBX(ctx context.Context, projectMember *dbx.ProjectMember) }, nil } -// sanitizedOrderColumnName return valid order by column +// sanitizedOrderColumnName return valid order by column. func sanitizedOrderColumnName(pmo console.ProjectMemberOrder) string { switch pmo { case 2: @@ -210,7 +210,7 @@ func sanitizeOrderDirectionName(pmo console.OrderDirection) string { return "ASC" } -// projectMembersFromDbxSlice is used for creating []ProjectMember entities from autogenerated []*dbx.ProjectMember struct +// projectMembersFromDbxSlice is used for creating []ProjectMember entities from autogenerated []*dbx.ProjectMember struct. func projectMembersFromDbxSlice(ctx context.Context, projectMembersDbx []*dbx.ProjectMember) (_ []console.ProjectMember, err error) { defer mon.Task()(&ctx)(&err) var projectMembers []console.ProjectMember diff --git a/satellite/satellitedb/projects.go b/satellite/satellitedb/projects.go index 9900d190e..b72070de1 100644 --- a/satellite/satellitedb/projects.go +++ b/satellite/satellitedb/projects.go @@ -47,7 +47,7 @@ func (projects *projects) GetOwn(ctx context.Context, userID uuid.UUID) (_ []con return projectsFromDbxSlice(ctx, projectsDbx) } -// GetCreatedBefore retrieves all projects created before provided date +// GetCreatedBefore retrieves all projects created before provided date. func (projects *projects) GetCreatedBefore(ctx context.Context, before time.Time) (_ []console.Project, err error) { defer mon.Task()(&ctx)(&err) @@ -122,7 +122,7 @@ func (projects *projects) Delete(ctx context.Context, id uuid.UUID) (err error) return err } -// Update is a method for updating project entity +// Update is a method for updating project entity. func (projects *projects) Update(ctx context.Context, project *console.Project) (err error) { defer mon.Task()(&ctx)(&err) @@ -201,7 +201,7 @@ func (projects *projects) List(ctx context.Context, offset int64, limit int, bef return page, nil } -// projectFromDBX is used for creating Project entity from autogenerated dbx.Project struct +// projectFromDBX is used for creating Project entity from autogenerated dbx.Project struct. func projectFromDBX(ctx context.Context, project *dbx.Project) (_ *console.Project, err error) { defer mon.Task()(&ctx)(&err) @@ -239,7 +239,7 @@ func projectFromDBX(ctx context.Context, project *dbx.Project) (_ *console.Proje }, nil } -// projectsFromDbxSlice is used for creating []Project entities from autogenerated []*dbx.Project struct +// projectsFromDbxSlice is used for creating []Project entities from autogenerated []*dbx.Project struct. func projectsFromDbxSlice(ctx context.Context, projectsDbx []*dbx.Project) (_ []console.Project, err error) { defer mon.Task()(&ctx)(&err) @@ -260,7 +260,7 @@ func projectsFromDbxSlice(ctx context.Context, projectsDbx []*dbx.Project) (_ [] return projects, errs.Combine(errors...) } -// GetMaxBuckets is a method to get the maximum number of buckets allowed for the project +// GetMaxBuckets is a method to get the maximum number of buckets allowed for the project. func (projects *projects) GetMaxBuckets(ctx context.Context, id uuid.UUID) (maxBuckets int, err error) { defer mon.Task()(&ctx)(&err) diff --git a/satellite/satellitedb/regtokens.go b/satellite/satellitedb/regtokens.go index d8169c8af..fb432ab10 100644 --- a/satellite/satellitedb/regtokens.go +++ b/satellite/satellitedb/regtokens.go @@ -16,12 +16,12 @@ import ( // ensures that registrationTokens implements console.RegistrationTokens. var _ console.RegistrationTokens = (*registrationTokens)(nil) -// registrationTokens is an implementation of RegistrationTokens interface using spacemonkeygo/dbx orm +// registrationTokens is an implementation of RegistrationTokens interface using spacemonkeygo/dbx orm. type registrationTokens struct { db dbx.Methods } -// Create creates new registration token +// Create creates new registration token. func (rt *registrationTokens) Create(ctx context.Context, projectLimit int) (_ *console.RegistrationToken, err error) { defer mon.Task()(&ctx)(&err) secret, err := console.NewRegistrationSecret() @@ -42,7 +42,7 @@ func (rt *registrationTokens) Create(ctx context.Context, projectLimit int) (_ * return registrationTokenFromDBX(ctx, regToken) } -// GetBySecret retrieves RegTokenInfo with given Secret +// GetBySecret retrieves RegTokenInfo with given Secret. func (rt *registrationTokens) GetBySecret(ctx context.Context, secret console.RegistrationSecret) (_ *console.RegistrationToken, err error) { defer mon.Task()(&ctx)(&err) regToken, err := rt.db.Get_RegistrationToken_By_Secret(ctx, dbx.RegistrationToken_Secret(secret[:])) @@ -53,7 +53,7 @@ func (rt *registrationTokens) GetBySecret(ctx context.Context, secret console.Re return registrationTokenFromDBX(ctx, regToken) } -// GetByOwnerID retrieves RegTokenInfo by ownerID +// GetByOwnerID retrieves RegTokenInfo by ownerID. func (rt *registrationTokens) GetByOwnerID(ctx context.Context, ownerID uuid.UUID) (_ *console.RegistrationToken, err error) { defer mon.Task()(&ctx)(&err) regToken, err := rt.db.Get_RegistrationToken_By_OwnerId(ctx, dbx.RegistrationToken_OwnerId(ownerID[:])) @@ -64,7 +64,7 @@ func (rt *registrationTokens) GetByOwnerID(ctx context.Context, ownerID uuid.UUI return registrationTokenFromDBX(ctx, regToken) } -// UpdateOwner updates registration token's owner +// UpdateOwner updates registration token's owner. func (rt *registrationTokens) UpdateOwner(ctx context.Context, secret console.RegistrationSecret, ownerID uuid.UUID) (err error) { defer mon.Task()(&ctx)(&err) _, err = rt.db.Update_RegistrationToken_By_Secret( @@ -78,7 +78,7 @@ func (rt *registrationTokens) UpdateOwner(ctx context.Context, secret console.Re return err } -// registrationTokenFromDBX is used for creating RegistrationToken entity from autogenerated dbx.RegistrationToken struct +// registrationTokenFromDBX is used for creating RegistrationToken entity from autogenerated dbx.RegistrationToken struct. func registrationTokenFromDBX(ctx context.Context, regToken *dbx.RegistrationToken) (_ *console.RegistrationToken, err error) { if regToken == nil { return nil, errs.New("token parameter is nil") diff --git a/satellite/satellitedb/resetpasstokens.go b/satellite/satellitedb/resetpasstokens.go index 00ba0e5d8..eea309132 100644 --- a/satellite/satellitedb/resetpasstokens.go +++ b/satellite/satellitedb/resetpasstokens.go @@ -19,7 +19,7 @@ type resetPasswordTokens struct { db dbx.Methods } -// Create creates new reset password token +// Create creates new reset password token. func (rpt *resetPasswordTokens) Create(ctx context.Context, ownerID uuid.UUID) (_ *console.ResetPasswordToken, err error) { defer mon.Task()(&ctx)(&err) secret, err := console.NewResetPasswordSecret() @@ -39,7 +39,7 @@ func (rpt *resetPasswordTokens) Create(ctx context.Context, ownerID uuid.UUID) ( return resetPasswordTokenFromDBX(ctx, resToken) } -// GetBySecret retrieves ResetPasswordToken with given Secret +// GetBySecret retrieves ResetPasswordToken with given Secret. func (rpt *resetPasswordTokens) GetBySecret(ctx context.Context, secret console.ResetPasswordSecret) (_ *console.ResetPasswordToken, err error) { defer mon.Task()(&ctx)(&err) resToken, err := rpt.db.Get_ResetPasswordToken_By_Secret( @@ -53,7 +53,7 @@ func (rpt *resetPasswordTokens) GetBySecret(ctx context.Context, secret console. return resetPasswordTokenFromDBX(ctx, resToken) } -// GetByOwnerID retrieves ResetPasswordToken by ownerID +// GetByOwnerID retrieves ResetPasswordToken by ownerID. func (rpt *resetPasswordTokens) GetByOwnerID(ctx context.Context, ownerID uuid.UUID) (_ *console.ResetPasswordToken, err error) { defer mon.Task()(&ctx)(&err) resToken, err := rpt.db.Get_ResetPasswordToken_By_OwnerId( @@ -67,7 +67,7 @@ func (rpt *resetPasswordTokens) GetByOwnerID(ctx context.Context, ownerID uuid.U return resetPasswordTokenFromDBX(ctx, resToken) } -// Delete deletes ResetPasswordToken by ResetPasswordSecret +// Delete deletes ResetPasswordToken by ResetPasswordSecret. func (rpt *resetPasswordTokens) Delete(ctx context.Context, secret console.ResetPasswordSecret) (err error) { defer mon.Task()(&ctx)(&err) _, err = rpt.db.Delete_ResetPasswordToken_By_Secret( @@ -78,7 +78,7 @@ func (rpt *resetPasswordTokens) Delete(ctx context.Context, secret console.Reset return err } -// resetPasswordTokenFromDBX is used for creating ResetPasswordToken entity from autogenerated dbx.ResetPasswordToken struct +// resetPasswordTokenFromDBX is used for creating ResetPasswordToken entity from autogenerated dbx.ResetPasswordToken struct. func resetPasswordTokenFromDBX(ctx context.Context, resetToken *dbx.ResetPasswordToken) (_ *console.ResetPasswordToken, err error) { defer mon.Task()(&ctx)(&err) if resetToken == nil { diff --git a/satellite/satellitedb/revocation.go b/satellite/satellitedb/revocation.go index cc2b34a41..37738cc74 100644 --- a/satellite/satellitedb/revocation.go +++ b/satellite/satellitedb/revocation.go @@ -19,12 +19,12 @@ type revocationDB struct { methods dbx.Methods } -// Revoke will revoke the supplied tail +// Revoke will revoke the supplied tail. func (db *revocationDB) Revoke(ctx context.Context, tail []byte, apiKeyID []byte) error { return errs.Wrap(db.methods.CreateNoReturn_Revocation(ctx, dbx.Revocation_Revoked(tail), dbx.Revocation_ApiKeyId(apiKeyID))) } -// Check will check whether any of the supplied tails have been revoked +// Check will check whether any of the supplied tails have been revoked. func (db *revocationDB) Check(ctx context.Context, tails [][]byte) (bool, error) { numTails := len(tails) if numTails == 0 { diff --git a/satellite/satellitedb/satellitedbtest/run.go b/satellite/satellitedb/satellitedbtest/run.go index 6720751b2..78f633745 100644 --- a/satellite/satellitedb/satellitedbtest/run.go +++ b/satellite/satellitedb/satellitedbtest/run.go @@ -27,14 +27,14 @@ import ( "storj.io/storj/satellite/satellitedb/dbx" ) -// SatelliteDatabases maybe name can be better +// SatelliteDatabases maybe name can be better. type SatelliteDatabases struct { Name string MasterDB Database PointerDB Database } -// Database describes a test database +// Database describes a test database. type Database struct { Name string URL string @@ -99,12 +99,12 @@ func (db *tempMasterDB) Close() error { return errs.Combine(db.DB.Close(), db.tempDB.Close()) } -// TestDBAccess provides a somewhat regularized access to the underlying DB +// TestDBAccess provides a somewhat regularized access to the underlying DB. func (db *tempMasterDB) TestDBAccess() *dbx.DB { return db.DB.(interface{ TestDBAccess() *dbx.DB }).TestDBAccess() } -// CreateMasterDB creates a new satellite database for testing +// CreateMasterDB creates a new satellite database for testing. func CreateMasterDB(ctx context.Context, log *zap.Logger, name string, category string, index int, dbInfo Database) (db satellite.DB, err error) { if dbInfo.URL == "" { return nil, fmt.Errorf("Database %s connection string not provided. %s", dbInfo.Name, dbInfo.Message) @@ -140,7 +140,7 @@ func (db *tempPointerDB) Close() error { return errs.Combine(db.PointerDB.Close(), db.tempDB.Close()) } -// CreatePointerDB creates a new satellite pointer database for testing +// CreatePointerDB creates a new satellite pointer database for testing. func CreatePointerDB(ctx context.Context, log *zap.Logger, name string, category string, index int, dbInfo Database) (db metainfo.PointerDB, err error) { if dbInfo.URL == "" { return nil, fmt.Errorf("Database %s connection string not provided. %s", dbInfo.Name, dbInfo.Message) diff --git a/satellite/satellitedb/storagenodeaccounting.go b/satellite/satellitedb/storagenodeaccounting.go index bb1ae4925..2c72d2540 100644 --- a/satellite/satellitedb/storagenodeaccounting.go +++ b/satellite/satellitedb/storagenodeaccounting.go @@ -18,12 +18,12 @@ import ( "storj.io/storj/satellite/satellitedb/dbx" ) -// StoragenodeAccounting implements the accounting/db StoragenodeAccounting interface +// StoragenodeAccounting implements the accounting/db StoragenodeAccounting interface. type StoragenodeAccounting struct { db *satelliteDB } -// SaveTallies records raw tallies of at rest data to the database +// SaveTallies records raw tallies of at rest data to the database. func (db *StoragenodeAccounting) SaveTallies(ctx context.Context, latestTally time.Time, nodeData map[storj.NodeID]float64) (err error) { defer mon.Task()(&ctx)(&err) if len(nodeData) == 0 { @@ -59,7 +59,7 @@ func (db *StoragenodeAccounting) SaveTallies(ctx context.Context, latestTally ti return Error.Wrap(err) } -// GetTallies retrieves all raw tallies +// GetTallies retrieves all raw tallies. func (db *StoragenodeAccounting) GetTallies(ctx context.Context) (_ []*accounting.StoragenodeStorageTally, err error) { defer mon.Task()(&ctx)(&err) raws, err := db.db.All_StoragenodeStorageTally(ctx) @@ -78,7 +78,7 @@ func (db *StoragenodeAccounting) GetTallies(ctx context.Context) (_ []*accountin return out, Error.Wrap(err) } -// GetTalliesSince retrieves all raw tallies since latestRollup +// GetTalliesSince retrieves all raw tallies since latestRollup. func (db *StoragenodeAccounting) GetTalliesSince(ctx context.Context, latestRollup time.Time) (_ []*accounting.StoragenodeStorageTally, err error) { defer mon.Task()(&ctx)(&err) raws, err := db.db.All_StoragenodeStorageTally_By_IntervalEndTime_GreaterOrEqual(ctx, dbx.StoragenodeStorageTally_IntervalEndTime(latestRollup)) @@ -97,7 +97,7 @@ func (db *StoragenodeAccounting) GetTalliesSince(ctx context.Context, latestRoll return out, Error.Wrap(err) } -// GetBandwidthSince retrieves all storagenode_bandwidth_rollup entires since latestRollup +// GetBandwidthSince retrieves all storagenode_bandwidth_rollup entires since latestRollup. func (db *StoragenodeAccounting) GetBandwidthSince(ctx context.Context, latestRollup time.Time) (_ []*accounting.StoragenodeBandwidthRollup, err error) { defer mon.Task()(&ctx)(&err) rollups, err := db.db.All_StoragenodeBandwidthRollup_By_IntervalStart_GreaterOrEqual(ctx, dbx.StoragenodeBandwidthRollup_IntervalStart(latestRollup)) @@ -117,7 +117,7 @@ func (db *StoragenodeAccounting) GetBandwidthSince(ctx context.Context, latestRo return out, Error.Wrap(err) } -// SaveRollup records raw tallies of at rest data to the database +// SaveRollup records raw tallies of at rest data to the database. func (db *StoragenodeAccounting) SaveRollup(ctx context.Context, latestRollup time.Time, stats accounting.RollupStats) (err error) { defer mon.Task()(&ctx)(&err) if len(stats) == 0 { @@ -152,7 +152,7 @@ func (db *StoragenodeAccounting) SaveRollup(ctx context.Context, latestRollup ti return Error.Wrap(err) } -// LastTimestamp records the greatest last tallied time +// LastTimestamp records the greatest last tallied time. func (db *StoragenodeAccounting) LastTimestamp(ctx context.Context, timestampType string) (_ time.Time, err error) { defer mon.Task()(&ctx)(&err) lastTally := time.Time{} @@ -170,7 +170,7 @@ func (db *StoragenodeAccounting) LastTimestamp(ctx context.Context, timestampTyp return lastTally, err } -// QueryPaymentInfo queries Overlay, Accounting Rollup on nodeID +// QueryPaymentInfo queries Overlay, Accounting Rollup on nodeID. func (db *StoragenodeAccounting) QueryPaymentInfo(ctx context.Context, start time.Time, end time.Time) (_ []*accounting.CSVRow, err error) { defer mon.Task()(&ctx)(&err) var sqlStmt = `SELECT n.id, n.created_at, r.at_rest_total, r.get_repair_total, @@ -217,7 +217,7 @@ func (db *StoragenodeAccounting) QueryPaymentInfo(ctx context.Context, start tim return csv, rows.Err() } -// QueryStorageNodePeriodUsage returns usage invoices for nodes for a compensation period +// QueryStorageNodePeriodUsage returns usage invoices for nodes for a compensation period. func (db *StoragenodeAccounting) QueryStorageNodePeriodUsage(ctx context.Context, period compensation.Period) (_ []accounting.StorageNodePeriodUsage, err error) { defer mon.Task()(&ctx)(&err) @@ -271,7 +271,7 @@ func (db *StoragenodeAccounting) QueryStorageNodePeriodUsage(ctx context.Context return usages, rows.Err() } -// QueryStorageNodeUsage returns slice of StorageNodeUsage for given period +// QueryStorageNodeUsage returns slice of StorageNodeUsage for given period. func (db *StoragenodeAccounting) QueryStorageNodeUsage(ctx context.Context, nodeID storj.NodeID, start time.Time, end time.Time) (_ []accounting.StorageNodeUsage, err error) { defer mon.Task()(&ctx)(&err) @@ -333,7 +333,7 @@ func (db *StoragenodeAccounting) QueryStorageNodeUsage(ctx context.Context, node return nodeStorageUsages, rows.Err() } -// DeleteTalliesBefore deletes all raw tallies prior to some time +// DeleteTalliesBefore deletes all raw tallies prior to some time. func (db *StoragenodeAccounting) DeleteTalliesBefore(ctx context.Context, latestRollup time.Time) (err error) { defer mon.Task()(&ctx)(&err) var deleteRawSQL = `DELETE FROM storagenode_storage_tallies WHERE interval_end_time < ?` diff --git a/satellite/satellitedb/usercredits.go b/satellite/satellitedb/usercredits.go index cf2be1c8d..ea6d45375 100644 --- a/satellite/satellitedb/usercredits.go +++ b/satellite/satellitedb/usercredits.go @@ -26,7 +26,7 @@ type usercredits struct { tx *dbx.Tx } -// GetCreditUsage returns the total amount of referral a user has made based on user id, total available credits, and total used credits based on user id +// GetCreditUsage returns the total amount of referral a user has made based on user id, total available credits, and total used credits based on user id. func (c *usercredits) GetCreditUsage(ctx context.Context, userID uuid.UUID, expirationEndDate time.Time) (*console.UserCreditUsage, error) { usageRows, err := c.db.DB.QueryContext(ctx, c.db.Rebind(`SELECT a.used_credit, b.available_credit, c.referred FROM (SELECT SUM(credits_used_in_cents) AS used_credit FROM user_credits WHERE user_id = ?) AS a, @@ -58,7 +58,7 @@ func (c *usercredits) GetCreditUsage(ctx context.Context, userID uuid.UUID, expi return &usage, usageRows.Err() } -// Create insert a new record of user credit +// Create insert a new record of user credit. func (c *usercredits) Create(ctx context.Context, userCredit console.CreateCredit) (err error) { if userCredit.ExpiresAt.Before(time.Now().UTC()) { return errs.New("user credit is already expired") @@ -131,7 +131,7 @@ func (c *usercredits) Create(ctx context.Context, userCredit console.CreateCredi return nil } -// UpdateEarnedCredits updates user credits after user activated their account +// UpdateEarnedCredits updates user credits after user activated their account. func (c *usercredits) UpdateEarnedCredits(ctx context.Context, userID uuid.UUID) error { statement := ` UPDATE user_credits SET credits_earned_in_cents = offers.invitee_credit_in_cents @@ -155,7 +155,7 @@ func (c *usercredits) UpdateEarnedCredits(ctx context.Context, userID uuid.UUID) return nil } -// UpdateAvailableCredits updates user's available credits based on their spending and the time of their spending +// UpdateAvailableCredits updates user's available credits based on their spending and the time of their spending. func (c *usercredits) UpdateAvailableCredits(ctx context.Context, creditsToCharge int, id uuid.UUID, expirationEndDate time.Time) (remainingCharge int, err error) { err = c.db.WithTx(ctx, func(ctx context.Context, tx *dbx.Tx) (err error) { availableCredits, err := tx.All_UserCredit_By_UserId_And_ExpiresAt_Greater_And_CreditsUsedInCents_Less_CreditsEarnedInCents_OrderBy_Asc_ExpiresAt(ctx, diff --git a/satellite/satellitedb/users.go b/satellite/satellitedb/users.go index c53af9397..d9db302a7 100644 --- a/satellite/satellitedb/users.go +++ b/satellite/satellitedb/users.go @@ -17,12 +17,12 @@ import ( // ensures that users implements console.Users. var _ console.Users = (*users)(nil) -// implementation of Users interface repository using spacemonkeygo/dbx orm +// implementation of Users interface repository using spacemonkeygo/dbx orm. type users struct { db dbx.Methods } -// Get is a method for querying user from the database by id +// Get is a method for querying user from the database by id. func (users *users) Get(ctx context.Context, id uuid.UUID) (_ *console.User, err error) { defer mon.Task()(&ctx)(&err) user, err := users.db.Get_User_By_Id(ctx, dbx.User_Id(id[:])) @@ -45,7 +45,7 @@ func (users *users) GetByEmail(ctx context.Context, email string) (_ *console.Us return userFromDBX(ctx, user) } -// Insert is a method for inserting user into the database +// Insert is a method for inserting user into the database. func (users *users) Insert(ctx context.Context, user *console.User) (_ *console.User, err error) { defer mon.Task()(&ctx)(&err) @@ -87,7 +87,7 @@ func (users *users) Delete(ctx context.Context, id uuid.UUID) (err error) { return err } -// Update is a method for updating user entity +// Update is a method for updating user entity. func (users *users) Update(ctx context.Context, user *console.User) (err error) { defer mon.Task()(&ctx)(&err) @@ -100,7 +100,7 @@ func (users *users) Update(ctx context.Context, user *console.User) (err error) return err } -// GetProjectLimit is a method to get the users project limit +// GetProjectLimit is a method to get the users project limit. func (users *users) GetProjectLimit(ctx context.Context, id uuid.UUID) (limit int, err error) { defer mon.Task()(&ctx)(&err) @@ -111,7 +111,7 @@ func (users *users) GetProjectLimit(ctx context.Context, id uuid.UUID) (limit in return row.ProjectLimit, nil } -// toUpdateUser creates dbx.User_Update_Fields with only non-empty fields as updatable +// toUpdateUser creates dbx.User_Update_Fields with only non-empty fields as updatable. func toUpdateUser(user *console.User) dbx.User_Update_Fields { update := dbx.User_Update_Fields{ FullName: dbx.User_FullName(user.FullName), @@ -130,7 +130,7 @@ func toUpdateUser(user *console.User) dbx.User_Update_Fields { return update } -// userFromDBX is used for creating User entity from autogenerated dbx.User struct +// userFromDBX is used for creating User entity from autogenerated dbx.User struct. func userFromDBX(ctx context.Context, user *dbx.User) (_ *console.User, err error) { defer mon.Task()(&ctx)(&err) if user == nil { diff --git a/scripts/pg-to-crdb.go b/scripts/pg-to-crdb.go index b5afc2131..9f50cdf49 100644 --- a/scripts/pg-to-crdb.go +++ b/scripts/pg-to-crdb.go @@ -15,7 +15,7 @@ import ( // pg-to-crdb converts a Postgres plaintext sql backup generated by pg_dump // to a compatible plaintext sql backup that only has SQL statements compatible with CockroachDB. // Usage: -// cat postgres_backup.sql | go run pg-to-crdb.go > cockroach_backup.sql +// cat postgres_backup.sql | go run pg-to-crdb.go > cockroach_backup.sql func main() { print := false printOnce := false diff --git a/scripts/test-network-stalls.go b/scripts/test-network-stalls.go index 7ffb8ca7b..0349ee0a5 100644 --- a/scripts/test-network-stalls.go +++ b/scripts/test-network-stalls.go @@ -84,7 +84,7 @@ func (ur *uplinkRunner) Run(ctx context.Context, args ...string) ([]byte, error) return cmd.CombinedOutput() } -// skip the first four whitespace-delimited fields and keep the rest +// skip the first four whitespace-delimited fields and keep the rest. var lsOutputRegexp = regexp.MustCompile(`(?m)^\s*(?:\S+\s+){4}(.*)$`) func (ur *uplinkRunner) doesRemoteExist(remotePath string) (bool, error) { diff --git a/storage/blob.go b/storage/blob.go index 111a09aa2..a63c7eeb7 100644 --- a/storage/blob.go +++ b/storage/blob.go @@ -25,7 +25,7 @@ var ErrInvalidBlobRef = errs.Class("invalid blob ref") // the same FormatVersion is returned later when reading that stored blob. type FormatVersion int -// BlobRef is a reference to a blob +// BlobRef is a reference to a blob. type BlobRef struct { Namespace []byte Key []byte diff --git a/storage/boltdb/client.go b/storage/boltdb/client.go index 0f4043533..c2454a25e 100644 --- a/storage/boltdb/client.go +++ b/storage/boltdb/client.go @@ -18,10 +18,10 @@ import ( var mon = monkit.Package() -// Error is the default boltdb errs class +// Error is the default boltdb errs class. var Error = errs.Class("boltdb error") -// Client is the entrypoint into a bolt data store +// Client is the entrypoint into a bolt data store. type Client struct { db *bbolt.DB Path string @@ -37,7 +37,7 @@ const ( defaultTimeout = 1 * time.Second ) -// New instantiates a new BoltDB client given db file path, and a bucket name +// New instantiates a new BoltDB client given db file path, and a bucket name. func New(path, bucket string) (*Client, error) { db, err := bbolt.Open(path, fileMode, &bbolt.Options{Timeout: defaultTimeout}) if err != nil { @@ -141,7 +141,7 @@ func (client *Client) Get(ctx context.Context, key storage.Key) (_ storage.Value return value, err } -// Delete deletes a key/value pair from boltdb, for a given the key +// Delete deletes a key/value pair from boltdb, for a given the key. func (client *Client) Delete(ctx context.Context, key storage.Key) (err error) { defer mon.Task()(&ctx)(&err) if key.IsZero() { @@ -153,7 +153,7 @@ func (client *Client) Delete(ctx context.Context, key storage.Key) (err error) { }) } -// DeleteMultiple deletes keys ignoring missing keys +// DeleteMultiple deletes keys ignoring missing keys. func (client *Client) DeleteMultiple(ctx context.Context, keys []storage.Key) (_ storage.Items, err error) { defer mon.Task()(&ctx, len(keys))(&err) @@ -188,7 +188,7 @@ func (client *Client) List(ctx context.Context, first storage.Key, limit int) (_ return rv, Error.Wrap(err) } -// Close closes a BoltDB client +// Close closes a BoltDB client. func (client *Client) Close() (err error) { if atomic.AddInt32(client.referenceCount, -1) == 0 { return Error.Wrap(client.db.Close()) @@ -311,7 +311,7 @@ func (cursor forward) Advance() (key, value []byte) { return cursor.Next() } -// CompareAndSwap atomically compares and swaps oldValue with newValue +// CompareAndSwap atomically compares and swaps oldValue with newValue. func (client *Client) CompareAndSwap(ctx context.Context, key storage.Key, oldValue, newValue storage.Value) (err error) { defer mon.Task()(&ctx)(&err) if key.IsZero() { diff --git a/storage/cockroachkv/client.go b/storage/cockroachkv/client.go index 1e031c6f4..6bd08d260 100644 --- a/storage/cockroachkv/client.go +++ b/storage/cockroachkv/client.go @@ -26,14 +26,14 @@ var ( mon = monkit.Package() ) -// Client is the entrypoint into a cockroachkv data store +// Client is the entrypoint into a cockroachkv data store. type Client struct { db tagsql.DB dbURL string lookupLimit int } -// New instantiates a new cockroachkv client given db URL +// New instantiates a new cockroachkv client given db URL. func New(dbURL string) (*Client, error) { dbURL = pgutil.CheckApplicationName(dbURL) @@ -63,7 +63,7 @@ func (client *Client) SetLookupLimit(v int) { client.lookupLimit = v } // LookupLimit returns the maximum limit that is allowed. func (client *Client) LookupLimit() int { return client.lookupLimit } -// Close closes the client +// Close closes the client. func (client *Client) Close() error { return client.db.Close() } @@ -185,7 +185,7 @@ func (client *Client) Delete(ctx context.Context, key storage.Key) (err error) { return nil } -// DeleteMultiple deletes keys ignoring missing keys +// DeleteMultiple deletes keys ignoring missing keys. func (client *Client) DeleteMultiple(ctx context.Context, keys []storage.Key) (items storage.Items, err error) { defer mon.Task()(&ctx)(&err) @@ -272,7 +272,7 @@ func (client *Client) IterateWithoutLookupLimit(ctx context.Context, opts storag return fn(ctx, opi) } -// CompareAndSwap atomically compares and swaps oldValue with newValue +// CompareAndSwap atomically compares and swaps oldValue with newValue. func (client *Client) CompareAndSwap(ctx context.Context, key storage.Key, oldValue, newValue storage.Value) (err error) { defer mon.Task()(&ctx)(&err) diff --git a/storage/cockroachkv/common.go b/storage/cockroachkv/common.go index 4776ebf2c..c3053c264 100644 --- a/storage/cockroachkv/common.go +++ b/storage/cockroachkv/common.go @@ -7,5 +7,5 @@ import ( "github.com/zeebo/errs" ) -// Error is the default postgreskv errs class +// Error is the default postgreskv errs class. var Error = errs.Class("cockroachkv error") diff --git a/storage/common.go b/storage/common.go index 2b700ea3b..937a2fe9c 100644 --- a/storage/common.go +++ b/storage/common.go @@ -16,7 +16,7 @@ var mon = monkit.Package() // Delimiter separates nested paths in storage. const Delimiter = '/' -//ErrKeyNotFound used when something doesn't exist +//ErrKeyNotFound used when something doesn't exist. var ErrKeyNotFound = errs.Class("key not found") // ErrEmptyKey is returned when an empty key is used in Put or in CompareAndSwap. diff --git a/storage/filestore/blob.go b/storage/filestore/blob.go index adba6de48..583bedd70 100644 --- a/storage/filestore/blob.go +++ b/storage/filestore/blob.go @@ -39,7 +39,7 @@ const ( MinFormatVersionSupported = FormatV0 ) -// blobReader implements reading blobs +// blobReader implements reading blobs. type blobReader struct { *os.File formatVersion storage.FormatVersion @@ -63,7 +63,7 @@ func (blob *blobReader) StorageFormatVersion() storage.FormatVersion { return blob.formatVersion } -// blobWriter implements writing blobs +// blobWriter implements writing blobs. type blobWriter struct { ref storage.BlobRef store *blobStore diff --git a/storage/filestore/dir.go b/storage/filestore/dir.go index 290a9e006..ecb382359 100644 --- a/storage/filestore/dir.go +++ b/storage/filestore/dir.go @@ -33,7 +33,7 @@ const ( var pathEncoding = base32.NewEncoding("abcdefghijklmnopqrstuvwxyz234567").WithPadding(base32.NoPadding) -// Dir represents single folder for storing blobs +// Dir represents single folder for storing blobs. type Dir struct { log *zap.Logger path string @@ -43,7 +43,7 @@ type Dir struct { trashnow func() time.Time // the function used by trash to determine "now" } -// NewDir returns folder for storing blobs +// NewDir returns folder for storing blobs. func NewDir(log *zap.Logger, path string) (*Dir, error) { dir := &Dir{ log: log, @@ -59,23 +59,23 @@ func NewDir(log *zap.Logger, path string) (*Dir, error) { ) } -// Path returns the directory path +// Path returns the directory path. func (dir *Dir) Path() string { return dir.path } -// blobsdir is the sub-directory containing the blobs +// blobsdir is the sub-directory containing the blobs. func (dir *Dir) blobsdir() string { return filepath.Join(dir.path, "blobs") } -// tempdir is used for temp files prior to being moved into blobsdir +// tempdir is used for temp files prior to being moved into blobsdir. func (dir *Dir) tempdir() string { return filepath.Join(dir.path, "temp") } -// garbagedir contains files that failed to delete but should be deleted +// garbagedir contains files that failed to delete but should be deleted. func (dir *Dir) garbagedir() string { return filepath.Join(dir.path, "garbage") } -// trashdir contains files staged for deletion for a period of time +// trashdir contains files staged for deletion for a period of time. func (dir *Dir) trashdir() string { return filepath.Join(dir.path, "trash") } // CreateTemporaryFile creates a preallocated temporary file in the temp directory -// prealloc preallocates file to make writing faster +// prealloc preallocates file to make writing faster. func (dir *Dir) CreateTemporaryFile(ctx context.Context, prealloc int64) (_ *os.File, err error) { const preallocLimit = 5 << 20 // 5 MB if prealloc > preallocLimit { @@ -95,7 +95,7 @@ func (dir *Dir) CreateTemporaryFile(ctx context.Context, prealloc int64) (_ *os. return file, nil } -// DeleteTemporary deletes a temporary file +// DeleteTemporary deletes a temporary file. func (dir *Dir) DeleteTemporary(ctx context.Context, file *os.File) (err error) { defer mon.Task()(&ctx)(&err) closeErr := file.Close() @@ -293,13 +293,13 @@ func (dir *Dir) StatWithStorageFormat(ctx context.Context, ref storage.BlobRef, return nil, Error.New("unable to stat %q: %v", vPath, err) } -// Trash moves the piece specified by ref to the trashdir for every format version +// Trash moves the piece specified by ref to the trashdir for every format version. func (dir *Dir) Trash(ctx context.Context, ref storage.BlobRef) (err error) { defer mon.Task()(&ctx)(&err) return dir.iterateStorageFormatVersions(ctx, ref, dir.TrashWithStorageFormat) } -// TrashWithStorageFormat moves the piece specified by ref to the trashdir for the specified format version +// TrashWithStorageFormat moves the piece specified by ref to the trashdir for the specified format version. func (dir *Dir) TrashWithStorageFormat(ctx context.Context, ref storage.BlobRef, formatVer storage.FormatVersion) (err error) { // Ensure trashdir exists so that we know any os.IsNotExist errors below // are not from a missing trash dir @@ -357,12 +357,12 @@ func (dir *Dir) TrashWithStorageFormat(ctx context.Context, ref storage.BlobRef, } // ReplaceTrashnow is a helper for tests to replace the trashnow function used -// when moving files to the trash +// when moving files to the trash. func (dir *Dir) ReplaceTrashnow(trashnow func() time.Time) { dir.trashnow = trashnow } -// RestoreTrash moves every piece in the trash folder back into blobsdir +// RestoreTrash moves every piece in the trash folder back into blobsdir. func (dir *Dir) RestoreTrash(ctx context.Context, namespace []byte) (keysRestored [][]byte, err error) { err = dir.walkNamespaceInPath(ctx, namespace, dir.trashdir(), func(info storage.BlobInfo) error { blobsBasePath, err := dir.blobToBasePath(info.BlobRef()) @@ -442,7 +442,7 @@ func (dir *Dir) EmptyTrash(ctx context.Context, namespace []byte, trashedBefore // version. // // f will be executed for every storage formate version regardless of the -// result, and will aggregate errors into a single returned error +// result, and will aggregate errors into a single returned error. func (dir *Dir) iterateStorageFormatVersions(ctx context.Context, ref storage.BlobRef, f func(ctx context.Context, ref storage.BlobRef, i storage.FormatVersion) error) (err error) { defer mon.Task()(&ctx)(&err) var combinedErrors errs.Group @@ -750,7 +750,7 @@ func walkNamespaceWithPrefix(ctx context.Context, log *zap.Logger, namespace []b } } -// removeAllContent deletes everything in the folder +// removeAllContent deletes everything in the folder. func removeAllContent(ctx context.Context, path string) (err error) { defer mon.Task()(&ctx)(&err) dir, err := os.Open(path) @@ -773,13 +773,13 @@ func removeAllContent(ctx context.Context, path string) (err error) { } } -// DiskInfo contains statistics about this dir +// DiskInfo contains statistics about this dir. type DiskInfo struct { ID string AvailableSpace int64 } -// Info returns information about the current state of the dir +// Info returns information about the current state of the dir. func (dir *Dir) Info() (DiskInfo, error) { path, err := filepath.Abs(dir.path) if err != nil { diff --git a/storage/filestore/dir_unix.go b/storage/filestore/dir_unix.go index 6cef177c5..84ebb59f0 100644 --- a/storage/filestore/dir_unix.go +++ b/storage/filestore/dir_unix.go @@ -32,12 +32,12 @@ func diskInfoFromPath(path string) (info DiskInfo, err error) { return DiskInfo{filesystemID, availableSpace}, nil } -// rename renames oldpath to newpath +// rename renames oldpath to newpath. func rename(oldpath, newpath string) error { return os.Rename(oldpath, newpath) } -// openFileReadOnly opens the file with read only +// openFileReadOnly opens the file with read only. func openFileReadOnly(path string, perm os.FileMode) (*os.File, error) { return os.OpenFile(path, os.O_RDONLY, perm) } diff --git a/storage/filestore/dir_windows.go b/storage/filestore/dir_windows.go index 66ea0e6a3..f22fd4247 100644 --- a/storage/filestore/dir_windows.go +++ b/storage/filestore/dir_windows.go @@ -90,7 +90,7 @@ func getVolumeSerialNumber(path string) (string, error) { return fmt.Sprintf("%08x", volumeSerial), nil } -// windows api occasionally returns +// windows api occasionally returns. func ignoreSuccess(err error) error { if errors.Is(err, windows.Errno(0)) { return nil @@ -108,7 +108,7 @@ func tryFixLongPath(path string) string { return `\\?\` + abspath } -// rename implements atomic file rename on windows +// rename implements atomic file rename on windows. func rename(oldpath, newpath string) error { oldpathp, err := windows.UTF16PtrFromString(tryFixLongPath(oldpath)) if err != nil { @@ -128,7 +128,7 @@ func rename(oldpath, newpath string) error { } // openFileReadOnly opens the file with read only -// a custom implementation, because os.Open doesn't support specifying FILE_SHARE_DELETE +// a custom implementation, because os.Open doesn't support specifying FILE_SHARE_DELETE. func openFileReadOnly(path string, perm os.FileMode) (*os.File, error) { pathp, err := windows.UTF16PtrFromString(tryFixLongPath(path)) if err != nil { diff --git a/storage/filestore/store.go b/storage/filestore/store.go index 720190b9f..64b0055d9 100644 --- a/storage/filestore/store.go +++ b/storage/filestore/store.go @@ -39,19 +39,19 @@ var DefaultConfig = Config{ WriteBufferSize: 128 * memory.KiB, } -// blobStore implements a blob store +// blobStore implements a blob store. type blobStore struct { log *zap.Logger dir *Dir config Config } -// New creates a new disk blob store in the specified directory +// New creates a new disk blob store in the specified directory. func New(log *zap.Logger, dir *Dir, config Config) storage.Blobs { return &blobStore{dir: dir, log: log, config: config} } -// NewAt creates a new disk blob store in the specified directory +// NewAt creates a new disk blob store in the specified directory. func NewAt(log *zap.Logger, path string, config Config) (storage.Blobs, error) { dir, err := NewDir(log, path) if err != nil { @@ -63,7 +63,7 @@ func NewAt(log *zap.Logger, path string, config Config) (storage.Blobs, error) { // Close closes the store. func (store *blobStore) Close() error { return nil } -// Open loads blob with the specified hash +// Open loads blob with the specified hash. func (store *blobStore) Open(ctx context.Context, ref storage.BlobRef) (_ storage.BlobReader, err error) { defer mon.Task()(&ctx)(&err) file, formatVer, err := store.dir.Open(ctx, ref) @@ -90,14 +90,14 @@ func (store *blobStore) OpenWithStorageFormat(ctx context.Context, blobRef stora return newBlobReader(file, formatVer), nil } -// Stat looks up disk metadata on the blob file +// Stat looks up disk metadata on the blob file. func (store *blobStore) Stat(ctx context.Context, ref storage.BlobRef) (_ storage.BlobInfo, err error) { defer mon.Task()(&ctx)(&err) info, err := store.dir.Stat(ctx, ref) return info, Error.Wrap(err) } -// StatWithStorageFormat looks up disk metadata on the blob file with the given storage format version +// StatWithStorageFormat looks up disk metadata on the blob file with the given storage format version. func (store *blobStore) StatWithStorageFormat(ctx context.Context, ref storage.BlobRef, formatVer storage.FormatVersion) (_ storage.BlobInfo, err error) { defer mon.Task()(&ctx)(&err) info, err := store.dir.StatWithStorageFormat(ctx, ref, formatVer) @@ -114,7 +114,7 @@ func (store *blobStore) Delete(ctx context.Context, ref storage.BlobRef) (err er return Error.Wrap(err) } -// DeleteWithStorageFormat deletes blobs with the specified ref and storage format version +// DeleteWithStorageFormat deletes blobs with the specified ref and storage format version. func (store *blobStore) DeleteWithStorageFormat(ctx context.Context, ref storage.BlobRef, formatVer storage.FormatVersion) (err error) { defer mon.Task()(&ctx)(&err) err = store.dir.DeleteWithStorageFormat(ctx, ref, formatVer) @@ -128,27 +128,27 @@ func (store *blobStore) DeleteNamespace(ctx context.Context, ref []byte) (err er return Error.Wrap(err) } -// Trash moves the ref to a trash directory +// Trash moves the ref to a trash directory. func (store *blobStore) Trash(ctx context.Context, ref storage.BlobRef) (err error) { defer mon.Task()(&ctx)(&err) return Error.Wrap(store.dir.Trash(ctx, ref)) } -// RestoreTrash moves every piece in the trash back into the regular location +// RestoreTrash moves every piece in the trash back into the regular location. func (store *blobStore) RestoreTrash(ctx context.Context, namespace []byte) (keysRestored [][]byte, err error) { defer mon.Task()(&ctx)(&err) keysRestored, err = store.dir.RestoreTrash(ctx, namespace) return keysRestored, Error.Wrap(err) } -// // EmptyTrash removes all files in trash that have been there longer than trashExpiryDur +// // EmptyTrash removes all files in trash that have been there longer than trashExpiryDur. func (store *blobStore) EmptyTrash(ctx context.Context, namespace []byte, trashedBefore time.Time) (bytesEmptied int64, keys [][]byte, err error) { defer mon.Task()(&ctx)(&err) bytesEmptied, keys, err = store.dir.EmptyTrash(ctx, namespace, trashedBefore) return bytesEmptied, keys, Error.Wrap(err) } -// GarbageCollect tries to delete any files that haven't yet been deleted +// GarbageCollect tries to delete any files that haven't yet been deleted. func (store *blobStore) GarbageCollect(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) err = store.dir.GarbageCollect(ctx) @@ -156,7 +156,7 @@ func (store *blobStore) GarbageCollect(ctx context.Context) (err error) { } // Create creates a new blob that can be written -// optionally takes a size argument for performance improvements, -1 is unknown size +// optionally takes a size argument for performance improvements, -1 is unknown size. func (store *blobStore) Create(ctx context.Context, ref storage.BlobRef, size int64) (_ storage.BlobWriter, err error) { defer mon.Task()(&ctx)(&err) file, err := store.dir.CreateTemporaryFile(ctx, size) @@ -166,7 +166,7 @@ func (store *blobStore) Create(ctx context.Context, ref storage.BlobRef, size in return newBlobWriter(ref, store, MaxFormatVersionSupported, file, store.config.WriteBufferSize.Int()), nil } -// SpaceUsedForBlobs adds up the space used in all namespaces for blob storage +// SpaceUsedForBlobs adds up the space used in all namespaces for blob storage. func (store *blobStore) SpaceUsedForBlobs(ctx context.Context) (space int64, err error) { defer mon.Task()(&ctx)(&err) @@ -185,7 +185,7 @@ func (store *blobStore) SpaceUsedForBlobs(ctx context.Context) (space int64, err return totalSpaceUsed, nil } -// SpaceUsedForBlobsInNamespace adds up how much is used in the given namespace for blob storage +// SpaceUsedForBlobsInNamespace adds up how much is used in the given namespace for blob storage. func (store *blobStore) SpaceUsedForBlobsInNamespace(ctx context.Context, namespace []byte) (int64, error) { var totalUsed int64 err := store.WalkNamespace(ctx, namespace, func(info storage.BlobInfo) error { @@ -221,7 +221,7 @@ func (store *blobStore) TrashIsEmpty() (_ bool, err error) { return false, err } -// SpaceUsedForTrash returns the total space used by the trash +// SpaceUsedForTrash returns the total space used by the trash. func (store *blobStore) SpaceUsedForTrash(ctx context.Context) (total int64, err error) { defer mon.Task()(&ctx)(&err) @@ -244,7 +244,7 @@ func (store *blobStore) SpaceUsedForTrash(ctx context.Context) (total int64, err return total, err } -// FreeSpace returns how much space left in underlying directory +// FreeSpace returns how much space left in underlying directory. func (store *blobStore) FreeSpace() (int64, error) { info, err := store.dir.Info() if err != nil { diff --git a/storage/postgreskv/client.go b/storage/postgreskv/client.go index 0cc74908a..a47071d74 100644 --- a/storage/postgreskv/client.go +++ b/storage/postgreskv/client.go @@ -23,7 +23,7 @@ var ( mon = monkit.Package() ) -// Client is the entrypoint into a postgreskv data store +// Client is the entrypoint into a postgreskv data store. type Client struct { db tagsql.DB dbURL string @@ -59,7 +59,7 @@ func (client *Client) SetLookupLimit(v int) { client.lookupLimit = v } // LookupLimit returns the maximum limit that is allowed. func (client *Client) LookupLimit() int { return client.lookupLimit } -// Close closes the client +// Close closes the client. func (client *Client) Close() error { return client.db.Close() } @@ -161,7 +161,7 @@ func (client *Client) Delete(ctx context.Context, key storage.Key) (err error) { return nil } -// DeleteMultiple deletes keys ignoring missing keys +// DeleteMultiple deletes keys ignoring missing keys. func (client *Client) DeleteMultiple(ctx context.Context, keys []storage.Key) (_ storage.Items, err error) { defer mon.Task()(&ctx, len(keys))(&err) @@ -230,7 +230,7 @@ func (client *Client) IterateWithoutLookupLimit(ctx context.Context, opts storag return fn(ctx, opi) } -// CompareAndSwap atomically compares and swaps oldValue with newValue +// CompareAndSwap atomically compares and swaps oldValue with newValue. func (client *Client) CompareAndSwap(ctx context.Context, key storage.Key, oldValue, newValue storage.Value) (err error) { defer mon.Task()(&ctx)(&err) diff --git a/storage/postgreskv/common.go b/storage/postgreskv/common.go index 932d98235..148e7cf90 100644 --- a/storage/postgreskv/common.go +++ b/storage/postgreskv/common.go @@ -7,5 +7,5 @@ import ( "github.com/zeebo/errs" ) -// Error is the default postgreskv errs class +// Error is the default postgreskv errs class. var Error = errs.Class("postgreskv error") diff --git a/storage/postgreskv/schema/data.go b/storage/postgreskv/schema/data.go index 2b2e841c6..a187c6e3e 100644 --- a/storage/postgreskv/schema/data.go +++ b/storage/postgreskv/schema/data.go @@ -55,32 +55,32 @@ type bindataFileInfo struct { modTime time.Time } -// Name return file name +// Name return file name. func (fi bindataFileInfo) Name() string { return fi.name } -// Size return file size +// Size return file size. func (fi bindataFileInfo) Size() int64 { return fi.size } -// Mode return file mode +// Mode return file mode. func (fi bindataFileInfo) Mode() os.FileMode { return fi.mode } -// Mode return file modify time +// Mode return file modify time. func (fi bindataFileInfo) ModTime() time.Time { return fi.modTime } -// IsDir return file whether a directory +// IsDir return file whether a directory. func (fi bindataFileInfo) IsDir() bool { return fi.mode&os.ModeDir != 0 } -// Sys return file is sys mode +// Sys return file is sys mode. func (fi bindataFileInfo) Sys() interface{} { return nil } @@ -358,7 +358,7 @@ var _bintree = &bintree{nil, map[string]*bintree{ "2020011601_kvimplementation_switchover.up.sql": &bintree{_2020011601_kvimplementation_switchoverUpSql, map[string]*bintree{}}, }} -// RestoreAsset restores an asset under the given directory +// RestoreAsset restores an asset under the given directory. func RestoreAsset(dir, name string) error { data, err := Asset(name) if err != nil { @@ -383,7 +383,7 @@ func RestoreAsset(dir, name string) error { return nil } -// RestoreAssets restores an asset under the given directory recursively +// RestoreAssets restores an asset under the given directory recursively. func RestoreAssets(dir, name string) error { children, err := AssetDir(name) // File diff --git a/storage/redis/client.go b/storage/redis/client.go index a4d1ae500..12218d1be 100644 --- a/storage/redis/client.go +++ b/storage/redis/client.go @@ -27,10 +27,10 @@ var ( ) // TODO(coyle): this should be set to 61 * time.Minute after we implement Ping and Refresh on Overlay. -// This disables the TTL since the Set command only includes a TTL if it is greater than 0 +// This disables the TTL since the Set command only includes a TTL if it is greater than 0. const defaultNodeExpiration = 0 * time.Minute -// Client is the entrypoint into Redis +// Client is the entrypoint into Redis. type Client struct { db *redis.Client TTL time.Duration @@ -38,7 +38,7 @@ type Client struct { lookupLimit int } -// NewClient returns a configured Client instance, verifying a successful connection to redis +// NewClient returns a configured Client instance, verifying a successful connection to redis. func NewClient(address, password string, db int) (*Client, error) { client := &Client{ db: redis.NewClient(&redis.Options{ @@ -58,7 +58,7 @@ func NewClient(address, password string, db int) (*Client, error) { return client, nil } -// NewClientFrom returns a configured Client instance from a redis address, verifying a successful connection to redis +// NewClientFrom returns a configured Client instance from a redis address, verifying a successful connection to redis. func NewClientFrom(address string) (*Client, error) { redisurl, err := url.Parse(address) if err != nil { @@ -126,7 +126,7 @@ func (client *Client) List(ctx context.Context, first storage.Key, limit int) (_ return storage.ListKeys(ctx, client, first, limit) } -// Delete deletes a key/value pair from redis, for a given the key +// Delete deletes a key/value pair from redis, for a given the key. func (client *Client) Delete(ctx context.Context, key storage.Key) (err error) { defer mon.Task()(&ctx)(&err) if key.IsZero() { @@ -135,20 +135,20 @@ func (client *Client) Delete(ctx context.Context, key storage.Key) (err error) { return delete(ctx, client.db, key) } -// DeleteMultiple deletes keys ignoring missing keys +// DeleteMultiple deletes keys ignoring missing keys. func (client *Client) DeleteMultiple(ctx context.Context, keys []storage.Key) (_ storage.Items, err error) { defer mon.Task()(&ctx, len(keys))(&err) return deleteMultiple(ctx, client.db, keys) } -// Close closes a redis client +// Close closes a redis client. func (client *Client) Close() error { return client.db.Close() } // GetAll is the bulk method for gets from the redis data store. // The maximum keys returned will be LookupLimit. If more than that -// is requested, an error will be returned +// is requested, an error will be returned. func (client *Client) GetAll(ctx context.Context, keys storage.Keys) (_ storage.Values, err error) { defer mon.Task()(&ctx)(&err) if len(keys) == 0 { @@ -255,7 +255,7 @@ func (client *Client) allPrefixedItems(prefix, first, last storage.Key, limit in return all, nil } -// CompareAndSwap atomically compares and swaps oldValue with newValue +// CompareAndSwap atomically compares and swaps oldValue with newValue. func (client *Client) CompareAndSwap(ctx context.Context, key storage.Key, oldValue, newValue storage.Value) (err error) { defer mon.Task()(&ctx)(&err) if key.IsZero() { diff --git a/storage/redis/redisserver/server.go b/storage/redis/redisserver/server.go index 8f03409b1..28a07f339 100644 --- a/storage/redis/redisserver/server.go +++ b/storage/redis/redisserver/server.go @@ -50,7 +50,7 @@ func freeport() (addr string, port int) { return addr, port } -// Start starts a redis-server when available, otherwise falls back to miniredis +// Start starts a redis-server when available, otherwise falls back to miniredis. func Start() (Server, error) { server, err := Process() if err != nil { @@ -60,7 +60,7 @@ func Start() (Server, error) { return server, err } -// Process starts a redis-server test process +// Process starts a redis-server test process. func Process() (Server, error) { tmpdir, err := ioutil.TempDir("", "storj-redis") if err != nil { @@ -158,7 +158,7 @@ func pingServer(addr string) error { return client.Ping().Err() } -// Mini starts miniredis server +// Mini starts miniredis server. func Mini() (Server, error) { server, err := miniredis.Run() if err != nil { @@ -172,7 +172,7 @@ type miniserver struct { *miniredis.Miniredis } -// Close closes the underlying miniredis server +// Close closes the underlying miniredis server. func (s *miniserver) Close() error { s.Miniredis.Close() return nil diff --git a/storage/storelogger/logger.go b/storage/storelogger/logger.go index b6b60e37e..b132161d9 100644 --- a/storage/storelogger/logger.go +++ b/storage/storelogger/logger.go @@ -18,13 +18,13 @@ var mon = monkit.Package() var id int64 -// Logger implements a zap.Logger for storage.KeyValueStore +// Logger implements a zap.Logger for storage.KeyValueStore. type Logger struct { log *zap.Logger store storage.KeyValueStore } -// New creates a new Logger with log and store +// New creates a new Logger with log and store. func New(log *zap.Logger, store storage.KeyValueStore) *Logger { loggerid := atomic.AddInt64(&id, 1) name := strconv.Itoa(int(loggerid)) @@ -34,42 +34,42 @@ func New(log *zap.Logger, store storage.KeyValueStore) *Logger { // LookupLimit returns the maximum limit that is allowed. func (store *Logger) LookupLimit() int { return store.store.LookupLimit() } -// Put adds a value to store +// Put adds a value to store. func (store *Logger) Put(ctx context.Context, key storage.Key, value storage.Value) (err error) { defer mon.Task()(&ctx)(&err) store.log.Debug("Put", zap.ByteString("key", key), zap.Int("value length", len(value)), zap.Binary("truncated value", truncate(value))) return store.store.Put(ctx, key, value) } -// Get gets a value to store +// Get gets a value to store. func (store *Logger) Get(ctx context.Context, key storage.Key) (_ storage.Value, err error) { defer mon.Task()(&ctx)(&err) store.log.Debug("Get", zap.ByteString("key", key)) return store.store.Get(ctx, key) } -// GetAll gets all values from the store corresponding to keys +// GetAll gets all values from the store corresponding to keys. func (store *Logger) GetAll(ctx context.Context, keys storage.Keys) (_ storage.Values, err error) { defer mon.Task()(&ctx)(&err) store.log.Debug("GetAll", zap.Any("keys", keys)) return store.store.GetAll(ctx, keys) } -// Delete deletes key and the value +// Delete deletes key and the value. func (store *Logger) Delete(ctx context.Context, key storage.Key) (err error) { defer mon.Task()(&ctx)(&err) store.log.Debug("Delete", zap.ByteString("key", key)) return store.store.Delete(ctx, key) } -// DeleteMultiple deletes keys ignoring missing keys +// DeleteMultiple deletes keys ignoring missing keys. func (store *Logger) DeleteMultiple(ctx context.Context, keys []storage.Key) (_ storage.Items, err error) { defer mon.Task()(&ctx, len(keys))(&err) store.log.Debug("DeleteMultiple", zap.Any("keys", keys)) return store.store.DeleteMultiple(ctx, keys) } -// List lists all keys starting from first and upto limit items +// List lists all keys starting from first and upto limit items. func (store *Logger) List(ctx context.Context, first storage.Key, limit int) (_ storage.Keys, err error) { defer mon.Task()(&ctx)(&err) keys, err := store.store.List(ctx, first, limit) @@ -77,7 +77,7 @@ func (store *Logger) List(ctx context.Context, first storage.Key, limit int) (_ return keys, err } -// Iterate iterates over items based on opts +// Iterate iterates over items based on opts. func (store *Logger) Iterate(ctx context.Context, opts storage.IterateOptions, fn func(context.Context, storage.Iterator) error) (err error) { defer mon.Task()(&ctx)(&err) store.log.Debug("Iterate", @@ -123,13 +123,13 @@ func (store *Logger) IterateWithoutLookupLimit(ctx context.Context, opts storage }) } -// Close closes the store +// Close closes the store. func (store *Logger) Close() error { store.log.Debug("Close") return store.store.Close() } -// CompareAndSwap atomically compares and swaps oldValue with newValue +// CompareAndSwap atomically compares and swaps oldValue with newValue. func (store *Logger) CompareAndSwap(ctx context.Context, key storage.Key, oldValue, newValue storage.Value) (err error) { defer mon.Task()(&ctx)(&err) store.log.Debug("CompareAndSwap", zap.ByteString("key", key), diff --git a/storage/teststore/store.go b/storage/teststore/store.go index d11ba9051..41d77d4a8 100644 --- a/storage/teststore/store.go +++ b/storage/teststore/store.go @@ -18,7 +18,7 @@ import ( var errInternal = errors.New("internal error") var mon = monkit.Package() -// Client implements in-memory key value store +// Client implements in-memory key value store. type Client struct { lookupLimit int @@ -41,7 +41,7 @@ type Client struct { version int } -// New creates a new in-memory key-value store +// New creates a new in-memory key-value store. func New() *Client { return &Client{lookupLimit: storage.DefaultLookupLimit} } // MigrateToLatest pretends to migrate to latest db schema version. @@ -53,7 +53,7 @@ func (store *Client) SetLookupLimit(v int) { store.lookupLimit = v } // LookupLimit returns the maximum limit that is allowed. func (store *Client) LookupLimit() int { return store.lookupLimit } -// indexOf finds index of key or where it could be inserted +// indexOf finds index of key or where it could be inserted. func (store *Client) indexOf(key storage.Key) (int, bool) { i := sort.Search(len(store.Items), func(k int) bool { return !store.Items[k].Key.Less(key) @@ -78,7 +78,7 @@ func (store *Client) forcedError() bool { return false } -// Put adds a value to store +// Put adds a value to store. func (store *Client) Put(ctx context.Context, key storage.Key, value storage.Value) (err error) { defer mon.Task()(&ctx)(&err) defer store.locked()() @@ -104,7 +104,7 @@ func (store *Client) Put(ctx context.Context, key storage.Key, value storage.Val return nil } -// Get gets a value to store +// Get gets a value to store. func (store *Client) Get(ctx context.Context, key storage.Key) (_ storage.Value, err error) { defer mon.Task()(&ctx)(&err) defer store.locked()() @@ -127,7 +127,7 @@ func (store *Client) Get(ctx context.Context, key storage.Key) (_ storage.Value, return storage.CloneValue(store.Items[keyIndex].Value), nil } -// GetAll gets all values from the store +// GetAll gets all values from the store. func (store *Client) GetAll(ctx context.Context, keys storage.Keys) (_ storage.Values, err error) { defer mon.Task()(&ctx)(&err) defer store.locked()() @@ -153,7 +153,7 @@ func (store *Client) GetAll(ctx context.Context, keys storage.Keys) (_ storage.V return values, nil } -// Delete deletes key and the value +// Delete deletes key and the value. func (store *Client) Delete(ctx context.Context, key storage.Key) (err error) { defer mon.Task()(&ctx)(&err) defer store.locked()() @@ -178,7 +178,7 @@ func (store *Client) Delete(ctx context.Context, key storage.Key) (err error) { return nil } -// DeleteMultiple deletes keys ignoring missing keys +// DeleteMultiple deletes keys ignoring missing keys. func (store *Client) DeleteMultiple(ctx context.Context, keys []storage.Key) (_ storage.Items, err error) { defer mon.Task()(&ctx, len(keys))(&err) defer store.locked()() @@ -207,7 +207,7 @@ func (store *Client) DeleteMultiple(ctx context.Context, keys []storage.Key) (_ return items, nil } -// List lists all keys starting from start and upto limit items +// List lists all keys starting from start and upto limit items. func (store *Client) List(ctx context.Context, first storage.Key, limit int) (_ storage.Keys, err error) { defer mon.Task()(&ctx)(&err) store.mu.Lock() @@ -220,7 +220,7 @@ func (store *Client) List(ctx context.Context, first storage.Key, limit int) (_ return storage.ListKeys(ctx, store, first, limit) } -// Close closes the store +// Close closes the store. func (store *Client) Close() error { defer store.locked()() @@ -325,7 +325,7 @@ func (cursor *forward) Advance() (*storage.ListItem, bool) { return cursor.next() } -// cursor implements iterating over items with basic repositioning when the items change +// cursor implements iterating over items with basic repositioning when the items change. type cursor struct { store *Client done bool @@ -341,7 +341,7 @@ func (cursor *cursor) close() { cursor.done = true } -// positionForward positions at key or the next item +// positionForward positions at key or the next item. func (cursor *cursor) positionForward(key storage.Key) { store := cursor.store store.mu.Lock() @@ -378,7 +378,7 @@ func (cursor *cursor) next() (*storage.ListItem, bool) { return item, true } -// CompareAndSwap atomically compares and swaps oldValue with newValue +// CompareAndSwap atomically compares and swaps oldValue with newValue. func (store *Client) CompareAndSwap(ctx context.Context, key storage.Key, oldValue, newValue storage.Value) (err error) { defer mon.Task()(&ctx)(&err) defer store.locked()() diff --git a/storage/testsuite/bench.go b/storage/testsuite/bench.go index 5cacb26a4..5c993835a 100644 --- a/storage/testsuite/bench.go +++ b/storage/testsuite/bench.go @@ -14,7 +14,7 @@ import ( "storj.io/storj/storage" ) -// RunBenchmarks runs common storage.KeyValueStore benchmarks +// RunBenchmarks runs common storage.KeyValueStore benchmarks. func RunBenchmarks(b *testing.B, store storage.KeyValueStore) { var words = []string{ "alpha", "beta", "gamma", "delta", "iota", "kappa", "lambda", "mu", diff --git a/storage/testsuite/test.go b/storage/testsuite/test.go index 58a40d35d..ab475910a 100644 --- a/storage/testsuite/test.go +++ b/storage/testsuite/test.go @@ -18,7 +18,7 @@ import ( "storj.io/storj/storage" ) -// RunTests runs common storage.KeyValueStore tests +// RunTests runs common storage.KeyValueStore tests. func RunTests(t *testing.T, store storage.KeyValueStore) { // store = storelogger.NewTest(t, store) ctx := testcontext.New(t) diff --git a/storagenode/bandwidth/service.go b/storagenode/bandwidth/service.go index e3d8468f5..4ef958df8 100644 --- a/storagenode/bandwidth/service.go +++ b/storagenode/bandwidth/service.go @@ -39,13 +39,13 @@ func NewService(log *zap.Logger, db DB, config Config) *Service { } } -// Run starts the background process for rollups of bandwidth usage +// Run starts the background process for rollups of bandwidth usage. func (service *Service) Run(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) return service.Loop.Run(ctx, service.Rollup) } -// Rollup calls bandwidth DB Rollup method and logs any errors +// Rollup calls bandwidth DB Rollup method and logs any errors. func (service *Service) Rollup(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) @@ -57,7 +57,7 @@ func (service *Service) Rollup(ctx context.Context) (err error) { return nil } -// Close stops the background process for rollups of bandwidth usage +// Close stops the background process for rollups of bandwidth usage. func (service *Service) Close() (err error) { service.Loop.Close() return nil diff --git a/storagenode/bandwidth/service_test.go b/storagenode/bandwidth/service_test.go index 9bf1713ac..8c6582a57 100644 --- a/storagenode/bandwidth/service_test.go +++ b/storagenode/bandwidth/service_test.go @@ -15,7 +15,7 @@ import ( "storj.io/storj/private/teststorj" ) -// Simple test for ensuring the service runs Rollups in the Loop +// Simple test for ensuring the service runs Rollups in the Loop. func TestBandwidthService(t *testing.T) { testplanet.Run(t, testplanet.Config{ SatelliteCount: 1, StorageNodeCount: 3, UplinkCount: 1, diff --git a/storagenode/bandwidth/usage.go b/storagenode/bandwidth/usage.go index f2188a1ce..6e18357c3 100644 --- a/storagenode/bandwidth/usage.go +++ b/storagenode/bandwidth/usage.go @@ -40,7 +40,7 @@ type DB interface { GetDailySatelliteRollups(ctx context.Context, satelliteID storj.NodeID, from, to time.Time) ([]UsageRollup, error) } -// Usage contains bandwidth usage information based on the type +// Usage contains bandwidth usage information based on the type. type Usage struct { Invalid int64 Unknown int64 @@ -108,7 +108,7 @@ func (usage *Usage) Add(b *Usage) { usage.Delete += b.Delete } -// Total sums all type of bandwidths +// Total sums all type of bandwidths. func (usage *Usage) Total() int64 { return usage.Invalid + usage.Unknown + @@ -120,7 +120,7 @@ func (usage *Usage) Total() int64 { usage.Delete } -// TotalMonthlySummary returns total bandwidth usage for current month +// TotalMonthlySummary returns total bandwidth usage for current month. func TotalMonthlySummary(ctx context.Context, db DB) (*Usage, error) { return db.Summary(ctx, getBeginningOfMonth(), time.Now()) } diff --git a/storagenode/console/bandwidth.go b/storagenode/console/bandwidth.go index 6907fd4af..33a3c650c 100644 --- a/storagenode/console/bandwidth.go +++ b/storagenode/console/bandwidth.go @@ -3,7 +3,7 @@ package console -// BandwidthInfo stores all info about storage node bandwidth usage +// BandwidthInfo stores all info about storage node bandwidth usage. type BandwidthInfo struct { Used int64 `json:"used"` Available int64 `json:"available"` diff --git a/storagenode/console/diskspace.go b/storagenode/console/diskspace.go index 577ffc917..f37f32739 100644 --- a/storagenode/console/diskspace.go +++ b/storagenode/console/diskspace.go @@ -3,7 +3,7 @@ package console -// DiskSpaceInfo stores all info about storagenode disk space usage +// DiskSpaceInfo stores all info about storagenode disk space usage. type DiskSpaceInfo struct { Used int64 `json:"used"` Available int64 `json:"available"` diff --git a/storagenode/contact/chore.go b/storagenode/contact/chore.go index b9d722719..e42777572 100644 --- a/storagenode/contact/chore.go +++ b/storagenode/contact/chore.go @@ -28,7 +28,7 @@ type Chore struct { interval time.Duration } -// NewChore creates a new contact chore +// NewChore creates a new contact chore. func NewChore(log *zap.Logger, interval time.Duration, service *Service) *Chore { return &Chore{ log: log, @@ -39,7 +39,7 @@ func NewChore(log *zap.Logger, interval time.Duration, service *Service) *Chore } } -// Run the contact chore on a regular interval with jitter +// Run the contact chore on a regular interval with jitter. func (chore *Chore) Run(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) var group errgroup.Group diff --git a/storagenode/contact/endpoint.go b/storagenode/contact/endpoint.go index ba07cb467..28a5c1e64 100644 --- a/storagenode/contact/endpoint.go +++ b/storagenode/contact/endpoint.go @@ -24,13 +24,13 @@ type Endpoint struct { pingStats *PingStats } -// PingStats contains information regarding when the node was last pinged +// PingStats contains information regarding when the node was last pinged. type PingStats struct { mu sync.Mutex lastPinged time.Time } -// NewEndpoint returns a new contact service endpoint +// NewEndpoint returns a new contact service endpoint. func NewEndpoint(log *zap.Logger, pingStats *PingStats) *Endpoint { return &Endpoint{ log: log, @@ -38,7 +38,7 @@ func NewEndpoint(log *zap.Logger, pingStats *PingStats) *Endpoint { } } -// PingNode provides an easy way to verify a node is online and accepting requests +// PingNode provides an easy way to verify a node is online and accepting requests. func (endpoint *Endpoint) PingNode(ctx context.Context, req *pb.ContactPingRequest) (_ *pb.ContactPingResponse, err error) { defer mon.Task()(&ctx)(&err) peer, err := rpcpeer.FromContext(ctx) diff --git a/storagenode/contact/service.go b/storagenode/contact/service.go index f7cb9e3cf..a7063e679 100644 --- a/storagenode/contact/service.go +++ b/storagenode/contact/service.go @@ -31,7 +31,7 @@ var ( const initialBackOff = time.Second -// Config contains configurable values for contact service +// Config contains configurable values for contact service. type Config struct { ExternalAddress string `user:"true" help:"the public address of the node, useful for nodes behind NAT" default:""` @@ -48,7 +48,7 @@ type NodeInfo struct { Operator pb.NodeOperator } -// Service is the contact service between storage nodes and satellites +// Service is the contact service between storage nodes and satellites. type Service struct { log *zap.Logger dialer rpc.Dialer @@ -61,7 +61,7 @@ type Service struct { initialized sync2.Fence } -// NewService creates a new contact service +// NewService creates a new contact service. func NewService(log *zap.Logger, dialer rpc.Dialer, self NodeInfo, trust *trust.Pool) *Service { return &Service{ log: log, @@ -71,7 +71,7 @@ func NewService(log *zap.Logger, dialer rpc.Dialer, self NodeInfo, trust *trust. } } -// PingSatellites attempts to ping all satellites in trusted list until backoff reaches maxInterval +// PingSatellites attempts to ping all satellites in trusted list until backoff reaches maxInterval. func (service *Service) PingSatellites(ctx context.Context, maxInterval time.Duration) (err error) { defer mon.Task()(&ctx)(&err) satellites := service.trust.GetSatellites(ctx) @@ -147,7 +147,7 @@ func (service *Service) Local() NodeInfo { return service.self } -// UpdateSelf updates the local node with the capacity +// UpdateSelf updates the local node with the capacity. func (service *Service) UpdateSelf(capacity *pb.NodeCapacity) { service.mu.Lock() defer service.mu.Unlock() diff --git a/storagenode/gracefulexit/common.go b/storagenode/gracefulexit/common.go index 5e673ec9e..6374d0253 100644 --- a/storagenode/gracefulexit/common.go +++ b/storagenode/gracefulexit/common.go @@ -19,7 +19,7 @@ var ( mon = monkit.Package() ) -// Config for graceful exit +// Config for graceful exit. type Config struct { ChoreInterval time.Duration `help:"how often to run the chore to check for satellites for the node to exit." releaseDefault:"15m" devDefault:"10s"` NumWorkers int `help:"number of workers to handle satellite exits" default:"4"` diff --git a/storagenode/gracefulexit/db_test.go b/storagenode/gracefulexit/db_test.go index fc3c302f0..495383f89 100644 --- a/storagenode/gracefulexit/db_test.go +++ b/storagenode/gracefulexit/db_test.go @@ -16,7 +16,7 @@ import ( "storj.io/storj/storagenode/storagenodedb/storagenodedbtest" ) -// TestDB tests the graceful exit database calls +// TestDB tests the graceful exit database calls. func TestDB(t *testing.T) { storagenodedbtest.Run(t, func(ctx *testcontext.Context, t *testing.T, db storagenode.DB) { for i := 0; i <= 3; i++ { diff --git a/storagenode/gracefulexit/endpoint.go b/storagenode/gracefulexit/endpoint.go index c880b0398..b27fafd68 100644 --- a/storagenode/gracefulexit/endpoint.go +++ b/storagenode/gracefulexit/endpoint.go @@ -18,7 +18,7 @@ import ( "storj.io/storj/storagenode/trust" ) -// Endpoint is +// Endpoint is. type Endpoint struct { log *zap.Logger usageCache *pieces.BlobsUsageCache diff --git a/storagenode/gracefulexit/worker.go b/storagenode/gracefulexit/worker.go index 5e6c91727..3c295454e 100644 --- a/storagenode/gracefulexit/worker.go +++ b/storagenode/gracefulexit/worker.go @@ -59,7 +59,7 @@ func NewWorker(log *zap.Logger, store *pieces.Store, trust *trust.Pool, satellit } // Run calls the satellite endpoint, transfers pieces, validates, and responds with success or failure. -// It also marks the satellite finished once all the pieces have been transferred +// It also marks the satellite finished once all the pieces have been transferred. func (worker *Worker) Run(ctx context.Context, done func()) (err error) { defer mon.Task()(&ctx)(&err) defer done() @@ -313,7 +313,7 @@ func (worker *Worker) transferPiece(ctx context.Context, transferPiece *pb.Trans return c.Send(success) } -// deleteOnePiece deletes one piece stored for a satellite +// deleteOnePiece deletes one piece stored for a satellite. func (worker *Worker) deleteOnePiece(ctx context.Context, pieceID storj.PieceID) error { piece, err := worker.store.Reader(ctx, worker.satelliteURL.ID, pieceID) if err != nil { @@ -333,7 +333,7 @@ func (worker *Worker) deleteOnePiece(ctx context.Context, pieceID storj.PieceID) return worker.satelliteDB.UpdateGracefulExit(ctx, worker.satelliteURL.ID, size) } -// deletePiece deletes one piece stored for a satellite, without updating satellite Graceful Exit status +// deletePiece deletes one piece stored for a satellite, without updating satellite Graceful Exit status. func (worker *Worker) deletePiece(ctx context.Context, pieceID storj.PieceID) error { err := worker.store.Delete(ctx, worker.satelliteURL.ID, pieceID) if err != nil { @@ -359,7 +359,7 @@ func (worker *Worker) deletePiece(ctx context.Context, pieceID storj.PieceID) er return err } -// deleteAllPieces deletes pieces stored for a satellite +// deleteAllPieces deletes pieces stored for a satellite. func (worker *Worker) deleteAllPieces(ctx context.Context) error { var totalDeleted int64 err := worker.store.WalkSatellitePieces(ctx, worker.satelliteURL.ID, func(piece pieces.StoredPieceAccess) error { diff --git a/storagenode/heldamount/endpoint.go b/storagenode/heldamount/endpoint.go index c7bf121f6..b6b292c31 100644 --- a/storagenode/heldamount/endpoint.go +++ b/storagenode/heldamount/endpoint.go @@ -215,7 +215,7 @@ func (endpoint *Endpoint) GetAllPayments(ctx context.Context, satelliteID storj. return payments, nil } -// dial dials the HeldAmount client for the satellite by id +// dial dials the HeldAmount client for the satellite by id. func (endpoint *Endpoint) dial(ctx context.Context, satelliteID storj.NodeID) (_ *Client, err error) { defer mon.Task()(&ctx)(&err) diff --git a/storagenode/inspector/inspector.go b/storagenode/inspector/inspector.go index 45d25376c..b6902eacc 100644 --- a/storagenode/inspector/inspector.go +++ b/storagenode/inspector/inspector.go @@ -43,7 +43,7 @@ type Endpoint struct { externalAddress string } -// NewEndpoint creates piecestore inspector instance +// NewEndpoint creates piecestore inspector instance. func NewEndpoint( log *zap.Logger, pieceStore *pieces.Store, @@ -67,7 +67,7 @@ func NewEndpoint( } } -// Stats returns current statistics about the storage node +// Stats returns current statistics about the storage node. func (inspector *Endpoint) Stats(ctx context.Context, in *pb.StatsRequest) (out *pb.StatSummaryResponse, err error) { defer mon.Task()(&ctx)(&err) return inspector.retrieveStats(ctx) @@ -99,7 +99,7 @@ func (inspector *Endpoint) retrieveStats(ctx context.Context) (_ *pb.StatSummary }, nil } -// Dashboard returns dashboard information +// Dashboard returns dashboard information. func (inspector *Endpoint) Dashboard(ctx context.Context, in *pb.DashboardRequest) (out *pb.DashboardResponse, err error) { defer mon.Task()(&ctx)(&err) return inspector.getDashboardData(ctx) diff --git a/storagenode/monitor/monitor.go b/storagenode/monitor/monitor.go index 197f6a45e..e219ea814 100644 --- a/storagenode/monitor/monitor.go +++ b/storagenode/monitor/monitor.go @@ -63,7 +63,7 @@ func NewService(log *zap.Logger, store *pieces.Store, contact *contact.Service, } } -// Run runs monitor service +// Run runs monitor service. func (service *Service) Run(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) @@ -133,7 +133,7 @@ func (service *Service) Run(ctx context.Context) (err error) { return group.Wait() } -// NotifyLowDisk reports disk space to satellites if cooldown timer has expired +// NotifyLowDisk reports disk space to satellites if cooldown timer has expired. func (service *Service) NotifyLowDisk() { service.cooldown.Trigger() } @@ -169,7 +169,7 @@ func (service *Service) usedSpace(ctx context.Context) (_ int64, err error) { return usedSpace, nil } -// AvailableSpace returns available disk space for upload +// AvailableSpace returns available disk space for upload. func (service *Service) AvailableSpace(ctx context.Context) (_ int64, err error) { defer mon.Task()(&ctx)(&err) usedSpace, err := service.usedSpace(ctx) diff --git a/storagenode/nodestats/cache.go b/storagenode/nodestats/cache.go index f022d7495..cb6d5fed8 100644 --- a/storagenode/nodestats/cache.go +++ b/storagenode/nodestats/cache.go @@ -23,7 +23,7 @@ import ( "storj.io/storj/storagenode/trust" ) -// Config defines nodestats cache configuration +// Config defines nodestats cache configuration. type Config struct { MaxSleep time.Duration `help:"maximum duration to wait before requesting data" releaseDefault:"300s" devDefault:"1s"` ReputationSync time.Duration `help:"how often to sync reputation" releaseDefault:"4h" devDefault:"1m"` @@ -57,7 +57,7 @@ type Cache struct { Storage *sync2.Cycle } -// NewCache creates new caching service instance +// NewCache creates new caching service instance. func NewCache(log *zap.Logger, config Config, db CacheStorage, service *Service, heldamountEndpoint *heldamount.Endpoint, heldamountService *heldamount.Service, trust *trust.Pool) *Cache { return &Cache{ log: log, @@ -72,7 +72,7 @@ func NewCache(log *zap.Logger, config Config, db CacheStorage, service *Service, } } -// Run runs loop +// Run runs loop. func (cache *Cache) Run(ctx context.Context) error { var group errgroup.Group @@ -145,7 +145,7 @@ func (cache *Cache) Run(ctx context.Context) error { } // CacheReputationStats queries node stats from all the satellites -// known to the storagenode and stores information into db +// known to the storagenode and stores information into db. func (cache *Cache) CacheReputationStats(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) @@ -165,7 +165,7 @@ func (cache *Cache) CacheReputationStats(ctx context.Context) (err error) { } // CacheSpaceUsage queries disk space usage from all the satellites -// known to the storagenode and stores information into db +// known to the storagenode and stores information into db. func (cache *Cache) CacheSpaceUsage(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) @@ -231,7 +231,7 @@ func (cache *Cache) CacheHeldAmount(ctx context.Context) (err error) { } // sleep for random interval in [0;maxSleep) -// returns error if context was cancelled +// returns error if context was cancelled. func (cache *Cache) sleep(ctx context.Context) error { if cache.maxSleep <= 0 { return nil @@ -246,7 +246,7 @@ func (cache *Cache) sleep(ctx context.Context) error { } // satelliteLoop loops over all satellites from trust pool executing provided fn, caching errors if occurred, -// on each step checks if context has been cancelled +// on each step checks if context has been cancelled. func (cache *Cache) satelliteLoop(ctx context.Context, fn func(id storj.NodeID) error) error { var groupErr errs.Group for _, satellite := range cache.trust.GetSatellites(ctx) { @@ -262,7 +262,7 @@ func (cache *Cache) satelliteLoop(ctx context.Context, fn func(id storj.NodeID) return groupErr.Err() } -// Close closes underlying cycles +// Close closes underlying cycles. func (cache *Cache) Close() error { defer mon.Task()(nil)(nil) cache.Reputation.Close() diff --git a/storagenode/nodestats/service.go b/storagenode/nodestats/service.go index 4f34417e4..2024d4410 100644 --- a/storagenode/nodestats/service.go +++ b/storagenode/nodestats/service.go @@ -35,7 +35,7 @@ type Client struct { pb.DRPCNodeStatsClient } -// Close closes underlying client connection +// Close closes underlying client connection. func (c *Client) Close() error { return c.conn.Close() } @@ -50,7 +50,7 @@ type Service struct { trust *trust.Pool } -// NewService creates new instance of service +// NewService creates new instance of service. func NewService(log *zap.Logger, dialer rpc.Dialer, trust *trust.Pool) *Service { return &Service{ log: log, @@ -59,7 +59,7 @@ func NewService(log *zap.Logger, dialer rpc.Dialer, trust *trust.Pool) *Service } } -// GetReputationStats retrieves reputation stats from particular satellite +// GetReputationStats retrieves reputation stats from particular satellite. func (s *Service) GetReputationStats(ctx context.Context, satelliteID storj.NodeID) (_ *reputation.Stats, err error) { defer mon.Task()(&ctx)(&err) @@ -100,7 +100,7 @@ func (s *Service) GetReputationStats(ctx context.Context, satelliteID storj.Node }, nil } -// GetDailyStorageUsage returns daily storage usage over a period of time for a particular satellite +// GetDailyStorageUsage returns daily storage usage over a period of time for a particular satellite. func (s *Service) GetDailyStorageUsage(ctx context.Context, satelliteID storj.NodeID, from, to time.Time) (_ []storageusage.Stamp, err error) { defer mon.Task()(&ctx)(&err) @@ -142,7 +142,7 @@ func (s *Service) GetPricingModel(ctx context.Context, satelliteID storj.NodeID) }, nil } -// dial dials the NodeStats client for the satellite by id +// dial dials the NodeStats client for the satellite by id. func (s *Service) dial(ctx context.Context, satelliteID storj.NodeID) (_ *Client, err error) { defer mon.Task()(&ctx)(&err) @@ -162,7 +162,7 @@ func (s *Service) dial(ctx context.Context, satelliteID storj.NodeID) (_ *Client }, nil } -// fromSpaceUsageResponse get DiskSpaceUsage slice from pb.SpaceUsageResponse +// fromSpaceUsageResponse get DiskSpaceUsage slice from pb.SpaceUsageResponse. func fromSpaceUsageResponse(resp *pb.DailyStorageUsageResponse, satelliteID storj.NodeID) []storageusage.Stamp { var stamps []storageusage.Stamp diff --git a/storagenode/operator.go b/storagenode/operator.go index de3a9bb40..c6d18298b 100644 --- a/storagenode/operator.go +++ b/storagenode/operator.go @@ -10,7 +10,7 @@ import ( "go.uber.org/zap" ) -// OperatorConfig defines properties related to storage node operator metadata +// OperatorConfig defines properties related to storage node operator metadata. type OperatorConfig struct { Email string `user:"true" help:"operator email address" default:""` Wallet string `user:"true" help:"operator wallet address" default:""` diff --git a/storagenode/orders/service.go b/storagenode/orders/service.go index 4e8765ab2..d738ef597 100644 --- a/storagenode/orders/service.go +++ b/storagenode/orders/service.go @@ -363,7 +363,7 @@ func (service *Service) settle(ctx context.Context, log *zap.Logger, satelliteID } // sleep for random interval in [0;maxSleep) -// returns error if context was cancelled +// returns error if context was cancelled. func (service *Service) sleep(ctx context.Context) error { if service.config.MaxSleep <= 0 { return nil diff --git a/storagenode/orders/store.go b/storagenode/orders/store.go index 493d087c6..804047d44 100644 --- a/storagenode/orders/store.go +++ b/storagenode/orders/store.go @@ -172,7 +172,7 @@ func (store *FileStore) ListUnsentBySatellite() (infoMap map[storj.NodeID]Unsent // Archive moves a file from "unsent" to "archive". The filename/path changes from // unsent/unsent-orders-- // to -// archive/archived-orders---- +// archive/archived-orders----. func (store *FileStore) Archive(satelliteID storj.NodeID, createdAtHour, archivedAt time.Time, status pb.SettlementWithWindowResponse_Status) error { store.unsentMu.Lock() defer store.unsentMu.Unlock() @@ -343,7 +343,7 @@ func (store *FileStore) settleBufferPassed(createdHour time.Time) bool { } // getUnsentFileInfo gets the satellite ID and created hour from a filename. -// it expects the file name to be in the format "unsent-orders--" +// it expects the file name to be in the format "unsent-orders--". func getUnsentFileInfo(name string) (satellite storj.NodeID, createdHour time.Time, err error) { if !strings.HasPrefix(name, unsentFilePrefix) { return storj.NodeID{}, time.Time{}, OrderError.New("Not a valid unsent order file name: %s", name) @@ -372,7 +372,7 @@ func getUnsentFileInfo(name string) (satellite storj.NodeID, createdHour time.Ti } // getArchivedFileInfo gets the archived at time from an archive file name. -// it expects the file name to be in the format "archived-orders----" +// it expects the file name to be in the format "archived-orders----". func getArchivedFileInfo(name string) (satelliteID storj.NodeID, createdAtHour, archivedAt time.Time, status string, err error) { if !strings.HasPrefix(name, archiveFilePrefix) { return storj.NodeID{}, time.Time{}, time.Time{}, "", OrderError.New("Not a valid archived order file name: %s", name) diff --git a/storagenode/pieces/cache.go b/storagenode/pieces/cache.go index b558e91b6..ccbd1dc67 100644 --- a/storagenode/pieces/cache.go +++ b/storagenode/pieces/cache.go @@ -32,7 +32,7 @@ type CacheService struct { } // NewService creates a new cache service that updates the space usage cache on startup and syncs the cache values to -// persistent storage on an interval +// persistent storage on an interval. func NewService(log *zap.Logger, usageCache *BlobsUsageCache, pieces *Store, interval time.Duration) *CacheService { return &CacheService{ log: log, @@ -43,7 +43,7 @@ func NewService(log *zap.Logger, usageCache *BlobsUsageCache, pieces *Store, int } // Run recalculates the space used cache once and also runs a loop to sync the space used cache -// to persistent storage on an interval +// to persistent storage on an interval. func (service *CacheService) Run(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) defer service.InitFence.Release() @@ -92,7 +92,7 @@ func (service *CacheService) Run(ctx context.Context) (err error) { // PersistCacheTotals saves the current totals of the space used cache to the database // so that if the storagenode restarts it can retrieve the latest space used -// values without needing to recalculate since that could take a long time +// values without needing to recalculate since that could take a long time. func (service *CacheService) PersistCacheTotals(ctx context.Context) error { cache := service.usageCache cache.mu.Lock() @@ -109,7 +109,7 @@ func (service *CacheService) PersistCacheTotals(ctx context.Context) error { return nil } -// Init initializes the space used cache with the most recent values that were stored persistently +// Init initializes the space used cache with the most recent values that were stored persistently. func (service *CacheService) Init(ctx context.Context) (err error) { piecesTotal, piecesContentSize, err := service.store.spaceUsedDB.GetPieceTotals(ctx) if err != nil { @@ -133,7 +133,7 @@ func (service *CacheService) Init(ctx context.Context) (err error) { return nil } -// Close closes the loop +// Close closes the loop. func (service *CacheService) Close() (err error) { service.Loop.Close() return nil @@ -160,7 +160,7 @@ type BlobsUsageCache struct { spaceUsedBySatellite map[storj.NodeID]SatelliteUsage } -// NewBlobsUsageCache creates a new disk blob store with a space used cache +// NewBlobsUsageCache creates a new disk blob store with a space used cache. func NewBlobsUsageCache(log *zap.Logger, blob storage.Blobs) *BlobsUsageCache { return &BlobsUsageCache{ log: log, @@ -169,7 +169,7 @@ func NewBlobsUsageCache(log *zap.Logger, blob storage.Blobs) *BlobsUsageCache { } } -// NewBlobsUsageCacheTest creates a new disk blob store with a space used cache +// NewBlobsUsageCacheTest creates a new disk blob store with a space used cache. func NewBlobsUsageCacheTest(log *zap.Logger, blob storage.Blobs, piecesTotal, piecesContentSize, trashTotal int64, spaceUsedBySatellite map[storj.NodeID]SatelliteUsage) *BlobsUsageCache { return &BlobsUsageCache{ log: log, @@ -191,7 +191,7 @@ func (blobs *BlobsUsageCache) init(pieceTotal, contentSize, trashTotal int64, to } // SpaceUsedBySatellite returns the current total space used for a specific -// satellite for all pieces +// satellite for all pieces. func (blobs *BlobsUsageCache) SpaceUsedBySatellite(ctx context.Context, satelliteID storj.NodeID) (piecesTotal int64, piecesContentSize int64, err error) { blobs.mu.Lock() defer blobs.mu.Unlock() @@ -200,14 +200,14 @@ func (blobs *BlobsUsageCache) SpaceUsedBySatellite(ctx context.Context, satellit } // SpaceUsedForPieces returns the current total used space for -//// all pieces +//// all pieces. func (blobs *BlobsUsageCache) SpaceUsedForPieces(ctx context.Context) (int64, int64, error) { blobs.mu.Lock() defer blobs.mu.Unlock() return blobs.piecesTotal, blobs.piecesContentSize, nil } -// SpaceUsedForTrash returns the current total used space for the trash dir +// SpaceUsedForTrash returns the current total used space for the trash dir. func (blobs *BlobsUsageCache) SpaceUsedForTrash(ctx context.Context) (int64, error) { blobs.mu.Lock() defer blobs.mu.Unlock() @@ -215,7 +215,7 @@ func (blobs *BlobsUsageCache) SpaceUsedForTrash(ctx context.Context) (int64, err } // Delete gets the size of the piece that is going to be deleted then deletes it and -// updates the space used cache accordingly +// updates the space used cache accordingly. func (blobs *BlobsUsageCache) Delete(ctx context.Context, blobRef storage.BlobRef) error { pieceTotal, pieceContentSize, err := blobs.pieceSizes(ctx, blobRef) if err != nil { @@ -246,7 +246,7 @@ func (blobs *BlobsUsageCache) pieceSizes(ctx context.Context, blobRef storage.Bl return pieceAccess.Size(ctx) } -// Update updates the cache totals +// Update updates the cache totals. func (blobs *BlobsUsageCache) Update(ctx context.Context, satelliteID storj.NodeID, piecesTotalDelta, piecesContentSizeDelta, trashDelta int64) { blobs.mu.Lock() defer blobs.mu.Unlock() @@ -278,7 +278,7 @@ func (blobs *BlobsUsageCache) ensurePositiveCacheValue(value *int64, name string *value = 0 } -// Trash moves the ref to the trash and updates the cache +// Trash moves the ref to the trash and updates the cache. func (blobs *BlobsUsageCache) Trash(ctx context.Context, blobRef storage.BlobRef) error { pieceTotal, pieceContentSize, err := blobs.pieceSizes(ctx, blobRef) if err != nil { @@ -299,7 +299,7 @@ func (blobs *BlobsUsageCache) Trash(ctx context.Context, blobRef storage.BlobRef return nil } -// EmptyTrash empties the trash and updates the cache +// EmptyTrash empties the trash and updates the cache. func (blobs *BlobsUsageCache) EmptyTrash(ctx context.Context, namespace []byte, trashedBefore time.Time) (int64, [][]byte, error) { satelliteID, err := storj.NodeIDFromBytes(namespace) if err != nil { @@ -316,7 +316,7 @@ func (blobs *BlobsUsageCache) EmptyTrash(ctx context.Context, namespace []byte, return bytesEmptied, keys, nil } -// RestoreTrash restores the trash for the namespace and updates the cache +// RestoreTrash restores the trash for the namespace and updates the cache. func (blobs *BlobsUsageCache) RestoreTrash(ctx context.Context, namespace []byte) ([][]byte, error) { satelliteID, err := storj.NodeIDFromBytes(namespace) if err != nil { @@ -479,7 +479,7 @@ func getMissed(endTotals, newTotals map[storj.NodeID]SatelliteUsage) map[storj.N return missed } -// Close satisfies the pieces interface +// Close satisfies the pieces interface. func (blobs *BlobsUsageCache) Close() error { return nil } diff --git a/storagenode/pieces/readwrite.go b/storagenode/pieces/readwrite.go index 44d43a96e..637222036 100644 --- a/storagenode/pieces/readwrite.go +++ b/storagenode/pieces/readwrite.go @@ -57,7 +57,7 @@ const ( v1PieceHeaderFramingSize = 2 ) -// BadFormatVersion is returned when a storage format cannot support the request function +// BadFormatVersion is returned when a storage format cannot support the request function. var BadFormatVersion = errs.Class("Incompatible storage format version") // Writer implements a piece writer that writes content to blob store and calculates a hash. @@ -246,7 +246,7 @@ func (r *Reader) StorageFormatVersion() storage.FormatVersion { // GetPieceHeader reads, unmarshals, and returns the piece header. It may only be called once, // before any Read() calls. (Retrieving the header at any time could be supported, but for the sake -// of performance we need to understand why and how often that would happen.) +// of performance we need to understand why and how often that would happen.). func (r *Reader) GetPieceHeader() (*pb.PieceHeader, error) { if r.formatVersion < filestore.FormatV1 { return nil, BadFormatVersion.New("Can't get piece header from storage format V0 reader") diff --git a/storagenode/pieces/store.go b/storagenode/pieces/store.go index fdea8c634..7aa362254 100644 --- a/storagenode/pieces/store.go +++ b/storagenode/pieces/store.go @@ -40,7 +40,7 @@ type Info struct { UplinkPieceHash *pb.PieceHash } -// ExpiredInfo is a fully namespaced piece id +// ExpiredInfo is a fully namespaced piece id. type ExpiredInfo struct { SatelliteID storj.NodeID PieceID storj.PieceID @@ -146,7 +146,7 @@ type StoredPieceAccess interface { ModTime(ctx context.Context) (time.Time, error) } -// SatelliteUsage contains information of how much space is used by a satellite +// SatelliteUsage contains information of how much space is used by a satellite. type SatelliteUsage struct { Total int64 // the total space used (including headers) ContentSize int64 // only content size used (excluding things like headers) @@ -176,12 +176,12 @@ type Store struct { } // StoreForTest is a wrapper around Store to be used only in test scenarios. It enables writing -// pieces with older storage formats +// pieces with older storage formats. type StoreForTest struct { *Store } -// NewStore creates a new piece store +// NewStore creates a new piece store. func NewStore(log *zap.Logger, blobs storage.Blobs, v0PieceInfo V0PieceInfoDB, expirationInfo PieceExpirationDB, pieceSpaceUsedDB PieceSpaceUsedDB, config Config) *Store { return &Store{ log: log, @@ -339,7 +339,7 @@ func (store *Store) Trash(ctx context.Context, satellite storj.NodeID, pieceID s return Error.Wrap(err) } -// EmptyTrash deletes pieces in the trash that have been in there longer than trashExpiryInterval +// EmptyTrash deletes pieces in the trash that have been in there longer than trashExpiryInterval. func (store *Store) EmptyTrash(ctx context.Context, satelliteID storj.NodeID, trashedBefore time.Time) (err error) { defer mon.Task()(&ctx)(&err) @@ -359,7 +359,7 @@ func (store *Store) EmptyTrash(ctx context.Context, satelliteID storj.NodeID, tr return Error.Wrap(err) } -// RestoreTrash restores all pieces in the trash +// RestoreTrash restores all pieces in the trash. func (store *Store) RestoreTrash(ctx context.Context, satelliteID storj.NodeID) (err error) { defer mon.Task()(&ctx)(&err) @@ -493,7 +493,7 @@ func (store *Store) WalkSatellitePieces(ctx context.Context, satellite storj.Nod return err } -// GetExpired gets piece IDs that are expired and were created before the given time +// GetExpired gets piece IDs that are expired and were created before the given time. func (store *Store) GetExpired(ctx context.Context, expiredAt time.Time, limit int64) (_ []ExpiredInfo, err error) { defer mon.Task()(&ctx)(&err) @@ -511,7 +511,7 @@ func (store *Store) GetExpired(ctx context.Context, expiredAt time.Time, limit i return expired, nil } -// SetExpiration records an expiration time for the specified piece ID owned by the specified satellite +// SetExpiration records an expiration time for the specified piece ID owned by the specified satellite. func (store *Store) SetExpiration(ctx context.Context, satellite storj.NodeID, pieceID storj.PieceID, expiresAt time.Time) (err error) { return store.expirationInfo.SetExpiration(ctx, satellite, pieceID, expiresAt) } @@ -563,7 +563,7 @@ func (store *Store) SpaceUsedForTrash(ctx context.Context) (int64, error) { } // SpaceUsedForPiecesAndTrash returns the total space used by both active -// pieces and the trash directory +// pieces and the trash directory. func (store *Store) SpaceUsedForPiecesAndTrash(ctx context.Context) (int64, error) { piecesTotal, _, err := store.SpaceUsedForPieces(ctx) if err != nil { @@ -622,7 +622,7 @@ func (store *Store) SpaceUsedBySatellite(ctx context.Context, satelliteID storj. return piecesTotal, piecesContentSize, nil } -// SpaceUsedTotalAndBySatellite adds up the space used by and for all satellites for blob storage +// SpaceUsedTotalAndBySatellite adds up the space used by and for all satellites for blob storage. func (store *Store) SpaceUsedTotalAndBySatellite(ctx context.Context) (piecesTotal, piecesContentSize int64, totalBySatellite map[storj.NodeID]SatelliteUsage, err error) { defer mon.Task()(&ctx)(&err) @@ -704,17 +704,17 @@ func newStoredPieceAccess(store *Store, blobInfo storage.BlobInfo) (storedPieceA }, nil } -// PieceID returns the piece ID of the piece +// PieceID returns the piece ID of the piece. func (access storedPieceAccess) PieceID() storj.PieceID { return access.pieceID } -// Satellite returns the satellite ID that owns the piece +// Satellite returns the satellite ID that owns the piece. func (access storedPieceAccess) Satellite() (storj.NodeID, error) { return storj.NodeIDFromBytes(access.BlobRef().Namespace) } -// Size gives the size of the piece on disk, and the size of the content (not including the piece header, if applicable) +// Size gives the size of the piece on disk, and the size of the content (not including the piece header, if applicable). func (access storedPieceAccess) Size(ctx context.Context) (size, contentSize int64, err error) { defer mon.Task()(&ctx)(&err) stat, err := access.Stat(ctx) diff --git a/storagenode/pieces/trashchore.go b/storagenode/pieces/trashchore.go index 841c941d7..544be1568 100644 --- a/storagenode/pieces/trashchore.go +++ b/storagenode/pieces/trashchore.go @@ -14,7 +14,7 @@ import ( "storj.io/storj/storagenode/trust" ) -// TrashChore is the chore that periodically empties the trash +// TrashChore is the chore that periodically empties the trash. type TrashChore struct { log *zap.Logger interval time.Duration @@ -27,7 +27,7 @@ type TrashChore struct { // NewTrashChore instantiates a new TrashChore. choreInterval is how often this // chore runs, and trashExpiryInterval is passed into the EmptyTrash method to -// determine which trashed pieces should be deleted +// determine which trashed pieces should be deleted. func NewTrashChore(log *zap.Logger, choreInterval, trashExpiryInterval time.Duration, trust *trust.Pool, store *Store) *TrashChore { return &TrashChore{ log: log, @@ -38,7 +38,7 @@ func NewTrashChore(log *zap.Logger, choreInterval, trashExpiryInterval time.Dura } } -// Run starts the cycle +// Run starts the cycle. func (chore *TrashChore) Run(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) @@ -68,7 +68,7 @@ func (chore *TrashChore) TriggerWait(ctx context.Context) { chore.cycle.TriggerWait() } -// Close the chore +// Close the chore. func (chore *TrashChore) Close() error { if chore.cycle != nil { chore.cycle.Close() diff --git a/storagenode/piecestore/endpoint.go b/storagenode/piecestore/endpoint.go index 61ff84e52..843ef112a 100644 --- a/storagenode/piecestore/endpoint.go +++ b/storagenode/piecestore/endpoint.go @@ -40,7 +40,7 @@ var ( mon = monkit.Package() ) -// OldConfig contains everything necessary for a server +// OldConfig contains everything necessary for a server. type OldConfig struct { Path string `help:"path to store data in" default:"$CONFDIR/storage"` WhitelistedSatellites storj.NodeURLs `help:"a comma-separated list of approved satellite node urls (unused)" devDefault:"" releaseDefault:""` @@ -681,7 +681,7 @@ func (endpoint *Endpoint) saveOrder(ctx context.Context, limit *pb.OrderLimit, o } } -// RestoreTrash restores all trashed items for the satellite issuing the call +// RestoreTrash restores all trashed items for the satellite issuing the call. func (endpoint *Endpoint) RestoreTrash(ctx context.Context, restoreTrashReq *pb.RestoreTrashRequest) (res *pb.RestoreTrashResponse, err error) { defer mon.Task()(&ctx)(&err) @@ -703,7 +703,7 @@ func (endpoint *Endpoint) RestoreTrash(ctx context.Context, restoreTrashReq *pb. return &pb.RestoreTrashResponse{}, nil } -// Retain keeps only piece ids specified in the request +// Retain keeps only piece ids specified in the request. func (endpoint *Endpoint) Retain(ctx context.Context, retainReq *pb.RetainRequest) (res *pb.RetainResponse, err error) { defer mon.Task()(&ctx)(&err) @@ -745,7 +745,7 @@ func (endpoint *Endpoint) TestLiveRequestCount() int32 { return atomic.LoadInt32(&endpoint.liveRequests) } -// min finds the min of two values +// min finds the min of two values. func min(a, b int64) int64 { if a < b { return a diff --git a/storagenode/piecestore/usedserials/table.go b/storagenode/piecestore/usedserials/table.go index f9263ee74..d1a3a8187 100644 --- a/storagenode/piecestore/usedserials/table.go +++ b/storagenode/piecestore/usedserials/table.go @@ -51,7 +51,7 @@ func (a Full) Less(b Full) bool { // serialsList is a structure that contains a list of partial serials and a list of full serials // if the satellite puts the expiration time as the first 8 bytes, the partial serials list will be used -// otherwise, the full serials list will be used +// otherwise, the full serials list will be used. type serialsList struct { partialSerials []Partial fullSerials []storj.SerialNumber diff --git a/storagenode/preflight/common.go b/storagenode/preflight/common.go index 697781134..9944c3f16 100644 --- a/storagenode/preflight/common.go +++ b/storagenode/preflight/common.go @@ -9,7 +9,7 @@ import ( var mon = monkit.Package() -// Config for preflight checks +// Config for preflight checks. type Config struct { LocalTimeCheck bool `help:"whether or not preflight check for local system clock is enabled on the satellite side. When disabling this feature, your storagenode may not setup correctly." default:"true"` DatabaseCheck bool `help:"whether or not preflight check for database is enabled." default:"true"` diff --git a/storagenode/preflight/localtime.go b/storagenode/preflight/localtime.go index e26b1be24..7afac667d 100644 --- a/storagenode/preflight/localtime.go +++ b/storagenode/preflight/localtime.go @@ -18,10 +18,10 @@ import ( "storj.io/storj/storagenode/trust" ) -// ErrClockOutOfSyncMinor is the error class for system clock is off by more than 10m +// ErrClockOutOfSyncMinor is the error class for system clock is off by more than 10m. var ErrClockOutOfSyncMinor = errs.Class("system clock is off") -// ErrClockOutOfSyncMajor is the error class for system clock is out of sync by more than 30m +// ErrClockOutOfSyncMajor is the error class for system clock is out of sync by more than 30m. var ErrClockOutOfSyncMajor = errs.Class("system clock is out of sync") // LocalTime checks local system clock against all trusted satellites. diff --git a/storagenode/reputation/reputation.go b/storagenode/reputation/reputation.go index 8a4db4c50..39341dd73 100644 --- a/storagenode/reputation/reputation.go +++ b/storagenode/reputation/reputation.go @@ -22,7 +22,7 @@ type DB interface { All(ctx context.Context) ([]Stats, error) } -// Stats consist of reputation metrics +// Stats consist of reputation metrics. type Stats struct { SatelliteID storj.NodeID @@ -36,7 +36,7 @@ type Stats struct { JoinedAt time.Time } -// Metric encapsulates storagenode reputation metrics +// Metric encapsulates storagenode reputation metrics. type Metric struct { TotalCount int64 `json:"totalCount"` SuccessCount int64 `json:"successCount"` diff --git a/storagenode/reputation/reputation_test.go b/storagenode/reputation/reputation_test.go index 14f0a19a3..fbfd18817 100644 --- a/storagenode/reputation/reputation_test.go +++ b/storagenode/reputation/reputation_test.go @@ -129,7 +129,7 @@ func TestReputationDBGetAll(t *testing.T) { }) } -// compareReputationMetric compares two reputation metrics and asserts that they are equal +// compareReputationMetric compares two reputation metrics and asserts that they are equal. func compareReputationMetric(t *testing.T, a, b *reputation.Metric) { assert.Equal(t, a.SuccessCount, b.SuccessCount) assert.Equal(t, a.TotalCount, b.TotalCount) diff --git a/storagenode/retain/retain.go b/storagenode/retain/retain.go index cc83a4efa..5e632578d 100644 --- a/storagenode/retain/retain.go +++ b/storagenode/retain/retain.go @@ -120,7 +120,7 @@ func NewService(log *zap.Logger, store *pieces.Store, config Config) *Service { // Queue adds a retain request to the queue. // It discards a request for a satellite that already has a queued request. -// true is returned if the request is queued and false is returned if it is discarded +// true is returned if the request is queued and false is returned if it is discarded. func (s *Service) Queue(req Request) bool { s.cond.L.Lock() defer s.cond.L.Unlock() @@ -245,7 +245,7 @@ func (s *Service) Run(ctx context.Context) error { return err } -// next returns next item from queue, requires mutex to be held +// next returns next item from queue, requires mutex to be held. func (s *Service) next() (Request, bool) { for id, request := range s.queued { // Check whether a worker is retaining this satellite, @@ -261,7 +261,7 @@ func (s *Service) next() (Request, bool) { return Request{}, false } -// finish marks the request as finished, requires mutex to be held +// finish marks the request as finished, requires mutex to be held. func (s *Service) finish(request Request) { delete(s.working, request.SatelliteID) } diff --git a/storagenode/retain/retain_test.go b/storagenode/retain/retain_test.go index 472033405..29b75a7fb 100644 --- a/storagenode/retain/retain_test.go +++ b/storagenode/retain/retain_test.go @@ -202,7 +202,7 @@ func getAllPieceIDs(ctx context.Context, store *pieces.Store, satellite storj.No return pieceIDs, err } -// generateTestIDs generates n piece ids +// generateTestIDs generates n piece ids. func generateTestIDs(n int) []storj.PieceID { ids := make([]storj.PieceID, n) for i := range ids { diff --git a/storagenode/satellites/satellites.go b/storagenode/satellites/satellites.go index cea1db2a9..c674da96c 100644 --- a/storagenode/satellites/satellites.go +++ b/storagenode/satellites/satellites.go @@ -10,7 +10,7 @@ import ( "storj.io/common/storj" ) -// Status refers to the state of the relationship with a satellites +// Status refers to the state of the relationship with a satellites. type Status = int const ( @@ -26,7 +26,7 @@ const ( ExitFailed = 4 ) -// ExitProgress contains the status of a graceful exit +// ExitProgress contains the status of a graceful exit. type ExitProgress struct { SatelliteID storj.NodeID InitiatedAt *time.Time @@ -37,7 +37,7 @@ type ExitProgress struct { Status int32 } -// Satellite contains the satellite and status +// Satellite contains the satellite and status. type Satellite struct { SatelliteID storj.NodeID AddedAt time.Time diff --git a/storagenode/storagenodedb/bandwidthdb.go b/storagenode/storagenodedb/bandwidthdb.go index c4ee49dba..a4c72c2cb 100644 --- a/storagenode/storagenodedb/bandwidthdb.go +++ b/storagenode/storagenodedb/bandwidthdb.go @@ -34,7 +34,7 @@ type bandwidthDB struct { dbContainerImpl } -// Add adds bandwidth usage to the table +// Add adds bandwidth usage to the table. func (db *bandwidthDB) Add(ctx context.Context, satelliteID storj.NodeID, action pb.PieceAction, amount int64, created time.Time) (err error) { defer mon.Task()(&ctx)(&err) _, err = db.ExecContext(ctx, ` @@ -60,7 +60,7 @@ func (db *bandwidthDB) Add(ctx context.Context, satelliteID storj.NodeID, action return ErrBandwidth.Wrap(err) } -// MonthSummary returns summary of the current months bandwidth usages +// MonthSummary returns summary of the current months bandwidth usages. func (db *bandwidthDB) MonthSummary(ctx context.Context, now time.Time) (_ int64, err error) { defer mon.Task()(&ctx)(&err) diff --git a/storagenode/storagenodedb/database.go b/storagenode/storagenodedb/database.go index eb9d6f8a0..dea10ecfa 100644 --- a/storagenode/storagenodedb/database.go +++ b/storagenode/storagenodedb/database.go @@ -36,7 +36,7 @@ import ( "storj.io/storj/storagenode/storageusage" ) -// VersionTable is the table that stores the version info in each db +// VersionTable is the table that stores the version info in each db. const VersionTable = "versions" var ( @@ -50,13 +50,13 @@ var ( ErrPreflight = errs.Class("storage node preflight database error") ) -// DBContainer defines an interface to allow accessing and setting a SQLDB +// DBContainer defines an interface to allow accessing and setting a SQLDB. type DBContainer interface { Configure(sqlDB tagsql.DB) GetDB() tagsql.DB } -// withTx is a helper method which executes callback in transaction scope +// withTx is a helper method which executes callback in transaction scope. func withTx(ctx context.Context, db tagsql.DB, cb func(tx tagsql.Tx) error) error { tx, err := db.BeginTx(ctx, nil) if err != nil { @@ -73,7 +73,7 @@ func withTx(ctx context.Context, db tagsql.DB, cb func(tx tagsql.Tx) error) erro return cb(tx) } -// Config configures storage node database +// Config configures storage node database. type Config struct { // TODO: figure out better names Storage string @@ -84,7 +84,7 @@ type Config struct { Filestore filestore.Config } -// DB contains access to different database tables +// DB contains access to different database tables. type DB struct { log *zap.Logger config Config @@ -110,7 +110,7 @@ type DB struct { SQLDBs map[string]DBContainer } -// New creates a new master database for storage node +// New creates a new master database for storage node. func New(log *zap.Logger, config Config) (*DB, error) { piecesDir, err := filestore.NewDir(log, config.Pieces) if err != nil { @@ -439,7 +439,7 @@ func (db *DB) Orders() orders.DB { return db.ordersDB } -// Pieces returns blob storage for pieces +// Pieces returns blob storage for pieces. func (db *DB) Pieces() storage.Blobs { return db.pieces } @@ -484,7 +484,7 @@ func (db *DB) Pricing() pricing.DB { return db.pricingDB } -// RawDatabases are required for testing purposes +// RawDatabases are required for testing purposes. func (db *DB) RawDatabases() map[string]DBContainer { return db.SQLDBs } diff --git a/storagenode/storagenodedb/heldamount.go b/storagenode/storagenodedb/heldamount.go index ae928f18d..55006ec83 100644 --- a/storagenode/storagenodedb/heldamount.go +++ b/storagenode/storagenodedb/heldamount.go @@ -22,7 +22,7 @@ var ErrHeldAmount = errs.Class("heldamount error") // HeldAmountDBName represents the database name. const HeldAmountDBName = "heldamount" -// heldamountDB works with node heldamount DB +// heldamountDB works with node heldamount DB. type heldamountDB struct { dbContainerImpl } diff --git a/storagenode/storagenodedb/migrations_test.go b/storagenode/storagenodedb/migrations_test.go index 551a6dc97..8eb9c352e 100644 --- a/storagenode/storagenodedb/migrations_test.go +++ b/storagenode/storagenodedb/migrations_test.go @@ -43,7 +43,7 @@ func insertNewData(ctx context.Context, mdbs *testdata.MultiDBState, rawDBs map[ } // getSchemas queries the schema of each rawDB and returns a map of each rawDB's -// schema keyed by dbName +// schema keyed by dbName. func getSchemas(ctx context.Context, rawDBs map[string]storagenodedb.DBContainer) (map[string]*dbschema.Schema, error) { schemas := make(map[string]*dbschema.Schema) for dbName, rawDB := range rawDBs { @@ -61,7 +61,7 @@ func getSchemas(ctx context.Context, rawDBs map[string]storagenodedb.DBContainer } // getSchemas queries the data of each rawDB and returns a map of each rawDB's -// data keyed by dbName +// data keyed by dbName. func getData(ctx context.Context, rawDBs map[string]storagenodedb.DBContainer, schemas map[string]*dbschema.Schema) (map[string]*dbschema.Data, error) { data := make(map[string]*dbschema.Data) for dbName, rawDB := range rawDBs { diff --git a/storagenode/storagenodedb/orders.go b/storagenode/storagenodedb/orders.go index 417ffb456..3d9cce64e 100644 --- a/storagenode/storagenodedb/orders.go +++ b/storagenode/storagenodedb/orders.go @@ -27,7 +27,7 @@ type ordersDB struct { dbContainerImpl } -// Enqueue inserts order to the unsent list +// Enqueue inserts order to the unsent list. func (db *ordersDB) Enqueue(ctx context.Context, info *orders.Info) (err error) { defer mon.Task()(&ctx)(&err) @@ -305,7 +305,7 @@ func (db *ordersDB) ListArchived(ctx context.Context, limit int) (_ []*orders.Ar return infos, ErrOrders.Wrap(rows.Err()) } -// CleanArchive deletes all entries older than ttl +// CleanArchive deletes all entries older than ttl. func (db *ordersDB) CleanArchive(ctx context.Context, ttl time.Duration) (_ int, err error) { defer mon.Task()(&ctx)(&err) diff --git a/storagenode/storagenodedb/pieceexpiration.go b/storagenode/storagenodedb/pieceexpiration.go index 1b68478db..8dd022e8c 100644 --- a/storagenode/storagenodedb/pieceexpiration.go +++ b/storagenode/storagenodedb/pieceexpiration.go @@ -23,7 +23,7 @@ type pieceExpirationDB struct { dbContainerImpl } -// GetExpired gets piece IDs that expire or have expired before the given time +// GetExpired gets piece IDs that expire or have expired before the given time. func (db *pieceExpirationDB) GetExpired(ctx context.Context, expiresBefore time.Time, limit int64) (expiredPieceIDs []pieces.ExpiredInfo, err error) { defer mon.Task()(&ctx)(&err) @@ -56,7 +56,7 @@ func (db *pieceExpirationDB) GetExpired(ctx context.Context, expiresBefore time. return expiredPieceIDs, rows.Err() } -// SetExpiration sets an expiration time for the given piece ID on the given satellite +// SetExpiration sets an expiration time for the given piece ID on the given satellite. func (db *pieceExpirationDB) SetExpiration(ctx context.Context, satellite storj.NodeID, pieceID storj.PieceID, expiresAt time.Time) (err error) { defer mon.Task()(&ctx)(&err) @@ -67,7 +67,7 @@ func (db *pieceExpirationDB) SetExpiration(ctx context.Context, satellite storj. return ErrPieceExpiration.Wrap(err) } -// DeleteExpiration removes an expiration record for the given piece ID on the given satellite +// DeleteExpiration removes an expiration record for the given piece ID on the given satellite. func (db *pieceExpirationDB) DeleteExpiration(ctx context.Context, satelliteID storj.NodeID, pieceID storj.PieceID) (found bool, err error) { defer mon.Task()(&ctx)(&err) @@ -86,7 +86,7 @@ func (db *pieceExpirationDB) DeleteExpiration(ctx context.Context, satelliteID s } // DeleteFailed marks an expiration record as having experienced a failure in deleting the piece -// from the disk +// from the disk. func (db *pieceExpirationDB) DeleteFailed(ctx context.Context, satelliteID storj.NodeID, pieceID storj.PieceID, when time.Time) (err error) { defer mon.Task()(&ctx)(&err) @@ -99,7 +99,7 @@ func (db *pieceExpirationDB) DeleteFailed(ctx context.Context, satelliteID storj return ErrPieceExpiration.Wrap(err) } -// Trash marks a piece expiration as "trashed" +// Trash marks a piece expiration as "trashed". func (db *pieceExpirationDB) Trash(ctx context.Context, satelliteID storj.NodeID, pieceID storj.PieceID) (err error) { defer mon.Task()(&ctx)(&err) @@ -112,7 +112,7 @@ func (db *pieceExpirationDB) Trash(ctx context.Context, satelliteID storj.NodeID return ErrPieceExpiration.Wrap(err) } -// Restore restores all trashed pieces +// Restore restores all trashed pieces. func (db *pieceExpirationDB) RestoreTrash(ctx context.Context, satelliteID storj.NodeID) (err error) { defer mon.Task()(&ctx)(&err) diff --git a/storagenode/storagenodedb/pieceinfo.go b/storagenode/storagenodedb/pieceinfo.go index 9081a2ad1..65bb6ff37 100644 --- a/storagenode/storagenodedb/pieceinfo.go +++ b/storagenode/storagenodedb/pieceinfo.go @@ -215,17 +215,17 @@ type v0StoredPieceAccess struct { blobInfo storage.BlobInfo } -// PieceID returns the piece ID for the piece +// PieceID returns the piece ID for the piece. func (v0Access v0StoredPieceAccess) PieceID() storj.PieceID { return v0Access.pieceID } -// Satellite returns the satellite ID that owns the piece +// Satellite returns the satellite ID that owns the piece. func (v0Access v0StoredPieceAccess) Satellite() (storj.NodeID, error) { return v0Access.satellite, nil } -// BlobRef returns the relevant storage.BlobRef locator for the piece +// BlobRef returns the relevant storage.BlobRef locator for the piece. func (v0Access v0StoredPieceAccess) BlobRef() storage.BlobRef { return storage.BlobRef{ Namespace: v0Access.satellite.Bytes(), @@ -247,7 +247,7 @@ func (v0Access v0StoredPieceAccess) fillInBlobAccess(ctx context.Context) error return nil } -// Size gives the size of the piece, and the piece content size (not including the piece header, if applicable) +// Size gives the size of the piece, and the piece content size (not including the piece header, if applicable). func (v0Access v0StoredPieceAccess) Size(ctx context.Context) (int64, int64, error) { return v0Access.pieceSize, v0Access.pieceSize, nil } @@ -265,7 +265,7 @@ func (v0Access v0StoredPieceAccess) ModTime(ctx context.Context) (time.Time, err return v0Access.creationTime, nil } -// FullPath gives the full path to the on-disk blob file +// FullPath gives the full path to the on-disk blob file. func (v0Access v0StoredPieceAccess) FullPath(ctx context.Context) (string, error) { if err := v0Access.fillInBlobAccess(ctx); err != nil { return "", err @@ -273,12 +273,12 @@ func (v0Access v0StoredPieceAccess) FullPath(ctx context.Context) (string, error return v0Access.blobInfo.FullPath(ctx) } -// StorageFormatVersion indicates the storage format version used to store the piece +// StorageFormatVersion indicates the storage format version used to store the piece. func (v0Access v0StoredPieceAccess) StorageFormatVersion() storage.FormatVersion { return filestore.FormatV0 } -// Stat does a stat on the on-disk blob file +// Stat does a stat on the on-disk blob file. func (v0Access v0StoredPieceAccess) Stat(ctx context.Context) (os.FileInfo, error) { if err := v0Access.fillInBlobAccess(ctx); err != nil { return nil, err diff --git a/storagenode/storagenodedb/piecespaceused.go b/storagenode/storagenodedb/piecespaceused.go index 337ac150f..d73ab0ddf 100644 --- a/storagenode/storagenodedb/piecespaceused.go +++ b/storagenode/storagenodedb/piecespaceused.go @@ -26,14 +26,14 @@ const PieceSpaceUsedDBName = "piece_spaced_used" // identify the row storing the total for trash. // // It is intentionally an otherwise-invalid satellite_id (not 32 bytes) so that -// it cannot conflict with real satellite_id names +// it cannot conflict with real satellite_id names. const trashTotalRowName = "trashtotal" type pieceSpaceUsedDB struct { dbContainerImpl } -// Init creates the total pieces and total trash records if they don't already exist +// Init creates the total pieces and total trash records if they don't already exist. func (db *pieceSpaceUsedDB) Init(ctx context.Context) (err error) { totalPiecesRow := db.QueryRowContext(ctx, ` SELECT total @@ -87,7 +87,7 @@ func (db *pieceSpaceUsedDB) createInitTotalTrash(ctx context.Context) (err error return ErrPieceSpaceUsed.Wrap(err) } -// GetPieceTotal returns the total space used (total and contentSize) for all pieces stored +// GetPieceTotal returns the total space used (total and contentSize) for all pieces stored. func (db *pieceSpaceUsedDB) GetPieceTotals(ctx context.Context) (total int64, contentSize int64, err error) { defer mon.Task()(&ctx)(&err) @@ -107,7 +107,7 @@ func (db *pieceSpaceUsedDB) GetPieceTotals(ctx context.Context) (total int64, co return total, contentSize, nil } -// GetTrashTotal returns the total space used by all trash +// GetTrashTotal returns the total space used by all trash. func (db *pieceSpaceUsedDB) GetTrashTotal(ctx context.Context) (total int64, err error) { defer mon.Task()(&ctx)(&err) @@ -127,7 +127,7 @@ func (db *pieceSpaceUsedDB) GetTrashTotal(ctx context.Context) (total int64, err return total, nil } -// GetPieceTotalsForAllSatellites returns how much space used by pieces stored for each satelliteID +// GetPieceTotalsForAllSatellites returns how much space used by pieces stored for each satelliteID. func (db *pieceSpaceUsedDB) GetPieceTotalsForAllSatellites(ctx context.Context) (_ map[storj.NodeID]pieces.SatelliteUsage, err error) { defer mon.Task()(&ctx)(&err) @@ -162,7 +162,7 @@ func (db *pieceSpaceUsedDB) GetPieceTotalsForAllSatellites(ctx context.Context) return totalBySatellite, rows.Err() } -// UpdatePieceTotals updates the record for total spaced used with new total and contentSize values +// UpdatePieceTotals updates the record for total spaced used with new total and contentSize values. func (db *pieceSpaceUsedDB) UpdatePieceTotals(ctx context.Context, newTotal, newContentSize int64) (err error) { defer mon.Task()(&ctx)(&err) @@ -175,7 +175,7 @@ func (db *pieceSpaceUsedDB) UpdatePieceTotals(ctx context.Context, newTotal, new return ErrPieceSpaceUsed.Wrap(err) } -// UpdateTrashTotal updates the record for total spaced used with a new value +// UpdateTrashTotal updates the record for total spaced used with a new value. func (db *pieceSpaceUsedDB) UpdateTrashTotal(ctx context.Context, newTotal int64) (err error) { defer mon.Task()(&ctx)(&err) @@ -188,7 +188,7 @@ func (db *pieceSpaceUsedDB) UpdateTrashTotal(ctx context.Context, newTotal int64 return ErrPieceSpaceUsed.Wrap(err) } -// UpdatePieceTotalsForAllSatellites updates each record with new values for each satelliteID +// UpdatePieceTotalsForAllSatellites updates each record with new values for each satelliteID. func (db *pieceSpaceUsedDB) UpdatePieceTotalsForAllSatellites(ctx context.Context, newTotalsBySatellites map[storj.NodeID]pieces.SatelliteUsage) (err error) { defer mon.Task()(&ctx)(&err) diff --git a/storagenode/storagenodedb/reputation.go b/storagenode/storagenodedb/reputation.go index 6055fc2c7..a375c23f1 100644 --- a/storagenode/storagenodedb/reputation.go +++ b/storagenode/storagenodedb/reputation.go @@ -20,7 +20,7 @@ var ErrReputation = errs.Class("reputation error") // ReputationDBName represents the database name. const ReputationDBName = "reputation" -// reputation works with node reputation DB +// reputation works with node reputation DB. type reputationDB struct { dbContainerImpl } diff --git a/storagenode/storagenodedb/satellites.go b/storagenode/storagenodedb/satellites.go index 04de434bc..1c6346fae 100644 --- a/storagenode/storagenodedb/satellites.go +++ b/storagenode/storagenodedb/satellites.go @@ -20,12 +20,12 @@ var ErrSatellitesDB = errs.Class("satellitesdb error") // SatellitesDBName represents the database name. const SatellitesDBName = "satellites" -// reputation works with node reputation DB +// reputation works with node reputation DB. type satellitesDB struct { dbContainerImpl } -// GetSatellite retrieves that satellite by ID +// GetSatellite retrieves that satellite by ID. func (db *satellitesDB) GetSatellite(ctx context.Context, satelliteID storj.NodeID) (satellite satellites.Satellite, err error) { defer mon.Task()(&ctx)(&err) @@ -44,7 +44,7 @@ func (db *satellitesDB) GetSatellite(ctx context.Context, satelliteID storj.Node return satellite, rows.Err() } -// InitiateGracefulExit updates the database to reflect the beginning of a graceful exit +// InitiateGracefulExit updates the database to reflect the beginning of a graceful exit. func (db *satellitesDB) InitiateGracefulExit(ctx context.Context, satelliteID storj.NodeID, intitiatedAt time.Time, startingDiskUsage int64) (err error) { defer mon.Task()(&ctx)(&err) return ErrSatellitesDB.Wrap(withTx(ctx, db.GetDB(), func(tx tagsql.Tx) error { @@ -59,7 +59,7 @@ func (db *satellitesDB) InitiateGracefulExit(ctx context.Context, satelliteID st })) } -// CancelGracefulExit delete an entry by satellite ID +// CancelGracefulExit delete an entry by satellite ID. func (db *satellitesDB) CancelGracefulExit(ctx context.Context, satelliteID storj.NodeID) (err error) { defer mon.Task()(&ctx)(&err) @@ -67,7 +67,7 @@ func (db *satellitesDB) CancelGracefulExit(ctx context.Context, satelliteID stor return ErrSatellitesDB.Wrap(err) } -// UpdateGracefulExit increments the total bytes deleted during a graceful exit +// UpdateGracefulExit increments the total bytes deleted during a graceful exit. func (db *satellitesDB) UpdateGracefulExit(ctx context.Context, satelliteID storj.NodeID, addToBytesDeleted int64) (err error) { defer mon.Task()(&ctx)(&err) query := `UPDATE satellite_exit_progress SET bytes_deleted = bytes_deleted + ? WHERE satellite_id = ?` @@ -75,7 +75,7 @@ func (db *satellitesDB) UpdateGracefulExit(ctx context.Context, satelliteID stor return ErrSatellitesDB.Wrap(err) } -// CompleteGracefulExit updates the database when a graceful exit is completed or failed +// CompleteGracefulExit updates the database when a graceful exit is completed or failed. func (db *satellitesDB) CompleteGracefulExit(ctx context.Context, satelliteID storj.NodeID, finishedAt time.Time, exitStatus satellites.Status, completionReceipt []byte) (err error) { defer mon.Task()(&ctx)(&err) return ErrSatellitesDB.Wrap(withTx(ctx, db.GetDB(), func(tx tagsql.Tx) error { @@ -90,7 +90,7 @@ func (db *satellitesDB) CompleteGracefulExit(ctx context.Context, satelliteID st })) } -// ListGracefulExits lists all graceful exit records +// ListGracefulExits lists all graceful exit records. func (db *satellitesDB) ListGracefulExits(ctx context.Context) (exitList []satellites.ExitProgress, err error) { defer mon.Task()(&ctx)(&err) diff --git a/storagenode/storagenodedb/storageusage.go b/storagenode/storagenodedb/storageusage.go index 073d058d2..840713a21 100644 --- a/storagenode/storagenodedb/storageusage.go +++ b/storagenode/storagenodedb/storageusage.go @@ -18,12 +18,12 @@ import ( // StorageUsageDBName represents the database name. const StorageUsageDBName = "storage_usage" -// storageUsageDB storage usage DB +// storageUsageDB storage usage DB. type storageUsageDB struct { dbContainerImpl } -// Store stores storage usage stamps to db replacing conflicting entries +// Store stores storage usage stamps to db replacing conflicting entries. func (db *storageUsageDB) Store(ctx context.Context, stamps []storageusage.Stamp) (err error) { defer mon.Task()(&ctx)(&err) @@ -48,7 +48,7 @@ func (db *storageUsageDB) Store(ctx context.Context, stamps []storageusage.Stamp } // GetDaily returns daily storage usage stamps for particular satellite -// for provided time range +// for provided time range. func (db *storageUsageDB) GetDaily(ctx context.Context, satelliteID storj.NodeID, from, to time.Time) (_ []storageusage.Stamp, err error) { defer mon.Task()(&ctx)(&err) @@ -89,7 +89,7 @@ func (db *storageUsageDB) GetDaily(ctx context.Context, satelliteID storj.NodeID } // GetDailyTotal returns daily storage usage stamps summed across all known satellites -// for provided time range +// for provided time range. func (db *storageUsageDB) GetDailyTotal(ctx context.Context, from, to time.Time) (_ []storageusage.Stamp, err error) { defer mon.Task()(&ctx)(&err) diff --git a/storagenode/storagenodedb/testdata/multidbsnapshot.go b/storagenode/storagenodedb/testdata/multidbsnapshot.go index c74f1d623..6a628db65 100644 --- a/storagenode/storagenodedb/testdata/multidbsnapshot.go +++ b/storagenode/storagenodedb/testdata/multidbsnapshot.go @@ -11,7 +11,7 @@ import ( "storj.io/storj/private/dbutil/sqliteutil" ) -// States is the global variable that stores all the states for testing +// States is the global variable that stores all the states for testing. var States = MultiDBStates{ List: []*MultiDBState{ &v0, @@ -61,7 +61,7 @@ var States = MultiDBStates{ }, } -// MultiDBStates provides a convenient list of MultiDBState +// MultiDBStates provides a convenient list of MultiDBState. type MultiDBStates struct { List []*MultiDBState } @@ -83,7 +83,7 @@ type MultiDBState struct { DBStates DBStates } -// DBStates is a convenience type +// DBStates is a convenience type. type DBStates map[string]*DBState // DBState allows you to define the desired state of the DB using SQl commands. @@ -95,20 +95,20 @@ type DBState struct { NewData string } -// MultiDBSnapshot represents an expected state among multiple databases +// MultiDBSnapshot represents an expected state among multiple databases. type MultiDBSnapshot struct { Version int DBSnapshots DBSnapshots } -// NewMultiDBSnapshot returns a new MultiDBSnapshot +// NewMultiDBSnapshot returns a new MultiDBSnapshot. func NewMultiDBSnapshot() *MultiDBSnapshot { return &MultiDBSnapshot{ DBSnapshots: DBSnapshots{}, } } -// DBSnapshots is a convenience type +// DBSnapshots is a convenience type. type DBSnapshots map[string]*DBSnapshot // DBSnapshot is a snapshot of a single DB. diff --git a/storagenode/trust/cache.go b/storagenode/trust/cache.go index e2ba4a533..d95872bef 100644 --- a/storagenode/trust/cache.go +++ b/storagenode/trust/cache.go @@ -15,7 +15,7 @@ import ( "storj.io/common/fpath" ) -// Cache caches source information about trusted satellites +// Cache caches source information about trusted satellites. type Cache struct { path string data *CacheData @@ -48,7 +48,7 @@ func LoadCache(path string) (*Cache, error) { }, nil } -// Path returns the path on disk to the file containing the cache +// Path returns the path on disk to the file containing the cache. func (cache *Cache) Path() string { return cache.path } @@ -61,30 +61,30 @@ func (cache *Cache) Lookup(key string) (entries []Entry, ok bool) { return entries, ok } -// Set sets the entries in the cache for the provided key +// Set sets the entries in the cache for the provided key. func (cache *Cache) Set(key string, entries []Entry) { cache.data.Entries[key] = entries } -// Save persists the cache to disk +// Save persists the cache to disk. func (cache *Cache) Save(ctx context.Context) (err error) { defer mon.Task()(&ctx)(&err) return SaveCacheData(cache.path, cache.data) } -// CacheData represents the data stored in the cache +// CacheData represents the data stored in the cache. type CacheData struct { Entries map[string][]Entry `json:"entries"` } -// NewCacheData returns an new CacheData +// NewCacheData returns an new CacheData. func NewCacheData() *CacheData { return &CacheData{ Entries: make(map[string][]Entry), } } -// LoadCacheData loads the cache data from the given path +// LoadCacheData loads the cache data from the given path. func LoadCacheData(path string) (*CacheData, error) { dataBytes, err := ioutil.ReadFile(path) if err != nil { @@ -102,7 +102,7 @@ func LoadCacheData(path string) (*CacheData, error) { return data, nil } -// SaveCacheData persists the cache data to the given path +// SaveCacheData persists the cache data to the given path. func SaveCacheData(path string, data *CacheData) error { // Ensure the entries map is always non-nil on save if data.Entries == nil { diff --git a/storagenode/trust/config.go b/storagenode/trust/config.go index f67760cb2..7fb7841cd 100644 --- a/storagenode/trust/config.go +++ b/storagenode/trust/config.go @@ -10,7 +10,7 @@ import ( "github.com/zeebo/errs" ) -// Config is the trust configuration +// Config is the trust configuration. type Config struct { Sources Sources `help:"list of trust sources" devDefault:"" releaseDefault:"https://tardigrade.io/trusted-satellites"` Exclusions Exclusions `help:"list of trust exclusions" devDefault:"" releaseDefault:""` @@ -18,10 +18,10 @@ type Config struct { CachePath string `help:"file path where trust lists should be cached" default:"${CONFDIR}/trust-cache.json"` } -// Sources is a list of sources that implements pflag.Value +// Sources is a list of sources that implements pflag.Value. type Sources []Source -// String returns the string representation of the config +// String returns the string representation of the config. func (sources Sources) String() string { s := make([]string, 0, len(sources)) for _, source := range sources { @@ -30,7 +30,7 @@ func (sources Sources) String() string { return strings.Join(s, ",") } -// Set implements pflag.Value by parsing a comma separated list of sources +// Set implements pflag.Value by parsing a comma separated list of sources. func (sources *Sources) Set(value string) error { var entries []string if value != "" { @@ -50,17 +50,17 @@ func (sources *Sources) Set(value string) error { return nil } -// Type returns the type of the pflag.Value +// Type returns the type of the pflag.Value. func (sources Sources) Type() string { return "trust-sources" } -// Exclusions is a list of excluding rules that implements pflag.Value +// Exclusions is a list of excluding rules that implements pflag.Value. type Exclusions struct { Rules Rules } -// String returns the string representation of the config +// String returns the string representation of the config. func (exclusions *Exclusions) String() string { s := make([]string, 0, len(exclusions.Rules)) for _, rule := range exclusions.Rules { @@ -69,7 +69,7 @@ func (exclusions *Exclusions) String() string { return strings.Join(s, ",") } -// Set implements pflag.Value by parsing a comma separated list of exclusions +// Set implements pflag.Value by parsing a comma separated list of exclusions. func (exclusions *Exclusions) Set(value string) error { var entries []string if value != "" { @@ -89,7 +89,7 @@ func (exclusions *Exclusions) Set(value string) error { return nil } -// Type returns the type of the pflag.Value +// Type returns the type of the pflag.Value. func (exclusions Exclusions) Type() string { return "trust-exclusions" } diff --git a/storagenode/trust/excluder.go b/storagenode/trust/excluder.go index 969e11695..6ee3e17ce 100644 --- a/storagenode/trust/excluder.go +++ b/storagenode/trust/excluder.go @@ -37,12 +37,12 @@ func NewExcluder(config string) (Rule, error) { } } -// URLExcluder excludes matching URLs +// URLExcluder excludes matching URLs. type URLExcluder struct { url SatelliteURL } -// NewURLExcluder returns a new URLExcluder +// NewURLExcluder returns a new URLExcluder. func NewURLExcluder(url SatelliteURL) *URLExcluder { url.Host = normalizeHost(url.Host) return &URLExcluder{ @@ -50,35 +50,35 @@ func NewURLExcluder(url SatelliteURL) *URLExcluder { } } -// IsTrusted returns true if the given Satellite is trusted and false otherwise +// IsTrusted returns true if the given Satellite is trusted and false otherwise. func (excluder *URLExcluder) IsTrusted(url SatelliteURL) bool { url.Host = normalizeHost(url.Host) return excluder.url != url } -// String returns a string representation of the excluder +// String returns a string representation of the excluder. func (excluder *URLExcluder) String() string { return excluder.url.String() } -// IDExcluder excludes URLs matching a given URL +// IDExcluder excludes URLs matching a given URL. type IDExcluder struct { id storj.NodeID } -// NewIDExcluder returns a new IDExcluder +// NewIDExcluder returns a new IDExcluder. func NewIDExcluder(id storj.NodeID) *IDExcluder { return &IDExcluder{ id: id, } } -// IsTrusted returns true if the given Satellite is trusted and false otherwise +// IsTrusted returns true if the given Satellite is trusted and false otherwise. func (excluder *IDExcluder) IsTrusted(url SatelliteURL) bool { return excluder.id != url.ID } -// String returns a string representation of the excluder +// String returns a string representation of the excluder. func (excluder *IDExcluder) String() string { return excluder.id.String() + "@" } @@ -90,7 +90,7 @@ type HostExcluder struct { suffix string } -// NewHostExcluder returns a new HostExcluder +// NewHostExcluder returns a new HostExcluder. func NewHostExcluder(host string) *HostExcluder { host = normalizeHost(host) @@ -106,7 +106,7 @@ func NewHostExcluder(host string) *HostExcluder { } } -// IsTrusted returns true if the given Satellite is trusted and false otherwise +// IsTrusted returns true if the given Satellite is trusted and false otherwise. func (excluder *HostExcluder) IsTrusted(url SatelliteURL) bool { host := normalizeHost(url.Host) if excluder.host == host { @@ -119,7 +119,7 @@ func (excluder *HostExcluder) IsTrusted(url SatelliteURL) bool { return true } -// String returns a string representation of the excluder +// String returns a string representation of the excluder. func (excluder *HostExcluder) String() string { return excluder.host } @@ -127,7 +127,7 @@ func (excluder *HostExcluder) String() string { // parseExcluderConfig parses a excluder configuration. The following forms are accepted: // - Satellite ID followed by @ // - Satellite host -// - Full Satellite URL (i.e. id@host:port) +// - Full Satellite URL (i.e. id@host:port). func parseExcluderConfig(s string) (SatelliteURL, error) { url, err := storj.ParseNodeURL(s) if err != nil { diff --git a/storagenode/trust/file_source.go b/storagenode/trust/file_source.go index 91a33fd83..30a583fa8 100644 --- a/storagenode/trust/file_source.go +++ b/storagenode/trust/file_source.go @@ -15,7 +15,7 @@ var ( ErrFileSource = errs.Class("file source") ) -// FileSource represents a trust source contained in a file on disk +// FileSource represents a trust source contained in a file on disk. type FileSource struct { path string } @@ -28,7 +28,7 @@ func NewFileSource(path string) *FileSource { } } -// String implements the Source interface and returns the FileSource URL +// String implements the Source interface and returns the FileSource URL. func (source *FileSource) String() string { return source.path } @@ -54,7 +54,7 @@ func (source *FileSource) FetchEntries(ctx context.Context) (_ []Entry, err erro return entries, nil } -// LoadSatelliteURLList loads a list of Satellite URLs from a path on disk +// LoadSatelliteURLList loads a list of Satellite URLs from a path on disk. func LoadSatelliteURLList(ctx context.Context, path string) (_ []SatelliteURL, err error) { defer mon.Task()(&ctx)(&err) diff --git a/storagenode/trust/http_source.go b/storagenode/trust/http_source.go index 751136684..00f6d2893 100644 --- a/storagenode/trust/http_source.go +++ b/storagenode/trust/http_source.go @@ -20,7 +20,7 @@ var ( ErrHTTPSource = errs.Class("HTTP source") ) -// HTTPSource represents a trust source at a http:// or https:// URL +// HTTPSource represents a trust source at a http:// or https:// URL. type HTTPSource struct { url *url.URL } @@ -44,7 +44,7 @@ func NewHTTPSource(httpURL string) (*HTTPSource, error) { return &HTTPSource{url: u}, nil } -// String implements the Source interface and returns the URL +// String implements the Source interface and returns the URL. func (source *HTTPSource) String() string { return source.url.String() } diff --git a/storagenode/trust/list.go b/storagenode/trust/list.go index bcab8cd9c..51f213ab8 100644 --- a/storagenode/trust/list.go +++ b/storagenode/trust/list.go @@ -11,7 +11,7 @@ import ( "storj.io/common/storj" ) -// List represents a dynamic trust list +// List represents a dynamic trust list. type List struct { log *zap.Logger sources Sources diff --git a/storagenode/trust/rule.go b/storagenode/trust/rule.go index 1af83b21f..6888a0a52 100644 --- a/storagenode/trust/rule.go +++ b/storagenode/trust/rule.go @@ -3,7 +3,7 @@ package trust -// Rule indicates whether or not a Satellite URL is trusted +// Rule indicates whether or not a Satellite URL is trusted. type Rule interface { // IsTrusted returns true if the given Satellite is trusted and false otherwise IsTrusted(url SatelliteURL) bool @@ -12,10 +12,10 @@ type Rule interface { String() string } -// Rules is a collection of rules +// Rules is a collection of rules. type Rules []Rule -// IsTrusted returns true if the given Satellite is trusted and false otherwise +// IsTrusted returns true if the given Satellite is trusted and false otherwise. func (rules Rules) IsTrusted(url SatelliteURL) bool { for _, rule := range rules { if !rule.IsTrusted(url) { diff --git a/storagenode/trust/satellite_url.go b/storagenode/trust/satellite_url.go index 35c4e3354..cf2cb83b7 100644 --- a/storagenode/trust/satellite_url.go +++ b/storagenode/trust/satellite_url.go @@ -21,19 +21,19 @@ var ( ErrSatelliteURL = errs.Class("invalid satellite URL") ) -// SatelliteURL represents a Satellite URL +// SatelliteURL represents a Satellite URL. type SatelliteURL struct { ID storj.NodeID `json:"id"` Host string `json:"host"` Port int `json:"port"` } -// Address returns the address (i.e. host:port) of the Satellite +// Address returns the address (i.e. host:port) of the Satellite. func (u *SatelliteURL) Address() string { return net.JoinHostPort(u.Host, strconv.Itoa(u.Port)) } -// NodeURL returns a full Node URL to the Satellite +// NodeURL returns a full Node URL to the Satellite. func (u *SatelliteURL) NodeURL() storj.NodeURL { return storj.NodeURL{ ID: u.ID, @@ -41,7 +41,7 @@ func (u *SatelliteURL) NodeURL() storj.NodeURL { } } -// String returns a string representation of the Satellite URL +// String returns a string representation of the Satellite URL. func (u *SatelliteURL) String() string { return u.ID.String() + "@" + u.Address() } diff --git a/storagenode/trust/service.go b/storagenode/trust/service.go index a111d51a5..c56523c99 100644 --- a/storagenode/trust/service.go +++ b/storagenode/trust/service.go @@ -21,14 +21,14 @@ import ( "storj.io/common/sync2" ) -// Error is the default error class +// Error is the default error class. var ( Error = errs.Class("trust") mon = monkit.Package() ) -// IdentityResolver resolves peer identities from a node URL +// IdentityResolver resolves peer identities from a node URL. type IdentityResolver interface { // ResolveIdentity returns the peer identity of the peer located at the Node URL ResolveIdentity(ctx context.Context, url storj.NodeURL) (*identity.PeerIdentity, error) @@ -38,12 +38,12 @@ type IdentityResolver interface { // function literal. type IdentityResolverFunc func(ctx context.Context, url storj.NodeURL) (*identity.PeerIdentity, error) -// ResolveIdentity returns the peer identity of the peer located at the Node URL +// ResolveIdentity returns the peer identity of the peer located at the Node URL. func (fn IdentityResolverFunc) ResolveIdentity(ctx context.Context, url storj.NodeURL) (*identity.PeerIdentity, error) { return fn(ctx, url) } -// Dialer implements an IdentityResolver using an RPC dialer +// Dialer implements an IdentityResolver using an RPC dialer. func Dialer(dialer rpc.Dialer) IdentityResolver { return IdentityResolverFunc(func(ctx context.Context, url storj.NodeURL) (_ *identity.PeerIdentity, err error) { defer mon.Task()(&ctx)(&err) @@ -72,7 +72,7 @@ type Pool struct { satellites map[storj.NodeID]*satelliteInfoCache } -// satelliteInfoCache caches identity information about a satellite +// satelliteInfoCache caches identity information about a satellite. type satelliteInfoCache struct { mu sync.Mutex url storj.NodeURL @@ -150,7 +150,7 @@ func (pool *Pool) GetSignee(ctx context.Context, id storj.NodeID) (_ signing.Sig return signing.SigneeFromPeerIdentity(info.identity), nil } -// GetSatellites returns a slice containing all trusted satellites +// GetSatellites returns a slice containing all trusted satellites. func (pool *Pool) GetSatellites(ctx context.Context) (satellites []storj.NodeID) { defer mon.Task()(&ctx)(nil) for sat := range pool.satellites { diff --git a/storagenode/trust/source.go b/storagenode/trust/source.go index 48dfd3974..db14f59d8 100644 --- a/storagenode/trust/source.go +++ b/storagenode/trust/source.go @@ -10,7 +10,7 @@ import ( "github.com/zeebo/errs" ) -// Entry represents a trust entry +// Entry represents a trust entry. type Entry struct { // SatelliteURL is the URL of the satellite SatelliteURL SatelliteURL @@ -20,7 +20,7 @@ type Entry struct { Authoritative bool `json:"authoritative"` } -// Source is a trust source for trusted Satellites +// Source is a trust source for trusted Satellites. type Source interface { // String is the string representation of the source. It is used as a key // into the cache. @@ -73,7 +73,7 @@ func isReserved(s string) (schema string, ok bool) { // - @ // - id@ // - host:9999 -// - id@host:9999 +// - id@host:9999. var reProbablySatelliteURL = regexp.MustCompile(`@|(^[^/\\]{2,}:\d+$)`) func isProbablySatelliteURL(s string) bool { diff --git a/storagenode/trust/static_source.go b/storagenode/trust/static_source.go index 9c1124b87..10960b2c6 100644 --- a/storagenode/trust/static_source.go +++ b/storagenode/trust/static_source.go @@ -14,7 +14,7 @@ var ( ErrStaticSource = errs.Class("static source") ) -// StaticURLSource is a trust source that returns an explicitly trusted URL +// StaticURLSource is a trust source that returns an explicitly trusted URL. type StaticURLSource struct { URL SatelliteURL } @@ -28,7 +28,7 @@ func NewStaticURLSource(satelliteURL string) (*StaticURLSource, error) { return &StaticURLSource{URL: url}, nil } -// String implements the Source interface and returns the static trusted URL +// String implements the Source interface and returns the static trusted URL. func (source *StaticURLSource) String() string { return source.URL.String() }