#295. A member's plan change (a switch to another tier, Keep plan, Cancel plan) and the sweep that fires scheduled changes made their Stripe calls without a deadline, and the calls after the first ran on the request's context or none: a request that ended mid-change could leave a change made at Stripe and unrecorded in the console. Each move's first Stripe call, its read of the subscription, carries the request's context, and requestEnded checks the request again before the first write, so a request that ends before then changes nothing. Every later call carries a deadline of its own that the end of the request does not cut (stripeCallContext): 60 seconds for an upgrade's charge, 40 for the others, and 20 for the calls of the switch of a subscription paused for a grant, which resolves them before the member is answered. The record and the reconcile after the last Stripe call run within another 60 seconds (recordMove). Every Stripe write carries the idempotency key stripe-go adds, so its own retries cannot repeat a write. A write that gets no answer before its deadline is reported as failed and records nothing; Stripe's event for a write that did land brings the console in line. A downgrade's update of its subscription schedule is the exception, since no event records it: it carries a key the console chose, and when it got no answer (gotNoAnswer) it is sent once more with the same parameters and key (sendScheduleUpdate). An update Stripe answered, a 500 included, is not sent again, because Stripe replays its saved answer to the same key. Each move lists the subscription's active scheduled changes before its first Stripe call, and its record supersedes only those, so a later request's cancellation or downgrade recorded meanwhile is not erased. The sweep gives each cancel or price change 20 seconds inside its one-minute run, and when less than 30 seconds are left (20 per write plus a margin of 10) it stops and leaves the remaining rows to its next attempt. Ride-alongs, listed in the proposal: - The switch's price preview ends with the request. - currentPrices skips only a price with no mapping and returns every other read error; a failed mapping read was taken as "this price is not current", which decides Keep plan's refusal and the reconcile's rule 1. The Stripe mock records the idempotency key a call's params carry (Call.IdempotencyKey); docs/stripe.md and docs/testing.md say what the code does. No user-visible string changes. Break list: 53 records, 53 CAUGHT. Named without a record, with the reason: the downgrade's read of the current item before its first Stripe call, each move's call of recordMove, requestEnded and activeMoves (none is one replacement; the recordMove, recordContext, requestEnded and item 4.11 breaks stand for them), the reconcile's use of currentPrices' error (an ended context fails the reconcile at its first statement), and the resend test's guard row. Full suite on reset databases: 5608 passed, 16 skipped, none failed.
182 lines
6.5 KiB
Go
182 lines
6.5 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
|
// SPDX-FileCopyrightText: 2025-2026 Christian Galo
|
|
|
|
package server
|
|
|
|
import (
|
|
"bufio"
|
|
"errors"
|
|
"html/template"
|
|
"io"
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"sync"
|
|
"testing"
|
|
"testing/synctest"
|
|
"time"
|
|
|
|
"git.coopcloud.tech/wiki-cafe/member-console/internal/fulfillment"
|
|
"git.coopcloud.tech/wiki-cafe/member-console/internal/middleware"
|
|
"git.coopcloud.tech/wiki-cafe/member-console/internal/testkit"
|
|
)
|
|
|
|
// oneConnListener hands out one connection and then waits until it is closed,
|
|
// as a listener whose only client has already connected.
|
|
type oneConnListener struct {
|
|
conns chan net.Conn
|
|
done chan struct{}
|
|
once sync.Once
|
|
}
|
|
|
|
func newOneConnListener(c net.Conn) *oneConnListener {
|
|
l := &oneConnListener{conns: make(chan net.Conn, 1), done: make(chan struct{})}
|
|
l.conns <- c
|
|
return l
|
|
}
|
|
|
|
func (l *oneConnListener) Accept() (net.Conn, error) {
|
|
select {
|
|
case c := <-l.conns:
|
|
return c, nil
|
|
case <-l.done:
|
|
return nil, net.ErrClosed
|
|
}
|
|
}
|
|
|
|
func (l *oneConnListener) Close() error {
|
|
l.once.Do(func() { close(l.done) })
|
|
return nil
|
|
}
|
|
|
|
func (l *oneConnListener) Addr() net.Addr { return &net.TCPAddr{} }
|
|
|
|
// serveOneRequest sends one request through the console's own chain, with the
|
|
// cross-origin check and the session layer passed through, and its server
|
|
// settings, over an in-memory connection and reads the answer readAfter after
|
|
// sending it. It must run inside a synctest bubble. A step that fails reports
|
|
// with Errorf and returns, never Fatalf: the deferred close ends the server's
|
|
// goroutines, and a bubble that exits with goroutines still blocked panics. It
|
|
// returns a nil response and a nil error when it could not send the request,
|
|
// having reported why.
|
|
func serveOneRequest(t *testing.T, name string, handler http.Handler, readAfter time.Duration) (*http.Response, []byte, time.Duration, error) {
|
|
t.Helper()
|
|
srvConn, cliConn := net.Pipe()
|
|
var pass middleware.Middleware = func(next http.Handler) http.Handler { return next }
|
|
chain := preAuthStack(NewSafeTemplates(template.New("error.html"), slog.Default()), pass, pass)
|
|
srv := newHTTPServer(chain(handler))
|
|
l := newOneConnListener(srvConn)
|
|
served := make(chan error, 1)
|
|
go func() { served <- srv.Serve(l) }()
|
|
defer func() {
|
|
testkit.Close(t, srv)
|
|
testkit.Close(t, cliConn)
|
|
if err := <-served; !errors.Is(err, http.ErrServerClosed) {
|
|
t.Errorf("%s: the server ended with %v", name, err)
|
|
}
|
|
}()
|
|
|
|
sent := time.Now()
|
|
if err := cliConn.SetDeadline(sent.Add(60 * time.Second)); err != nil { // htmx's own limit
|
|
t.Errorf("%s: could not send the request: %v", name, err)
|
|
return nil, nil, 0, nil
|
|
}
|
|
if _, err := io.WriteString(cliConn, "GET / HTTP/1.1\r\nHost: console.test\r\n\r\n"); err != nil {
|
|
t.Errorf("%s: could not send the request: %v", name, err)
|
|
return nil, nil, 0, nil
|
|
}
|
|
time.Sleep(readAfter)
|
|
resp, err := http.ReadResponse(bufio.NewReader(cliConn), nil)
|
|
if err != nil {
|
|
return nil, nil, time.Since(sent), err
|
|
}
|
|
defer resp.Body.Close()
|
|
body, err := io.ReadAll(resp.Body)
|
|
return resp, body, time.Since(sent), err
|
|
}
|
|
|
|
// Every request the console lets run gets its answer in full, or the timeout
|
|
// answer with the security headers, with the production timeouts in fake time.
|
|
func TestEveryRequestGetsItsAnswerOrTheTimeoutAnswer(t *testing.T) {
|
|
// The handlers' writes are checked through the body each row reads.
|
|
answers := func(after time.Duration) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
time.Sleep(after)
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = io.WriteString(w, "answered")
|
|
})
|
|
}
|
|
runsOut := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
<-r.Context().Done()
|
|
_, _ = io.WriteString(w, "late")
|
|
})
|
|
rows := []struct {
|
|
name string
|
|
handler http.Handler
|
|
readAfter time.Duration
|
|
wantStatus int
|
|
wantBody string
|
|
wantAt time.Duration // 0: not checked
|
|
}{
|
|
{"a handler past the old write timeout gets its answer", answers(10 * time.Second), 0, http.StatusOK, "answered", 0},
|
|
{"a handler at the end of the request timeout gets its answer", answers(requestTimeout - time.Second), 0, http.StatusOK, "answered", 0},
|
|
{"a handler past the request timeout gets the timeout answer", runsOut, 0, http.StatusServiceUnavailable, "Request timed out", 32 * time.Second},
|
|
{"a slow reader gets the margin to read the timeout answer", runsOut, requestTimeout + 7*time.Second, http.StatusServiceUnavailable, "Request timed out", 0},
|
|
}
|
|
for _, row := range rows {
|
|
t.Run(row.name, func(t *testing.T) {
|
|
synctest.Test(t, func(t *testing.T) {
|
|
resp, body, took, err := serveOneRequest(t, row.name, row.handler, row.readAfter)
|
|
if err != nil {
|
|
t.Errorf("%s: got no answer: %v", row.name, err)
|
|
return
|
|
}
|
|
if resp == nil {
|
|
return // serveOneRequest reported why the request was not sent
|
|
}
|
|
if resp.StatusCode != row.wantStatus || string(body) != row.wantBody {
|
|
t.Errorf("%s: answered %d %q, want %d %q", row.name, resp.StatusCode, body, row.wantStatus, row.wantBody)
|
|
}
|
|
if row.wantStatus == http.StatusServiceUnavailable && resp.Header.Get("X-Content-Type-Options") != "nosniff" {
|
|
t.Errorf("%s: the 503 carries no security headers", row.name)
|
|
}
|
|
if row.wantAt != 0 && took != row.wantAt {
|
|
t.Errorf("%s: answered at %v, want at %v", row.name, took, row.wantAt)
|
|
}
|
|
})
|
|
})
|
|
}
|
|
}
|
|
|
|
// A client that has not started reading when the write timeout ends is cut,
|
|
// so a reader that stops reading cannot hold its connection for longer.
|
|
func TestAReaderPastTheWriteTimeoutIsCut(t *testing.T) {
|
|
synctest.Test(t, func(t *testing.T) {
|
|
runsOut := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
<-r.Context().Done()
|
|
})
|
|
resp, _, _, _ := serveOneRequest(t, "a reader past the write timeout", runsOut, requestTimeout+9*time.Second)
|
|
if resp != nil {
|
|
t.Errorf("a reader past the write timeout: answered %d, want the connection cut", resp.StatusCode)
|
|
}
|
|
})
|
|
}
|
|
|
|
// A plan change's call, charge and record deadlines are each longer than the
|
|
// request's, so a call cut by its own deadline ends after the member has had
|
|
// the timeout answer (design D1).
|
|
func TestPlanChangeDeadlinesOutlastTheRequest(t *testing.T) {
|
|
for _, d := range []struct {
|
|
name string
|
|
d time.Duration
|
|
}{
|
|
{"PlanChangeCallTimeout", fulfillment.PlanChangeCallTimeout},
|
|
{"PlanChangeChargeTimeout", fulfillment.PlanChangeChargeTimeout},
|
|
{"PlanChangeRecordTimeout", fulfillment.PlanChangeRecordTimeout},
|
|
} {
|
|
if d.d <= requestTimeout {
|
|
t.Errorf("%s is %v, want longer than the request's %v", d.name, d.d, requestTimeout)
|
|
}
|
|
}
|
|
}
|