2022-01-03 19:37:09 +03:00
|
|
|
package runners
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
2022-05-08 20:49:45 +03:00
|
|
|
// closedctx is an always closed context.
|
|
|
|
var closedctx = func() context.Context {
|
2023-02-06 11:08:22 +03:00
|
|
|
ctx := make(chan struct{})
|
2022-05-08 20:49:45 +03:00
|
|
|
close(ctx)
|
2023-02-06 11:08:22 +03:00
|
|
|
return CancelCtx(ctx)
|
2022-05-08 20:49:45 +03:00
|
|
|
}()
|
|
|
|
|
2023-01-06 13:16:09 +03:00
|
|
|
// Closed returns an always closed context.
|
|
|
|
func Closed() context.Context {
|
|
|
|
return closedctx
|
|
|
|
}
|
|
|
|
|
2023-02-06 11:08:22 +03:00
|
|
|
// CtxWithCancel returns a new context.Context impl with cancel.
|
|
|
|
func CtxWithCancel() (context.Context, context.CancelFunc) {
|
|
|
|
ctx := make(chan struct{})
|
|
|
|
cncl := func() { close(ctx) }
|
|
|
|
return CancelCtx(ctx), cncl
|
2022-01-03 19:37:09 +03:00
|
|
|
}
|
|
|
|
|
2023-02-06 11:08:22 +03:00
|
|
|
// CancelCtx is the simplest possible cancellable context.
|
|
|
|
type CancelCtx (<-chan struct{})
|
2022-01-03 19:37:09 +03:00
|
|
|
|
2023-02-06 11:08:22 +03:00
|
|
|
func (CancelCtx) Deadline() (time.Time, bool) {
|
2022-01-03 19:37:09 +03:00
|
|
|
return time.Time{}, false
|
|
|
|
}
|
|
|
|
|
2023-02-06 11:08:22 +03:00
|
|
|
func (ctx CancelCtx) Done() <-chan struct{} {
|
2022-01-03 19:37:09 +03:00
|
|
|
return ctx
|
|
|
|
}
|
|
|
|
|
2023-02-06 11:08:22 +03:00
|
|
|
func (ctx CancelCtx) Err() error {
|
2022-01-03 19:37:09 +03:00
|
|
|
select {
|
|
|
|
case <-ctx:
|
|
|
|
return context.Canceled
|
|
|
|
default:
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-02-06 11:08:22 +03:00
|
|
|
func (CancelCtx) Value(key interface{}) interface{} {
|
2022-01-03 19:37:09 +03:00
|
|
|
return nil
|
|
|
|
}
|
2023-01-06 13:16:09 +03:00
|
|
|
|
2023-02-06 11:08:22 +03:00
|
|
|
func (ctx CancelCtx) String() string {
|
2023-01-06 13:16:09 +03:00
|
|
|
var state string
|
|
|
|
select {
|
|
|
|
case <-ctx:
|
|
|
|
state = "closed"
|
|
|
|
default:
|
|
|
|
state = "open"
|
|
|
|
}
|
2023-02-06 11:08:22 +03:00
|
|
|
return "CancelCtx{state:" + state + "}"
|
2023-01-06 13:16:09 +03:00
|
|
|
}
|
|
|
|
|
2023-02-06 11:08:22 +03:00
|
|
|
func (ctx CancelCtx) GoString() string {
|
2023-01-06 13:16:09 +03:00
|
|
|
return "runners." + ctx.String()
|
|
|
|
}
|