Compare commits
3 Commits
b97eb8f285
...
716f1121aa
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
716f1121aa | ||
|
|
12d87036f6 | ||
|
|
e7c67fbb9b |
@@ -1,396 +0,0 @@
|
|||||||
# gRPC Migration Plan
|
|
||||||
|
|
||||||
File: GRPC-MIGRATION-PLAN.md
|
|
||||||
Author: (Generated plan)
|
|
||||||
Status: Draft for review
|
|
||||||
Target Release: Next major version (breaking change – no mixed compatibility)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. Overview
|
|
||||||
|
|
||||||
This document describes the full migration of the current custom TCP frame-based protocol (both the cart mutation/state channel on port `1337` and the control plane on port `1338`) to gRPC. We will remove all legacy packet framing (`FrameWithPayload`, `RemoteGrain`, `GenericListener` handlers for these two ports) and replace them with two gRPC services:
|
|
||||||
|
|
||||||
1. Cart Actor Service (mutations + state retrieval)
|
|
||||||
2. Control Plane Service (cluster membership, negotiation, ownership change, lifecycle)
|
|
||||||
|
|
||||||
We intentionally keep:
|
|
||||||
- Internal `CartGrain` logic, message storage format, disk persistence, and JSON cart serialization.
|
|
||||||
- Existing message type numeric mapping for backward compatibility with persisted event logs.
|
|
||||||
- HTTP/REST API layer unchanged (it still consumes JSON state from the local/remote grain pipeline).
|
|
||||||
|
|
||||||
We do NOT implement mixed-version compatibility; migration occurs atomically (cluster restart with new image).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. Goals
|
|
||||||
|
|
||||||
- Remove custom binary frame protocol & simplify maintenance.
|
|
||||||
- Provide clearer, strongly defined interfaces via `.proto` schemas.
|
|
||||||
- Improve observability via gRPC interceptors (metrics & tracing hooks).
|
|
||||||
- Reduce per-call overhead compared with the current manual connection pooling + handwritten framing (HTTP/2 multiplexing + connection reuse).
|
|
||||||
- Prepare groundwork for future enhancements (streaming, typed state, event streaming) without rewriting again.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. Non-Goals (Phase 1)
|
|
||||||
|
|
||||||
- Converting the cart state payload from JSON to a strongly typed proto.
|
|
||||||
- Introducing authentication / mTLS (may be added later).
|
|
||||||
- Changing persistence or replay format.
|
|
||||||
- Changing the HTTP API contract.
|
|
||||||
- Implementing streaming watchers or push updates.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. Architecture After Migration
|
|
||||||
|
|
||||||
Ports:
|
|
||||||
- `:1337` → gRPC CartActor service.
|
|
||||||
- `:1338` → gRPC ControlPlane service.
|
|
||||||
|
|
||||||
Each node:
|
|
||||||
- Runs one gRPC server with both services (can use a single listener bound to two services or keep two separate listeners; we will keep two ports initially to minimize operational surprise, but they could be merged later).
|
|
||||||
- Maintains a connection pool of `*grpc.ClientConn` objects keyed by remote hostname (one per remote host, reused for both services).
|
|
||||||
|
|
||||||
Call Flow (Mutation):
|
|
||||||
1. HTTP request hits `PoolServer`.
|
|
||||||
2. `SyncedPool.getGrain(cartId)`:
|
|
||||||
- Local: direct invocation.
|
|
||||||
- Remote: uses `RemoteGrainGRPC` (new) which invokes `CartActor.Mutate`.
|
|
||||||
3. Response JSON returned unchanged.
|
|
||||||
|
|
||||||
Control Plane Flow:
|
|
||||||
- Discovery (K8s watch) still triggers `AddRemote(host)`.
|
|
||||||
- Instead of custom `Ping`, `Negotiate`, etc. via frames, call gRPC methods on `ControlPlane` service.
|
|
||||||
- Ownership changes use `ConfirmOwner` RPC.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. Proto Design
|
|
||||||
|
|
||||||
### 5.1 Cart Actor Proto (Envelope Pattern)
|
|
||||||
|
|
||||||
We keep an envelope with `bytes payload` holding the serialized underlying cart mutation proto (existing types in `messages.proto`). This minimizes churn.
|
|
||||||
|
|
||||||
Indented code block (proto sketch):
|
|
||||||
|
|
||||||
syntax = "proto3";
|
|
||||||
package cart;
|
|
||||||
option go_package = "git.tornberg.me/go-cart-actor/proto;proto";
|
|
||||||
|
|
||||||
enum MutationType {
|
|
||||||
MUTATION_TYPE_UNSPECIFIED = 0;
|
|
||||||
MUTATION_ADD_REQUEST = 1;
|
|
||||||
MUTATION_ADD_ITEM = 2;
|
|
||||||
MUTATION_REMOVE_ITEM = 4;
|
|
||||||
MUTATION_REMOVE_DELIVERY = 5;
|
|
||||||
MUTATION_CHANGE_QUANTITY = 6;
|
|
||||||
MUTATION_SET_DELIVERY = 7;
|
|
||||||
MUTATION_SET_PICKUP_POINT = 8;
|
|
||||||
MUTATION_CREATE_CHECKOUT_ORDER = 9;
|
|
||||||
MUTATION_SET_CART_ITEMS = 10;
|
|
||||||
MUTATION_ORDER_COMPLETED = 11;
|
|
||||||
}
|
|
||||||
|
|
||||||
message MutationRequest {
|
|
||||||
string cart_id = 1;
|
|
||||||
MutationType type = 2;
|
|
||||||
bytes payload = 3; // Serialized specific mutation proto
|
|
||||||
int64 client_timestamp = 4; // Optional; server fills if zero
|
|
||||||
}
|
|
||||||
|
|
||||||
message MutationReply {
|
|
||||||
int32 status_code = 1;
|
|
||||||
bytes payload = 2; // JSON cart state or error string
|
|
||||||
}
|
|
||||||
|
|
||||||
message StateRequest {
|
|
||||||
string cart_id = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message StateReply {
|
|
||||||
int32 status_code = 1;
|
|
||||||
bytes payload = 2; // JSON cart state
|
|
||||||
}
|
|
||||||
|
|
||||||
service CartActor {
|
|
||||||
rpc Mutate(MutationRequest) returns (MutationReply);
|
|
||||||
rpc GetState(StateRequest) returns (StateReply);
|
|
||||||
}
|
|
||||||
|
|
||||||
### 5.2 Control Plane Proto
|
|
||||||
|
|
||||||
syntax = "proto3";
|
|
||||||
package control;
|
|
||||||
option go_package = "git.tornberg.me/go-cart-actor/proto;proto";
|
|
||||||
|
|
||||||
message Empty {}
|
|
||||||
|
|
||||||
message PingReply {
|
|
||||||
string host = 1;
|
|
||||||
int64 unix_time = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message NegotiateRequest {
|
|
||||||
repeated string known_hosts = 1;
|
|
||||||
}
|
|
||||||
message NegotiateReply {
|
|
||||||
repeated string hosts = 1; // Healthy hosts returned
|
|
||||||
}
|
|
||||||
|
|
||||||
message CartIdsReply {
|
|
||||||
repeated string cart_ids = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
message OwnerChangeRequest {
|
|
||||||
string cart_id = 1;
|
|
||||||
string new_host = 2;
|
|
||||||
}
|
|
||||||
message OwnerChangeAck {
|
|
||||||
bool accepted = 1;
|
|
||||||
string message = 2;
|
|
||||||
}
|
|
||||||
|
|
||||||
message ClosingNotice {
|
|
||||||
string host = 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
service ControlPlane {
|
|
||||||
rpc Ping(Empty) returns (PingReply);
|
|
||||||
rpc Negotiate(NegotiateRequest) returns (NegotiateReply);
|
|
||||||
rpc GetCartIds(Empty) returns (CartIdsReply);
|
|
||||||
rpc ConfirmOwner(OwnerChangeRequest) returns (OwnerChangeAck);
|
|
||||||
rpc Closing(ClosingNotice) returns (OwnerChangeAck);
|
|
||||||
}
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. Message Type Mapping
|
|
||||||
|
|
||||||
| Legacy Constant | Numeric | New Enum Value |
|
|
||||||
|-----------------|---------|-----------------------------|
|
|
||||||
| AddRequestType | 1 | MUTATION_ADD_REQUEST |
|
|
||||||
| AddItemType | 2 | MUTATION_ADD_ITEM |
|
|
||||||
| RemoveItemType | 4 | MUTATION_REMOVE_ITEM |
|
|
||||||
| RemoveDeliveryType | 5 | MUTATION_REMOVE_DELIVERY |
|
|
||||||
| ChangeQuantityType | 6 | MUTATION_CHANGE_QUANTITY |
|
|
||||||
| SetDeliveryType | 7 | MUTATION_SET_DELIVERY |
|
|
||||||
| SetPickupPointType | 8 | MUTATION_SET_PICKUP_POINT |
|
|
||||||
| CreateCheckoutOrderType | 9 | MUTATION_CREATE_CHECKOUT_ORDER |
|
|
||||||
| SetCartItemsType | 10 | MUTATION_SET_CART_ITEMS |
|
|
||||||
| OrderCompletedType | 11 | MUTATION_ORDER_COMPLETED |
|
|
||||||
|
|
||||||
Persisted events keep original numeric codes; reconstruction simply casts to `MutationType`.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. Components To Remove / Replace
|
|
||||||
|
|
||||||
Remove (after migration complete):
|
|
||||||
- `remote-grain.go`
|
|
||||||
- `rpc-server.go`
|
|
||||||
- Any packet/frame-specific types solely used by the above (search: `FrameWithPayload`, `RemoteHandleMutation`, `RemoteGetState` where not reused by disk or internal logic).
|
|
||||||
- The constants representing network frame types in `synced-pool.go` (RemoteNegotiate, AckChange, etc.) replaced by gRPC calls.
|
|
||||||
- netpool usage for remote cart channel (control plane also no longer needs `Connection` abstraction).
|
|
||||||
|
|
||||||
Retain (until reworked or optionally cleaned later):
|
|
||||||
- `message.go` (for persistence)
|
|
||||||
- `message-handler.go`
|
|
||||||
- `cart-grain.go`
|
|
||||||
- `messages.proto` (underlying mutation messages)
|
|
||||||
- HTTP API server and REST handlers.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. New / Modified Components
|
|
||||||
|
|
||||||
New files (planned):
|
|
||||||
- `proto/cart_actor.proto`
|
|
||||||
- `proto/control_plane.proto`
|
|
||||||
- `grpc/cart_actor_server.go` (server impl)
|
|
||||||
- `grpc/cart_actor_client.go` (client adapter implementing `Grain`)
|
|
||||||
- `grpc/control_plane_server.go`
|
|
||||||
- `grpc/control_plane_client.go`
|
|
||||||
- `grpc/interceptors.go` (metrics, logging, optional tracing hooks)
|
|
||||||
- `remote_grain_grpc.go` (adapter bridging existing interfaces)
|
|
||||||
- `control_plane_adapter.go` (replaces frame handlers in `SyncedPool`)
|
|
||||||
|
|
||||||
Modified:
|
|
||||||
- `synced-pool.go` (remote host management now uses gRPC clients; negotiation logic updated)
|
|
||||||
- `main.go` (initialize both gRPC services on startup)
|
|
||||||
- `go.mod` (add `google.golang.org/grpc`)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 9. Step-by-Step Migration Plan
|
|
||||||
|
|
||||||
1. Add proto files and generate Go code (`protoc --go_out --go-grpc_out`).
|
|
||||||
2. Implement `CartActorServer`:
|
|
||||||
- Translate `MutationRequest` to `Message`.
|
|
||||||
- Use existing handler registry for payload encode/decode.
|
|
||||||
- Return JSON cart state.
|
|
||||||
3. Implement `CartActorClient` wrapper (`RemoteGrainGRPC`) implementing:
|
|
||||||
- `HandleMessage`: Build envelope, call `Mutate`.
|
|
||||||
- `GetCurrentState`: Call `GetState`.
|
|
||||||
4. Implement `ControlPlaneServer` with methods:
|
|
||||||
- `Ping`: returns host + time.
|
|
||||||
- `Negotiate`: merge host lists; emulate old logic.
|
|
||||||
- `GetCartIds`: iterate local grains.
|
|
||||||
- `ConfirmOwner`: replicate quorum flow (accept always; error path for future).
|
|
||||||
- `Closing`: schedule remote removal.
|
|
||||||
5. Implement `ControlPlaneClient` used inside `SyncedPool.AddRemote`.
|
|
||||||
6. Refactor `SyncedPool`:
|
|
||||||
- Replace frame handlers registration with gRPC client calls.
|
|
||||||
- Replace `Server.AddHandler(...)` start-up with launching gRPC server.
|
|
||||||
- Implement periodic health checks using `Ping`.
|
|
||||||
7. Remove old connection constructs for 1337/1338.
|
|
||||||
8. Metrics:
|
|
||||||
- Add unary interceptor capturing duration and status.
|
|
||||||
- Replace packet counters with `cart_grpc_mutate_calls_total`, `cart_grpc_control_calls_total`, histograms for latency.
|
|
||||||
9. Update `main.go` to start:
|
|
||||||
- gRPC server(s).
|
|
||||||
- HTTP server as before.
|
|
||||||
10. Delete legacy files & update README build instructions.
|
|
||||||
11. Load testing & profiling on Raspberry Pi hardware (or ARM emulation).
|
|
||||||
12. Final cleanup & dead code removal (search for now-unused constants & structs).
|
|
||||||
13. Tag release.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 10. Performance Considerations (Raspberry Pi Focus)
|
|
||||||
|
|
||||||
- Single `*grpc.ClientConn` per remote host (HTTP/2 multiplexing) to reduce file descriptor and handshake overhead.
|
|
||||||
- Use small keepalive pings (optional) only if connections drop; default may suffice.
|
|
||||||
- Avoid reflection / dynamic dispatch in hot path: pre-build a mapping from `MutationType` to handler function.
|
|
||||||
- Reuse byte buffers:
|
|
||||||
- Implement a `sync.Pool` for mutation serialization to reduce GC pressure.
|
|
||||||
- Enforce per-RPC deadlines (e.g. 300–400ms) to avoid pile-ups.
|
|
||||||
- Backpressure:
|
|
||||||
- Before dispatch: if local grain pool at capacity and target grain is remote, abort early with 503 to caller (optional).
|
|
||||||
- Disable gRPC compression for small payloads (mutation messages are small). Condition compression if payload > threshold (e.g. 8KB).
|
|
||||||
- Compile with `-ldflags="-s -w"` in production to reduce binary size (optional).
|
|
||||||
- Enable `GOMAXPROCS` tuned to CPU cores; Pi often benefits from leaving default but monitor.
|
|
||||||
- Use histograms with limited buckets to reduce Prometheus cardinality.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 11. Testing Strategy
|
|
||||||
|
|
||||||
Unit:
|
|
||||||
- Message type mapping tests (legacy -> enum).
|
|
||||||
- Envelope roundtrip: Original proto -> payload -> gRPC -> server decode -> internal Message.
|
|
||||||
|
|
||||||
Integration:
|
|
||||||
- Two-node cluster simulation:
|
|
||||||
- Mutate cart on Node A, ownership moves, verify remote access from Node B.
|
|
||||||
- Quorum failure simulation (temporarily reject `ConfirmOwner`).
|
|
||||||
- Control plane negotiation: start nodes in staggered order, assert final membership.
|
|
||||||
|
|
||||||
Load/Perf:
|
|
||||||
- Benchmark local mutation vs remote mutation latency.
|
|
||||||
- High concurrency test (N goroutines each performing X mutations).
|
|
||||||
- Memory profiling (ensure no large buffer retention).
|
|
||||||
|
|
||||||
Failure Injection:
|
|
||||||
- Kill a node mid-mutation; client call should timeout and not corrupt local state.
|
|
||||||
- Simulated network partition: drop `Ping` replies; ensure host removal path triggers.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 12. Rollback Strategy
|
|
||||||
|
|
||||||
Because no mixed-version compatibility is provided, rollback = redeploy previous version containing legacy protocol:
|
|
||||||
1. Stop all new-version pods.
|
|
||||||
2. Deploy old version cluster-wide.
|
|
||||||
3. No data migration needed (event persistence unaffected).
|
|
||||||
|
|
||||||
Note: Avoid partial upgrades; perform full rolling restart quickly to prevent split-brain (new nodes won’t talk to old nodes).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 13. Risks & Mitigations
|
|
||||||
|
|
||||||
| Risk | Description | Mitigation |
|
|
||||||
|------|-------------|------------|
|
|
||||||
| Full-cluster restart required | No mixed compatibility | Schedule maintenance window |
|
|
||||||
| gRPC adds CPU overhead | Envelope + marshaling cost | Buffer reuse, keep small messages uncompressed |
|
|
||||||
| Ownership race | Timing differences after refactor | Add explicit logs + tests around `RequestOwnership` path |
|
|
||||||
| Hidden dependency on frame-level status codes | Some code may assume `FrameWithPayload` fields | Wrap gRPC responses into minimal compatibility structs until fully removed |
|
|
||||||
| Memory growth | Connection reuse & pooled buffers not implemented initially | Add `sync.Pool` & track memory via pprof early |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 14. Logging & Observability
|
|
||||||
|
|
||||||
- Structured log entries for:
|
|
||||||
- Ownership changes
|
|
||||||
- Negotiation rounds
|
|
||||||
- Remote spawn events
|
|
||||||
- Mutation failures (with cart id, mutation type)
|
|
||||||
- Metrics:
|
|
||||||
- `cart_grpc_mutate_duration_seconds` (histogram)
|
|
||||||
- `cart_grpc_mutate_errors_total`
|
|
||||||
- `cart_grpc_control_duration_seconds`
|
|
||||||
- `cart_remote_hosts` (gauge)
|
|
||||||
- Retain existing grain counts.
|
|
||||||
- Optional future: OpenTelemetry tracing (span per remote mutation).
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 15. Future Enhancements (Post-Migration)
|
|
||||||
|
|
||||||
- Replace JSON state with `CartState` proto and provide streaming watch API.
|
|
||||||
- mTLS between nodes (certificate rotation via K8s Secret or SPIRE).
|
|
||||||
- Distributed tracing integration.
|
|
||||||
- Ownership leasing with TTL and optimistic renewal.
|
|
||||||
- Delta replication or CRDT-based conflict resolution for experimentation.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 16. Task Breakdown & Estimates
|
|
||||||
|
|
||||||
| Task | Estimate |
|
|
||||||
|------|----------|
|
|
||||||
| Proto definitions & generation | 0.5d |
|
|
||||||
| CartActor server/client | 1.0d |
|
|
||||||
| ControlPlane server/client | 1.0d |
|
|
||||||
| SyncedPool refactor | 1.0d |
|
|
||||||
| Metrics & interceptors | 0.5d |
|
|
||||||
| Remove legacy code & cleanup | 0.5d |
|
|
||||||
| Tests (unit + integration) | 1.5d |
|
|
||||||
| Benchmark & tuning | 0.5–1.0d |
|
|
||||||
| Total | ~6–7d |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 17. Open Questions (Confirm Before Implementation)
|
|
||||||
|
|
||||||
1. Combine both services on a single port (simplify ops) or keep dual-port first? (Default here: keep dual, but easy to merge.)
|
|
||||||
2. Minimum Go version remains 1.24.x—acceptable to add `google.golang.org/grpc` latest?
|
|
||||||
3. Accept adding `sync.Pool` micro-optimizations in first pass or postpone?
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 18. Acceptance Criteria
|
|
||||||
|
|
||||||
- All previous integration tests (adjusted to gRPC) pass.
|
|
||||||
- Cart operations (add, remove, delivery, checkout) function across at least a 2‑node cluster.
|
|
||||||
- Control plane negotiation forms consistent host list.
|
|
||||||
- Latency for a remote mutation does not degrade beyond an acceptable threshold (define baseline before merge).
|
|
||||||
- Legacy networking code fully removed.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 19. Next Steps (If Approved)
|
|
||||||
|
|
||||||
1. Implement proto files and commit.
|
|
||||||
2. Scaffold server & client code.
|
|
||||||
3. Refactor `SyncedPool` and `main.go`.
|
|
||||||
4. Add metrics and tests.
|
|
||||||
5. Run benchmark on target Pi hardware.
|
|
||||||
6. Review & merge.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
End of Plan.
|
|
||||||
119
Makefile
Normal file
119
Makefile
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
# Makefile for go-cart-actor
|
||||||
|
#
|
||||||
|
# Key targets:
|
||||||
|
# make protogen - Generate protobuf + gRPC code into proto/
|
||||||
|
# make clean_proto - Remove generated proto *.pb.go files
|
||||||
|
# make verify_proto - Ensure no stray root-level *.pb.go files exist
|
||||||
|
# make build - Build the project
|
||||||
|
# make test - Run tests (verbose)
|
||||||
|
# make tidy - Run go mod tidy
|
||||||
|
# make regen - Clean proto, regenerate, tidy, verify, build
|
||||||
|
# make help - Show this help
|
||||||
|
#
|
||||||
|
# Conventions:
|
||||||
|
# - All .proto files live in $(PROTO_DIR)
|
||||||
|
# - Generated Go code is emitted under $(PROTO_DIR) via go_package mapping
|
||||||
|
# - go_package is set to: git.tornberg.me/go-cart-actor/proto;messages
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
MODULE_PATH := git.tornberg.me/go-cart-actor
|
||||||
|
PROTO_DIR := proto
|
||||||
|
PROTOS := $(PROTO_DIR)/messages.proto $(PROTO_DIR)/cart_actor.proto $(PROTO_DIR)/control_plane.proto
|
||||||
|
|
||||||
|
# Allow override: make PROTOC=/path/to/protoc
|
||||||
|
PROTOC ?= protoc
|
||||||
|
|
||||||
|
# Tools (auto-detect; can override)
|
||||||
|
PROTOC_GEN_GO ?= $(shell command -v protoc-gen-go 2>/dev/null)
|
||||||
|
PROTOC_GEN_GO_GRPC ?= $(shell command -v protoc-gen-go-grpc 2>/dev/null)
|
||||||
|
|
||||||
|
GO ?= go
|
||||||
|
|
||||||
|
# Colors (optional)
|
||||||
|
GREEN := \033[32m
|
||||||
|
RED := \033[31m
|
||||||
|
YELLOW := \033[33m
|
||||||
|
RESET := \033[0m
|
||||||
|
|
||||||
|
# ------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
.PHONY: protogen clean_proto verify_proto tidy build test regen help check_tools
|
||||||
|
|
||||||
|
help:
|
||||||
|
@echo "Available targets:"
|
||||||
|
@echo " protogen Generate protobuf & gRPC code"
|
||||||
|
@echo " clean_proto Remove generated *.pb.go files in $(PROTO_DIR)"
|
||||||
|
@echo " verify_proto Ensure no root-level *.pb.go files (old layout)"
|
||||||
|
@echo " tidy Run go mod tidy"
|
||||||
|
@echo " build Build the module"
|
||||||
|
@echo " test Run tests (verbose)"
|
||||||
|
@echo " regen Clean proto, regenerate, tidy, verify, and build"
|
||||||
|
@echo " check_tools Verify protoc + plugins are installed"
|
||||||
|
|
||||||
|
check_tools:
|
||||||
|
@if [ -z "$(PROTOC_GEN_GO)" ] || [ -z "$(PROTOC_GEN_GO_GRPC)" ]; then \
|
||||||
|
echo "$(RED)Missing protoc-gen-go or protoc-gen-go-grpc in PATH.$(RESET)"; \
|
||||||
|
echo "Install with:"; \
|
||||||
|
echo " go install google.golang.org/protobuf/cmd/protoc-gen-go@latest"; \
|
||||||
|
echo " go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest"; \
|
||||||
|
exit 1; \
|
||||||
|
fi
|
||||||
|
@if ! command -v "$(PROTOC)" >/dev/null 2>&1; then \
|
||||||
|
echo "$(RED)protoc not found. Install protoc (e.g. via package manager)$(RESET)"; \
|
||||||
|
exit 1; \
|
||||||
|
fi
|
||||||
|
@echo "$(GREEN)All required tools detected.$(RESET)"
|
||||||
|
|
||||||
|
protogen: check_tools
|
||||||
|
@echo "$(YELLOW)Generating protobuf code (outputs -> ./proto)...$(RESET)"
|
||||||
|
$(PROTOC) -I $(PROTO_DIR) \
|
||||||
|
--go_out=./proto --go_opt=paths=source_relative \
|
||||||
|
--go-grpc_out=./proto --go-grpc_opt=paths=source_relative \
|
||||||
|
$(PROTOS)
|
||||||
|
@echo "$(GREEN)Protobuf generation complete.$(RESET)"
|
||||||
|
|
||||||
|
clean_proto:
|
||||||
|
@echo "$(YELLOW)Removing generated protobuf files...$(RESET)"
|
||||||
|
@rm -f $(PROTO_DIR)/*_grpc.pb.go $(PROTO_DIR)/*.pb.go
|
||||||
|
@rm -f *.pb.go
|
||||||
|
@rm -rf git.tornberg.me
|
||||||
|
@echo "$(GREEN)Clean complete.$(RESET)"
|
||||||
|
|
||||||
|
verify_proto:
|
||||||
|
@echo "$(YELLOW)Verifying proto layout...$(RESET)"
|
||||||
|
@if ls *.pb.go >/dev/null 2>&1; then \
|
||||||
|
echo "$(RED)ERROR: Found root-level generated *.pb.go files (should be only under $(PROTO_DIR)/).$(RESET)"; \
|
||||||
|
ls -1 *.pb.go; \
|
||||||
|
exit 1; \
|
||||||
|
fi
|
||||||
|
@echo "$(GREEN)Proto layout OK (no root-level *.pb.go files).$(RESET)"
|
||||||
|
|
||||||
|
tidy:
|
||||||
|
@echo "$(YELLOW)Running go mod tidy...$(RESET)"
|
||||||
|
$(GO) mod tidy
|
||||||
|
@echo "$(GREEN)tidy complete.$(RESET)"
|
||||||
|
|
||||||
|
build:
|
||||||
|
@echo "$(YELLOW)Building...$(RESET)"
|
||||||
|
$(GO) build ./...
|
||||||
|
@echo "$(GREEN)Build success.$(RESET)"
|
||||||
|
|
||||||
|
test:
|
||||||
|
@echo "$(YELLOW)Running tests...$(RESET)"
|
||||||
|
$(GO) test -v ./...
|
||||||
|
@echo "$(GREEN)Tests completed.$(RESET)"
|
||||||
|
|
||||||
|
regen: clean_proto protogen tidy verify_proto build
|
||||||
|
@echo "$(GREEN)Full regenerate cycle complete.$(RESET)"
|
||||||
|
|
||||||
|
# Utility: show proto sources and generated outputs
|
||||||
|
print_proto:
|
||||||
|
@echo "Proto sources:"
|
||||||
|
@ls -1 $(PROTOS)
|
||||||
|
@echo ""
|
||||||
|
@echo "Generated files (if any):"
|
||||||
|
@ls -1 $(PROTO_DIR)/*pb.go 2>/dev/null || echo "(none)"
|
||||||
|
|
||||||
|
# Prevent make from treating these as file targets if similarly named files appear.
|
||||||
|
.SILENT: help check_tools protogen clean_proto verify_proto tidy build test regen print_proto
|
||||||
238
README.md
238
README.md
@@ -175,4 +175,240 @@ curl --cookie cookies.txt http://localhost:8080/cart/add/TEST-SKU-123
|
|||||||
|
|
||||||
- Always regenerate protobuf Go code after modifying any `.proto` files (messages/cart_actor/control_plane)
|
- Always regenerate protobuf Go code after modifying any `.proto` files (messages/cart_actor/control_plane)
|
||||||
- The generated `messages.pb.go` file should not be edited manually
|
- The generated `messages.pb.go` file should not be edited manually
|
||||||
- Make sure your PATH includes the protoc-gen-go binary location (usually `$GOPATH/bin`)
|
- Make sure your PATH includes the protoc-gen-go binary location (usually `$GOPATH/bin`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architecture Overview
|
||||||
|
|
||||||
|
The system is a distributed, sharded (by cart id) actor model implementation:
|
||||||
|
|
||||||
|
- Each cart is a grain (an in‑memory struct `*CartGrain`) that owns and mutates its own state.
|
||||||
|
- A **local grain pool** holds grains owned by the node.
|
||||||
|
- A **synced (cluster) pool** (`SyncedPool`) coordinates multiple nodes and exposes local or remote grains through a uniform interface (`GrainPool`).
|
||||||
|
- All inter‑node communication is gRPC:
|
||||||
|
- Cart mutation & state RPCs (CartActor service).
|
||||||
|
- Control plane RPCs (ControlPlane service) for membership, ownership negotiation, liveness, and graceful shutdown.
|
||||||
|
|
||||||
|
### Key Processes
|
||||||
|
|
||||||
|
1. Client HTTP request (or gRPC client) arrives with a cart identifier (cookie or path).
|
||||||
|
2. The pool resolves ownership:
|
||||||
|
- If local grain exists → use it.
|
||||||
|
- If a remote host is known owner → a remote grain proxy (`RemoteGrainGRPC`) is used; it performs gRPC calls to the owning node.
|
||||||
|
- If ownership is unknown → node attempts to claim ownership (quorum negotiation) and spawns a local grain.
|
||||||
|
3. Mutation is executed via the **mutation registry** (registry wraps domain logic + optional totals recomputation).
|
||||||
|
4. Updated state returned to caller; ownership preserved unless relinquished later (not yet implemented to shed load).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Grain & Mutation Model
|
||||||
|
|
||||||
|
- `CartGrain` holds items, deliveries, pricing aggregates, and checkout/order metadata.
|
||||||
|
- All mutations are registered via `RegisterMutation[T]` with signature:
|
||||||
|
```
|
||||||
|
func(*CartGrain, *T) error
|
||||||
|
```
|
||||||
|
- `WithTotals()` flag triggers automatic recalculation of totals after successful handlers.
|
||||||
|
- The old giant `switch` in `CartGrain.Apply` has been replaced by registry dispatch; unregistered mutations fail fast.
|
||||||
|
- Adding a mutation:
|
||||||
|
1. Define proto message.
|
||||||
|
2. Generate code.
|
||||||
|
3. Register handler (optionally WithTotals).
|
||||||
|
4. Add gRPC RPC + request wrapper if the mutation must be remotely invokable.
|
||||||
|
5. (Optional) Add HTTP endpoint mapping to the mutation.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Local Grain Pool
|
||||||
|
|
||||||
|
- Manages an in‑memory map `map[CartId]*CartGrain`.
|
||||||
|
- Lazy spawn: first mutation or explicit access triggers `spawn(id)`.
|
||||||
|
- TTL / purge loop periodically removes expired grains unless they changed recently (basic memory pressure management).
|
||||||
|
- Capacity limit (`PoolSize`); oldest expired grain evicted first when full.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Synced (Cluster) Pool
|
||||||
|
|
||||||
|
`SyncedPool` wraps a local pool and tracks:
|
||||||
|
|
||||||
|
- `remoteHosts`: known peer nodes (gRPC connections).
|
||||||
|
- `remoteIndex`: mapping of cart id → remote grain proxy (`RemoteGrainGRPC`) for carts owned elsewhere.
|
||||||
|
|
||||||
|
Responsibilities:
|
||||||
|
|
||||||
|
1. Discovery integration (via a `Discovery` interface) adds/removes hosts.
|
||||||
|
2. Periodic ping health checks (ControlPlane.Ping).
|
||||||
|
3. Ownership negotiation:
|
||||||
|
- On first contention / unknown owner, node calls `ConfirmOwner` on peers to achieve quorum before making a local grain authoritative.
|
||||||
|
4. Remote spawning:
|
||||||
|
- When a remote host reports its cart ids (`GetCartIds`), the pool creates remote proxies for fast routing.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Remote Grain Proxies
|
||||||
|
|
||||||
|
A `RemoteGrainGRPC` implements the `Grain` interface but delegates:
|
||||||
|
|
||||||
|
- `Apply` → Specific CartActor per‑mutation RPC (e.g., `AddItem`, `RemoveItem`) constructed from the mutation type. (Legacy envelope removed.)
|
||||||
|
- `GetCurrentState` → `CartActor.GetState`.
|
||||||
|
|
||||||
|
Return path:
|
||||||
|
|
||||||
|
1. gRPC reply (CartMutationReply / StateReply) → proto `CartState`.
|
||||||
|
2. `ToCartState` / mapping reconstructs a local `CartGrain` snapshot for callers expecting grain semantics.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Control Plane (Inter‑Node Coordination)
|
||||||
|
|
||||||
|
Defined in `proto/control_plane.proto`:
|
||||||
|
|
||||||
|
| RPC | Purpose |
|
||||||
|
|-----|---------|
|
||||||
|
| `Ping` | Liveness; increments missed ping counter if failing. |
|
||||||
|
| `Negotiate` | Merges membership views; used after discovery events. |
|
||||||
|
| `GetCartIds` | Enumerate locally owned carts for remote index seeding. |
|
||||||
|
| `ConfirmOwner` | Quorum acknowledgment for ownership claim. |
|
||||||
|
| `Closing` | Graceful shutdown notice; peers remove host & associated remote grains. |
|
||||||
|
|
||||||
|
### Ownership / Quorum Rules
|
||||||
|
|
||||||
|
- If total participating hosts < 3 → all must accept.
|
||||||
|
- Otherwise majority acceptance (`ok >= total/2`).
|
||||||
|
- On failure → local tentative grain is removed (rollback to avoid split‑brain).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Request / Mutation Flow Examples
|
||||||
|
|
||||||
|
### Local Mutation
|
||||||
|
1. HTTP handler parses request → determines cart id.
|
||||||
|
2. `SyncedPool.Apply`:
|
||||||
|
- Finds local grain (or spawns new after quorum).
|
||||||
|
- Executes registry mutation.
|
||||||
|
3. Totals updated if flagged.
|
||||||
|
4. HTTP response returns updated JSON (via `ToCartState`).
|
||||||
|
|
||||||
|
### Remote Mutation
|
||||||
|
1. `SyncedPool.Apply` sees cart mapped to a remote host.
|
||||||
|
2. Routes to `RemoteGrainGRPC.Apply`.
|
||||||
|
3. Remote node executes mutation locally and returns updated state over gRPC.
|
||||||
|
4. Proxy materializes snapshot locally (not authoritative, read‑only view).
|
||||||
|
|
||||||
|
### Checkout (Side‑Effecting, Non-Pure)
|
||||||
|
- HTTP `/checkout` uses current grain snapshot to build payload (pure function).
|
||||||
|
- Calls Klarna externally (not a mutation).
|
||||||
|
- Applies `InitializeCheckout` mutation to persist reference + status.
|
||||||
|
- Returns Klarna order JSON to client.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Scaling & Deployment
|
||||||
|
|
||||||
|
- **Horizontal scaling**: Add more nodes; discovery layer (Kubernetes / service registry) feeds hosts to `SyncedPool`.
|
||||||
|
- **Sharding**: Implicit by cart id hash. Ownership is first-claim with quorum acceptance.
|
||||||
|
- **Hot spots**: A single popular cart remains on one node; for heavy multi-client concurrency, future work could add read replicas or partitioning (not implemented).
|
||||||
|
- **Capacity tuning**: Increase `PoolSize` & memory limits; adjust TTL for stale cart eviction.
|
||||||
|
|
||||||
|
### Adding Nodes
|
||||||
|
1. Node starts gRPC server (CartActor + ControlPlane).
|
||||||
|
2. After brief delay, begins discovery watch; on event:
|
||||||
|
- New host → dial + negotiate → seed remote cart ids.
|
||||||
|
3. Pings maintain health; failed hosts removed (proxies invalidated).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Failure Handling
|
||||||
|
|
||||||
|
| Scenario | Behavior |
|
||||||
|
|----------|----------|
|
||||||
|
| Remote host unreachable | Pings increment `MissedPings`; after threshold host removed. |
|
||||||
|
| Ownership negotiation fails | Tentative local grain discarded. |
|
||||||
|
| gRPC call error on remote mutation | Error bubbled to caller; no local fallback. |
|
||||||
|
| Missing mutation registration | Fast failure with explicit error message. |
|
||||||
|
| Partial checkout (Klarna fails) | No local state mutation for checkout; client sees error; cart remains unchanged. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Mutation Registry Summary
|
||||||
|
|
||||||
|
- Central, type-safe registry prevents silent omission.
|
||||||
|
- Each handler:
|
||||||
|
- Validates input.
|
||||||
|
- Mutates `*CartGrain`.
|
||||||
|
- Returns error for rejection.
|
||||||
|
- Automatic totals recomputation reduces boilerplate and consistency risk.
|
||||||
|
- Coverage test (add separately) can enforce all proto mutations are registered.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## gRPC Interfaces
|
||||||
|
|
||||||
|
- **CartActor**: Per-mutation unary RPCs + `GetState`. (Checkout logic intentionally excluded; handled at HTTP layer.)
|
||||||
|
- **ControlPlane**: Cluster coordination (Ping, Negotiate, ConfirmOwner, etc.).
|
||||||
|
|
||||||
|
**Ports** (default / implied):
|
||||||
|
- CartActor & ControlPlane share the same gRPC server/listener (single port, e.g. `:1337`).
|
||||||
|
- Legacy frame/TCP code has been removed.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Security & Future Enhancements
|
||||||
|
|
||||||
|
| Area | Potential Improvement |
|
||||||
|
|------|------------------------|
|
||||||
|
| Transport Security | Add TLS / mTLS to gRPC servers & clients. |
|
||||||
|
| Auth / RBAC | Intercept CartActor RPCs with auth metadata. |
|
||||||
|
| Backpressure | Rate-limit remote mutation calls per host. |
|
||||||
|
| Observability | Add per-mutation Prometheus metrics & tracing spans. |
|
||||||
|
| Ownership | Add lease timeouts / fencing tokens for stricter guarantees. |
|
||||||
|
| Batch Ops | Introduce batch mutation RPC or streaming updates (WatchState). |
|
||||||
|
| Persistence | Reintroduce event log or snapshot persistence layer if durability required. |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Adding a New Node (Operational Checklist)
|
||||||
|
|
||||||
|
1. Deploy binary/container with same proto + registry.
|
||||||
|
2. Expose gRPC port.
|
||||||
|
3. Ensure discovery lists the new host.
|
||||||
|
4. Node dials peers, negotiates membership.
|
||||||
|
5. Remote cart proxies seeded.
|
||||||
|
6. Traffic routed automatically based on ownership.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Adding a New Mutation (Checklist Recap)
|
||||||
|
|
||||||
|
1. Define proto message (+ request wrapper & RPC if remote invocation needed).
|
||||||
|
2. Regenerate protobuf code.
|
||||||
|
3. Implement & register handler (`RegisterMutation`).
|
||||||
|
4. Add client (HTTP/gRPC) endpoint.
|
||||||
|
5. Write unit + integration tests.
|
||||||
|
6. (Optional) Add to coverage test list and docs.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## High-Level Data Flow Diagram (Text)
|
||||||
|
|
||||||
|
```
|
||||||
|
Client -> HTTP Handler -> SyncedPool -> (local?) -> Registry -> Grain State
|
||||||
|
\-> (remote?) -> RemoteGrainGRPC -> gRPC -> Remote CartActor -> Registry -> Grain
|
||||||
|
ControlPlane: Discovery Events <-> Negotiation/Ping/ConfirmOwner <-> SyncedPool state
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
| Symptom | Likely Cause | Action |
|
||||||
|
|---------|--------------|--------|
|
||||||
|
| New cart every request | Secure cookie over plain HTTP or not sending cookie jar | Disable Secure locally or use HTTPS & proper curl `-b` |
|
||||||
|
| Unsupported mutation error | Missing registry handler | Add `RegisterMutation` for that proto |
|
||||||
|
| Ownership flapping | Quorum failing due to intermittent peers | Investigate `ConfirmOwner` errors / network |
|
||||||
|
| Remote mutation latency | Network / serialization overhead | Consider batching or colocating hot carts |
|
||||||
|
| Checkout returns 500 | Klarna call failed | Inspect logs; no grain state mutated |
|
||||||
|
|
||||||
|
---
|
||||||
|
|||||||
245
TODO.md
Normal file
245
TODO.md
Normal file
@@ -0,0 +1,245 @@
|
|||||||
|
# TODO / Roadmap
|
||||||
|
|
||||||
|
A living roadmap for improving the cart actor system. Focus areas:
|
||||||
|
1. Reliability & correctness
|
||||||
|
2. Simplicity of mutation & ownership flows
|
||||||
|
3. Developer experience (DX)
|
||||||
|
4. Operability (observability, tracing, metrics)
|
||||||
|
5. Performance & scalability
|
||||||
|
6. Security & multi-tenant readiness
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Immediate Next Steps (High-Leverage)
|
||||||
|
|
||||||
|
| Priority | Task | Goal | Effort | Owner | Notes |
|
||||||
|
|----------|------|------|--------|-------|-------|
|
||||||
|
| P0 | Add mutation registry coverage test | Ensure no unregistered mutations silently fail | S | | Failing fast in CI |
|
||||||
|
| P0 | Add decodeJSON helper + 400 mapping for EOF | Reduce noisy 500 logs | S | | Improves client API clarity |
|
||||||
|
| P0 | Regenerate protos & prune unused messages (CreateCheckoutOrder, Checkout RPC remnants) | Eliminate dead types | S | | Avoid confusion |
|
||||||
|
| P0 | Add integration test: multi-node ownership negotiation | Validate quorum logic | M | | Spin up 2–3 nodes ephemeral |
|
||||||
|
| P1 | Export Prometheus metrics for per-mutation counts & latency | Operability | M | | Wrap registry handlers |
|
||||||
|
| P1 | Add graceful shutdown ordering (Closing → wait for acks → stop gRPC) | Reduce in-flight mutation failures | S | | Add context cancellation |
|
||||||
|
| P1 | Add coverage for InitializeCheckout / OrderCreated flows | Checkout reliability | S | | Simulate Klarna stub |
|
||||||
|
| P2 | Add optional batching client (apply multiple mutations locally then persist) | Performance | M | | Only if needed |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Simplification Opportunities
|
||||||
|
|
||||||
|
### A. RemoteGrain Proxy Mapping
|
||||||
|
Current: manual switch building each RPC call.
|
||||||
|
Simplify by:
|
||||||
|
- Generating a thin client adapter from proto RPC descriptors (codegen).
|
||||||
|
- Or using a registry similar to mutation registry but for “outbound call constructors”.
|
||||||
|
Benefit: adding a new mutation = add proto + register server handler + register outbound invoker (no switch edits).
|
||||||
|
|
||||||
|
### B. Ownership Negotiation
|
||||||
|
Current: ad hoc quorum rule in `SyncedPool`.
|
||||||
|
Simplify:
|
||||||
|
- Introduce explicit `OwnershipLease{holder, expiresAt, version}`.
|
||||||
|
- Use monotonic version increment—reject stale ConfirmOwner replies.
|
||||||
|
- Optional: add randomized backoff to reduce thundering herd on contested cart ids.
|
||||||
|
|
||||||
|
### C. CartId Handling
|
||||||
|
Current: ephemeral 16-byte array with trimmed string semantics.
|
||||||
|
Simplify:
|
||||||
|
- Use ULID / UUIDv7 (time-ordered, collision-resistant) for easier external correlation.
|
||||||
|
- Provide helper `NewCartIdString()` and keep internal fixed-size if still desired.
|
||||||
|
|
||||||
|
### D. Mutation Signatures
|
||||||
|
Current: registry assumes `func(*CartGrain, *T) error`.
|
||||||
|
Extension option: allow pure transforms returning a delta struct (for audit/logging):
|
||||||
|
```
|
||||||
|
type MutationResult struct {
|
||||||
|
Changed bool
|
||||||
|
Events []interface{}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Only implement if auditing/event-sourcing reintroduced.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Developer Experience Improvements
|
||||||
|
|
||||||
|
| Task | Rationale | Approach |
|
||||||
|
|------|-----------|----------|
|
||||||
|
| Makefile targets: `make run-single`, `make run-multi N=3` | Faster local cluster spin-up | Docker compose or background “mini cluster” scripts |
|
||||||
|
| Template for new mutation (generator) | Reduce boilerplate | `go:generate` scanning proto for new RPCs |
|
||||||
|
| Lint config (golangci-lint) | Catch subtle issues early | Add `.golangci.yml` |
|
||||||
|
| Pre-commit hook for proto regeneration check | Avoid stale generated code | Script compares git diff after `make protogen` |
|
||||||
|
| Example client (Go + curl snippets auto-generated) | Onboarding | Codegen a markdown from proto comments |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Observability / Metrics / Tracing
|
||||||
|
|
||||||
|
| Area | Metric / Trace | Notes |
|
||||||
|
|------|----------------|-------|
|
||||||
|
| Mutation registry | `cart_mutations_total{type,success}`; duration histogram | Wrap handler |
|
||||||
|
| Ownership negotiation | `cart_ownership_attempts_total{result}` | result=accepted,rejected,timeout |
|
||||||
|
| Remote latency | `cart_remote_mutation_seconds{method}` | Use client interceptors |
|
||||||
|
| Pings | `cart_remote_missed_pings_total{host}` | Already count, expose |
|
||||||
|
| Checkout flow | `checkout_attempts_total`, `checkout_failures_total` | Differentiate Klarna vs internal errors |
|
||||||
|
| Tracing | Span: HTTP handler → SyncedPool.Apply → (Remote?) gRPC → mutation handler | Add OpenTelemetry instrumentation |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Performance & Scalability
|
||||||
|
|
||||||
|
| Concern | Idea | Trade-Off |
|
||||||
|
|---------|------|-----------|
|
||||||
|
| High mutation rate on single cart | Introduce optional mutation queue (serialize explicitly) | Slight latency increase per op |
|
||||||
|
| Remote call overhead | Add client-side gRPC pooling & per-host circuit breaker | Complexity vs resilience |
|
||||||
|
| TTL purge efficiency | Use min-heap or timing wheel instead of slice scan | More code, better big-N performance |
|
||||||
|
| Batch network latency | Add `BatchMutate` RPC (list of mutations applied atomically) | Lost single-op simplicity |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Reliability Features
|
||||||
|
|
||||||
|
| Feature | Description | Priority |
|
||||||
|
|---------|-------------|----------|
|
||||||
|
| Lease fencing token | Include `ownership_version` in all remote mutate requests | M |
|
||||||
|
| Retry policy | Limited retry for transient network errors (idempotent mutations only) | L |
|
||||||
|
| Dead host reconciliation | On host removal, proactively attempt re-acquire of its carts | M |
|
||||||
|
| Drain mode | Node marks itself “draining” → refuses new ownership claims | M |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Security & Hardening
|
||||||
|
|
||||||
|
| Area | Next Step | Detail |
|
||||||
|
|------|-----------|--------|
|
||||||
|
| Transport | mTLS on gRPC | Use SPIFFE IDs or simple CA |
|
||||||
|
| AuthN/AuthZ | Interceptor enforcing service token | Inject metadata header |
|
||||||
|
| Input validation | Strengthen JSON decode responses | Disallow unknown fields globally |
|
||||||
|
| Rate limiting | Per-IP / per-cart throttling | Guard hotspot abuse |
|
||||||
|
| Multi-tenancy | Tenant id dimension in cart id or metadata | Partition metrics & ownership |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Testing Strategy Enhancements
|
||||||
|
|
||||||
|
| Gap | Improvement |
|
||||||
|
|-----|------------|
|
||||||
|
| No multi-node integration test in CI | Spin ephemeral in-process servers on randomized ports |
|
||||||
|
| Mutation regression | Table-driven tests auto-discover handlers via registry |
|
||||||
|
| Ownership race | Stress test: concurrent Apply on same new cart id from N goroutines |
|
||||||
|
| Checkout external dependency | Klarna mock server (HTTptest) + deterministic responses |
|
||||||
|
| Fuzzing | Fuzz `BuildCheckoutOrderPayload` & mutation handlers for panics |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Cleanup / Tech Debt
|
||||||
|
|
||||||
|
| Item | Action |
|
||||||
|
|------|--------|
|
||||||
|
| Remove deprecated proto remnants (CreateCheckoutOrder, Checkout RPC) | Delete & regenerate |
|
||||||
|
| Consolidate duplicate tax computations | Single helper with tax config |
|
||||||
|
| Delivery price hard-coded (4900) | Config or pricing strategy interface |
|
||||||
|
| Mixed naming (camel vs snake JSON historically) | Provide stable external API doc; accept old forms if needed |
|
||||||
|
| Manual remote mutation switch (if still present) | Replace with generated outbound registry |
|
||||||
|
| Mixed error responses (string bodies) | Standardize JSON: `{ "error": "...", "code": 400 }` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Potential Future Features
|
||||||
|
|
||||||
|
| Feature | Value | Complexity |
|
||||||
|
|---------|-------|------------|
|
||||||
|
| Streaming `WatchState` RPC | Real-time cart updates for clients | Medium |
|
||||||
|
| Event sourcing / audit log | Replay, analytics, debugging | High |
|
||||||
|
| Promotion / coupon engine plugin | Business extensibility | Medium |
|
||||||
|
| Partial cart reservation / inventory lock | Stock accuracy under concurrency | High |
|
||||||
|
| Multi-currency pricing | Globalization | Medium |
|
||||||
|
| GraphQL facade | Client flexibility | Medium |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. Suggested Prioritized Backlog (Condensed)
|
||||||
|
|
||||||
|
1. Coverage test + decode error mapping (P0)
|
||||||
|
2. Proto regeneration & cleanup (P0)
|
||||||
|
3. Metrics wrapper for registry (P1)
|
||||||
|
4. Multi-node ownership integration test (P1)
|
||||||
|
5. Delivery pricing abstraction (P2)
|
||||||
|
6. Lease version in remote RPCs (P2)
|
||||||
|
7. BatchMutate evaluation (P3)
|
||||||
|
8. TLS / auth hardening (P3) if going multi-tenant/public
|
||||||
|
9. Event sourcing (Evaluate after stability) (P4)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. Simplifying the Developer Workflow
|
||||||
|
|
||||||
|
| Pain | Simplifier |
|
||||||
|
|------|------------|
|
||||||
|
| Manual mutation boilerplate | Code generator for registry stubs |
|
||||||
|
| Forgetting totals | Enforce WithTotals lint: fail if mutation touches items/deliveries without flag |
|
||||||
|
| Hard to inspect remote ownership | `/internal/ownership` debug endpoint (JSON of local + remoteIndex) |
|
||||||
|
| Hard to see mutation timings | Add `?debug=latency` header to return per-mutation durations |
|
||||||
|
| Cookie dev confusion (Secure flag) | Env var: `DEV_INSECURE_COOKIES=1` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 13. Example: Mutation Codegen Sketch (Future)
|
||||||
|
|
||||||
|
Input: cart_actor.proto
|
||||||
|
Output: `mutation_auto.go`
|
||||||
|
- Detect messages used in RPC wrappers (e.g., `AddItemRequest` → payload field).
|
||||||
|
- Generate `RegisterMutation` template if handler not found.
|
||||||
|
- Mark with `// TODO implement logic`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 14. Risk / Impact Matrix (Abbreviated)
|
||||||
|
|
||||||
|
| Change | Risk | Mitigation |
|
||||||
|
|--------|------|-----------|
|
||||||
|
| Replace remote switch with registry | Possible missing registration → runtime error | Coverage test gating CI |
|
||||||
|
| Lease introduction | Split-brain if version mishandled | Increment + assert monotonic; test race |
|
||||||
|
| BatchMutate | Large atomic operations starving others | Size limits & fair scheduling |
|
||||||
|
| Event sourcing | Storage + replay complexity | Start with append-only log + compaction job |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 15. Contributing Workflow (Proposed)
|
||||||
|
|
||||||
|
1. Add / modify proto → run `make protogen`
|
||||||
|
2. Implement mutation logic → add `RegisterMutation` invocation
|
||||||
|
3. Add/Update tests (unit + integration)
|
||||||
|
4. Run `make verify` (lint, test, coverage, proto diff)
|
||||||
|
5. Open PR (template auto-checklist referencing this TODO)
|
||||||
|
6. Merge requires green CI + coverage threshold
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 16. Open Questions
|
||||||
|
|
||||||
|
| Question | Notes |
|
||||||
|
|----------|-------|
|
||||||
|
| Do we need sticky sessions for HTTP layer scaling? | Currently cart id routing suffices |
|
||||||
|
| Should deliveries prune invalid line references on SetCartRequest? | Inconsistency risk; add optional cleanup |
|
||||||
|
| Is checkout idempotency strict enough? | Multiple create vs update semantics |
|
||||||
|
| Add version field to CartState for optimistic concurrency? | Could enable external CAS writes |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 17. Tracking
|
||||||
|
|
||||||
|
Mark any completed tasks with `[x]`:
|
||||||
|
|
||||||
|
- [ ] Coverage test
|
||||||
|
- [ ] Decode helper + 400 mapping
|
||||||
|
- [ ] Proto cleanup
|
||||||
|
- [ ] Registry metrics instrumentation
|
||||||
|
- [ ] Ownership multi-node test
|
||||||
|
- [ ] Lease versioning
|
||||||
|
- [ ] Delivery pricing abstraction
|
||||||
|
- [ ] TLS/mTLS internal
|
||||||
|
- [ ] BatchMutate design doc
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
_Last updated: roadmap draft – refine after first metrics & scaling test run._
|
||||||
@@ -1,83 +1,61 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log"
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
|
||||||
amqp "github.com/rabbitmq/amqp091-go"
|
amqp "github.com/rabbitmq/amqp091-go"
|
||||||
)
|
)
|
||||||
|
|
||||||
type AmqpOrderHandler struct {
|
type AmqpOrderHandler struct {
|
||||||
Url string
|
Url string
|
||||||
connection *amqp.Connection
|
Connection *amqp.Connection
|
||||||
//channel *amqp.Channel
|
Channel *amqp.Channel
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
func (h *AmqpOrderHandler) Connect() error {
|
||||||
topic = "order-placed"
|
conn, err := amqp.Dial(h.Url)
|
||||||
)
|
|
||||||
|
|
||||||
func (t *AmqpOrderHandler) Connect() error {
|
|
||||||
|
|
||||||
conn, err := amqp.DialConfig(t.Url, amqp.Config{
|
|
||||||
//Vhost: "/",
|
|
||||||
Properties: amqp.NewConnectionProperties(),
|
|
||||||
})
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return fmt.Errorf("failed to connect to RabbitMQ: %w", err)
|
||||||
}
|
}
|
||||||
t.connection = conn
|
h.Connection = conn
|
||||||
|
|
||||||
ch, err := conn.Channel()
|
ch, err := conn.Channel()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return fmt.Errorf("failed to open a channel: %w", err)
|
||||||
}
|
|
||||||
defer ch.Close()
|
|
||||||
if err := ch.ExchangeDeclare(
|
|
||||||
topic, // name
|
|
||||||
"topic", // type
|
|
||||||
true, // durable
|
|
||||||
false, // auto-delete
|
|
||||||
false, // internal
|
|
||||||
false, // noWait
|
|
||||||
nil, // arguments
|
|
||||||
); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, err = ch.QueueDeclare(
|
|
||||||
topic, // name of the queue
|
|
||||||
true, // durable
|
|
||||||
false, // delete when unused
|
|
||||||
false, // exclusive
|
|
||||||
false, // noWait
|
|
||||||
nil, // arguments
|
|
||||||
); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
|
h.Channel = ch
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *AmqpOrderHandler) Close() error {
|
func (h *AmqpOrderHandler) Close() error {
|
||||||
log.Println("Closing master channel")
|
if h.Channel != nil {
|
||||||
return t.connection.Close()
|
h.Channel.Close()
|
||||||
//return t.channel.Close()
|
}
|
||||||
|
if h.Connection != nil {
|
||||||
|
return h.Connection.Close()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (t *AmqpOrderHandler) OrderCompleted(data []byte) error {
|
func (h *AmqpOrderHandler) OrderCompleted(body []byte) error {
|
||||||
ch, err := t.connection.Channel()
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||||
if err != nil {
|
defer cancel()
|
||||||
return err
|
|
||||||
}
|
err := h.Channel.PublishWithContext(ctx,
|
||||||
defer ch.Close()
|
"orders", // exchange
|
||||||
return ch.Publish(
|
"new", // routing key
|
||||||
topic,
|
false, // mandatory
|
||||||
topic,
|
false, // immediate
|
||||||
true,
|
|
||||||
false,
|
|
||||||
amqp.Publishing{
|
amqp.Publishing{
|
||||||
ContentType: "application/json",
|
ContentType: "application/json",
|
||||||
Body: data,
|
Body: body,
|
||||||
},
|
})
|
||||||
)
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to publish a message: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|||||||
367
cart-grain.go
367
cart-grain.go
@@ -1,13 +1,9 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
|
||||||
"slices"
|
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
|
||||||
|
|
||||||
messages "git.tornberg.me/go-cart-actor/proto"
|
messages "git.tornberg.me/go-cart-actor/proto"
|
||||||
)
|
)
|
||||||
@@ -93,7 +89,6 @@ type CartGrain struct {
|
|||||||
mu sync.RWMutex
|
mu sync.RWMutex
|
||||||
lastItemId int
|
lastItemId int
|
||||||
lastDeliveryId int
|
lastDeliveryId int
|
||||||
storageMessages []Message
|
|
||||||
Id CartId `json:"id"`
|
Id CartId `json:"id"`
|
||||||
Items []*CartItem `json:"items"`
|
Items []*CartItem `json:"items"`
|
||||||
TotalPrice int64 `json:"totalPrice"`
|
TotalPrice int64 `json:"totalPrice"`
|
||||||
@@ -108,8 +103,8 @@ type CartGrain struct {
|
|||||||
|
|
||||||
type Grain interface {
|
type Grain interface {
|
||||||
GetId() CartId
|
GetId() CartId
|
||||||
HandleMessage(message *Message, isReplay bool) (*FrameWithPayload, error)
|
Apply(content interface{}, isReplay bool) (*CartGrain, error)
|
||||||
GetCurrentState() (*FrameWithPayload, error)
|
GetCurrentState() (*CartGrain, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *CartGrain) GetId() CartId {
|
func (c *CartGrain) GetId() CartId {
|
||||||
@@ -117,20 +112,12 @@ func (c *CartGrain) GetId() CartId {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *CartGrain) GetLastChange() int64 {
|
func (c *CartGrain) GetLastChange() int64 {
|
||||||
if len(c.storageMessages) == 0 {
|
// Legacy event log removed; return 0 to indicate no persisted mutation history.
|
||||||
return 0
|
return 0
|
||||||
}
|
|
||||||
return *c.storageMessages[len(c.storageMessages)-1].TimeStamp
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *CartGrain) GetCurrentState() (*FrameWithPayload, error) {
|
func (c *CartGrain) GetCurrentState() (*CartGrain, error) {
|
||||||
result, err := json.Marshal(c)
|
return c, nil
|
||||||
if err != nil {
|
|
||||||
ret := MakeFrameWithPayload(0, 400, []byte(err.Error()))
|
|
||||||
return &ret, nil
|
|
||||||
}
|
|
||||||
ret := MakeFrameWithPayload(0, 200, result)
|
|
||||||
return &ret, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func getInt(data float64, ok bool) (int, error) {
|
func getInt(data float64, ok bool) (int, error) {
|
||||||
@@ -201,30 +188,23 @@ func getItemData(sku string, qty int, country string) (*messages.AddItem, error)
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *CartGrain) AddItem(sku string, qty int, country string, storeId *string) (*FrameWithPayload, error) {
|
func (c *CartGrain) AddItem(sku string, qty int, country string, storeId *string) (*CartGrain, error) {
|
||||||
cartItem, err := getItemData(sku, qty, country)
|
cartItem, err := getItemData(sku, qty, country)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
cartItem.StoreId = storeId
|
cartItem.StoreId = storeId
|
||||||
return c.HandleMessage(&Message{
|
return c.Apply(cartItem, false)
|
||||||
Type: 2,
|
|
||||||
Content: cartItem,
|
|
||||||
}, false)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *CartGrain) GetStorageMessage(since int64) []StorableMessage {
|
/*
|
||||||
c.mu.RLock()
|
Legacy storage (event sourcing) removed in oneof refactor.
|
||||||
defer c.mu.RUnlock()
|
Kept stub (commented) for potential future reintroduction using proto envelopes.
|
||||||
ret := make([]StorableMessage, 0)
|
|
||||||
|
|
||||||
for _, message := range c.storageMessages {
|
func (c *CartGrain) GetStorageMessage(since int64) []interface{} {
|
||||||
if *message.TimeStamp > since {
|
return nil
|
||||||
ret = append(ret, message)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return ret
|
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
func (c *CartGrain) GetState() ([]byte, error) {
|
func (c *CartGrain) GetState() ([]byte, error) {
|
||||||
return json.Marshal(c)
|
return json.Marshal(c)
|
||||||
@@ -279,324 +259,17 @@ func GetTaxAmount(total int64, tax int) int64 {
|
|||||||
return int64(float64(total) / float64((1 + taxD)))
|
return int64(float64(total) / float64((1 + taxD)))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *CartGrain) HandleMessage(message *Message, isReplay bool) (*FrameWithPayload, error) {
|
func (c *CartGrain) Apply(content interface{}, isReplay bool) (*CartGrain, error) {
|
||||||
if message.TimeStamp == nil {
|
|
||||||
now := time.Now().Unix()
|
|
||||||
message.TimeStamp = &now
|
|
||||||
}
|
|
||||||
grainMutations.Inc()
|
grainMutations.Inc()
|
||||||
var err error
|
|
||||||
switch message.Type {
|
|
||||||
case SetCartItemsType:
|
|
||||||
msg, ok := message.Content.(*messages.SetCartRequest)
|
|
||||||
if !ok {
|
|
||||||
err = fmt.Errorf("expected SetCartItems")
|
|
||||||
} else {
|
|
||||||
|
|
||||||
c.mu.Lock()
|
updated, err := ApplyRegistered(c, content)
|
||||||
c.Items = make([]*CartItem, 0, len(msg.Items))
|
|
||||||
c.mu.Unlock()
|
|
||||||
for _, item := range msg.Items {
|
|
||||||
c.AddItem(item.Sku, int(item.Quantity), item.Country, item.StoreId)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
case AddRequestType:
|
|
||||||
msg, ok := message.Content.(*messages.AddRequest)
|
|
||||||
if !ok {
|
|
||||||
err = fmt.Errorf("expected AddRequest")
|
|
||||||
} else {
|
|
||||||
|
|
||||||
existingItem, found := c.FindItemWithSku(msg.Sku)
|
|
||||||
if found {
|
|
||||||
existingItem.Quantity += int(msg.Quantity)
|
|
||||||
c.UpdateTotals()
|
|
||||||
} else {
|
|
||||||
return c.AddItem(msg.Sku, int(msg.Quantity), msg.Country, msg.StoreId)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
case AddItemType:
|
|
||||||
msg, ok := message.Content.(*messages.AddItem)
|
|
||||||
if !ok {
|
|
||||||
err = fmt.Errorf("expected AddItem")
|
|
||||||
} else {
|
|
||||||
|
|
||||||
if msg.Quantity < 1 {
|
|
||||||
return nil, fmt.Errorf("invalid quantity")
|
|
||||||
}
|
|
||||||
existingItem, found := c.FindItemWithSku(msg.Sku)
|
|
||||||
if found {
|
|
||||||
existingItem.Quantity += int(msg.Quantity)
|
|
||||||
c.UpdateTotals()
|
|
||||||
} else {
|
|
||||||
c.mu.Lock()
|
|
||||||
c.lastItemId++
|
|
||||||
tax := 2500
|
|
||||||
if msg.Tax > 0 {
|
|
||||||
tax = int(msg.Tax)
|
|
||||||
}
|
|
||||||
|
|
||||||
taxAmount := GetTaxAmount(msg.Price, tax)
|
|
||||||
|
|
||||||
c.Items = append(c.Items, &CartItem{
|
|
||||||
Id: c.lastItemId,
|
|
||||||
ItemId: int(msg.ItemId),
|
|
||||||
Quantity: int(msg.Quantity),
|
|
||||||
Sku: msg.Sku,
|
|
||||||
Name: msg.Name,
|
|
||||||
Price: msg.Price,
|
|
||||||
TotalPrice: msg.Price * int64(msg.Quantity),
|
|
||||||
TotalTax: int64(taxAmount * int64(msg.Quantity)),
|
|
||||||
Image: msg.Image,
|
|
||||||
Stock: StockStatus(msg.Stock),
|
|
||||||
Disclaimer: msg.Disclaimer,
|
|
||||||
Brand: msg.Brand,
|
|
||||||
Category: msg.Category,
|
|
||||||
Category2: msg.Category2,
|
|
||||||
Category3: msg.Category3,
|
|
||||||
Category4: msg.Category4,
|
|
||||||
Category5: msg.Category5,
|
|
||||||
OrgPrice: msg.OrgPrice,
|
|
||||||
ArticleType: msg.ArticleType,
|
|
||||||
Outlet: msg.Outlet,
|
|
||||||
SellerId: msg.SellerId,
|
|
||||||
SellerName: msg.SellerName,
|
|
||||||
Tax: int(taxAmount),
|
|
||||||
TaxRate: tax,
|
|
||||||
StoreId: msg.StoreId,
|
|
||||||
})
|
|
||||||
c.UpdateTotals()
|
|
||||||
c.mu.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
case ChangeQuantityType:
|
|
||||||
msg, ok := message.Content.(*messages.ChangeQuantity)
|
|
||||||
if !ok {
|
|
||||||
err = fmt.Errorf("expected ChangeQuantity")
|
|
||||||
} else {
|
|
||||||
|
|
||||||
for i, item := range c.Items {
|
|
||||||
if item.Id == int(msg.Id) {
|
|
||||||
if msg.Quantity <= 0 {
|
|
||||||
//c.TotalPrice -= item.Price * int64(item.Quantity)
|
|
||||||
c.Items = append(c.Items[:i], c.Items[i+1:]...)
|
|
||||||
} else {
|
|
||||||
//diff := int(msg.Quantity) - item.Quantity
|
|
||||||
item.Quantity = int(msg.Quantity)
|
|
||||||
//c.TotalPrice += item.Price * int64(diff)
|
|
||||||
}
|
|
||||||
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c.UpdateTotals()
|
|
||||||
|
|
||||||
}
|
|
||||||
case RemoveItemType:
|
|
||||||
msg, ok := message.Content.(*messages.RemoveItem)
|
|
||||||
if !ok {
|
|
||||||
err = fmt.Errorf("expected RemoveItem")
|
|
||||||
} else {
|
|
||||||
|
|
||||||
items := make([]*CartItem, 0, len(c.Items))
|
|
||||||
for _, item := range c.Items {
|
|
||||||
if item.Id == int(msg.Id) {
|
|
||||||
//c.TotalPrice -= item.Price * int64(item.Quantity)
|
|
||||||
} else {
|
|
||||||
items = append(items, item)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c.Items = items
|
|
||||||
c.UpdateTotals()
|
|
||||||
}
|
|
||||||
case SetDeliveryType:
|
|
||||||
msg, ok := message.Content.(*messages.SetDelivery)
|
|
||||||
if !ok {
|
|
||||||
err = fmt.Errorf("expected SetDelivery")
|
|
||||||
} else {
|
|
||||||
|
|
||||||
c.lastDeliveryId++
|
|
||||||
items := make([]int, 0)
|
|
||||||
withDelivery := c.ItemsWithDelivery()
|
|
||||||
if len(msg.Items) == 0 {
|
|
||||||
items = append(items, c.ItemsWithoutDelivery()...)
|
|
||||||
} else {
|
|
||||||
for _, id := range msg.Items {
|
|
||||||
for _, item := range c.Items {
|
|
||||||
if item.Id == int(id) {
|
|
||||||
if slices.Contains(withDelivery, item.Id) {
|
|
||||||
return nil, fmt.Errorf("item already has delivery")
|
|
||||||
}
|
|
||||||
items = append(items, int(item.Id))
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(items) > 0 {
|
|
||||||
c.Deliveries = append(c.Deliveries, &CartDelivery{
|
|
||||||
Id: c.lastDeliveryId,
|
|
||||||
Provider: msg.Provider,
|
|
||||||
PickupPoint: msg.PickupPoint,
|
|
||||||
Price: 4900,
|
|
||||||
Items: items,
|
|
||||||
})
|
|
||||||
|
|
||||||
c.UpdateTotals()
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
case RemoveDeliveryType:
|
|
||||||
msg, ok := message.Content.(*messages.RemoveDelivery)
|
|
||||||
if !ok {
|
|
||||||
err = fmt.Errorf("expected RemoveDelivery")
|
|
||||||
} else {
|
|
||||||
|
|
||||||
deliveries := make([]*CartDelivery, 0, len(c.Deliveries))
|
|
||||||
for _, delivery := range c.Deliveries {
|
|
||||||
if delivery.Id == int(msg.Id) {
|
|
||||||
c.TotalPrice -= delivery.Price
|
|
||||||
} else {
|
|
||||||
deliveries = append(deliveries, delivery)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c.Deliveries = deliveries
|
|
||||||
c.UpdateTotals()
|
|
||||||
}
|
|
||||||
case SetPickupPointType:
|
|
||||||
msg, ok := message.Content.(*messages.SetPickupPoint)
|
|
||||||
if !ok {
|
|
||||||
err = fmt.Errorf("expected SetPickupPoint")
|
|
||||||
} else {
|
|
||||||
|
|
||||||
for _, delivery := range c.Deliveries {
|
|
||||||
if delivery.Id == int(msg.DeliveryId) {
|
|
||||||
delivery.PickupPoint = &messages.PickupPoint{
|
|
||||||
Id: msg.Id,
|
|
||||||
Address: msg.Address,
|
|
||||||
City: msg.City,
|
|
||||||
Zip: msg.Zip,
|
|
||||||
Country: msg.Country,
|
|
||||||
Name: msg.Name,
|
|
||||||
}
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
case CreateCheckoutOrderType:
|
|
||||||
msg, ok := message.Content.(*messages.CreateCheckoutOrder)
|
|
||||||
if !ok {
|
|
||||||
err = fmt.Errorf("expected CreateCheckoutOrder")
|
|
||||||
} else {
|
|
||||||
|
|
||||||
orderLines := make([]*Line, 0, len(c.Items))
|
|
||||||
|
|
||||||
c.PaymentInProgress = true
|
|
||||||
c.Processing = true
|
|
||||||
for _, item := range c.Items {
|
|
||||||
|
|
||||||
orderLines = append(orderLines, &Line{
|
|
||||||
Type: "physical",
|
|
||||||
Reference: item.Sku,
|
|
||||||
Name: item.Name,
|
|
||||||
Quantity: item.Quantity,
|
|
||||||
UnitPrice: int(item.Price),
|
|
||||||
TaxRate: 2500, // item.TaxRate,
|
|
||||||
QuantityUnit: "st",
|
|
||||||
TotalAmount: int(item.TotalPrice),
|
|
||||||
TotalTaxAmount: int(item.TotalTax),
|
|
||||||
ImageURL: fmt.Sprintf("https://www.elgiganten.se%s", item.Image),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
for _, line := range c.Deliveries {
|
|
||||||
if line.Price > 0 {
|
|
||||||
orderLines = append(orderLines, &Line{
|
|
||||||
Type: "shipping_fee",
|
|
||||||
Reference: line.Provider,
|
|
||||||
Name: "Delivery",
|
|
||||||
Quantity: 1,
|
|
||||||
UnitPrice: int(line.Price),
|
|
||||||
TaxRate: 2500, // item.TaxRate,
|
|
||||||
QuantityUnit: "st",
|
|
||||||
TotalAmount: int(line.Price),
|
|
||||||
TotalTaxAmount: int(GetTaxAmount(line.Price, 2500)),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
order := CheckoutOrder{
|
|
||||||
PurchaseCountry: "SE",
|
|
||||||
PurchaseCurrency: "SEK",
|
|
||||||
Locale: "sv-se",
|
|
||||||
OrderAmount: int(c.TotalPrice),
|
|
||||||
OrderTaxAmount: int(c.TotalTax),
|
|
||||||
OrderLines: orderLines,
|
|
||||||
MerchantReference1: c.Id.String(),
|
|
||||||
MerchantURLS: &CheckoutMerchantURLS{
|
|
||||||
Terms: msg.Terms,
|
|
||||||
Checkout: msg.Checkout,
|
|
||||||
Confirmation: msg.Confirmation,
|
|
||||||
Validation: msg.Validation,
|
|
||||||
Push: msg.Push,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
orderPayload, err := json.Marshal(order)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
var klarnaOrder *CheckoutOrder
|
|
||||||
if c.OrderReference != "" {
|
|
||||||
log.Printf("Updating order id %s", c.OrderReference)
|
|
||||||
klarnaOrder, err = KlarnaInstance.UpdateOrder(c.OrderReference, bytes.NewReader(orderPayload))
|
|
||||||
} else {
|
|
||||||
klarnaOrder, err = KlarnaInstance.CreateOrder(bytes.NewReader(orderPayload))
|
|
||||||
}
|
|
||||||
// log.Printf("Order result: %+v", klarnaOrder)
|
|
||||||
if nil != err {
|
|
||||||
log.Printf("error from klarna: %v", err)
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if c.OrderReference == "" {
|
|
||||||
c.OrderReference = klarnaOrder.ID
|
|
||||||
c.PaymentStatus = klarnaOrder.Status
|
|
||||||
}
|
|
||||||
|
|
||||||
orderData, err := json.Marshal(klarnaOrder)
|
|
||||||
if nil != err {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
result := MakeFrameWithPayload(RemoteCreateOrderReply, 200, orderData)
|
|
||||||
return &result, nil
|
|
||||||
}
|
|
||||||
case OrderCompletedType:
|
|
||||||
msg, ok := message.Content.(*messages.OrderCreated)
|
|
||||||
if !ok {
|
|
||||||
log.Printf("expected OrderCompleted, got %T", message.Content)
|
|
||||||
err = fmt.Errorf("expected OrderCompleted")
|
|
||||||
} else {
|
|
||||||
c.OrderReference = msg.OrderId
|
|
||||||
c.PaymentStatus = msg.Status
|
|
||||||
c.PaymentInProgress = false
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
err = fmt.Errorf("unknown message type %d", message.Type)
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
if err == ErrMutationNotRegistered {
|
||||||
|
return nil, fmt.Errorf("unsupported mutation type %T (not registered)", content)
|
||||||
|
}
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
return updated, nil
|
||||||
if !isReplay {
|
|
||||||
c.mu.Lock()
|
|
||||||
c.storageMessages = append(c.storageMessages, *message)
|
|
||||||
c.mu.Unlock()
|
|
||||||
}
|
|
||||||
result, err := json.Marshal(c)
|
|
||||||
msg := MakeFrameWithPayload(RemoteHandleMutationReply, 200, result)
|
|
||||||
return &msg, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *CartGrain) UpdateTotals() {
|
func (c *CartGrain) UpdateTotals() {
|
||||||
|
|||||||
211
cart_state_mapper.go
Normal file
211
cart_state_mapper.go
Normal file
@@ -0,0 +1,211 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
messages "git.tornberg.me/go-cart-actor/proto"
|
||||||
|
)
|
||||||
|
|
||||||
|
// cart_state_mapper.go
|
||||||
|
//
|
||||||
|
// Utilities to translate between internal CartGrain state and the gRPC
|
||||||
|
// (typed) protobuf representation CartState. This replaces the previous
|
||||||
|
// JSON blob framing and enables type-safe replies over gRPC, as well as
|
||||||
|
// internal reuse for HTTP handlers without an extra marshal / unmarshal
|
||||||
|
// hop (you can marshal CartState directly for JSON responses if desired).
|
||||||
|
//
|
||||||
|
// Only the one‑way mapping (CartGrain -> CartState) is strictly required
|
||||||
|
// for mutation / state replies. A reverse helper is included in case
|
||||||
|
// future features (e.g. snapshot import, replay, or migration) need it.
|
||||||
|
|
||||||
|
// ToCartState converts the in‑memory CartGrain into a protobuf CartState.
|
||||||
|
func ToCartState(c *CartGrain) *messages.CartState {
|
||||||
|
if c == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
items := make([]*messages.CartItemState, 0, len(c.Items))
|
||||||
|
for _, it := range c.Items {
|
||||||
|
if it == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
itemDiscountPerUnit := max(0, it.OrgPrice-it.Price)
|
||||||
|
itemTotalDiscount := itemDiscountPerUnit * int64(it.Quantity)
|
||||||
|
|
||||||
|
items = append(items, &messages.CartItemState{
|
||||||
|
Id: int64(it.Id),
|
||||||
|
SourceItemId: int64(it.ItemId),
|
||||||
|
Sku: it.Sku,
|
||||||
|
Name: it.Name,
|
||||||
|
UnitPrice: it.Price,
|
||||||
|
Quantity: int32(it.Quantity),
|
||||||
|
TotalPrice: it.TotalPrice,
|
||||||
|
TotalTax: it.TotalTax,
|
||||||
|
OrgPrice: it.OrgPrice,
|
||||||
|
TaxRate: int32(it.TaxRate),
|
||||||
|
TotalDiscount: itemTotalDiscount,
|
||||||
|
Brand: it.Brand,
|
||||||
|
Category: it.Category,
|
||||||
|
Category2: it.Category2,
|
||||||
|
Category3: it.Category3,
|
||||||
|
Category4: it.Category4,
|
||||||
|
Category5: it.Category5,
|
||||||
|
Image: it.Image,
|
||||||
|
ArticleType: it.ArticleType,
|
||||||
|
SellerId: it.SellerId,
|
||||||
|
SellerName: it.SellerName,
|
||||||
|
Disclaimer: it.Disclaimer,
|
||||||
|
Outlet: deref(it.Outlet),
|
||||||
|
StoreId: deref(it.StoreId),
|
||||||
|
Stock: int32(it.Stock),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
deliveries := make([]*messages.DeliveryState, 0, len(c.Deliveries))
|
||||||
|
for _, d := range c.Deliveries {
|
||||||
|
if d == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
itemIds := make([]int64, 0, len(d.Items))
|
||||||
|
for _, id := range d.Items {
|
||||||
|
itemIds = append(itemIds, int64(id))
|
||||||
|
}
|
||||||
|
var pp *messages.PickupPoint
|
||||||
|
if d.PickupPoint != nil {
|
||||||
|
// Copy to avoid accidental shared mutation (proto points are fine but explicit).
|
||||||
|
pp = &messages.PickupPoint{
|
||||||
|
Id: d.PickupPoint.Id,
|
||||||
|
Name: d.PickupPoint.Name,
|
||||||
|
Address: d.PickupPoint.Address,
|
||||||
|
City: d.PickupPoint.City,
|
||||||
|
Zip: d.PickupPoint.Zip,
|
||||||
|
Country: d.PickupPoint.Country,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
deliveries = append(deliveries, &messages.DeliveryState{
|
||||||
|
Id: int64(d.Id),
|
||||||
|
Provider: d.Provider,
|
||||||
|
Price: d.Price,
|
||||||
|
ItemIds: itemIds,
|
||||||
|
PickupPoint: pp,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return &messages.CartState{
|
||||||
|
CartId: c.Id.String(),
|
||||||
|
Items: items,
|
||||||
|
TotalPrice: c.TotalPrice,
|
||||||
|
TotalTax: c.TotalTax,
|
||||||
|
TotalDiscount: c.TotalDiscount,
|
||||||
|
Deliveries: deliveries,
|
||||||
|
PaymentInProgress: c.PaymentInProgress,
|
||||||
|
OrderReference: c.OrderReference,
|
||||||
|
PaymentStatus: c.PaymentStatus,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// FromCartState merges a protobuf CartState into an existing CartGrain.
|
||||||
|
// This is optional and primarily useful for snapshot import or testing.
|
||||||
|
func FromCartState(cs *messages.CartState, g *CartGrain) *CartGrain {
|
||||||
|
if cs == nil {
|
||||||
|
return g
|
||||||
|
}
|
||||||
|
if g == nil {
|
||||||
|
g = &CartGrain{}
|
||||||
|
}
|
||||||
|
g.Id = ToCartId(cs.CartId)
|
||||||
|
g.TotalPrice = cs.TotalPrice
|
||||||
|
g.TotalTax = cs.TotalTax
|
||||||
|
g.TotalDiscount = cs.TotalDiscount
|
||||||
|
g.PaymentInProgress = cs.PaymentInProgress
|
||||||
|
g.OrderReference = cs.OrderReference
|
||||||
|
g.PaymentStatus = cs.PaymentStatus
|
||||||
|
|
||||||
|
// Items
|
||||||
|
g.Items = g.Items[:0]
|
||||||
|
for _, it := range cs.Items {
|
||||||
|
if it == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
outlet := toPtr(it.Outlet)
|
||||||
|
storeId := toPtr(it.StoreId)
|
||||||
|
g.Items = append(g.Items, &CartItem{
|
||||||
|
Id: int(it.Id),
|
||||||
|
ItemId: int(it.SourceItemId),
|
||||||
|
Sku: it.Sku,
|
||||||
|
Name: it.Name,
|
||||||
|
Price: it.UnitPrice,
|
||||||
|
Quantity: int(it.Quantity),
|
||||||
|
TotalPrice: it.TotalPrice,
|
||||||
|
TotalTax: it.TotalTax,
|
||||||
|
OrgPrice: it.OrgPrice,
|
||||||
|
TaxRate: int(it.TaxRate),
|
||||||
|
Brand: it.Brand,
|
||||||
|
Category: it.Category,
|
||||||
|
Category2: it.Category2,
|
||||||
|
Category3: it.Category3,
|
||||||
|
Category4: it.Category4,
|
||||||
|
Category5: it.Category5,
|
||||||
|
Image: it.Image,
|
||||||
|
ArticleType: it.ArticleType,
|
||||||
|
SellerId: it.SellerId,
|
||||||
|
SellerName: it.SellerName,
|
||||||
|
Disclaimer: it.Disclaimer,
|
||||||
|
Outlet: outlet,
|
||||||
|
StoreId: storeId,
|
||||||
|
Stock: StockStatus(it.Stock),
|
||||||
|
// Tax, TaxRate already set via Price / Totals if needed
|
||||||
|
})
|
||||||
|
if it.Id > int64(g.lastItemId) {
|
||||||
|
g.lastItemId = int(it.Id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deliveries
|
||||||
|
g.Deliveries = g.Deliveries[:0]
|
||||||
|
for _, d := range cs.Deliveries {
|
||||||
|
if d == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
intIds := make([]int, 0, len(d.ItemIds))
|
||||||
|
for _, id := range d.ItemIds {
|
||||||
|
intIds = append(intIds, int(id))
|
||||||
|
}
|
||||||
|
var pp *messages.PickupPoint
|
||||||
|
if d.PickupPoint != nil {
|
||||||
|
pp = &messages.PickupPoint{
|
||||||
|
Id: d.PickupPoint.Id,
|
||||||
|
Name: d.PickupPoint.Name,
|
||||||
|
Address: d.PickupPoint.Address,
|
||||||
|
City: d.PickupPoint.City,
|
||||||
|
Zip: d.PickupPoint.Zip,
|
||||||
|
Country: d.PickupPoint.Country,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
g.Deliveries = append(g.Deliveries, &CartDelivery{
|
||||||
|
Id: int(d.Id),
|
||||||
|
Provider: d.Provider,
|
||||||
|
Price: d.Price,
|
||||||
|
Items: intIds,
|
||||||
|
PickupPoint: pp,
|
||||||
|
})
|
||||||
|
if d.Id > int64(g.lastDeliveryId) {
|
||||||
|
g.lastDeliveryId = int(d.Id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return g
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper to safely de-reference optional string pointers to value or "".
|
||||||
|
func deref(p *string) string {
|
||||||
|
if p == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return *p
|
||||||
|
}
|
||||||
|
|
||||||
|
func toPtr(s string) *string {
|
||||||
|
if s == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &s
|
||||||
|
}
|
||||||
119
checkout_builder.go
Normal file
119
checkout_builder.go
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
)
|
||||||
|
|
||||||
|
// CheckoutMeta carries the external / URL metadata required to build a
|
||||||
|
// Klarna CheckoutOrder from a CartGrain snapshot. It deliberately excludes
|
||||||
|
// any Klarna-specific response fields (HTML snippet, client token, etc.).
|
||||||
|
type CheckoutMeta struct {
|
||||||
|
Terms string
|
||||||
|
Checkout string
|
||||||
|
Confirmation string
|
||||||
|
Validation string
|
||||||
|
Push string
|
||||||
|
Country string
|
||||||
|
Currency string // optional override (defaults to "SEK" if empty)
|
||||||
|
Locale string // optional override (defaults to "sv-se" if empty)
|
||||||
|
}
|
||||||
|
|
||||||
|
// BuildCheckoutOrderPayload converts the current cart grain + meta information
|
||||||
|
// into a CheckoutOrder domain struct and returns its JSON-serialized payload
|
||||||
|
// (to send to Klarna) alongside the structured CheckoutOrder object.
|
||||||
|
//
|
||||||
|
// This function is PURE: it does not perform any network I/O or mutate the
|
||||||
|
// grain. The caller is responsible for:
|
||||||
|
//
|
||||||
|
// 1. Choosing whether to create or update the Klarna order.
|
||||||
|
// 2. Invoking KlarnaClient.CreateOrder / UpdateOrder with the returned payload.
|
||||||
|
// 3. Applying an InitializeCheckout mutation (or equivalent) with the
|
||||||
|
// resulting Klarna order id + status.
|
||||||
|
//
|
||||||
|
// If you later need to support different tax rates per line, you can extend
|
||||||
|
// CartItem / Delivery to expose that data and propagate it here.
|
||||||
|
func BuildCheckoutOrderPayload(grain *CartGrain, meta *CheckoutMeta) ([]byte, *CheckoutOrder, error) {
|
||||||
|
if grain == nil {
|
||||||
|
return nil, nil, fmt.Errorf("nil grain")
|
||||||
|
}
|
||||||
|
if meta == nil {
|
||||||
|
return nil, nil, fmt.Errorf("nil checkout meta")
|
||||||
|
}
|
||||||
|
|
||||||
|
currency := meta.Currency
|
||||||
|
if currency == "" {
|
||||||
|
currency = "SEK"
|
||||||
|
}
|
||||||
|
locale := meta.Locale
|
||||||
|
if locale == "" {
|
||||||
|
locale = "sv-se"
|
||||||
|
}
|
||||||
|
country := meta.Country
|
||||||
|
if country == "" {
|
||||||
|
country = "SE" // sensible default; adjust if multi-country support changes
|
||||||
|
}
|
||||||
|
|
||||||
|
lines := make([]*Line, 0, len(grain.Items)+len(grain.Deliveries))
|
||||||
|
|
||||||
|
// Item lines
|
||||||
|
for _, it := range grain.Items {
|
||||||
|
if it == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
lines = append(lines, &Line{
|
||||||
|
Type: "physical",
|
||||||
|
Reference: it.Sku,
|
||||||
|
Name: it.Name,
|
||||||
|
Quantity: it.Quantity,
|
||||||
|
UnitPrice: int(it.Price),
|
||||||
|
TaxRate: 2500, // TODO: derive if variable tax rates are introduced
|
||||||
|
QuantityUnit: "st",
|
||||||
|
TotalAmount: int(it.TotalPrice),
|
||||||
|
TotalTaxAmount: int(it.TotalTax),
|
||||||
|
ImageURL: fmt.Sprintf("https://www.elgiganten.se%s", it.Image),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delivery lines
|
||||||
|
for _, d := range grain.Deliveries {
|
||||||
|
if d == nil || d.Price <= 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
lines = append(lines, &Line{
|
||||||
|
Type: "shipping_fee",
|
||||||
|
Reference: d.Provider,
|
||||||
|
Name: "Delivery",
|
||||||
|
Quantity: 1,
|
||||||
|
UnitPrice: int(d.Price),
|
||||||
|
TaxRate: 2500,
|
||||||
|
QuantityUnit: "st",
|
||||||
|
TotalAmount: int(d.Price),
|
||||||
|
TotalTaxAmount: int(GetTaxAmount(d.Price, 2500)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
order := &CheckoutOrder{
|
||||||
|
PurchaseCountry: country,
|
||||||
|
PurchaseCurrency: currency,
|
||||||
|
Locale: locale,
|
||||||
|
OrderAmount: int(grain.TotalPrice),
|
||||||
|
OrderTaxAmount: int(grain.TotalTax),
|
||||||
|
OrderLines: lines,
|
||||||
|
MerchantReference1: grain.Id.String(),
|
||||||
|
MerchantURLS: &CheckoutMerchantURLS{
|
||||||
|
Terms: meta.Terms,
|
||||||
|
Checkout: meta.Checkout,
|
||||||
|
Confirmation: meta.Confirmation,
|
||||||
|
Validation: meta.Validation,
|
||||||
|
Push: meta.Push,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
payload, err := json.Marshal(order)
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil, fmt.Errorf("marshal checkout order: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return payload, order, nil
|
||||||
|
}
|
||||||
5
cookies.txt
Normal file
5
cookies.txt
Normal file
@@ -0,0 +1,5 @@
|
|||||||
|
# Netscape HTTP Cookie File
|
||||||
|
# https://curl.se/docs/http-cookies.html
|
||||||
|
# This file was generated by libcurl! Edit at your own risk.
|
||||||
|
|
||||||
|
#HttpOnly_localhost FALSE / FALSE 1761304670 cartid 4393545184291837
|
||||||
@@ -3,7 +3,6 @@ package main
|
|||||||
import (
|
import (
|
||||||
"encoding/gob"
|
"encoding/gob"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
|
||||||
"os"
|
"os"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -23,59 +22,18 @@ func NewDiskStorage(stateFile string) (*DiskStorage, error) {
|
|||||||
return ret, err
|
return ret, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func saveMessages(messages []StorableMessage, id CartId) error {
|
func saveMessages(_ interface{}, _ CartId) error {
|
||||||
|
// No-op: legacy event log persistence removed in oneof refactor.
|
||||||
if len(messages) == 0 {
|
return nil
|
||||||
return nil
|
|
||||||
}
|
|
||||||
log.Printf("%d messages to save for grain id %s", len(messages), id)
|
|
||||||
var file *os.File
|
|
||||||
var err error
|
|
||||||
path := getCartPath(id.String())
|
|
||||||
file, err = os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
for _, m := range messages {
|
|
||||||
err := m.Write(file)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func getCartPath(id string) string {
|
func getCartPath(id string) string {
|
||||||
return fmt.Sprintf("data/%s.prot", id)
|
return fmt.Sprintf("data/%s.prot", id)
|
||||||
}
|
}
|
||||||
|
|
||||||
func loadMessages(grain Grain, id CartId) error {
|
func loadMessages(_ Grain, _ CartId) error {
|
||||||
var err error
|
// No-op: legacy replay removed in oneof refactor.
|
||||||
path := getCartPath(id.String())
|
return nil
|
||||||
|
|
||||||
file, err := os.Open(path)
|
|
||||||
if err != nil {
|
|
||||||
if os.IsNotExist(err) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
for err == nil {
|
|
||||||
var msg Message
|
|
||||||
err = ReadMessage(file, &msg)
|
|
||||||
if err == nil {
|
|
||||||
grain.HandleMessage(&msg, true)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if err.Error() == "EOF" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *DiskStorage) saveState() error {
|
func (s *DiskStorage) saveState() error {
|
||||||
@@ -103,15 +61,8 @@ func (s *DiskStorage) loadState() error {
|
|||||||
return gob.NewDecoder(file).Decode(&s.LastSaves)
|
return gob.NewDecoder(file).Decode(&s.LastSaves)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *DiskStorage) Store(id CartId, grain *CartGrain) error {
|
func (s *DiskStorage) Store(id CartId, _ *CartGrain) error {
|
||||||
lastSavedMessage, ok := s.LastSaves[id]
|
// With the removal of the legacy message log, we only update the timestamp.
|
||||||
if ok && lastSavedMessage > grain.GetLastChange() {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
err := saveMessages(grain.GetStorageMessage(lastSavedMessage), id)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
ts := time.Now().Unix()
|
ts := time.Now().Unix()
|
||||||
s.LastSaves[id] = ts
|
s.LastSaves[id] = ts
|
||||||
s.lastSave = ts
|
s.lastSave = ts
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -27,8 +26,8 @@ var (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type GrainPool interface {
|
type GrainPool interface {
|
||||||
Process(id CartId, messages ...Message) (*FrameWithPayload, error)
|
Apply(id CartId, mutation interface{}) (*CartGrain, error)
|
||||||
Get(id CartId) (*FrameWithPayload, error)
|
Get(id CartId) (*CartGrain, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Ttl struct {
|
type Ttl struct {
|
||||||
@@ -143,26 +142,14 @@ func (p *GrainLocalPool) GetGrain(id CartId) (*CartGrain, error) {
|
|||||||
return grain, err
|
return grain, err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *GrainLocalPool) Process(id CartId, messages ...Message) (*FrameWithPayload, error) {
|
func (p *GrainLocalPool) Apply(id CartId, mutation interface{}) (*CartGrain, error) {
|
||||||
grain, err := p.GetGrain(id)
|
grain, err := p.GetGrain(id)
|
||||||
var result *FrameWithPayload
|
if err != nil || grain == nil {
|
||||||
if err == nil && grain != nil {
|
return nil, err
|
||||||
for _, message := range messages {
|
|
||||||
result, err = grain.HandleMessage(&message, false)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return result, err
|
return grain.Apply(mutation, false)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (p *GrainLocalPool) Get(id CartId) (*FrameWithPayload, error) {
|
func (p *GrainLocalPool) Get(id CartId) (*CartGrain, error) {
|
||||||
grain, err := p.GetGrain(id)
|
return p.GetGrain(id)
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
data, err := json.Marshal(grain)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
ret := MakeFrameWithPayload(0, 200, data)
|
|
||||||
return &ret, nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
@@ -14,7 +12,7 @@ import (
|
|||||||
|
|
||||||
// TestCartActorMutationAndState validates end-to-end gRPC mutation + state retrieval
|
// TestCartActorMutationAndState validates end-to-end gRPC mutation + state retrieval
|
||||||
// against a locally started gRPC server (single-node scenario).
|
// against a locally started gRPC server (single-node scenario).
|
||||||
// This test uses AddItemType directly to avoid hitting external product
|
// This test uses the new per-mutation AddItem RPC (breaking v2 API) to avoid external product fetch logic
|
||||||
// fetching logic (FetchItem) which would require network I/O.
|
// fetching logic (FetchItem) which would require network I/O.
|
||||||
func TestCartActorMutationAndState(t *testing.T) {
|
func TestCartActorMutationAndState(t *testing.T) {
|
||||||
// Setup local grain pool + synced pool (no discovery, single host)
|
// Setup local grain pool + synced pool (no discovery, single host)
|
||||||
@@ -62,37 +60,29 @@ func TestCartActorMutationAndState(t *testing.T) {
|
|||||||
Country: "se",
|
Country: "se",
|
||||||
}
|
}
|
||||||
|
|
||||||
// Marshal underlying mutation payload using the existing handler code path
|
// Issue AddItem RPC directly (breaking v2 API)
|
||||||
handler, ok := Handlers[AddItemType]
|
addResp, err := cartClient.AddItem(context.Background(), &messages.AddItemRequest{
|
||||||
if !ok {
|
|
||||||
t.Fatalf("Handler for AddItemType missing")
|
|
||||||
}
|
|
||||||
payloadData, err := getSerializedPayload(handler, AddItemType, addItem)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("serialize add item: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Issue Mutate RPC
|
|
||||||
mutResp, err := cartClient.Mutate(context.Background(), &messages.MutationRequest{
|
|
||||||
CartId: cartID,
|
CartId: cartID,
|
||||||
Type: messages.MutationType(AddItemType),
|
|
||||||
Payload: payloadData,
|
|
||||||
ClientTimestamp: time.Now().Unix(),
|
ClientTimestamp: time.Now().Unix(),
|
||||||
|
Payload: addItem,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Mutate RPC error: %v", err)
|
t.Fatalf("AddItem RPC error: %v", err)
|
||||||
}
|
}
|
||||||
if mutResp.StatusCode != 200 {
|
if addResp.StatusCode != 200 {
|
||||||
t.Fatalf("Mutate returned non-200 status: %d payload=%s", mutResp.StatusCode, string(mutResp.Payload))
|
t.Fatalf("AddItem returned non-200 status: %d, error: %s", addResp.StatusCode, addResp.GetError())
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decode cart state JSON and validate
|
// Validate the response state (from AddItem)
|
||||||
state := &CartGrain{}
|
state := addResp.GetState()
|
||||||
if err := json.Unmarshal(mutResp.Payload, state); err != nil {
|
if state == nil {
|
||||||
t.Fatalf("Unmarshal mutate cart state: %v\nPayload: %s", err, string(mutResp.Payload))
|
t.Fatalf("AddItem response state is nil")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// (Removed obsolete Mutate response handling)
|
||||||
|
|
||||||
if len(state.Items) != 1 {
|
if len(state.Items) != 1 {
|
||||||
t.Fatalf("Expected 1 item after mutation, got %d", len(state.Items))
|
t.Fatalf("Expected 1 item after AddItem, got %d", len(state.Items))
|
||||||
}
|
}
|
||||||
if state.Items[0].Sku != "test-sku" {
|
if state.Items[0].Sku != "test-sku" {
|
||||||
t.Fatalf("Unexpected item SKU: %s", state.Items[0].Sku)
|
t.Fatalf("Unexpected item SKU: %s", state.Items[0].Sku)
|
||||||
@@ -106,13 +96,14 @@ func TestCartActorMutationAndState(t *testing.T) {
|
|||||||
t.Fatalf("GetState RPC error: %v", err)
|
t.Fatalf("GetState RPC error: %v", err)
|
||||||
}
|
}
|
||||||
if getResp.StatusCode != 200 {
|
if getResp.StatusCode != 200 {
|
||||||
t.Fatalf("GetState returned non-200 status: %d payload=%s", getResp.StatusCode, string(getResp.Payload))
|
t.Fatalf("GetState returned non-200 status: %d, error: %s", getResp.StatusCode, getResp.GetError())
|
||||||
}
|
}
|
||||||
|
|
||||||
state2 := &CartGrain{}
|
state2 := getResp.GetState()
|
||||||
if err := json.Unmarshal(getResp.Payload, state2); err != nil {
|
if state2 == nil {
|
||||||
t.Fatalf("Unmarshal get state: %v", err)
|
t.Fatalf("GetState response state is nil")
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(state2.Items) != 1 {
|
if len(state2.Items) != 1 {
|
||||||
t.Fatalf("Expected 1 item in GetState, got %d", len(state2.Items))
|
t.Fatalf("Expected 1 item in GetState, got %d", len(state2.Items))
|
||||||
}
|
}
|
||||||
@@ -121,15 +112,4 @@ func TestCartActorMutationAndState(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// getSerializedPayload serializes a mutation proto using the registered handler.
|
// Legacy serialization helper removed (oneof envelope used directly)
|
||||||
func getSerializedPayload(handler MessageHandler, msgType uint16, content interface{}) ([]byte, error) {
|
|
||||||
msg := &Message{
|
|
||||||
Type: msgType,
|
|
||||||
Content: content,
|
|
||||||
}
|
|
||||||
var buf bytes.Buffer
|
|
||||||
if err := handler.Write(msg, &buf); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return buf.Bytes(), nil
|
|
||||||
}
|
|
||||||
|
|||||||
516
grpc_server.go
516
grpc_server.go
@@ -2,378 +2,202 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"net"
|
"net"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
proto "git.tornberg.me/go-cart-actor/proto" // underlying generated package name is 'messages'
|
messages "git.tornberg.me/go-cart-actor/proto"
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
|
||||||
"github.com/prometheus/client_golang/prometheus/promauto"
|
|
||||||
"google.golang.org/grpc"
|
"google.golang.org/grpc"
|
||||||
"google.golang.org/grpc/codes"
|
"google.golang.org/grpc/reflection"
|
||||||
"google.golang.org/grpc/status"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
// cartActorGRPCServer implements the CartActor and ControlPlane gRPC services.
|
||||||
// Metrics
|
// It delegates cart operations to a grain pool and cluster operations to a synced pool.
|
||||||
// -----------------------------------------------------------------------------
|
type cartActorGRPCServer struct {
|
||||||
|
messages.UnimplementedCartActorServer
|
||||||
|
messages.UnimplementedControlPlaneServer
|
||||||
|
|
||||||
var (
|
pool GrainPool // For cart state mutations and queries
|
||||||
grpcMutateDuration = promauto.NewHistogram(prometheus.HistogramOpts{
|
syncedPool *SyncedPool // For cluster membership and control
|
||||||
Name: "cart_grpc_mutate_duration_seconds",
|
|
||||||
Help: "Duration of CartActor.Mutate RPCs",
|
|
||||||
Buckets: prometheus.DefBuckets,
|
|
||||||
})
|
|
||||||
grpcMutateErrors = promauto.NewCounter(prometheus.CounterOpts{
|
|
||||||
Name: "cart_grpc_mutate_errors_total",
|
|
||||||
Help: "Total number of failed CartActor.Mutate RPCs",
|
|
||||||
})
|
|
||||||
grpcStateDuration = promauto.NewHistogram(prometheus.HistogramOpts{
|
|
||||||
Name: "cart_grpc_get_state_duration_seconds",
|
|
||||||
Help: "Duration of CartActor.GetState RPCs",
|
|
||||||
Buckets: prometheus.DefBuckets,
|
|
||||||
})
|
|
||||||
grpcControlDuration = promauto.NewHistogram(prometheus.HistogramOpts{
|
|
||||||
Name: "cart_grpc_control_duration_seconds",
|
|
||||||
Help: "Duration of ControlPlane RPCs",
|
|
||||||
Buckets: prometheus.DefBuckets,
|
|
||||||
})
|
|
||||||
grpcControlErrors = promauto.NewCounter(prometheus.CounterOpts{
|
|
||||||
Name: "cart_grpc_control_errors_total",
|
|
||||||
Help: "Total number of failed ControlPlane RPCs",
|
|
||||||
})
|
|
||||||
)
|
|
||||||
|
|
||||||
// timeTrack wraps a closure and records duration into the supplied histogram.
|
|
||||||
func timeTrack(hist prometheus.Observer, fn func() error) (err error) {
|
|
||||||
start := time.Now()
|
|
||||||
defer func() {
|
|
||||||
hist.Observe(time.Since(start).Seconds())
|
|
||||||
}()
|
|
||||||
return fn()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
// NewCartActorGRPCServer creates and initializes the server.
|
||||||
// CartActor Service Implementation
|
func NewCartActorGRPCServer(pool GrainPool, syncedPool *SyncedPool) *cartActorGRPCServer {
|
||||||
// -----------------------------------------------------------------------------
|
return &cartActorGRPCServer{
|
||||||
|
pool: pool,
|
||||||
type cartActorService struct {
|
syncedPool: syncedPool,
|
||||||
proto.UnimplementedCartActorServer
|
}
|
||||||
pool GrainPool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func newCartActorService(pool GrainPool) *cartActorService {
|
// applyMutation routes a single cart mutation to the target grain (used by per-mutation RPC handlers).
|
||||||
return &cartActorService{pool: pool}
|
func (s *cartActorGRPCServer) applyMutation(cartID string, mutation interface{}) *messages.CartMutationReply {
|
||||||
}
|
grain, err := s.pool.Apply(ToCartId(cartID), mutation)
|
||||||
|
|
||||||
func (s *cartActorService) Mutate(ctx context.Context, req *proto.MutationRequest) (*proto.MutationReply, error) {
|
|
||||||
var reply *proto.MutationReply
|
|
||||||
err := timeTrack(grpcMutateDuration, func() error {
|
|
||||||
if req == nil {
|
|
||||||
return status.Error(codes.InvalidArgument, "request is nil")
|
|
||||||
}
|
|
||||||
if req.CartId == "" {
|
|
||||||
return status.Error(codes.InvalidArgument, "cart_id is empty")
|
|
||||||
}
|
|
||||||
mt := uint16(req.Type.Number())
|
|
||||||
handler, ok := Handlers[mt]
|
|
||||||
if !ok {
|
|
||||||
return status.Errorf(codes.InvalidArgument, "unknown mutation type %d", mt)
|
|
||||||
}
|
|
||||||
content, err := handler.Read(req.Payload)
|
|
||||||
if err != nil {
|
|
||||||
return status.Errorf(codes.InvalidArgument, "decode payload: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
ts := req.ClientTimestamp
|
|
||||||
if ts == 0 {
|
|
||||||
ts = time.Now().Unix()
|
|
||||||
}
|
|
||||||
msg := Message{
|
|
||||||
Type: mt,
|
|
||||||
TimeStamp: &ts,
|
|
||||||
Content: content,
|
|
||||||
}
|
|
||||||
|
|
||||||
frame, err := s.pool.Process(ToCartId(req.CartId), msg)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
reply = &proto.MutationReply{
|
|
||||||
StatusCode: int32(frame.StatusCode),
|
|
||||||
Payload: frame.Payload,
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
grpcMutateErrors.Inc()
|
return &messages.CartMutationReply{
|
||||||
return nil, err
|
StatusCode: 500,
|
||||||
|
Result: &messages.CartMutationReply_Error{Error: err.Error()},
|
||||||
|
ServerTimestamp: time.Now().Unix(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cartState := ToCartState(grain)
|
||||||
|
return &messages.CartMutationReply{
|
||||||
|
StatusCode: 200,
|
||||||
|
Result: &messages.CartMutationReply_State{State: cartState},
|
||||||
|
ServerTimestamp: time.Now().Unix(),
|
||||||
}
|
}
|
||||||
return reply, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *cartActorService) GetState(ctx context.Context, req *proto.StateRequest) (*proto.StateReply, error) {
|
func (s *cartActorGRPCServer) AddRequest(ctx context.Context, req *messages.AddRequestRequest) (*messages.CartMutationReply, error) {
|
||||||
var reply *proto.StateReply
|
if req.GetCartId() == "" {
|
||||||
err := timeTrack(grpcStateDuration, func() error {
|
return &messages.CartMutationReply{
|
||||||
if req == nil || req.CartId == "" {
|
StatusCode: 400,
|
||||||
return status.Error(codes.InvalidArgument, "cart_id is empty")
|
Result: &messages.CartMutationReply_Error{Error: "cart_id is required"},
|
||||||
}
|
ServerTimestamp: time.Now().Unix(),
|
||||||
frame, err := s.pool.Get(ToCartId(req.CartId))
|
}, nil
|
||||||
if err != nil {
|
}
|
||||||
return err
|
return s.applyMutation(req.GetCartId(), req.GetPayload()), nil
|
||||||
}
|
}
|
||||||
reply = &proto.StateReply{
|
|
||||||
StatusCode: int32(frame.StatusCode),
|
func (s *cartActorGRPCServer) AddItem(ctx context.Context, req *messages.AddItemRequest) (*messages.CartMutationReply, error) {
|
||||||
Payload: frame.Payload,
|
if req.GetCartId() == "" {
|
||||||
}
|
return &messages.CartMutationReply{
|
||||||
return nil
|
StatusCode: 400,
|
||||||
})
|
Result: &messages.CartMutationReply_Error{Error: "cart_id is required"},
|
||||||
|
ServerTimestamp: time.Now().Unix(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return s.applyMutation(req.GetCartId(), req.GetPayload()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *cartActorGRPCServer) RemoveItem(ctx context.Context, req *messages.RemoveItemRequest) (*messages.CartMutationReply, error) {
|
||||||
|
if req.GetCartId() == "" {
|
||||||
|
return &messages.CartMutationReply{
|
||||||
|
StatusCode: 400,
|
||||||
|
Result: &messages.CartMutationReply_Error{Error: "cart_id is required"},
|
||||||
|
ServerTimestamp: time.Now().Unix(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return s.applyMutation(req.GetCartId(), req.GetPayload()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *cartActorGRPCServer) RemoveDelivery(ctx context.Context, req *messages.RemoveDeliveryRequest) (*messages.CartMutationReply, error) {
|
||||||
|
if req.GetCartId() == "" {
|
||||||
|
return &messages.CartMutationReply{
|
||||||
|
StatusCode: 400,
|
||||||
|
Result: &messages.CartMutationReply_Error{Error: "cart_id is required"},
|
||||||
|
ServerTimestamp: time.Now().Unix(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return s.applyMutation(req.GetCartId(), req.GetPayload()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *cartActorGRPCServer) ChangeQuantity(ctx context.Context, req *messages.ChangeQuantityRequest) (*messages.CartMutationReply, error) {
|
||||||
|
if req.GetCartId() == "" {
|
||||||
|
return &messages.CartMutationReply{
|
||||||
|
StatusCode: 400,
|
||||||
|
Result: &messages.CartMutationReply_Error{Error: "cart_id is required"},
|
||||||
|
ServerTimestamp: time.Now().Unix(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return s.applyMutation(req.GetCartId(), req.GetPayload()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *cartActorGRPCServer) SetDelivery(ctx context.Context, req *messages.SetDeliveryRequest) (*messages.CartMutationReply, error) {
|
||||||
|
if req.GetCartId() == "" {
|
||||||
|
return &messages.CartMutationReply{
|
||||||
|
StatusCode: 400,
|
||||||
|
Result: &messages.CartMutationReply_Error{Error: "cart_id is required"},
|
||||||
|
ServerTimestamp: time.Now().Unix(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return s.applyMutation(req.GetCartId(), req.GetPayload()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *cartActorGRPCServer) SetPickupPoint(ctx context.Context, req *messages.SetPickupPointRequest) (*messages.CartMutationReply, error) {
|
||||||
|
if req.GetCartId() == "" {
|
||||||
|
return &messages.CartMutationReply{
|
||||||
|
StatusCode: 400,
|
||||||
|
Result: &messages.CartMutationReply_Error{Error: "cart_id is required"},
|
||||||
|
ServerTimestamp: time.Now().Unix(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return s.applyMutation(req.GetCartId(), req.GetPayload()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Checkout RPC removed. Checkout is handled at the HTTP layer (PoolServer.HandleCheckout).
|
||||||
|
*/
|
||||||
|
|
||||||
|
func (s *cartActorGRPCServer) SetCartItems(ctx context.Context, req *messages.SetCartItemsRequest) (*messages.CartMutationReply, error) {
|
||||||
|
if req.GetCartId() == "" {
|
||||||
|
return &messages.CartMutationReply{
|
||||||
|
StatusCode: 400,
|
||||||
|
Result: &messages.CartMutationReply_Error{Error: "cart_id is required"},
|
||||||
|
ServerTimestamp: time.Now().Unix(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return s.applyMutation(req.GetCartId(), req.GetPayload()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *cartActorGRPCServer) OrderCompleted(ctx context.Context, req *messages.OrderCompletedRequest) (*messages.CartMutationReply, error) {
|
||||||
|
if req.GetCartId() == "" {
|
||||||
|
return &messages.CartMutationReply{
|
||||||
|
StatusCode: 400,
|
||||||
|
Result: &messages.CartMutationReply_Error{Error: "cart_id is required"},
|
||||||
|
ServerTimestamp: time.Now().Unix(),
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return s.applyMutation(req.GetCartId(), req.GetPayload()), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetState retrieves the current state of a cart grain.
|
||||||
|
func (s *cartActorGRPCServer) GetState(ctx context.Context, req *messages.StateRequest) (*messages.StateReply, error) {
|
||||||
|
if req.GetCartId() == "" {
|
||||||
|
return &messages.StateReply{
|
||||||
|
StatusCode: 400,
|
||||||
|
Result: &messages.StateReply_Error{Error: "cart_id is required"},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
cartID := ToCartId(req.GetCartId())
|
||||||
|
|
||||||
|
grain, err := s.pool.Get(cartID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return &messages.StateReply{
|
||||||
}
|
StatusCode: 500,
|
||||||
return reply, nil
|
Result: &messages.StateReply_Error{Error: err.Error()},
|
||||||
}
|
}, nil
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
// ControlPlane Service Implementation
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
|
|
||||||
// controlPlaneService directly leverages SyncedPool internals (same package).
|
|
||||||
// NOTE: This is a transitional adapter; once the legacy frame-based code is
|
|
||||||
// removed, related fields/methods in SyncedPool can be slimmed.
|
|
||||||
type controlPlaneService struct {
|
|
||||||
proto.UnimplementedControlPlaneServer
|
|
||||||
pool *SyncedPool
|
|
||||||
}
|
|
||||||
|
|
||||||
func newControlPlaneService(pool *SyncedPool) *controlPlaneService {
|
|
||||||
return &controlPlaneService{pool: pool}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *controlPlaneService) Ping(ctx context.Context, _ *proto.Empty) (*proto.PingReply, error) {
|
|
||||||
var reply *proto.PingReply
|
|
||||||
err := timeTrack(grpcControlDuration, func() error {
|
|
||||||
reply = &proto.PingReply{
|
|
||||||
Host: s.pool.Hostname,
|
|
||||||
UnixTime: time.Now().Unix(),
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
grpcControlErrors.Inc()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return reply, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *controlPlaneService) Negotiate(ctx context.Context, req *proto.NegotiateRequest) (*proto.NegotiateReply, error) {
|
|
||||||
var reply *proto.NegotiateReply
|
|
||||||
err := timeTrack(grpcControlDuration, func() error {
|
|
||||||
if req == nil {
|
|
||||||
return status.Error(codes.InvalidArgument, "request is nil")
|
|
||||||
}
|
|
||||||
// Add unknown hosts
|
|
||||||
for _, host := range req.KnownHosts {
|
|
||||||
if host == "" || host == s.pool.Hostname {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if !s.pool.IsKnown(host) {
|
|
||||||
go s.pool.AddRemote(host)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Build healthy host list
|
|
||||||
hosts := make([]string, 0)
|
|
||||||
for _, r := range s.pool.GetHealthyRemotes() {
|
|
||||||
hosts = append(hosts, r.Host)
|
|
||||||
}
|
|
||||||
hosts = append(hosts, s.pool.Hostname)
|
|
||||||
reply = &proto.NegotiateReply{
|
|
||||||
Hosts: hosts,
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
grpcControlErrors.Inc()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return reply, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *controlPlaneService) GetCartIds(ctx context.Context, _ *proto.Empty) (*proto.CartIdsReply, error) {
|
|
||||||
var reply *proto.CartIdsReply
|
|
||||||
err := timeTrack(grpcControlDuration, func() error {
|
|
||||||
s.pool.mu.RLock()
|
|
||||||
defer s.pool.mu.RUnlock()
|
|
||||||
ids := make([]string, 0, len(s.pool.local.grains))
|
|
||||||
for id, g := range s.pool.local.grains {
|
|
||||||
if g == nil {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if id.String() == "" {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
ids = append(ids, id.String())
|
|
||||||
}
|
|
||||||
reply = &proto.CartIdsReply{
|
|
||||||
CartIds: ids,
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
grpcControlErrors.Inc()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return reply, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *controlPlaneService) ConfirmOwner(ctx context.Context, req *proto.OwnerChangeRequest) (*proto.OwnerChangeAck, error) {
|
|
||||||
var reply *proto.OwnerChangeAck
|
|
||||||
err := timeTrack(grpcControlDuration, func() error {
|
|
||||||
if req == nil || req.CartId == "" || req.NewHost == "" {
|
|
||||||
return status.Error(codes.InvalidArgument, "cart_id or new_host missing")
|
|
||||||
}
|
|
||||||
id := ToCartId(req.CartId)
|
|
||||||
newHost := req.NewHost
|
|
||||||
|
|
||||||
// Mirror GrainOwnerChangeHandler semantics
|
|
||||||
log.Printf("gRPC ConfirmOwner: cart %s newHost=%s", id, newHost)
|
|
||||||
for _, r := range s.pool.remoteHosts {
|
|
||||||
if r.Host == newHost && r.IsHealthy() {
|
|
||||||
go s.pool.SpawnRemoteGrain(id, newHost)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
go s.pool.AddRemote(newHost)
|
|
||||||
|
|
||||||
reply = &proto.OwnerChangeAck{
|
|
||||||
Accepted: true,
|
|
||||||
Message: "ok",
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
grpcControlErrors.Inc()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return reply, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *controlPlaneService) Closing(ctx context.Context, notice *proto.ClosingNotice) (*proto.OwnerChangeAck, error) {
|
|
||||||
var reply *proto.OwnerChangeAck
|
|
||||||
err := timeTrack(grpcControlDuration, func() error {
|
|
||||||
if notice == nil || notice.Host == "" {
|
|
||||||
return status.Error(codes.InvalidArgument, "host missing")
|
|
||||||
}
|
|
||||||
host := notice.Host
|
|
||||||
s.pool.mu.RLock()
|
|
||||||
_, exists := s.pool.remoteHosts[host]
|
|
||||||
s.pool.mu.RUnlock()
|
|
||||||
if exists {
|
|
||||||
go s.pool.RemoveHost(host)
|
|
||||||
}
|
|
||||||
reply = &proto.OwnerChangeAck{
|
|
||||||
Accepted: true,
|
|
||||||
Message: "removed",
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
grpcControlErrors.Inc()
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return reply, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
// Server Bootstrap
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
|
|
||||||
type GRPCServer struct {
|
|
||||||
server *grpc.Server
|
|
||||||
lis net.Listener
|
|
||||||
addr string
|
|
||||||
}
|
|
||||||
|
|
||||||
// StartGRPCServer sets up a gRPC server hosting both CartActor and ControlPlane services.
|
|
||||||
// addr example: ":1337" (for combined) OR run two servers if you want separate ports.
|
|
||||||
// For the migration we can host both on the same listener to reduce open ports.
|
|
||||||
func StartGRPCServer(addr string, pool GrainPool, synced *SyncedPool, opts ...grpc.ServerOption) (*GRPCServer, error) {
|
|
||||||
if pool == nil {
|
|
||||||
return nil, errors.New("nil grain pool")
|
|
||||||
}
|
|
||||||
if synced == nil {
|
|
||||||
return nil, errors.New("nil synced pool")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
lis, err := net.Listen("tcp", addr)
|
cartState := ToCartState(grain)
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("listen %s: %w", addr, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
grpcServer := grpc.NewServer(opts...)
|
return &messages.StateReply{
|
||||||
proto.RegisterCartActorServer(grpcServer, newCartActorService(pool))
|
StatusCode: 200,
|
||||||
proto.RegisterControlPlaneServer(grpcServer, newControlPlaneService(synced))
|
Result: &messages.StateReply_State{State: cartState},
|
||||||
|
|
||||||
go func() {
|
|
||||||
log.Printf("gRPC server listening on %s", addr)
|
|
||||||
if serveErr := grpcServer.Serve(lis); serveErr != nil {
|
|
||||||
log.Printf("gRPC server stopped: %v", serveErr)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
return &GRPCServer{
|
|
||||||
server: grpcServer,
|
|
||||||
lis: lis,
|
|
||||||
addr: addr,
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GracefulStop stops the server gracefully.
|
// StartGRPCServer configures and starts the unified gRPC server on the given address.
|
||||||
func (s *GRPCServer) GracefulStop() {
|
// It registers both the CartActor and ControlPlane services.
|
||||||
if s == nil || s.server == nil {
|
func StartGRPCServer(addr string, pool GrainPool, syncedPool *SyncedPool) (*grpc.Server, error) {
|
||||||
return
|
lis, err := net.Listen("tcp", addr)
|
||||||
}
|
|
||||||
s.server.GracefulStop()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Addr returns the bound address.
|
|
||||||
func (s *GRPCServer) Addr() string {
|
|
||||||
if s == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return s.addr
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
// Client Dial Helpers (used later by refactored remote grain + control plane)
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
|
|
||||||
// DialRemote establishes (or reuses externally) a gRPC client connection.
|
|
||||||
func DialRemote(ctx context.Context, target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
|
|
||||||
dialOpts := []grpc.DialOption{
|
|
||||||
grpc.WithInsecure(), // NOTE: Intentional for initial migration; replace with TLS / mTLS later.
|
|
||||||
grpc.WithBlock(),
|
|
||||||
}
|
|
||||||
dialOpts = append(dialOpts, opts...)
|
|
||||||
ctxDial, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
||||||
defer cancel()
|
|
||||||
conn, err := grpc.DialContext(ctxDial, target, dialOpts...)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("failed to listen: %w", err)
|
||||||
}
|
}
|
||||||
return conn, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
grpcServer := grpc.NewServer()
|
||||||
// Utility for converting internal errors to gRPC status (if needed later).
|
server := NewCartActorGRPCServer(pool, syncedPool)
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
|
|
||||||
func grpcError(err error) error {
|
messages.RegisterCartActorServer(grpcServer, server)
|
||||||
if err == nil {
|
messages.RegisterControlPlaneServer(grpcServer, server)
|
||||||
return nil
|
reflection.Register(grpcServer)
|
||||||
}
|
|
||||||
// Extend mapping if we add richer error types.
|
log.Printf("gRPC server listening on %s", addr)
|
||||||
return status.Error(codes.Internal, err.Error())
|
go func() {
|
||||||
|
if err := grpcServer.Serve(lis); err != nil {
|
||||||
|
log.Fatalf("failed to serve gRPC: %v", err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
return grpcServer, nil
|
||||||
}
|
}
|
||||||
|
|||||||
73
main.go
73
main.go
@@ -38,13 +38,13 @@ var (
|
|||||||
func spawn(id CartId) (*CartGrain, error) {
|
func spawn(id CartId) (*CartGrain, error) {
|
||||||
grainSpawns.Inc()
|
grainSpawns.Inc()
|
||||||
ret := &CartGrain{
|
ret := &CartGrain{
|
||||||
lastItemId: 0,
|
lastItemId: 0,
|
||||||
lastDeliveryId: 0,
|
lastDeliveryId: 0,
|
||||||
Deliveries: []*CartDelivery{},
|
Deliveries: []*CartDelivery{},
|
||||||
Id: id,
|
Id: id,
|
||||||
Items: []*CartItem{},
|
Items: []*CartItem{},
|
||||||
storageMessages: []Message{},
|
// storageMessages removed (legacy event log deprecated)
|
||||||
TotalPrice: 0,
|
TotalPrice: 0,
|
||||||
}
|
}
|
||||||
err := loadMessages(ret, id)
|
err := loadMessages(ret, id)
|
||||||
return ret, err
|
return ret, err
|
||||||
@@ -97,23 +97,6 @@ var name = os.Getenv("POD_NAME")
|
|||||||
var amqpUrl = os.Getenv("AMQP_URL")
|
var amqpUrl = os.Getenv("AMQP_URL")
|
||||||
var KlarnaInstance = NewKlarnaClient(KlarnaPlaygroundUrl, os.Getenv("KLARNA_API_USERNAME"), os.Getenv("KLARNA_API_PASSWORD"))
|
var KlarnaInstance = NewKlarnaClient(KlarnaPlaygroundUrl, os.Getenv("KLARNA_API_USERNAME"), os.Getenv("KLARNA_API_PASSWORD"))
|
||||||
|
|
||||||
func GetDiscovery() Discovery {
|
|
||||||
if podIp == "" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
config, kerr := rest.InClusterConfig()
|
|
||||||
|
|
||||||
if kerr != nil {
|
|
||||||
log.Fatalf("Error creating kubernetes client: %v\n", kerr)
|
|
||||||
}
|
|
||||||
client, err := kubernetes.NewForConfig(config)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Error creating client: %v\n", err)
|
|
||||||
}
|
|
||||||
return NewK8sDiscovery(client)
|
|
||||||
}
|
|
||||||
|
|
||||||
var tpl = `<!DOCTYPE html>
|
var tpl = `<!DOCTYPE html>
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
@@ -153,6 +136,23 @@ func getCheckoutOrder(host string, cartId CartId) *messages.CreateCheckoutOrder
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetDiscovery() Discovery {
|
||||||
|
if podIp == "" {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
config, kerr := rest.InClusterConfig()
|
||||||
|
|
||||||
|
if kerr != nil {
|
||||||
|
log.Fatalf("Error creating kubernetes client: %v\n", kerr)
|
||||||
|
}
|
||||||
|
client, err := kubernetes.NewForConfig(config)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("Error creating client: %v\n", err)
|
||||||
|
}
|
||||||
|
return NewK8sDiscovery(client)
|
||||||
|
}
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
|
||||||
storage, err := NewDiskStorage(fmt.Sprintf("data/%s_state.gob", name))
|
storage, err := NewDiskStorage(fmt.Sprintf("data/%s_state.gob", name))
|
||||||
@@ -249,20 +249,12 @@ func main() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
cartId := ToCartId(cookie.Value)
|
cartId := ToCartId(cookie.Value)
|
||||||
reply, err := syncedServer.pool.Process(cartId, Message{
|
_, err = syncedServer.pool.Apply(cartId, getCheckoutOrder(r.Host, cartId))
|
||||||
Type: CreateCheckoutOrderType,
|
|
||||||
Content: getCheckoutOrder(r.Host, cartId),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
w.Write([]byte(err.Error()))
|
w.Write([]byte(err.Error()))
|
||||||
}
|
}
|
||||||
err = json.Unmarshal(reply.Payload, &order)
|
// v2: Apply now returns *CartGrain; order creation handled inside grain (no payload to unmarshal)
|
||||||
if err != nil {
|
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
|
||||||
w.Write([]byte(err.Error()))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
prevOrder, err := KlarnaInstance.GetOrder(orderId)
|
prevOrder, err := KlarnaInstance.GetOrder(orderId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -385,19 +377,16 @@ func main() {
|
|||||||
done <- true
|
done <- true
|
||||||
}()
|
}()
|
||||||
|
|
||||||
log.Print("Server started at port 8080")
|
log.Print("Server started at port 8083")
|
||||||
go http.ListenAndServe(":8080", mux)
|
go http.ListenAndServe(":8083", mux)
|
||||||
<-done
|
<-done
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func triggerOrderCompleted(err error, syncedServer *PoolServer, order *CheckoutOrder) error {
|
func triggerOrderCompleted(err error, syncedServer *PoolServer, order *CheckoutOrder) error {
|
||||||
_, err = syncedServer.pool.Process(ToCartId(order.MerchantReference1), Message{
|
_, err = syncedServer.pool.Apply(ToCartId(order.MerchantReference1), &messages.OrderCreated{
|
||||||
Type: OrderCompletedType,
|
OrderId: order.ID,
|
||||||
Content: &messages.OrderCreated{
|
Status: order.Status,
|
||||||
OrderId: order.ID,
|
|
||||||
Status: order.Status,
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,315 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"io"
|
|
||||||
|
|
||||||
messages "git.tornberg.me/go-cart-actor/proto"
|
|
||||||
"google.golang.org/protobuf/proto"
|
|
||||||
)
|
|
||||||
|
|
||||||
var Handlers = map[uint16]MessageHandler{
|
|
||||||
AddRequestType: &AddRequestHandler{},
|
|
||||||
AddItemType: &AddItemHandler{},
|
|
||||||
ChangeQuantityType: &ChangeQuantityHandler{},
|
|
||||||
SetDeliveryType: &SetDeliveryHandler{},
|
|
||||||
RemoveItemType: &RemoveItemHandler{},
|
|
||||||
RemoveDeliveryType: &RemoveDeliveryHandler{},
|
|
||||||
CreateCheckoutOrderType: &CheckoutHandler{},
|
|
||||||
SetCartItemsType: &SetCartItemsHandler{},
|
|
||||||
OrderCompletedType: &OrderCompletedHandler{},
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetMessageHandler(t uint16) (MessageHandler, error) {
|
|
||||||
h, ok := Handlers[t]
|
|
||||||
if !ok {
|
|
||||||
return nil, fmt.Errorf("no handler for message type %d", t)
|
|
||||||
}
|
|
||||||
return h, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type MessageHandler interface {
|
|
||||||
Write(*Message, io.Writer) error
|
|
||||||
Read(data []byte) (interface{}, error)
|
|
||||||
Is(*Message) bool
|
|
||||||
}
|
|
||||||
type TypedMessageHandler struct {
|
|
||||||
Type uint16
|
|
||||||
}
|
|
||||||
|
|
||||||
type SetCartItemsHandler struct {
|
|
||||||
TypedMessageHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *SetCartItemsHandler) Write(m *Message, w io.Writer) error {
|
|
||||||
messageBytes, err := proto.Marshal(m.Content.(*messages.SetCartRequest))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
w.Write(messageBytes)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *SetCartItemsHandler) Read(data []byte) (interface{}, error) {
|
|
||||||
msg := &messages.SetCartRequest{}
|
|
||||||
|
|
||||||
err := proto.Unmarshal(data, msg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return msg, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *SetCartItemsHandler) Is(m *Message) bool {
|
|
||||||
if m.Type != AddRequestType {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, ok := m.Content.(*messages.SetCartRequest)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
type AddRequestHandler struct {
|
|
||||||
TypedMessageHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *AddRequestHandler) Write(m *Message, w io.Writer) error {
|
|
||||||
messageBytes, err := proto.Marshal(m.Content.(*messages.AddRequest))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
w.Write(messageBytes)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *AddRequestHandler) Read(data []byte) (interface{}, error) {
|
|
||||||
msg := &messages.AddRequest{}
|
|
||||||
|
|
||||||
err := proto.Unmarshal(data, msg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return msg, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *AddRequestHandler) Is(m *Message) bool {
|
|
||||||
if m.Type != AddRequestType {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, ok := m.Content.(*messages.AddRequest)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
type AddItemHandler struct {
|
|
||||||
TypedMessageHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *AddItemHandler) Write(m *Message, w io.Writer) error {
|
|
||||||
messageBytes, err := proto.Marshal(m.Content.(*messages.AddItem))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
w.Write(messageBytes)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *AddItemHandler) Read(data []byte) (interface{}, error) {
|
|
||||||
msg := &messages.AddItem{}
|
|
||||||
|
|
||||||
err := proto.Unmarshal(data, msg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return msg, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *AddItemHandler) Is(m *Message) bool {
|
|
||||||
if m.Type != AddItemType {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, ok := m.Content.(*messages.AddItem)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
type ChangeQuantityHandler struct {
|
|
||||||
TypedMessageHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *ChangeQuantityHandler) Write(m *Message, w io.Writer) error {
|
|
||||||
messageBytes, err := proto.Marshal(m.Content.(*messages.ChangeQuantity))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
w.Write(messageBytes)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *ChangeQuantityHandler) Read(data []byte) (interface{}, error) {
|
|
||||||
msg := &messages.ChangeQuantity{}
|
|
||||||
|
|
||||||
err := proto.Unmarshal(data, msg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return msg, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *ChangeQuantityHandler) Is(m *Message) bool {
|
|
||||||
if m.Type != ChangeQuantityType {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, ok := m.Content.(*messages.ChangeQuantity)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
type SetDeliveryHandler struct {
|
|
||||||
TypedMessageHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *SetDeliveryHandler) Write(m *Message, w io.Writer) error {
|
|
||||||
messageBytes, err := proto.Marshal(m.Content.(*messages.SetDelivery))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
w.Write(messageBytes)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *SetDeliveryHandler) Read(data []byte) (interface{}, error) {
|
|
||||||
msg := &messages.SetDelivery{}
|
|
||||||
|
|
||||||
err := proto.Unmarshal(data, msg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return msg, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *SetDeliveryHandler) Is(m *Message) bool {
|
|
||||||
if m.Type != ChangeQuantityType {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, ok := m.Content.(*messages.SetDelivery)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
type RemoveItemHandler struct {
|
|
||||||
TypedMessageHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *RemoveItemHandler) Write(m *Message, w io.Writer) error {
|
|
||||||
messageBytes, err := proto.Marshal(m.Content.(*messages.RemoveItem))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
w.Write(messageBytes)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *RemoveItemHandler) Read(data []byte) (interface{}, error) {
|
|
||||||
msg := &messages.RemoveItem{}
|
|
||||||
|
|
||||||
err := proto.Unmarshal(data, msg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return msg, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *RemoveItemHandler) Is(m *Message) bool {
|
|
||||||
if m.Type != AddItemType {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, ok := m.Content.(*messages.RemoveItem)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
type RemoveDeliveryHandler struct {
|
|
||||||
TypedMessageHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *RemoveDeliveryHandler) Write(m *Message, w io.Writer) error {
|
|
||||||
messageBytes, err := proto.Marshal(m.Content.(*messages.RemoveDelivery))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
w.Write(messageBytes)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *RemoveDeliveryHandler) Read(data []byte) (interface{}, error) {
|
|
||||||
msg := &messages.RemoveDelivery{}
|
|
||||||
|
|
||||||
err := proto.Unmarshal(data, msg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return msg, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *RemoveDeliveryHandler) Is(m *Message) bool {
|
|
||||||
if m.Type != AddItemType {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, ok := m.Content.(*messages.RemoveDelivery)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
type CheckoutHandler struct {
|
|
||||||
TypedMessageHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *CheckoutHandler) Write(m *Message, w io.Writer) error {
|
|
||||||
messageBytes, err := proto.Marshal(m.Content.(*messages.CreateCheckoutOrder))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
w.Write(messageBytes)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *CheckoutHandler) Read(data []byte) (interface{}, error) {
|
|
||||||
msg := &messages.CreateCheckoutOrder{}
|
|
||||||
|
|
||||||
err := proto.Unmarshal(data, msg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return msg, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *CheckoutHandler) Is(m *Message) bool {
|
|
||||||
if m.Type != CreateCheckoutOrderType {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, ok := m.Content.(*messages.CreateCheckoutOrder)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
type OrderCompletedHandler struct {
|
|
||||||
TypedMessageHandler
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *OrderCompletedHandler) Write(m *Message, w io.Writer) error {
|
|
||||||
messageBytes, err := proto.Marshal(m.Content.(*messages.OrderCreated))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
w.Write(messageBytes)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
func (h *OrderCompletedHandler) Read(data []byte) (interface{}, error) {
|
|
||||||
msg := &messages.OrderCreated{}
|
|
||||||
|
|
||||||
err := proto.Unmarshal(data, msg)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return msg, nil
|
|
||||||
}
|
|
||||||
func (h *OrderCompletedHandler) Is(m *Message) bool {
|
|
||||||
if m.Type != OrderCompletedType {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, ok := m.Content.(*messages.OrderCreated)
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
const (
|
|
||||||
AddRequestType = 1
|
|
||||||
AddItemType = 2
|
|
||||||
|
|
||||||
RemoveItemType = 4
|
|
||||||
RemoveDeliveryType = 5
|
|
||||||
ChangeQuantityType = 6
|
|
||||||
SetDeliveryType = 7
|
|
||||||
SetPickupPointType = 8
|
|
||||||
CreateCheckoutOrderType = 9
|
|
||||||
SetCartItemsType = 10
|
|
||||||
OrderCompletedType = 11
|
|
||||||
)
|
|
||||||
94
message.go
94
message.go
@@ -1,94 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"encoding/binary"
|
|
||||||
"io"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
type StorableMessage interface {
|
|
||||||
Write(w io.Writer) error
|
|
||||||
}
|
|
||||||
|
|
||||||
type Message struct {
|
|
||||||
Type uint16
|
|
||||||
TimeStamp *int64
|
|
||||||
Content interface{}
|
|
||||||
}
|
|
||||||
|
|
||||||
type MessageWriter struct {
|
|
||||||
io.Writer
|
|
||||||
}
|
|
||||||
|
|
||||||
type StorableMessageHeader struct {
|
|
||||||
Version uint16
|
|
||||||
Type uint16
|
|
||||||
TimeStamp int64
|
|
||||||
DataLength uint64
|
|
||||||
}
|
|
||||||
|
|
||||||
func GetData(fn func(w io.Writer) error) ([]byte, error) {
|
|
||||||
var buf bytes.Buffer
|
|
||||||
err := fn(&buf)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
b := buf.Bytes()
|
|
||||||
return b, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m Message) Write(w io.Writer) error {
|
|
||||||
h, err := GetMessageHandler(m.Type)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
data, err := GetData(func(w io.Writer) error {
|
|
||||||
return h.Write(&m, w)
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
ts := time.Now().Unix()
|
|
||||||
if m.TimeStamp != nil {
|
|
||||||
ts = *m.TimeStamp
|
|
||||||
}
|
|
||||||
|
|
||||||
err = binary.Write(w, binary.LittleEndian, StorableMessageHeader{
|
|
||||||
Version: 1,
|
|
||||||
Type: m.Type,
|
|
||||||
TimeStamp: ts,
|
|
||||||
DataLength: uint64(len(data)),
|
|
||||||
})
|
|
||||||
w.Write(data)
|
|
||||||
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func ReadMessage(reader io.Reader, m *Message) error {
|
|
||||||
|
|
||||||
header := StorableMessageHeader{}
|
|
||||||
err := binary.Read(reader, binary.LittleEndian, &header)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
messageBytes := make([]byte, header.DataLength)
|
|
||||||
_, err = reader.Read(messageBytes)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
h, err := GetMessageHandler(header.Type)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
content, err := h.Read(messageBytes)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
m.Content = content
|
|
||||||
|
|
||||||
m.Type = header.Type
|
|
||||||
m.TimeStamp = &header.TimeStamp
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
82
mutation_add_item.go
Normal file
82
mutation_add_item.go
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
messages "git.tornberg.me/go-cart-actor/proto"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mutation_add_item.go
|
||||||
|
//
|
||||||
|
// Registers the AddItem cart mutation in the generic mutation registry.
|
||||||
|
// This replaces the legacy switch-based logic previously found in CartGrain.Apply.
|
||||||
|
//
|
||||||
|
// Behavior:
|
||||||
|
// * Validates quantity > 0
|
||||||
|
// * If an item with same SKU exists -> increases quantity
|
||||||
|
// * Else creates a new CartItem with computed tax amounts
|
||||||
|
// * Totals recalculated automatically via WithTotals()
|
||||||
|
//
|
||||||
|
// NOTE: Any future field additions in messages.AddItem that affect pricing / tax
|
||||||
|
// must keep this handler in sync.
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
RegisterMutation[messages.AddItem](
|
||||||
|
"AddItem",
|
||||||
|
func(g *CartGrain, m *messages.AddItem) error {
|
||||||
|
if m == nil {
|
||||||
|
return fmt.Errorf("AddItem: nil payload")
|
||||||
|
}
|
||||||
|
if m.Quantity < 1 {
|
||||||
|
return fmt.Errorf("AddItem: invalid quantity %d", m.Quantity)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fast path: merge with existing item having same SKU
|
||||||
|
if existing, found := g.FindItemWithSku(m.Sku); found {
|
||||||
|
existing.Quantity += int(m.Quantity)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
g.mu.Lock()
|
||||||
|
defer g.mu.Unlock()
|
||||||
|
|
||||||
|
g.lastItemId++
|
||||||
|
taxRate := 2500
|
||||||
|
if m.Tax > 0 {
|
||||||
|
taxRate = int(m.Tax)
|
||||||
|
}
|
||||||
|
taxAmountPerUnit := GetTaxAmount(m.Price, taxRate)
|
||||||
|
|
||||||
|
g.Items = append(g.Items, &CartItem{
|
||||||
|
Id: g.lastItemId,
|
||||||
|
ItemId: int(m.ItemId),
|
||||||
|
Quantity: int(m.Quantity),
|
||||||
|
Sku: m.Sku,
|
||||||
|
Name: m.Name,
|
||||||
|
Price: m.Price,
|
||||||
|
TotalPrice: m.Price * int64(m.Quantity),
|
||||||
|
TotalTax: int64(taxAmountPerUnit * int64(m.Quantity)),
|
||||||
|
Image: m.Image,
|
||||||
|
Stock: StockStatus(m.Stock),
|
||||||
|
Disclaimer: m.Disclaimer,
|
||||||
|
Brand: m.Brand,
|
||||||
|
Category: m.Category,
|
||||||
|
Category2: m.Category2,
|
||||||
|
Category3: m.Category3,
|
||||||
|
Category4: m.Category4,
|
||||||
|
Category5: m.Category5,
|
||||||
|
OrgPrice: m.OrgPrice,
|
||||||
|
ArticleType: m.ArticleType,
|
||||||
|
Outlet: m.Outlet,
|
||||||
|
SellerId: m.SellerId,
|
||||||
|
SellerName: m.SellerName,
|
||||||
|
Tax: int(taxAmountPerUnit),
|
||||||
|
TaxRate: taxRate,
|
||||||
|
StoreId: m.StoreId,
|
||||||
|
})
|
||||||
|
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
WithTotals(), // Recalculate totals after successful mutation
|
||||||
|
)
|
||||||
|
}
|
||||||
61
mutation_add_request.go
Normal file
61
mutation_add_request.go
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
messages "git.tornberg.me/go-cart-actor/proto"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mutation_add_request.go
|
||||||
|
//
|
||||||
|
// Registers the AddRequest mutation. This mutation is a higher-level intent
|
||||||
|
// (add by SKU + quantity) which may translate into either:
|
||||||
|
// - Increasing quantity of an existing line (same SKU), OR
|
||||||
|
// - Creating a new item by performing a product lookup (via getItemData inside CartGrain.AddItem)
|
||||||
|
//
|
||||||
|
// Behavior:
|
||||||
|
// - Validates non-empty SKU and quantity > 0
|
||||||
|
// - If an item with the SKU already exists: increments its quantity
|
||||||
|
// - Else delegates to CartGrain.AddItem (which itself produces an AddItem mutation)
|
||||||
|
// - Totals recalculated automatically (WithTotals)
|
||||||
|
//
|
||||||
|
// NOTE:
|
||||||
|
// - This handler purposely avoids duplicating the detailed AddItem logic;
|
||||||
|
// it reuses CartGrain.AddItem which then flows through the AddItem mutation
|
||||||
|
// registry handler.
|
||||||
|
// - Double total recalculation can occur (AddItem has WithTotals too), but
|
||||||
|
// is acceptable for clarity. Optimize later if needed.
|
||||||
|
//
|
||||||
|
// Potential future improvements:
|
||||||
|
// - Stock validation before increasing quantity
|
||||||
|
// - Reservation logic or concurrency guards around stock updates
|
||||||
|
// - Coupon / pricing rules applied conditionally during add-by-sku
|
||||||
|
func init() {
|
||||||
|
RegisterMutation[messages.AddRequest](
|
||||||
|
"AddRequest",
|
||||||
|
func(g *CartGrain, m *messages.AddRequest) error {
|
||||||
|
if m == nil {
|
||||||
|
return fmt.Errorf("AddRequest: nil payload")
|
||||||
|
}
|
||||||
|
if m.Sku == "" {
|
||||||
|
return fmt.Errorf("AddRequest: sku is empty")
|
||||||
|
}
|
||||||
|
if m.Quantity < 1 {
|
||||||
|
return fmt.Errorf("AddRequest: invalid quantity %d", m.Quantity)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Existing line: accumulate quantity only.
|
||||||
|
if existing, found := g.FindItemWithSku(m.Sku); found {
|
||||||
|
existing.Quantity += int(m.Quantity)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// New line: delegate to higher-level AddItem flow (product lookup).
|
||||||
|
// We intentionally ignore the returned *CartGrain; registry will
|
||||||
|
// do totals again after this handler returns (harmless).
|
||||||
|
_, err := g.AddItem(m.Sku, int(m.Quantity), m.Country, m.StoreId)
|
||||||
|
return err
|
||||||
|
},
|
||||||
|
WithTotals(),
|
||||||
|
)
|
||||||
|
}
|
||||||
58
mutation_change_quantity.go
Normal file
58
mutation_change_quantity.go
Normal file
@@ -0,0 +1,58 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
messages "git.tornberg.me/go-cart-actor/proto"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mutation_change_quantity.go
|
||||||
|
//
|
||||||
|
// Registers the ChangeQuantity mutation.
|
||||||
|
//
|
||||||
|
// Behavior:
|
||||||
|
// - Locates an item by its cart-local line item Id (not source item_id).
|
||||||
|
// - If requested quantity <= 0 the line is removed.
|
||||||
|
// - Otherwise the line's Quantity field is updated.
|
||||||
|
// - Totals are recalculated (WithTotals).
|
||||||
|
//
|
||||||
|
// Error handling:
|
||||||
|
// - Returns an error if the item Id is not found.
|
||||||
|
// - Returns an error if payload is nil (defensive).
|
||||||
|
//
|
||||||
|
// Concurrency:
|
||||||
|
// - Uses the grain's RW-safe mutation pattern: we mutate in place under
|
||||||
|
// the grain's implicit expectation that higher layers control access.
|
||||||
|
// (If strict locking is required around every mutation, wrap logic in
|
||||||
|
// an explicit g.mu.Lock()/Unlock(), but current model mirrors prior code.)
|
||||||
|
func init() {
|
||||||
|
RegisterMutation[messages.ChangeQuantity](
|
||||||
|
"ChangeQuantity",
|
||||||
|
func(g *CartGrain, m *messages.ChangeQuantity) error {
|
||||||
|
if m == nil {
|
||||||
|
return fmt.Errorf("ChangeQuantity: nil payload")
|
||||||
|
}
|
||||||
|
|
||||||
|
foundIndex := -1
|
||||||
|
for i, it := range g.Items {
|
||||||
|
if it.Id == int(m.Id) {
|
||||||
|
foundIndex = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if foundIndex == -1 {
|
||||||
|
return fmt.Errorf("ChangeQuantity: item id %d not found", m.Id)
|
||||||
|
}
|
||||||
|
|
||||||
|
if m.Quantity <= 0 {
|
||||||
|
// Remove the item
|
||||||
|
g.Items = append(g.Items[:foundIndex], g.Items[foundIndex+1:]...)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
g.Items[foundIndex].Quantity = int(m.Quantity)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
WithTotals(),
|
||||||
|
)
|
||||||
|
}
|
||||||
49
mutation_initialize_checkout.go
Normal file
49
mutation_initialize_checkout.go
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
messages "git.tornberg.me/go-cart-actor/proto"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mutation_initialize_checkout.go
|
||||||
|
//
|
||||||
|
// Registers the InitializeCheckout mutation.
|
||||||
|
// This mutation is invoked AFTER an external Klarna checkout session
|
||||||
|
// has been successfully created or updated. It persists the Klarna
|
||||||
|
// order reference / status and marks the cart as having a payment in progress.
|
||||||
|
//
|
||||||
|
// Behavior:
|
||||||
|
// - Sets OrderReference to the Klarna order ID (overwriting if already set).
|
||||||
|
// - Sets PaymentStatus to the current Klarna status.
|
||||||
|
// - Sets / updates PaymentInProgress flag.
|
||||||
|
// - Does NOT alter pricing or line items (so no totals recalculation).
|
||||||
|
//
|
||||||
|
// Validation:
|
||||||
|
// - Returns an error if payload is nil.
|
||||||
|
// - Returns an error if orderId is empty (integrity guard).
|
||||||
|
//
|
||||||
|
// Concurrency:
|
||||||
|
// - Relies on upstream mutation serialization for a single grain. If
|
||||||
|
// parallel checkout attempts are possible, add higher-level guards
|
||||||
|
// (e.g. reject if PaymentInProgress already true unless reusing
|
||||||
|
// the same OrderReference).
|
||||||
|
func init() {
|
||||||
|
RegisterMutation[messages.InitializeCheckout](
|
||||||
|
"InitializeCheckout",
|
||||||
|
func(g *CartGrain, m *messages.InitializeCheckout) error {
|
||||||
|
if m == nil {
|
||||||
|
return fmt.Errorf("InitializeCheckout: nil payload")
|
||||||
|
}
|
||||||
|
if m.OrderId == "" {
|
||||||
|
return fmt.Errorf("InitializeCheckout: missing orderId")
|
||||||
|
}
|
||||||
|
|
||||||
|
g.OrderReference = m.OrderId
|
||||||
|
g.PaymentStatus = m.Status
|
||||||
|
g.PaymentInProgress = m.PaymentInProgress
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
// No WithTotals(): monetary aggregates are unaffected.
|
||||||
|
)
|
||||||
|
}
|
||||||
53
mutation_order_created.go
Normal file
53
mutation_order_created.go
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
messages "git.tornberg.me/go-cart-actor/proto"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mutation_order_created.go
|
||||||
|
//
|
||||||
|
// Registers the OrderCreated mutation.
|
||||||
|
//
|
||||||
|
// This mutation represents the completion (or state transition) of an order
|
||||||
|
// initiated earlier via InitializeCheckout / external Klarna processing.
|
||||||
|
// It finalizes (or updates) the cart's order metadata.
|
||||||
|
//
|
||||||
|
// Behavior:
|
||||||
|
// - Validates payload non-nil and OrderId not empty.
|
||||||
|
// - Sets (or overwrites) OrderReference with the provided OrderId.
|
||||||
|
// - Sets PaymentStatus from payload.Status.
|
||||||
|
// - Marks PaymentInProgress = false (checkout flow finished / acknowledged).
|
||||||
|
// - Does NOT adjust monetary totals (no WithTotals()).
|
||||||
|
//
|
||||||
|
// Notes / Future Extensions:
|
||||||
|
// - If multiple order completion events can arrive (e.g., retries / webhook
|
||||||
|
// replays), this handler is idempotent: it simply overwrites fields.
|
||||||
|
// - If you need to guard against conflicting order IDs, add a check:
|
||||||
|
// if g.OrderReference != "" && g.OrderReference != m.OrderId { ... }
|
||||||
|
// - Add audit logging or metrics here if required.
|
||||||
|
//
|
||||||
|
// Concurrency:
|
||||||
|
// - Relies on the higher-level guarantee that Apply() calls are serialized
|
||||||
|
// per grain. If out-of-order events are possible, embed versioning or
|
||||||
|
// timestamps in the mutation and compare before applying changes.
|
||||||
|
func init() {
|
||||||
|
RegisterMutation[messages.OrderCreated](
|
||||||
|
"OrderCreated",
|
||||||
|
func(g *CartGrain, m *messages.OrderCreated) error {
|
||||||
|
if m == nil {
|
||||||
|
return fmt.Errorf("OrderCreated: nil payload")
|
||||||
|
}
|
||||||
|
if m.OrderId == "" {
|
||||||
|
return fmt.Errorf("OrderCreated: missing orderId")
|
||||||
|
}
|
||||||
|
|
||||||
|
g.OrderReference = m.OrderId
|
||||||
|
g.PaymentStatus = m.Status
|
||||||
|
g.PaymentInProgress = false
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
// No WithTotals(): order completion does not modify pricing or taxes.
|
||||||
|
)
|
||||||
|
}
|
||||||
301
mutation_registry.go
Normal file
301
mutation_registry.go
Normal file
@@ -0,0 +1,301 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mutation_registry.go
|
||||||
|
//
|
||||||
|
// Mutation Registry Infrastructure
|
||||||
|
// --------------------------------
|
||||||
|
// This file introduces a generic registry for cart mutations that:
|
||||||
|
//
|
||||||
|
// 1. Decouples mutation logic from the large type-switch inside CartGrain.Apply.
|
||||||
|
// 2. Enforces (at registration time) that every mutation handler has the correct
|
||||||
|
// signature: func(*CartGrain, *T) error
|
||||||
|
// 3. Optionally auto-updates cart totals after a mutation if flagged.
|
||||||
|
// 4. Provides a single authoritative list of registered mutations for
|
||||||
|
// introspection / coverage testing.
|
||||||
|
// 5. Allows incremental migration: you can first register new mutations here,
|
||||||
|
// and later prune the legacy switch cases.
|
||||||
|
//
|
||||||
|
// Usage Pattern
|
||||||
|
// -------------
|
||||||
|
// // Define your mutation proto message (e.g. messages.ApplyCoupon in messages.proto)
|
||||||
|
// // Regenerate protobufs.
|
||||||
|
//
|
||||||
|
// // In an init() (ideally in a small file like mutations_apply_coupon.go)
|
||||||
|
// func init() {
|
||||||
|
// RegisterMutation[*messages.ApplyCoupon](
|
||||||
|
// "ApplyCoupon",
|
||||||
|
// func(g *CartGrain, m *messages.ApplyCoupon) error {
|
||||||
|
// // domain logic ...
|
||||||
|
// discount := int64(5000)
|
||||||
|
// if g.TotalPrice < discount {
|
||||||
|
// discount = g.TotalPrice
|
||||||
|
// }
|
||||||
|
// g.TotalDiscount += discount
|
||||||
|
// g.TotalPrice -= discount
|
||||||
|
// return nil
|
||||||
|
// },
|
||||||
|
// WithTotals(), // we changed price-related fields; recalc totals
|
||||||
|
// )
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// // To invoke dynamically (alternative to the current switch):
|
||||||
|
// if updated, err := ApplyRegistered(grain, incomingMessage); err == nil {
|
||||||
|
// grain = updated
|
||||||
|
// } else if errors.Is(err, ErrMutationNotRegistered) {
|
||||||
|
// // fallback to legacy switch logic
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// Migration Strategy
|
||||||
|
// ------------------
|
||||||
|
// 1. For each existing mutation handled in CartGrain.Apply, add a registry
|
||||||
|
// registration with equivalent logic.
|
||||||
|
// 2. Add a test that enumerates all *expected* mutation proto types and asserts
|
||||||
|
// they are present in RegisteredMutationTypes().
|
||||||
|
// 3. Once coverage is 100%, replace the switch in CartGrain.Apply with a call
|
||||||
|
// to ApplyRegistered (and optionally keep a minimal default to produce an
|
||||||
|
// "unsupported mutation" error).
|
||||||
|
//
|
||||||
|
// Thread Safety
|
||||||
|
// -------------
|
||||||
|
// Registration is typically done at init() time; a RWMutex provides safety
|
||||||
|
// should late dynamic registration ever be introduced.
|
||||||
|
//
|
||||||
|
// Auto Totals
|
||||||
|
// -----------
|
||||||
|
// Many mutations require recomputing totals. To avoid forgetting this, pass
|
||||||
|
// WithTotals() when registering. This will invoke grain.UpdateTotals() after
|
||||||
|
// the handler returns successfully.
|
||||||
|
//
|
||||||
|
// Error Semantics
|
||||||
|
// ---------------
|
||||||
|
// - If a handler returns an error, totals are NOT recalculated (even if
|
||||||
|
// WithTotals() was specified).
|
||||||
|
// - ApplyRegistered returns (nil, ErrMutationNotRegistered) if the message type
|
||||||
|
// is absent.
|
||||||
|
//
|
||||||
|
// Extensibility
|
||||||
|
// -------------
|
||||||
|
// It is straightforward to add options like audit hooks, metrics wrappers,
|
||||||
|
// or optimistic concurrency guards by extending MutationOption.
|
||||||
|
//
|
||||||
|
// NOTE: Generics require Go 1.18+. If constrained to earlier Go versions,
|
||||||
|
// replace the generic registration with a non-generic RegisterMutationType
|
||||||
|
// that accepts reflect.Type and an adapter function.
|
||||||
|
//
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
var (
|
||||||
|
mutationRegistryMu sync.RWMutex
|
||||||
|
mutationRegistry = make(map[reflect.Type]*registeredMutation)
|
||||||
|
|
||||||
|
// ErrMutationNotRegistered is returned when no handler exists for a given mutation type.
|
||||||
|
ErrMutationNotRegistered = fmt.Errorf("mutation not registered")
|
||||||
|
)
|
||||||
|
|
||||||
|
// MutationOption configures additional behavior for a registered mutation.
|
||||||
|
type MutationOption func(*mutationOptions)
|
||||||
|
|
||||||
|
// mutationOptions holds flags adjustable per registration.
|
||||||
|
type mutationOptions struct {
|
||||||
|
updateTotals bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// WithTotals ensures CartGrain.UpdateTotals() is called after a successful handler.
|
||||||
|
func WithTotals() MutationOption {
|
||||||
|
return func(o *mutationOptions) {
|
||||||
|
o.updateTotals = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// registeredMutation stores metadata + the execution closure.
|
||||||
|
type registeredMutation struct {
|
||||||
|
name string
|
||||||
|
handler func(*CartGrain, interface{}) error
|
||||||
|
updateTotals bool
|
||||||
|
msgType reflect.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegisterMutation registers a mutation handler for a specific message type T.
|
||||||
|
//
|
||||||
|
// Parameters:
|
||||||
|
//
|
||||||
|
// name - a human-readable identifier (used for diagnostics / coverage tests).
|
||||||
|
// handler - business logic operating on the cart grain & strongly typed message.
|
||||||
|
// options - optional behavior flags (e.g., WithTotals()).
|
||||||
|
//
|
||||||
|
// Panics if:
|
||||||
|
// - name is empty
|
||||||
|
// - handler is nil
|
||||||
|
// - duplicate registration for the same message type T
|
||||||
|
//
|
||||||
|
// Typical call is placed in an init() function.
|
||||||
|
func RegisterMutation[T any](name string, handler func(*CartGrain, *T) error, options ...MutationOption) {
|
||||||
|
if name == "" {
|
||||||
|
panic("RegisterMutation: name is required")
|
||||||
|
}
|
||||||
|
if handler == nil {
|
||||||
|
panic("RegisterMutation: handler is nil")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Derive the reflect.Type for *T then its Elem (T) for mapping.
|
||||||
|
var zero *T
|
||||||
|
rtPtr := reflect.TypeOf(zero)
|
||||||
|
if rtPtr.Kind() != reflect.Ptr {
|
||||||
|
panic("RegisterMutation: expected pointer type for generic parameter")
|
||||||
|
}
|
||||||
|
rt := rtPtr.Elem()
|
||||||
|
|
||||||
|
opts := mutationOptions{}
|
||||||
|
for _, opt := range options {
|
||||||
|
opt(&opts)
|
||||||
|
}
|
||||||
|
|
||||||
|
wrapped := func(g *CartGrain, m interface{}) error {
|
||||||
|
typed, ok := m.(*T)
|
||||||
|
if !ok {
|
||||||
|
return fmt.Errorf("mutation type mismatch: have %T want *%s", m, rt.Name())
|
||||||
|
}
|
||||||
|
return handler(g, typed)
|
||||||
|
}
|
||||||
|
|
||||||
|
mutationRegistryMu.Lock()
|
||||||
|
defer mutationRegistryMu.Unlock()
|
||||||
|
|
||||||
|
if _, exists := mutationRegistry[rt]; exists {
|
||||||
|
panic(fmt.Sprintf("RegisterMutation: duplicate registration for type %s", rt.String()))
|
||||||
|
}
|
||||||
|
|
||||||
|
mutationRegistry[rt] = ®isteredMutation{
|
||||||
|
name: name,
|
||||||
|
handler: wrapped,
|
||||||
|
updateTotals: opts.updateTotals,
|
||||||
|
msgType: rt,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ApplyRegistered attempts to apply a registered mutation.
|
||||||
|
// Returns updated grain if successful.
|
||||||
|
//
|
||||||
|
// If the mutation is not registered, returns (nil, ErrMutationNotRegistered).
|
||||||
|
func ApplyRegistered(grain *CartGrain, msg interface{}) (*CartGrain, error) {
|
||||||
|
if grain == nil {
|
||||||
|
return nil, fmt.Errorf("nil grain")
|
||||||
|
}
|
||||||
|
if msg == nil {
|
||||||
|
return nil, fmt.Errorf("nil mutation message")
|
||||||
|
}
|
||||||
|
|
||||||
|
rt := indirectType(reflect.TypeOf(msg))
|
||||||
|
mutationRegistryMu.RLock()
|
||||||
|
entry, ok := mutationRegistry[rt]
|
||||||
|
mutationRegistryMu.RUnlock()
|
||||||
|
|
||||||
|
if !ok {
|
||||||
|
return nil, ErrMutationNotRegistered
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := entry.handler(grain, msg); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if entry.updateTotals {
|
||||||
|
grain.UpdateTotals()
|
||||||
|
}
|
||||||
|
|
||||||
|
return grain, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegisteredMutations returns metadata for all registered mutations (snapshot).
|
||||||
|
func RegisteredMutations() []string {
|
||||||
|
mutationRegistryMu.RLock()
|
||||||
|
defer mutationRegistryMu.RUnlock()
|
||||||
|
out := make([]string, 0, len(mutationRegistry))
|
||||||
|
for _, entry := range mutationRegistry {
|
||||||
|
out = append(out, entry.name)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// RegisteredMutationTypes returns the reflect.Type list of all registered messages.
|
||||||
|
// Useful for coverage tests ensuring expected set matches actual set.
|
||||||
|
func RegisteredMutationTypes() []reflect.Type {
|
||||||
|
mutationRegistryMu.RLock()
|
||||||
|
defer mutationRegistryMu.RUnlock()
|
||||||
|
out := make([]reflect.Type, 0, len(mutationRegistry))
|
||||||
|
for t := range mutationRegistry {
|
||||||
|
out = append(out, t)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// MustAssertMutationCoverage can be called at startup to ensure every expected
|
||||||
|
// mutation type has been registered. It panics with a descriptive message if any
|
||||||
|
// are missing. Provide a slice of prototype pointers (e.g. []*messages.AddItem{nil} ...)
|
||||||
|
func MustAssertMutationCoverage(expected []interface{}) {
|
||||||
|
mutationRegistryMu.RLock()
|
||||||
|
defer mutationRegistryMu.RUnlock()
|
||||||
|
|
||||||
|
missing := make([]string, 0)
|
||||||
|
for _, ex := range expected {
|
||||||
|
if ex == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
t := indirectType(reflect.TypeOf(ex))
|
||||||
|
if _, ok := mutationRegistry[t]; !ok {
|
||||||
|
missing = append(missing, t.String())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(missing) > 0 {
|
||||||
|
panic(fmt.Sprintf("mutation registry missing handlers for: %v", missing))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// indirectType returns the element type if given a pointer; otherwise the type itself.
|
||||||
|
func indirectType(t reflect.Type) reflect.Type {
|
||||||
|
for t.Kind() == reflect.Ptr {
|
||||||
|
t = t.Elem()
|
||||||
|
}
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
Integration Guide
|
||||||
|
-----------------
|
||||||
|
|
||||||
|
1. Register all existing mutations:
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
RegisterMutation[*messages.AddItem]("AddItem",
|
||||||
|
func(g *CartGrain, m *messages.AddItem) error {
|
||||||
|
// (port logic from existing switch branch)
|
||||||
|
// ...
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
WithTotals(),
|
||||||
|
)
|
||||||
|
// ... repeat for others
|
||||||
|
}
|
||||||
|
|
||||||
|
2. In CartGrain.Apply (early in the method) add:
|
||||||
|
|
||||||
|
if updated, err := ApplyRegistered(c, content); err == nil {
|
||||||
|
return updated, nil
|
||||||
|
} else if err != ErrMutationNotRegistered {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// existing switch fallback below
|
||||||
|
|
||||||
|
3. Once all mutations are registered, remove the legacy switch cases
|
||||||
|
and leave a single ErrMutationNotRegistered path for unknown types.
|
||||||
|
|
||||||
|
4. Add a coverage test (see docs for example; removed from source for clarity).
|
||||||
|
5. (Optional) Add metrics / tracing wrappers for handlers.
|
||||||
|
|
||||||
|
*/
|
||||||
53
mutation_remove_delivery.go
Normal file
53
mutation_remove_delivery.go
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
messages "git.tornberg.me/go-cart-actor/proto"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mutation_remove_delivery.go
|
||||||
|
//
|
||||||
|
// Registers the RemoveDelivery mutation.
|
||||||
|
//
|
||||||
|
// Behavior:
|
||||||
|
// - Removes the delivery entry whose Id == payload.Id.
|
||||||
|
// - If not found, returns an error.
|
||||||
|
// - Cart totals are recalculated (WithTotals) after removal.
|
||||||
|
// - Items previously associated with that delivery simply become "without delivery";
|
||||||
|
// subsequent delivery mutations can reassign them.
|
||||||
|
//
|
||||||
|
// Differences vs legacy:
|
||||||
|
// - Legacy logic decremented TotalPrice explicitly before recalculating.
|
||||||
|
// Here we rely solely on UpdateTotals() to recompute from remaining
|
||||||
|
// deliveries and items (simpler / single source of truth).
|
||||||
|
//
|
||||||
|
// Future considerations:
|
||||||
|
// - If delivery pricing logic changes (e.g., dynamic taxes per delivery),
|
||||||
|
// UpdateTotals() may need enhancement to incorporate delivery tax properly.
|
||||||
|
func init() {
|
||||||
|
RegisterMutation[messages.RemoveDelivery](
|
||||||
|
"RemoveDelivery",
|
||||||
|
func(g *CartGrain, m *messages.RemoveDelivery) error {
|
||||||
|
if m == nil {
|
||||||
|
return fmt.Errorf("RemoveDelivery: nil payload")
|
||||||
|
}
|
||||||
|
targetID := int(m.Id)
|
||||||
|
index := -1
|
||||||
|
for i, d := range g.Deliveries {
|
||||||
|
if d.Id == targetID {
|
||||||
|
index = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if index == -1 {
|
||||||
|
return fmt.Errorf("RemoveDelivery: delivery id %d not found", m.Id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Remove delivery (order not preserved beyond necessity)
|
||||||
|
g.Deliveries = append(g.Deliveries[:index], g.Deliveries[index+1:]...)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
WithTotals(),
|
||||||
|
)
|
||||||
|
}
|
||||||
49
mutation_remove_item.go
Normal file
49
mutation_remove_item.go
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
messages "git.tornberg.me/go-cart-actor/proto"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mutation_remove_item.go
|
||||||
|
//
|
||||||
|
// Registers the RemoveItem mutation.
|
||||||
|
//
|
||||||
|
// Behavior:
|
||||||
|
// - Removes the cart line whose local cart line Id == payload.Id
|
||||||
|
// - If no such line exists returns an error
|
||||||
|
// - Recalculates cart totals (WithTotals)
|
||||||
|
//
|
||||||
|
// Notes:
|
||||||
|
// - This removes only the line item; any deliveries referencing the removed
|
||||||
|
// item are NOT automatically adjusted (mirrors prior logic). If future
|
||||||
|
// semantics require pruning delivery.item_ids you can extend this handler.
|
||||||
|
// - If multiple lines somehow shared the same Id (should not happen), only
|
||||||
|
// the first match would be removed—data integrity relies on unique line Ids.
|
||||||
|
func init() {
|
||||||
|
RegisterMutation[messages.RemoveItem](
|
||||||
|
"RemoveItem",
|
||||||
|
func(g *CartGrain, m *messages.RemoveItem) error {
|
||||||
|
if m == nil {
|
||||||
|
return fmt.Errorf("RemoveItem: nil payload")
|
||||||
|
}
|
||||||
|
targetID := int(m.Id)
|
||||||
|
|
||||||
|
index := -1
|
||||||
|
for i, it := range g.Items {
|
||||||
|
if it.Id == targetID {
|
||||||
|
index = i
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if index == -1 {
|
||||||
|
return fmt.Errorf("RemoveItem: item id %d not found", m.Id)
|
||||||
|
}
|
||||||
|
|
||||||
|
g.Items = append(g.Items[:index], g.Items[index+1:]...)
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
WithTotals(),
|
||||||
|
)
|
||||||
|
}
|
||||||
57
mutation_set_cart_items.go
Normal file
57
mutation_set_cart_items.go
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
messages "git.tornberg.me/go-cart-actor/proto"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mutation_set_cart_items.go
|
||||||
|
//
|
||||||
|
// Registers the SetCartRequest mutation. This mutation replaces the entire list
|
||||||
|
// of cart items with the provided list (each entry is an AddRequest).
|
||||||
|
//
|
||||||
|
// Behavior:
|
||||||
|
// - Clears existing items (but leaves deliveries intact).
|
||||||
|
// - Iterates over each AddRequest and delegates to CartGrain.AddItem
|
||||||
|
// (which performs product lookup, creates AddItem mutation).
|
||||||
|
// - If any single addition fails, the mutation aborts with an error;
|
||||||
|
// items added prior to the failure remain (consistent with previous behavior).
|
||||||
|
// - Totals recalculated after completion via WithTotals().
|
||||||
|
//
|
||||||
|
// Notes:
|
||||||
|
// - Potential optimization: batch product lookups; currently sequential.
|
||||||
|
// - Consider adding rollback semantics if atomic replacement is desired.
|
||||||
|
// - Deliveries might reference item IDs that are now invalid—original logic
|
||||||
|
// also left deliveries untouched. If that becomes an issue, add a cleanup
|
||||||
|
// pass to remove deliveries whose item IDs no longer exist.
|
||||||
|
func init() {
|
||||||
|
RegisterMutation[messages.SetCartRequest](
|
||||||
|
"SetCartRequest",
|
||||||
|
func(g *CartGrain, m *messages.SetCartRequest) error {
|
||||||
|
if m == nil {
|
||||||
|
return fmt.Errorf("SetCartRequest: nil payload")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clear current items (keep deliveries)
|
||||||
|
g.mu.Lock()
|
||||||
|
g.Items = make([]*CartItem, 0, len(m.Items))
|
||||||
|
g.mu.Unlock()
|
||||||
|
|
||||||
|
for _, it := range m.Items {
|
||||||
|
if it == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if it.Sku == "" || it.Quantity < 1 {
|
||||||
|
return fmt.Errorf("SetCartRequest: invalid item (sku='%s' qty=%d)", it.Sku, it.Quantity)
|
||||||
|
}
|
||||||
|
_, err := g.AddItem(it.Sku, int(it.Quantity), it.Country, it.StoreId)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("SetCartRequest: add sku '%s' failed: %w", it.Sku, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
WithTotals(),
|
||||||
|
)
|
||||||
|
}
|
||||||
101
mutation_set_delivery.go
Normal file
101
mutation_set_delivery.go
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"slices"
|
||||||
|
|
||||||
|
messages "git.tornberg.me/go-cart-actor/proto"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mutation_set_delivery.go
|
||||||
|
//
|
||||||
|
// Registers the SetDelivery mutation.
|
||||||
|
//
|
||||||
|
// Semantics (mirrors legacy switch logic):
|
||||||
|
// - If the payload specifies an explicit list of item IDs (payload.Items):
|
||||||
|
// - Each referenced cart line must exist.
|
||||||
|
// - None of the referenced items may already belong to a delivery.
|
||||||
|
// - Only those items are associated with the new delivery.
|
||||||
|
// - If payload.Items is empty:
|
||||||
|
// - All items currently without any delivery are associated with the new delivery.
|
||||||
|
// - A new delivery line is created with:
|
||||||
|
// - Auto-incremented delivery ID (cart-local)
|
||||||
|
// - Provider from payload
|
||||||
|
// - Fixed price (currently hard-coded: 4900 minor units) – adjust as needed
|
||||||
|
// - Optional PickupPoint copied from payload
|
||||||
|
// - Cart totals are recalculated (WithTotals)
|
||||||
|
//
|
||||||
|
// Error cases:
|
||||||
|
// - Referenced item does not exist
|
||||||
|
// - Referenced item already has a delivery
|
||||||
|
// - No items qualify (resulting association set empty) -> returns error (prevents creating empty delivery)
|
||||||
|
//
|
||||||
|
// Concurrency:
|
||||||
|
// - Uses g.mu to protect lastDeliveryId increment and append to Deliveries slice.
|
||||||
|
// Item scans are read-only and performed outside the lock for simplicity;
|
||||||
|
// if stricter guarantees are needed, widen the lock section.
|
||||||
|
//
|
||||||
|
// Future extension points:
|
||||||
|
// - Variable delivery pricing (based on weight, distance, provider, etc.)
|
||||||
|
// - Validation of provider codes
|
||||||
|
// - Multi-currency delivery pricing
|
||||||
|
func init() {
|
||||||
|
RegisterMutation[messages.SetDelivery](
|
||||||
|
"SetDelivery",
|
||||||
|
func(g *CartGrain, m *messages.SetDelivery) error {
|
||||||
|
if m == nil {
|
||||||
|
return fmt.Errorf("SetDelivery: nil payload")
|
||||||
|
}
|
||||||
|
if m.Provider == "" {
|
||||||
|
return fmt.Errorf("SetDelivery: provider is empty")
|
||||||
|
}
|
||||||
|
|
||||||
|
withDelivery := g.ItemsWithDelivery()
|
||||||
|
targetItems := make([]int, 0)
|
||||||
|
|
||||||
|
if len(m.Items) == 0 {
|
||||||
|
// Use every item currently without a delivery
|
||||||
|
targetItems = append(targetItems, g.ItemsWithoutDelivery()...)
|
||||||
|
} else {
|
||||||
|
// Validate explicit list
|
||||||
|
for _, id64 := range m.Items {
|
||||||
|
id := int(id64)
|
||||||
|
found := false
|
||||||
|
for _, it := range g.Items {
|
||||||
|
if it.Id == id {
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !found {
|
||||||
|
return fmt.Errorf("SetDelivery: item id %d not found", id)
|
||||||
|
}
|
||||||
|
if slices.Contains(withDelivery, id) {
|
||||||
|
return fmt.Errorf("SetDelivery: item id %d already has a delivery", id)
|
||||||
|
}
|
||||||
|
targetItems = append(targetItems, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(targetItems) == 0 {
|
||||||
|
return fmt.Errorf("SetDelivery: no eligible items to attach")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Append new delivery
|
||||||
|
g.mu.Lock()
|
||||||
|
g.lastDeliveryId++
|
||||||
|
newId := g.lastDeliveryId
|
||||||
|
g.Deliveries = append(g.Deliveries, &CartDelivery{
|
||||||
|
Id: newId,
|
||||||
|
Provider: m.Provider,
|
||||||
|
PickupPoint: m.PickupPoint,
|
||||||
|
Price: 4900, // TODO: externalize pricing
|
||||||
|
Items: targetItems,
|
||||||
|
})
|
||||||
|
g.mu.Unlock()
|
||||||
|
|
||||||
|
return nil
|
||||||
|
},
|
||||||
|
WithTotals(),
|
||||||
|
)
|
||||||
|
}
|
||||||
56
mutation_set_pickup_point.go
Normal file
56
mutation_set_pickup_point.go
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
|
||||||
|
messages "git.tornberg.me/go-cart-actor/proto"
|
||||||
|
)
|
||||||
|
|
||||||
|
// mutation_set_pickup_point.go
|
||||||
|
//
|
||||||
|
// Registers the SetPickupPoint mutation using the generic mutation registry.
|
||||||
|
//
|
||||||
|
// Semantics (mirrors original switch-based implementation):
|
||||||
|
// - Locate the delivery with Id == payload.DeliveryId
|
||||||
|
// - Set (or overwrite) its PickupPoint with the provided data
|
||||||
|
// - Does NOT alter pricing or taxes (so no totals recalculation required)
|
||||||
|
//
|
||||||
|
// Validation / Error Handling:
|
||||||
|
// - If payload is nil -> error
|
||||||
|
// - If DeliveryId not found -> error
|
||||||
|
//
|
||||||
|
// Concurrency:
|
||||||
|
// - Relies on the existing expectation that higher-level mutation routing
|
||||||
|
// serializes Apply() calls per grain; if stricter guarantees are needed,
|
||||||
|
// a delivery-level lock could be introduced later.
|
||||||
|
//
|
||||||
|
// Future Extensions:
|
||||||
|
// - Validate pickup point fields (country code, zip format, etc.)
|
||||||
|
// - Track history / audit of pickup point changes
|
||||||
|
// - Trigger delivery price adjustments (which would then require WithTotals()).
|
||||||
|
func init() {
|
||||||
|
RegisterMutation[messages.SetPickupPoint](
|
||||||
|
"SetPickupPoint",
|
||||||
|
func(g *CartGrain, m *messages.SetPickupPoint) error {
|
||||||
|
if m == nil {
|
||||||
|
return fmt.Errorf("SetPickupPoint: nil payload")
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, d := range g.Deliveries {
|
||||||
|
if d.Id == int(m.DeliveryId) {
|
||||||
|
d.PickupPoint = &messages.PickupPoint{
|
||||||
|
Id: m.Id,
|
||||||
|
Name: m.Name,
|
||||||
|
Address: m.Address,
|
||||||
|
City: m.City,
|
||||||
|
Zip: m.Zip,
|
||||||
|
Country: m.Country,
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fmt.Errorf("SetPickupPoint: delivery id %d not found", m.DeliveryId)
|
||||||
|
},
|
||||||
|
// No WithTotals(): pickup point does not change pricing / tax.
|
||||||
|
)
|
||||||
|
}
|
||||||
148
pool-server.go
148
pool-server.go
@@ -1,6 +1,7 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
@@ -24,21 +25,26 @@ func NewPoolServer(pool GrainPool, pod_name string) *PoolServer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (s *PoolServer) process(id CartId, mutation interface{}) (*messages.CartState, error) {
|
||||||
|
grain, err := s.pool.Apply(id, mutation)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return ToCartState(grain), nil
|
||||||
|
}
|
||||||
|
|
||||||
func (s *PoolServer) HandleGet(w http.ResponseWriter, r *http.Request, id CartId) error {
|
func (s *PoolServer) HandleGet(w http.ResponseWriter, r *http.Request, id CartId) error {
|
||||||
data, err := s.pool.Get(id)
|
grain, err := s.pool.Get(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
return s.WriteResult(w, data)
|
return s.WriteResult(w, ToCartState(grain))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *PoolServer) HandleAddSku(w http.ResponseWriter, r *http.Request, id CartId) error {
|
func (s *PoolServer) HandleAddSku(w http.ResponseWriter, r *http.Request, id CartId) error {
|
||||||
sku := r.PathValue("sku")
|
sku := r.PathValue("sku")
|
||||||
data, err := s.pool.Process(id, Message{
|
data, err := s.process(id, &messages.AddRequest{Sku: sku, Quantity: 1})
|
||||||
Type: AddRequestType,
|
|
||||||
Content: &messages.AddRequest{Sku: sku, Quantity: 1},
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -56,23 +62,20 @@ func ErrorHandler(fn func(w http.ResponseWriter, r *http.Request) error) func(w
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *PoolServer) WriteResult(w http.ResponseWriter, result *FrameWithPayload) error {
|
func (s *PoolServer) WriteResult(w http.ResponseWriter, result *messages.CartState) error {
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
w.Header().Set("Cache-Control", "no-cache")
|
w.Header().Set("Cache-Control", "no-cache")
|
||||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||||
w.Header().Set("X-Pod-Name", s.pod_name)
|
w.Header().Set("X-Pod-Name", s.pod_name)
|
||||||
if result.StatusCode != 200 {
|
if result == nil {
|
||||||
log.Printf("Call error: %d\n", result.StatusCode)
|
|
||||||
if result.StatusCode >= 200 && result.StatusCode < 600 {
|
w.WriteHeader(http.StatusInternalServerError)
|
||||||
w.WriteHeader(int(result.StatusCode))
|
|
||||||
} else {
|
|
||||||
w.WriteHeader(http.StatusInternalServerError)
|
|
||||||
}
|
|
||||||
w.Write([]byte(result.Payload))
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
_, err := w.Write(result.Payload)
|
enc := json.NewEncoder(w)
|
||||||
|
err := enc.Encode(result)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -83,10 +86,7 @@ func (s *PoolServer) HandleDeleteItem(w http.ResponseWriter, r *http.Request, id
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
data, err := s.pool.Process(id, Message{
|
data, err := s.process(id, &messages.RemoveItem{Id: int64(itemId)})
|
||||||
Type: RemoveItemType,
|
|
||||||
Content: &messages.RemoveItem{Id: int64(itemId)},
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -106,13 +106,10 @@ func (s *PoolServer) HandleSetDelivery(w http.ResponseWriter, r *http.Request, i
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
data, err := s.pool.Process(id, Message{
|
data, err := s.process(id, &messages.SetDelivery{
|
||||||
Type: SetDeliveryType,
|
Provider: delivery.Provider,
|
||||||
Content: &messages.SetDelivery{
|
Items: delivery.Items,
|
||||||
Provider: delivery.Provider,
|
PickupPoint: delivery.PickupPoint,
|
||||||
Items: delivery.Items,
|
|
||||||
PickupPoint: delivery.PickupPoint,
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -132,17 +129,14 @@ func (s *PoolServer) HandleSetPickupPoint(w http.ResponseWriter, r *http.Request
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
reply, err := s.pool.Process(id, Message{
|
reply, err := s.process(id, &messages.SetPickupPoint{
|
||||||
Type: SetPickupPointType,
|
DeliveryId: int64(deliveryId),
|
||||||
Content: &messages.SetPickupPoint{
|
Id: pickupPoint.Id,
|
||||||
DeliveryId: int64(deliveryId),
|
Name: pickupPoint.Name,
|
||||||
Id: pickupPoint.Id,
|
Address: pickupPoint.Address,
|
||||||
Name: pickupPoint.Name,
|
City: pickupPoint.City,
|
||||||
Address: pickupPoint.Address,
|
Zip: pickupPoint.Zip,
|
||||||
City: pickupPoint.City,
|
Country: pickupPoint.Country,
|
||||||
Zip: pickupPoint.Zip,
|
|
||||||
Country: pickupPoint.Country,
|
|
||||||
},
|
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -157,10 +151,7 @@ func (s *PoolServer) HandleRemoveDelivery(w http.ResponseWriter, r *http.Request
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
reply, err := s.pool.Process(id, Message{
|
reply, err := s.process(id, &messages.RemoveDelivery{Id: int64(deliveryId)})
|
||||||
Type: RemoveDeliveryType,
|
|
||||||
Content: &messages.RemoveDelivery{Id: int64(deliveryId)},
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -173,10 +164,7 @@ func (s *PoolServer) HandleQuantityChange(w http.ResponseWriter, r *http.Request
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
reply, err := s.pool.Process(id, Message{
|
reply, err := s.process(id, &changeQuantity)
|
||||||
Type: ChangeQuantityType,
|
|
||||||
Content: &changeQuantity,
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -189,10 +177,7 @@ func (s *PoolServer) HandleSetCartItems(w http.ResponseWriter, r *http.Request,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
reply, err := s.pool.Process(id, Message{
|
reply, err := s.process(id, &setCartItems)
|
||||||
Type: SetCartItemsType,
|
|
||||||
Content: &setCartItems,
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -205,10 +190,7 @@ func (s *PoolServer) HandleAddRequest(w http.ResponseWriter, r *http.Request, id
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
reply, err := s.pool.Process(id, Message{
|
reply, err := s.process(id, &addRequest)
|
||||||
Type: AddRequestType,
|
|
||||||
Content: &addRequest,
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -235,30 +217,50 @@ func (s *PoolServer) HandleConfirmation(w http.ResponseWriter, r *http.Request,
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s *PoolServer) HandleCheckout(w http.ResponseWriter, r *http.Request, id CartId) error {
|
func (s *PoolServer) HandleCheckout(w http.ResponseWriter, r *http.Request, id CartId) error {
|
||||||
|
// Build checkout meta (URLs derived from host)
|
||||||
|
meta := &CheckoutMeta{
|
||||||
|
Terms: fmt.Sprintf("https://%s/terms", r.Host),
|
||||||
|
Checkout: fmt.Sprintf("https://%s/checkout?order_id={checkout.order.id}", r.Host),
|
||||||
|
Confirmation: fmt.Sprintf("https://%s/confirmation/{checkout.order.id}", r.Host),
|
||||||
|
Validation: fmt.Sprintf("https://%s/validate", r.Host),
|
||||||
|
Push: fmt.Sprintf("https://%s/push?order_id={checkout.order.id}", r.Host),
|
||||||
|
Country: getCountryFromHost(r.Host),
|
||||||
|
}
|
||||||
|
|
||||||
reply, err := s.pool.Process(id, Message{
|
// Get current grain state (may be local or remote)
|
||||||
Type: CreateCheckoutOrderType,
|
grain, err := s.pool.Get(id)
|
||||||
Content: &messages.CreateCheckoutOrder{
|
|
||||||
Terms: "https://slask-finder.tornberg.me/terms",
|
|
||||||
Checkout: "https://slask-finder.tornberg.me/checkout?order_id={checkout.order.id}",
|
|
||||||
Confirmation: "https://slask-finder.tornberg.me/confirmation/{checkout.order.id}",
|
|
||||||
Push: "https://cart.tornberg.me/push?order_id={checkout.order.id}",
|
|
||||||
},
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if reply.StatusCode != 200 {
|
|
||||||
return s.WriteResult(w, reply)
|
// Build pure checkout payload
|
||||||
|
payload, _, err := BuildCheckoutOrderPayload(grain, meta)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// w.Header().Set("Content-Type", "application/json")
|
// Call Klarna (create or update)
|
||||||
// w.Header().Set("X-Pod-Name", s.pod_name)
|
var klarnaOrder *CheckoutOrder
|
||||||
// w.Header().Set("Cache-Control", "no-cache")
|
if grain.OrderReference != "" {
|
||||||
// w.Header().Set("Access-Control-Allow-Origin", "*")
|
klarnaOrder, err = KlarnaInstance.UpdateOrder(grain.OrderReference, bytes.NewReader(payload))
|
||||||
// w.WriteHeader(http.StatusOK)
|
} else {
|
||||||
|
klarnaOrder, err = KlarnaInstance.CreateOrder(bytes.NewReader(payload))
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
return s.WriteResult(w, reply)
|
// Persist initialization state via mutation (best-effort)
|
||||||
|
if _, applyErr := s.pool.Apply(id, &messages.InitializeCheckout{
|
||||||
|
OrderId: klarnaOrder.ID,
|
||||||
|
Status: klarnaOrder.Status,
|
||||||
|
PaymentInProgress: true,
|
||||||
|
}); applyErr != nil {
|
||||||
|
log.Printf("InitializeCheckout apply error: %v", applyErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
return json.NewEncoder(w).Encode(klarnaOrder)
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewCartId() CartId {
|
func NewCartId() CartId {
|
||||||
@@ -276,7 +278,7 @@ func CookieCartIdHandler(fn func(w http.ResponseWriter, r *http.Request, cartId
|
|||||||
http.SetCookie(w, &http.Cookie{
|
http.SetCookie(w, &http.Cookie{
|
||||||
Name: "cartid",
|
Name: "cartid",
|
||||||
Value: cartId.String(),
|
Value: cartId.String(),
|
||||||
Secure: true,
|
Secure: r.TLS != nil,
|
||||||
HttpOnly: true,
|
HttpOnly: true,
|
||||||
Path: "/",
|
Path: "/",
|
||||||
Expires: time.Now().AddDate(0, 0, 14),
|
Expires: time.Now().AddDate(0, 0, 14),
|
||||||
@@ -295,7 +297,7 @@ func (s *PoolServer) RemoveCartCookie(w http.ResponseWriter, r *http.Request, ca
|
|||||||
Name: "cartid",
|
Name: "cartid",
|
||||||
Value: cartId.String(),
|
Value: cartId.String(),
|
||||||
Path: "/",
|
Path: "/",
|
||||||
Secure: true,
|
Secure: r.TLS != nil,
|
||||||
HttpOnly: true,
|
HttpOnly: true,
|
||||||
Expires: time.Unix(0, 0),
|
Expires: time.Unix(0, 0),
|
||||||
SameSite: http.SameSiteLaxMode,
|
SameSite: http.SameSiteLaxMode,
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -2,88 +2,187 @@ syntax = "proto3";
|
|||||||
|
|
||||||
package messages;
|
package messages;
|
||||||
|
|
||||||
option go_package = ".;messages";
|
option go_package = "git.tornberg.me/go-cart-actor/proto;messages";
|
||||||
|
|
||||||
|
import "messages.proto";
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
// Cart Actor gRPC API (Envelope Variant)
|
// Cart Actor gRPC API (Breaking v2 - Per-Mutation RPCs)
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
// This service replaces the legacy custom TCP frame protocol used on port 1337.
|
// This version removes the previous MutationEnvelope + Mutate RPC.
|
||||||
// It keeps the existing per-mutation proto messages (defined in messages.proto)
|
// Each mutation now has its own request wrapper and dedicated RPC method
|
||||||
// serialized into an opaque `bytes payload` field for minimal refactor cost.
|
// providing simpler, type-focused client stubs and enabling per-mutation
|
||||||
// The numeric values in MutationType MUST match the legacy message type
|
// metrics, auth and rate limiting.
|
||||||
// constants (see message-types.go) so persisted event logs replay correctly.
|
//
|
||||||
|
// Regenerate Go code after editing:
|
||||||
|
// protoc --go_out=. --go_opt=paths=source_relative \
|
||||||
|
// --go-grpc_out=. --go-grpc_opt=paths=source_relative \
|
||||||
|
// proto/cart_actor.proto proto/messages.proto
|
||||||
|
//
|
||||||
|
// Backward compatibility: This is a breaking change (old clients must update).
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
// MutationType corresponds 1:1 with the legacy uint16 message type constants.
|
// Shared reply for all mutation RPCs.
|
||||||
enum MutationType {
|
message CartMutationReply {
|
||||||
MUTATION_TYPE_UNSPECIFIED = 0;
|
int32 status_code = 1; // HTTP-like status (200 success, 4xx client, 5xx server)
|
||||||
MUTATION_ADD_REQUEST = 1;
|
oneof result {
|
||||||
MUTATION_ADD_ITEM = 2;
|
CartState state = 2; // Updated cart state on success
|
||||||
// (3 was unused / reserved in legacy framing)
|
string error = 3; // Error message on failure
|
||||||
MUTATION_REMOVE_ITEM = 4;
|
}
|
||||||
MUTATION_REMOVE_DELIVERY = 5;
|
int64 server_timestamp = 4; // Server-assigned Unix timestamp (optional auditing)
|
||||||
MUTATION_CHANGE_QUANTITY = 6;
|
|
||||||
MUTATION_SET_DELIVERY = 7;
|
|
||||||
MUTATION_SET_PICKUP_POINT = 8;
|
|
||||||
MUTATION_CREATE_CHECKOUT_ORDER = 9;
|
|
||||||
MUTATION_SET_CART_ITEMS = 10;
|
|
||||||
MUTATION_ORDER_COMPLETED = 11;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// MutationRequest is an envelope:
|
// Fetch current cart state without mutation.
|
||||||
// - cart_id: string form of CartId (legacy 16-byte array truncated/padded).
|
|
||||||
// - type: mutation kind (see enum).
|
|
||||||
// - payload: serialized underlying proto message (AddRequest, AddItem, etc.).
|
|
||||||
// - client_timestamp: optional unix timestamp; server sets if zero.
|
|
||||||
message MutationRequest {
|
|
||||||
string cart_id = 1;
|
|
||||||
MutationType type = 2;
|
|
||||||
bytes payload = 3;
|
|
||||||
int64 client_timestamp = 4;
|
|
||||||
}
|
|
||||||
|
|
||||||
// MutationReply returns a status code (legacy semantics) plus a JSON payload
|
|
||||||
// representing the full cart state (or an error message if non-200).
|
|
||||||
message MutationReply {
|
|
||||||
int32 status_code = 1;
|
|
||||||
bytes payload = 2; // JSON cart state or error string
|
|
||||||
}
|
|
||||||
|
|
||||||
// StateRequest fetches current cart state without mutation.
|
|
||||||
message StateRequest {
|
message StateRequest {
|
||||||
string cart_id = 1;
|
string cart_id = 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
// StateReply mirrors MutationReply for consistency.
|
|
||||||
message StateReply {
|
message StateReply {
|
||||||
int32 status_code = 1;
|
int32 status_code = 1;
|
||||||
bytes payload = 2; // JSON cart state or error string
|
oneof result {
|
||||||
|
CartState state = 2;
|
||||||
|
string error = 3;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// CartActor exposes mutation and state retrieval for remote grains.
|
// Per-mutation request wrappers. We wrap the existing inner mutation
|
||||||
service CartActor {
|
// messages (defined in messages.proto) to add cart_id + optional metadata
|
||||||
// Mutate applies a single mutation to a cart, creating the cart lazily if needed.
|
// without altering the inner message definitions.
|
||||||
rpc Mutate(MutationRequest) returns (MutationReply);
|
|
||||||
|
message AddRequestRequest {
|
||||||
|
string cart_id = 1;
|
||||||
|
int64 client_timestamp = 2;
|
||||||
|
AddRequest payload = 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
message AddItemRequest {
|
||||||
|
string cart_id = 1;
|
||||||
|
int64 client_timestamp = 2;
|
||||||
|
AddItem payload = 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
message RemoveItemRequest {
|
||||||
|
string cart_id = 1;
|
||||||
|
int64 client_timestamp = 2;
|
||||||
|
RemoveItem payload = 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
message RemoveDeliveryRequest {
|
||||||
|
string cart_id = 1;
|
||||||
|
int64 client_timestamp = 2;
|
||||||
|
RemoveDelivery payload = 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
message ChangeQuantityRequest {
|
||||||
|
string cart_id = 1;
|
||||||
|
int64 client_timestamp = 2;
|
||||||
|
ChangeQuantity payload = 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
message SetDeliveryRequest {
|
||||||
|
string cart_id = 1;
|
||||||
|
int64 client_timestamp = 2;
|
||||||
|
SetDelivery payload = 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
message SetPickupPointRequest {
|
||||||
|
string cart_id = 1;
|
||||||
|
int64 client_timestamp = 2;
|
||||||
|
SetPickupPoint payload = 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
message CreateCheckoutOrderRequest {
|
||||||
|
string cart_id = 1;
|
||||||
|
int64 client_timestamp = 2;
|
||||||
|
CreateCheckoutOrder payload = 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
message SetCartItemsRequest {
|
||||||
|
string cart_id = 1;
|
||||||
|
int64 client_timestamp = 2;
|
||||||
|
SetCartRequest payload = 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
message OrderCompletedRequest {
|
||||||
|
string cart_id = 1;
|
||||||
|
int64 client_timestamp = 2;
|
||||||
|
OrderCreated payload = 10;
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Cart state snapshot (unchanged from v1 except envelope removal context)
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
message CartState {
|
||||||
|
string cart_id = 1;
|
||||||
|
repeated CartItemState items = 2;
|
||||||
|
int64 total_price = 3;
|
||||||
|
int64 total_tax = 4;
|
||||||
|
int64 total_discount = 5;
|
||||||
|
repeated DeliveryState deliveries = 6;
|
||||||
|
bool payment_in_progress = 7;
|
||||||
|
string order_reference = 8;
|
||||||
|
string payment_status = 9;
|
||||||
|
}
|
||||||
|
|
||||||
|
message CartItemState {
|
||||||
|
int64 id = 1;
|
||||||
|
int64 source_item_id = 2;
|
||||||
|
string sku = 3;
|
||||||
|
string name = 4;
|
||||||
|
int64 unit_price = 5;
|
||||||
|
int32 quantity = 6;
|
||||||
|
int64 total_price = 7;
|
||||||
|
int64 total_tax = 8;
|
||||||
|
int64 org_price = 9;
|
||||||
|
int32 tax_rate = 10;
|
||||||
|
int64 total_discount = 11;
|
||||||
|
string brand = 12;
|
||||||
|
string category = 13;
|
||||||
|
string category2 = 14;
|
||||||
|
string category3 = 15;
|
||||||
|
string category4 = 16;
|
||||||
|
string category5 = 17;
|
||||||
|
string image = 18;
|
||||||
|
string article_type = 19;
|
||||||
|
string seller_id = 20;
|
||||||
|
string seller_name = 21;
|
||||||
|
string disclaimer = 22;
|
||||||
|
string outlet = 23;
|
||||||
|
string store_id = 24;
|
||||||
|
int32 stock = 25;
|
||||||
|
}
|
||||||
|
|
||||||
|
message DeliveryState {
|
||||||
|
int64 id = 1;
|
||||||
|
string provider = 2;
|
||||||
|
int64 price = 3;
|
||||||
|
repeated int64 item_ids = 4;
|
||||||
|
PickupPoint pickup_point = 5; // Defined in messages.proto
|
||||||
|
}
|
||||||
|
|
||||||
|
// (CheckoutRequest / CheckoutReply removed - checkout handled at HTTP layer)
|
||||||
|
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// Service definition (per-mutation RPCs + checkout)
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
service CartActor {
|
||||||
|
rpc AddRequest(AddRequestRequest) returns (CartMutationReply);
|
||||||
|
rpc AddItem(AddItemRequest) returns (CartMutationReply);
|
||||||
|
rpc RemoveItem(RemoveItemRequest) returns (CartMutationReply);
|
||||||
|
rpc RemoveDelivery(RemoveDeliveryRequest) returns (CartMutationReply);
|
||||||
|
rpc ChangeQuantity(ChangeQuantityRequest) returns (CartMutationReply);
|
||||||
|
rpc SetDelivery(SetDeliveryRequest) returns (CartMutationReply);
|
||||||
|
rpc SetPickupPoint(SetPickupPointRequest) returns (CartMutationReply);
|
||||||
|
// (Checkout RPC removed - handled externally)
|
||||||
|
rpc SetCartItems(SetCartItemsRequest) returns (CartMutationReply);
|
||||||
|
rpc OrderCompleted(OrderCompletedRequest) returns (CartMutationReply);
|
||||||
|
|
||||||
// GetState retrieves the cart's current state (JSON).
|
|
||||||
rpc GetState(StateRequest) returns (StateReply);
|
rpc GetState(StateRequest) returns (StateReply);
|
||||||
}
|
}
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
// Notes:
|
// Future enhancements:
|
||||||
//
|
// * BatchMutate RPC (repeated heterogeneous mutations)
|
||||||
// 1. Generation:
|
// * Streaming state updates (WatchState)
|
||||||
// protoc --go_out=. --go_opt=paths=source_relative \
|
// * Versioning / optimistic concurrency control
|
||||||
// --go-grpc_out=. --go-grpc_opt=paths=source_relative \
|
|
||||||
// cart_actor.proto
|
|
||||||
//
|
|
||||||
// 2. Underlying mutation payloads originate from messages.proto definitions.
|
|
||||||
// The server side will route based on MutationType and decode payload bytes
|
|
||||||
// using existing handler registry logic.
|
|
||||||
//
|
|
||||||
// 3. Future Enhancements:
|
|
||||||
// - Replace JSON state payload with a strongly typed CartState proto.
|
|
||||||
// - Add streaming RPC (e.g. WatchState) for live updates.
|
|
||||||
// - Migrate control plane (negotiate/ownership) into a separate proto
|
|
||||||
// (control_plane.proto) as per the migration plan.
|
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
|
|||||||
@@ -19,19 +19,36 @@ import (
|
|||||||
const _ = grpc.SupportPackageIsVersion9
|
const _ = grpc.SupportPackageIsVersion9
|
||||||
|
|
||||||
const (
|
const (
|
||||||
CartActor_Mutate_FullMethodName = "/messages.CartActor/Mutate"
|
CartActor_AddRequest_FullMethodName = "/messages.CartActor/AddRequest"
|
||||||
CartActor_GetState_FullMethodName = "/messages.CartActor/GetState"
|
CartActor_AddItem_FullMethodName = "/messages.CartActor/AddItem"
|
||||||
|
CartActor_RemoveItem_FullMethodName = "/messages.CartActor/RemoveItem"
|
||||||
|
CartActor_RemoveDelivery_FullMethodName = "/messages.CartActor/RemoveDelivery"
|
||||||
|
CartActor_ChangeQuantity_FullMethodName = "/messages.CartActor/ChangeQuantity"
|
||||||
|
CartActor_SetDelivery_FullMethodName = "/messages.CartActor/SetDelivery"
|
||||||
|
CartActor_SetPickupPoint_FullMethodName = "/messages.CartActor/SetPickupPoint"
|
||||||
|
CartActor_SetCartItems_FullMethodName = "/messages.CartActor/SetCartItems"
|
||||||
|
CartActor_OrderCompleted_FullMethodName = "/messages.CartActor/OrderCompleted"
|
||||||
|
CartActor_GetState_FullMethodName = "/messages.CartActor/GetState"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CartActorClient is the client API for CartActor service.
|
// CartActorClient is the client API for CartActor service.
|
||||||
//
|
//
|
||||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||||
//
|
//
|
||||||
// CartActor exposes mutation and state retrieval for remote grains.
|
// -----------------------------------------------------------------------------
|
||||||
|
// Service definition (per-mutation RPCs + checkout)
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
type CartActorClient interface {
|
type CartActorClient interface {
|
||||||
// Mutate applies a single mutation to a cart, creating the cart lazily if needed.
|
AddRequest(ctx context.Context, in *AddRequestRequest, opts ...grpc.CallOption) (*CartMutationReply, error)
|
||||||
Mutate(ctx context.Context, in *MutationRequest, opts ...grpc.CallOption) (*MutationReply, error)
|
AddItem(ctx context.Context, in *AddItemRequest, opts ...grpc.CallOption) (*CartMutationReply, error)
|
||||||
// GetState retrieves the cart's current state (JSON).
|
RemoveItem(ctx context.Context, in *RemoveItemRequest, opts ...grpc.CallOption) (*CartMutationReply, error)
|
||||||
|
RemoveDelivery(ctx context.Context, in *RemoveDeliveryRequest, opts ...grpc.CallOption) (*CartMutationReply, error)
|
||||||
|
ChangeQuantity(ctx context.Context, in *ChangeQuantityRequest, opts ...grpc.CallOption) (*CartMutationReply, error)
|
||||||
|
SetDelivery(ctx context.Context, in *SetDeliveryRequest, opts ...grpc.CallOption) (*CartMutationReply, error)
|
||||||
|
SetPickupPoint(ctx context.Context, in *SetPickupPointRequest, opts ...grpc.CallOption) (*CartMutationReply, error)
|
||||||
|
// (Checkout RPC removed - handled externally)
|
||||||
|
SetCartItems(ctx context.Context, in *SetCartItemsRequest, opts ...grpc.CallOption) (*CartMutationReply, error)
|
||||||
|
OrderCompleted(ctx context.Context, in *OrderCompletedRequest, opts ...grpc.CallOption) (*CartMutationReply, error)
|
||||||
GetState(ctx context.Context, in *StateRequest, opts ...grpc.CallOption) (*StateReply, error)
|
GetState(ctx context.Context, in *StateRequest, opts ...grpc.CallOption) (*StateReply, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -43,10 +60,90 @@ func NewCartActorClient(cc grpc.ClientConnInterface) CartActorClient {
|
|||||||
return &cartActorClient{cc}
|
return &cartActorClient{cc}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *cartActorClient) Mutate(ctx context.Context, in *MutationRequest, opts ...grpc.CallOption) (*MutationReply, error) {
|
func (c *cartActorClient) AddRequest(ctx context.Context, in *AddRequestRequest, opts ...grpc.CallOption) (*CartMutationReply, error) {
|
||||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
out := new(MutationReply)
|
out := new(CartMutationReply)
|
||||||
err := c.cc.Invoke(ctx, CartActor_Mutate_FullMethodName, in, out, cOpts...)
|
err := c.cc.Invoke(ctx, CartActor_AddRequest_FullMethodName, in, out, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *cartActorClient) AddItem(ctx context.Context, in *AddItemRequest, opts ...grpc.CallOption) (*CartMutationReply, error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
out := new(CartMutationReply)
|
||||||
|
err := c.cc.Invoke(ctx, CartActor_AddItem_FullMethodName, in, out, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *cartActorClient) RemoveItem(ctx context.Context, in *RemoveItemRequest, opts ...grpc.CallOption) (*CartMutationReply, error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
out := new(CartMutationReply)
|
||||||
|
err := c.cc.Invoke(ctx, CartActor_RemoveItem_FullMethodName, in, out, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *cartActorClient) RemoveDelivery(ctx context.Context, in *RemoveDeliveryRequest, opts ...grpc.CallOption) (*CartMutationReply, error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
out := new(CartMutationReply)
|
||||||
|
err := c.cc.Invoke(ctx, CartActor_RemoveDelivery_FullMethodName, in, out, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *cartActorClient) ChangeQuantity(ctx context.Context, in *ChangeQuantityRequest, opts ...grpc.CallOption) (*CartMutationReply, error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
out := new(CartMutationReply)
|
||||||
|
err := c.cc.Invoke(ctx, CartActor_ChangeQuantity_FullMethodName, in, out, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *cartActorClient) SetDelivery(ctx context.Context, in *SetDeliveryRequest, opts ...grpc.CallOption) (*CartMutationReply, error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
out := new(CartMutationReply)
|
||||||
|
err := c.cc.Invoke(ctx, CartActor_SetDelivery_FullMethodName, in, out, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *cartActorClient) SetPickupPoint(ctx context.Context, in *SetPickupPointRequest, opts ...grpc.CallOption) (*CartMutationReply, error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
out := new(CartMutationReply)
|
||||||
|
err := c.cc.Invoke(ctx, CartActor_SetPickupPoint_FullMethodName, in, out, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *cartActorClient) SetCartItems(ctx context.Context, in *SetCartItemsRequest, opts ...grpc.CallOption) (*CartMutationReply, error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
out := new(CartMutationReply)
|
||||||
|
err := c.cc.Invoke(ctx, CartActor_SetCartItems_FullMethodName, in, out, cOpts...)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return out, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *cartActorClient) OrderCompleted(ctx context.Context, in *OrderCompletedRequest, opts ...grpc.CallOption) (*CartMutationReply, error) {
|
||||||
|
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||||
|
out := new(CartMutationReply)
|
||||||
|
err := c.cc.Invoke(ctx, CartActor_OrderCompleted_FullMethodName, in, out, cOpts...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -67,11 +164,20 @@ func (c *cartActorClient) GetState(ctx context.Context, in *StateRequest, opts .
|
|||||||
// All implementations must embed UnimplementedCartActorServer
|
// All implementations must embed UnimplementedCartActorServer
|
||||||
// for forward compatibility.
|
// for forward compatibility.
|
||||||
//
|
//
|
||||||
// CartActor exposes mutation and state retrieval for remote grains.
|
// -----------------------------------------------------------------------------
|
||||||
|
// Service definition (per-mutation RPCs + checkout)
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
type CartActorServer interface {
|
type CartActorServer interface {
|
||||||
// Mutate applies a single mutation to a cart, creating the cart lazily if needed.
|
AddRequest(context.Context, *AddRequestRequest) (*CartMutationReply, error)
|
||||||
Mutate(context.Context, *MutationRequest) (*MutationReply, error)
|
AddItem(context.Context, *AddItemRequest) (*CartMutationReply, error)
|
||||||
// GetState retrieves the cart's current state (JSON).
|
RemoveItem(context.Context, *RemoveItemRequest) (*CartMutationReply, error)
|
||||||
|
RemoveDelivery(context.Context, *RemoveDeliveryRequest) (*CartMutationReply, error)
|
||||||
|
ChangeQuantity(context.Context, *ChangeQuantityRequest) (*CartMutationReply, error)
|
||||||
|
SetDelivery(context.Context, *SetDeliveryRequest) (*CartMutationReply, error)
|
||||||
|
SetPickupPoint(context.Context, *SetPickupPointRequest) (*CartMutationReply, error)
|
||||||
|
// (Checkout RPC removed - handled externally)
|
||||||
|
SetCartItems(context.Context, *SetCartItemsRequest) (*CartMutationReply, error)
|
||||||
|
OrderCompleted(context.Context, *OrderCompletedRequest) (*CartMutationReply, error)
|
||||||
GetState(context.Context, *StateRequest) (*StateReply, error)
|
GetState(context.Context, *StateRequest) (*StateReply, error)
|
||||||
mustEmbedUnimplementedCartActorServer()
|
mustEmbedUnimplementedCartActorServer()
|
||||||
}
|
}
|
||||||
@@ -83,8 +189,32 @@ type CartActorServer interface {
|
|||||||
// pointer dereference when methods are called.
|
// pointer dereference when methods are called.
|
||||||
type UnimplementedCartActorServer struct{}
|
type UnimplementedCartActorServer struct{}
|
||||||
|
|
||||||
func (UnimplementedCartActorServer) Mutate(context.Context, *MutationRequest) (*MutationReply, error) {
|
func (UnimplementedCartActorServer) AddRequest(context.Context, *AddRequestRequest) (*CartMutationReply, error) {
|
||||||
return nil, status.Errorf(codes.Unimplemented, "method Mutate not implemented")
|
return nil, status.Errorf(codes.Unimplemented, "method AddRequest not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedCartActorServer) AddItem(context.Context, *AddItemRequest) (*CartMutationReply, error) {
|
||||||
|
return nil, status.Errorf(codes.Unimplemented, "method AddItem not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedCartActorServer) RemoveItem(context.Context, *RemoveItemRequest) (*CartMutationReply, error) {
|
||||||
|
return nil, status.Errorf(codes.Unimplemented, "method RemoveItem not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedCartActorServer) RemoveDelivery(context.Context, *RemoveDeliveryRequest) (*CartMutationReply, error) {
|
||||||
|
return nil, status.Errorf(codes.Unimplemented, "method RemoveDelivery not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedCartActorServer) ChangeQuantity(context.Context, *ChangeQuantityRequest) (*CartMutationReply, error) {
|
||||||
|
return nil, status.Errorf(codes.Unimplemented, "method ChangeQuantity not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedCartActorServer) SetDelivery(context.Context, *SetDeliveryRequest) (*CartMutationReply, error) {
|
||||||
|
return nil, status.Errorf(codes.Unimplemented, "method SetDelivery not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedCartActorServer) SetPickupPoint(context.Context, *SetPickupPointRequest) (*CartMutationReply, error) {
|
||||||
|
return nil, status.Errorf(codes.Unimplemented, "method SetPickupPoint not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedCartActorServer) SetCartItems(context.Context, *SetCartItemsRequest) (*CartMutationReply, error) {
|
||||||
|
return nil, status.Errorf(codes.Unimplemented, "method SetCartItems not implemented")
|
||||||
|
}
|
||||||
|
func (UnimplementedCartActorServer) OrderCompleted(context.Context, *OrderCompletedRequest) (*CartMutationReply, error) {
|
||||||
|
return nil, status.Errorf(codes.Unimplemented, "method OrderCompleted not implemented")
|
||||||
}
|
}
|
||||||
func (UnimplementedCartActorServer) GetState(context.Context, *StateRequest) (*StateReply, error) {
|
func (UnimplementedCartActorServer) GetState(context.Context, *StateRequest) (*StateReply, error) {
|
||||||
return nil, status.Errorf(codes.Unimplemented, "method GetState not implemented")
|
return nil, status.Errorf(codes.Unimplemented, "method GetState not implemented")
|
||||||
@@ -110,20 +240,164 @@ func RegisterCartActorServer(s grpc.ServiceRegistrar, srv CartActorServer) {
|
|||||||
s.RegisterService(&CartActor_ServiceDesc, srv)
|
s.RegisterService(&CartActor_ServiceDesc, srv)
|
||||||
}
|
}
|
||||||
|
|
||||||
func _CartActor_Mutate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
func _CartActor_AddRequest_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
in := new(MutationRequest)
|
in := new(AddRequestRequest)
|
||||||
if err := dec(in); err != nil {
|
if err := dec(in); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
if interceptor == nil {
|
if interceptor == nil {
|
||||||
return srv.(CartActorServer).Mutate(ctx, in)
|
return srv.(CartActorServer).AddRequest(ctx, in)
|
||||||
}
|
}
|
||||||
info := &grpc.UnaryServerInfo{
|
info := &grpc.UnaryServerInfo{
|
||||||
Server: srv,
|
Server: srv,
|
||||||
FullMethod: CartActor_Mutate_FullMethodName,
|
FullMethod: CartActor_AddRequest_FullMethodName,
|
||||||
}
|
}
|
||||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
return srv.(CartActorServer).Mutate(ctx, req.(*MutationRequest))
|
return srv.(CartActorServer).AddRequest(ctx, req.(*AddRequestRequest))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _CartActor_AddItem_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(AddItemRequest)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(CartActorServer).AddItem(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: CartActor_AddItem_FullMethodName,
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(CartActorServer).AddItem(ctx, req.(*AddItemRequest))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _CartActor_RemoveItem_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(RemoveItemRequest)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(CartActorServer).RemoveItem(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: CartActor_RemoveItem_FullMethodName,
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(CartActorServer).RemoveItem(ctx, req.(*RemoveItemRequest))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _CartActor_RemoveDelivery_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(RemoveDeliveryRequest)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(CartActorServer).RemoveDelivery(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: CartActor_RemoveDelivery_FullMethodName,
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(CartActorServer).RemoveDelivery(ctx, req.(*RemoveDeliveryRequest))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _CartActor_ChangeQuantity_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(ChangeQuantityRequest)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(CartActorServer).ChangeQuantity(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: CartActor_ChangeQuantity_FullMethodName,
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(CartActorServer).ChangeQuantity(ctx, req.(*ChangeQuantityRequest))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _CartActor_SetDelivery_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(SetDeliveryRequest)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(CartActorServer).SetDelivery(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: CartActor_SetDelivery_FullMethodName,
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(CartActorServer).SetDelivery(ctx, req.(*SetDeliveryRequest))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _CartActor_SetPickupPoint_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(SetPickupPointRequest)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(CartActorServer).SetPickupPoint(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: CartActor_SetPickupPoint_FullMethodName,
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(CartActorServer).SetPickupPoint(ctx, req.(*SetPickupPointRequest))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _CartActor_SetCartItems_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(SetCartItemsRequest)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(CartActorServer).SetCartItems(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: CartActor_SetCartItems_FullMethodName,
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(CartActorServer).SetCartItems(ctx, req.(*SetCartItemsRequest))
|
||||||
|
}
|
||||||
|
return interceptor(ctx, in, info, handler)
|
||||||
|
}
|
||||||
|
|
||||||
|
func _CartActor_OrderCompleted_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||||
|
in := new(OrderCompletedRequest)
|
||||||
|
if err := dec(in); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if interceptor == nil {
|
||||||
|
return srv.(CartActorServer).OrderCompleted(ctx, in)
|
||||||
|
}
|
||||||
|
info := &grpc.UnaryServerInfo{
|
||||||
|
Server: srv,
|
||||||
|
FullMethod: CartActor_OrderCompleted_FullMethodName,
|
||||||
|
}
|
||||||
|
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||||
|
return srv.(CartActorServer).OrderCompleted(ctx, req.(*OrderCompletedRequest))
|
||||||
}
|
}
|
||||||
return interceptor(ctx, in, info, handler)
|
return interceptor(ctx, in, info, handler)
|
||||||
}
|
}
|
||||||
@@ -154,8 +428,40 @@ var CartActor_ServiceDesc = grpc.ServiceDesc{
|
|||||||
HandlerType: (*CartActorServer)(nil),
|
HandlerType: (*CartActorServer)(nil),
|
||||||
Methods: []grpc.MethodDesc{
|
Methods: []grpc.MethodDesc{
|
||||||
{
|
{
|
||||||
MethodName: "Mutate",
|
MethodName: "AddRequest",
|
||||||
Handler: _CartActor_Mutate_Handler,
|
Handler: _CartActor_AddRequest_Handler,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MethodName: "AddItem",
|
||||||
|
Handler: _CartActor_AddItem_Handler,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MethodName: "RemoveItem",
|
||||||
|
Handler: _CartActor_RemoveItem_Handler,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MethodName: "RemoveDelivery",
|
||||||
|
Handler: _CartActor_RemoveDelivery_Handler,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MethodName: "ChangeQuantity",
|
||||||
|
Handler: _CartActor_ChangeQuantity_Handler,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MethodName: "SetDelivery",
|
||||||
|
Handler: _CartActor_SetDelivery_Handler,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MethodName: "SetPickupPoint",
|
||||||
|
Handler: _CartActor_SetPickupPoint_Handler,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MethodName: "SetCartItems",
|
||||||
|
Handler: _CartActor_SetCartItems_Handler,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
MethodName: "OrderCompleted",
|
||||||
|
Handler: _CartActor_OrderCompleted_Handler,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
MethodName: "GetState",
|
MethodName: "GetState",
|
||||||
|
|||||||
@@ -427,8 +427,7 @@ const file_control_plane_proto_rawDesc = "" +
|
|||||||
"\n" +
|
"\n" +
|
||||||
"GetCartIds\x12\x0f.messages.Empty\x1a\x16.messages.CartIdsReply\x12F\n" +
|
"GetCartIds\x12\x0f.messages.Empty\x1a\x16.messages.CartIdsReply\x12F\n" +
|
||||||
"\fConfirmOwner\x12\x1c.messages.OwnerChangeRequest\x1a\x18.messages.OwnerChangeAck\x12<\n" +
|
"\fConfirmOwner\x12\x1c.messages.OwnerChangeRequest\x1a\x18.messages.OwnerChangeAck\x12<\n" +
|
||||||
"\aClosing\x12\x17.messages.ClosingNotice\x1a\x18.messages.OwnerChangeAckB\fZ\n" +
|
"\aClosing\x12\x17.messages.ClosingNotice\x1a\x18.messages.OwnerChangeAckB.Z,git.tornberg.me/go-cart-actor/proto;messagesb\x06proto3"
|
||||||
".;messagesb\x06proto3"
|
|
||||||
|
|
||||||
var (
|
var (
|
||||||
file_control_plane_proto_rawDescOnce sync.Once
|
file_control_plane_proto_rawDescOnce sync.Once
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ syntax = "proto3";
|
|||||||
|
|
||||||
package messages;
|
package messages;
|
||||||
|
|
||||||
option go_package = ".;messages";
|
option go_package = "git.tornberg.me/go-cart-actor/proto;messages";
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
// -----------------------------------------------------------------------------
|
||||||
// Control Plane gRPC API
|
// Control Plane gRPC API
|
||||||
|
|||||||
@@ -889,6 +889,102 @@ func (x *OrderCreated) GetStatus() string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Noop struct {
|
||||||
|
state protoimpl.MessageState `protogen:"open.v1"`
|
||||||
|
unknownFields protoimpl.UnknownFields
|
||||||
|
sizeCache protoimpl.SizeCache
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *Noop) Reset() {
|
||||||
|
*x = Noop{}
|
||||||
|
mi := &file_messages_proto_msgTypes[11]
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *Noop) String() string {
|
||||||
|
return protoimpl.X.MessageStringOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*Noop) ProtoMessage() {}
|
||||||
|
|
||||||
|
func (x *Noop) ProtoReflect() protoreflect.Message {
|
||||||
|
mi := &file_messages_proto_msgTypes[11]
|
||||||
|
if x != nil {
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
if ms.LoadMessageInfo() == nil {
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
return mi.MessageOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deprecated: Use Noop.ProtoReflect.Descriptor instead.
|
||||||
|
func (*Noop) Descriptor() ([]byte, []int) {
|
||||||
|
return file_messages_proto_rawDescGZIP(), []int{11}
|
||||||
|
}
|
||||||
|
|
||||||
|
type InitializeCheckout struct {
|
||||||
|
state protoimpl.MessageState `protogen:"open.v1"`
|
||||||
|
OrderId string `protobuf:"bytes,1,opt,name=orderId,proto3" json:"orderId,omitempty"`
|
||||||
|
Status string `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"`
|
||||||
|
PaymentInProgress bool `protobuf:"varint,3,opt,name=paymentInProgress,proto3" json:"paymentInProgress,omitempty"`
|
||||||
|
unknownFields protoimpl.UnknownFields
|
||||||
|
sizeCache protoimpl.SizeCache
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *InitializeCheckout) Reset() {
|
||||||
|
*x = InitializeCheckout{}
|
||||||
|
mi := &file_messages_proto_msgTypes[12]
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *InitializeCheckout) String() string {
|
||||||
|
return protoimpl.X.MessageStringOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (*InitializeCheckout) ProtoMessage() {}
|
||||||
|
|
||||||
|
func (x *InitializeCheckout) ProtoReflect() protoreflect.Message {
|
||||||
|
mi := &file_messages_proto_msgTypes[12]
|
||||||
|
if x != nil {
|
||||||
|
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
|
||||||
|
if ms.LoadMessageInfo() == nil {
|
||||||
|
ms.StoreMessageInfo(mi)
|
||||||
|
}
|
||||||
|
return ms
|
||||||
|
}
|
||||||
|
return mi.MessageOf(x)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deprecated: Use InitializeCheckout.ProtoReflect.Descriptor instead.
|
||||||
|
func (*InitializeCheckout) Descriptor() ([]byte, []int) {
|
||||||
|
return file_messages_proto_rawDescGZIP(), []int{12}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *InitializeCheckout) GetOrderId() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.OrderId
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *InitializeCheckout) GetStatus() string {
|
||||||
|
if x != nil {
|
||||||
|
return x.Status
|
||||||
|
}
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
|
||||||
|
func (x *InitializeCheckout) GetPaymentInProgress() bool {
|
||||||
|
if x != nil {
|
||||||
|
return x.PaymentInProgress
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
var File_messages_proto protoreflect.FileDescriptor
|
var File_messages_proto protoreflect.FileDescriptor
|
||||||
|
|
||||||
const file_messages_proto_rawDesc = "" +
|
const file_messages_proto_rawDesc = "" +
|
||||||
@@ -997,8 +1093,12 @@ const file_messages_proto_rawDesc = "" +
|
|||||||
"\acountry\x18\x06 \x01(\tR\acountry\"@\n" +
|
"\acountry\x18\x06 \x01(\tR\acountry\"@\n" +
|
||||||
"\fOrderCreated\x12\x18\n" +
|
"\fOrderCreated\x12\x18\n" +
|
||||||
"\aorderId\x18\x01 \x01(\tR\aorderId\x12\x16\n" +
|
"\aorderId\x18\x01 \x01(\tR\aorderId\x12\x16\n" +
|
||||||
"\x06status\x18\x02 \x01(\tR\x06statusB\fZ\n" +
|
"\x06status\x18\x02 \x01(\tR\x06status\"\x06\n" +
|
||||||
".;messagesb\x06proto3"
|
"\x04Noop\"t\n" +
|
||||||
|
"\x12InitializeCheckout\x12\x18\n" +
|
||||||
|
"\aorderId\x18\x01 \x01(\tR\aorderId\x12\x16\n" +
|
||||||
|
"\x06status\x18\x02 \x01(\tR\x06status\x12,\n" +
|
||||||
|
"\x11paymentInProgress\x18\x03 \x01(\bR\x11paymentInProgressB.Z,git.tornberg.me/go-cart-actor/proto;messagesb\x06proto3"
|
||||||
|
|
||||||
var (
|
var (
|
||||||
file_messages_proto_rawDescOnce sync.Once
|
file_messages_proto_rawDescOnce sync.Once
|
||||||
@@ -1012,7 +1112,7 @@ func file_messages_proto_rawDescGZIP() []byte {
|
|||||||
return file_messages_proto_rawDescData
|
return file_messages_proto_rawDescData
|
||||||
}
|
}
|
||||||
|
|
||||||
var file_messages_proto_msgTypes = make([]protoimpl.MessageInfo, 11)
|
var file_messages_proto_msgTypes = make([]protoimpl.MessageInfo, 13)
|
||||||
var file_messages_proto_goTypes = []any{
|
var file_messages_proto_goTypes = []any{
|
||||||
(*AddRequest)(nil), // 0: messages.AddRequest
|
(*AddRequest)(nil), // 0: messages.AddRequest
|
||||||
(*SetCartRequest)(nil), // 1: messages.SetCartRequest
|
(*SetCartRequest)(nil), // 1: messages.SetCartRequest
|
||||||
@@ -1025,6 +1125,8 @@ var file_messages_proto_goTypes = []any{
|
|||||||
(*RemoveDelivery)(nil), // 8: messages.RemoveDelivery
|
(*RemoveDelivery)(nil), // 8: messages.RemoveDelivery
|
||||||
(*CreateCheckoutOrder)(nil), // 9: messages.CreateCheckoutOrder
|
(*CreateCheckoutOrder)(nil), // 9: messages.CreateCheckoutOrder
|
||||||
(*OrderCreated)(nil), // 10: messages.OrderCreated
|
(*OrderCreated)(nil), // 10: messages.OrderCreated
|
||||||
|
(*Noop)(nil), // 11: messages.Noop
|
||||||
|
(*InitializeCheckout)(nil), // 12: messages.InitializeCheckout
|
||||||
}
|
}
|
||||||
var file_messages_proto_depIdxs = []int32{
|
var file_messages_proto_depIdxs = []int32{
|
||||||
0, // 0: messages.SetCartRequest.items:type_name -> messages.AddRequest
|
0, // 0: messages.SetCartRequest.items:type_name -> messages.AddRequest
|
||||||
@@ -1052,7 +1154,7 @@ func file_messages_proto_init() {
|
|||||||
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
|
||||||
RawDescriptor: unsafe.Slice(unsafe.StringData(file_messages_proto_rawDesc), len(file_messages_proto_rawDesc)),
|
RawDescriptor: unsafe.Slice(unsafe.StringData(file_messages_proto_rawDesc), len(file_messages_proto_rawDesc)),
|
||||||
NumEnums: 0,
|
NumEnums: 0,
|
||||||
NumMessages: 11,
|
NumMessages: 13,
|
||||||
NumExtensions: 0,
|
NumExtensions: 0,
|
||||||
NumServices: 0,
|
NumServices: 0,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
syntax = "proto3";
|
syntax = "proto3";
|
||||||
package messages;
|
package messages;
|
||||||
option go_package = ".;messages";
|
option go_package = "git.tornberg.me/go-cart-actor/proto;messages";
|
||||||
|
|
||||||
message AddRequest {
|
message AddRequest {
|
||||||
int32 quantity = 1;
|
int32 quantity = 1;
|
||||||
@@ -93,3 +93,13 @@ message OrderCreated {
|
|||||||
string orderId = 1;
|
string orderId = 1;
|
||||||
string status = 2;
|
string status = 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
message Noop {
|
||||||
|
// Intentionally empty - used for ownership acquisition or health pings
|
||||||
|
}
|
||||||
|
|
||||||
|
message InitializeCheckout {
|
||||||
|
string orderId = 1;
|
||||||
|
string status = 2;
|
||||||
|
bool paymentInProgress = 3;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,67 +0,0 @@
|
|||||||
// package main
|
|
||||||
|
|
||||||
// import "sync"
|
|
||||||
|
|
||||||
// type RemoteGrainPool struct {
|
|
||||||
// mu sync.RWMutex
|
|
||||||
// Host string
|
|
||||||
// grains map[CartId]*RemoteGrain
|
|
||||||
// }
|
|
||||||
|
|
||||||
// func NewRemoteGrainPool(addr string) *RemoteGrainPool {
|
|
||||||
// return &RemoteGrainPool{
|
|
||||||
// Host: addr,
|
|
||||||
// grains: make(map[CartId]*RemoteGrain),
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
// func (p *RemoteGrainPool) findRemoteGrain(id CartId) *RemoteGrain {
|
|
||||||
// p.mu.RLock()
|
|
||||||
// grain, ok := p.grains[id]
|
|
||||||
// p.mu.RUnlock()
|
|
||||||
// if !ok {
|
|
||||||
// return nil
|
|
||||||
// }
|
|
||||||
// return grain
|
|
||||||
// }
|
|
||||||
|
|
||||||
// func (p *RemoteGrainPool) findOrCreateGrain(id CartId) (*RemoteGrain, error) {
|
|
||||||
// grain := p.findRemoteGrain(id)
|
|
||||||
|
|
||||||
// if grain == nil {
|
|
||||||
// grain, err := NewRemoteGrain(id, p.Host)
|
|
||||||
// if err != nil {
|
|
||||||
// return nil, err
|
|
||||||
// }
|
|
||||||
// p.mu.Lock()
|
|
||||||
// p.grains[id] = grain
|
|
||||||
// p.mu.Unlock()
|
|
||||||
// }
|
|
||||||
// return grain, nil
|
|
||||||
// }
|
|
||||||
|
|
||||||
// func (p *RemoteGrainPool) Delete(id CartId) {
|
|
||||||
// p.mu.Lock()
|
|
||||||
// delete(p.grains, id)
|
|
||||||
// p.mu.Unlock()
|
|
||||||
// }
|
|
||||||
|
|
||||||
// func (p *RemoteGrainPool) Process(id CartId, messages ...Message) (*FrameWithPayload, error) {
|
|
||||||
// var result *FrameWithPayload
|
|
||||||
// grain, err := p.findOrCreateGrain(id)
|
|
||||||
// if err != nil {
|
|
||||||
// return nil, err
|
|
||||||
// }
|
|
||||||
// for _, message := range messages {
|
|
||||||
// result, err = grain.HandleMessage(&message, false)
|
|
||||||
// }
|
|
||||||
// return result, err
|
|
||||||
// }
|
|
||||||
|
|
||||||
// func (p *RemoteGrainPool) Get(id CartId) (*FrameWithPayload, error) {
|
|
||||||
// grain, err := p.findOrCreateGrain(id)
|
|
||||||
// if err != nil {
|
|
||||||
// return nil, err
|
|
||||||
// }
|
|
||||||
// return grain.GetCurrentState()
|
|
||||||
// }
|
|
||||||
@@ -1,7 +1,6 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
@@ -68,69 +67,264 @@ func (g *RemoteGrainGRPC) GetId() CartId {
|
|||||||
return g.Id
|
return g.Id
|
||||||
}
|
}
|
||||||
|
|
||||||
// HandleMessage serializes the underlying mutation proto (without legacy message header)
|
// Apply executes a cart mutation via per-mutation RPCs (breaking v2 API)
|
||||||
// and invokes the CartActor.Mutate RPC. It wraps the reply into a FrameWithPayload
|
// and returns a *CartGrain reconstructed from the CartMutationReply state.
|
||||||
// for compatibility with existing higher-level code paths.
|
func (g *RemoteGrainGRPC) Apply(content interface{}, isReplay bool) (*CartGrain, error) {
|
||||||
func (g *RemoteGrainGRPC) HandleMessage(message *Message, isReplay bool) (*FrameWithPayload, error) {
|
|
||||||
if message == nil {
|
|
||||||
return nil, fmt.Errorf("nil message")
|
|
||||||
}
|
|
||||||
if isReplay {
|
if isReplay {
|
||||||
// Remote replay not expected; ignore to keep parity with old implementation.
|
|
||||||
return nil, fmt.Errorf("replay not supported for remote grains")
|
return nil, fmt.Errorf("replay not supported for remote grains")
|
||||||
}
|
}
|
||||||
|
if content == nil {
|
||||||
handler, err := GetMessageHandler(message.Type)
|
return nil, fmt.Errorf("nil mutation content")
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ensure timestamp set (legacy behavior)
|
ts := time.Now().Unix()
|
||||||
if message.TimeStamp == nil {
|
|
||||||
ts := time.Now().Unix()
|
var invoke func(ctx context.Context) (*proto.CartMutationReply, error)
|
||||||
message.TimeStamp = &ts
|
|
||||||
|
switch m := content.(type) {
|
||||||
|
case *proto.AddRequest:
|
||||||
|
invoke = func(ctx context.Context) (*proto.CartMutationReply, error) {
|
||||||
|
return g.client.AddRequest(ctx, &proto.AddRequestRequest{
|
||||||
|
CartId: g.Id.String(),
|
||||||
|
ClientTimestamp: ts,
|
||||||
|
Payload: m,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
case *proto.AddItem:
|
||||||
|
invoke = func(ctx context.Context) (*proto.CartMutationReply, error) {
|
||||||
|
return g.client.AddItem(ctx, &proto.AddItemRequest{
|
||||||
|
CartId: g.Id.String(),
|
||||||
|
ClientTimestamp: ts,
|
||||||
|
Payload: m,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
case *proto.RemoveItem:
|
||||||
|
invoke = func(ctx context.Context) (*proto.CartMutationReply, error) {
|
||||||
|
return g.client.RemoveItem(ctx, &proto.RemoveItemRequest{
|
||||||
|
CartId: g.Id.String(),
|
||||||
|
ClientTimestamp: ts,
|
||||||
|
Payload: m,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
case *proto.RemoveDelivery:
|
||||||
|
invoke = func(ctx context.Context) (*proto.CartMutationReply, error) {
|
||||||
|
return g.client.RemoveDelivery(ctx, &proto.RemoveDeliveryRequest{
|
||||||
|
CartId: g.Id.String(),
|
||||||
|
ClientTimestamp: ts,
|
||||||
|
Payload: m,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
case *proto.ChangeQuantity:
|
||||||
|
invoke = func(ctx context.Context) (*proto.CartMutationReply, error) {
|
||||||
|
return g.client.ChangeQuantity(ctx, &proto.ChangeQuantityRequest{
|
||||||
|
CartId: g.Id.String(),
|
||||||
|
ClientTimestamp: ts,
|
||||||
|
Payload: m,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
case *proto.SetDelivery:
|
||||||
|
invoke = func(ctx context.Context) (*proto.CartMutationReply, error) {
|
||||||
|
return g.client.SetDelivery(ctx, &proto.SetDeliveryRequest{
|
||||||
|
CartId: g.Id.String(),
|
||||||
|
ClientTimestamp: ts,
|
||||||
|
Payload: m,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
case *proto.SetPickupPoint:
|
||||||
|
invoke = func(ctx context.Context) (*proto.CartMutationReply, error) {
|
||||||
|
return g.client.SetPickupPoint(ctx, &proto.SetPickupPointRequest{
|
||||||
|
CartId: g.Id.String(),
|
||||||
|
ClientTimestamp: ts,
|
||||||
|
Payload: m,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
case *proto.CreateCheckoutOrder:
|
||||||
|
return nil, fmt.Errorf("CreateCheckoutOrder deprecated: checkout is handled via HTTP endpoint (HandleCheckout)")
|
||||||
|
case *proto.SetCartRequest:
|
||||||
|
invoke = func(ctx context.Context) (*proto.CartMutationReply, error) {
|
||||||
|
return g.client.SetCartItems(ctx, &proto.SetCartItemsRequest{
|
||||||
|
CartId: g.Id.String(),
|
||||||
|
ClientTimestamp: ts,
|
||||||
|
Payload: m,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
case *proto.OrderCreated:
|
||||||
|
invoke = func(ctx context.Context) (*proto.CartMutationReply, error) {
|
||||||
|
return g.client.OrderCompleted(ctx, &proto.OrderCompletedRequest{
|
||||||
|
CartId: g.Id.String(),
|
||||||
|
ClientTimestamp: ts,
|
||||||
|
Payload: m,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported mutation type %T", content)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Marshal underlying proto payload only (no StorableMessageHeader)
|
if invoke == nil {
|
||||||
var buf bytes.Buffer
|
return nil, fmt.Errorf("no invocation mapped for mutation %T", content)
|
||||||
err = handler.Write(message, &buf)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("encode mutation payload: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
req := &proto.MutationRequest{
|
|
||||||
CartId: g.Id.String(),
|
|
||||||
Type: proto.MutationType(message.Type), // numeric mapping preserved
|
|
||||||
Payload: buf.Bytes(),
|
|
||||||
ClientTimestamp: *message.TimeStamp,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), g.mutateTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), g.mutateTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
resp, err := g.client.Mutate(ctx, req)
|
resp, err := invoke(ctx)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
frame := MakeFrameWithPayload(RemoteHandleMutationReply, StatusCode(resp.StatusCode), resp.Payload)
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
return &frame, nil
|
if e := resp.GetError(); e != "" {
|
||||||
|
return nil, fmt.Errorf("remote mutation failed %d: %s", resp.StatusCode, e)
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("remote mutation failed %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
state := resp.GetState()
|
||||||
|
if state == nil {
|
||||||
|
return nil, fmt.Errorf("mutation reply missing state on success")
|
||||||
|
}
|
||||||
|
// Reconstruct a lightweight CartGrain (only fields we expose internally)
|
||||||
|
grain := &CartGrain{
|
||||||
|
Id: ToCartId(state.CartId),
|
||||||
|
TotalPrice: state.TotalPrice,
|
||||||
|
TotalTax: state.TotalTax,
|
||||||
|
TotalDiscount: state.TotalDiscount,
|
||||||
|
PaymentInProgress: state.PaymentInProgress,
|
||||||
|
OrderReference: state.OrderReference,
|
||||||
|
PaymentStatus: state.PaymentStatus,
|
||||||
|
}
|
||||||
|
// Items
|
||||||
|
for _, it := range state.Items {
|
||||||
|
if it == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
outlet := toPtr(it.Outlet)
|
||||||
|
storeId := toPtr(it.StoreId)
|
||||||
|
grain.Items = append(grain.Items, &CartItem{
|
||||||
|
Id: int(it.Id),
|
||||||
|
ItemId: int(it.SourceItemId),
|
||||||
|
Sku: it.Sku,
|
||||||
|
Name: it.Name,
|
||||||
|
Price: it.UnitPrice,
|
||||||
|
Quantity: int(it.Quantity),
|
||||||
|
TotalPrice: it.TotalPrice,
|
||||||
|
TotalTax: it.TotalTax,
|
||||||
|
OrgPrice: it.OrgPrice,
|
||||||
|
TaxRate: int(it.TaxRate),
|
||||||
|
Brand: it.Brand,
|
||||||
|
Category: it.Category,
|
||||||
|
Category2: it.Category2,
|
||||||
|
Category3: it.Category3,
|
||||||
|
Category4: it.Category4,
|
||||||
|
Category5: it.Category5,
|
||||||
|
Image: it.Image,
|
||||||
|
ArticleType: it.ArticleType,
|
||||||
|
SellerId: it.SellerId,
|
||||||
|
SellerName: it.SellerName,
|
||||||
|
Disclaimer: it.Disclaimer,
|
||||||
|
Outlet: outlet,
|
||||||
|
StoreId: storeId,
|
||||||
|
Stock: StockStatus(it.Stock),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// Deliveries
|
||||||
|
for _, d := range state.Deliveries {
|
||||||
|
if d == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
intIds := make([]int, 0, len(d.ItemIds))
|
||||||
|
for _, id := range d.ItemIds {
|
||||||
|
intIds = append(intIds, int(id))
|
||||||
|
}
|
||||||
|
grain.Deliveries = append(grain.Deliveries, &CartDelivery{
|
||||||
|
Id: int(d.Id),
|
||||||
|
Provider: d.Provider,
|
||||||
|
Price: d.Price,
|
||||||
|
Items: intIds,
|
||||||
|
PickupPoint: d.PickupPoint,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return grain, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetCurrentState calls CartActor.GetState and returns a FrameWithPayload
|
// GetCurrentState retrieves the current cart state using the typed StateReply oneof.
|
||||||
// shaped like the legacy RemoteGetStateReply.
|
func (g *RemoteGrainGRPC) GetCurrentState() (*CartGrain, error) {
|
||||||
func (g *RemoteGrainGRPC) GetCurrentState() (*FrameWithPayload, error) {
|
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), g.stateTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), g.stateTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
|
resp, err := g.client.GetState(ctx, &proto.StateRequest{CartId: g.Id.String()})
|
||||||
resp, err := g.client.GetState(ctx, &proto.StateRequest{
|
|
||||||
CartId: g.Id.String(),
|
|
||||||
})
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
frame := MakeFrameWithPayload(RemoteGetStateReply, StatusCode(resp.StatusCode), resp.Payload)
|
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||||
return &frame, nil
|
if e := resp.GetError(); e != "" {
|
||||||
|
return nil, fmt.Errorf("remote get state failed %d: %s", resp.StatusCode, e)
|
||||||
|
}
|
||||||
|
return nil, fmt.Errorf("remote get state failed %d", resp.StatusCode)
|
||||||
|
}
|
||||||
|
state := resp.GetState()
|
||||||
|
if state == nil {
|
||||||
|
return nil, fmt.Errorf("state reply missing state on success")
|
||||||
|
}
|
||||||
|
grain := &CartGrain{
|
||||||
|
Id: ToCartId(state.CartId),
|
||||||
|
TotalPrice: state.TotalPrice,
|
||||||
|
TotalTax: state.TotalTax,
|
||||||
|
TotalDiscount: state.TotalDiscount,
|
||||||
|
PaymentInProgress: state.PaymentInProgress,
|
||||||
|
OrderReference: state.OrderReference,
|
||||||
|
PaymentStatus: state.PaymentStatus,
|
||||||
|
}
|
||||||
|
for _, it := range state.Items {
|
||||||
|
if it == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
outlet := toPtr(it.Outlet)
|
||||||
|
storeId := toPtr(it.StoreId)
|
||||||
|
grain.Items = append(grain.Items, &CartItem{
|
||||||
|
Id: int(it.Id),
|
||||||
|
ItemId: int(it.SourceItemId),
|
||||||
|
Sku: it.Sku,
|
||||||
|
Name: it.Name,
|
||||||
|
Price: it.UnitPrice,
|
||||||
|
Quantity: int(it.Quantity),
|
||||||
|
TotalPrice: it.TotalPrice,
|
||||||
|
TotalTax: it.TotalTax,
|
||||||
|
OrgPrice: it.OrgPrice,
|
||||||
|
TaxRate: int(it.TaxRate),
|
||||||
|
Brand: it.Brand,
|
||||||
|
Category: it.Category,
|
||||||
|
Category2: it.Category2,
|
||||||
|
Category3: it.Category3,
|
||||||
|
Category4: it.Category4,
|
||||||
|
Category5: it.Category5,
|
||||||
|
Image: it.Image,
|
||||||
|
ArticleType: it.ArticleType,
|
||||||
|
SellerId: it.SellerId,
|
||||||
|
SellerName: it.SellerName,
|
||||||
|
Disclaimer: it.Disclaimer,
|
||||||
|
Outlet: outlet,
|
||||||
|
StoreId: storeId,
|
||||||
|
Stock: StockStatus(it.Stock),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
for _, d := range state.Deliveries {
|
||||||
|
if d == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
intIds := make([]int, 0, len(d.ItemIds))
|
||||||
|
for _, id := range d.ItemIds {
|
||||||
|
intIds = append(intIds, int(id))
|
||||||
|
}
|
||||||
|
grain.Deliveries = append(grain.Deliveries, &CartDelivery{
|
||||||
|
Id: int(d.Id),
|
||||||
|
Provider: d.Provider,
|
||||||
|
Price: d.Price,
|
||||||
|
Items: intIds,
|
||||||
|
PickupPoint: d.PickupPoint,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return grain, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Close closes the underlying gRPC connection if this adapter created it.
|
// Close closes the underlying gRPC connection if this adapter created it.
|
||||||
|
|||||||
@@ -426,24 +426,17 @@ func (p *SyncedPool) getGrain(id CartId) (Grain, error) {
|
|||||||
return grain, nil
|
return grain, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Process applies mutation(s) to a grain (local or remote).
|
// Apply applies a single mutation to a grain (local or remote).
|
||||||
func (p *SyncedPool) Process(id CartId, messages ...Message) (*FrameWithPayload, error) {
|
func (p *SyncedPool) Apply(id CartId, mutation interface{}) (*CartGrain, error) {
|
||||||
grain, err := p.getGrain(id)
|
grain, err := p.getGrain(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
var res *FrameWithPayload
|
return grain.Apply(mutation, false)
|
||||||
for _, m := range messages {
|
|
||||||
res, err = grain.HandleMessage(&m, false)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return res, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get returns current state of a grain (local or remote).
|
// Get returns current state of a grain (local or remote).
|
||||||
func (p *SyncedPool) Get(id CartId) (*FrameWithPayload, error) {
|
func (p *SyncedPool) Get(id CartId) (*CartGrain, error) {
|
||||||
grain, err := p.getGrain(id)
|
grain, err := p.getGrain(id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
|
|||||||
Reference in New Issue
Block a user