Files
go-cart-actor/main.go
matst80 23c3cae9b9
All checks were successful
Build and Publish / BuildAndDeploy (push) Successful in 31s
more metrics
2024-11-09 11:49:11 +01:00

161 lines
3.7 KiB
Go

package main
import (
"fmt"
"log"
"net/http"
"os"
"time"
messages "git.tornberg.me/go-cart-actor/proto"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
grainSpawns = promauto.NewCounter(prometheus.CounterOpts{
Name: "cart_grain_spawned_total",
Help: "The total number of spawned grains",
})
grainMutations = promauto.NewCounter(prometheus.CounterOpts{
Name: "cart_grain_mutations_total",
Help: "The total number of mutations",
})
grainLookups = promauto.NewCounter(prometheus.CounterOpts{
Name: "cart_grain_lookups_total",
Help: "The total number of lookups",
})
)
func spawn(id CartId) (*CartGrain, error) {
grainSpawns.Inc()
ret := &CartGrain{
Id: id,
Items: []CartItem{},
storageMessages: []Message{},
TotalPrice: 0,
}
err := loadMessages(ret, id)
return ret, err
}
func init() {
os.Mkdir("data", 0755)
}
type App struct {
pool *GrainLocalPool
storage *DiskStorage
}
func (a *App) Save() error {
for id, grain := range a.pool.GetGrains() {
if grain == nil {
continue
}
err := a.storage.Store(id, grain)
if err != nil {
log.Printf("Error saving grain %s: %v\n", id, err)
}
}
return a.storage.saveState()
}
func (a *App) HandleSave(w http.ResponseWriter, r *http.Request) {
err := a.Save()
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
} else {
w.WriteHeader(http.StatusCreated)
}
}
type PoolServer struct {
pool GrainPool
}
func NewPoolServer(pool GrainPool) *PoolServer {
return &PoolServer{
pool: pool,
}
}
func (s *PoolServer) HandleGet(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
data, err := s.pool.Get(ToCartId(id))
if err != nil {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(data)
}
func (s *PoolServer) HandleAddSku(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
sku := r.PathValue("sku")
data, err := s.pool.Process(ToCartId(id), Message{
Type: AddRequestType,
Content: &messages.AddRequest{Sku: sku},
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(data)
}
func (s *PoolServer) Serve() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("GET /{id}", s.HandleGet)
mux.HandleFunc("GET /{id}/add/{sku}", s.HandleAddSku)
return mux
}
var clientName = os.Getenv("NODE_NAME")
func main() {
// Create a new instance of the server
storage, err := NewDiskStorage(fmt.Sprintf("data/%s_state.gob", clientName))
if err != nil {
log.Printf("Error loading state: %v\n", err)
}
app := &App{
pool: NewGrainLocalPool(1000, 5*time.Minute, spawn),
storage: storage,
}
syncedPool, err := NewSyncedPool(app.pool, clientName)
if err != nil {
log.Fatalf("Error creating synced pool: %v\n", err)
}
// if local
syncedPool.AddRemote("localhost")
rpcHandler, err := NewGrainHandler(app.pool, ":1337")
if err != nil {
log.Fatalf("Error creating handler: %v\n", err)
}
go rpcHandler.Serve()
syncedServer := NewPoolServer(syncedPool)
mux := http.NewServeMux()
mux.Handle("/api/", http.StripPrefix("/api", syncedServer.Serve()))
mux.HandleFunc("GET /add/remote/{host}", func(w http.ResponseWriter, r *http.Request) {
syncedPool.AddRemote(r.PathValue("host"))
})
mux.HandleFunc("GET /save", app.HandleSave)
mux.Handle("/metrics", promhttp.Handler())
http.ListenAndServe(":8080", mux)
}