// Package grpc exposes asyncmachines over gRPC. It's an equivalent of // /pkg/integrations/rest, using the same machine group and filters.
package grpc import ( ggrpc amhelp am ) // Server exposes a group of state machines over gRPC. type Server struct { UnimplementedAsyncmachineServiceServer ctx context.Context machs amhelp.MachGroup mu sync.RWMutex grpc *ggrpc.Server ln net.Listener } // New creates a gRPC server for the passed machines. func ( context.Context, amhelp.MachGroup) *Server { if == nil { = context.Background() } := &Server{ ctx: , machs: slices.Clone(), } .grpc = ggrpc.NewServer() RegisterAsyncmachineServiceServer(.grpc, ) return } // ListenAndServe listens on addr and serves the gRPC API, blocking until the // server is closed. func ( *Server) ( string) error { , := net.Listen("tcp", ) if != nil { return } return .Serve() } // Serve serves the gRPC API on ln, blocking until the server is closed. func ( *Server) ( net.Listener) error { .mu.Lock() .ln = .mu.Unlock() := .grpc.Serve() if errors.Is(, ggrpc.ErrServerStopped) { 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 { .grpc.Stop() return nil } // ///// ///// ///// // ///// API // ///// ///// ///// func ( *Server) ( context.Context, *ListMachinesReq, ) (*ListMachinesResp, error) { , := .filter() if != nil { return nil, } .mu.RLock() := slices.Clone(.machs) .mu.RUnlock() := .Filter() := make([]*Serialized, len()) for , := range { [] = toProto(integrations.Serialize()) } return &ListMachinesResp{Machines: }, nil } func ( *Server) ( context.Context, *GetMachineReq, ) (*Serialized, error) { := .mach(.Id) if == nil { return nil, status.Errorf(codes.NotFound, "machine not found: %s", .Id) } return toProto(integrations.Serialize()), nil } func ( *Server) ( context.Context, *CreateMachineReq, ) (*Serialized, error) { , := schemaFromStruct(.Schema) if != nil { return nil, } := fromProto(.Serialized) if != nil && .ID != "" && .mach(.ID) != nil { return nil, status.Errorf(codes.AlreadyExists, "machine already exists: %s", .ID) } if .ctx.Err() != nil { return nil, status.Error(codes.Unavailable, .ctx.Err().Error()) } , := integrations.NewMach(.ctx, , ) if != nil { return nil, status.Error(codes.InvalidArgument, .Error()) } .mu.Lock() .machs = append(.machs, ) .mu.Unlock() return toProto(integrations.Serialize()), nil } func ( *Server) ( context.Context, *MutateReq, ) (*MutateResp, error) { := .mach(.Id) if == nil { return nil, status.Errorf(codes.NotFound, "machine not found: %s", .Id) } := integrations.NewMutationReq() .Add = .Add .Remove = .Remove if .Args != nil { .Args = .Args.AsMap() } , := integrations.HandlerMutation(, , ) if != nil { return nil, status.Error(codes.InvalidArgument, .Error()) } return &MutateResp{Result: int64(.Result)}, nil } func ( *Server) ( context.Context, *WaitReq, ) (*WaitResp, error) { := .mach(.Id) if == nil { return nil, status.Errorf(codes.NotFound, "machine not found: %s", .Id) } := integrations.NewWaitingReq() .States = .States .StatesNot = .StatesNot .Time = .Time , := integrations.HandlerWaiting(, , ) if != nil { if errors.Is(, context.Canceled) || errors.Is(, context.DeadlineExceeded) { return nil, status.FromContextError().Err() } return nil, status.Error(codes.InvalidArgument, .Error()) } return &WaitResp{ Id: .MachId, States: .States, StatesNot: .StatesNot, Time: .Time, }, nil } func ( *Server) ( context.Context, *DisposeReq, ) (*DisposeResp, error) { := .removeMach(.Id) if == nil { return nil, status.Errorf(codes.NotFound, "machine not found: %s", .Id) } .Dispose() return &DisposeResp{Disposed: true}, nil } // ///// ///// ///// // ///// UTILS // ///// ///// ///// func ( *ListMachinesReq) () (*amhelp.MachGroupFilter, error) { := &amhelp.MachGroupFilter{ IdExact: .Id, IdSubstr: .IdSubstr, IdPrefix: .IdPrefix, IdSuffix: .IdSuffix, Parent: .Parent, MtimeMin: .MtimeMin, MtimeMax: .MtimeMax, MtimeStates: .MtimeStates, StatesActive: .Active, StatesInactive: .Inactive, Limit: int(.Limit), StartIdx: int(.StartIdx), } if .IdRegexp != "" { , := regexp.Compile(.IdRegexp) if != nil { return nil, status.Errorf(codes.InvalidArgument, "id_regexp: %s", ) } .IdRegexp = } return , nil } func ( *Server) ( string) am.Api { .mu.RLock() defer .mu.RUnlock() for , := range .machs { if .Id() == { return } } return nil } func ( *Server) ( string) am.Api { .mu.Lock() defer .mu.Unlock() := slices.IndexFunc(.machs, func( am.Api) bool { return .Id() == }) if < 0 { return nil } := .machs[] .machs = slices.Delete(.machs, , +1) return } func schemaFromStruct( *structpb.Struct) (am.Schema, error) { if == nil || len(.Fields) == 0 { return nil, status.Error(codes.InvalidArgument, "schema required") } , := json.Marshal(.AsMap()) if != nil { return nil, status.Error(codes.InvalidArgument, .Error()) } var am.Schema if := json.Unmarshal(, &); != nil { return nil, status.Error(codes.InvalidArgument, .Error()) } return , nil } func toProto( *am.Serialized) *Serialized { return &Serialized{ Id: .ID, StateNames: .StateNames, Time: .Time, QueueTick: .QueueTick, MachineTick: .MachineTick, Tags: .Tags, } } func fromProto( *Serialized) *am.Serialized { if == nil { return nil } return &am.Serialized{ ID: .Id, StateNames: .StateNames, Time: .Time, QueueTick: .QueueTick, MachineTick: .MachineTick, Tags: .Tags, } }