k3s/vendor/github.com/rancher/lasso/pkg/controller/transaction.go

60 lines
915 B
Go
Raw Normal View History

package controller
2020-03-26 21:07:15 +00:00
import (
"context"
"sync"
2020-03-26 21:07:15 +00:00
)
type hTransactionKey struct{}
type HandlerTransaction struct {
context.Context
lock sync.Mutex
2020-03-26 21:07:15 +00:00
parent context.Context
todo []func()
2020-03-26 21:07:15 +00:00
}
func (h *HandlerTransaction) do(f func()) {
if h == nil {
f()
return
2020-03-26 21:07:15 +00:00
}
h.lock.Lock()
defer h.lock.Unlock()
h.todo = append(h.todo, f)
2020-03-26 21:07:15 +00:00
}
func (h *HandlerTransaction) Commit() {
h.lock.Lock()
fs := h.todo
h.todo = nil
h.lock.Unlock()
for _, f := range fs {
f()
}
2020-03-26 21:07:15 +00:00
}
func (h *HandlerTransaction) Rollback() {
h.lock.Lock()
h.todo = nil
h.lock.Unlock()
2020-03-26 21:07:15 +00:00
}
func NewHandlerTransaction(ctx context.Context) *HandlerTransaction {
ht := &HandlerTransaction{
parent: ctx,
}
ctx = context.WithValue(ctx, hTransactionKey{}, ht)
ht.Context = ctx
return ht
}
func getHandlerTransaction(ctx context.Context) *HandlerTransaction {
v, _ := ctx.Value(hTransactionKey{}).(*HandlerTransaction)
return v
}