Skip to content

A continuation of HomeBox the inventory and organization system built for the Home User

perf: minor performance improvements, test fix

Matthew Kilgore8222a88de7b4
diff --git a/backend/app/api/handlers/v1/controller.go b/backend/app/api/handlers/v1/controller.go
index a0a22b44..68f9b935 100644
--- a/backend/app/api/handlers/v1/controller.go
+++ b/backend/app/api/handlers/v1/controller.go
@@ -235,6 +235,14 @@ func (ctrl *V1Controller) HandleCacheWS() errchain.HandlerFunc {
})
factory := func(e string) func(data any) {
+ // The payload depends only on the event name, so marshal it once at
+ // subscription time instead of on every dispatch.
+ jsonBytes, err := json.Marshal(&eventMsg{Event: e})
+ if err != nil {
+ log.Log().Msgf("error marshaling event %q: %v", e, err)
+ return func(any) {}
+ }
+
return func(data any) {
eventData, ok := data.(eventbus.GroupMutationEvent)
if !ok {
@@ -242,14 +250,6 @@ func (ctrl *V1Controller) HandleCacheWS() errchain.HandlerFunc {
return
}
- msg := &eventMsg{Event: e}
-
- jsonBytes, err := json.Marshal(msg)
- if err != nil {
- log.Log().Msgf("error marshling event data %v: %v", data, err)
- return
- }
-
_ = m.BroadcastFilter(jsonBytes, func(s *melody.Session) bool {
groupIDStr, ok := s.Get("gid")
if !ok {
@@ -272,18 +272,18 @@ func (ctrl *V1Controller) HandleCacheWS() errchain.HandlerFunc {
go func() {
const interval = 10 * time.Second
+ // The ping frame never changes, so build it once rather than on every tick.
+ pingBytes, err := json.Marshal(&eventMsg{Event: "ping"})
+ if err != nil {
+ log.Log().Msgf("error marshaling ping: %v", err)
+ return
+ }
+
ping := time.NewTicker(interval)
defer ping.Stop()
for range ping.C {
- msg := &eventMsg{Event: "ping"}
-
- pingBytes, err := json.Marshal(msg)
- if err != nil {
- log.Log().Msgf("error marshaling ping: %v", err)
- } else {
- _ = m.Broadcast(pingBytes)
- }
+ _ = m.Broadcast(pingBytes)
}
}()
diff --git a/backend/app/api/handlers/v1/v1_ctrl_product_search.go b/backend/app/api/handlers/v1/v1_ctrl_product_search.go
index 5d86d20a..cfdd2072 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_product_search.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_product_search.go
@@ -23,8 +23,22 @@ import (
const (
barcodeHTTPTimeoutSec = 10
schemeHTTPS = "https"
+
+ // barcodeMaxResponseBytes caps how much of an upstream response is decoded so a
+ // misbehaving third-party API cannot drive unbounded allocation.
+ barcodeMaxResponseBytes = 4 << 20 // 4 MiB
)
+// barcodeHTTPClient is shared by every barcode lookup so outbound requests reuse a
+// single connection pool instead of allocating a client per call.
+var barcodeHTTPClient = &http.Client{Timeout: barcodeHTTPTimeoutSec * time.Second}
+
+// decodeBarcodeResponse streams the response body into v. Decoding directly off the
+// body avoids materializing the whole payload before parsing it.
+func decodeBarcodeResponse(body io.Reader, v any) error {
+ return json.NewDecoder(io.LimitReader(body, barcodeMaxResponseBytes)).Decode(v)
+}
+
// flexibleString is a string that can be unmarshaled from either a JSON
// string or a JSON number. upcitemdb.com sometimes returns price fields
// (e.g. list_price, shipping) as numbers rather than strings, which would
@@ -172,32 +186,26 @@ type BARCODESPIDER_COMResponse struct {
}
func lookupUPCItemDB(iEan string) ([]repo.BarcodeProduct, error) {
- client := &http.Client{Timeout: barcodeHTTPTimeoutSec * time.Second}
- resp, err := client.Get("https://api.upcitemdb.com/prod/trial/lookup?upc=" + url.QueryEscape(iEan))
+ resp, err := barcodeHTTPClient.Get("https://api.upcitemdb.com/prod/trial/lookup?upc=" + url.QueryEscape(iEan))
if err != nil {
return nil, err
}
defer func() {
- err = errors.Join(err, resp.Body.Close())
+ _ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API returned status code: %d", resp.StatusCode)
}
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, err
- }
-
var result UPCITEMDBResponse
- if err := json.Unmarshal(body, &result); err != nil {
+ if err := decodeBarcodeResponse(resp.Body, &result); err != nil {
log.Error().Msg("Can not unmarshal JSON from upcitemdb.com")
return nil, err
}
- var res []repo.BarcodeProduct
+ res := make([]repo.BarcodeProduct, 0, len(result.Items))
for _, it := range result.Items {
var p repo.BarcodeProduct
@@ -233,28 +241,21 @@ func lookupBarcodespider(tokenAPI string, iEan string) ([]repo.BarcodeProduct, e
req.Header.Add("token", tokenAPI)
- client := &http.Client{Timeout: barcodeHTTPTimeoutSec * time.Second}
-
- resp, err := client.Do(req)
+ resp, err := barcodeHTTPClient.Do(req)
if err != nil {
return nil, err
}
defer func() {
- err = errors.Join(err, resp.Body.Close())
+ _ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("barcodespider API returned status code: %d", resp.StatusCode)
}
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, err
- }
-
var result BARCODESPIDER_COMResponse
- if err := json.Unmarshal(body, &result); err != nil {
+ if err := decodeBarcodeResponse(resp.Body, &result); err != nil {
log.Error().Msg("Can not unmarshal JSON from barcodespider.com")
return nil, err
}
@@ -291,15 +292,16 @@ func firstNonEmpty(values ...string) string {
return ""
}
+var openFactsAllowedImageDomains = []string{
+ "openfoodfacts.org",
+ "openbeautyfacts.org",
+ "openproductsfacts.org",
+}
+
func isAllowedOpenFactsImageHost(host string) bool {
host = strings.ToLower(strings.TrimSuffix(strings.TrimSpace(host), "."))
- allowedDomains := []string{
- "openfoodfacts.org",
- "openbeautyfacts.org",
- "openproductsfacts.org",
- }
- for _, domain := range allowedDomains {
+ for _, domain := range openFactsAllowedImageDomains {
if host == domain || strings.HasSuffix(host, "."+domain) {
return true
}
@@ -346,8 +348,9 @@ func buildOpenFactsBarcodeProduct(sourceName string, iEan string, product openFa
p.Item.Name = name
p.Manufacturer = product.Brands
- var descriptionParts []string
- for _, value := range []string{product.GenericName, product.Categories, product.Quantity} {
+ descriptionSources := [...]string{product.GenericName, product.Categories, product.Quantity}
+ descriptionParts := make([]string, 0, len(descriptionSources))
+ for _, value := range descriptionSources {
value = strings.TrimSpace(value)
if value != "" && value != name {
descriptionParts = append(descriptionParts, value)
@@ -361,7 +364,6 @@ func buildOpenFactsBarcodeProduct(sourceName string, iEan string, product openFa
}
func lookupOpenFacts(contact string, source openFactsSource, iEan string) ([]repo.BarcodeProduct, error) {
- client := &http.Client{Timeout: barcodeHTTPTimeoutSec * time.Second}
req, err := http.NewRequest(
"GET", strings.TrimRight(source.BaseURL, "/")+"/api/v2/product/"+url.PathEscape(iEan)+".json", nil)
if err != nil {
@@ -374,13 +376,13 @@ func lookupOpenFacts(contact string, source openFactsSource, iEan string) ([]rep
}
req.Header.Set("User-Agent", userAgent)
- resp, err := client.Do(req)
+ resp, err := barcodeHTTPClient.Do(req)
if err != nil {
return nil, err
}
defer func() {
- err = errors.Join(err, resp.Body.Close())
+ _ = resp.Body.Close()
}()
if resp.StatusCode == http.StatusNotFound {
@@ -390,13 +392,8 @@ func lookupOpenFacts(contact string, source openFactsSource, iEan string) ([]rep
return nil, fmt.Errorf("%s API returned status code: %d", source.Name, resp.StatusCode)
}
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, err
- }
-
var result OpenFactsResponse
- if err := json.Unmarshal(body, &result); err != nil {
+ if err := decodeBarcodeResponse(resp.Body, &result); err != nil {
log.Error().Msg("Can not unmarshal " + source.Name + " JSON")
return nil, err
}
@@ -415,8 +412,7 @@ func lookupOpenFacts(contact string, source openFactsSource, iEan string) ([]rep
// fetchImageBase64 fetches an image from the given HTTPS URL and returns it as a base64-encoded data URI.
func fetchImageBase64(imageURL string) (string, error) {
- client := &http.Client{Timeout: barcodeHTTPTimeoutSec * time.Second}
- res, err := client.Get(imageURL)
+ res, err := barcodeHTTPClient.Get(imageURL)
if err != nil {
return "", err
}
@@ -434,23 +430,29 @@ func fetchImageBase64(imageURL string) (string, error) {
}
limitedReader := io.LimitReader(res.Body, 8*1024*1024)
- bytes, err := io.ReadAll(limitedReader)
+ raw, err := io.ReadAll(limitedReader)
if err != nil {
return "", err
}
- mimeType := http.DetectContentType(bytes)
- var base64Encoding string
+ mimeType := http.DetectContentType(raw)
+ var prefix string
switch mimeType {
case "image/jpeg":
- base64Encoding = "data:image/jpeg;base64,"
+ prefix = "data:image/jpeg;base64,"
case "image/png":
- base64Encoding = "data:image/png;base64,"
+ prefix = "data:image/png;base64,"
default:
return "", fmt.Errorf("unsupported image type: %s", mimeType)
}
- return base64Encoding + base64.StdEncoding.EncodeToString(bytes), nil
+ // Encode straight into a single buffer sized for prefix+payload so the data URI
+ // is built without an intermediate base64 string and a second concat.
+ out := make([]byte, len(prefix)+base64.StdEncoding.EncodedLen(len(raw)))
+ copy(out, prefix)
+ base64.StdEncoding.Encode(out[len(prefix):], raw)
+
+ return string(out), nil
}
// HandleProductSearchFromBarcode godoc
@@ -476,7 +478,9 @@ func (ctrl *V1Controller) HandleProductSearchFromBarcode(conf config.BarcodeAPIC
log.Info().Msg("Processing barcode lookup request on: " + q.EAN)
- var products []repo.BarcodeProduct
+ // Sized for one hit from each configured upstream: upcitemdb, barcodespider,
+ // and the three Open*Facts sources.
+ products := make([]repo.BarcodeProduct, 0, 2+len(openFactsSources))
// www.ean-search.org/: not free
diff --git a/backend/internal/core/services/main_test.go b/backend/internal/core/services/main_test.go
index cc15811b..3d813f2c 100644
--- a/backend/internal/core/services/main_test.go
+++ b/backend/internal/core/services/main_test.go
@@ -15,6 +15,7 @@ import (
"github.com/sysadminsmedia/homebox/backend/internal/data/repo"
_ "github.com/sysadminsmedia/homebox/backend/pkgs/cgofreesqlite"
"github.com/sysadminsmedia/homebox/backend/pkgs/faker"
+ "github.com/sysadminsmedia/homebox/backend/pkgs/hasher"
)
var (
@@ -53,6 +54,10 @@ func bootstrap() {
}
func MainNoExit(m *testing.M) int {
+ // API key hashing is peppered and panics if the pepper was never configured
+ // (see hasher.HashAPIKey); the app sets it at startup, so tests must too.
+ hasher.SetAPIKeyPepper([]byte("test-api-key-pepper"))
+
client, err := ent.Open("sqlite3", "file:ent?mode=memory&cache=shared&_fk=1&_time_format=sqlite")
if err != nil {
log.Fatalf("failed opening connection to sqlite: %v", err)
diff --git a/backend/internal/core/services/service_user_api_key_expiry_test.go b/backend/internal/core/services/service_user_api_key_expiry_test.go
index 23671c7f..10dd25e3 100644
--- a/backend/internal/core/services/service_user_api_key_expiry_test.go
+++ b/backend/internal/core/services/service_user_api_key_expiry_test.go
@@ -11,12 +11,6 @@ import (
"github.com/sysadminsmedia/homebox/backend/pkgs/hasher"
)
-// API key hashing is peppered and panics if the pepper was never configured
-// (see hasher.HashAPIKey); the app sets it at startup, so tests must too.
-func init() {
- hasher.SetAPIKeyPepper([]byte("test-api-key-pepper"))
-}
-
// TestCreateAPIKey_DefaultsToBoundedLifetime pins the default API key TTL. A
// password change revokes sessions but intentionally leaves API keys alone, so
// a key created without an explicit expiry must not live forever — otherwise a