mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 08:05:12 +00:00
feat(accounts): 按账号自动同步上游分组名称与备注
This commit is contained in:
1 parent
a95c9e2631
commit
03aa05fd9f
26 files changed
+433
-162
No files matched your search
@@ -61,6 +61,7 @@ var schedulerNeutralExtraKeyPrefixes = []string{
|
||||
"passive_usage_",
|
||||
"upstream_billing_probe",
|
||||
"upstream_billing_rate_sync",
|
||||
"upstream_billing_group_sync",
|
||||
"ollama_cloud_usage",
|
||||
}
|
||||
|
||||
@@ -449,7 +450,7 @@ func (r *accountRepository) Update(ctx context.Context, account *service.Account
|
||||
if scoped := r.accountTransactionScope(ctx); scoped != r {
|
||||
return scoped.Update(ctx, account)
|
||||
}
|
||||
return r.updateAccount(ctx, account, nil, nil, account.RateMultiplier)
|
||||
return r.updateAccount(ctx, account, service.AccountBillingSettingsUpdate{RateMultiplier: account.RateMultiplier, SetName: true, SetNotes: true})
|
||||
}
|
||||
|
||||
// UpdateWithAccountBillingSettings applies an admin account edit while
|
||||
@@ -458,19 +459,15 @@ func (r *accountRepository) Update(ctx context.Context, account *service.Account
|
||||
func (r *accountRepository) UpdateWithAccountBillingSettings(
|
||||
ctx context.Context,
|
||||
account *service.Account,
|
||||
probeEnabled *bool,
|
||||
rateSyncEnabled *bool,
|
||||
rateMultiplier *float64,
|
||||
settings service.AccountBillingSettingsUpdate,
|
||||
) error {
|
||||
return r.updateAccount(ctx, account, probeEnabled, rateSyncEnabled, rateMultiplier)
|
||||
return r.updateAccount(ctx, account, settings)
|
||||
}
|
||||
|
||||
func (r *accountRepository) updateAccount(
|
||||
ctx context.Context,
|
||||
account *service.Account,
|
||||
explicitProbeEnabled *bool,
|
||||
explicitRateSyncEnabled *bool,
|
||||
explicitRateMultiplier *float64,
|
||||
settings service.AccountBillingSettingsUpdate,
|
||||
) error {
|
||||
if account == nil {
|
||||
return nil
|
||||
@@ -499,9 +496,7 @@ func (r *accountRepository) updateAccount(
|
||||
ctx,
|
||||
client,
|
||||
account,
|
||||
explicitProbeEnabled,
|
||||
explicitRateSyncEnabled,
|
||||
explicitRateMultiplier,
|
||||
settings,
|
||||
)
|
||||
if err != nil {
|
||||
return translatePersistenceError(err, service.ErrAccountNotFound, nil)
|
||||
@@ -528,11 +523,9 @@ func (r *accountRepository) updateLockedAccount(
|
||||
ctx context.Context,
|
||||
client *dbent.Client,
|
||||
account *service.Account,
|
||||
explicitProbeEnabled *bool,
|
||||
explicitRateSyncEnabled *bool,
|
||||
explicitRateMultiplier *float64,
|
||||
settings service.AccountBillingSettingsUpdate,
|
||||
) (*dbent.Account, error) {
|
||||
extra, err := lockAndMergeAccountProbeExtra(ctx, client, account, explicitProbeEnabled, explicitRateSyncEnabled)
|
||||
extra, err := lockAndMergeAccountProbeExtra(ctx, client, account, settings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -544,8 +537,6 @@ func (r *accountRepository) updateLockedAccount(
|
||||
}
|
||||
|
||||
builder := client.Account.UpdateOneID(account.ID).
|
||||
SetName(account.Name).
|
||||
SetNillableNotes(account.Notes).
|
||||
SetPlatform(account.Platform).
|
||||
SetType(account.Type).
|
||||
SetCredentials(normalizeJSONMap(account.Credentials)).
|
||||
@@ -557,8 +548,18 @@ func (r *accountRepository) updateLockedAccount(
|
||||
SetSchedulable(schedulable).
|
||||
SetAutoPauseOnExpired(account.AutoPauseOnExpired)
|
||||
|
||||
if explicitRateMultiplier != nil {
|
||||
builder.SetRateMultiplier(*explicitRateMultiplier)
|
||||
if settings.SetName {
|
||||
builder.SetName(account.Name)
|
||||
}
|
||||
if settings.SetNotes {
|
||||
if account.Notes == nil {
|
||||
builder.ClearNotes()
|
||||
} else {
|
||||
builder.SetNotes(*account.Notes)
|
||||
}
|
||||
}
|
||||
if settings.RateMultiplier != nil {
|
||||
builder.SetRateMultiplier(*settings.RateMultiplier)
|
||||
}
|
||||
if account.LoadFactor != nil {
|
||||
builder.SetLoadFactor(*account.LoadFactor)
|
||||
@@ -611,10 +612,6 @@ func (r *accountRepository) updateLockedAccount(
|
||||
} else {
|
||||
builder.ClearSessionWindowStatus()
|
||||
}
|
||||
if account.Notes == nil {
|
||||
builder.ClearNotes()
|
||||
}
|
||||
|
||||
builder.SetQuotaDimension(dbaccount.QuotaDimension(account.QuotaDimensionOrDefault()))
|
||||
builder.SetNillableParentAccountID(account.ParentAccountID)
|
||||
|
||||
@@ -625,8 +622,7 @@ func lockAndMergeAccountProbeExtra(
|
||||
ctx context.Context,
|
||||
client *dbent.Client,
|
||||
account *service.Account,
|
||||
explicitProbeEnabled *bool,
|
||||
explicitRateSyncEnabled *bool,
|
||||
settings service.AccountBillingSettingsUpdate,
|
||||
) (map[string]any, error) {
|
||||
credentials, err := json.Marshal(normalizeJSONMap(account.Credentials))
|
||||
if err != nil {
|
||||
@@ -682,7 +678,8 @@ func lockAndMergeAccountProbeExtra(
|
||||
extra -> 'opencode_go_usage_auto_refresh',
|
||||
extra -> 'opencode_go_usage_snapshot',
|
||||
extra -> 'grok_observed_models',
|
||||
extra -> 'upstream_model_metadata'
|
||||
extra -> 'upstream_model_metadata',
|
||||
extra -> 'upstream_billing_group_sync_enabled'
|
||||
FROM accounts
|
||||
WHERE id = $1 AND deleted_at IS NULL
|
||||
FOR NO KEY UPDATE
|
||||
@@ -705,6 +702,7 @@ func lockAndMergeAccountProbeExtra(
|
||||
opencodeGroupIdentityUnchanged bool
|
||||
currentEnabled []byte
|
||||
currentRateSyncEnabled []byte
|
||||
currentGroupSyncEnabled []byte
|
||||
currentSnapshot []byte
|
||||
currentOllamaSession []byte
|
||||
currentOllamaAutoRefresh []byte
|
||||
@@ -729,6 +727,7 @@ func lockAndMergeAccountProbeExtra(
|
||||
¤tOpenCodeSnapshot,
|
||||
¤tGrokObservedModels,
|
||||
¤tUpstreamModelMetadata,
|
||||
¤tGroupSyncEnabled,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -740,6 +739,7 @@ func lockAndMergeAccountProbeExtra(
|
||||
for _, key := range []string{
|
||||
service.UpstreamBillingProbeEnabledExtraKey,
|
||||
service.UpstreamBillingRateSyncEnabledExtraKey,
|
||||
service.UpstreamBillingGroupSyncEnabledExtraKey,
|
||||
service.UpstreamBillingProbeExtraKey,
|
||||
service.OllamaCloudUsageSessionExtraKey,
|
||||
service.OllamaCloudUsageAutoRefreshExtraKey,
|
||||
@@ -759,40 +759,32 @@ func lockAndMergeAccountProbeExtra(
|
||||
probeEnabled = value
|
||||
probeEnabledPresent = true
|
||||
}
|
||||
if explicitProbeEnabled != nil {
|
||||
probeEnabled = *explicitProbeEnabled
|
||||
if settings.ProbeEnabled != nil {
|
||||
probeEnabled = *settings.ProbeEnabled
|
||||
probeEnabledPresent = true
|
||||
}
|
||||
}
|
||||
rateSyncEnabled := false
|
||||
rateSyncEnabledPresent := false
|
||||
if probeAccount {
|
||||
if enabled, ok, err := decodeAccountExtraJSON(currentRateSyncEnabled); err != nil {
|
||||
return nil, err
|
||||
} else if value, isBool := enabled.(bool); ok && isBool {
|
||||
rateSyncEnabled = value
|
||||
rateSyncEnabledPresent = true
|
||||
}
|
||||
if explicitRateSyncEnabled != nil {
|
||||
rateSyncEnabled = *explicitRateSyncEnabled
|
||||
rateSyncEnabledPresent = true
|
||||
}
|
||||
if explicitProbeEnabled != nil && !*explicitProbeEnabled {
|
||||
rateSyncEnabled = false
|
||||
rateSyncEnabledPresent = true
|
||||
}
|
||||
// 同步依赖探测,方向是单向的:探测关闭(或探测键缺失)一律把同步归零。
|
||||
// 不做反向推导——由 rate_sync=true 推出 probe=true 会让一条"同步开、探测键
|
||||
// 缺失"的僵尸记录在任意一次无关编辑时静默打开周期性外呼。需要同时打开两个
|
||||
// 开关的调用方(管理端编辑)自己显式传 explicitProbeEnabled=true。
|
||||
if !probeEnabled {
|
||||
rateSyncEnabled = false
|
||||
}
|
||||
if probeEnabledPresent {
|
||||
extra[service.UpstreamBillingProbeEnabledExtraKey] = probeEnabled
|
||||
}
|
||||
if rateSyncEnabledPresent {
|
||||
extra[service.UpstreamBillingRateSyncEnabledExtraKey] = rateSyncEnabled
|
||||
for _, flag := range []struct {
|
||||
key string
|
||||
stored []byte
|
||||
requested *bool
|
||||
}{
|
||||
{service.UpstreamBillingRateSyncEnabledExtraKey, currentRateSyncEnabled, settings.RateSyncEnabled},
|
||||
{service.UpstreamBillingGroupSyncEnabledExtraKey, currentGroupSyncEnabled, settings.GroupSyncEnabled},
|
||||
} {
|
||||
value, _, err := decodeAccountExtraJSON(flag.stored)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
enabled, present := value.(bool)
|
||||
if flag.requested != nil {
|
||||
enabled, present = *flag.requested, true
|
||||
}
|
||||
if present || (settings.ProbeEnabled != nil && !*settings.ProbeEnabled) {
|
||||
extra[flag.key] = probeEnabled && enabled
|
||||
}
|
||||
}
|
||||
}
|
||||
probeExplicitlyDisabled := probeEnabledPresent && !probeEnabled
|
||||
@@ -2973,24 +2965,26 @@ func (r *accountRepository) UpdateUpstreamBillingProbeSnapshot(
|
||||
account *service.Account,
|
||||
snapshot *service.UpstreamBillingProbeSnapshot,
|
||||
rateMultiplier *float64,
|
||||
group service.BillingGroupInfo,
|
||||
) error {
|
||||
if account == nil || snapshot == nil {
|
||||
return service.ErrAccountNilInput
|
||||
}
|
||||
if snapshot.Status != service.UpstreamBillingProbeStatusOK {
|
||||
rateMultiplier = nil
|
||||
group = service.BillingGroupInfo{}
|
||||
}
|
||||
if dbent.TxFromContext(ctx) == nil {
|
||||
tx, err := r.client.Tx(ctx)
|
||||
if errors.Is(err, dbent.ErrTxStarted) {
|
||||
return r.updateUpstreamBillingProbeSnapshotInTx(ctx, account, snapshot, rateMultiplier)
|
||||
return r.updateUpstreamBillingProbeSnapshotInTx(ctx, account, snapshot, rateMultiplier, group)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
if err := r.updateUpstreamBillingProbeSnapshotInTx(dbent.NewTxContext(ctx, tx), account, snapshot, rateMultiplier); err != nil {
|
||||
if err := r.updateUpstreamBillingProbeSnapshotInTx(dbent.NewTxContext(ctx, tx), account, snapshot, rateMultiplier, group); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
@@ -3001,7 +2995,7 @@ func (r *accountRepository) UpdateUpstreamBillingProbeSnapshot(
|
||||
r.syncSchedulerAccountSnapshot(ctx, account.ID)
|
||||
return nil
|
||||
}
|
||||
return r.updateUpstreamBillingProbeSnapshotInTx(ctx, account, snapshot, rateMultiplier)
|
||||
return r.updateUpstreamBillingProbeSnapshotInTx(ctx, account, snapshot, rateMultiplier, group)
|
||||
}
|
||||
|
||||
func (r *accountRepository) updateUpstreamBillingProbeSnapshotInTx(
|
||||
@@ -3009,6 +3003,7 @@ func (r *accountRepository) updateUpstreamBillingProbeSnapshotInTx(
|
||||
account *service.Account,
|
||||
snapshot *service.UpstreamBillingProbeSnapshot,
|
||||
rateMultiplier *float64,
|
||||
group service.BillingGroupInfo,
|
||||
) error {
|
||||
payload, err := json.Marshal(map[string]any{service.UpstreamBillingProbeExtraKey: snapshot})
|
||||
if err != nil {
|
||||
@@ -3065,6 +3060,10 @@ func (r *accountRepository) updateUpstreamBillingProbeSnapshotInTx(
|
||||
THEN $10::numeric
|
||||
ELSE rate_multiplier
|
||||
END,
|
||||
name = CASE WHEN extra @> '{"upstream_billing_group_sync_enabled": true, "upstream_billing_probe_enabled": true}'::jsonb
|
||||
THEN COALESCE(NULLIF($11, ''), name) ELSE name END,
|
||||
notes = CASE WHEN extra @> '{"upstream_billing_group_sync_enabled": true, "upstream_billing_probe_enabled": true}'::jsonb
|
||||
THEN COALESCE(NULLIF($12, ''), notes) ELSE notes END,
|
||||
updated_at = NOW()
|
||||
WHERE id = $2
|
||||
AND platform = $3
|
||||
@@ -3075,7 +3074,7 @@ func (r *accountRepository) updateUpstreamBillingProbeSnapshotInTx(
|
||||
AND COALESCE(extra -> 'upstream_billing_probe_enabled', 'null'::jsonb) = $8::jsonb
|
||||
AND COALESCE(extra -> 'upstream_billing_rate_sync_enabled', 'null'::jsonb) = $9::jsonb
|
||||
AND deleted_at IS NULL
|
||||
`, string(payload), account.ID, account.Platform, account.Type, string(credentials), proxyID, string(expectedSnapshotJSON), string(expectedEnabledJSON), string(expectedRateSyncEnabledJSON), rateMultiplier)
|
||||
`, string(payload), account.ID, account.Platform, account.Type, string(credentials), proxyID, string(expectedSnapshotJSON), string(expectedEnabledJSON), string(expectedRateSyncEnabledJSON), rateMultiplier, group.Name, group.Description)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -142,8 +142,8 @@ func TestLockAndMergeAccountProbeExtraKeepsLatestGrokManagedKeys(t *testing.T) {
|
||||
"enabled", "rate_sync_enabled", "snapshot",
|
||||
"ollama_session", "ollama_auto", "ollama_snapshot",
|
||||
"opencode_group_unchanged", "opencode_auto", "opencode_snapshot",
|
||||
"grok_observed_models", "upstream_model_metadata",
|
||||
}).AddRow(false, false, true, nil, nil, nil, nil, nil, nil, false, nil, nil, tt.databaseModels, tt.databaseMetadata))
|
||||
"grok_observed_models", "upstream_model_metadata", "group_sync_enabled",
|
||||
}).AddRow(false, false, true, nil, nil, nil, nil, nil, nil, false, nil, nil, tt.databaseModels, tt.databaseMetadata, nil))
|
||||
|
||||
account := &service.Account{
|
||||
ID: 41,
|
||||
@@ -152,7 +152,7 @@ func TestLockAndMergeAccountProbeExtraKeepsLatestGrokManagedKeys(t *testing.T) {
|
||||
Credentials: tt.credentials,
|
||||
Extra: tt.inputExtra,
|
||||
}
|
||||
got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, nil, nil)
|
||||
got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, service.AccountBillingSettingsUpdate{})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "from-form", got["note"])
|
||||
if tt.wantModels == nil {
|
||||
|
||||
@@ -229,7 +229,7 @@ func TestLockAndMergeAccountProbeExtraCoalescesNullableOllamaGroupIdentity(t *te
|
||||
loaded, err := newAccountRepositoryWithSQL(tx.Client(), tx, nil).GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
merged, err := lockAndMergeAccountProbeExtra(ctx, tx.Client(), loaded, nil, nil)
|
||||
merged, err := lockAndMergeAccountProbeExtra(ctx, tx.Client(), loaded, service.AccountBillingSettingsUpdate{})
|
||||
|
||||
require.NoError(t, err, "a NULL Ollama eligibility expression must scan as false")
|
||||
require.NotContains(t, merged, service.OllamaCloudUsageSessionExtraKey)
|
||||
@@ -421,7 +421,7 @@ func TestOllamaCloudUsageEligibilityExtendsToCNOpenAICompatPlatforms(t *testing.
|
||||
// lockAndMerge 组身份守卫:CN 行凭证未变时必须保留 ollama 托管键。
|
||||
kimiLoaded, err := repo.GetByID(ctx, kimi.ID)
|
||||
require.NoError(t, err)
|
||||
merged, err := lockAndMergeAccountProbeExtra(ctx, tx.Client(), kimiLoaded, nil, nil)
|
||||
merged, err := lockAndMergeAccountProbeExtra(ctx, tx.Client(), kimiLoaded, service.AccountBillingSettingsUpdate{})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "cipher:cn-shared", merged[service.OllamaCloudUsageSessionExtraKey])
|
||||
require.Equal(t, true, merged[service.OllamaCloudUsageAutoRefreshExtraKey])
|
||||
|
||||
@@ -76,7 +76,7 @@ func openCodeGoMergeMockColumns() []string {
|
||||
"enabled", "rate_sync_enabled", "snapshot",
|
||||
"ollama_session", "ollama_auto", "ollama_snapshot",
|
||||
"opencode_group_unchanged", "opencode_auto", "opencode_snapshot",
|
||||
"grok_observed_models", "upstream_model_metadata",
|
||||
"grok_observed_models", "upstream_model_metadata", "group_sync_enabled",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,9 +189,9 @@ func TestLockAndMergeAccountProbeExtraPreservesOpenCodeGoManagedState(t *testing
|
||||
mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")).
|
||||
WithArgs(tt.account.ID, tt.account.Platform, tt.account.Type, string(credentials), nil).
|
||||
WillReturnRows(sqlmock.NewRows(openCodeGoMergeMockColumns()).
|
||||
AddRow(false, false, tt.proxyUnchanged, nil, nil, nil, nil, nil, nil, tt.groupUnchanged, tt.databaseAuto, tt.databaseSnapshot, nil, nil))
|
||||
AddRow(false, false, tt.proxyUnchanged, nil, nil, nil, nil, nil, nil, tt.groupUnchanged, tt.databaseAuto, tt.databaseSnapshot, nil, nil, nil))
|
||||
|
||||
got, err := lockAndMergeAccountProbeExtra(context.Background(), client, tt.account, nil, nil)
|
||||
got, err := lockAndMergeAccountProbeExtra(context.Background(), client, tt.account, service.AccountBillingSettingsUpdate{})
|
||||
require.NoError(t, err)
|
||||
if tt.wantAuto == nil {
|
||||
require.NotContains(t, got, service.OpenCodeGoUsageAutoRefreshExtraKey)
|
||||
|
||||
@@ -42,7 +42,7 @@ func TestUpdateUpstreamBillingProbeSnapshotRequiresSameIdentityAndSnapshot(t *te
|
||||
WillReturnRows(sqlmock.NewRows([]string{"protocol", "host", "port", "username", "password", "status"}).
|
||||
AddRow("http", "127.0.0.1", 3128, "user", "pass", service.StatusActive))
|
||||
mock.ExpectExec(`(?s)`+regexp.QuoteMeta("UPDATE accounts")+`.*`+regexp.QuoteMeta("WHERE id = $2")+`.*`+regexp.QuoteMeta("AND platform = $3")+`.*`+regexp.QuoteMeta("AND type = $4")+`.*`+regexp.QuoteMeta("AND credentials = $5::jsonb")+`.*`+regexp.QuoteMeta("AND proxy_id IS NOT DISTINCT FROM $6")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_probe', 'null'::jsonb) = $7::jsonb")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_probe_enabled', 'null'::jsonb) = $8::jsonb")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_rate_sync_enabled', 'null'::jsonb) = $9::jsonb")).
|
||||
WithArgs(sqlmock.AnyArg(), int64(17), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test","base_url":"http://127.0.0.1:8080"}`, int64(9), `{"status":"stale"}`, "null", "null", nil).
|
||||
WithArgs(sqlmock.AnyArg(), int64(17), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test","base_url":"http://127.0.0.1:8080"}`, int64(9), `{"status":"stale"}`, "null", "null", nil, "", "").
|
||||
WillReturnResult(sqlmock.NewResult(0, tt.affected))
|
||||
if tt.affected > 0 {
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")).
|
||||
@@ -75,7 +75,7 @@ func TestUpdateUpstreamBillingProbeSnapshotRequiresSameIdentityAndSnapshot(t *te
|
||||
}
|
||||
|
||||
txCtx := dbent.NewTxContext(context.Background(), tx)
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(txCtx, account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK}, nil)
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(txCtx, account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK}, nil, service.BillingGroupInfo{})
|
||||
|
||||
if tt.wantErr != nil {
|
||||
require.ErrorIs(t, err, tt.wantErr)
|
||||
@@ -99,7 +99,7 @@ func TestUpdateUpstreamBillingProbeSnapshotCommitsSnapshotAndOutboxAtomically(t
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec(`(?s)`+regexp.QuoteMeta("UPDATE accounts")+`.*`+regexp.QuoteMeta("rate_multiplier = CASE")+`.*`+regexp.QuoteMeta("THEN $10::numeric")+`.*`+regexp.QuoteMeta("AND credentials = $5::jsonb")+`.*`+regexp.QuoteMeta("AND proxy_id IS NOT DISTINCT FROM $6")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_probe', 'null'::jsonb) = $7::jsonb")).
|
||||
WithArgs(sqlmock.AnyArg(), int64(17), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil, "null", "true", "true", 0.065).
|
||||
WithArgs(sqlmock.AnyArg(), int64(17), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil, "null", "true", "true", 0.065, "", "").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")).
|
||||
WithArgs(service.SchedulerOutboxEventAccountChanged, int64(17), nil, nil, sqlmock.AnyArg()).
|
||||
@@ -124,6 +124,7 @@ func TestUpdateUpstreamBillingProbeSnapshotCommitsSnapshotAndOutboxAtomically(t
|
||||
account,
|
||||
&service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK},
|
||||
&rateMultiplier,
|
||||
service.BillingGroupInfo{},
|
||||
)
|
||||
|
||||
require.NoError(t, err)
|
||||
@@ -158,7 +159,7 @@ func TestUpdateUpstreamBillingProbeSnapshotRejectsChangedProxyIdentity(t *testin
|
||||
},
|
||||
}
|
||||
repo := newAccountRepositoryWithSQL(client, db, nil)
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(dbent.NewTxContext(context.Background(), tx), account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK}, nil)
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(dbent.NewTxContext(context.Background(), tx), account, &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK}, nil, service.BillingGroupInfo{})
|
||||
|
||||
require.ErrorIs(t, err, service.ErrUpstreamBillingProbeIdentityChanged)
|
||||
mock.ExpectRollback()
|
||||
@@ -176,7 +177,7 @@ func TestUpdateUpstreamBillingProbeSnapshotRollsBackWhenOutboxFails(t *testing.T
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec(`(?s)`+regexp.QuoteMeta("UPDATE accounts")+`.*`+regexp.QuoteMeta("AND proxy_id IS NOT DISTINCT FROM $6")+`.*`+regexp.QuoteMeta("COALESCE(extra -> 'upstream_billing_probe', 'null'::jsonb) = $7::jsonb")).
|
||||
WithArgs(sqlmock.AnyArg(), int64(18), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil, "null", "true", "true", 0.7).
|
||||
WithArgs(sqlmock.AnyArg(), int64(18), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil, "null", "true", "true", 0.7, "", "").
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectExec(regexp.QuoteMeta("INSERT INTO scheduler_outbox")).WillReturnError(errors.New("outbox failed"))
|
||||
mock.ExpectRollback()
|
||||
@@ -199,6 +200,7 @@ func TestUpdateUpstreamBillingProbeSnapshotRollsBackWhenOutboxFails(t *testing.T
|
||||
account,
|
||||
&service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK},
|
||||
&rateMultiplier,
|
||||
service.BillingGroupInfo{},
|
||||
)
|
||||
|
||||
require.EqualError(t, err, "outbox failed")
|
||||
|
||||
@@ -81,8 +81,8 @@ func TestLockAndMergeAccountProbeExtraUsesCurrentDatabaseSnapshot(t *testing.T)
|
||||
|
||||
mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")).
|
||||
WithArgs(int64(27), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}).
|
||||
AddRow(tt.identityUnchanged, false, true, tt.databaseEnabled, nil, tt.databaseSnapshot, nil, nil, nil, false, nil, nil, nil, nil))
|
||||
WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata", "group_sync_enabled"}).
|
||||
AddRow(tt.identityUnchanged, false, true, tt.databaseEnabled, nil, tt.databaseSnapshot, nil, nil, nil, false, nil, nil, nil, nil, nil))
|
||||
|
||||
account := &service.Account{
|
||||
ID: 27,
|
||||
@@ -91,7 +91,7 @@ func TestLockAndMergeAccountProbeExtraUsesCurrentDatabaseSnapshot(t *testing.T)
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
Extra: tt.inputExtra,
|
||||
}
|
||||
got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, nil, nil)
|
||||
got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, service.AccountBillingSettingsUpdate{})
|
||||
require.NoError(t, err)
|
||||
if tt.wantSnapshot == nil {
|
||||
require.NotContains(t, got, service.UpstreamBillingProbeExtraKey)
|
||||
@@ -172,8 +172,8 @@ func TestLockAndMergeAccountProbeExtraNeverInfersProbeFromRateSync(t *testing.T)
|
||||
|
||||
mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")).
|
||||
WithArgs(int64(31), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}).
|
||||
AddRow(true, false, true, tt.databaseEnabled, tt.databaseRateSync, nil, nil, nil, nil, false, nil, nil, nil, nil))
|
||||
WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata", "group_sync_enabled"}).
|
||||
AddRow(true, false, true, tt.databaseEnabled, tt.databaseRateSync, nil, nil, nil, nil, false, nil, nil, nil, nil, nil))
|
||||
|
||||
account := &service.Account{
|
||||
ID: 31,
|
||||
@@ -182,7 +182,7 @@ func TestLockAndMergeAccountProbeExtraNeverInfersProbeFromRateSync(t *testing.T)
|
||||
Credentials: map[string]any{"api_key": "sk-test"},
|
||||
}
|
||||
got, err := lockAndMergeAccountProbeExtra(
|
||||
context.Background(), client, account, tt.explicitProbeEnabled, tt.explicitRateSync,
|
||||
context.Background(), client, account, service.AccountBillingSettingsUpdate{ProbeEnabled: tt.explicitProbeEnabled, RateSyncEnabled: tt.explicitRateSync},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
if tt.wantEnabled == nil {
|
||||
@@ -211,8 +211,8 @@ func TestLockAndMergeAccountProbeExtraProtectsOllamaManagedFields(t *testing.T)
|
||||
|
||||
mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")).
|
||||
WithArgs(int64(29), service.PlatformAnthropic, service.AccountTypeAPIKey, `{"api_key":"key","base_url":"https://ollama.com"}`, nil).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}).
|
||||
AddRow(identityUnchanged, identityUnchanged, true, nil, nil, nil, []byte(`"local-ciphertext"`), []byte(`true`), []byte(`{"status":"ok"}`), false, nil, nil, nil, nil))
|
||||
WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata", "group_sync_enabled"}).
|
||||
AddRow(identityUnchanged, identityUnchanged, true, nil, nil, nil, []byte(`"local-ciphertext"`), []byte(`true`), []byte(`{"status":"ok"}`), false, nil, nil, nil, nil, nil))
|
||||
|
||||
account := &service.Account{
|
||||
ID: 29, Platform: service.PlatformAnthropic, Type: service.AccountTypeAPIKey,
|
||||
@@ -223,7 +223,7 @@ func TestLockAndMergeAccountProbeExtraProtectsOllamaManagedFields(t *testing.T)
|
||||
service.OllamaCloudUsageSnapshotExtraKey: map[string]any{"status": "forged"},
|
||||
},
|
||||
}
|
||||
got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, nil, nil)
|
||||
got, err := lockAndMergeAccountProbeExtra(context.Background(), client, account, service.AccountBillingSettingsUpdate{})
|
||||
require.NoError(t, err)
|
||||
if identityUnchanged {
|
||||
require.Equal(t, "local-ciphertext", got[service.OllamaCloudUsageSessionExtraKey])
|
||||
@@ -371,8 +371,8 @@ func TestUpdateWithAccountBillingSettingsRollsBackWhenOutboxFails(t *testing.T)
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectQuery(`(?s)`+regexp.QuoteMeta("SELECT")+`.*`+regexp.QuoteMeta("FOR NO KEY UPDATE")).
|
||||
WithArgs(int64(27), service.PlatformOpenAI, service.AccountTypeAPIKey, `{"api_key":"sk-test"}`, nil).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata"}).
|
||||
AddRow(true, false, true, []byte(`true`), []byte(`true`), []byte(`{"status":"ok"}`), nil, nil, nil, false, nil, nil, nil, nil))
|
||||
WillReturnRows(sqlmock.NewRows([]string{"identity_unchanged", "ollama_group_unchanged", "ollama_proxy_unchanged", "enabled", "rate_sync_enabled", "snapshot", "ollama_session", "ollama_auto", "ollama_snapshot", "opencode_group_unchanged", "opencode_auto", "opencode_snapshot", "grok_observed_models", "upstream_model_metadata", "group_sync_enabled"}).
|
||||
AddRow(true, false, true, []byte(`true`), []byte(`true`), []byte(`{"status":"ok"}`), nil, nil, nil, false, nil, nil, nil, nil, nil))
|
||||
mock.ExpectExec(`(?s)UPDATE .*accounts.*SET.*WHERE .*id.*`).
|
||||
WillReturnResult(sqlmock.NewResult(0, 1))
|
||||
mock.ExpectQuery(`(?s)SELECT .* FROM "accounts" WHERE "id" = \$1`).
|
||||
@@ -398,7 +398,7 @@ func TestUpdateWithAccountBillingSettingsRollsBackWhenOutboxFails(t *testing.T)
|
||||
}
|
||||
|
||||
probeDisabled := false
|
||||
err = repo.UpdateWithAccountBillingSettings(context.Background(), account, &probeDisabled, nil, nil)
|
||||
err = repo.UpdateWithAccountBillingSettings(context.Background(), account, service.AccountBillingSettingsUpdate{ProbeEnabled: &probeDisabled})
|
||||
|
||||
require.EqualError(t, err, "outbox failed")
|
||||
require.Equal(t, false, account.Extra[service.UpstreamBillingProbeEnabledExtraKey])
|
||||
|
||||
+44
-11
@@ -30,7 +30,7 @@ func TestAccountUpdatePreservesConcurrentProbeSnapshot(t *testing.T) {
|
||||
require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, stale, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}, nil))
|
||||
}, nil, service.BillingGroupInfo{}))
|
||||
|
||||
stale.Name = "ordinary-edit"
|
||||
require.NoError(t, repo.Update(ctx, stale))
|
||||
@@ -72,10 +72,10 @@ func TestAdminAccountEditPreservesRateSynchronizedAfterLoad(t *testing.T) {
|
||||
require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, probeAccount, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}, &synchronizedRate))
|
||||
}, &synchronizedRate, service.BillingGroupInfo{}))
|
||||
|
||||
staleAdminEdit.Name = "name-only-edit"
|
||||
require.NoError(t, repo.UpdateWithAccountBillingSettings(ctx, staleAdminEdit, nil, nil, nil))
|
||||
require.NoError(t, repo.UpdateWithAccountBillingSettings(ctx, staleAdminEdit, service.AccountBillingSettingsUpdate{SetName: true}))
|
||||
|
||||
got, err := repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
@@ -107,7 +107,7 @@ func TestProbeSnapshotSyncsRateOnlyForSuccessfulEnabledAccount(t *testing.T) {
|
||||
require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, loaded, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}, &syncedRate))
|
||||
}, &syncedRate, service.BillingGroupInfo{}))
|
||||
|
||||
got, err := repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
@@ -118,7 +118,7 @@ func TestProbeSnapshotSyncsRateOnlyForSuccessfulEnabledAccount(t *testing.T) {
|
||||
require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, got, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusFailed,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}, &failedRate))
|
||||
}, &failedRate, service.BillingGroupInfo{}))
|
||||
got, err = repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.RateMultiplier)
|
||||
@@ -133,7 +133,7 @@ func TestProbeSnapshotSyncsRateOnlyForSuccessfulEnabledAccount(t *testing.T) {
|
||||
require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, manual, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}, &manualProbeRate))
|
||||
}, &manualProbeRate, service.BillingGroupInfo{}))
|
||||
got, err = repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.RateMultiplier)
|
||||
@@ -148,7 +148,7 @@ func TestProbeSnapshotSyncsRateOnlyForSuccessfulEnabledAccount(t *testing.T) {
|
||||
require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, disabled, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}, &manualProbeRate))
|
||||
}, &manualProbeRate, service.BillingGroupInfo{}))
|
||||
got, err = repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, got.RateMultiplier)
|
||||
@@ -275,7 +275,7 @@ func TestProbeSnapshotCASIncludesLoadedEnabledState(t *testing.T) {
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(ctx, inFlight, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}, nil)
|
||||
}, nil, service.BillingGroupInfo{})
|
||||
if tt.wantConflict {
|
||||
require.ErrorIs(t, err, service.ErrUpstreamBillingProbeIdentityChanged)
|
||||
} else {
|
||||
@@ -315,13 +315,13 @@ func TestProbeSnapshotCASProtectsManualRateAfterSyncDisabled(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
manualRate := 0.8
|
||||
syncDisabled := false
|
||||
require.NoError(t, repo.UpdateWithAccountBillingSettings(ctx, manual, nil, &syncDisabled, &manualRate))
|
||||
require.NoError(t, repo.UpdateWithAccountBillingSettings(ctx, manual, service.AccountBillingSettingsUpdate{RateSyncEnabled: &syncDisabled, RateMultiplier: &manualRate}))
|
||||
|
||||
probedRate := 0.1
|
||||
err = repo.UpdateUpstreamBillingProbeSnapshot(ctx, inFlight, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}, &probedRate)
|
||||
}, &probedRate, service.BillingGroupInfo{})
|
||||
require.ErrorIs(t, err, service.ErrUpstreamBillingProbeIdentityChanged)
|
||||
|
||||
got, err := repo.GetByID(ctx, account.ID)
|
||||
@@ -398,7 +398,7 @@ func TestProxyIdentityUpdateInvalidatesProbeAndRejectsInFlightSnapshot(t *testin
|
||||
err = accountRepo.UpdateUpstreamBillingProbeSnapshot(ctx, inFlight, &service.UpstreamBillingProbeSnapshot{
|
||||
Status: service.UpstreamBillingProbeStatusOK,
|
||||
LastAttemptAt: time.Now().UTC(),
|
||||
}, nil)
|
||||
}, nil, service.BillingGroupInfo{})
|
||||
require.ErrorIs(t, err, service.ErrUpstreamBillingProbeIdentityChanged)
|
||||
|
||||
rows, err := tx.QueryContext(ctx, `
|
||||
@@ -542,3 +542,36 @@ func latestBulkAccountOutboxPayload(t *testing.T, ctx context.Context, tx sqlQue
|
||||
require.NoError(t, json.Unmarshal(payloadJSON, &payload))
|
||||
return payload.AccountIDs
|
||||
}
|
||||
|
||||
func TestProbeGroupWriteHonorsDisableDuringRequest(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tx := testEntTx(t)
|
||||
repo := newAccountRepositoryWithSQL(tx.Client(), tx, nil)
|
||||
rate, notes := 0.25, "local notes"
|
||||
account := &service.Account{
|
||||
Name: "local", Notes: ¬es, Platform: service.PlatformOpenAI, Type: service.AccountTypeAPIKey,
|
||||
Status: service.StatusActive, Credentials: map[string]any{"api_key": "test-key"}, RateMultiplier: &rate,
|
||||
Extra: map[string]any{service.UpstreamBillingProbeEnabledExtraKey: true, service.UpstreamBillingGroupSyncEnabledExtraKey: true},
|
||||
}
|
||||
require.NoError(t, repo.Create(ctx, account))
|
||||
loaded, err := repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
group := service.BillingGroupInfo{Name: "Pro"}
|
||||
snapshot := &service.UpstreamBillingProbeSnapshot{Status: service.UpstreamBillingProbeStatusOK}
|
||||
require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, loaded, snapshot, nil, group))
|
||||
inFlight, err := repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "Pro", inFlight.Name)
|
||||
require.Equal(t, notes, *inFlight.Notes)
|
||||
require.Equal(t, rate, *inFlight.RateMultiplier)
|
||||
|
||||
disabled := false
|
||||
require.NoError(t, repo.UpdateWithAccountBillingSettings(ctx, loaded, service.AccountBillingSettingsUpdate{GroupSyncEnabled: &disabled}))
|
||||
group.Name, group.Description = "too late", "too late"
|
||||
require.NoError(t, repo.UpdateUpstreamBillingProbeSnapshot(ctx, inFlight, snapshot, nil, group))
|
||||
after, err := repo.GetByID(ctx, account.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "Pro", after.Name)
|
||||
require.Equal(t, notes, *after.Notes)
|
||||
require.Equal(t, false, after.Extra[service.UpstreamBillingGroupSyncEnabledExtraKey])
|
||||
}
|
||||
Reference in new issue
Block a user