// Package rest exposes asyncmachines over a JSON REST API. // // Routes: // - GET /mach list machines as am.Serialized, with filters // - GET /mach/{id} machine as am.Serialized // - POST /mach create a machine from a schema (and optional state) // - POST /mach/{id} mutate states (integrations.MutationReq) // - POST /mach/{id}/wait wait for states (integrations.WaitingReq) // - POST /dispose/{id} dispose a machine // // GET /mach accepts query params matching [amhelp.MachGroupFilter]: id, // id_substr, id_regexp, id_prefix, id_suffix, parent, mtime_min, mtime_max, // mtime_states, active, inactive, limit, start_idx. List params accept both // CSV and repeated values.
package rest import ( amhelp am ) // Server exposes a group of state machines over HTTP. type Server struct { ctx context.Context machs amhelp.MachGroup mu sync.RWMutex handler http.Handler http *http.Server ln net.Listener } // NewMachReq is a request to create a state machine. It's compatible with // [am.Serialized], so an exported machine can be re-created by adding a // schema. type NewMachReq struct { am.Serialized // Schema defines the new state machine. Schema am.Schema `json:"schema"` } // ErrResp is a JSON error response. type ErrResp struct { Error string `json:"error"` } // New creates a REST server for the passed machines. func ( context.Context, amhelp.MachGroup) *Server { if == nil { = context.Background() } := &Server{ ctx: , machs: slices.Clone(), } := http.NewServeMux() .HandleFunc("GET /mach", .machsRpcJson) .HandleFunc("POST /mach", .createMachRpcJson) .HandleFunc("GET /mach/{id}", .machRpcJson) .HandleFunc("POST /mach/{id}", .mutationRpcJson) .HandleFunc("POST /mach/{id}/wait", .waitingRpcJson) .HandleFunc("POST /dispose/{id}", .disposeRpcJson) .handler = return } // Handler returns the HTTP handler of this server. func ( *Server) () http.Handler { return .handler } // ListenAndServe listens on addr and serves the REST API, blocking until the // server is closed. func ( *Server) ( string) error { , := net.Listen("tcp", ) if != nil { return } := &http.Server{Handler: .handler} .mu.Lock() .ln = .http = .mu.Unlock() = .Serve() if errors.Is(, http.ErrServerClosed) { return nil } return } // Addr returns the address the server listens on. func ( *Server) () string { .mu.RLock() defer .mu.RUnlock() if .ln == nil { return "" } return .ln.Addr().String() } // Close closes the server. func ( *Server) () error { .mu.Lock() defer .mu.Unlock() if .http == nil { return nil } return .http.Close() } // ///// ///// ///// // ///// HANDLERS // ///// ///// ///// func ( *Server) ( http.ResponseWriter, *http.Request) { , := parseFilter() if != nil { writeErr(, http.StatusBadRequest, .Error()) return } .mu.RLock() := slices.Clone(.machs) .mu.RUnlock() := .Filter() := make([]*am.Serialized, len()) for , := range { [] = integrations.Serialize() } writeJson(, http.StatusOK, ) } func ( *Server) ( http.ResponseWriter, *http.Request) { := .mach(.PathValue("id")) if == nil { writeErr(, http.StatusNotFound, "machine not found") return } writeJson(, http.StatusOK, integrations.Serialize()) } func ( *Server) ( http.ResponseWriter, *http.Request) { := &NewMachReq{} if := json.NewDecoder(.Body).Decode(); != nil { writeErr(, http.StatusBadRequest, .Error()) return } if len(.Schema) == 0 { writeErr(, http.StatusBadRequest, "schema required") return } if , := .Schema.Parse(); != nil { writeErr(, http.StatusBadRequest, .Error()) return } if .ID != "" && .mach(.ID) != nil { writeErr(, http.StatusConflict, "machine already exists") return } , := integrations.NewMach(.ctx, .Schema, &.Serialized) if != nil { writeErr(, http.StatusBadRequest, .Error()) return } .mu.Lock() .machs = append(.machs, ) .mu.Unlock() writeJson(, http.StatusCreated, integrations.Serialize()) } func ( *Server) ( http.ResponseWriter, *http.Request) { := .mach(.PathValue("id")) if == nil { writeErr(, http.StatusNotFound, "machine not found") return } := &integrations.MutationReq{} if := json.NewDecoder(.Body).Decode(); != nil { writeErr(, http.StatusBadRequest, .Error()) return } if .Kind.Value == "" { .Kind = integrations.KindReqMutation } , := integrations.HandlerMutation(.Context(), , ) if != nil { writeErr(, http.StatusBadRequest, .Error()) return } writeJson(, http.StatusOK, ) } func ( *Server) ( http.ResponseWriter, *http.Request) { := .mach(.PathValue("id")) if == nil { writeErr(, http.StatusNotFound, "machine not found") return } := &integrations.WaitingReq{} if := json.NewDecoder(.Body).Decode(); != nil { writeErr(, http.StatusBadRequest, .Error()) return } if .Kind.Value == "" { .Kind = integrations.KindReqWaiting } , := integrations.HandlerWaiting(.Context(), , ) if != nil { writeErr(, http.StatusBadRequest, .Error()) return } writeJson(, http.StatusOK, ) } func ( *Server) ( http.ResponseWriter, *http.Request) { := .PathValue("id") .mu.Lock() := slices.IndexFunc(.machs, func( am.Api) bool { return .Id() == }) var am.Api if >= 0 { = .machs[] .machs = slices.Delete(.machs, , +1) } .mu.Unlock() if == nil { writeErr(, http.StatusNotFound, "machine not found") return } .Dispose() writeJson(, http.StatusOK, map[string]any{ "id": , "disposed": true, }) } // ///// ///// ///// // ///// UTILS // ///// ///// ///// func ( *Server) ( string) am.Api { .mu.RLock() defer .mu.RUnlock() for , := range .machs { if .Id() == { return } } return nil } func parseFilter( *http.Request) (*amhelp.MachGroupFilter, error) { := .URL.Query() := &amhelp.MachGroupFilter{ IdExact: .Get("id"), IdSubstr: .Get("id_substr"), IdPrefix: .Get("id_prefix"), IdSuffix: .Get("id_suffix"), Parent: .Get("parent"), MtimeStates: csv(["mtime_states"]), StatesActive: csv(["active"]), StatesInactive: csv(["inactive"]), } if := .Get("id_regexp"); != "" { var error .IdRegexp, = regexp.Compile() if != nil { return nil, fmt.Errorf("id_regexp: %w", ) } } var error if .MtimeMin, = parseUint(.Get("mtime_min")); != nil { return nil, fmt.Errorf("mtime_min: %w", ) } if .MtimeMax, = parseUint(.Get("mtime_max")); != nil { return nil, fmt.Errorf("mtime_max: %w", ) } if .Limit, = parseInt(.Get("limit")); != nil { return nil, fmt.Errorf("limit: %w", ) } if .StartIdx, = parseInt(.Get("start_idx")); != nil { return nil, fmt.Errorf("start_idx: %w", ) } return , nil } func csv( []string) am.S { var am.S for , := range { for , := range strings.Split(, ",") { if = strings.TrimSpace(); != "" { = append(, ) } } } return } func parseUint( string) (uint64, error) { if == "" { return 0, nil } return strconv.ParseUint(, 10, 64) } func parseInt( string) (int, error) { if == "" { return 0, nil } return strconv.Atoi() } func writeJson( http.ResponseWriter, int, any) { .Header().Set("Content-Type", "application/json") .WriteHeader() _ = json.NewEncoder().Encode() } func writeErr( http.ResponseWriter, int, string) { writeJson(, , &ErrResp{Error: }) }