Skip to content
This repository was archived by the owner on Jun 12, 2024. It is now read-only.

Commit e8449b3

Browse files
authored
fix: inaccruate 401 & sql busy error (#679)
* fix inaccruate 401 error on SQL db error * init golangci-lint config * linter autofix * testify auto fixes * fix sqlite busy errors * fix naming * more linter errors * fix rest of linter issues
1 parent b918310 commit e8449b3

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

62 files changed

+392
-295
lines changed

Diff for: .vscode/settings.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
"editor.formatOnSave": false,
1717
"editor.defaultFormatter": "dbaeumer.vscode-eslint",
1818
"editor.codeActionsOnSave": {
19-
"source.fixAll.eslint": true
19+
"source.fixAll.eslint": "explicit"
2020
},
2121
"[typescript]": {
2222
"editor.defaultFormatter": "dbaeumer.vscode-eslint"

Diff for: Dockerfile

+1-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ FROM alpine:latest
3232

3333
ENV HBOX_MODE=production
3434
ENV HBOX_STORAGE_DATA=/data/
35-
ENV HBOX_STORAGE_SQLITE_URL=/data/homebox.db?_fk=1
35+
ENV HBOX_STORAGE_SQLITE_URL=/data/homebox.db?_pragma=busy_timeout=2000&_pragma=journal_mode=WAL&_fk=1
3636

3737
RUN apk --no-cache add ca-certificates
3838
RUN mkdir /app

Diff for: backend/.golangci.yml

+73
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
run:
2+
timeout: 10m
3+
skip-dirs:
4+
- internal/data/ent.*
5+
linters-settings:
6+
goconst:
7+
min-len: 5
8+
min-occurrences: 5
9+
exhaustive:
10+
default-signifies-exhaustive: true
11+
revive:
12+
ignore-generated-header: false
13+
severity: warning
14+
confidence: 3
15+
depguard:
16+
rules:
17+
main:
18+
deny:
19+
- pkg: io/util
20+
desc: |
21+
Deprecated: As of Go 1.16, the same functionality is now provided by
22+
package io or package os, and those implementations should be
23+
preferred in new code. See the specific function documentation for
24+
details.
25+
gocritic:
26+
enabled-checks:
27+
- ruleguard
28+
testifylint:
29+
enable-all: true
30+
tagalign:
31+
order:
32+
- json
33+
- schema
34+
- yaml
35+
- yml
36+
- toml
37+
- validate
38+
linters:
39+
disable-all: true
40+
enable:
41+
- asciicheck
42+
- bodyclose
43+
- depguard
44+
- dogsled
45+
- errcheck
46+
- errorlint
47+
- exhaustive
48+
- exportloopref
49+
- gochecknoinits
50+
- goconst
51+
- gocritic
52+
- gocyclo
53+
- goprintffuncname
54+
- gosimple
55+
- govet
56+
- ineffassign
57+
- misspell
58+
- nakedret
59+
- revive
60+
- staticcheck
61+
- stylecheck
62+
- tagalign
63+
- testifylint
64+
- typecheck
65+
- typecheck
66+
- unconvert
67+
- unused
68+
- whitespace
69+
- zerologlint
70+
- sqlclosecheck
71+
issues:
72+
exclude-use-default: false
73+
fix: true

Diff for: backend/app/api/demo.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ func (a *app) SetupDemo() {
1515
,Office,IOT;Home Assistant; Z-Wave,1,Zooz 110v Power Switch,"Zooz Z-Wave Plus Power Switch ZEN15 for 110V AC Units, Sump Pumps, Humidifiers, and More",,,ZEN15,Zooz,,Amazon,39.95,10/13/2021,,,,,,,
1616
,Downstairs,IOT;Home Assistant; Z-Wave,1,Ecolink Z-Wave PIR Motion Sensor,"Ecolink Z-Wave PIR Motion Detector Pet Immune, White (PIRZWAVE2.5-ECO)",,,PIRZWAVE2.5-ECO,Ecolink,,Amazon,35.58,10/21/2020,,,,,,,
1717
,Entry,IOT;Home Assistant; Z-Wave,1,Yale Security Touchscreen Deadbolt,"Yale Security YRD226-ZW2-619 YRD226ZW2619 Touchscreen Deadbolt, Satin Nickel",,,YRD226ZW2619,Yale,,Amazon,120.39,10/14/2020,,,,,,,
18-
,Kitchen,IOT;Home Assistant; Z-Wave,1,Smart Rocker Light Dimmer,"UltraPro Z-Wave Smart Rocker Light Dimmer with QuickFit and SimpleWire, 3-Way Ready, Compatible with Alexa, Google Assistant, ZWave Hub Required, Repeater/Range Extender, White Paddle Only, 39351",,,39351,Honeywell,,Amazon,65.98,09/30/0202,,,,,,,
18+
,Kitchen,IOT;Home Assistant; Z-Wave,1,Smart Rocker Light Dimmer,"UltraPro Z-Wave Smart Rocker Light Dimmer with QuickFit and SimpleWire, 3-Way Ready, Compatible with Alexa, Google Assistant, ZWave Hub Required, Repeater/Range Extender, White Paddle Only, 39351",,,39351,Honeywell,,Amazon,65.98,09/30/0202,,,,,,,
1919
`
2020

2121
registration := services.UserRegistration{

Diff for: backend/app/api/handlers/debughandlers/debug.go

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// Package debughandlers provides handlers for debugging.
12
package debughandlers
23

34
import (

Diff for: backend/app/api/handlers/v1/controller.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// Package v1 provides the API handlers for version 1 of the API.
12
package v1
23

34
import (
@@ -74,7 +75,7 @@ type (
7475
BuildTime string `json:"buildTime"`
7576
}
7677

77-
ApiSummary struct {
78+
APISummary struct {
7879
Healthy bool `json:"health"`
7980
Versions []string `json:"versions"`
8081
Title string `json:"title"`
@@ -85,7 +86,7 @@ type (
8586
}
8687
)
8788

88-
func BaseUrlFunc(prefix string) func(s string) string {
89+
func BaseURLFunc(prefix string) func(s string) string {
8990
return func(s string) string {
9091
return prefix + "/v1" + s
9192
}
@@ -115,7 +116,7 @@ func NewControllerV1(svc *services.AllServices, repos *repo.AllRepos, bus *event
115116
// @Router /v1/status [GET]
116117
func (ctrl *V1Controller) HandleBase(ready ReadyFunc, build Build) errchain.HandlerFunc {
117118
return func(w http.ResponseWriter, r *http.Request) error {
118-
return server.JSON(w, http.StatusOK, ApiSummary{
119+
return server.JSON(w, http.StatusOK, APISummary{
119120
Healthy: ready(),
120121
Title: "Homebox",
121122
Message: "Track, Manage, and Organize your Things",

Diff for: backend/app/api/handlers/v1/v1_ctrl_assets.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@ import (
2727
func (ctrl *V1Controller) HandleAssetGet() errchain.HandlerFunc {
2828
return func(w http.ResponseWriter, r *http.Request) error {
2929
ctx := services.NewContext(r.Context())
30-
assetIdParam := chi.URLParam(r, "id")
31-
assetIdParam = strings.ReplaceAll(assetIdParam, "-", "") // Remove dashes
30+
assetIDParam := chi.URLParam(r, "id")
31+
assetIDParam = strings.ReplaceAll(assetIDParam, "-", "") // Remove dashes
3232
// Convert the asset ID to an int64
33-
assetId, err := strconv.ParseInt(assetIdParam, 10, 64)
33+
assetID, err := strconv.ParseInt(assetIDParam, 10, 64)
3434
if err != nil {
3535
return err
3636
}
@@ -52,7 +52,7 @@ func (ctrl *V1Controller) HandleAssetGet() errchain.HandlerFunc {
5252
}
5353
}
5454

55-
items, err := ctrl.repo.Items.QueryByAssetID(r.Context(), ctx.GID, repo.AssetID(assetId), int(page), int(pageSize))
55+
items, err := ctrl.repo.Items.QueryByAssetID(r.Context(), ctx.GID, repo.AssetID(assetID), int(page), int(pageSize))
5656
if err != nil {
5757
log.Err(err).Msg("failed to get item")
5858
return validate.NewRequestError(err, http.StatusInternalServerError)

Diff for: backend/app/api/handlers/v1/v1_ctrl_auth.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ func (ctrl *V1Controller) HandleAuthLogout() errchain.HandlerFunc {
153153
}
154154
}
155155

156-
// HandleAuthLogout godoc
156+
// HandleAuthRefresh godoc
157157
//
158158
// @Summary User Token Refresh
159159
// @Description handleAuthRefresh returns a handler that will issue a new token from an existing token.

Diff for: backend/app/api/handlers/v1/v1_ctrl_group.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import (
1212

1313
type (
1414
GroupInvitationCreate struct {
15-
Uses int `json:"uses" validate:"required,min=1,max=100"`
15+
Uses int `json:"uses" validate:"required,min=1,max=100"`
1616
ExpiresAt time.Time `json:"expiresAt"`
1717
}
1818

Diff for: backend/app/api/handlers/v1/v1_ctrl_items.go

-1
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,6 @@ func (ctrl *V1Controller) HandleGetAllCustomFieldValues() errchain.HandlerFunc {
233233
}
234234

235235
return adapters.Query(fn, http.StatusOK)
236-
237236
}
238237

239238
// HandleItemsImport godocs

Diff for: backend/app/api/handlers/v1/v1_ctrl_items_attachments.go

-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,6 @@ func (ctrl *V1Controller) HandleItemAttachmentCreate() errchain.HandlerFunc {
3939
if err != nil {
4040
log.Err(err).Msg("failed to parse multipart form")
4141
return validate.NewRequestError(errors.New("failed to parse multipart form"), http.StatusBadRequest)
42-
4342
}
4443

4544
errs := validate.NewFieldErrors()

Diff for: backend/app/api/handlers/v1/v1_ctrl_locations.go

+6-6
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010
"github.com/hay-kot/httpkit/errchain"
1111
)
1212

13-
// HandleLocationTreeQuery
13+
// HandleLocationTreeQuery godoc
1414
//
1515
// @Summary Get Locations Tree
1616
// @Tags Locations
@@ -28,7 +28,7 @@ func (ctrl *V1Controller) HandleLocationTreeQuery() errchain.HandlerFunc {
2828
return adapters.Query(fn, http.StatusOK)
2929
}
3030

31-
// HandleLocationGetAll
31+
// HandleLocationGetAll godoc
3232
//
3333
// @Summary Get All Locations
3434
// @Tags Locations
@@ -46,7 +46,7 @@ func (ctrl *V1Controller) HandleLocationGetAll() errchain.HandlerFunc {
4646
return adapters.Query(fn, http.StatusOK)
4747
}
4848

49-
// HandleLocationCreate
49+
// HandleLocationCreate godoc
5050
//
5151
// @Summary Create Location
5252
// @Tags Locations
@@ -64,7 +64,7 @@ func (ctrl *V1Controller) HandleLocationCreate() errchain.HandlerFunc {
6464
return adapters.Action(fn, http.StatusCreated)
6565
}
6666

67-
// HandleLocationDelete
67+
// HandleLocationDelete godoc
6868
//
6969
// @Summary Delete Location
7070
// @Tags Locations
@@ -83,7 +83,7 @@ func (ctrl *V1Controller) HandleLocationDelete() errchain.HandlerFunc {
8383
return adapters.CommandID("id", fn, http.StatusNoContent)
8484
}
8585

86-
// HandleLocationGet
86+
// HandleLocationGet godoc
8787
//
8888
// @Summary Get Location
8989
// @Tags Locations
@@ -101,7 +101,7 @@ func (ctrl *V1Controller) HandleLocationGet() errchain.HandlerFunc {
101101
return adapters.CommandID("id", fn, http.StatusOK)
102102
}
103103

104-
// HandleLocationUpdate
104+
// HandleLocationUpdate godoc
105105
//
106106
// @Summary Update Location
107107
// @Tags Locations

Diff for: backend/app/api/handlers/v1/v1_ctrl_maint_entry.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import (
1010
"github.com/hay-kot/httpkit/errchain"
1111
)
1212

13-
// HandleMaintenanceGetLog godoc
13+
// HandleMaintenanceLogGet godoc
1414
//
1515
// @Summary Get Maintenance Log
1616
// @Tags Maintenance

Diff for: backend/app/api/handlers/v1/v1_ctrl_statistics.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import (
1212
"github.com/hay-kot/httpkit/server"
1313
)
1414

15-
// HandleGroupGet godoc
15+
// HandleGroupStatisticsLocations godoc
1616
//
1717
// @Summary Get Location Statistics
1818
// @Tags Statistics

Diff for: backend/app/api/main.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -78,12 +78,12 @@ func run(cfg *config.Config) error {
7878
log.Fatal().Err(err).Msg("failed to create data directory")
7979
}
8080

81-
c, err := ent.Open("sqlite3", cfg.Storage.SqliteUrl)
81+
c, err := ent.Open("sqlite3", cfg.Storage.SqliteURL)
8282
if err != nil {
8383
log.Fatal().
8484
Err(err).
8585
Str("driver", "sqlite").
86-
Str("url", cfg.Storage.SqliteUrl).
86+
Str("url", cfg.Storage.SqliteURL).
8787
Msg("failed opening connection to sqlite")
8888
}
8989
defer func(c *ent.Client) {
@@ -116,7 +116,7 @@ func run(cfg *config.Config) error {
116116
log.Fatal().
117117
Err(err).
118118
Str("driver", "sqlite").
119-
Str("url", cfg.Storage.SqliteUrl).
119+
Str("url", cfg.Storage.SqliteURL).
120120
Msg("failed creating schema resources")
121121
}
122122

Diff for: backend/app/api/middleware.go

+7-2
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99

1010
v1 "github.com/hay-kot/homebox/backend/app/api/handlers/v1"
1111
"github.com/hay-kot/homebox/backend/internal/core/services"
12+
"github.com/hay-kot/homebox/backend/internal/data/ent"
1213
"github.com/hay-kot/homebox/backend/internal/sys/validate"
1314
"github.com/hay-kot/httpkit/errchain"
1415
)
@@ -130,7 +131,7 @@ func (a *app) mwAuthToken(next errchain.Handler) errchain.Handler {
130131
}
131132

132133
if requestToken == "" {
133-
return validate.NewRequestError(errors.New("Authorization header or query is required"), http.StatusUnauthorized)
134+
return validate.NewRequestError(errors.New("authorization header or query is required"), http.StatusUnauthorized)
134135
}
135136

136137
requestToken = strings.TrimPrefix(requestToken, "Bearer ")
@@ -140,7 +141,11 @@ func (a *app) mwAuthToken(next errchain.Handler) errchain.Handler {
140141
usr, err := a.services.User.GetSelf(r.Context(), requestToken)
141142
// Check the database for the token
142143
if err != nil {
143-
return validate.NewRequestError(errors.New("valid authorization header is required"), http.StatusUnauthorized)
144+
if ent.IsNotFound(err) {
145+
return validate.NewRequestError(errors.New("valid authorization token is required"), http.StatusUnauthorized)
146+
}
147+
148+
return err
144149
}
145150

146151
r = r.WithContext(services.SetUserCtx(r.Context(), &usr, requestToken))

Diff for: backend/app/api/providers/doc.go

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
// Package providers provides a authentication abstraction for the backend.
2+
package providers

Diff for: backend/app/api/routes.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ func (a *app) mountRoutes(r *chi.Mux, chain *errchain.ErrChain, repos *repo.AllR
4747
// =========================================================================
4848
// API Version 1
4949

50-
v1Base := v1.BaseUrlFunc(prefix)
50+
v1Base := v1.BaseURLFunc(prefix)
5151

5252
v1Ctrl := v1.NewControllerV1(
5353
a.services,
@@ -183,7 +183,7 @@ func notFoundHandler() errchain.HandlerFunc {
183183
if err != nil {
184184
return err
185185
}
186-
defer f.Close()
186+
defer func() { _ = f.Close() }()
187187

188188
stat, _ := f.Stat()
189189
if stat.IsDir() {

Diff for: backend/internal/core/services/all.go

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// Package services provides the core business logic for the application.
12
package services
23

34
import (

Diff for: backend/internal/core/services/main_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ func TestMain(m *testing.M) {
6262
tClient = client
6363
tRepos = repo.New(tClient, tbus, os.TempDir()+"/homebox")
6464
tSvc = New(tRepos)
65-
defer client.Close()
65+
defer func() { _ = client.Close() }()
6666

6767
bootstrap()
6868
tCtx = Context{

Diff for: backend/internal/core/services/reporting/eventbus/eventbus.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// / Package eventbus provides an interface for event bus.
1+
// Package eventbus provides an interface for event bus.
22
package eventbus
33

44
import (

Diff for: backend/internal/core/services/reporting/import.go

+1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// Package reporting provides a way to import CSV files into the database.
12
package reporting
23

34
import (

Diff for: backend/internal/core/services/reporting/io_sheet.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@ func (s *IOSheet) Read(data io.Reader) error {
152152
return nil
153153
}
154154

155-
// Write writes the sheet to a writer.
155+
// ReadItems writes the sheet to a writer.
156156
func (s *IOSheet) ReadItems(ctx context.Context, items []repo.ItemOut, GID uuid.UUID, repos *repo.AllRepos) error {
157157
s.Rows = make([]ExportTSVRow, len(items))
158158

@@ -162,9 +162,9 @@ func (s *IOSheet) ReadItems(ctx context.Context, items []repo.ItemOut, GID uuid.
162162
item := items[i]
163163

164164
// TODO: Support fetching nested locations
165-
locId := item.Location.ID
165+
locID := item.Location.ID
166166

167-
locPaths, err := repos.Locations.PathForLoc(context.Background(), GID, locId)
167+
locPaths, err := repos.Locations.PathForLoc(context.Background(), GID, locID)
168168
if err != nil {
169169
log.Error().Err(err).Msg("could not get location path")
170170
return err
@@ -252,7 +252,7 @@ func (s *IOSheet) ReadItems(ctx context.Context, items []repo.ItemOut, GID uuid.
252252
return nil
253253
}
254254

255-
// Writes the current sheet to a writer in TSV format.
255+
// TSV writes the current sheet to a writer in TSV format.
256256
func (s *IOSheet) TSV() ([][]string, error) {
257257
memcsv := make([][]string, len(s.Rows)+1)
258258

0 commit comments

Comments
 (0)