Skip to content

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

Return barcode results when one provider fails (#1727)

Aditya Raj Singh93923268f92d
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 cfdd2072..564c925a 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_product_search.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_product_search.go
@@ -10,6 +10,7 @@ import (
"net/http"
"net/url"
"strings"
+ "sync"
"time"
"github.com/hay-kot/httpkit/errchain"
@@ -477,35 +478,58 @@ func (ctrl *V1Controller) HandleProductSearchFromBarcode(conf config.BarcodeAPIC
}
log.Info().Msg("Processing barcode lookup request on: " + q.EAN)
-
- // Sized for one hit from each configured upstream: upcitemdb, barcodespider,
- // and the three Open*Facts sources.
- products := make([]repo.BarcodeProduct, 0, 2+len(openFactsSources))
+ // A provider timeout must not consume the server's write deadline and
+ // prevent already available results from reaching the client.
+ allowSlowResponse(w, r)
// www.ean-search.org/: not free
// Example code: dewalt 5035048748428
-
- ps, err := lookupUPCItemDB(q.EAN)
- if err != nil {
- log.Error().Msg("Can not retrieve product from upcitemdb.com: " + err.Error())
+ type lookup struct {
+ name string
+ run func() ([]repo.BarcodeProduct, error)
}
- products = append(products, ps...)
+ lookups := []lookup{{
+ name: "upcitemdb.com",
+ run: func() ([]repo.BarcodeProduct, error) { return lookupUPCItemDB(q.EAN) },
+ }}
if conf.TokenBarcodespider != "" {
- ps2, err := lookupBarcodespider(conf.TokenBarcodespider, q.EAN)
- if err != nil {
- log.Error().Msg("Can not retrieve product from barcodespider.com: " + err.Error())
- }
- products = append(products, ps2...)
+ lookups = append(lookups, lookup{
+ name: "barcodespider.com",
+ run: func() ([]repo.BarcodeProduct, error) {
+ return lookupBarcodespider(conf.TokenBarcodespider, q.EAN)
+ },
+ })
}
for _, source := range openFactsSources {
- ps3, err := lookupOpenFacts(conf.OpenFoodFactsContact, source, q.EAN)
- if err != nil {
- log.Error().Msg("Can not retrieve product from " + source.Name + ": " + err.Error())
- }
- products = append(products, ps3...)
+ lookups = append(lookups, lookup{
+ name: source.Name,
+ run: func() ([]repo.BarcodeProduct, error) {
+ return lookupOpenFacts(conf.OpenFoodFactsContact, source, q.EAN)
+ },
+ })
+ }
+
+ results := make([][]repo.BarcodeProduct, len(lookups))
+ var wg sync.WaitGroup
+ for i, lookup := range lookups {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ ps, err := lookup.run()
+ if err != nil {
+ log.Error().Msg("Can not retrieve product from " + lookup.name + ": " + err.Error())
+ }
+ results[i] = ps
+ }()
+ }
+ wg.Wait()
+
+ products := make([]repo.BarcodeProduct, 0, len(results))
+ for _, result := range results {
+ products = append(products, result...)
}
// Retrieve images if possible
diff --git a/backend/app/api/handlers/v1/v1_ctrl_product_search_test.go b/backend/app/api/handlers/v1/v1_ctrl_product_search_test.go
index d5c4263d..dc334c42 100644
--- a/backend/app/api/handlers/v1/v1_ctrl_product_search_test.go
+++ b/backend/app/api/handlers/v1/v1_ctrl_product_search_test.go
@@ -2,9 +2,104 @@ package v1
import (
"encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
"testing"
+ "time"
+
+ "github.com/sysadminsmedia/homebox/backend/internal/data/repo"
+ "github.com/sysadminsmedia/homebox/backend/internal/sys/config"
)
+type roundTripFunc func(*http.Request) (*http.Response, error)
+
+func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) {
+ return f(r)
+}
+
+func TestBarcodeSearchReturnsAvailableProviderResults(t *testing.T) {
+ originalClient := barcodeHTTPClient
+ started := make(chan string, 1+len(openFactsSources))
+ release := make(chan struct{})
+ barcodeHTTPClient = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
+ started <- r.URL.Host
+ <-release
+
+ status := http.StatusNotFound
+ body := ""
+ if r.URL.Host == "api.upcitemdb.com" {
+ status = http.StatusOK
+ body = `{"code":"OK","items":[{"ean":"1234567890123","title":"Available product"}]}`
+ }
+ return &http.Response{
+ StatusCode: status,
+ Header: make(http.Header),
+ Body: io.NopCloser(strings.NewReader(body)),
+ Request: r,
+ }, nil
+ })}
+ t.Cleanup(func() { barcodeHTTPClient = originalClient })
+
+ handler := (&V1Controller{}).HandleProductSearchFromBarcode(config.BarcodeAPIConf{})
+ server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if err := handler(w, r); err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ }
+ }))
+ server.Config.WriteTimeout = 50 * time.Millisecond
+ server.Start()
+ t.Cleanup(server.Close)
+
+ type response struct {
+ status int
+ body []byte
+ err error
+ }
+ responseCh := make(chan response, 1)
+ go func() {
+ resp, err := server.Client().Get(server.URL + "/?productEAN=1234567890123")
+ if err != nil {
+ responseCh <- response{err: err}
+ return
+ }
+ defer func() { _ = resp.Body.Close() }()
+ body, err := io.ReadAll(resp.Body)
+ responseCh <- response{status: resp.StatusCode, body: body, err: err}
+ }()
+
+ timer := time.NewTimer(time.Second)
+ defer timer.Stop()
+ for count := 0; count < cap(started); count++ {
+ select {
+ case <-started:
+ case <-timer.C:
+ close(release)
+ <-responseCh
+ t.Fatalf("only %d of %d barcode providers started before the first response", count, cap(started))
+ }
+ }
+
+ time.Sleep(75 * time.Millisecond)
+ close(release)
+ result := <-responseCh
+ if result.err != nil {
+ t.Fatalf("barcode search failed after a provider delay: %v", result.err)
+ }
+ if result.status != http.StatusOK {
+ t.Fatalf("expected status 200, got %d", result.status)
+ }
+
+ var products []repo.BarcodeProduct
+ if err := json.Unmarshal(result.body, &products); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if len(products) != 1 || products[0].Item.Name != "Available product" {
+ t.Fatalf("unexpected products: %+v", products)
+ }
+}
+
func TestUPCITEMDBResponseUnmarshalNumericListPrice(t *testing.T) {
body := []byte(`{
"code": "OK",