Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement concurrency limit template #32

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add concurrency limit template.
  • Loading branch information
masim05 committed Jan 4, 2021
commit 90cfde63c87b24268e75e30a0c53535ee8b99467
46 changes: 46 additions & 0 deletions templates/concurrencylimit
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{{ $decorator := (or .Vars.DecoratorName (printf "%sWithConcurrencyLimit" .Interface.Name)) }}

import (
"time"
)

// {{$decorator}} implements {{.Interface.Type}}
type {{$decorator}} struct {
_base {{.Interface.Type}}
_burst chan int
}

// New{{$decorator}} instruments an implementation of the {{.Interface.Type}} with concurrency limiting
func New{{$decorator}}(base {{.Interface.Type}}, concurrentCalls int) *{{$decorator}} {
d := &{{$decorator}}{
_base: base,
_burst: make(chan int, concurrentCalls),
}

return d
}

{{range $method := .Interface.Methods}}
// {{$method.Name}} implements {{$.Interface.Type}}
func (_d *{{$decorator}}) {{$method.Declaration}} {

{{- if (and $method.AcceptsContext $method.ReturnsError)}}
select {
case <-ctx.Done():
err = ctx.Err()
return
case _d._burst<-1:
defer func() {
<-_d._burst
}()
}
{{else}}
_d._burst<-1
defer func() {
<-_d._burst
}()
{{end}}

{{ $method.Pass "_d._base." }}
}
{{end}}