|
| 1 | +package xcontext |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "sync" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/ydb-platform/ydb-go-sdk/v3/internal/xerrors" |
| 10 | +) |
| 11 | + |
| 12 | +var errCancelWithNilError = cancelError{err: errors.New("cancel context with nil error")} |
| 13 | + |
| 14 | +// CancelErrFunc use for cancel with wrap with specific error |
| 15 | +// if err == nil CancelErrFunc will panic for prevent |
| 16 | +// call cancel, then ctx.Err() == nil |
| 17 | +type CancelErrFunc func(err error) |
| 18 | + |
| 19 | +func WithErrCancel(ctx context.Context) (resCtx context.Context, cancel CancelErrFunc) { |
| 20 | + res := &ctxError{} |
| 21 | + res.ctx, res.ctxCancel = context.WithCancel(ctx) |
| 22 | + return res, res.cancel |
| 23 | +} |
| 24 | + |
| 25 | +type ctxError struct { |
| 26 | + ctx context.Context |
| 27 | + ctxCancel context.CancelFunc |
| 28 | + |
| 29 | + m sync.Mutex |
| 30 | + err error |
| 31 | +} |
| 32 | + |
| 33 | +func (c *ctxError) Deadline() (deadline time.Time, ok bool) { |
| 34 | + return c.ctx.Deadline() |
| 35 | +} |
| 36 | + |
| 37 | +func (c *ctxError) Done() <-chan struct{} { |
| 38 | + return c.ctx.Done() |
| 39 | +} |
| 40 | + |
| 41 | +func (c *ctxError) Err() error { |
| 42 | + c.m.Lock() |
| 43 | + defer c.m.Unlock() |
| 44 | + |
| 45 | + return c.errUnderLock() |
| 46 | +} |
| 47 | + |
| 48 | +func (c *ctxError) errUnderLock() error { |
| 49 | + if c.err == nil { |
| 50 | + c.err = c.ctx.Err() |
| 51 | + } |
| 52 | + |
| 53 | + return c.err |
| 54 | +} |
| 55 | + |
| 56 | +func (c *ctxError) Value(key interface{}) interface{} { |
| 57 | + return c.ctx.Value(key) |
| 58 | +} |
| 59 | + |
| 60 | +func (c *ctxError) cancel(err error) { |
| 61 | + c.m.Lock() |
| 62 | + defer c.m.Unlock() |
| 63 | + |
| 64 | + if err == nil { |
| 65 | + err = xerrors.WithStackTrace(errCancelWithNilError) |
| 66 | + } |
| 67 | + |
| 68 | + if c.errUnderLock() == nil { |
| 69 | + err = cancelError{err: err} |
| 70 | + c.err = err |
| 71 | + } |
| 72 | + |
| 73 | + c.ctxCancel() |
| 74 | +} |
| 75 | + |
| 76 | +type cancelError struct { |
| 77 | + err error |
| 78 | +} |
| 79 | + |
| 80 | +func (e cancelError) Error() string { |
| 81 | + return e.err.Error() |
| 82 | +} |
| 83 | + |
| 84 | +func (e cancelError) Is(target error) bool { |
| 85 | + return errors.Is(e.err, target) || errors.Is(context.Canceled, target) |
| 86 | +} |
| 87 | + |
| 88 | +func (e cancelError) As(target interface{}) bool { |
| 89 | + return errors.As(e.err, target) || errors.As(context.Canceled, target) |
| 90 | +} |
| 91 | + |
| 92 | +func (e cancelError) Unwrap() error { |
| 93 | + return e.err |
| 94 | +} |
0 commit comments