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
334 changes: 321 additions & 13 deletions README.md

Large diffs are not rendered by default.

7 changes: 7 additions & 0 deletions callback.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ const (
// EventTimeout fires when a queued request's context is cancelled or
// its deadline expires before a slot becomes available.
EventTimeout

// EventPromote fires when a queued token is promoted to a higher
// position via PromoteToken. Use this to track revenue events or
// log queue jumps for fairness monitoring.
EventPromote
)

// String returns the canonical name of the Event, suitable for logging.
Expand All @@ -62,6 +67,8 @@ func (e Event) String() string {
return "Evict"
case EventTimeout:
return "Timeout"
case EventPromote:
return "Promote"
default:
return "Unknown"
}
Expand Down
3 changes: 2 additions & 1 deletion callback_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ func TestEvent_String(t *testing.T) {
{EventQueue, "Queue"},
{EventEvict, "Evict"},
{EventTimeout, "Timeout"},
{EventPromote, "Promote"},
{Event(255), "Unknown"},
}
for _, tc := range cases {
Expand Down Expand Up @@ -246,7 +247,7 @@ func TestConcurrent_OnOffEmit_AllEvents(t *testing.T) {
t.Parallel()
wr := newTestWR(t, 5)

events := []Event{EventEnter, EventExit, EventFull, EventDrain, EventQueue, EventEvict, EventTimeout}
events := []Event{EventEnter, EventExit, EventFull, EventDrain, EventQueue, EventEvict, EventTimeout, EventPromote}
var wg sync.WaitGroup
for _, ev := range events {
ev := ev
Expand Down
17 changes: 17 additions & 0 deletions const.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ const (
// cookieName is the HTTP-only session cookie issued to queued clients.
cookieName = "room_ticket"

// passCookieName is the HTTP-only cookie that holds the VIP pass
// token. This cookie outlives individual queue tickets — it persists
// for the configured pass duration so that clients who paid to skip
// are auto-promoted on re-entry without paying again.
passCookieName = "room_pass"

// cookieTTL is how long a queued client's token remains valid.
// If a client disappears before being admitted, their token is
// evicted by the reaper after this duration.
Expand Down Expand Up @@ -46,4 +52,15 @@ const (
// /queue/status polls for a single token. Polls arriving faster
// than this receive a cached response with a Retry-After header.
statusPollMinInterval = 1 * time.Second

// defaultPassDuration is the default lifetime of a VIP pass issued
// by PromoteTokenToFront / GrantPass. Zero means passes are disabled
// (single-use promotion only). Call SetPassDuration to enable.
defaultPassDuration = 0

// passMinDuration is the minimum value accepted by SetPassDuration.
passMinDuration = 1 * time.Minute

// passMaxDuration is the maximum value accepted by SetPassDuration.
passMaxDuration = 24 * time.Hour
)
48 changes: 48 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,51 @@ type ErrInvalidMaxQueueDepth struct {
func (e ErrInvalidMaxQueueDepth) Error() string {
return fmt.Sprintf("room: invalid max queue depth %d: must be >= 0", e.Given)
}

// ErrPromotionDisabled is returned when PromoteToken or QuoteCost is
// called without a RateFunc configured via SetRateFunc.
type ErrPromotionDisabled struct{}

func (e ErrPromotionDisabled) Error() string {
return "room: promotions disabled — call SetRateFunc first"
}

// ErrTokenNotFound is returned when the token does not exist in the
// token store (expired, already admitted, or never issued).
type ErrTokenNotFound struct{}

func (e ErrTokenNotFound) Error() string {
return "room: token not found"
}

// ErrAlreadyAdmitted is returned when a promotion is attempted on a
// token that is already within the serving window.
type ErrAlreadyAdmitted struct{}

func (e ErrAlreadyAdmitted) Error() string {
return "room: token already within serving window"
}

// ErrInvalidTargetPosition is returned when targetPosition < 1.
type ErrInvalidTargetPosition struct {
Given int64
}

func (e ErrInvalidTargetPosition) Error() string {
return fmt.Sprintf("room: invalid target position %d: must be >= 1", e.Given)
}

// ErrPassDuration is returned by SetPassDuration when the provided
// duration falls outside [passMinDuration, passMaxDuration].
type ErrPassDuration struct {
Given time.Duration
Min time.Duration
Max time.Duration
}

func (e ErrPassDuration) Error() string {
return fmt.Sprintf(
"room: pass duration %s out of range [%s, %s]",
e.Given, e.Min, e.Max,
)
}
120 changes: 120 additions & 0 deletions new.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package room
import (
"context"
"fmt"
"math"
"net/http"
"time"

"github.com/andreimerlescu/sema"
"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -84,6 +86,7 @@ func (wr *WaitingRoom) Init(cap int32) error {
wr.cap.Store(cap)
wr.sem = sema.Must(int(cap))
wr.tokens = newTokenStore()
wr.passes = newPassStore()
wr.reaperRestart = make(chan struct{}, 1)
wr.nowServing.Store(0)
wr.nextTicket.Store(0)
Expand All @@ -92,6 +95,10 @@ func (wr *WaitingRoom) Init(cap int32) error {
wr.maxQueueDepth.Store(defaultMaxQueueDepth)
wr.cookiePath.Store("/")
wr.cookieDomain.Store("")
wr.rateFunc.Store((*rateFuncHolder)(nil))
wr.promoteInsert.Store(math.MaxInt64)
wr.skipURL.Store("")
wr.passDuration.Store(int64(defaultPassDuration))
wr.initialised.Store(true)
wr.callbacks = newCallbackRegistry()

Expand Down Expand Up @@ -179,6 +186,119 @@ func (wr *WaitingRoom) CookieDomain() string {
return wr.cookieDomain.Load().(string)
}

// SetSkipURL sets the URL that the waiting room "Pay to skip" button
// navigates to. This is typically a payment page (Stripe Checkout,
// crypto invoice, etc.) that your application hosts.
//
// The handler at this URL can read the room_ticket cookie to identify
// which queued client is paying. After payment verification, call
// PromoteTokenToFront to move them to the front of the queue.
//
// If empty (the default), the skip-the-line offer is never shown on
// the waiting room page, even if a RateFunc is configured. Both
// SetRateFunc and SetSkipURL must be set for the offer to appear.
//
// Safe to call at any time.
//
// Related: SetRateFunc, PromoteToken, PromoteTokenToFront
func (wr *WaitingRoom) SetSkipURL(url string) {
wr.skipURL.Store(url)
}

// SkipURL returns the current skip-the-line payment URL.
func (wr *WaitingRoom) SkipURL() string {
return wr.skipURL.Load().(string)
}

// SetPassDuration sets the lifetime of VIP passes issued by GrantPass.
// After a client pays to skip the line, they receive a pass that
// auto-promotes them for this duration on any subsequent queue entry,
// without requiring another payment.
//
// A value of 0 disables passes (the default). When disabled, promotions
// are single-use: the client is promoted once and must pay again if they
// re-enter the queue.
//
// Valid range when non-zero: 1m – 24h. Values outside this range return
// ErrPassDuration.
//
// Safe to call at any time.
//
// Related: GrantPass, HasValidPass, PassDuration
func (wr *WaitingRoom) SetPassDuration(d time.Duration) error {
if d == 0 {
wr.passDuration.Store(0)
return nil
}
if d < passMinDuration || d > passMaxDuration {
return ErrPassDuration{Given: d, Min: passMinDuration, Max: passMaxDuration}
}
wr.passDuration.Store(int64(d))
return nil
}

// PassDuration returns the current VIP pass lifetime. Zero means passes
// are disabled (single-use promotions only).
func (wr *WaitingRoom) PassDuration() time.Duration {
return time.Duration(wr.passDuration.Load())
}

// GrantPass creates a time-limited VIP pass and returns the pass token.
// The caller is responsible for setting the room_pass cookie on the
// HTTP response with this token value.
//
// The pass expires after PassDuration from now. If PassDuration is 0
// (passes disabled), GrantPass returns an empty string and no pass is
// created.
//
// Typical usage in your payment confirmation handler:
//
// cost, err := wr.PromoteTokenToFront(ticketToken)
// if err != nil { ... }
// passToken := wr.GrantPass()
// if passToken != "" {
// http.SetCookie(w, &http.Cookie{
// Name: "room_pass",
// Value: passToken,
// Path: wr.CookiePath(),
// MaxAge: int(wr.PassDuration().Seconds()),
// HttpOnly: true,
// Secure: true,
// })
// }
//
// Related: SetPassDuration, HasValidPass, PromoteTokenToFront
func (wr *WaitingRoom) GrantPass() string {
d := wr.PassDuration()
if d == 0 {
return ""
}

token, err := generateToken()
if err != nil {
return ""
}

wr.passes.set(token, passEntry{
expiresAt: time.Now().Add(d),
})

return token
}

// HasValidPass reports whether the given pass token exists and has not
// expired. Use this in your middleware or handlers to check if a client
// should be auto-promoted.
//
// Related: GrantPass, SetPassDuration
func (wr *WaitingRoom) HasValidPass(passToken string) bool {
if passToken == "" {
return false
}
_, ok := wr.passes.get(passToken)
return ok
}

// checkInitialised aborts the request with 500 and returns false if the
// WaitingRoom has not been initialised. Prevents nil pointer dereferences
// on zero-value WaitingRoom structs.
Expand Down
Loading
Loading