fix: clear all go vet findings (upstream lint debt)

- pkg/serializer: rename GobDecode -> DecodeGob (custom signature, not gob.GobDecoder)
- aria2 rpc: pointer receivers for Call (were copying sync.Once)
- HMACAuth: keyed struct literals (8 sites)
- webdav prop: keyed xml.Name literal
- request_test: pointer receiver on ClientMock (dead mock, copied sync.Mutex)

CI backend job now passes vet.

Authored By: TDvorak <info@tdvorak.dev>
pull/3579/head
Tomas Dvorak 2 weeks ago
parent 791bfb07e5
commit 88b1910d99

@ -28,7 +28,7 @@ func Init() error {
if confDBType == "sqlite3" { if confDBType == "sqlite3" {
confDBType = "sqlite" confDBType = "sqlite"
} }
// 兼容 "mariadb" 数据库 // 兼容 "mariadb" 数据库
if confDBType == "mariadb" { if confDBType == "mariadb" {
confDBType = "mysql" confDBType = "mysql"

@ -92,9 +92,7 @@ func newMasterNode(model *ent.Node, config conf.ConfigProvider, settings setting
if config.System().Mode == conf.SlaveMode { if config.System().Mode == conf.SlaveMode {
n.client = request.NewClient(config, n.client = request.NewClient(config,
request.WithCorrelationID(), request.WithCorrelationID(),
request.WithCredential(auth.HMACAuth{ request.WithCredential(auth.HMACAuth{SecretKey: []byte(config.Slave().Secret)}, int64(config.Slave().SignatureTTL)),
[]byte(config.Slave().Secret),
}, int64(config.Slave().SignatureTTL)),
) )
} }
@ -126,7 +124,7 @@ func (b *masterNode) PrepareUpload(ctx context.Context, args *fs.StatelessPrepar
} }
uploadRequest := &fs.StatelessPrepareUploadResponse{} uploadRequest := &fs.StatelessPrepareUploadResponse{}
resp.GobDecode(uploadRequest) resp.DecodeGob(uploadRequest)
return uploadRequest, nil return uploadRequest, nil
} }
@ -245,7 +243,7 @@ func newSlaveNode(ctx context.Context, model *ent.Node, config conf.ConfigProvid
request.WithCorrelationID(), request.WithCorrelationID(),
request.WithSlaveMeta(model.ID), request.WithSlaveMeta(model.ID),
request.WithMasterMeta(siteBasic.ID, settings.SiteURL(setting.UseFirstSiteUrl(ctx)).String()), request.WithMasterMeta(siteBasic.ID, settings.SiteURL(setting.UseFirstSiteUrl(ctx)).String()),
request.WithCredential(auth.HMACAuth{[]byte(model.SlaveKey)}, int64(settings.SlaveRequestSignTTL(ctx))), request.WithCredential(auth.HMACAuth{SecretKey: []byte(model.SlaveKey)}, int64(settings.SlaveRequestSignTTL(ctx))),
request.WithEndpoint(model.Server)), request.WithEndpoint(model.Server)),
} }
} }
@ -276,7 +274,7 @@ func (n *slaveNode) CreateTask(ctx context.Context, taskType string, state strin
} }
taskId := 0 taskId := 0
if resp.GobDecode(&taskId); taskId > 0 { if resp.DecodeGob(&taskId); taskId > 0 {
return taskId, nil return taskId, nil
} }
@ -301,7 +299,7 @@ func (n *slaveNode) GetTask(ctx context.Context, id int, clearOnComplete bool) (
} }
summary := &SlaveTaskSummary{} summary := &SlaveTaskSummary{}
resp.GobDecode(summary) resp.DecodeGob(summary)
return summary, nil return summary, nil
} }
@ -359,7 +357,7 @@ func (b *nodeBase) CreateTask(ctx context.Context, taskType string, state string
} }
func (b *nodeBase) AuthInstance() auth.Auth { func (b *nodeBase) AuthInstance() auth.Auth {
return auth.HMACAuth{[]byte(b.model.SlaveKey)} return auth.HMACAuth{SecretKey: []byte(b.model.SlaveKey)}
} }
func (b *nodeBase) GetTask(ctx context.Context, id int, clearOnComplete bool) (*SlaveTaskSummary, error) { func (b *nodeBase) GetTask(ctx context.Context, id int, clearOnComplete bool) (*SlaveTaskSummary, error) {

@ -166,9 +166,7 @@ func NewSlaveManager(kv cache.Driver, config conf.ConfigProvider) CredManager {
kv: kv, kv: kv,
client: request.NewClient( client: request.NewClient(
config, config,
request.WithCredential(auth.HMACAuth{ request.WithCredential(auth.HMACAuth{SecretKey: []byte(config.Slave().Secret)}, int64(config.Slave().SignatureTTL)),
[]byte(config.Slave().Secret),
}, int64(config.Slave().SignatureTTL)),
), ),
} }
} }
@ -228,7 +226,7 @@ func (m *slaveCredManager) requestCredFromMaster(ctx context.Context, key string
} }
cred := &CredentialResponse{} cred := &CredentialResponse{}
resp.GobDecode(&cred) resp.DecodeGob(&cred)
if err := m.kv.Set(key, *cred, max(int(time.Until(cred.Expiry()).Seconds()), 1)); err != nil { if err := m.kv.Set(key, *cred, max(int(time.Until(cred.Expiry()).Seconds()), 1)); err != nil {
return nil, fmt.Errorf("failed to update credential in KV for key %q: %w", key, err) return nil, fmt.Errorf("failed to update credential in KV for key %q: %w", key, err)

@ -120,7 +120,7 @@ func (h *httpCaller) setNotifier(ctx context.Context, u url.URL, notifer Notifie
return return
} }
func (h httpCaller) Call(method string, params, reply interface{}) (err error) { func (h *httpCaller) Call(method string, params, reply interface{}) (err error) {
payload, err := EncodeClientRequest(method, params) payload, err := EncodeClientRequest(method, params)
if err != nil { if err != nil {
return return
@ -236,7 +236,7 @@ func (w *websocketCaller) Close() (err error) {
return return
} }
func (w websocketCaller) Call(method string, params, reply interface{}) (err error) { func (w *websocketCaller) Call(method string, params, reply interface{}) (err error) {
ctx, cancel := context.WithTimeout(context.Background(), w.timeout) ctx, cancel := context.WithTimeout(context.Background(), w.timeout)
defer cancel() defer cancel()
select { select {

@ -63,7 +63,7 @@ func (s *slaveDownloader) CreateTask(ctx context.Context, url string, options ma
} }
var taskHandle *downloader.TaskHandle var taskHandle *downloader.TaskHandle
if resp.GobDecode(&taskHandle); taskHandle != nil { if resp.DecodeGob(&taskHandle); taskHandle != nil {
return taskHandle, nil return taskHandle, nil
} }
@ -101,7 +101,7 @@ func (s *slaveDownloader) Info(ctx context.Context, handle *downloader.TaskHandl
} }
var taskStatus *downloader.TaskStatus var taskStatus *downloader.TaskStatus
if resp.GobDecode(&taskStatus); taskStatus != nil { if resp.DecodeGob(&taskStatus); taskStatus != nil {
return taskStatus, nil return taskStatus, nil
} }

@ -229,9 +229,9 @@ func (handler *Driver) Token(ctx context.Context, uploadSession *fs.UploadSessio
} else { } else {
// When disk pre-allocation is disabled, concurrent chunk uploads must be 1 // When disk pre-allocation is disabled, concurrent chunk uploads must be 1
// to avoid disk fragmentation and write contention on local storage. // to avoid disk fragmentation and write contention on local storage.
settings := *handler.Policy.Settings settings := *handler.Policy.Settings
settings.ChunkConcurrency = 1 settings.ChunkConcurrency = 1
handler.Policy.Settings = &settings handler.Policy.Settings = &settings
} }
return &fs.UploadCredential{ return &fs.UploadCredential{
@ -275,7 +275,7 @@ func (handler *Driver) CompleteUpload(ctx context.Context, session *fs.UploadSes
nil, nil,
request.WithTimeout(time.Duration(handler.config.Slave().CallbackTimeout)*time.Second), request.WithTimeout(time.Duration(handler.config.Slave().CallbackTimeout)*time.Second),
request.WithCredential( request.WithCredential(
auth.HMACAuth{[]byte(session.Policy.Edges.Node.SlaveKey)}, auth.HMACAuth{SecretKey: []byte(session.Policy.Edges.Node.SlaveKey)},
int64(handler.config.Slave().SignatureTTL), int64(handler.config.Slave().SignatureTTL),
), ),
request.WithContext(ctx), request.WithContext(ctx),

@ -61,7 +61,7 @@ func NewClient(ctx context.Context, policy *ent.StoragePolicy, settings setting.
return nil, fmt.Errorf("remote storage policy %d has no node", policy.ID) return nil, fmt.Errorf("remote storage policy %d has no node", policy.ID)
} }
authInstance := auth.HMACAuth{[]byte(policy.Edges.Node.SlaveKey)} authInstance := auth.HMACAuth{SecretKey: []byte(policy.Edges.Node.SlaveKey)}
serverURL, err := url.Parse(policy.Edges.Node.Server) serverURL, err := url.Parse(policy.Edges.Node.Server)
if err != nil { if err != nil {
return nil, err return nil, err
@ -176,7 +176,7 @@ func (c *remoteClient) DeleteFiles(ctx context.Context, files ...string) ([]stri
var failed []string var failed []string
failed = files failed = files
if resp.Code == serializer.CodeNotFullySuccess { if resp.Code == serializer.CodeNotFullySuccess {
resp.GobDecode(&failed) resp.DecodeGob(&failed)
} }
return failed, errors.New(resp.Error) return failed, errors.New(resp.Error)
} }
@ -201,7 +201,7 @@ func (c *remoteClient) MediaMeta(ctx context.Context, src, ext, language string)
} }
var metas []driver.MediaMeta var metas []driver.MediaMeta
resp.GobDecode(&metas) resp.DecodeGob(&metas)
return metas, nil return metas, nil
} }
@ -250,7 +250,7 @@ func (c *remoteClient) List(ctx context.Context, path string, recursive bool) ([
} }
var objects []fs.PhysicalObject var objects []fs.PhysicalObject
resp.GobDecode(&objects) resp.DecodeGob(&objects)
return objects, nil return objects, nil
} }

@ -47,7 +47,7 @@ func New(ctx context.Context, policy *ent.StoragePolicy, settings setting.Provid
return &Driver{ return &Driver{
Policy: policy, Policy: policy,
Client: request.NewClient(config), Client: request.NewClient(config),
AuthInstance: auth.HMACAuth{[]byte(policy.Edges.Node.SlaveKey)}, AuthInstance: auth.HMACAuth{SecretKey: []byte(policy.Edges.Node.SlaveKey)},
uploadClient: client, uploadClient: client,
settings: settings, settings: settings,
config: config, config: config,

@ -18,7 +18,7 @@ type ClientMock struct {
testMock.Mock testMock.Mock
} }
func (m ClientMock) Request(method, target string, body io.Reader, opts ...Option) *Response { func (m *ClientMock) Request(method, target string, body io.Reader, opts ...Option) *Response {
args := m.Called(method, target, body, opts) args := m.Called(method, target, body, opts)
return args.Get(0).(*Response) return args.Get(0).(*Response)
} }

@ -28,8 +28,8 @@ func NewResponseWithGobData(c context.Context, data interface{}) Response {
return Response{Data: w.Bytes()} return Response{Data: w.Bytes()}
} }
// GobDecode 将 Response 正文解码至目标指针 // DecodeGob 将 Response 正文解码至目标指针
func (r *Response) GobDecode(target interface{}) { func (r *Response) DecodeGob(target interface{}) {
src := r.Data.(string) src := r.Data.(string)
raw := make([]byte, len(src)*len(src)/base64.StdEncoding.DecodedLen(len(src))) raw := make([]byte, len(src)*len(src)/base64.StdEncoding.DecodedLen(len(src)))
base64.StdEncoding.Decode(raw, []byte(src)) base64.StdEncoding.Decode(raw, []byte(src))

@ -322,9 +322,9 @@ func TestIPMatcher_MatchIP_WithNetIP(t *testing.T) {
func TestWildcardToCIDR(t *testing.T) { func TestWildcardToCIDR(t *testing.T) {
tests := []struct { tests := []struct {
pattern string pattern string
cidr string cidr string
wantErr bool wantErr bool
}{ }{
{"192.168.1.*", "192.168.1.0/24", false}, {"192.168.1.*", "192.168.1.0/24", false},
{"192.168.*.*", "192.168.0.0/16", false}, {"192.168.*.*", "192.168.0.0/16", false},

@ -1,3 +1,4 @@
//go:build !race
// +build !race // +build !race
package util package util

@ -32,33 +32,33 @@ const (
// elements containing the data. // elements containing the data.
// //
// The name for the XML elements is taken from, in order of preference: // The name for the XML elements is taken from, in order of preference:
// - the tag on the XMLName field, if the data is a struct // - the tag on the XMLName field, if the data is a struct
// - the value of the XMLName field of type xml.Name // - the value of the XMLName field of type xml.Name
// - the tag of the struct field used to obtain the data // - the tag of the struct field used to obtain the data
// - the name of the struct field used to obtain the data // - the name of the struct field used to obtain the data
// - the name of the marshalled type // - the name of the marshalled type
// //
// The XML element for a struct contains marshalled elements for each of the // The XML element for a struct contains marshalled elements for each of the
// exported fields of the struct, with these exceptions: // exported fields of the struct, with these exceptions:
// - the XMLName field, described above, is omitted. // - the XMLName field, described above, is omitted.
// - a field with tag "-" is omitted. // - a field with tag "-" is omitted.
// - a field with tag "name,attr" becomes an attribute with // - a field with tag "name,attr" becomes an attribute with
// the given name in the XML element. // the given name in the XML element.
// - a field with tag ",attr" becomes an attribute with the // - a field with tag ",attr" becomes an attribute with the
// field name in the XML element. // field name in the XML element.
// - a field with tag ",chardata" is written as character data, // - a field with tag ",chardata" is written as character data,
// not as an XML element. // not as an XML element.
// - a field with tag ",innerxml" is written verbatim, not subject // - a field with tag ",innerxml" is written verbatim, not subject
// to the usual marshalling procedure. // to the usual marshalling procedure.
// - a field with tag ",comment" is written as an XML comment, not // - a field with tag ",comment" is written as an XML comment, not
// subject to the usual marshalling procedure. It must not contain // subject to the usual marshalling procedure. It must not contain
// the "--" string within it. // the "--" string within it.
// - a field with a tag including the "omitempty" option is omitted // - a field with a tag including the "omitempty" option is omitted
// if the field value is empty. The empty values are false, 0, any // if the field value is empty. The empty values are false, 0, any
// nil pointer or interface value, and any array, slice, map, or // nil pointer or interface value, and any array, slice, map, or
// string of length zero. // string of length zero.
// - an anonymous struct field is handled as if the fields of its // - an anonymous struct field is handled as if the fields of its
// value were part of the outer struct. // value were part of the outer struct.
// //
// If a field uses a tag "a>b>c", then the element c will be nested inside // If a field uses a tag "a>b>c", then the element c will be nested inside
// parent elements a and b. Fields that appear next to each other that name // parent elements a and b. Fields that appear next to each other that name

@ -35,57 +35,57 @@ import (
// In the rules, the tag of a field refers to the value associated with the // In the rules, the tag of a field refers to the value associated with the
// key 'xml' in the struct field's tag (see the example above). // key 'xml' in the struct field's tag (see the example above).
// //
// * If the struct has a field of type []byte or string with tag // - If the struct has a field of type []byte or string with tag
// ",innerxml", Unmarshal accumulates the raw XML nested inside the // ",innerxml", Unmarshal accumulates the raw XML nested inside the
// element in that field. The rest of the rules still apply. // element in that field. The rest of the rules still apply.
// //
// * If the struct has a field named XMLName of type xml.Name, // - If the struct has a field named XMLName of type xml.Name,
// Unmarshal records the element name in that field. // Unmarshal records the element name in that field.
// //
// * If the XMLName field has an associated tag of the form // - If the XMLName field has an associated tag of the form
// "name" or "namespace-URL name", the XML element must have // "name" or "namespace-URL name", the XML element must have
// the given name (and, optionally, name space) or else Unmarshal // the given name (and, optionally, name space) or else Unmarshal
// returns an error. // returns an error.
// //
// * If the XML element has an attribute whose name matches a // - If the XML element has an attribute whose name matches a
// struct field name with an associated tag containing ",attr" or // struct field name with an associated tag containing ",attr" or
// the explicit name in a struct field tag of the form "name,attr", // the explicit name in a struct field tag of the form "name,attr",
// Unmarshal records the attribute value in that field. // Unmarshal records the attribute value in that field.
// //
// * If the XML element contains character data, that data is // - If the XML element contains character data, that data is
// accumulated in the first struct field that has tag ",chardata". // accumulated in the first struct field that has tag ",chardata".
// The struct field may have type []byte or string. // The struct field may have type []byte or string.
// If there is no such field, the character data is discarded. // If there is no such field, the character data is discarded.
// //
// * If the XML element contains comments, they are accumulated in // - If the XML element contains comments, they are accumulated in
// the first struct field that has tag ",comment". The struct // the first struct field that has tag ",comment". The struct
// field may have type []byte or string. If there is no such // field may have type []byte or string. If there is no such
// field, the comments are discarded. // field, the comments are discarded.
// //
// * If the XML element contains a sub-element whose name matches // - If the XML element contains a sub-element whose name matches
// the prefix of a tag formatted as "a" or "a>b>c", unmarshal // the prefix of a tag formatted as "a" or "a>b>c", unmarshal
// will descend into the XML structure looking for elements with the // will descend into the XML structure looking for elements with the
// given names, and will map the innermost elements to that struct // given names, and will map the innermost elements to that struct
// field. A tag starting with ">" is equivalent to one starting // field. A tag starting with ">" is equivalent to one starting
// with the field name followed by ">". // with the field name followed by ">".
// //
// * If the XML element contains a sub-element whose name matches // - If the XML element contains a sub-element whose name matches
// a struct field's XMLName tag and the struct field has no // a struct field's XMLName tag and the struct field has no
// explicit name tag as per the previous rule, unmarshal maps // explicit name tag as per the previous rule, unmarshal maps
// the sub-element to that struct field. // the sub-element to that struct field.
// //
// * If the XML element contains a sub-element whose name matches a // - If the XML element contains a sub-element whose name matches a
// field without any mode flags (",attr", ",chardata", etc), Unmarshal // field without any mode flags (",attr", ",chardata", etc), Unmarshal
// maps the sub-element to that struct field. // maps the sub-element to that struct field.
// //
// * If the XML element contains a sub-element that hasn't matched any // - If the XML element contains a sub-element that hasn't matched any
// of the above rules and the struct has a field with tag ",any", // of the above rules and the struct has a field with tag ",any",
// unmarshal maps the sub-element to that struct field. // unmarshal maps the sub-element to that struct field.
// //
// * An anonymous struct field is handled as if the fields of its // - An anonymous struct field is handled as if the fields of its
// value were part of the outer struct. // value were part of the outer struct.
// //
// * A struct field with tag "-" is never unmarshalled into. // - A struct field with tag "-" is never unmarshalled into.
// //
// Unmarshal maps an XML element to a string or []byte by saving the // Unmarshal maps an XML element to a string or []byte by saving the
// concatenation of that element's character data in the string or // concatenation of that element's character data in the string or
@ -110,7 +110,6 @@ import (
// //
// Unmarshal maps an XML element to a pointer by setting the pointer // Unmarshal maps an XML element to a pointer by setting the pointer
// to a freshly allocated value and then mapping the element to that value. // to a freshly allocated value and then mapping the element to that value.
//
func Unmarshal(data []byte, v interface{}) error { func Unmarshal(data []byte, v interface{}) error {
return NewDecoder(bytes.NewReader(data)).Decode(v) return NewDecoder(bytes.NewReader(data)).Decode(v)
} }

@ -113,7 +113,7 @@ func (m *metadataDeadProps) DeadProps() (map[xml.Name]Property, error) {
} }
spaceLocal := strings.SplitN(strings.TrimPrefix(k, DeadPropsMetadataPrefix), SpaceNameSeparator, 2) spaceLocal := strings.SplitN(strings.TrimPrefix(k, DeadPropsMetadataPrefix), SpaceNameSeparator, 2)
name := xml.Name{spaceLocal[0], spaceLocal[1]} name := xml.Name{Space: spaceLocal[0], Local: spaceLocal[1]}
propsStore := &DeadPropsStore{} propsStore := &DeadPropsStore{}
if err := json.Unmarshal([]byte(v), propsStore); err != nil { if err := json.Unmarshal([]byte(v), propsStore); err != nil {
return nil, err return nil, err

@ -141,7 +141,7 @@ func (service *TestNodeDownloaderService) Test(c *gin.Context) (string, error) {
request.WithCorrelationID(), request.WithCorrelationID(),
request.WithSlaveMeta(service.Node.ID), request.WithSlaveMeta(service.Node.ID),
request.WithMasterMeta(settings.SiteBasic(c).ID, settings.SiteURL(setting.UseFirstSiteUrl(c)).String()), request.WithMasterMeta(settings.SiteBasic(c).ID, settings.SiteURL(setting.UseFirstSiteUrl(c)).String()),
request.WithCredential(auth.HMACAuth{[]byte(service.Node.SlaveKey)}, int64(settings.SlaveRequestSignTTL(c))), request.WithCredential(auth.HMACAuth{SecretKey: []byte(service.Node.SlaveKey)}, int64(settings.SlaveRequestSignTTL(c))),
request.WithEndpoint(service.Node.Server), request.WithEndpoint(service.Node.Server),
), service.Node.Settings) ), service.Node.Settings)
} }

Loading…
Cancel
Save