Skip to content

Commit

Permalink
Merge pull request #31 from sev-2/feature/scheduler
Browse files Browse the repository at this point in the history
Feature : support scheduler
  • Loading branch information
toopay committed Jun 14, 2024
2 parents ed92043 + 1354622 commit 68b2a40
Show file tree
Hide file tree
Showing 9 changed files with 331 additions and 14 deletions.
5 changes: 5 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ type Config struct {
SupabaseApiUrl string `mapstructure:"SUPABASE_API_URL"`
SupabaseApiBasePath string `mapstructure:"SUPABASE_API_BASE_PATH"`
SupabasePublicUrl string `mapstructure:"SUPABASE_PUBLIC_URL"`
ScheduleStatus ScheduleStatus `mapstructure:"SCHEDULE_STATUS"`
TraceEnable bool `mapstructure:"TRACE_ENABLE"`
TraceCollector string `mapstructure:"TRACE_COLLECTOR"`
TraceCollectorEndpoint string `mapstructure:"TRACE_COLLECTOR_ENDPOINT"`
Expand Down Expand Up @@ -84,6 +85,10 @@ func LoadConfig(path *string) (*Config, error) {
config.Environment = "development"
}

if config.ScheduleStatus == "" {
config.ScheduleStatus = ScheduleStatusOff
}

if len(config.SupabaseApiBasePath) > 0 && config.SupabaseApiBasePath[0] != '/' {
config.SupabaseApiBasePath = "/" + config.SupabaseApiBasePath
}
Expand Down
10 changes: 7 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ require (
github.com/erikgeiser/promptkit v0.9.0
github.com/fasthttp/websocket v1.5.8
github.com/fatih/color v1.16.0
github.com/go-co-op/gocron/v2 v2.5.0
github.com/google/uuid v1.6.0
github.com/hashicorp/go-hclog v1.6.3
github.com/jinzhu/inflection v1.0.0
github.com/spf13/cobra v1.8.0
github.com/stretchr/testify v1.8.4
github.com/stretchr/testify v1.9.0
github.com/zeromicro/go-zero v1.6.1
go.opentelemetry.io/otel v1.22.0
go.opentelemetry.io/otel/trace v1.22.0
Expand Down Expand Up @@ -39,7 +41,7 @@ require (
github.com/golang/protobuf v1.5.3 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.18.0 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jonboulle/clockwork v0.4.0 // indirect
github.com/klauspost/compress v1.17.7 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
Expand All @@ -54,6 +56,7 @@ require (
github.com/pelletier/go-toml v1.2.0 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/rivo/uniseg v0.4.4 // indirect
github.com/robfig/cron/v3 v3.0.1 // indirect
github.com/savsgio/gotils v0.0.0-20240303185622-093b76447511 // indirect
github.com/spaolacci/murmur3 v1.1.0 // indirect
github.com/spf13/afero v1.1.2 // indirect
Expand All @@ -67,8 +70,9 @@ require (
go.opentelemetry.io/proto/otlp v1.0.0 // indirect
go.uber.org/automaxprocs v1.5.3 // indirect
golang.org/x/crypto v0.21.0 // indirect
golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f // indirect
golang.org/x/net v0.23.0 // indirect
golang.org/x/sync v0.5.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/term v0.18.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20231016165738-49dd2c1f3d0b // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20231016165738-49dd2c1f3d0b // indirect
Expand Down
16 changes: 12 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4
github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
github.com/go-co-op/gocron/v2 v2.5.0 h1:ff/TJX9GdTJBDL1il9cyd/Sj3WnS+BB7ZzwHKSNL5p8=
github.com/go-co-op/gocron/v2 v2.5.0/go.mod h1:ckPQw96ZuZLRUGu88vVpd9a6d9HakI14KWahFZtGvNw=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ=
github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
Expand Down Expand Up @@ -79,6 +81,8 @@ github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jonboulle/clockwork v0.4.0 h1:p4Cf1aMWXnXAUh8lVfewRBx1zaTSYKrKMF2g3ST4RZ4=
github.com/jonboulle/clockwork v0.4.0/go.mod h1:xgRqUGwRcjKCO1vbZUEtSLrqKoPSsUpK7fnezOII0kc=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/klauspost/compress v1.17.7 h1:ehO88t2UGzQK66LMdE8tibEd1ErmzZjNEqWkjLAKQQg=
github.com/klauspost/compress v1.17.7/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
Expand Down Expand Up @@ -133,6 +137,8 @@ github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJ
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis=
github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=
github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
Expand Down Expand Up @@ -163,8 +169,8 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
Expand Down Expand Up @@ -201,12 +207,14 @@ golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACk
golang.org/x/crypto v0.0.0-20200510223506-06a226fb4e37/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f h1:99ci1mjWVBWwJiEKYY6jWa4d2nTQVIEhZIptnrVb1XY=
golang.org/x/exp v0.0.0-20240416160154-fe59bbe5cc7f/go.mod h1:/lliqkxwWAhPjf5oSOIJup2XcqJaw8RGS6k3TGEc7GI=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs=
golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
Expand Down
7 changes: 7 additions & 0 deletions pkg/cli/generate/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,13 @@ func Run(flags *Flags, config *raiden.Config, projectPath string, initialize boo
}
GenerateLogger.Debug("finish generate storages register file")

// generate job register
GenerateLogger.Debug("start generate job register file")
if err := generator.GenerateJobRegister(projectPath, config.ProjectName, generator.Generate); err != nil {
errChan <- err
}
GenerateLogger.Debug("finish generate job register file")

if initialize {
// generate import main function
GenerateLogger.Debug("start generate import main function file")
Expand Down
2 changes: 1 addition & 1 deletion pkg/generator/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func createHelloWorldController(controllerPath string, generateFn GenerateFn) er
data := GenerateControllerData{
Name: "HelloWorld",
Package: "controllers",
HttpTag: "`path:\"/hello/{name}\" type:\"custom\"`",
HttpTag: "`path:\"/hello\" type:\"custom\"`",
Imports: imports,
RequestFields: requestFields,
ResponseFields: responseField,
Expand Down
131 changes: 131 additions & 0 deletions pkg/generator/job_register.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
package generator

import (
"fmt"
"io/fs"
"path/filepath"
"strings"

"github.com/hashicorp/go-hclog"
"github.com/sev-2/raiden/pkg/logger"
"github.com/sev-2/raiden/pkg/utils"
)

var JobRegisterLogger hclog.Logger = logger.HcLog().Named("generator.job_register")

// ----- Define type, variable and constant -----
type (
GenerateRegisterJobData struct {
Imports []string
Package string
Jobs []string
}
)

const (
JobRegisterFilename = "jobs.go"
JobRegisterDir = "internal/bootstrap"
JobDir = "internal/jobs"
JobRegisterTemplate = `// Code generated by raiden-cli; DO NOT EDIT.
package {{ .Package }}
{{if gt (len .Imports) 0 }}
import (
{{- range .Imports}}
{{.}}
{{- end}}
)
{{end }}
func RegisterJobs(server *raiden.Server) {
server.RegisterJobs(
{{- range .Jobs}}
&jobs.{{.}}{},
{{- end}}
)
}
`
)

func GenerateJobRegister(basePath string, projectName string, generateFn GenerateFn) error {
jobRegisterDir := filepath.Join(basePath, JobRegisterDir)
JobRegisterLogger.Trace("create bootstrap folder if not exist", "path", jobRegisterDir)
if exist := utils.IsFolderExists(jobRegisterDir); !exist {
if err := utils.CreateFolder(jobRegisterDir); err != nil {
return err
}
}

jobDir := filepath.Join(basePath, JobDir)
JobRegisterLogger.Trace("create job folder if not exist", "path", jobDir)
if exist := utils.IsFolderExists(jobDir); !exist {
if err := utils.CreateFolder(jobDir); err != nil {
return err
}
}

// scan all controller
jobList, err := WalkScanJob(jobDir)
if err != nil {
return err
}

input, err := createRegisterJobInput(projectName, jobRegisterDir, jobList)
if err != nil {
return err
}

JobRegisterLogger.Debug("generate job", "path", input.OutputPath)
return generateFn(input, nil)
}

func createRegisterJobInput(projectName string, jobRegisterDir string, jobList []string) (input GenerateInput, err error) {
// set file path
filePath := filepath.Join(jobRegisterDir, JobRegisterFilename)

// set imports path
imports := []string{
fmt.Sprintf("%q", "github.com/sev-2/raiden"),
}

if len(jobList) > 0 {
rpcImportPath := fmt.Sprintf("%s/internal/jobs", utils.ToGoModuleName(projectName))
imports = append(imports, fmt.Sprintf("%q", rpcImportPath))
}

// set passed parameter
data := GenerateRegisterJobData{
Package: "bootstrap",
Imports: imports,
Jobs: jobList,
}

input = GenerateInput{
BindData: data,
Template: JobRegisterTemplate,
TemplateName: "jobRegisterTemplate",
OutputPath: filePath,
}

return
}

func WalkScanJob(jobDir string) ([]string, error) {
RpcRegisterLogger.Trace("scan all job", "path", jobDir)

job := make([]string, 0)
err := filepath.Walk(jobDir, func(path string, info fs.FileInfo, err error) error {
if strings.HasSuffix(path, ".go") {
RpcRegisterLogger.Trace("collect job", "path", path)
rs, e := getStructByBaseName(path, "JobBase")
if e != nil {
return e
}
job = append(job, rs...)
}
return nil
})
if err != nil {
return nil, err
}

return job, nil
}
1 change: 1 addition & 0 deletions pkg/generator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ func main() {
// register route
bootstrap.RegisterRoute(server)
bootstrap.RegisterJobs(server)
// run server
server.Run()
Expand Down
107 changes: 107 additions & 0 deletions schedule.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
package raiden

import (
"fmt"

"github.com/go-co-op/gocron/v2"
"github.com/google/uuid"
"github.com/sev-2/raiden/pkg/logger"
)

var SchedulerLogger = logger.HcLog().Named("raiden.scheduler")

// ----- Custom Type
type ScheduleStatus string

const (
ScheduleStatusOn ScheduleStatus = "on"
ScheduleStatusOff ScheduleStatus = "off"
)

// ----- Scheduler Base
type JobDuration = gocron.JobDefinition
type Job interface {
Name() string
Duration() JobDuration
After(cfg *Config, jobID uuid.UUID, jobName string)
AfterErr(cfg *Config, jobID uuid.UUID, jobName string, err error)
Before(cfg *Config, jobID uuid.UUID, jobName string)
Task(cfg *Config) error
}

type JobBase struct{}

func (j *JobBase) Duration() JobDuration {
return nil
}

func (j *JobBase) After(cfg *Config, jobID uuid.UUID, jobName string) {}

func (j *JobBase) AfterErr(cfg *Config, jobID uuid.UUID, jobName string, err error) {}

func (j *JobBase) Before(cfg *Config, jobID uuid.UUID, jobName string) {}

func (j *JobBase) Task(cfg *Config) error {
return nil
}

// ----- Scheduler server
func NewSchedulerServer(cfg *Config, options ...gocron.SchedulerOption) (*SchedulerServer, error) {
server, err := gocron.NewScheduler(options...)
if err != nil {
SchedulerLogger.Error(err.Error())
return nil, err
}

return &SchedulerServer{
Config: cfg,
Server: server,
}, nil

}

type SchedulerServer struct {
Config *Config
Server gocron.Scheduler
}

func (s *SchedulerServer) RegisterJob(job Job) error {
options := make([]gocron.JobOption, 0)

// setup job name
options = append(options, gocron.WithName(job.Name()))

// setup job event listener
options = append(options, gocron.WithEventListeners(
gocron.AfterJobRuns(func(jobID uuid.UUID, jobName string) {
job.After(s.Config, jobID, jobName)
}),
gocron.AfterJobRunsWithError(func(jobID uuid.UUID, jobName string, err error) {
job.AfterErr(s.Config, jobID, jobName, err)
}),
gocron.BeforeJobRuns(func(jobID uuid.UUID, jobName string) {
job.Before(s.Config, jobID, jobName)
}),
))

j, err := s.Server.NewJob(job.Duration(), gocron.NewTask(func() (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
}
}()
err = job.Task(s.Config)
return
}), options...)
if err != nil {
SchedulerLogger.Error("failed run job", "name", job.Name())
return err
}

SchedulerLogger.Info("start run job", "id", j.ID(), "name", j.Name())
return nil
}

// ----- TODO
// 1. make auto create `schedule_log` to save all job report
// 2. make function to record report job after running and save to database
Loading

0 comments on commit 68b2a40

Please sign in to comment.