Skip to content
Merged
4 changes: 3 additions & 1 deletion acceleration/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2392,7 +2392,9 @@ window the replacement already has taking the forgotten one's spend), and again
database their own policy and user-level limits, deleted, so the app's defaults apply, and the
id on their resets, grants and campaigns. Usage and cost stay under the app. It writes one
`end_user` audit row naming the replacement and the actor, never the id, and the service one
`forget_user` row per organization. `--dry-run` prints the counts and changes nothing. Every
`forget_user` row per organization. `--dry-run` prints the counts and changes nothing. Once the
last step, the shared database's, has started, it completes even if the command is interrupted,
and the command drops the user's cached policy from every router before it exits. Every
step only touches what still names the id, so it is safe to repeat: to finish a run that
stopped, pass the replacement it printed as `--replacement`, and the rest is rewritten under
that one replacement, with the run's own audit row. Sessions, conversation history and
Expand Down
165 changes: 165 additions & 0 deletions acceleration/cmd/router/forget_close_integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
//go:build integration

package main

import (
"bytes"
"encoding/binary"
"io"
"net"
"net/url"
"sync"
"time"

"github.com/GetStream/Vision-Agents/acceleration/internal/store"
)

// commitHolder stands in front of a Postgres and holds, on the first connection that deletes
// a policy, the COMMIT after that delete until let. gaveUp is closed once the client drops that
// connection, as pgdriver does when its read times out.
type commitHolder struct {
listener net.Listener
target string
release chan struct{}
gaveUp chan struct{}
once sync.Once
letOnce sync.Once
}

// holdingCommit puts a commitHolder in front of the shared database and answers the DSN that
// reaches it, whose reads give up after a second.
func (s *ForgetUserSuite) holdingCommit() (*commitHolder, string) {
target, err := url.Parse(s.settings.Postgres.DSN)
s.Require().NoError(err)
listener, err := net.Listen("tcp", "127.0.0.1:0")
s.Require().NoError(err)
holder := &commitHolder{listener: listener, target: target.Host, release: make(chan struct{}), gaveUp: make(chan struct{})}
s.T().Cleanup(func() {
_ = listener.Close()
holder.let()
})
go holder.serve()
target.Host = listener.Addr().String()
query := target.Query()
query.Set("read_timeout", "1s")
target.RawQuery = query.Encode()
return holder, target.String()
}

func (h *commitHolder) let() { h.letOnce.Do(func() { close(h.release) }) }

func (h *commitHolder) serve() {
for {
conn, err := h.listener.Accept()
if err != nil {
return
}
upstream, err := net.Dial("tcp", h.target)
if err != nil {
_ = conn.Close()
continue
}
go func() {
defer func() { _ = upstream.Close() }()
h.toServer(conn, upstream)
}()
go func() {
defer func() { _ = conn.Close() }()
_, _ = io.Copy(conn, upstream)
}()
}
}

// toServer forwards a client's startup message and then its typed messages, holding the
// COMMIT that follows a delete of policies on the first connection to send one.
func (h *commitHolder) toServer(conn, upstream net.Conn) {
header := make([]byte, 4)
if _, err := io.ReadFull(conn, header); err != nil {
return
}
startup := make([]byte, binary.BigEndian.Uint32(header)-4)
if _, err := io.ReadFull(conn, startup); err != nil {
return
}
if _, err := upstream.Write(append(header, startup...)); err != nil {
return
}
var deleting bool
for {
header := make([]byte, 5)
if _, err := io.ReadFull(conn, header); err != nil {
return
}
body := make([]byte, binary.BigEndian.Uint32(header[1:])-4)
if _, err := io.ReadFull(conn, body); err != nil {
return
}
if header[0] == 'Q' && bytes.HasPrefix(body, []byte(`DELETE FROM "policies"`)) {
deleting = true
}
if header[0] == 'Q' && deleting && bytes.HasPrefix(body, []byte("COMMIT")) {
held := false
h.once.Do(func() { held = true })
if held {
// The client gives up on the answer and drops the connection meanwhile.
go func() {
_, _ = io.Copy(io.Discard, conn)
close(h.gaveUp)
}()
<-h.release
}
}
if _, err := upstream.Write(append(header, body...)); err != nil {
return
}
}
}

// A run whose COMMIT lands after it gave up on its answer still drops, before it exits, the
// policy a router cached meanwhile: closing the store lets the deletions held for that COMMIT
// run.
func (s *ForgetUserSuite) TestARunWhoseCommitLandsAfterItGaveUpStillDropsThePolicyARouterCached() {
router, err := store.OpenShards(store.Options{
DSN: s.settings.Postgres.DSN, ShardDSN: s.settings.Postgres.ShardDSN, Shards: s.settings.Postgres.Shards,
Redis: store.Redis{Address: s.settings.Redis.Addr},
})
s.Require().NoError(err)
s.T().Cleanup(func() { s.NoError(router.Close()) })
s.settingsOf(s.app, person)
scope := store.UserScopeID(s.app, person)
cached, err := router.Policies.Get(s.ctx, store.ScopeUser, scope)
s.Require().NoError(err)
s.Require().NotNil(cached.Quota)
holder, dsn := s.holdingCommit()
s.settings.Postgres.DSN = dsn

ran := make(chan error, 1)
go func() {
ran <- s.runForget([]string{"forget-user", "--app", s.app, "--user", person, "--actor", "staff@example.com", "--settle", "0s"}, &bytes.Buffer{})
}()
select {
case <-holder.gaveUp:
case <-time.After(10 * time.Second):
s.FailNow("the run never gave up on the held COMMIT")
}
// The run drops the policy as it gives up; a router reading it meanwhile caches it again,
// since the delete has not committed.
for deadline := time.Now().Add(30 * time.Millisecond); time.Now().Before(deadline); {
read, err := router.Policies.Get(s.ctx, store.ScopeUser, scope)
s.Require().NoError(err)
s.Require().NotNil(read.Quota, "the delete is not committed yet")
}
holder.let()
select {
case err := <-ran:
s.Error(err, "the run never had the COMMIT's answer")
case <-time.After(10 * time.Second):
s.FailNow("the run never ended")
}

s.Eventually(func() bool {
read, err := router.Policies.Get(s.ctx, store.ScopeUser, scope)
s.Require().NoError(err)
return read.Quota == nil
}, 3*time.Second, 10*time.Millisecond, "the router still answers the policy the user had")
}
183 changes: 183 additions & 0 deletions acceleration/internal/policy/join_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
//go:build integration

package policy

import (
"fmt"
"time"

"github.com/google/uuid"
"github.com/uptrace/bun"

"github.com/GetStream/Vision-Agents/acceleration/internal/store"
)

// heldMembership begins a transaction holding an app's membership row, which a write of it
// waits behind, and answers it with its backend's pid.
func (s *PolicySuite) heldMembership(appID string) (bun.Tx, int) {
s.Require().NoError(s.store.AppOrganizations.Upsert(s.ctx, &store.AppOrganization{AppID: appID, OrganizationID: "org-before"}))
holder, err := s.store.GlobalDB().BeginTx(s.ctx, nil)
s.Require().NoError(err)
s.T().Cleanup(func() { _ = holder.Rollback() })
var pid int
s.Require().NoError(holder.QueryRowContext(s.ctx, "SELECT pg_backend_pid()").Scan(&pid))
_, err = holder.ExecContext(s.ctx, "SELECT 1 FROM app_organizations WHERE app_id = ? FOR UPDATE", appID)
s.Require().NoError(err)
return holder, pid
}

// waitingBehind is how many statements wait for the holder with this pid.
func (s *PolicySuite) waitingBehind(holder int) int {
var waiting int
s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx,
"SELECT count(*) FROM pg_stat_activity WHERE ? = ANY(pg_blocking_pids(pid))", holder).Scan(&waiting))
return waiting
}

// organizationOf is the organization the app's row names now, read past the cache, or empty
// with no row.
func (s *PolicySuite) organizationOf(appID string) string {
var organization string
s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx,
"SELECT coalesce((SELECT organization_id FROM app_organizations WHERE app_id = ?), '')", appID).Scan(&organization))
return organization
}

func (s *PolicySuite) TestAnAppNamingOrganizationsInTurnHasOneMembershipWrittenAtATimeAndTheLastWins() {
enforcer := s.newEnforcer(s.store, nil)
app := "app-" + uuid.NewString()
holder, pid := s.heldMembership(app)

for i := range 200 {
enforcer.Join(s.ctx, app, fmt.Sprintf("org-%d", i%2), openTier)
}
enforcer.Join(s.ctx, app, "org-last", openTier)
s.Require().Eventually(func() bool { return s.waitingBehind(pid) > 0 }, 5*time.Second, 10*time.Millisecond,
"the first write waits behind the holder")
s.Never(func() bool { return s.waitingBehind(pid) > 1 }, 300*time.Millisecond, 10*time.Millisecond,
"one write of the app's membership runs at a time")

s.Require().NoError(holder.Commit())
s.Eventually(func() bool { return s.organizationOf(app) == "org-last" }, 5*time.Second, 10*time.Millisecond,
"the organization named last is the one recorded")
closed := make(chan struct{})
go func() {
enforcer.Close()
close(closed)
}()
select {
case <-closed:
case <-time.After(joinTimeout / 2):
s.FailNow("the app's writes go on once the last organization named landed")
}
}

func (s *PolicySuite) TestAnAppJoiningAnotherOrganizationLaterIsRecordedUnderIt() {
enforcer := s.newEnforcer(s.store, nil)
app := "app-" + uuid.NewString()
enforcer.Join(s.ctx, app, "org-first", openTier)
s.Require().Eventually(func() bool { return s.organizationOf(app) == "org-first" }, 5*time.Second, 10*time.Millisecond,
"the first organization is recorded")

enforcer.Join(s.ctx, app, "org-second", openTier)

s.Eventually(func() bool { return s.organizationOf(app) == "org-second" }, 5*time.Second, 10*time.Millisecond,
"an organization named after the first write ended is written too")
}

func (s *PolicySuite) TestAnOrganizationNamedBehindAWriteIsNotWrittenOnceCloseBegan() {
enforcer, err := New(s.store, quick, nil)
s.Require().NoError(err)
app := "app-" + uuid.NewString()
holder, pid := s.heldMembership(app)
enforcer.Join(s.ctx, app, "org-first", openTier)
s.Require().Eventually(func() bool { return s.waitingBehind(pid) > 0 }, 5*time.Second, 10*time.Millisecond,
"the first write waits behind the holder")
enforcer.Join(s.ctx, app, "org-second", openTier)

closed := make(chan struct{})
go func() {
enforcer.Close()
close(closed)
}()
s.Require().Eventually(func() bool {
enforcer.joinsMu.Lock()
defer enforcer.joinsMu.Unlock()
return enforcer.joinsClosed
}, 5*time.Second, 10*time.Millisecond, "Close began")
s.Require().NoError(holder.Commit())
select {
case <-closed:
case <-time.After(5 * time.Second):
s.FailNow("Close never returned")
}
s.Equal("org-first", s.organizationOf(app), "the write under way when Close began lands, and the one behind it is not started")
}

func (s *PolicySuite) TestCloseWaitsForAMembershipBeingWritten() {
enforcer, err := New(s.store, quick, nil)
s.Require().NoError(err)
app := "app-" + uuid.NewString()
holder, pid := s.heldMembership(app)
enforcer.Join(s.ctx, app, "org-after", openTier)
s.Require().Eventually(func() bool { return s.waitingBehind(pid) > 0 }, 5*time.Second, 10*time.Millisecond,
"the write waits behind the holder")

closed := make(chan struct{})
go func() {
enforcer.Close()
close(closed)
}()
s.Never(func() bool {
select {
case <-closed:
return true
default:
return false
}
}, 300*time.Millisecond, 10*time.Millisecond, "Close returns while the membership is being written")
s.Require().NoError(holder.Commit())
select {
case <-closed:
case <-time.After(5 * time.Second):
s.FailNow("Close never returned")
}
s.Equal("org-after", s.organizationOf(app), "the membership landed before Close returned")
}

func (s *PolicySuite) TestCloseStopsWaitingForAMembershipAfterJoinTimeout() {
enforcer, err := New(s.store, quick, nil)
s.Require().NoError(err)
app := "app-" + uuid.NewString()
_, pid := s.heldMembership(app)
enforcer.Join(s.ctx, app, "org-after", openTier)
s.Require().Eventually(func() bool { return s.waitingBehind(pid) > 0 }, 5*time.Second, 10*time.Millisecond,
"the write waits behind the holder")

closed := make(chan struct{})
go func() {
enforcer.Close()
close(closed)
}()
select {
case <-closed:
case <-time.After(joinTimeout + 2*time.Second):
s.FailNow("Close waited on the membership past joinTimeout")
}
}

func (s *PolicySuite) TestAJoinAfterCloseWritesNoMembership() {
enforcer, err := New(s.store, quick, nil)
s.Require().NoError(err)
enforcer.Close()
app := "app-" + uuid.NewString()

enforcer.Join(s.ctx, app, "org-after", openTier)

s.Never(func() bool {
var written bool
s.Require().NoError(s.store.GlobalDB().QueryRowContext(s.ctx,
"SELECT EXISTS (SELECT 1 FROM app_organizations WHERE app_id = ?)", app).Scan(&written))
return written
}, 300*time.Millisecond, 10*time.Millisecond, "a closed enforcer starts no write")
}
Loading
Loading