initial commit

This commit is contained in:
2022-02-04 20:23:04 +01:00
parent 0c44f26522
commit 2b614f6bd3
21 changed files with 1236 additions and 1 deletions

56
pkg/broadcaster.go Normal file
View File

@ -0,0 +1,56 @@
package gocron_server
import (
pb "github.com/strnophix/gocron-server/pkg/proto"
)
type Streamer interface {
Send(*pb.ListenJobResponse) error
}
type Streams []Streamer
type EventBroadcaster struct {
streams Streams
}
func NewEventBroadcaster() *EventBroadcaster {
return &EventBroadcaster{
streams: make(Streams, 0),
}
}
func (b *EventBroadcaster) Subscribe(stream Streamer) {
b.streams = append(b.streams, stream)
}
func (b *EventBroadcaster) Publish(resp *pb.ListenJobResponse) {
closed := make([]int, 0)
for idx, stream := range b.streams {
if err := stream.Send(resp); err != nil {
closed = append(closed, idx)
}
}
if len(closed) == len(b.streams) {
b.streams = nil
return
}
for idx := len(closed) - 1; idx > -1; idx-- {
removeStream(b.streams, idx)
}
}
func (b *EventBroadcaster) SubscriberCount() int {
return len(b.streams)
}
func removeStream(s Streams, i int) Streams {
s[i] = s[len(s)-1]
return s[:len(s)-1]
}
func NewBroadcastResponse(name, result string) *pb.ListenJobResponse {
return &pb.ListenJobResponse{JobName: name, JobResult: result}
}

43
pkg/broadcaster_test.go Normal file
View File

@ -0,0 +1,43 @@
package gocron_server_test
import (
"fmt"
"testing"
gocron_server "github.com/strnophix/gocron-server/pkg"
pb "github.com/strnophix/gocron-server/pkg/proto"
)
type TestStreamer struct {
CalledOnce bool
}
func NewTestStreamer() *TestStreamer {
return &TestStreamer{CalledOnce: false}
}
func (ts *TestStreamer) Send(stream *pb.ListenJobResponse) error {
if ts.CalledOnce == true {
return fmt.Errorf("Send can only be called once")
}
ts.CalledOnce = true
return nil
}
func TestPublish(t *testing.T) {
cl := NewTestStreamer()
eb := gocron_server.NewEventBroadcaster()
eb.Subscribe(cl)
msg := gocron_server.NewBroadcastResponse("test", "Content :)")
eb.Publish(msg)
if cl.CalledOnce == false {
t.Fatalf("The Send function should have been called on the stream")
}
eb.Publish(msg)
if eb.SubscriberCount() != 0 {
t.Fatalf("The second call of Send should have unsubscribed the stream")
}
}

View File

@ -0,0 +1,347 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.26.0
// protoc v3.19.2
// source: proto/gocron-server.proto
package gocron_server
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
type RunJobRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
UnitName string `protobuf:"bytes,1,opt,name=UnitName,proto3" json:"UnitName,omitempty"`
RunAt int64 `protobuf:"varint,10,opt,name=RunAt,proto3" json:"RunAt,omitempty"`
}
func (x *RunJobRequest) Reset() {
*x = RunJobRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_proto_gocron_server_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RunJobRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RunJobRequest) ProtoMessage() {}
func (x *RunJobRequest) ProtoReflect() protoreflect.Message {
mi := &file_proto_gocron_server_proto_msgTypes[0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RunJobRequest.ProtoReflect.Descriptor instead.
func (*RunJobRequest) Descriptor() ([]byte, []int) {
return file_proto_gocron_server_proto_rawDescGZIP(), []int{0}
}
func (x *RunJobRequest) GetUnitName() string {
if x != nil {
return x.UnitName
}
return ""
}
func (x *RunJobRequest) GetRunAt() int64 {
if x != nil {
return x.RunAt
}
return 0
}
type RunJobResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *RunJobResponse) Reset() {
*x = RunJobResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_proto_gocron_server_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *RunJobResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*RunJobResponse) ProtoMessage() {}
func (x *RunJobResponse) ProtoReflect() protoreflect.Message {
mi := &file_proto_gocron_server_proto_msgTypes[1]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use RunJobResponse.ProtoReflect.Descriptor instead.
func (*RunJobResponse) Descriptor() ([]byte, []int) {
return file_proto_gocron_server_proto_rawDescGZIP(), []int{1}
}
type ListenJobRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
}
func (x *ListenJobRequest) Reset() {
*x = ListenJobRequest{}
if protoimpl.UnsafeEnabled {
mi := &file_proto_gocron_server_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ListenJobRequest) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ListenJobRequest) ProtoMessage() {}
func (x *ListenJobRequest) ProtoReflect() protoreflect.Message {
mi := &file_proto_gocron_server_proto_msgTypes[2]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ListenJobRequest.ProtoReflect.Descriptor instead.
func (*ListenJobRequest) Descriptor() ([]byte, []int) {
return file_proto_gocron_server_proto_rawDescGZIP(), []int{2}
}
type ListenJobResponse struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
JobName string `protobuf:"bytes,1,opt,name=JobName,proto3" json:"JobName,omitempty"`
JobResult string `protobuf:"bytes,2,opt,name=JobResult,proto3" json:"JobResult,omitempty"`
}
func (x *ListenJobResponse) Reset() {
*x = ListenJobResponse{}
if protoimpl.UnsafeEnabled {
mi := &file_proto_gocron_server_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
}
func (x *ListenJobResponse) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*ListenJobResponse) ProtoMessage() {}
func (x *ListenJobResponse) ProtoReflect() protoreflect.Message {
mi := &file_proto_gocron_server_proto_msgTypes[3]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use ListenJobResponse.ProtoReflect.Descriptor instead.
func (*ListenJobResponse) Descriptor() ([]byte, []int) {
return file_proto_gocron_server_proto_rawDescGZIP(), []int{3}
}
func (x *ListenJobResponse) GetJobName() string {
if x != nil {
return x.JobName
}
return ""
}
func (x *ListenJobResponse) GetJobResult() string {
if x != nil {
return x.JobResult
}
return ""
}
var File_proto_gocron_server_proto protoreflect.FileDescriptor
var file_proto_gocron_server_proto_rawDesc = []byte{
0x0a, 0x19, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x63, 0x72, 0x6f, 0x6e, 0x2d, 0x73,
0x65, 0x72, 0x76, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0d, 0x67, 0x6f, 0x63,
0x72, 0x6f, 0x6e, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x22, 0x41, 0x0a, 0x0d, 0x52, 0x75,
0x6e, 0x4a, 0x6f, 0x62, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x12, 0x1a, 0x0a, 0x08, 0x55,
0x6e, 0x69, 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x55,
0x6e, 0x69, 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x52, 0x75, 0x6e, 0x41, 0x74,
0x18, 0x0a, 0x20, 0x01, 0x28, 0x03, 0x52, 0x05, 0x52, 0x75, 0x6e, 0x41, 0x74, 0x22, 0x10, 0x0a,
0x0e, 0x52, 0x75, 0x6e, 0x4a, 0x6f, 0x62, 0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x22,
0x12, 0x0a, 0x10, 0x4c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x4a, 0x6f, 0x62, 0x52, 0x65, 0x71, 0x75,
0x65, 0x73, 0x74, 0x22, 0x4b, 0x0a, 0x11, 0x4c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x4a, 0x6f, 0x62,
0x52, 0x65, 0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x4a, 0x6f, 0x62, 0x4e,
0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x4a, 0x6f, 0x62, 0x4e, 0x61,
0x6d, 0x65, 0x12, 0x1c, 0x0a, 0x09, 0x4a, 0x6f, 0x62, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x18,
0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x09, 0x4a, 0x6f, 0x62, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74,
0x32, 0xa5, 0x01, 0x0a, 0x09, 0x53, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, 0x72, 0x12, 0x45,
0x0a, 0x06, 0x52, 0x75, 0x6e, 0x4a, 0x6f, 0x62, 0x12, 0x1c, 0x2e, 0x67, 0x6f, 0x63, 0x72, 0x6f,
0x6e, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e, 0x52, 0x75, 0x6e, 0x4a, 0x6f, 0x62, 0x52,
0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x1a, 0x1d, 0x2e, 0x67, 0x6f, 0x63, 0x72, 0x6f, 0x6e, 0x5f,
0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x2e, 0x52, 0x75, 0x6e, 0x4a, 0x6f, 0x62, 0x52, 0x65, 0x73,
0x70, 0x6f, 0x6e, 0x73, 0x65, 0x12, 0x51, 0x0a, 0x0a, 0x4c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x4a,
0x6f, 0x62, 0x73, 0x12, 0x1f, 0x2e, 0x67, 0x6f, 0x63, 0x72, 0x6f, 0x6e, 0x5f, 0x73, 0x65, 0x72,
0x76, 0x65, 0x72, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x4a, 0x6f, 0x62, 0x52, 0x65, 0x71,
0x75, 0x65, 0x73, 0x74, 0x1a, 0x20, 0x2e, 0x67, 0x6f, 0x63, 0x72, 0x6f, 0x6e, 0x5f, 0x73, 0x65,
0x72, 0x76, 0x65, 0x72, 0x2e, 0x4c, 0x69, 0x73, 0x74, 0x65, 0x6e, 0x4a, 0x6f, 0x62, 0x52, 0x65,
0x73, 0x70, 0x6f, 0x6e, 0x73, 0x65, 0x30, 0x01, 0x42, 0x32, 0x5a, 0x30, 0x67, 0x69, 0x74, 0x68,
0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x73, 0x74, 0x72, 0x6e, 0x6f, 0x70, 0x68, 0x69, 0x78,
0x2f, 0x67, 0x6f, 0x63, 0x72, 0x6f, 0x6e, 0x2d, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x3b, 0x67,
0x6f, 0x63, 0x72, 0x6f, 0x6e, 0x5f, 0x73, 0x65, 0x72, 0x76, 0x65, 0x72, 0x62, 0x06, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x33,
}
var (
file_proto_gocron_server_proto_rawDescOnce sync.Once
file_proto_gocron_server_proto_rawDescData = file_proto_gocron_server_proto_rawDesc
)
func file_proto_gocron_server_proto_rawDescGZIP() []byte {
file_proto_gocron_server_proto_rawDescOnce.Do(func() {
file_proto_gocron_server_proto_rawDescData = protoimpl.X.CompressGZIP(file_proto_gocron_server_proto_rawDescData)
})
return file_proto_gocron_server_proto_rawDescData
}
var file_proto_gocron_server_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
var file_proto_gocron_server_proto_goTypes = []interface{}{
(*RunJobRequest)(nil), // 0: gocron_server.RunJobRequest
(*RunJobResponse)(nil), // 1: gocron_server.RunJobResponse
(*ListenJobRequest)(nil), // 2: gocron_server.ListenJobRequest
(*ListenJobResponse)(nil), // 3: gocron_server.ListenJobResponse
}
var file_proto_gocron_server_proto_depIdxs = []int32{
0, // 0: gocron_server.Scheduler.RunJob:input_type -> gocron_server.RunJobRequest
2, // 1: gocron_server.Scheduler.ListenJobs:input_type -> gocron_server.ListenJobRequest
1, // 2: gocron_server.Scheduler.RunJob:output_type -> gocron_server.RunJobResponse
3, // 3: gocron_server.Scheduler.ListenJobs:output_type -> gocron_server.ListenJobResponse
2, // [2:4] is the sub-list for method output_type
0, // [0:2] is the sub-list for method input_type
0, // [0:0] is the sub-list for extension type_name
0, // [0:0] is the sub-list for extension extendee
0, // [0:0] is the sub-list for field type_name
}
func init() { file_proto_gocron_server_proto_init() }
func file_proto_gocron_server_proto_init() {
if File_proto_gocron_server_proto != nil {
return
}
if !protoimpl.UnsafeEnabled {
file_proto_gocron_server_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RunJobRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_proto_gocron_server_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*RunJobResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_proto_gocron_server_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ListenJobRequest); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
file_proto_gocron_server_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
switch v := v.(*ListenJobResponse); i {
case 0:
return &v.state
case 1:
return &v.sizeCache
case 2:
return &v.unknownFields
default:
return nil
}
}
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: file_proto_gocron_server_proto_rawDesc,
NumEnums: 0,
NumMessages: 4,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_proto_gocron_server_proto_goTypes,
DependencyIndexes: file_proto_gocron_server_proto_depIdxs,
MessageInfos: file_proto_gocron_server_proto_msgTypes,
}.Build()
File_proto_gocron_server_proto = out.File
file_proto_gocron_server_proto_rawDesc = nil
file_proto_gocron_server_proto_goTypes = nil
file_proto_gocron_server_proto_depIdxs = nil
}

View File

@ -0,0 +1,23 @@
syntax = "proto3";
package gocron_server;
option go_package = "github.com/strnophix/gocron-server;gocron_server";
service Scheduler {
rpc RunJob(RunJobRequest) returns (RunJobResponse);
rpc ListenJobs(ListenJobRequest) returns (stream ListenJobResponse);
}
message RunJobRequest {
string UnitName = 1;
int64 RunAt = 10;
}
message RunJobResponse {}
message ListenJobRequest {}
message ListenJobResponse {
string JobName = 1;
string JobResult = 2;
}

View File

@ -0,0 +1,165 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
package gocron_server
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.32.0 or later.
const _ = grpc.SupportPackageIsVersion7
// SchedulerClient is the client API for Scheduler 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.
type SchedulerClient interface {
RunJob(ctx context.Context, in *RunJobRequest, opts ...grpc.CallOption) (*RunJobResponse, error)
ListenJobs(ctx context.Context, in *ListenJobRequest, opts ...grpc.CallOption) (Scheduler_ListenJobsClient, error)
}
type schedulerClient struct {
cc grpc.ClientConnInterface
}
func NewSchedulerClient(cc grpc.ClientConnInterface) SchedulerClient {
return &schedulerClient{cc}
}
func (c *schedulerClient) RunJob(ctx context.Context, in *RunJobRequest, opts ...grpc.CallOption) (*RunJobResponse, error) {
out := new(RunJobResponse)
err := c.cc.Invoke(ctx, "/gocron_server.Scheduler/RunJob", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *schedulerClient) ListenJobs(ctx context.Context, in *ListenJobRequest, opts ...grpc.CallOption) (Scheduler_ListenJobsClient, error) {
stream, err := c.cc.NewStream(ctx, &Scheduler_ServiceDesc.Streams[0], "/gocron_server.Scheduler/ListenJobs", opts...)
if err != nil {
return nil, err
}
x := &schedulerListenJobsClient{stream}
if err := x.ClientStream.SendMsg(in); err != nil {
return nil, err
}
if err := x.ClientStream.CloseSend(); err != nil {
return nil, err
}
return x, nil
}
type Scheduler_ListenJobsClient interface {
Recv() (*ListenJobResponse, error)
grpc.ClientStream
}
type schedulerListenJobsClient struct {
grpc.ClientStream
}
func (x *schedulerListenJobsClient) Recv() (*ListenJobResponse, error) {
m := new(ListenJobResponse)
if err := x.ClientStream.RecvMsg(m); err != nil {
return nil, err
}
return m, nil
}
// SchedulerServer is the server API for Scheduler service.
// All implementations must embed UnimplementedSchedulerServer
// for forward compatibility
type SchedulerServer interface {
RunJob(context.Context, *RunJobRequest) (*RunJobResponse, error)
ListenJobs(*ListenJobRequest, Scheduler_ListenJobsServer) error
mustEmbedUnimplementedSchedulerServer()
}
// UnimplementedSchedulerServer must be embedded to have forward compatible implementations.
type UnimplementedSchedulerServer struct {
}
func (UnimplementedSchedulerServer) RunJob(context.Context, *RunJobRequest) (*RunJobResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method RunJob not implemented")
}
func (UnimplementedSchedulerServer) ListenJobs(*ListenJobRequest, Scheduler_ListenJobsServer) error {
return status.Errorf(codes.Unimplemented, "method ListenJobs not implemented")
}
func (UnimplementedSchedulerServer) mustEmbedUnimplementedSchedulerServer() {}
// UnsafeSchedulerServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to SchedulerServer will
// result in compilation errors.
type UnsafeSchedulerServer interface {
mustEmbedUnimplementedSchedulerServer()
}
func RegisterSchedulerServer(s grpc.ServiceRegistrar, srv SchedulerServer) {
s.RegisterService(&Scheduler_ServiceDesc, srv)
}
func _Scheduler_RunJob_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RunJobRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(SchedulerServer).RunJob(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/gocron_server.Scheduler/RunJob",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(SchedulerServer).RunJob(ctx, req.(*RunJobRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Scheduler_ListenJobs_Handler(srv interface{}, stream grpc.ServerStream) error {
m := new(ListenJobRequest)
if err := stream.RecvMsg(m); err != nil {
return err
}
return srv.(SchedulerServer).ListenJobs(m, &schedulerListenJobsServer{stream})
}
type Scheduler_ListenJobsServer interface {
Send(*ListenJobResponse) error
grpc.ServerStream
}
type schedulerListenJobsServer struct {
grpc.ServerStream
}
func (x *schedulerListenJobsServer) Send(m *ListenJobResponse) error {
return x.ServerStream.SendMsg(m)
}
// Scheduler_ServiceDesc is the grpc.ServiceDesc for Scheduler service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Scheduler_ServiceDesc = grpc.ServiceDesc{
ServiceName: "gocron_server.Scheduler",
HandlerType: (*SchedulerServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "RunJob",
Handler: _Scheduler_RunJob_Handler,
},
},
Streams: []grpc.StreamDesc{
{
StreamName: "ListenJobs",
Handler: _Scheduler_ListenJobs_Handler,
ServerStreams: true,
},
},
Metadata: "proto/gocron-server.proto",
}

106
pkg/scheduler_service.go Normal file
View File

@ -0,0 +1,106 @@
package gocron_server
import (
"context"
"fmt"
"time"
"github.com/go-co-op/gocron"
pb "github.com/strnophix/gocron-server/pkg/proto"
)
type JobFunc func() (string, error)
type UnitStore map[string]*SchedulerUnit
type JobStore map[string]*gocron.Job
type SchedulerService struct {
pb.UnimplementedSchedulerServer
UnitStore
JobStore
EventBroadcaster
Scheduler *gocron.Scheduler
}
func NewSchedulerService() *SchedulerService {
scheduler := gocron.NewScheduler(time.UTC)
scheduler.StartAsync()
return &SchedulerService{
Scheduler: scheduler,
UnitStore: make(UnitStore),
JobStore: make(JobStore),
}
}
func (s *SchedulerService) Shutdown() {
s.Scheduler.Stop()
}
func (s *SchedulerService) AddUnit(unit *SchedulerUnit) error {
s.UnitStore[unit.Name] = unit
if unit.Cron != "" {
routine := s.BuildRoutine(unit)
job, err := s.Scheduler.Cron(unit.Cron).SingletonMode().Do(routine)
if err != nil {
return err
}
s.JobStore[unit.Name] = job
}
return nil
}
func (s *SchedulerService) BuildRoutine(unit *SchedulerUnit) func() {
return func() {
out, err := unit.Exec.Call()
if err != nil {
msg := NewBroadcastResponse(unit.Name, err.Error())
s.EventBroadcaster.Publish(msg)
return
}
msg := NewBroadcastResponse(unit.Name, out)
s.EventBroadcaster.Publish(msg)
}
}
func NewRunJobError(reason string) (*pb.RunJobResponse, error) {
return &pb.RunJobResponse{}, fmt.Errorf(reason)
}
func NewRunJobSucces() (*pb.RunJobResponse, error) {
return &pb.RunJobResponse{}, nil
}
func (s *SchedulerService) RunJob(ctx context.Context, req *pb.RunJobRequest) (*pb.RunJobResponse, error) {
unit, exists := s.UnitStore[req.UnitName]
if !exists {
return NewRunJobError(fmt.Sprintf("Unit with name %s does not exist", req.UnitName))
}
routine := s.BuildRoutine(unit)
if req.RunAt != 0 {
ts := time.Unix(req.RunAt, 0).UTC()
job, err := s.Scheduler.Every(1).Day().At(ts).LimitRunsTo(1).SingletonMode().Do(routine)
if err != nil {
fmt.Printf("Unix run error: %v", err)
}
s.JobStore[unit.Name] = job
return NewRunJobSucces()
}
go routine()
return NewRunJobSucces()
}
func (s *SchedulerService) ListenJobs(req *pb.ListenJobRequest, stream pb.Scheduler_ListenJobsServer) error {
s.EventBroadcaster.Subscribe(stream)
<-stream.Context().Done()
return nil
}

View File

@ -0,0 +1,71 @@
package gocron_server_test
import (
"context"
"log"
"net"
"testing"
"time"
gocron_server "github.com/strnophix/gocron-server/pkg"
pb "github.com/strnophix/gocron-server/pkg/proto"
"google.golang.org/grpc"
"google.golang.org/grpc/test/bufconn"
)
const bufSize = 1024 * 1024
var lis *bufconn.Listener
var c *Counter
func init() {
c = &Counter{Current: 1}
lis = bufconn.Listen(bufSize)
gs := grpc.NewServer()
s := gocron_server.NewSchedulerService()
defer s.Shutdown()
incr := gocron_server.NewUnitExecFn(c.Increment)
unit := gocron_server.NewManualUnit("incr", incr)
s.AddUnit(unit)
pb.RegisterSchedulerServer(gs, s)
go func() {
if err := gs.Serve(lis); err != nil {
log.Fatalf("Failed to serve: %v", err)
}
}()
}
func bufDialer(context.Context, string) (net.Conn, error) {
return lis.Dial()
}
func TestRunJob(t *testing.T) {
ctx := context.Background()
conn, err := grpc.DialContext(ctx, "bufnet", grpc.WithContextDialer(bufDialer), grpc.WithInsecure())
if err != nil {
t.Fatalf("Failed to dial bufnet: %v", err)
}
defer conn.Close()
client := pb.NewSchedulerClient(conn)
_, err = client.RunJob(ctx, &pb.RunJobRequest{UnitName: "niku"})
if err == nil {
t.Fatalf("RunJob should have returned an error for unit niku")
}
_, err = client.RunJob(ctx, &pb.RunJobRequest{UnitName: "incr"})
if err != nil {
t.Fatalf("RunJob call should have passed but got: %v", err)
}
time.Sleep(1 * time.Second)
if c.Current != 2 {
t.Fatalf("RunJob call `incr` should have incremented counter but stays at: %d", c.Current)
}
}

66
pkg/scheduler_unit.go Normal file
View File

@ -0,0 +1,66 @@
package gocron_server
import (
"os/exec"
"strings"
)
type UnitExecutable interface {
Call() (string, error)
}
type UnitExecCmd struct {
name string
args []string
}
func (ue *UnitExecCmd) Call() (string, error) {
cmd := exec.Command(ue.name, ue.args...)
out, err := cmd.Output()
strout := string(out[:])
if err != nil {
return strout, err
}
return strout, nil
}
func NewUnitExecCmd(command string) *UnitExecCmd {
cmdFrags := strings.Split(command, " ")
return &UnitExecCmd{name: cmdFrags[0], args: cmdFrags[1:]}
}
type UnitExecFn struct {
fn JobFunc
}
func (ue *UnitExecFn) Call() (string, error) {
return ue.fn()
}
func NewUnitExecFn(fn JobFunc) *UnitExecFn {
return &UnitExecFn{fn}
}
type SchedulerUnit struct {
Name string
Exec UnitExecutable
Cron string
}
func NewSchedulerUnit(name, cron string, exec UnitExecutable) *SchedulerUnit {
return &SchedulerUnit{
Name: name,
Exec: exec,
Cron: cron,
}
}
func NewManualUnit(name string, exec UnitExecutable) *SchedulerUnit {
return &SchedulerUnit{
Name: name,
Exec: exec,
Cron: "",
}
}

View File

@ -0,0 +1,32 @@
package gocron_server_test
import (
"testing"
gocron_server "github.com/strnophix/gocron-server/pkg"
)
func TestUnitExecutableCommand(t *testing.T) {
cmd := gocron_server.NewUnitExecCmd("echo hi")
out, err := cmd.Call()
if err != nil {
t.Fatalf("Should not have errored on a simple echo")
}
if out != "hi\n" {
t.Fatalf("Execution should have returned \"hi\" but gave: %s", out)
}
c := Counter{Current: 1}
fn := gocron_server.NewUnitExecFn(c.Increment)
out, _ = fn.Call()
if out != "2" {
t.Fatalf("Execution of unit should have incremented counter but got: %d", c.Current)
}
cmd = gocron_server.NewUnitExecCmd("false")
_, err = cmd.Call()
if err == nil {
t.Fatalf("Should have returned an error on a non-zero exit")
}
}

12
pkg/setup_test.go Normal file
View File

@ -0,0 +1,12 @@
package gocron_server_test
import "fmt"
type Counter struct {
Current int
}
func (c *Counter) Increment() (string, error) {
c.Current += 1
return fmt.Sprint(c.Current), nil
}