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
30 changes: 30 additions & 0 deletions .github/scripts/prepare-image-usage-free-fast-red.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#!/usr/bin/env python3
"""Keep additive image receipt types available in the older Free Fast overlays.

Only extend exact historical DTO declarations. Never copy candidate billing or
snapshot producers: the original Free Fast business RED remains unchanged.
"""
import pathlib
import subprocess
import sys

phase, baseline = sys.argv[1:]
if phase == 'usage':
name = 'backend/internal/service/usage_log.go'
marker = 'type UsageLog struct {'
# Omit nil just as the pre-snapshot DTO did; persistence RED must reach
# its original missing-snapshot assertion, not a later JSON null mismatch.
addition = '\n\tCustomerCostDetails *CustomerCostDetails `json:"CustomerCostDetails,omitempty"`\n'
elif phase == 'cache':
name = 'backend/internal/service/customer_cost_details.go'
marker = 'type CustomerCostDetails struct {'
addition = '\n\tImageMinimumCharge float64 `json:"image_minimum_charge,omitempty"`\n\tImageMinimumChargeAdjustment float64 `json:"image_minimum_charge_adjustment,omitempty"`\n'
else:
raise SystemExit('unsupported overlay')
path = pathlib.Path(name)
old = subprocess.check_output(['git', 'show', f'{baseline}:{name}'])
assert path.read_bytes() == old, f'expected exact historical declaration: {name}'
assert old.count(marker.encode()) == 1
new = old.replace(marker.encode(), (marker + addition).encode(), 1)
path.write_bytes(new)
print(f'image receipt DTO compatibility phase={phase} baseline={baseline} path={name}; producers and selected tests unchanged')
9 changes: 9 additions & 0 deletions .github/scripts/upstream-v0222-red-fixtures.txt
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,12 @@ backend/internal/service/openai_relogin_settings_test.go
backend/internal/service/openai_subscription_long_context_test.go
backend/internal/service/openai_two_fa_login_test.go
backend/internal/service/upstream_batch_whitelist_identity_policy_test.go

# Image usage settlement fixtures need the candidate billing implementation.
backend/internal/handler/image_billing_response_test.go
backend/internal/service/image_usage_billing_test.go

# Account balance notifications require newer AccountOps APIs.
backend/internal/service/account_ops_balance_notification_test.go
backend/internal/service/grok_rate_limit_history_test.go
backend/internal/service/new_api_cost_test.go
4 changes: 4 additions & 0 deletions .github/workflows/free-fast-customer-cost-details.yml
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ jobs:
git show "$baseline:$file" > "$file"
test "$(git hash-object "$file")" = "$(git rev-parse "$baseline:$file")"
done
# The new image receipt reader needs the additive DTO field; retain
# the old Free Fast producer so the selected assertions still fail.
python3 .github/scripts/prepare-image-usage-free-fast-red.py usage "$baseline"
# Tests stay byte-for-byte at candidate HEAD. Keep the new additive
# DB column so a missing migration can never qualify as business RED.
set +e
Expand Down Expand Up @@ -120,6 +123,7 @@ jobs:
git fetch --no-tags --depth=1 origin "$baseline"
git show "$baseline:backend/internal/service/customer_cost_details.go" > backend/internal/service/customer_cost_details.go
test "$(git hash-object backend/internal/service/customer_cost_details.go)" = "$(git rev-parse "$baseline:backend/internal/service/customer_cost_details.go")"
python3 .github/scripts/prepare-image-usage-free-fast-red.py cache "$baseline"
set +e
(cd backend && go test -json -tags=unit ./internal/service -run '^TestFreeFastCustomerCostCachePrices$' -count=1 -timeout=15m) > "$RUNNER_TEMP/free-fast/red-cache.jsonl" 2>&1
code=$?
Expand Down
2 changes: 2 additions & 0 deletions backend/internal/handler/available_channel_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ type userAvailableGroup struct {

// userSupportedModelPricing 用户可见的定价字段白名单。
type userSupportedModelPricing struct {
ImageMinimumCharge *float64 `json:"image_minimum_charge,omitempty"`
BillingMode string `json:"billing_mode"`
InputPrice *float64 `json:"input_price"`
OutputPrice *float64 `json:"output_price"`
Expand Down Expand Up @@ -348,6 +349,7 @@ func toUserPricing(p *service.ChannelModelPricing) *userSupportedModelPricing {
billingMode = string(service.BillingModeToken)
}
return &userSupportedModelPricing{
ImageMinimumCharge: p.ImageMinimumCharge,
BillingMode: billingMode,
InputPrice: p.InputPrice,
OutputPrice: p.OutputPrice,
Expand Down
215 changes: 215 additions & 0 deletions backend/internal/handler/image_billing_response.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
package handler

import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"

"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
)

const imageBillingResponseLimit int64 = 64 << 20

// Opt-in settlement responses are spooled to a private temporary file. They
// cannot expose a successful image/usage event until the ledger commits. The
// upstream stream is still drained normally; only comment heartbeats go out early.
type imageBillingResponse struct {
gin.ResponseWriter
file *os.File
header http.Header
status, size int
stream bool
flushed bool
failure error
}

func newImageBillingResponse(writer gin.ResponseWriter, stream bool) (*imageBillingResponse, error) {
file, err := os.CreateTemp("", "sub2api-image-settlement-*")
if err != nil {
return nil, err
}
// Unlink on Unix while retaining the open descriptor: a process crash cannot
// leave generated images behind. Other platforms still remove it on close.
_ = os.Remove(file.Name())
return &imageBillingResponse{ResponseWriter: writer, file: file, header: writer.Header().Clone(), status: 200, size: -1, stream: stream}, nil
}
func (w *imageBillingResponse) Header() http.Header { return w.header }
func (w *imageBillingResponse) Status() int { return w.status }
func (w *imageBillingResponse) Size() int { return w.size }
func (w *imageBillingResponse) Written() bool { return w.size >= 0 }
func (w *imageBillingResponse) WriteHeader(code int) {
if !w.Written() {
w.status = code
}
}
func (w *imageBillingResponse) WriteHeaderNow() {
if w.size < 0 {
w.size = 0
}
}
func (w *imageBillingResponse) WriteString(s string) (int, error) { return w.Write([]byte(s)) }
func (w *imageBillingResponse) Write(b []byte) (int, error) {
w.WriteHeaderNow()
if int64(w.size)+int64(len(b)) > imageBillingResponseLimit {
w.failure = errors.New("image billing response exceeds 64 MiB")
return 0, w.failure
}
n, err := w.file.Write(b)
w.size += n
if err != nil {
w.failure = err
}
return n, err
}
func (w *imageBillingResponse) Flush() {
// Never expose a provisional amount or image as a successful completion.
if !w.stream {
return
}
w.ResponseWriter.Header().Set("Content-Type", "text/event-stream")
w.ResponseWriter.Header().Set("Cache-Control", "no-cache")
w.ResponseWriter.Header().Set("X-Accel-Buffering", "no")
_, _ = w.ResponseWriter.WriteString(": billing_pending\n\n")
w.ResponseWriter.Flush()
}
func (w *imageBillingResponse) close() { _ = w.file.Close(); _ = os.Remove(w.file.Name()) }
func (w *imageBillingResponse) commitHeaders() {
for k, v := range w.header {
w.ResponseWriter.Header()[k] = v
}
w.ResponseWriter.Header().Del("Content-Length")
w.ResponseWriter.Header().Del("ETag")
w.ResponseWriter.WriteHeader(w.status)
}
func (w *imageBillingResponse) passthrough() {
if w.flushed {
return
}
w.flushed = true
if w.status < http.StatusBadRequest {
w.errorResponse("image_billing_unavailable", "Image settlement was not confirmed; do not automatically retry")
return
}
if w.failure != nil {
w.errorResponse("image_response_unavailable", "Image response could not be retained")
return
}
w.commitHeaders()
_, _ = w.file.Seek(0, io.SeekStart)
_, _ = io.Copy(w.ResponseWriter, w.file)
w.ResponseWriter.Flush()
}
func (w *imageBillingResponse) errorResponse(code, message string) {
w.flushed = true
payload, _ := json.Marshal(gin.H{"error": gin.H{"type": "api_error", "code": code, "message": message}})
if w.stream {
w.ResponseWriter.Header().Set("Content-Type", "text/event-stream")
_, _ = fmt.Fprintf(w.ResponseWriter, "event: error\ndata: %s\n\n", payload)
} else {
w.ResponseWriter.Header().Set("Content-Type", "application/json")
w.ResponseWriter.WriteHeader(http.StatusServiceUnavailable)
_, _ = w.ResponseWriter.Write(payload)
}
w.ResponseWriter.Flush()
}
func imageEquivalentPayload(body []byte, receipt service.ImageBillingReceipt, includeUsage bool) ([]byte, error) {
var out map[string]json.RawMessage
if err := json.Unmarshal(body, &out); err != nil {
return nil, err
}
if out == nil {
return nil, errors.New("invalid image response")
}
delete(out, "billing")
delete(out, "upstream_usage")
if raw, ok := out["usage"]; ok {
out["upstream_usage"] = raw
delete(out, "usage")
}
if includeUsage {
tokens, err := receipt.EquivalentTokens()
if err != nil {
return nil, err
}
out["usage"], _ = json.Marshal(gin.H{"input_tokens": 0, "output_tokens": tokens, "total_tokens": tokens})
out["billing"], _ = json.Marshal(gin.H{"usage_kind": "billing_equivalent", "billing_mode": receipt.BillingMode, "actual_cost": receipt.ActualCost, "image_count": receipt.ImageCount, "output_price_per_million": service.ImageEquivalentOutputPricePerMillion, "minimum_charge": receipt.MinimumCharge, "minimum_charge_adjustment": receipt.MinimumChargeAdjustment})
}
return json.Marshal(out)
}
func (w *imageBillingResponse) settle(receipt service.ImageBillingReceipt) error {
if w.failure != nil {
return w.failure
}
if _, err := receipt.EquivalentTokens(); err != nil {
return err
}
_, _ = w.file.Seek(0, io.SeekStart)
body, err := io.ReadAll(io.LimitReader(w.file, imageBillingResponseLimit+1))
if err != nil {
return err
}
var out []byte
if !w.stream {
out, err = imageEquivalentPayload(body, receipt, true)
} else {
// Rewrite only JSON data events. Put the request total on the final image
// event exactly once, including multi-image and partial-success responses.
blocks := bytes.Split(bytes.ReplaceAll(body, []byte("\r\n"), []byte("\n")), []byte("\n\n"))
payloads := make([][]byte, len(blocks))
last := -1
for i, block := range blocks {
var data [][]byte
for _, line := range bytes.Split(block, []byte("\n")) {
if bytes.HasPrefix(line, []byte("data:")) {
data = append(data, bytes.TrimPrefix(bytes.TrimPrefix(line, []byte("data:")), []byte(" ")))
}
}
payload := bytes.Join(data, []byte("\n"))
var event map[string]json.RawMessage
if json.Unmarshal(payload, &event) != nil || event == nil {
continue
}
payloads[i] = payload
var kind string
_ = json.Unmarshal(event["type"], &kind)
if strings.HasSuffix(kind, ".completed") || event["b64_json"] != nil || event["url"] != nil || event["data"] != nil {
last = i
}
}
if last < 0 {
return errors.New("image stream has no completed image event")
}
for i, payload := range payloads {
if payload == nil {
continue
}
rewritten, e := imageEquivalentPayload(payload, receipt, i == last)
if e != nil {
return e
}
var lines [][]byte
for _, line := range bytes.Split(blocks[i], []byte("\n")) {
if !bytes.HasPrefix(line, []byte("data:")) {
lines = append(lines, line)
}
}
lines = append(lines, append([]byte("data: "), rewritten...))
blocks[i] = bytes.Join(lines, []byte("\n"))
}
out = bytes.Join(blocks, []byte("\n\n"))
}
if err != nil {
return err
}
w.flushed = true
w.commitHeaders()
_, err = w.ResponseWriter.Write(out)
w.ResponseWriter.Flush()
return err
}
89 changes: 89 additions & 0 deletions backend/internal/handler/image_billing_response_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
//go:build unit

package handler

import (
"encoding/json"
"github.com/Wei-Shaw/sub2api/internal/service"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"net/http/httptest"
"strings"
"testing"
)

func TestImageBillingPayloadPreservesRawUsage(t *testing.T) {
r := service.ImageBillingReceipt{Settled: true, ActualCost: .0201, BillingMode: "image", ImageCount: 2}
for _, raw := range []string{`{"data":[{"url":"https://example.invalid/image"}],"usage":{"input_tokens":9,"output_tokens":1200}}`, `{"data":[{"b64_json":"fixture"}]}`, `{"data":[],"usage":{"input_tokens":0,"output_tokens":0}}`} {
b, err := imageEquivalentPayload([]byte(raw), r, true)
require.NoError(t, err)
var x map[string]any
require.NoError(t, json.Unmarshal(b, &x))
u := x["usage"].(map[string]any)
require.Equal(t, float64(0), u["input_tokens"])
require.Equal(t, float64(2010000), u["output_tokens"])
require.Equal(t, "image", x["billing"].(map[string]any)["billing_mode"])
if strings.Contains(raw, `"usage"`) {
require.Contains(t, x, "upstream_usage")
}
}
}
func TestImageBillingStreamChargesOnlyFinalImageEvent(t *testing.T) {
gin.SetMode(gin.TestMode)
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
w, err := newImageBillingResponse(c.Writer, true)
require.NoError(t, err)
defer w.close()
raw := "event: image_generation.completed\ndata: {\"type\":\"image_generation.completed\",\"b64_json\":\"first\",\"usage\":{\"output_tokens\":100}}\n\nevent: image_generation.completed\ndata: {\"type\":\"image_generation.completed\",\"b64_json\":\"second\",\"usage\":{\"output_tokens\":200}}\n\ndata: [DONE]\n\n"
_, err = w.WriteString(raw)
require.NoError(t, err)
w.Flush()
require.NotContains(t, rec.Body.String(), "first")
require.NoError(t, w.settle(service.ImageBillingReceipt{Settled: true, ActualCost: .02, BillingMode: "image", ImageCount: 2}))
require.Equal(t, 1, strings.Count(rec.Body.String(), `"usage":`))
require.Equal(t, 2, strings.Count(rec.Body.String(), `"upstream_usage":`))
require.Contains(t, rec.Body.String(), `"output_tokens":2000000`)
require.Contains(t, rec.Body.String(), "[DONE]")
}
func TestImageBillingUnsettledResponseNeverExposesImage(t *testing.T) {
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
w, err := newImageBillingResponse(c.Writer, false)
require.NoError(t, err)
defer w.close()
_, err = w.WriteString(`{"data":[{"b64_json":"secret-result"}]}`)
require.NoError(t, err)
require.Error(t, w.settle(service.ImageBillingReceipt{ActualCost: .01}))
w.errorResponse("image_billing_unavailable", "not settled")
w.passthrough()
require.NotContains(t, rec.Body.String(), "secret-result")
require.Equal(t, 503, rec.Code)
}

func TestImageBillingEarlyReturnCannotLeakUnsettledSuccess(t *testing.T) {
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
w, err := newImageBillingResponse(c.Writer, false)
require.NoError(t, err)
defer w.close()
_, err = w.WriteString(`{"data":[{"b64_json":"unsettled-image"}]}`)
require.NoError(t, err)
w.passthrough()
require.Equal(t, 503, rec.Code)
require.NotContains(t, rec.Body.String(), "unsettled-image")
}

func TestImageBillingMultilineSSEReplacesUsageOnce(t *testing.T) {
rec := httptest.NewRecorder()
c, _ := gin.CreateTestContext(rec)
w, err := newImageBillingResponse(c.Writer, true)
require.NoError(t, err)
defer w.close()
_, err = w.WriteString("event: image_generation.completed\ndata: {\"type\":\"image_generation.completed\",\n" + "data: \"b64_json\":\"image\",\"usage\":{\"output_tokens\":100},\"billing\":{\"actual_cost\":999}}\n\n")
require.NoError(t, err)
require.NoError(t, w.settle(service.ImageBillingReceipt{Settled: true, ActualCost: .01, BillingMode: "token", ImageCount: 1}))
require.Equal(t, 1, strings.Count(rec.Body.String(), `"usage":`))
require.Contains(t, rec.Body.String(), `"output_tokens":1000000`)
require.NotContains(t, rec.Body.String(), "999")
}
5 changes: 5 additions & 0 deletions backend/internal/handler/openai_chat_completions.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ import (
// ChatCompletions handles OpenAI Chat Completions API requests.
// POST /v1/chat/completions
func (h *OpenAIGatewayHandler) ChatCompletions(c *gin.Context) {
if c.GetHeader("X-Image-Usage") != "" {
h.errorResponse(c, http.StatusBadRequest, "invalid_request_error", "X-Image-Usage is supported only by /v1/images/generations and /v1/images/edits")
return
}

streamStarted := false
defer h.recoverResponsesPanic(c, &streamStarted)

Expand Down
Loading
Loading