|
| 1 | +// Copyright 2025 The Bucketeer Authors. |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package processor |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "encoding/json" |
| 20 | + "fmt" |
| 21 | + "sync" |
| 22 | + "time" |
| 23 | + |
| 24 | + "go.uber.org/zap" |
| 25 | + "google.golang.org/protobuf/proto" |
| 26 | + "google.golang.org/protobuf/types/known/anypb" |
| 27 | + |
| 28 | + "github.com/bucketeer-io/bucketeer/v2/pkg/account/domain" |
| 29 | + "github.com/bucketeer-io/bucketeer/v2/pkg/pubsub/puller" |
| 30 | + "github.com/bucketeer-io/bucketeer/v2/pkg/pubsub/puller/codes" |
| 31 | + "github.com/bucketeer-io/bucketeer/v2/pkg/storage/v2/mysql" |
| 32 | + "github.com/bucketeer-io/bucketeer/v2/pkg/subscriber" |
| 33 | + eventproto "github.com/bucketeer-io/bucketeer/v2/proto/event/client" |
| 34 | +) |
| 35 | + |
| 36 | +type APIKeyLastUsedInfoWriterConfig struct { |
| 37 | + FlushSize int `json:"flushSize"` |
| 38 | + FlushInterval int `json:"flushInterval"` |
| 39 | + WriteCacheInterval int `json:"writeCacheInterval"` |
| 40 | + UserAttributeKeyTTL int `json:"userAttributeKeyTtl"` |
| 41 | +} |
| 42 | + |
| 43 | +type apikeyLastUsedInfoCache map[string]*domain.APIKeyLastUsedInfo |
| 44 | + |
| 45 | +type envAPIKeyLastUsedInfoCache map[string]apikeyLastUsedInfoCache |
| 46 | + |
| 47 | +type apiKeyUsageEventMap map[string]*eventproto.APIKeyUsageEvent |
| 48 | + |
| 49 | +type envAPIKeyUsageEventMap map[string]apiKeyUsageEventMap |
| 50 | + |
| 51 | +type apikeyLastUsedInfoWriter struct { |
| 52 | + config APIKeyLastUsedInfoWriterConfig |
| 53 | + apikeyLastUsedInfoCacher envAPIKeyLastUsedInfoCache |
| 54 | + |
| 55 | + envLastUsedCacheMutex sync.Mutex |
| 56 | + |
| 57 | + mysqlClient mysql.Client |
| 58 | + logger *zap.Logger |
| 59 | +} |
| 60 | + |
| 61 | +func NewAPIKeyLastUsedInfoWriter( |
| 62 | + config interface{}, |
| 63 | + mysqlClient mysql.Client, |
| 64 | + logger *zap.Logger, |
| 65 | +) (subscriber.PubSubProcessor, error) { |
| 66 | + apikeyLastUsedInfWriterConfig, ok := config.(map[string]interface{}) |
| 67 | + if !ok { |
| 68 | + logger.Error("apikeyLastUsedInfoWriter: invalid config") |
| 69 | + return nil, ErrAPIKeyLastUsedInfoWriterInvalidConfig |
| 70 | + } |
| 71 | + configBytes, err := json.Marshal(apikeyLastUsedInfWriterConfig) |
| 72 | + if err != nil { |
| 73 | + logger.Error("apikeyLastUsedInfoWriter: failed to marshal config", zap.Error(err)) |
| 74 | + return nil, ErrAPIKeyLastUsedInfoWriterInvalidConfig |
| 75 | + } |
| 76 | + var apikeyLastUsedInfoWriterConfig APIKeyLastUsedInfoWriterConfig |
| 77 | + err = json.Unmarshal(configBytes, &apikeyLastUsedInfoWriterConfig) |
| 78 | + if err != nil { |
| 79 | + logger.Error("apikeyLastUsedInfoWriter: failed to unmarshal config", zap.Error(err)) |
| 80 | + return nil, ErrAPIKeyLastUsedInfoWriterInvalidConfig |
| 81 | + } |
| 82 | + w := &apikeyLastUsedInfoWriter{ |
| 83 | + config: apikeyLastUsedInfoWriterConfig, |
| 84 | + mysqlClient: mysqlClient, |
| 85 | + logger: logger, |
| 86 | + } |
| 87 | + |
| 88 | + return w, nil |
| 89 | +} |
| 90 | + |
| 91 | +func (a *apikeyLastUsedInfoWriter) Process(ctx context.Context, msgChan <-chan *puller.Message) error { |
| 92 | + batch := make(map[string]*puller.Message) |
| 93 | + ticket := time.NewTicker(time.Duration(a.config.UserAttributeKeyTTL) * time.Second) |
| 94 | + defer ticket.Stop() |
| 95 | + |
| 96 | + resetBatch := func() { |
| 97 | + for _, msg := range batch { |
| 98 | + msg.Ack() |
| 99 | + subscriberHandledCounter.WithLabelValues(subscriberAPIKeyLastUsedInfo, codes.OK.String()).Inc() |
| 100 | + } |
| 101 | + batch = make(map[string]*puller.Message) |
| 102 | + } |
| 103 | + |
| 104 | + for { |
| 105 | + select { |
| 106 | + case msg, ok := <-msgChan: |
| 107 | + if !ok { |
| 108 | + a.logger.Error("Failed to pull message") |
| 109 | + return nil |
| 110 | + } |
| 111 | + subscriberReceivedCounter.WithLabelValues(subscriberAPIKeyLastUsedInfo).Inc() |
| 112 | + id := msg.Attributes["id"] |
| 113 | + if id == "" { |
| 114 | + a.logger.Error("apikeyLastUsedInfoWriter: id is empty") |
| 115 | + subscriberHandledCounter.WithLabelValues(subscriberAPIKeyLastUsedInfo, codes.MissingID.String()).Inc() |
| 116 | + continue |
| 117 | + } |
| 118 | + if previous, ok := batch[id]; ok { |
| 119 | + subscriberHandledCounter.WithLabelValues(subscriberAPIKeyLastUsedInfo, codes.MissingID.String()).Inc() |
| 120 | + previous.Ack() |
| 121 | + } |
| 122 | + batch[id] = msg |
| 123 | + if len(batch) < a.config.FlushSize { |
| 124 | + continue |
| 125 | + } |
| 126 | + envEvents := a.extractEvents(batch) |
| 127 | + a.cacheAPIKeyLastUsedInfoPerEnv(envEvents) |
| 128 | + resetBatch() |
| 129 | + case <-ticket.C: |
| 130 | + envEvents := a.extractEvents(batch) |
| 131 | + a.cacheAPIKeyLastUsedInfoPerEnv(envEvents) |
| 132 | + resetBatch() |
| 133 | + case <-ctx.Done(): |
| 134 | + // Nack the messages to be redelivered |
| 135 | + for _, msg := range batch { |
| 136 | + msg.Nack() |
| 137 | + } |
| 138 | + a.logger.Debug("All the left messages were Nack successfully before shutting down", |
| 139 | + zap.Int("batchSize", len(batch))) |
| 140 | + return nil |
| 141 | + } |
| 142 | + } |
| 143 | +} |
| 144 | + |
| 145 | +func (a *apikeyLastUsedInfoWriter) cacheAPIKeyLastUsedInfoPerEnv(envEvents envAPIKeyUsageEventMap) { |
| 146 | + for environmentID, events := range envEvents { |
| 147 | + for _, event := range events { |
| 148 | + a.cacheEnvAPIKeyLastUsedInfo(event, environmentID) |
| 149 | + } |
| 150 | + a.logger.Debug("Update cache API key last used info", |
| 151 | + zap.String("environmentID", environmentID), |
| 152 | + zap.Int("cacheSize", len(a.apikeyLastUsedInfoCacher[environmentID])), |
| 153 | + zap.Int("eventSize", len(events)), |
| 154 | + ) |
| 155 | + } |
| 156 | +} |
| 157 | + |
| 158 | +func (a *apikeyLastUsedInfoWriter) cacheEnvAPIKeyLastUsedInfo( |
| 159 | + event *eventproto.APIKeyUsageEvent, |
| 160 | + environmentID string, |
| 161 | +) { |
| 162 | + a.envLastUsedCacheMutex.Lock() |
| 163 | + defer a.envLastUsedCacheMutex.Unlock() |
| 164 | + if cache, ok := a.apikeyLastUsedInfoCacher[environmentID]; ok { |
| 165 | + if info, ok := cache[event.ApiKeyId]; ok { |
| 166 | + info.UsedAt(event.Timestamp) |
| 167 | + return |
| 168 | + } |
| 169 | + cache[event.ApiKeyId] = domain.NewAPIKeyLastUsedInfo(event.ApiKeyId, event.Timestamp, environmentID) |
| 170 | + return |
| 171 | + } |
| 172 | + cache := apikeyLastUsedInfoCache{} |
| 173 | + cache[event.ApiKeyId] = domain.NewAPIKeyLastUsedInfo(event.ApiKeyId, event.Timestamp, environmentID) |
| 174 | + a.apikeyLastUsedInfoCacher[environmentID] = cache |
| 175 | +} |
| 176 | + |
| 177 | +func (a *apikeyLastUsedInfoWriter) extractEvents(messages map[string]*puller.Message) envAPIKeyUsageEventMap { |
| 178 | + envEvents := envAPIKeyUsageEventMap{} |
| 179 | + handleBadMessage := func(m *puller.Message, err error) { |
| 180 | + m.Ack() |
| 181 | + a.logger.Error("Bad proto message", |
| 182 | + zap.Error(err), |
| 183 | + zap.String("messageID", m.ID), |
| 184 | + zap.ByteString("data", m.Data), |
| 185 | + zap.Any("attributes", m.Attributes), |
| 186 | + ) |
| 187 | + subscriberHandledCounter.WithLabelValues(subscriberAPIKeyLastUsedInfo, codes.BadMessage.String()).Inc() |
| 188 | + } |
| 189 | + for _, msg := range messages { |
| 190 | + // check if data is empty |
| 191 | + if len(msg.Data) == 0 { |
| 192 | + handleBadMessage(msg, fmt.Errorf("message data is empty")) |
| 193 | + continue |
| 194 | + } |
| 195 | + event := &eventproto.Event{} |
| 196 | + if err := proto.Unmarshal(msg.Data, event); err != nil { |
| 197 | + handleBadMessage(msg, err) |
| 198 | + continue |
| 199 | + } |
| 200 | + innerEvent := &eventproto.APIKeyUsageEvent{} |
| 201 | + if err := anypb.UnmarshalTo(event.Event, innerEvent, proto.UnmarshalOptions{}); err != nil { |
| 202 | + handleBadMessage(msg, err) |
| 203 | + continue |
| 204 | + } |
| 205 | + if innerEvents, ok := envEvents[event.EnvironmentId]; ok { |
| 206 | + innerEvents[event.Id] = innerEvent |
| 207 | + continue |
| 208 | + } |
| 209 | + envEvents[event.EnvironmentId] = apiKeyUsageEventMap{event.Id: innerEvent} |
| 210 | + } |
| 211 | + return envEvents |
| 212 | +} |
0 commit comments