refactor
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"git.k6n.net/mats/go-redis-inventory/pkg/inventory"
|
||||
)
|
||||
|
||||
// batchItem is one stock set in a batch request. LocationID is optional; an
|
||||
// empty value defaults to the service's country location (the same location the
|
||||
// catalog-feed listener writes to).
|
||||
type batchItem struct {
|
||||
SKU string `json:"sku"`
|
||||
LocationID string `json:"locationId,omitempty"`
|
||||
Quantity int64 `json:"quantity"`
|
||||
}
|
||||
|
||||
// batchResult mirrors one input item with the location actually written and an
|
||||
// optional per-item error (empty on success).
|
||||
type batchResult struct {
|
||||
SKU string `json:"sku"`
|
||||
LocationID string `json:"locationId"`
|
||||
Quantity int64 `json:"quantity"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// batchInventoryHandler SETS stock to absolute values for many SKUs in one
|
||||
// pipelined call — for re-seeding/import and for testing the inventory + reserve
|
||||
// paths directly. Same write as the catalog-feed listener (UpdateInventory +
|
||||
// level crossing), so a value set here is authoritative until the next
|
||||
// catalog.item_changed for that SKU overwrites it (catalog is the source of
|
||||
// truth). Body is a JSON array of {sku, locationId?, quantity}.
|
||||
func (srv *Server) batchInventoryHandler(w http.ResponseWriter, r *http.Request) {
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 16<<20)) // 16 MiB
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var items []batchItem
|
||||
if err := json.Unmarshal(body, &items); err != nil {
|
||||
http.Error(w, "body must be a JSON array of {sku, locationId?, quantity}: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if len(items) == 0 {
|
||||
http.Error(w, "empty batch", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
results := make([]batchResult, len(items))
|
||||
pipe := srv.rdb.Pipeline()
|
||||
for i, it := range items {
|
||||
loc := it.LocationID
|
||||
if loc == "" {
|
||||
loc = country
|
||||
}
|
||||
results[i] = batchResult{SKU: it.SKU, LocationID: loc, Quantity: it.Quantity}
|
||||
if it.SKU == "" {
|
||||
results[i].Error = "sku is required"
|
||||
continue
|
||||
}
|
||||
srv.inventoryService.UpdateInventory(ctx, pipe, inventory.SKU(it.SKU), inventory.LocationID(loc), it.Quantity)
|
||||
}
|
||||
|
||||
hadError := false
|
||||
if _, err := pipe.Exec(ctx); err != nil {
|
||||
// Exec reports the first failing command; flag the whole batch rather than
|
||||
// guess which items committed.
|
||||
hadError = true
|
||||
for i := range results {
|
||||
if results[i].Error == "" {
|
||||
results[i].Error = err.Error()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Emit level crossings for the items that were actually written, so the
|
||||
// finder/level listeners react the same way they do for catalog feeds.
|
||||
for i := range results {
|
||||
if results[i].Error == "" {
|
||||
emitLevelIfChanged(ctx, srv.rdb, srv.conn, country, lowWatermark, results[i].SKU, results[i].LocationID, results[i].Quantity)
|
||||
}
|
||||
}
|
||||
}
|
||||
for i := range results {
|
||||
if results[i].Error != "" {
|
||||
hadError = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
status := http.StatusOK
|
||||
if hadError {
|
||||
status = http.StatusMultiStatus // 207
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
json.NewEncoder(w).Encode(map[string]any{"count": len(results), "results": results})
|
||||
}
|
||||
@@ -40,6 +40,11 @@ func commitOrder(ctx context.Context, rdb *redis.Client, svc *inventory.RedisInv
|
||||
if line.SKU == "" || line.Quantity <= 0 {
|
||||
continue
|
||||
}
|
||||
// Drop-ship items are fulfilled by the supplier — never decrement
|
||||
// local stock for them.
|
||||
if line.DropShip {
|
||||
continue
|
||||
}
|
||||
loc := inventory.LocationID(defaultLoc)
|
||||
if line.Location != "" {
|
||||
loc = inventory.LocationID(line.Location)
|
||||
|
||||
+12
-1
@@ -24,6 +24,11 @@ import (
|
||||
type Server struct {
|
||||
inventoryService *inventory.RedisInventoryService
|
||||
reservationService *inventory.RedisCartReservationService
|
||||
|
||||
// rdb + conn back the batch write path (pipelined UpdateInventory + level
|
||||
// crossing). conn is nil when RABBIT_HOST is unset; emit is then skipped.
|
||||
rdb *redis.Client
|
||||
conn *rabbit.Conn
|
||||
}
|
||||
|
||||
func (srv *Server) livezHandler(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -124,13 +129,16 @@ func main() {
|
||||
return
|
||||
}
|
||||
|
||||
server := &Server{inventoryService: s, reservationService: r}
|
||||
server := &Server{inventoryService: s, reservationService: r, rdb: rdb}
|
||||
|
||||
// Set up HTTP routes
|
||||
http.HandleFunc("/livez", server.livezHandler)
|
||||
http.HandleFunc("/readyz", server.readyzHandler)
|
||||
http.HandleFunc("/inventory/{sku}/{locationId}", server.getInventoryHandler)
|
||||
http.HandleFunc("/reservations/{sku}/{locationId}", server.getReservationHandler)
|
||||
http.HandleFunc("POST /reservations", server.reserveInventoryHandler)
|
||||
http.HandleFunc("POST /reservations/release", server.releaseReservationHandler)
|
||||
http.HandleFunc("POST /inventory/batch", server.batchInventoryHandler)
|
||||
|
||||
stockhandler := &StockHandler{
|
||||
MainStockLocationID: inventory.LocationID(country),
|
||||
@@ -151,6 +159,9 @@ func main() {
|
||||
// The catalog-feed handler emits inventory.level_changed crossings
|
||||
// directly on this connection as it writes stock.
|
||||
stockhandler.conn = conn
|
||||
// Share the bus connection with the batch handler so its writes emit
|
||||
// inventory.level_changed crossings too.
|
||||
server.conn = conn
|
||||
// Reconnecting consumer: re-listen on reconnect.
|
||||
conn.NotifyOnReconnect(func() {
|
||||
ch, err := conn.Channel()
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"git.k6n.net/mats/go-redis-inventory/pkg/inventory"
|
||||
)
|
||||
|
||||
type reservationLineReq struct {
|
||||
SKU string `json:"sku"`
|
||||
LocationID string `json:"locationId"`
|
||||
Quantity uint32 `json:"quantity"`
|
||||
}
|
||||
|
||||
type reservationBatchReq struct {
|
||||
HolderID string `json:"holderId"`
|
||||
TTLSeconds int64 `json:"ttlSeconds,omitempty"`
|
||||
Lines []reservationLineReq `json:"lines"`
|
||||
}
|
||||
|
||||
func (srv *Server) reserveInventoryHandler(w http.ResponseWriter, r *http.Request) {
|
||||
var req reservationBatchReq
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if req.HolderID == "" {
|
||||
http.Error(w, "missing holderId", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if len(req.Lines) == 0 {
|
||||
http.Error(w, "missing lines", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
ttl := 15 * time.Minute
|
||||
if req.TTLSeconds > 0 {
|
||||
ttl = time.Duration(req.TTLSeconds) * time.Second
|
||||
}
|
||||
for _, line := range req.Lines {
|
||||
if line.SKU == "" || line.LocationID == "" || line.Quantity == 0 {
|
||||
http.Error(w, "each line must include sku, locationId, and quantity", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := srv.reservationService.ReserveForCart(r.Context(), inventory.CartReserveRequest{
|
||||
InventoryReference: &inventory.InventoryReference{
|
||||
SKU: inventory.SKU(line.SKU),
|
||||
LocationID: inventory.LocationID(line.LocationID),
|
||||
},
|
||||
CartID: inventory.CartID(req.HolderID),
|
||||
Quantity: line.Quantity,
|
||||
TTL: ttl,
|
||||
}); err != nil {
|
||||
status := http.StatusInternalServerError
|
||||
if errors.Is(err, inventory.ErrInsufficientInventory) {
|
||||
status = http.StatusConflict
|
||||
}
|
||||
http.Error(w, err.Error(), status)
|
||||
return
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"status": "reserved", "holderId": req.HolderID})
|
||||
}
|
||||
|
||||
func (srv *Server) releaseReservationHandler(w http.ResponseWriter, r *http.Request) {
|
||||
var req reservationBatchReq
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if req.HolderID == "" {
|
||||
http.Error(w, "missing holderId", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if len(req.Lines) == 0 {
|
||||
http.Error(w, "missing lines", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
for _, line := range req.Lines {
|
||||
if line.SKU == "" || line.LocationID == "" {
|
||||
http.Error(w, "each line must include sku and locationId", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := srv.reservationService.ReleaseForCart(r.Context(),
|
||||
inventory.SKU(line.SKU),
|
||||
inventory.LocationID(line.LocationID),
|
||||
inventory.CartID(req.HolderID),
|
||||
); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"status": "released", "holderId": req.HolderID})
|
||||
}
|
||||
Reference in New Issue
Block a user