fix: harden CSV export streaming behind reverse proxies
Flush headers early, keep export DB context alive, log stream failures, skip redundant payment counts, and expose Content-Disposition for CORS downloads. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
713bd95f97
commit
56c644b0e3
|
|
@ -60,6 +60,8 @@ type PaymentListFilter struct {
|
|||
MaxAmount *float64
|
||||
Limit int32
|
||||
Offset int32
|
||||
// SkipTotalCount skips the COUNT(*) query (used by CSV export batches).
|
||||
SkipTotalCount bool
|
||||
}
|
||||
|
||||
type PaymentListPage struct {
|
||||
|
|
|
|||
|
|
@ -173,9 +173,13 @@ func (s *Store) ExpireStalePendingPayments(ctx context.Context) (int64, error) {
|
|||
func (s *Store) ListPaymentsAdmin(ctx context.Context, filter domain.PaymentListFilter) (domain.PaymentListPage, error) {
|
||||
params := buildPaymentsAdminFilterParams(filter)
|
||||
|
||||
total, err := s.queries.CountPaymentsAdmin(ctx, dbgen.CountPaymentsAdminParams(params))
|
||||
if err != nil {
|
||||
return domain.PaymentListPage{}, err
|
||||
var total int64
|
||||
if !filter.SkipTotalCount {
|
||||
var err error
|
||||
total, err = s.queries.CountPaymentsAdmin(ctx, dbgen.CountPaymentsAdminParams(params))
|
||||
if err != nil {
|
||||
return domain.PaymentListPage{}, err
|
||||
}
|
||||
}
|
||||
|
||||
rows, err := s.queries.ListPaymentsAdmin(ctx, dbgen.ListPaymentsAdminParams{
|
||||
|
|
|
|||
|
|
@ -155,6 +155,7 @@ func NewApp(
|
|||
AllowOrigins: "*",
|
||||
AllowMethods: "GET,POST,PUT,PATCH,DELETE,OPTIONS",
|
||||
AllowHeaders: "Content-Type,Authorization,platform",
|
||||
ExposeHeaders: "Content-Disposition",
|
||||
// AllowCredentials: true,
|
||||
}))
|
||||
|
||||
|
|
|
|||
|
|
@ -3,14 +3,40 @@ package handlers
|
|||
import (
|
||||
"Yimaru-Backend/internal/domain"
|
||||
"Yimaru-Backend/internal/web_server/response"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
const exportRequestTimeout = 10 * time.Minute
|
||||
|
||||
// exportRequestContext keeps DB work alive after the handler returns while the CSV body streams.
|
||||
func exportRequestContext(c *fiber.Ctx) context.Context {
|
||||
base := c.UserContext()
|
||||
if base == nil {
|
||||
base = context.Background()
|
||||
}
|
||||
ctx, _ := context.WithTimeout(context.WithoutCancel(base), exportRequestTimeout)
|
||||
return ctx
|
||||
}
|
||||
|
||||
func (h *Handler) csvStreamErrorLogger(resource string) func(error) {
|
||||
return func(err error) {
|
||||
h.logger.Error("csv export stream failed", "resource", resource, "error", err)
|
||||
if h.mongoLoggerSvc != nil {
|
||||
h.mongoLoggerSvc.Error("csv export stream failed",
|
||||
zap.String("resource", resource),
|
||||
zap.Error(err),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func csvOptionalString(p *string) string {
|
||||
if p == nil {
|
||||
return ""
|
||||
|
|
@ -81,10 +107,11 @@ func (h *Handler) ExportAdminPaymentsCSV(c *fiber.Ctx) error {
|
|||
"payment_method", "status", "paid_at", "expires_at", "created_at", "updated_at",
|
||||
}
|
||||
|
||||
ctx := c.Context()
|
||||
ctx := exportRequestContext(c)
|
||||
return response.StreamCSV(c, exportFilename("payments"), headers, func(offset, limit int32) ([][]string, error) {
|
||||
filter.Limit = limit
|
||||
filter.Offset = offset
|
||||
filter.SkipTotalCount = true
|
||||
page, err := h.chapaSvc.ListPaymentsAdmin(ctx, filter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
@ -116,7 +143,7 @@ func (h *Handler) ExportAdminPaymentsCSV(c *fiber.Ctx) error {
|
|||
}
|
||||
}
|
||||
return rows, nil
|
||||
})
|
||||
}, h.csvStreamErrorLogger("payments"))
|
||||
}
|
||||
|
||||
// ExportUsersCSV godoc
|
||||
|
|
@ -143,7 +170,7 @@ func (h *Handler) ExportUsersCSV(c *fiber.Ctx) error {
|
|||
"profile_completed", "created_at", "updated_at", "last_login",
|
||||
}
|
||||
|
||||
ctx := c.Context()
|
||||
ctx := exportRequestContext(c)
|
||||
batchSize := int32(response.ExportBatchSize)
|
||||
return response.StreamCSV(c, exportFilename("users"), headers, func(offset, limit int32) ([][]string, error) {
|
||||
filter.Page = int64(offset / batchSize)
|
||||
|
|
@ -194,7 +221,7 @@ func (h *Handler) ExportUsersCSV(c *fiber.Ctx) error {
|
|||
rows = rows[:limit]
|
||||
}
|
||||
return rows, nil
|
||||
})
|
||||
}, h.csvStreamErrorLogger("users"))
|
||||
}
|
||||
|
||||
// ExportActivityLogsCSV godoc
|
||||
|
|
@ -217,7 +244,7 @@ func (h *Handler) ExportActivityLogsCSV(c *fiber.Ctx) error {
|
|||
"ip_address", "user_agent", "created_at",
|
||||
}
|
||||
|
||||
ctx := c.Context()
|
||||
ctx := exportRequestContext(c)
|
||||
return response.StreamCSV(c, exportFilename("activity-logs"), headers, func(offset, limit int32) ([][]string, error) {
|
||||
filter.Limit = limit
|
||||
filter.Offset = offset
|
||||
|
|
@ -246,7 +273,7 @@ func (h *Handler) ExportActivityLogsCSV(c *fiber.Ctx) error {
|
|||
}
|
||||
}
|
||||
return rows, nil
|
||||
})
|
||||
}, h.csvStreamErrorLogger("activity-logs"))
|
||||
}
|
||||
|
||||
// ExportUserSubscriptionsCSV godoc
|
||||
|
|
@ -271,7 +298,7 @@ func (h *Handler) ExportUserSubscriptionsCSV(c *fiber.Ctx) error {
|
|||
"cancelled_at", "created_at", "updated_at",
|
||||
}
|
||||
|
||||
ctx := c.Context()
|
||||
ctx := exportRequestContext(c)
|
||||
return response.StreamCSV(c, exportFilename("subscriptions"), headers, func(offset, limit int32) ([][]string, error) {
|
||||
filter.Limit = limit
|
||||
filter.Offset = offset
|
||||
|
|
@ -307,7 +334,7 @@ func (h *Handler) ExportUserSubscriptionsCSV(c *fiber.Ctx) error {
|
|||
}
|
||||
}
|
||||
return rows, nil
|
||||
})
|
||||
}, h.csvStreamErrorLogger("subscriptions"))
|
||||
}
|
||||
|
||||
// ExportTeamMembersCSV godoc
|
||||
|
|
@ -317,7 +344,7 @@ func (h *Handler) ExportUserSubscriptionsCSV(c *fiber.Ctx) error {
|
|||
// @Router /api/v1/team/members/export [get]
|
||||
func (h *Handler) ExportTeamMembersCSV(c *fiber.Ctx) error {
|
||||
filter := parseTeamMemberListFilter(c)
|
||||
ctx := c.Context()
|
||||
ctx := exportRequestContext(c)
|
||||
|
||||
headers := []string{
|
||||
"id", "first_name", "last_name", "email", "phone_number",
|
||||
|
|
@ -342,7 +369,7 @@ func (h *Handler) ExportTeamMembersCSV(c *fiber.Ctx) error {
|
|||
return rows[:limit], nil
|
||||
}
|
||||
return rows, nil
|
||||
})
|
||||
}, h.csvStreamErrorLogger("team-members"))
|
||||
}
|
||||
|
||||
batchSize := int32(response.ExportBatchSize)
|
||||
|
|
@ -358,7 +385,7 @@ func (h *Handler) ExportTeamMembersCSV(c *fiber.Ctx) error {
|
|||
rows = rows[:limit]
|
||||
}
|
||||
return rows, nil
|
||||
})
|
||||
}, h.csvStreamErrorLogger("team-members"))
|
||||
}
|
||||
|
||||
func int32CSV(p *int32) string {
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import (
|
|||
"bufio"
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
|
@ -14,22 +15,46 @@ const (
|
|||
)
|
||||
|
||||
// StreamCSV writes a UTF-8 CSV attachment, fetching rows in batches until a batch is empty
|
||||
// or ExportMaxRows is reached.
|
||||
// or ExportMaxRows is reached. Flushes the header row immediately so reverse proxies (nginx)
|
||||
// receive bytes before the first DB batch completes.
|
||||
func StreamCSV(
|
||||
c *fiber.Ctx,
|
||||
filename string,
|
||||
headers []string,
|
||||
fetchBatch func(offset, limit int32) ([][]string, error),
|
||||
onError func(error),
|
||||
) error {
|
||||
c.Set("Content-Type", "text/csv; charset=utf-8")
|
||||
c.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename))
|
||||
|
||||
c.Context().SetBodyStreamWriter(func(w *bufio.Writer) {
|
||||
report := func(err error) {
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
if onError != nil {
|
||||
onError(err)
|
||||
return
|
||||
}
|
||||
slog.Error("csv export stream failed", "error", err, "path", c.Path())
|
||||
}
|
||||
|
||||
if _, err := w.Write([]byte{0xEF, 0xBB, 0xBF}); err != nil {
|
||||
report(err)
|
||||
return
|
||||
}
|
||||
writer := csv.NewWriter(w)
|
||||
if err := writer.Write(headers); err != nil {
|
||||
report(err)
|
||||
return
|
||||
}
|
||||
writer.Flush()
|
||||
if err := writer.Error(); err != nil {
|
||||
report(err)
|
||||
return
|
||||
}
|
||||
if err := w.Flush(); err != nil {
|
||||
report(err)
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -42,6 +67,7 @@ func StreamCSV(
|
|||
}
|
||||
rows, err := fetchBatch(offset, limit)
|
||||
if err != nil {
|
||||
report(err)
|
||||
return
|
||||
}
|
||||
if len(rows) == 0 {
|
||||
|
|
@ -49,14 +75,17 @@ func StreamCSV(
|
|||
}
|
||||
for _, row := range rows {
|
||||
if err := writer.Write(row); err != nil {
|
||||
report(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
writer.Flush()
|
||||
if err := writer.Error(); err != nil {
|
||||
report(err)
|
||||
return
|
||||
}
|
||||
if err := w.Flush(); err != nil {
|
||||
report(err)
|
||||
return
|
||||
}
|
||||
written += len(rows)
|
||||
|
|
|
|||
Loading…
Reference in New Issue
Block a user