Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 13 additions & 13 deletions cmd/fmsg-webapi/apikey_cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (

"github.com/markmnl/fmsg-webapi/internal/apiauth"
"github.com/markmnl/fmsg-webapi/internal/db"
"github.com/markmnl/fmsg-webapi/internal/handlers"
"github.com/markmnl/fmsg-webapi/internal/middleware"
)

Expand Down Expand Up @@ -55,6 +56,14 @@ func runAPIKeyCreate(ctx context.Context, args []string) error {
if err := requireAcceptingCLIAddress(idURL, *owner, "owner"); err != nil {
return err
}
// Open the database first: undoing a registration needs it.
database, err := db.New(ctx, "")
if err != nil {
return err
}
defer database.Close()
store := apiauth.NewStore(database)

// Match the self-service sub-account flow: derived addresses are created in
// fmsgid, in the owner's quota pool, before their API key is persisted, and
// one used before is reinstated.
Expand All @@ -65,26 +74,17 @@ func runAPIKeyCreate(ctx context.Context, args []string) error {
if err := requireAcceptingCLIAddress(idURL, subAddr, "derived address"); err != nil {
return err
}
// Undo registration or reinstatement if no grant comes of it, unless the
// address has a grant after all (a concurrent create won the race).
granted := false
conflict := false
if created || reinstated {
defer func() {
if !granted && !conflict {
disableCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := middleware.DisableFmsgIDContext(disableCtx, idURL, subAddr); err != nil {
fmt.Fprintf(os.Stderr, "disabling address %s after failed create: %v\n", subAddr, err)
}
if !granted {
handlers.UndoLinkedRegistration(store, idURL, *owner, subAddr, conflict)
}
}()
}
database, err := db.New(ctx, "")
if err != nil {
return err
}
defer database.Close()

store := apiauth.NewStore(database)
if err := store.Create(ctx, *owner, *agent, subAddr, key.ID, hash, allowed, expires); err != nil {
if errors.Is(err, apiauth.ErrAlreadyExists) {
conflict = true
Expand Down
6 changes: 4 additions & 2 deletions cmd/fmsg-webapi/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,10 +252,12 @@ func main() {
<-serveErr
cancelHub()
<-hubDone
// Send the Web Pushes already queued, including those for requests
// that committed during the drain above, before giving up on the rest.
pushDrainCtx, cancelPushDrain := context.WithTimeout(context.Background(), 5*time.Second)
defer cancelPushDrain()
if err := hub.CloseContext(pushDrainCtx); err != nil {
log.Printf("push shutdown error: %v", err)
if err := hub.DrainContext(pushDrainCtx); err != nil {
log.Printf("push shutdown: gave up on queued pushes: %v", err)
}
}
}
Expand Down
29 changes: 29 additions & 0 deletions internal/apiauth/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,35 @@ func (s *Store) createGrant(ctx context.Context, ownerAddr, agent, subAddr, gran
return tx.Commit(ctx)
}

// UnlessGranted runs fn only if no grant exists for subAddr, and reports
// whether it ran. It holds the lock createGrant takes for ownerAddr while it
// checks and while fn runs, so a concurrent create for the same owner either
// commits its grant first (fn is skipped) or inserts after fn has finished.
func (s *Store) UnlessGranted(ctx context.Context, ownerAddr, subAddr string, fn func() error) (bool, error) {
tx, err := s.DB.Pool.Begin(ctx)
if err != nil {
return false, err
}
defer tx.Rollback(ctx) //nolint:errcheck

if _, err := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtext(lower($1)))`, ownerAddr); err != nil {
return false, err
}
var granted bool
if err := tx.QueryRow(ctx,
`SELECT EXISTS (SELECT 1 FROM fmsg_api_sub_account WHERE lower(sub_addr) = lower($1))`,
subAddr).Scan(&granted); err != nil {
return false, err
}
if granted {
return false, nil
}
if err := fn(); err != nil {
return true, err
}
return true, tx.Commit(ctx)
}

func (s *Store) RotateKey(ctx context.Context, ownerAddr, agent, keyID string, keyHash []byte, keyExpiresAt time.Time) (string, error) {
var subAddr string
err := s.DB.Pool.QueryRow(ctx,
Expand Down
78 changes: 61 additions & 17 deletions internal/handlers/hub.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,39 +171,83 @@ func (h *Hub) Close() {
_ = h.CloseContext(context.Background())
}

// CloseContext shuts down the bounded Web Push worker pool, cancelling its
// push context so queued jobs are skipped and in-flight pushes abort promptly,
// and waits for workers to exit until ctx is cancelled.
func (h *Hub) CloseContext(ctx context.Context) error {
// pushAbortGrace is how long DrainContext waits for workers to exit after it
// has cancelled their pushes.
const pushAbortGrace = time.Second

// closePushQueue stops the pool accepting jobs. Workers exit once they have
// taken everything already queued.
func (h *Hub) closePushQueue() {
h.pushMu.Lock()
if !h.pushClosed {
h.pushClosed = true
if h.pushCancel != nil {
h.pushCancel()
}
if h.pushCh != nil {
close(h.pushCh)
}
defer h.pushMu.Unlock()
if h.pushClosed {
return
}
h.pushMu.Unlock()
h.pushClosed = true
if h.pushCh != nil {
close(h.pushCh)
}
}

if ctx == nil {
h.pushWG.Wait()
return nil
// cancelPushes aborts in-flight pushes and makes workers skip what is queued.
func (h *Hub) cancelPushes() {
h.pushMu.Lock()
defer h.pushMu.Unlock()
if h.pushCancel != nil {
h.pushCancel()
}
}

// pushWorkersDone is closed once every push worker has exited.
func (h *Hub) pushWorkersDone() <-chan struct{} {
done := make(chan struct{})
go func() {
h.pushWG.Wait()
close(done)
}()
return done
}

// CloseContext shuts down the bounded Web Push worker pool, cancelling its
// push context so queued jobs are skipped and in-flight pushes abort promptly,
// and waits for workers to exit until ctx is cancelled.
func (h *Hub) CloseContext(ctx context.Context) error {
h.closePushQueue()
h.cancelPushes()

if ctx == nil {
h.pushWG.Wait()
return nil
}
select {
case <-done:
case <-h.pushWorkersDone():
return nil
case <-ctx.Done():
return ctx.Err()
}
}

// DrainContext shuts down the bounded Web Push worker pool without losing
// work: it stops accepting jobs and lets the workers send what is queued and
// in flight, waiting for them until ctx is done. If ctx ends first it cancels
// what remains, as CloseContext does, and returns ctx's error.
func (h *Hub) DrainContext(ctx context.Context) error {
h.closePushQueue()
done := h.pushWorkersDone()
select {
case <-done:
h.cancelPushes() // nothing left to cancel; releases the push context
return nil
case <-ctx.Done():
}
h.cancelPushes()
select {
case <-done:
case <-time.After(pushAbortGrace):
}
return ctx.Err()
}

func (h *Hub) enqueuePush(msgID int64, addr string) {
h.pushMu.Lock()
if h.pushClosed {
Expand Down
71 changes: 71 additions & 0 deletions internal/handlers/hub_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,3 +400,74 @@ func TestHubCloseContext_RespectsDeadlineWhenWorkerBlocks(t *testing.T) {
t.Fatalf("CloseContext err = %v, want context.DeadlineExceeded", err)
}
}

func TestHubDrainContext_SendsQueuedPushes(t *testing.T) {
hub := newTestHub()
hub.pushWorkers = 2
hub.pushQueueSize = 16

const total = 8
var completed, cancelled syncatomic.Int32
hub.SetPushNotifier(func(ctx context.Context, _ int64, _ string) {
time.Sleep(15 * time.Millisecond)
if ctx.Err() != nil {
cancelled.Add(1)
return
}
completed.Add(1)
})
for i := int64(1); i <= total; i++ {
hub.route(context.Background(), "new_msg", i, "@offline@x")
}

drainCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := hub.DrainContext(drainCtx); err != nil {
t.Fatalf("DrainContext returned error: %v", err)
}
if got := completed.Load(); got != total {
t.Fatalf("pushes sent = %d, want all %d queued at shutdown (cancelled: %d)", got, total, cancelled.Load())
}

// The pool is closed: a later notification is not queued.
hub.route(context.Background(), "new_msg", total+1, "@offline@x")
time.Sleep(30 * time.Millisecond)
if got := completed.Load(); got != total {
t.Fatalf("a push was sent after the drain: %d", got)
}
}

func TestHubDrainContext_CancelsWhatIsLeftAtTheDeadline(t *testing.T) {
hub := newTestHub()
hub.pushWorkers = 1
hub.pushQueueSize = 4

started := make(chan struct{}, 1)
var called, cancelled syncatomic.Int32
hub.SetPushNotifier(func(ctx context.Context, _ int64, _ string) {
called.Add(1)
started <- struct{}{}
<-ctx.Done()
cancelled.Add(1)
})
hub.route(context.Background(), "new_msg", 1, "@offline@x")
<-started
hub.route(context.Background(), "new_msg", 2, "@offline@x")

drainCtx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel()
start := time.Now()
err := hub.DrainContext(drainCtx)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("DrainContext err = %v, want context.DeadlineExceeded", err)
}
if elapsed := time.Since(start); elapsed > pushAbortGrace {
t.Fatalf("DrainContext took %s; workers should exit promptly once cancelled", elapsed)
}
if got := cancelled.Load(); got != 1 {
t.Fatalf("in-flight pushes observing cancellation = %d, want 1", got)
}
if got := called.Load(); got != 1 {
t.Fatalf("notifyPush called %d times, want 1 (the queued job is skipped after cancel)", got)
}
}
71 changes: 60 additions & 11 deletions internal/handlers/subaccounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,15 +150,14 @@ func (h *SubAccountHandler) Create(c *gin.Context) {
}
// Undo registration or reinstatement if no grant comes of it, so a
// newly-registered or deleted address doesn't stay accepting new messages
// without a grant. An already-active address or a concurrent create that
// won the race (ErrAlreadyExists) is left untouched so an active grant is
// never disabled.
// without a grant. An address that has a grant after all (a concurrent
// create won the race) is left as it is.
granted := false
conflict := false
if created || reinstated {
defer func() {
if !granted && !conflict {
disableAfterFailedCreate(h.idURL, subAddr)
if !granted {
UndoLinkedRegistration(h.store, h.idURL, owner, subAddr, conflict)
}
}()
}
Expand All @@ -177,6 +176,13 @@ func (h *SubAccountHandler) Create(c *gin.Context) {
return
}
granted = true
if !created && !reinstated {
// The address was registered by a create that may since have failed
// and undone its registration; make sure this grant's address accepts.
if err := ensureLinkedRegistration(h.idURL, owner, subAddr); err != nil {
log.Printf("sub-account create: confirming address accepts: addr=%s: %v", subAddr, err)
}
}
c.JSON(http.StatusCreated, createSubAccountResponse{
subAccountResponse: subAccountResponse{
Agent: in.Agent,
Expand All @@ -191,15 +197,58 @@ func (h *SubAccountHandler) Create(c *gin.Context) {
})
}

// disableAfterFailedCreate stops a newly-registered or reinstated derived
// address accepting new messages after its grant couldn't be created. It is
// best effort: the create has already failed, so a failure here is only logged.
func disableAfterFailedCreate(idURL, addr string) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
// linkedRegistrationTimeout bounds the identity-service calls made after a
// create has been decided, which run detached from the request.
const linkedRegistrationTimeout = 5 * time.Second

// UndoLinkedRegistration stops a newly-registered or reinstated derived
// address accepting new messages after its grant couldn't be created, unless
// the address has a grant after all: a concurrent create for the same address
// can win, and the loser doesn't always learn that from its own error (it may
// be told the owner's limit is reached instead). It is best effort: the create
// has already failed, so a failure here is only logged.
//
// conflict reports that the store refused the create because the grant
// exists. It decides only when the store can't be asked.
func UndoLinkedRegistration(store *apiauth.Store, idURL, owner, addr string, conflict bool) {
ctx, cancel := context.WithTimeout(context.Background(), 2*linkedRegistrationTimeout)
defer cancel()
if err := middleware.DisableFmsgIDContext(ctx, idURL, addr); err != nil {
attempted := false
_, err := store.UnlessGranted(ctx, owner, addr, func() error {
attempted = true
return disableLinkedAddress(idURL, addr)
})
if err == nil {
return
}
if attempted {
log.Printf("sub-account create: disabling address after failure: addr=%s: %v", addr, err)
return
}
log.Printf("sub-account create: checking for a grant before disabling: addr=%s: %v", addr, err)
if conflict {
return
}
if err := disableLinkedAddress(idURL, addr); err != nil {
log.Printf("sub-account create: disabling address after failure: addr=%s: %v", addr, err)
}
}

func disableLinkedAddress(idURL, addr string) error {
ctx, cancel := context.WithTimeout(context.Background(), linkedRegistrationTimeout)
defer cancel()
return middleware.DisableFmsgIDContext(ctx, idURL, addr)
}

// ensureLinkedRegistration makes sure a derived address that now has a grant
// accepts new messages. A create that found the address already registered
// calls it once its grant is stored, because the create that registered the
// address may have failed and undone the registration in the meantime.
func ensureLinkedRegistration(idURL, owner, addr string) error {
ctx, cancel := context.WithTimeout(context.Background(), linkedRegistrationTimeout)
defer cancel()
_, _, err := middleware.RegisterLinkedFmsgIDContext(ctx, idURL, addr, owner)
return err
}

func (h *SubAccountHandler) RotateKey(c *gin.Context) {
Expand Down
Loading