summaryrefslogtreecommitdiff
path: root/internal/controlplane/snapshot.go
blob: bc04e7cc9d6c9fa6fa81d702425fc2a8bde21936 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package controlplane

import (
	"context"
	"crypto/sha256"
	"encoding/json"
	"fmt"
	"strings"

	"aigw/internal/auth"
	"aigw/internal/domain"

	"github.com/jackc/pgx/v5"
)

func (s *Store) LoadSnapshot(ctx context.Context) (Snapshot, error) {
	tx, err := s.db.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
	if err != nil {
		return Snapshot{}, fmt.Errorf("begin snapshot transaction: %w", err)
	}
	defer tx.Rollback(ctx)

	var result Snapshot
	if err := tx.QueryRow(ctx, `SELECT generation FROM control_state WHERE singleton = TRUE`).Scan(&result.Generation); err != nil {
		return Snapshot{}, fmt.Errorf("read snapshot generation: %w", err)
	}

	providers, err := s.loadProviders(ctx, tx)
	if err != nil {
		return Snapshot{}, err
	}
	result.Models, err = loadModels(ctx, tx, providers)
	if err != nil {
		return Snapshot{}, err
	}
	result.APIKeys, err = loadAPIKeys(ctx, tx)
	if err != nil {
		return Snapshot{}, err
	}
	result.Limits, err = loadLimitPolicies(ctx, tx)
	if err != nil {
		return Snapshot{}, err
	}
	if err := tx.Commit(ctx); err != nil {
		return Snapshot{}, fmt.Errorf("commit snapshot transaction: %w", err)
	}
	return result, nil
}

func loadLimitPolicies(ctx context.Context, tx pgx.Tx) ([]domain.LimitPolicy, error) {
	rows, err := tx.Query(ctx, `
		SELECT tenant_id::text, project_id::text, requests_per_minute, tokens_per_minute,
		       concurrent_requests, monthly_spend_micros
		FROM project_limits`)
	if err != nil {
		return nil, fmt.Errorf("query project limits: %w", err)
	}
	defer rows.Close()
	result := make([]domain.LimitPolicy, 0)
	for rows.Next() {
		var policy domain.LimitPolicy
		if err := rows.Scan(&policy.TenantID, &policy.ProjectID, &policy.RequestsPerMinute,
			&policy.TokensPerMinute, &policy.Concurrent, &policy.MonthlySpendMicros); err != nil {
			return nil, fmt.Errorf("scan project limit: %w", err)
		}
		result = append(result, policy)
	}
	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("read project limits: %w", err)
	}
	return result, nil
}

func (s *Store) loadProviders(ctx context.Context, tx pgx.Tx) (map[string]domain.Provider, error) {
	rows, err := tx.Query(ctx, `
		SELECT id::text, name, protocol, base_url, api_key_ciphertext
		FROM providers
		WHERE enabled = TRUE
		ORDER BY name`)
	if err != nil {
		return nil, fmt.Errorf("query providers: %w", err)
	}
	defer rows.Close()
	providers := make(map[string]domain.Provider)
	for rows.Next() {
		var id, name, protocol, baseURL string
		var ciphertext []byte
		if err := rows.Scan(&id, &name, &protocol, &baseURL, &ciphertext); err != nil {
			return nil, fmt.Errorf("scan provider: %w", err)
		}
		apiKey, err := s.cipher.Decrypt(ciphertext)
		if err != nil {
			return nil, fmt.Errorf("decrypt provider %q credential: %w", name, err)
		}
		providers[id] = domain.Provider{ID: id, Protocol: domain.Protocol(protocol), BaseURL: strings.TrimRight(baseURL, "/"), APIKey: apiKey}
	}
	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("read providers: %w", err)
	}
	return providers, nil
}

func loadModels(ctx context.Context, tx pgx.Tx, providers map[string]domain.Provider) ([]domain.Model, error) {
	rows, err := tx.Query(ctx, `
		SELECT m.public_id, m.owned_by, m.input_price_micros_per_million, m.output_price_micros_per_million,
		       m.cache_read_price_micros_per_million, m.cache_write_price_micros_per_million,
		       r.provider_id::text, r.upstream_model, r.priority, r.weight
		FROM models m
		JOIN model_routes r ON r.model_id = m.id AND r.enabled = TRUE
		JOIN providers p ON p.id = r.provider_id AND p.enabled = TRUE
		WHERE m.enabled = TRUE
		ORDER BY m.public_id, r.priority, r.created_at`)
	if err != nil {
		return nil, fmt.Errorf("query model routes: %w", err)
	}
	defer rows.Close()
	models := make([]domain.Model, 0)
	index := make(map[string]int)
	for rows.Next() {
		var publicID, ownedBy, providerID, upstreamModel string
		var inputPrice, outputPrice, cacheReadPrice, cacheWritePrice int64
		var priority, weight int
		if err := rows.Scan(&publicID, &ownedBy, &inputPrice, &outputPrice, &cacheReadPrice, &cacheWritePrice, &providerID, &upstreamModel, &priority, &weight); err != nil {
			return nil, fmt.Errorf("scan model route: %w", err)
		}
		provider, ok := providers[providerID]
		if !ok {
			continue
		}
		position, exists := index[publicID]
		if !exists {
			position = len(models)
			index[publicID] = position
			models = append(models, domain.Model{
				ID: publicID, OwnedBy: ownedBy,
				InputPriceMicrosPerMillion: inputPrice, OutputPriceMicrosPerMillion: outputPrice,
				CacheReadPriceMicrosPerMillion: cacheReadPrice, CacheWritePriceMicrosPerMillion: cacheWritePrice,
			})
		}
		models[position].Routes = append(models[position].Routes, domain.Route{
			Provider: provider, UpstreamModel: upstreamModel, Priority: priority, Weight: weight,
		})
	}
	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("read model routes: %w", err)
	}
	return models, nil
}

func loadAPIKeys(ctx context.Context, tx pgx.Tx) ([]auth.HashedKeyRecord, error) {
	rows, err := tx.Query(ctx, `
		SELECT k.id::text, k.key_hash, k.tenant_id::text, k.project_id::text, k.scopes
		FROM api_keys k
		JOIN tenants t ON t.id = k.tenant_id AND t.status = 'active'
		JOIN projects p ON p.id = k.project_id AND p.status = 'active'
		WHERE k.status = 'active'`)
	if err != nil {
		return nil, fmt.Errorf("query API keys: %w", err)
	}
	defer rows.Close()
	records := make([]auth.HashedKeyRecord, 0)
	for rows.Next() {
		var keyID, tenantID, projectID string
		var hashBytes, scopesJSON []byte
		if err := rows.Scan(&keyID, &hashBytes, &tenantID, &projectID, &scopesJSON); err != nil {
			return nil, fmt.Errorf("scan API key: %w", err)
		}
		if len(hashBytes) != sha256.Size {
			return nil, fmt.Errorf("API key %s has invalid hash length", keyID)
		}
		var hash [sha256.Size]byte
		copy(hash[:], hashBytes)
		var scopes []string
		if err := json.Unmarshal(scopesJSON, &scopes); err != nil {
			return nil, fmt.Errorf("decode API key %s scopes: %w", keyID, err)
		}
		records = append(records, auth.HashedKeyRecord{Hash: hash, Principal: domain.Principal{
			KeyID: keyID, TenantID: tenantID, ProjectID: projectID, Scopes: scopes,
		}})
	}
	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("read API keys: %w", err)
	}
	return records, nil
}