chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
commit 7ec21f35b0
5767 files changed
+1436788

No files matched your search

+295
View File
@@ -0,0 +1,295 @@
// Package admission tracks operations in flight on a shared machine and on
// each session of it, so a rebuild, a reclaim, a rewind or a workspace delete
// can stop new work and wait for running work instead of cutting it off.
//
// Every user-mode operation holds a member in the machine scope and then in
// its session scope. A destructive path closes the scope it destroys, then
// requires ActiveExcept to report zero, and calls Barrier.Check before every
// destructive step. A lease that can no longer be confirmed reports Lost; the
// caller cancels the work it guards.
package admission
import (
"context"
"errors"
"strconv"
"sync"
"time"
)
var (
// ErrClosed reports that the scope is being rebuilt, reclaimed, or held
// exclusively.
ErrClosed = errors.New("sandbox: not admitting new operations")
// ErrLeaseLost reports a lease or barrier whose ownership can no longer
// be confirmed.
ErrLeaseLost = errors.New("sandbox: operation lease lost")
)
// DefaultHoldTTL bounds a holder that died without releasing.
const DefaultHoldTTL = 2 * time.Minute
// Scope names one admission domain. Tag is the machine digest, so every
// scope of a machine shares one Redis hash tag.
type Scope struct {
Tag string
Name string
}
// MachineScope covers every operation on a shared machine.
func MachineScope(digest string) Scope { return Scope{Tag: digest, Name: "machine"} }
// SessionScope covers one session's operations on its machine.
func SessionScope(digest, sessionID string) Scope {
return Scope{Tag: digest, Name: "session:" + sessionID}
}
// ConfigCreateScope registers provider creates of one sandbox config, so a
// config deletion can stop new creates and wait for running ones before it
// takes inventory.
func ConfigCreateScope(configTenantID uint64, configID string) Scope {
return Scope{Tag: "config:" + strconv.FormatUint(configTenantID, 10) + ":" + configID, Name: "create"}
}
// SessionMember names one operation of sessionID: kind is "turn", "shell",
// "file", "exec", "pty", "desktop", "fork" or "cleanup". token is unique per
// hold — including turns, which may nest — so releasing one hold never
// removes another.
func SessionMember(sessionID, kind, token string) string {
return "s:" + sessionID + ":" + kind + ":" + token
}
// Signal is the loss side of a lease or a barrier.
type Signal interface {
// Lost is closed once ownership can no longer be confirmed: the member
// is gone, or the local deadline passed without a confirmation.
Lost() <-chan struct{}
// Check returns ErrLeaseLost once Lost is closed or the deadline passed.
// Call it before every destructive step.
Check() error
}
// Lease is one registered operation.
type Lease interface {
Signal
Member() string
// Release removes the member. Idempotent.
Release()
}
// Barrier is an exclusive close of a scope.
type Barrier interface {
Signal
// Release reopens the scope. Idempotent, and exclusive with Seal:
// whichever runs first wins.
Release()
// Seal stops renewal and leaves the scope closed. It does not remove
// the closed flag, so new creates of this scope stay refused. Idempotent,
// and exclusive with Release.
Seal()
}
// Bind returns a context cancelled with ErrLeaseLost as soon as any of
// signals is lost, and a function that ends the watch and cancels the
// context. Pass the context to every provider call the signals protect, so a
// lost lease also stops the call in flight.
func Bind(ctx context.Context, signals ...Signal) (context.Context, func()) {
bound, cancel := context.WithCancelCause(ctx)
done := make(chan struct{})
for _, sig := range signals {
if sig == nil {
continue
}
if sig.Check() != nil {
cancel(ErrLeaseLost)
continue
}
lost := sig.Lost()
go func() {
select {
case <-lost:
cancel(ErrLeaseLost)
case <-done:
case <-bound.Done():
}
}()
}
var once sync.Once
return bound, func() {
once.Do(func() {
close(done)
cancel(nil)
})
}
}
// Registry is the admission contract. Implementations are safe for
// concurrent use.
type Registry interface {
Hold(ctx context.Context, scope Scope, member string, ttl time.Duration) (Lease, error)
ActiveExcept(ctx context.Context, scope Scope, except ...string) (int, error)
Close(ctx context.Context, scope Scope, ttl time.Duration) (Barrier, error)
}
// signal is the shared Lost/deadline/Release bookkeeping of leases and
// barriers. A zero deadline (the memory registry) never expires on its own.
type signal struct {
lost chan struct{}
lostOnce sync.Once
finishOnce sync.Once
release func()
// seal stops renewal without reopening. Nil on a memory barrier: the
// scope stays in the barrier map.
seal func()
mu sync.Mutex
deadline time.Time
timer *time.Timer
// stopped is set by Release. extend and the timer callback both refuse
// to arm another timer once it is set, so a confirmation that arrives
// as Release runs cannot resurrect the deadline.
stopped bool
}
func newSignal() *signal { return &signal{lost: make(chan struct{})} }
func (s *signal) markLost() {
s.mu.Lock()
s.closeLostLocked()
s.mu.Unlock()
}
func (s *signal) closeLostLocked() {
s.lostOnce.Do(func() { close(s.lost) })
}
func (s *signal) Lost() <-chan struct{} { return s.lost }
// extend moves the local deadline to sentAt+ttl-margin. sentAt is when the
// confirming request was sent: Redis may have applied it any time after, so
// counting from the reply would overstate how long the lease is still ours.
// A lost or released signal is never extended.
func (s *signal) extend(sentAt time.Time, ttl time.Duration) {
d := sentAt.Add(ttl - renewMargin(ttl))
s.mu.Lock()
defer s.mu.Unlock()
if s.stopped || s.lostClosed() {
return
}
if !s.deadline.IsZero() && !time.Now().Before(s.deadline) {
s.closeLostLocked()
return
}
if !d.After(s.deadline) {
return
}
s.deadline = d
s.armLocked(time.Until(d))
}
// armLocked schedules markLost at the deadline. A callback that wakes early,
// or one already in flight when the deadline moves, waits again instead of
// closing Lost. Go's AfterFunc Reset can run an already-started callback
// alongside the rescheduled one; the callback re-reads the deadline under
// s.mu so a stale wake cannot drop a lease that was just confirmed.
func (s *signal) armLocked(delay time.Duration) {
if s.timer != nil {
s.timer.Stop()
}
if delay <= 0 {
s.closeLostLocked()
return
}
s.timer = time.AfterFunc(delay, s.onDeadline)
}
func (s *signal) onDeadline() {
s.mu.Lock()
defer s.mu.Unlock()
if s.stopped || s.lostClosed() || s.deadline.IsZero() {
return
}
if delay := time.Until(s.deadline); delay > 0 {
// This wake is from an earlier deadline. Drop it and any timer it
// would race with, and wait out the deadline we hold now.
if s.timer != nil {
s.timer.Stop()
}
s.timer = time.AfterFunc(delay, s.onDeadline)
return
}
s.closeLostLocked()
}
func (s *signal) lostClosed() bool {
select {
case <-s.lost:
return true
default:
return false
}
}
func (s *signal) currentDeadline() time.Time {
s.mu.Lock()
defer s.mu.Unlock()
return s.deadline
}
func (s *signal) Release() { s.finish(true) }
// Seal stops the local deadline timer the same way Release does, so it
// cannot mark the barrier lost, and runs the non-reopening callback.
func (b *barrier) Seal() { b.finish(false) }
func (s *signal) finish(reopen bool) {
s.finishOnce.Do(func() {
s.mu.Lock()
s.stopped = true
if s.timer != nil {
s.timer.Stop()
s.timer = nil
}
s.mu.Unlock()
if reopen {
if s.release != nil {
s.release()
}
return
}
if s.seal != nil {
s.seal()
}
})
}
func (s *signal) Check() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.lostClosed() {
return ErrLeaseLost
}
// Release and Seal both stop the deadline. A stopped signal is not a
// loss, even if the old deadline has since passed.
if s.stopped {
return nil
}
if d := s.deadline; !d.IsZero() && !time.Now().Before(d) {
s.closeLostLocked()
return ErrLeaseLost
}
return nil
}
type lease struct {
*signal
member string
}
func (l *lease) Member() string { return l.member }
type barrier struct{ *signal }
// renewMargin is how long before expiry an unconfirmed lease is declared
// lost: the holder must stop before another replica can see it as gone.
func renewMargin(ttl time.Duration) time.Duration { return ttl / 6 }
@@ -0,0 +1,396 @@
package admission
import (
"context"
"strconv"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
)
const prefix = "academy:sandbox:user:"
func newRedis(t *testing.T) (*RedisRegistry, *miniredis.Miniredis) {
t.Helper()
mini := miniredis.RunT(t)
client := redis.NewClient(&redis.Options{Addr: mini.Addr()})
t.Cleanup(func() { _ = client.Close() })
return NewRedis(client, prefix), mini
}
func registries(t *testing.T) map[string]Registry {
r, _ := newRedis(t)
return map[string]Registry{"redis": r, "memory": NewMemory()}
}
func waitClosed(t *testing.T, ch <-chan struct{}) {
t.Helper()
select {
case <-ch:
case <-time.After(2 * time.Second):
t.Fatal("expected the lease to be reported lost")
}
}
func TestRegistryContract(t *testing.T) {
for name, reg := range registries(t) {
t.Run(name, func(t *testing.T) {
ctx := context.Background()
machine := MachineScope("d-1")
a := SessionMember("s1", "turn", "t1")
b := SessionMember("s1", "pty", "p1")
c := SessionMember("s2", "shell", "x1")
la, err := reg.Hold(ctx, machine, a, time.Minute)
require.NoError(t, err)
lb, err := reg.Hold(ctx, machine, b, time.Minute)
require.NoError(t, err)
lc, err := reg.Hold(ctx, machine, c, time.Minute)
require.NoError(t, err)
n, err := reg.ActiveExcept(ctx, machine)
require.NoError(t, err)
require.Equal(t, 3, n)
n, err = reg.ActiveExcept(ctx, machine, a)
require.NoError(t, err)
require.Equal(t, 2, n, "only the exact members passed are exempt; the same session's PTY still counts")
n, err = reg.ActiveExcept(ctx, SessionScope("d-1", "s1"))
require.NoError(t, err)
require.Zero(t, n, "scopes are independent")
barrier, err := reg.Close(ctx, machine, time.Minute)
require.NoError(t, err)
require.NoError(t, barrier.Check())
_, err = reg.Hold(ctx, machine, SessionMember("s3", "file", "f"), time.Minute)
require.ErrorIs(t, err, ErrClosed)
_, err = reg.Close(ctx, machine, time.Minute)
require.ErrorIs(t, err, ErrClosed, "a second closer backs off")
la.Release()
lb.Release()
lc.Release()
la.Release() // idempotent
n, err = reg.ActiveExcept(ctx, machine)
require.NoError(t, err)
require.Zero(t, n)
barrier.Release()
l, err := reg.Hold(ctx, machine, SessionMember("s3", "file", "f2"), time.Minute)
require.NoError(t, err)
require.Equal(t, SessionMember("s3", "file", "f2"), l.Member())
l.Release()
})
}
}
func TestRedisRenewNeverResurrectsAnExpiredMember(t *testing.T) {
reg, mini := newRedis(t)
ctx := context.Background()
scope := MachineScope("d-1")
lease, err := reg.Hold(ctx, scope, SessionMember("s", "shell", "1"), 300*time.Millisecond)
require.NoError(t, err)
defer lease.Release()
// Redis TIME jumps past the lease: the member has expired server-side.
mini.SetTime(time.Now().Add(time.Hour))
waitClosed(t, lease.Lost())
// The renew loop ticks every ttl/3. Wait past one more tick so a loop
// that re-added the member after declaring it lost cannot hide.
time.Sleep(200 * time.Millisecond)
n, err := reg.ActiveExcept(ctx, scope)
require.NoError(t, err)
require.Zero(t, n, "an expired member must not be re-registered by its renew loop")
}
func TestRedisLeaseIsLostWhenRedisIsUnreachable(t *testing.T) {
reg, mini := newRedis(t)
lease, err := reg.Hold(
context.Background(), MachineScope("d-1"), SessionMember("s", "shell", "1"), 300*time.Millisecond,
)
require.NoError(t, err)
defer lease.Release()
mini.Close()
waitClosed(t, lease.Lost())
}
// stallHook makes every command hang until its context ends, the way a
// Redis behind a partition does.
type stallHook struct{ stall *atomic.Bool }
func (h stallHook) DialHook(next redis.DialHook) redis.DialHook { return next }
func (h stallHook) ProcessHook(next redis.ProcessHook) redis.ProcessHook {
return func(ctx context.Context, cmd redis.Cmder) error {
if h.stall.Load() {
<-ctx.Done()
return ctx.Err()
}
return next(ctx, cmd)
}
}
func (h stallHook) ProcessPipelineHook(next redis.ProcessPipelineHook) redis.ProcessPipelineHook {
return next
}
func newStallingRedis(t *testing.T) (*RedisRegistry, *atomic.Bool) {
t.Helper()
mini := miniredis.RunT(t)
client := redis.NewClient(&redis.Options{Addr: mini.Addr()})
t.Cleanup(func() { _ = client.Close() })
stall := &atomic.Bool{}
client.AddHook(stallHook{stall: stall})
return NewRedis(client, prefix), stall
}
func TestRedisLeaseIsLostAtItsLocalDeadlineWhileRenewStalls(t *testing.T) {
reg, stall := newStallingRedis(t)
ttl := 600 * time.Millisecond
lease, err := reg.Hold(context.Background(), MachineScope("d-1"), SessionMember("s", "shell", "1"), ttl)
require.NoError(t, err)
defer lease.Release()
stall.Store(true)
stalledAt := time.Now()
waitClosed(t, lease.Lost())
// The last confirmed request was sent before stalledAt, so the deadline
// is at most ttl-ttl/6 after it. Losing it only at Redis expiry (ttl) or
// after the hung call returns would let another replica act first.
require.Less(t, time.Since(stalledAt), ttl)
require.ErrorIs(t, lease.Check(), ErrLeaseLost)
}
func TestRedisBarrierIsLostAtItsLocalDeadlineWhileRenewStalls(t *testing.T) {
reg, stall := newStallingRedis(t)
ttl := 600 * time.Millisecond
barrier, err := reg.Close(context.Background(), MachineScope("d-1"), ttl)
require.NoError(t, err)
defer barrier.Release()
stall.Store(true)
stalledAt := time.Now()
waitClosed(t, barrier.Lost())
require.Less(t, time.Since(stalledAt), ttl)
require.ErrorIs(t, barrier.Check(), ErrLeaseLost)
}
func TestBindCancelsWhenAnySignalIsLost(t *testing.T) {
reg := NewMemory()
ctx := context.Background()
lease, err := reg.Hold(ctx, MachineScope("d"), SessionMember("s", "shell", "1"), time.Minute)
require.NoError(t, err)
barrier, err := reg.Close(ctx, SessionScope("d", "s"), time.Minute)
require.NoError(t, err)
bound, stop := Bind(ctx, lease, barrier)
defer stop()
require.NoError(t, bound.Err())
reg.LoseBarrier(SessionScope("d", "s"))
waitClosed(t, bound.Done())
require.ErrorIs(t, context.Cause(bound), ErrLeaseLost)
again, stopAgain := Bind(ctx, lease)
stopAgain()
require.ErrorIs(t, again.Err(), context.Canceled, "stop ends the watch and the context")
require.NotErrorIs(t, context.Cause(again), ErrLeaseLost, "stop is not a loss")
}
func TestBindOnAnAlreadyLostSignalIsCancelledAtOnce(t *testing.T) {
reg := NewMemory()
scope := MachineScope("d")
member := SessionMember("s", "shell", "1")
lease, err := reg.Hold(context.Background(), scope, member, time.Minute)
require.NoError(t, err)
reg.ExpireMember(scope, member)
bound, stop := Bind(context.Background(), lease)
defer stop()
require.ErrorIs(t, context.Cause(bound), ErrLeaseLost)
}
func TestRedisBarrierRenewsAndReportsLoss(t *testing.T) {
reg, mini := newRedis(t)
ctx := context.Background()
scope := MachineScope("d-1")
barrier, err := reg.Close(ctx, scope, 300*time.Millisecond)
require.NoError(t, err)
defer barrier.Release()
// miniredis ages key TTLs only when FastForward is called, not during a
// wall-clock sleep. Leave a short remainder of the initial TTL, wait for
// a renew to PEXPIRE the key back to a full TTL, then jump farther than
// that remainder. Without a renew the key is gone.
mini.FastForward(250 * time.Millisecond)
time.Sleep(250 * time.Millisecond) // renew interval is ttl/3 = 100ms
mini.FastForward(100 * time.Millisecond)
require.True(t, mini.Exists(prefix+"{d-1}:machine:closed"), "the barrier outlives its initial TTL while held")
require.NoError(t, barrier.Check())
mini.Del(prefix + "{d-1}:machine:closed")
waitClosed(t, barrier.Lost())
require.ErrorIs(t, barrier.Check(), ErrLeaseLost)
}
func TestRedisKeysShareTheMachineHashTag(t *testing.T) {
reg, mini := newRedis(t)
l, err := reg.Hold(context.Background(), SessionScope("abc", "s1"), SessionMember("s1", "x", "1"), time.Minute)
require.NoError(t, err)
defer l.Release()
require.True(t, mini.Exists(prefix+"{abc}:session:s1:ops"))
}
func TestMemoryHooksSimulateLoss(t *testing.T) {
reg := NewMemory()
ctx := context.Background()
scope := MachineScope("d")
member := SessionMember("s", "shell", "1")
lease, err := reg.Hold(ctx, scope, member, time.Minute)
require.NoError(t, err)
reg.ExpireMember(scope, member)
waitClosed(t, lease.Lost())
n, _ := reg.ActiveExcept(ctx, scope)
require.Zero(t, n)
barrier, err := reg.Close(ctx, scope, time.Minute)
require.NoError(t, err)
reg.LoseBarrier(scope)
waitClosed(t, barrier.Lost())
require.ErrorIs(t, barrier.Check(), ErrLeaseLost)
}
func TestReleaseIsIdempotentAndIsNotLoss(t *testing.T) {
for name, reg := range registries(t) {
t.Run(name, func(t *testing.T) {
ctx := context.Background()
scope := MachineScope("d")
lease, err := reg.Hold(ctx, scope, SessionMember("s", "shell", "1"), time.Minute)
require.NoError(t, err)
lease.Release()
lease.Release()
select {
case <-lease.Lost():
t.Fatal("release must not report the lease lost")
default:
}
require.NoError(t, lease.Check())
n, err := reg.ActiveExcept(ctx, scope)
require.NoError(t, err)
require.Zero(t, n)
barrier, err := reg.Close(ctx, scope, time.Minute)
require.NoError(t, err)
barrier.Release()
barrier.Release()
select {
case <-barrier.Lost():
t.Fatal("release must not report the barrier lost")
default:
}
require.NoError(t, barrier.Check())
again, err := reg.Hold(ctx, scope, SessionMember("s", "shell", "2"), time.Minute)
require.NoError(t, err)
again.Release()
})
}
}
func TestConcurrentHoldAndRelease(t *testing.T) {
for name, reg := range registries(t) {
t.Run(name, func(t *testing.T) {
ctx := context.Background()
scope := MachineScope("d-conc")
var wg sync.WaitGroup
for i := 0; i < 8; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
member := SessionMember("s", "shell", strconv.Itoa(i))
for n := 0; n < 15; n++ {
lease, err := reg.Hold(ctx, scope, member, time.Minute)
if err != nil {
t.Errorf("hold: %v", err)
return
}
if _, err := reg.ActiveExcept(ctx, scope, member); err != nil {
t.Errorf("count: %v", err)
}
lease.Release()
lease.Release()
}
}(i)
}
wg.Wait()
n, err := reg.ActiveExcept(ctx, scope)
require.NoError(t, err)
require.Zero(t, n)
})
}
}
// A short hold must not cut the key's lifetime below a longer member's
// deadline: once the key expires, ActiveExcept would see an idle machine while
// the long operation is still running.
func TestRedisShortHoldNeverShortensALongerLease(t *testing.T) {
reg, mini := newRedis(t)
ctx := context.Background()
scope := MachineScope("d-ttl")
long, err := reg.Hold(ctx, scope, SessionMember("a", "turn", "1"), 30*time.Minute)
require.NoError(t, err)
defer long.Release()
short, err := reg.Hold(ctx, scope, SessionMember("b", "shell", "1"), 2*time.Minute)
require.NoError(t, err)
short.Release()
ops := reg.key(scope, "ops")
require.GreaterOrEqual(t, mini.TTL(ops), 30*time.Minute, "the key outlives its longest member")
mini.FastForward(5 * time.Minute)
n, err := reg.ActiveExcept(ctx, scope)
require.NoError(t, err)
require.Equal(t, 1, n, "the long lease is still registered")
}
func TestSealKeepsTheScopeClosedWithoutReportingLoss(t *testing.T) {
ctx := context.Background()
scope := ConfigCreateScope(7, "cfg-a")
t.Run("memory", func(t *testing.T) {
reg := NewMemory()
barrier, err := reg.Close(ctx, scope, time.Minute)
require.NoError(t, err)
barrier.Seal()
barrier.Seal()
_, err = reg.Hold(ctx, scope, "create:again", time.Minute)
require.ErrorIs(t, err, ErrClosed)
_, err = reg.Close(ctx, scope, time.Minute)
require.ErrorIs(t, err, ErrClosed)
select {
case <-barrier.Lost():
t.Fatal("seal must not report the barrier lost")
default:
}
require.NoError(t, barrier.Check())
})
t.Run("redis", func(t *testing.T) {
reg, mini := newRedis(t)
barrier, err := reg.Close(ctx, scope, 300*time.Millisecond)
require.NoError(t, err)
barrier.Seal()
time.Sleep(400 * time.Millisecond)
mini.FastForward(time.Second)
key := prefix + "{config:7:cfg-a}:create:closed"
require.True(t, mini.Exists(key), "seal persists the closed flag past its TTL")
require.Equal(t, time.Duration(0), mini.TTL(key))
_, err = reg.Hold(ctx, scope, "create:again", time.Minute)
require.ErrorIs(t, err, ErrClosed)
select {
case <-barrier.Lost():
t.Fatal("seal must not report the barrier lost")
default:
}
require.NoError(t, barrier.Check())
})
}
+122
View File
@@ -0,0 +1,122 @@
package admission
import (
"context"
"sync"
"time"
)
// MemoryRegistry is a process-local Registry for tests and single-process
// deployments. User mode is never enabled without Redis, so multi-replica
// production never uses it. Leases never expire on their own; tests force
// loss with ExpireMember and LoseBarrier.
type MemoryRegistry struct {
mu sync.Mutex
members map[Scope]map[string]*lease
barriers map[Scope]*barrier
}
// NewMemory builds an empty registry.
func NewMemory() *MemoryRegistry {
return &MemoryRegistry{members: map[Scope]map[string]*lease{}, barriers: map[Scope]*barrier{}}
}
// Hold registers member until Release. The memory registry does not expire on its own.
func (r *MemoryRegistry) Hold(_ context.Context, scope Scope, member string, _ time.Duration) (Lease, error) {
r.mu.Lock()
defer r.mu.Unlock()
if _, closed := r.barriers[scope]; closed {
return nil, ErrClosed
}
set := r.members[scope]
if set == nil {
set = map[string]*lease{}
r.members[scope] = set
}
l := &lease{signal: newSignal(), member: member}
l.release = func() {
r.mu.Lock()
defer r.mu.Unlock()
if r.members[scope][member] == l {
delete(r.members[scope], member)
}
}
set[member] = l
return l, nil
}
// ActiveExcept counts members of scope other than except.
func (r *MemoryRegistry) ActiveExcept(_ context.Context, scope Scope, except ...string) (int, error) {
r.mu.Lock()
defer r.mu.Unlock()
skip := make(map[string]struct{}, len(except))
for _, m := range except {
skip[m] = struct{}{}
}
n := 0
for m := range r.members[scope] {
if _, ok := skip[m]; !ok {
n++
}
}
return n, nil
}
// Close stops new holds on scope until the barrier is released.
func (r *MemoryRegistry) Close(_ context.Context, scope Scope, _ time.Duration) (Barrier, error) {
r.mu.Lock()
defer r.mu.Unlock()
if _, closed := r.barriers[scope]; closed {
return nil, ErrClosed
}
b := &barrier{signal: newSignal()}
b.release = func() {
r.mu.Lock()
defer r.mu.Unlock()
if r.barriers[scope] == b {
delete(r.barriers, scope)
}
}
r.barriers[scope] = b
return b, nil
}
// ExpireScope marks every member of scope lost. Tests use it when the
// member token is chosen inside the call under test.
func (r *MemoryRegistry) ExpireScope(scope Scope) {
r.mu.Lock()
set := r.members[scope]
delete(r.members, scope)
lost := make([]*lease, 0, len(set))
for _, l := range set {
lost = append(lost, l)
}
r.mu.Unlock()
for _, l := range lost {
l.markLost()
}
}
// ExpireMember simulates a lease that expired server-side.
func (r *MemoryRegistry) ExpireMember(scope Scope, member string) {
r.mu.Lock()
l := r.members[scope][member]
delete(r.members[scope], member)
r.mu.Unlock()
if l != nil {
l.markLost()
}
}
// LoseBarrier simulates a barrier whose ownership could not be renewed.
func (r *MemoryRegistry) LoseBarrier(scope Scope) {
r.mu.Lock()
b := r.barriers[scope]
delete(r.barriers, scope)
r.mu.Unlock()
if b != nil {
b.markLost()
}
}
var _ Registry = (*MemoryRegistry)(nil)
+214
View File
@@ -0,0 +1,214 @@
package admission
import (
"context"
"fmt"
"strings"
"time"
"academy/internal/common/redislock"
"github.com/redis/go-redis/v9"
)
const redisNowLua = "local t = redis.call('TIME'); " +
"local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)"
// KEYS[1] ops zset, KEYS[2] closed flag. ARGV[1] member, ARGV[2] ttl ms.
var holdScript = redis.NewScript(redisNowLua + `
if redis.call('EXISTS', KEYS[2]) == 1 then return redis.error_reply('ERR_SCOPE_CLOSED') end
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now)
redis.call('ZADD', KEYS[1], now + tonumber(ARGV[2]), ARGV[1])
-- The zset holds every member's lease; only ever extend its lifetime, or a
-- short hold would expire the key under a longer, still-live member.
local keep = tonumber(ARGV[2]) * 2
if redis.call('PTTL', KEYS[1]) < keep then redis.call('PEXPIRE', KEYS[1], keep) end
return 1
`)
// Renewal only extends a member that is still live. An expired member is
// removed and reported lost: another replica may already have acted on its
// absence, so it must never come back. Renewing while the scope is closed is
// allowed — it protects work the closer is waiting for.
var renewScript = redis.NewScript(redisNowLua + `
local score = redis.call('ZSCORE', KEYS[1], ARGV[1])
if (not score) or tonumber(score) <= now then
redis.call('ZREM', KEYS[1], ARGV[1])
return 0
end
redis.call('ZADD', KEYS[1], 'XX', now + tonumber(ARGV[2]), ARGV[1])
-- The zset holds every member's lease; only ever extend its lifetime, or a
-- short hold would expire the key under a longer, still-live member.
local keep = tonumber(ARGV[2]) * 2
if redis.call('PTTL', KEYS[1]) < keep then redis.call('PEXPIRE', KEYS[1], keep) end
return 1
`)
// ARGV: exempt members.
var activeExceptScript = redis.NewScript(redisNowLua + `
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now)
local members = redis.call('ZRANGEBYSCORE', KEYS[1], now, '+inf')
local skip = {}
for i = 1, #ARGV do skip[ARGV[i]] = true end
local n = 0
for _, m in ipairs(members) do
if not skip[m] then n = n + 1 end
end
return n
`)
// RedisRegistry is the distributed admission registry.
type RedisRegistry struct {
client redis.UniversalClient
prefix string
}
// NewRedis builds a registry whose keys start with keyPrefix, e.g.
// "academy:sandbox:user:", matching the user binding keys.
func NewRedis(client redis.UniversalClient, keyPrefix string) *RedisRegistry {
return &RedisRegistry{client: client, prefix: keyPrefix}
}
func (r *RedisRegistry) key(scope Scope, suffix string) string {
return r.prefix + "{" + scope.Tag + "}:" + scope.Name + ":" + suffix
}
// Hold registers member until Release or until the lease can no longer be renewed.
func (r *RedisRegistry) Hold(ctx context.Context, scope Scope, member string, ttl time.Duration) (Lease, error) {
if ttl <= 0 {
ttl = DefaultHoldTTL
}
ops, closed := r.key(scope, "ops"), r.key(scope, "closed")
sent := time.Now()
if err := holdScript.Run(ctx, r.client, []string{ops, closed}, member, ttl.Milliseconds()).Err(); err != nil {
if strings.Contains(err.Error(), "ERR_SCOPE_CLOSED") {
return nil, ErrClosed
}
return nil, fmt.Errorf("admission: hold %s: %w", member, err)
}
l := &lease{signal: newSignal(), member: member}
l.extend(sent, ttl)
renewCtx, stop := context.WithCancel(context.WithoutCancel(ctx))
l.release = func() {
stop()
relCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = r.client.ZRem(relCtx, ops, member).Err()
}
go r.renewLease(renewCtx, l, ops, ttl)
return l, nil
}
// renewLease confirms the lease every ttl/3. Each request is bounded by the
// local deadline; a failed or hung renewal leaves the deadline where it was,
// and the deadline timer reports the loss on time.
func (r *RedisRegistry) renewLease(ctx context.Context, l *lease, ops string, ttl time.Duration) {
ticker := time.NewTicker(renewInterval(ttl))
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-l.Lost():
return
case <-ticker.C:
sent := time.Now()
callCtx, cancel := context.WithDeadline(ctx, l.currentDeadline())
n, err := renewScript.Run(callCtx, r.client, []string{ops}, l.member, ttl.Milliseconds()).Int()
cancel()
switch {
case err == nil && n == 1:
l.extend(sent, ttl)
case err == nil:
l.markLost()
return
}
}
}
}
// ActiveExcept counts members of scope other than except.
func (r *RedisRegistry) ActiveExcept(ctx context.Context, scope Scope, except ...string) (int, error) {
args := make([]any, len(except))
for i, m := range except {
args[i] = m
}
n, err := activeExceptScript.Run(ctx, r.client, []string{r.key(scope, "ops")}, args...).Int()
if err != nil {
return 0, fmt.Errorf("admission: count %s/%s: %w", scope.Tag, scope.Name, err)
}
return n, nil
}
// Close stops new holds on scope until the barrier is released.
func (r *RedisRegistry) Close(ctx context.Context, scope Scope, ttl time.Duration) (Barrier, error) {
token, err := redislock.NewToken()
if err != nil {
return nil, err
}
key := r.key(scope, "closed")
sent := time.Now()
ok, err := redislock.TryAcquire(ctx, r.client, key, token, ttl)
if err != nil {
return nil, fmt.Errorf("admission: close %s/%s: %w", scope.Tag, scope.Name, err)
}
if !ok {
return nil, ErrClosed
}
b := &barrier{signal: newSignal()}
b.extend(sent, ttl)
renewCtx, stop := context.WithCancel(context.WithoutCancel(ctx))
renewDone := make(chan struct{})
go func() {
defer close(renewDone)
ticker := time.NewTicker(renewInterval(ttl))
defer ticker.Stop()
for {
select {
case <-renewCtx.Done():
return
case <-b.Lost():
return
case <-ticker.C:
sent := time.Now()
callCtx, cancel := context.WithDeadline(renewCtx, b.currentDeadline())
renewed, err := redislock.Renew(callCtx, r.client, key, token, ttl)
cancel()
switch {
case err == nil && renewed:
b.extend(sent, ttl)
case err == nil:
b.markLost()
return
}
}
}
}()
// Wait for the renewal goroutine to leave before touching the key, so a
// PEXPIRE cannot land after PERSIST and put the TTL back.
finishKey := func(persist bool) {
stop()
<-renewDone
relCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if persist {
_ = r.client.Persist(relCtx, key).Err()
return
}
_, _ = redislock.Release(relCtx, r.client, key, token)
}
b.release = func() { finishKey(false) }
b.seal = func() { finishKey(true) }
return b, nil
}
// renewInterval is how often a holder reconfirms. It stays inside the
// deadline (ttl - ttl/6) so one hung renewal still loses the lease on time.
func renewInterval(ttl time.Duration) time.Duration {
every := ttl / 3
if every <= 0 {
return time.Millisecond
}
return every
}
var _ Registry = (*RedisRegistry)(nil)
@@ -0,0 +1,139 @@
package admission_test
import (
"os"
"strings"
"testing"
"time"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"github.com/stretchr/testify/require"
"academy/internal/sandbox/admission"
)
// integrationEnv returns an integration dependency's address. Missing, the
// test is skipped — unless ACADEMY_REQUIRE_INTEGRATION=1, which turns the
// skip into a failure so an enablement run cannot pass by skipping.
func integrationEnv(t *testing.T, name string) string {
t.Helper()
v := strings.TrimSpace(os.Getenv(name))
if v != "" {
return v
}
if os.Getenv("ACADEMY_REQUIRE_INTEGRATION") == "1" {
t.Fatalf("%s is required when ACADEMY_REQUIRE_INTEGRATION=1", name)
}
t.Skipf("set %s to run against a real dependency", name)
return ""
}
// realRedisPair dials ACADEMY_TEST_REDIS_ADDR twice. prefix isolates this run.
func realRedisPair(t *testing.T) (c1, c2 *admission.RedisRegistry, raw *redis.Client, prefix string) {
t.Helper()
addr := integrationEnv(t, "ACADEMY_TEST_REDIS_ADDR")
prefix = "it-" + uuid.NewString() + ":"
open := func() *redis.Client {
rc := redis.NewClient(&redis.Options{Addr: addr})
t.Cleanup(func() { _ = rc.Close() })
return rc
}
left, right := open(), open()
raw = open()
return admission.NewRedis(left, prefix), admission.NewRedis(right, prefix), raw, prefix
}
// redisKey is RedisRegistry's key layout. The method is unexported; the
// integration test builds the same string so it can inject faults.
func redisKey(prefix string, scope admission.Scope, suffix string) string {
return prefix + "{" + scope.Tag + "}:" + scope.Name + ":" + suffix
}
func TestRedisRealTwoClientsShareAdmission(t *testing.T) {
c1, c2, _, _ := realRedisPair(t)
ctx := t.Context()
scope := admission.MachineScope("d-" + uuid.NewString())
member := "s:a:pty:1"
lease, err := c1.Hold(ctx, scope, member, time.Minute)
require.NoError(t, err)
defer lease.Release()
barrier, err := c2.Close(ctx, scope, time.Minute)
require.NoError(t, err)
defer barrier.Release()
n, err := c2.ActiveExcept(ctx, scope)
require.NoError(t, err)
require.Equal(t, 1, n)
lease.Release()
n, err = c2.ActiveExcept(ctx, scope)
require.NoError(t, err)
require.Zero(t, n)
_, err = c1.Hold(ctx, scope, "s:a:pty:2", time.Minute)
require.ErrorIs(t, err, admission.ErrClosed)
barrier.Release()
again, err := c1.Hold(ctx, scope, "s:a:pty:3", time.Minute)
require.NoError(t, err)
again.Release()
}
func TestRedisRealBarrierIsRenewedAndLossIsReported(t *testing.T) {
c1, c2, raw, prefix := realRedisPair(t)
ctx := t.Context()
scope := admission.MachineScope("d-" + uuid.NewString())
ttl := 2 * time.Second
barrier, err := c2.Close(ctx, scope, ttl)
require.NoError(t, err)
defer barrier.Release()
time.Sleep(3 * time.Second)
require.NoError(t, barrier.Check(), "a held barrier is renewed past its initial TTL")
closedKey := redisKey(prefix, scope, "closed")
require.NoError(t, raw.Del(ctx, closedKey).Err())
select {
case <-barrier.Lost():
require.ErrorIs(t, barrier.Check(), admission.ErrLeaseLost)
case <-time.After(ttl):
t.Fatal("the barrier kept reporting ownership after its key was deleted")
}
again, err := c1.Close(ctx, scope, time.Minute)
require.NoError(t, err, "a lost barrier does not keep the scope closed")
again.Release()
}
func TestRedisRealLostMemberIsNotResurrected(t *testing.T) {
c1, _, raw, prefix := realRedisPair(t)
ctx := t.Context()
scope := admission.MachineScope("d-" + uuid.NewString())
member := admission.SessionMember("s", "shell", "1")
ttl := 2 * time.Second
lease, err := c1.Hold(ctx, scope, member, ttl)
require.NoError(t, err)
defer lease.Release()
opsKey := redisKey(prefix, scope, "ops")
require.NoError(t, raw.ZRem(ctx, opsKey, member).Err())
// Renewal ticks every ttl/3. Wait past one tick, and past the ttl/6
// margin, so a loop that put the member back would be visible.
select {
case <-lease.Lost():
case <-time.After(ttl):
t.Fatal("a removed member was not reported lost")
}
time.Sleep(ttl/3 + 100*time.Millisecond)
_, err = raw.ZScore(ctx, opsKey, member).Result()
require.ErrorIs(t, err, redis.Nil, "renewal must not resurrect a removed member")
require.ErrorIs(t, lease.Check(), admission.ErrLeaseLost)
}