Skip to content

Commit

Permalink
add semaphore for goroutine limitation in template
Browse files Browse the repository at this point in the history
  • Loading branch information
OldBigBuddha committed Nov 18, 2024
1 parent 15aa9c0 commit 1c3cb2b
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
2 changes: 1 addition & 1 deletion codegen/config/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ type ExecConfig struct {
FilenameTemplate string `yaml:"filename_template,omitempty"` // String template with {name} as placeholder for base name.
DirName string `yaml:"dir"`

WorkerLimit uint `yaml: "worker_limit"`
WorkerLimit uint `yaml:"worker_limit"`
}

type ExecLayout string
Expand Down
1 change: 1 addition & 0 deletions codegen/generated!.gotpl
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
{{ reserveImport "bytes" }}
{{ reserveImport "embed" }}

{{ reserveImport "golang.org/x/sync/semaphore"}}
{{ reserveImport "github.com/vektah/gqlparser/v2" "gqlparser" }}
{{ reserveImport "github.com/vektah/gqlparser/v2/ast" }}
{{ reserveImport "github.com/99designs/gqlgen/graphql" }}
Expand Down
22 changes: 20 additions & 2 deletions codegen/type.gotpl
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@
ret := make(graphql.Array, len(v))
{{- if not $type.IsScalar }}
var wg sync.WaitGroup
{{- if gt $.Config.Exec.WorkerLimit 0 }}
sm := semaphore.NewWeighted({{ $.Config.Exec.WorkerLimit }})
{{- end }}
isLen1 := len(v) == 1
if !isLen1 {
wg.Add(len(v))
Expand All @@ -124,14 +127,29 @@
}()
{{- end }}
if !isLen1 {
defer wg.Done()
{{- if gt $.Config.Exec.WorkerLimit 0 }}
defer func(){
sm.Release(1)
wg.Done()
}()
{{- else }}
defer wg.Done()
{{- end }}
}
ret[i] = ec.{{ $type.Elem.MarshalFunc }}(ctx, sel, v[i])
}
if isLen1 {
f(i)
} else {
go f(i)
{{- if gt $.Config.Exec.WorkerLimit 0 }}
if err := sm.Acquire(ctx, 1); err != nil {
ec.Error(ctx, ctx.Err())
} else {
go f(i)
}
{{- else }}
go f(i)
{{- end }}
}
{{ else }}
ret[i] = ec.{{ $type.Elem.MarshalFunc }}(ctx, sel, v[i])
Expand Down

0 comments on commit 1c3cb2b

Please sign in to comment.