addToBatch inserts an item into the batch, deduplicating by conflict key on the fly. For entries with the same key, disconnect events are preferred over connect events, and later events are preferred over earlier ones. This is safe because each new connection gets a fresh UUID (see agent/agent.go a
(item database.UpsertConnectionLogParams)
| 228 | // same (connection_id, workspace_id, agent_name) is a connect/disconnect |
| 229 | // pair for the same session. A "reconnect" always uses a new ID. |
| 230 | func (b *DBBatcher) addToBatch(item database.UpsertConnectionLogParams) { |
| 231 | entry := batchEntry{ |
| 232 | UpsertConnectionLogParams: item, |
| 233 | } |
| 234 | if item.ConnectionStatus == database.ConnectionStatusDisconnected { |
| 235 | // For standalone disconnect events, use the disconnect |
| 236 | // time as both connect and disconnect time. This matches |
| 237 | // the single-row UpsertConnectionLog behavior which uses |
| 238 | // @time for connect_time regardless of status. The SQL |
| 239 | // LEAST logic will correct connect_time if the real |
| 240 | // connect event arrives in a later batch. |
| 241 | entry.connectTime = item.Time |
| 242 | entry.disconnectTime = item.Time |
| 243 | } else { |
| 244 | entry.connectTime = item.Time |
| 245 | } |
| 246 | |
| 247 | if !item.ConnectionID.Valid { |
| 248 | b.nullConnIDBatch = append(b.nullConnIDBatch, entry) |
| 249 | return |
| 250 | } |
| 251 | connID := item.ConnectionID.UUID |
| 252 | existing, ok := b.dedupedBatch[connID] |
| 253 | if !ok { |
| 254 | b.dedupedBatch[connID] = entry |
| 255 | return |
| 256 | } |
| 257 | // When merging entries for the same connection, always preserve |
| 258 | // the earliest non-zero connect_time and latest disconnect_time |
| 259 | // so the row records the full session span. |
| 260 | if !existing.connectTime.IsZero() && existing.connectTime.Before(entry.connectTime) { |
| 261 | entry.connectTime = existing.connectTime |
| 262 | } |
| 263 | if existing.disconnectTime.After(entry.disconnectTime) { |
| 264 | entry.disconnectTime = existing.disconnectTime |
| 265 | } |
| 266 | |
| 267 | // Prefer disconnect over connect (superset of info). |
| 268 | // If same status, prefer the later event. |
| 269 | if item.ConnectionStatus == database.ConnectionStatusDisconnected && |
| 270 | existing.ConnectionStatus != database.ConnectionStatusDisconnected { |
| 271 | b.dedupedBatch[connID] = entry |
| 272 | } else if item.Time.After(existing.Time) { |
| 273 | b.dedupedBatch[connID] = entry |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | // batchLen returns the total number of entries currently buffered. |
| 278 | func (b *DBBatcher) batchLen() int { |