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
|
package controlplane
import (
"context"
_ "embed"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"aigw/internal/security"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
)
//go:embed schema.sql
var schemaSQL string
var ErrRedisDisabled = errors.New("Redis propagation is disabled")
type Options struct {
DatabaseURL string
RedisURL string
CredentialKey string
RedisChannel string
VersionCacheKey string
}
type Store struct {
db *pgxpool.Pool
redis *redis.Client
cipher *security.CredentialCipher
redisChannel string
versionCacheKey string
}
func NewStore(ctx context.Context, options Options) (*Store, error) {
cipher, err := security.NewCredentialCipher(options.CredentialKey)
if err != nil {
return nil, err
}
db, err := pgxpool.New(ctx, options.DatabaseURL)
if err != nil {
return nil, fmt.Errorf("configure PostgreSQL: %w", err)
}
if err := db.Ping(ctx); err != nil {
db.Close()
return nil, fmt.Errorf("connect PostgreSQL: %w", err)
}
var redisClient *redis.Client
if strings.TrimSpace(options.RedisURL) != "" {
redisOptions, err := redis.ParseURL(options.RedisURL)
if err != nil {
db.Close()
return nil, fmt.Errorf("parse Redis URL: %w", err)
}
redisClient = redis.NewClient(redisOptions)
}
return &Store{
db: db, redis: redisClient, cipher: cipher,
redisChannel: options.RedisChannel, versionCacheKey: options.VersionCacheKey,
}, nil
}
func (s *Store) Close() error {
s.db.Close()
if s.redis == nil {
return nil
}
return s.redis.Close()
}
func (s *Store) RedisEnabled() bool {
return s.redis != nil
}
func (s *Store) Migrate(ctx context.Context) error {
if _, err := s.db.Exec(ctx, schemaSQL); err != nil {
return fmt.Errorf("apply control-plane schema: %w", err)
}
return nil
}
func MigrateDatabase(ctx context.Context, databaseURL string) error {
db, err := pgxpool.New(ctx, databaseURL)
if err != nil {
return fmt.Errorf("configure PostgreSQL: %w", err)
}
defer db.Close()
if _, err := db.Exec(ctx, schemaSQL); err != nil {
return fmt.Errorf("apply control-plane schema: %w", err)
}
return nil
}
func (s *Store) DatabaseGeneration(ctx context.Context) (int64, error) {
var generation int64
err := s.db.QueryRow(ctx, `SELECT generation FROM control_state WHERE singleton = TRUE`).Scan(&generation)
if err != nil {
return 0, fmt.Errorf("read control-plane generation: %w", err)
}
return generation, nil
}
func (s *Store) RedisGeneration(ctx context.Context) (int64, error) {
if s.redis == nil {
return 0, ErrRedisDisabled
}
generation, err := s.redis.Get(ctx, s.versionCacheKey).Int64()
if errors.Is(err, redis.Nil) {
return 0, nil
}
return generation, err
}
func (s *Store) PublishChange(ctx context.Context, event ChangeEvent) error {
if s.redis == nil {
return ErrRedisDisabled
}
payload, err := json.Marshal(event)
if err != nil {
return err
}
pipeline := s.redis.TxPipeline()
pipeline.Set(ctx, s.versionCacheKey, event.Generation, 0)
pipeline.Publish(ctx, s.redisChannel, payload)
_, err = pipeline.Exec(ctx)
if err != nil {
return fmt.Errorf("publish control-plane change: %w", err)
}
return nil
}
func (s *Store) Subscribe(ctx context.Context) (<-chan ChangeMessage, func() error, error) {
if s.redis == nil {
return nil, nil, ErrRedisDisabled
}
pubsub := s.redis.Subscribe(ctx, s.redisChannel)
if _, err := pubsub.Receive(ctx); err != nil {
_ = pubsub.Close()
return nil, nil, fmt.Errorf("subscribe control-plane changes: %w", err)
}
messages := make(chan ChangeMessage)
redisMessages := pubsub.Channel()
go func() {
defer close(messages)
for {
select {
case <-ctx.Done():
return
case message, ok := <-redisMessages:
if !ok {
return
}
select {
case messages <- ChangeMessage{Payload: message.Payload}:
case <-ctx.Done():
return
}
}
}
}()
return messages, pubsub.Close, nil
}
func newChange(generation int64, resource, id string) ChangeEvent {
return ChangeEvent{Generation: generation, Resource: resource, ID: id, ChangedAt: time.Now().UTC().Format(time.RFC3339Nano)}
}
|