-
Notifications
You must be signed in to change notification settings - Fork 4
/
duckdb.go
1447 lines (1335 loc) · 37.4 KB
/
duckdb.go
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//TO ACCESS:
//SELECT json_extract_scalar(params::json, '$.rock') FROM read_parquet('s3://bucket/v1/tracker/events/*/*/*/*.parquet', hive_partitioning=true) where year=2025;
//SELECT params::json->'$.threadId' FROM read_parquet('s3://bucket/v1/tracker/events/*/*/*/*.parquet', hive_partitioning=true) where year=2024
package main
import (
"database/sql"
"fmt"
"log"
"net"
"net/http"
"strings"
"time"
"context"
"encoding/json"
"math/rand"
"strconv"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
awsSession "github.com/aws/aws-sdk-go/aws/session" // Add alias here
"github.com/aws/aws-sdk-go/service/s3"
"github.com/gocql/gocql"
"github.com/google/uuid"
_ "github.com/marcboeker/go-duckdb" // Import DuckDB driver
)
// Connect initiates the primary connection to DuckDB
func (i *DuckService) connect() error {
err := fmt.Errorf("Could not connect to DuckDB")
i.S3Client = s3.New(awsSession.Must(awsSession.NewSession(&aws.Config{
Region: &i.AppConfig.S3Region,
Credentials: credentials.NewStaticCredentials(i.AppConfig.S3AccessKeyID, i.AppConfig.S3SecretAccessKey, ""),
})))
//Delete old version
testKey := "x/y/z/test/this/key/for/testing/delete/object"
_, err = i.S3Client.DeleteObject(&s3.DeleteObjectInput{
Bucket: &i.AppConfig.S3Bucket,
Key: &testKey,
})
if err != nil {
log.Fatal("[ERROR] Could not connect to S3:", err)
}
// Check if connection already exists
if i.Session != nil {
return fmt.Errorf("database connection already exists")
}
// Open DuckDB connection with configuration
i.Session, err = sql.Open("duckdb", "")
if err != nil {
fmt.Println("[ERROR] Connecting to DuckDB:", err)
return err
} else {
_, err = i.Session.Exec("SET threads=4")
if err != nil {
fmt.Println("[ERROR] Setting threads:", err)
}
_, err = i.Session.Exec("SET memory_limit='4GB'")
if err != nil {
fmt.Println("[ERROR] Setting memory_limit:", err)
}
_, err = i.Session.Exec("SET timezone='UTC'")
if err != nil {
fmt.Println("[ERROR] Setting timezone:", err)
}
_, err = i.Session.Exec(`INSTALL httpfs; LOAD httpfs;`)
if err != nil {
fmt.Println("[ERROR] Installing httpfs:", err)
}
_, err = i.Session.Exec(`INSTALL json; LOAD json;`)
if err != nil {
fmt.Println("[ERROR] Installing json:", err)
}
_, err = i.Session.Exec(fmt.Sprintf(`CREATE SECRET IF NOT EXISTS secret_tracker (
TYPE S3,
KEY_ID '%s',
SECRET '%s',
REGION '%s'
)`, i.AppConfig.S3AccessKeyID, i.AppConfig.S3SecretAccessKey, i.AppConfig.S3Region))
if err != nil {
fmt.Println("[ERROR] Creating secret_tracker:", err)
}
}
// Configure connection pool settings
i.Session.SetMaxOpenConns(30) //(i.Configuration.Connections)
i.Session.SetMaxIdleConns(5)
//i.Session.SetConnMaxLifetime(time.Second * time.Duration(i.Configuration.Timeout/1000))
//i.Session.SetConnMaxIdleTime(time.Millisecond * 500)
// Test connection
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(i.Configuration.Timeout)*time.Millisecond)
defer cancel()
if err = i.Session.PingContext(ctx); err != nil {
i.close() // Clean up if connection test fails
fmt.Println("[ERROR] Verifying DuckDB connection:", err)
return err
}
// Setup tables
if err = i.createTables(); err != nil {
i.close()
fmt.Println("[ERROR] Creating DuckDB tables:", err)
return err
}
i.Configuration.Session = i
// Setup rand seed (following Cassandra implementation pattern)
rand.Seed(time.Now().UTC().UnixNano())
// Start background health check if not already running
if i.HealthCheckTicker == nil {
interval := 5 * time.Minute //default interval
if i.AppConfig.HealthCheckInterval > 0 {
interval = time.Duration(i.AppConfig.HealthCheckInterval) * time.Second
}
i.HealthCheckTicker = time.NewTicker(interval)
i.HealthCheckDone = make(chan bool)
go i.runHealthCheck()
}
return nil
}
// Close terminates the DuckDB connection
func (i *DuckService) close() error {
// Stop health check if running
if i.HealthCheckTicker != nil {
i.HealthCheckTicker.Stop()
i.HealthCheckDone <- true
close(i.HealthCheckDone)
i.HealthCheckTicker = nil
}
// Existing close logic
if i.Session != nil {
return i.Session.Close()
}
return nil
}
// Listen is not implemented for DuckDB
func (i *DuckService) listen() error {
return fmt.Errorf("[ERROR] DuckDB listen not implemented")
}
// Auth checks user credentials
func (i *DuckService) auth(s *ServiceArgs) error {
if i.Configuration.ProxyRealtimeStorageService != nil && i.Configuration.ProxyRealtimeStorageService.Session != nil {
return i.Configuration.ProxyRealtimeStorageService.Session.auth(s)
} else {
return fmt.Errorf("[ERROR] DuckDB proxy storage service not implemented or connection not established")
}
}
// Serve handles HTTP requests
func (i *DuckService) serve(w *http.ResponseWriter, r *http.Request, s *ServiceArgs) error {
if i.Configuration.ProxyRealtimeStorageService != nil && i.Configuration.ProxyRealtimeStorageService.Session != nil {
return i.Configuration.ProxyRealtimeStorageService.Session.serve(w, r, s)
} else {
return fmt.Errorf("[ERROR] DuckDB proxy storage service not implemented or connection not established")
}
}
// Helper function to create required tables
func (i *DuckService) createTables() error {
queries := []string{
`CREATE TABLE IF NOT EXISTS table_versions (
table_name VARCHAR PRIMARY KEY,
version INTEGER,
modified TIMESTAMP,
estimated_size INTEGER
)`,
`CREATE TABLE IF NOT EXISTS events (
eid UUID PRIMARY KEY,
vid UUID,
sid UUID,
hhash VARCHAR,
app VARCHAR,
rel VARCHAR,
cflags INTEGER,
created TIMESTAMP,
updated TIMESTAMP,
uid UUID,
last VARCHAR,
url VARCHAR,
ip VARCHAR,
iphash VARCHAR,
lat DOUBLE,
lon DOUBLE,
ptyp VARCHAR,
bhash VARCHAR,
auth UUID,
duration INTEGER,
xid VARCHAR,
split VARCHAR,
ename VARCHAR,
source VARCHAR,
medium VARCHAR,
campaign VARCHAR,
country VARCHAR,
region VARCHAR,
city VARCHAR,
zip VARCHAR,
term VARCHAR,
etyp VARCHAR,
ver INTEGER,
sink VARCHAR,
score DOUBLE,
params JSON,
nparams JSON,
payment JSON,
targets JSON,
relation VARCHAR,
rid UUID
)`,
// `CREATE TABLE IF NOT EXISTS events_recent (
// eid UUID PRIMARY KEY,
// vid UUID,
// sid UUID,
// hhash VARCHAR,
// app VARCHAR,
// rel VARCHAR,
// cflags INTEGER,
// created TIMESTAMP,
// updated TIMESTAMP,
// uid UUID,
// last VARCHAR,
// url VARCHAR,
// ip VARCHAR,
// iphash VARCHAR,
// lat DOUBLE,
// lon DOUBLE,
// ptyp VARCHAR,
// bhash VARCHAR,
// auth UUID,
// duration INTEGER,
// xid VARCHAR,
// split VARCHAR,
// ename VARCHAR,
// source VARCHAR,
// medium VARCHAR,
// campaign VARCHAR,
// country VARCHAR,
// region VARCHAR,
// city VARCHAR,
// zip VARCHAR,
// term VARCHAR,
// etyp VARCHAR,
// ver INTEGER,
// sink VARCHAR,
// score DOUBLE,
// params JSON,
// nparams JSON,
// payment JSON,
// targets JSON,
// relation VARCHAR,
// rid UUID
// )`,
// `CREATE TABLE IF NOT EXISTS nodes (
// hhash VARCHAR,
// vid UUID,
// uid UUID,
// iphash VARCHAR,
// ip VARCHAR,
// sid UUID,
// PRIMARY KEY (hhash, vid, iphash)
// )`,
// `CREATE TABLE IF NOT EXISTS locations (
// hhash VARCHAR,
// vid UUID,
// lat DOUBLE,
// lon DOUBLE,
// uid UUID,
// sid UUID,
// PRIMARY KEY (hhash, vid, lat, lon)
// )`,
// `CREATE TABLE IF NOT EXISTS aliases (
// hhash VARCHAR,
// vid UUID,
// uid UUID,
// sid UUID,
// PRIMARY KEY (hhash, vid, uid)
// )`,
// `CREATE TABLE IF NOT EXISTS hits (
// hhash VARCHAR,
// url VARCHAR,
// total INTEGER DEFAULT 0,
// PRIMARY KEY (hhash, url)
// )`,
// `CREATE TABLE IF NOT EXISTS counters (
// id VARCHAR PRIMARY KEY,
// total INTEGER DEFAULT 0
// )`,
`CREATE TABLE IF NOT EXISTS logs (
id UUID PRIMARY KEY,
ldate DATE,
created TIMESTAMP,
ltime TIME,
topic VARCHAR,
name VARCHAR,
host VARCHAR,
hostname VARCHAR,
owner UUID,
ip VARCHAR,
iphash VARCHAR,
level INTEGER,
msg VARCHAR,
params JSON
)`,
`CREATE TABLE IF NOT EXISTS updates (
id VARCHAR PRIMARY KEY,
updated TIMESTAMP,
msg VARCHAR
)`,
// `CREATE TABLE IF NOT EXISTS zips (
// country VARCHAR,
// zip VARCHAR,
// region VARCHAR,
// rcode VARCHAR,
// county VARCHAR,
// city VARCHAR,
// culture VARCHAR,
// population INTEGER,
// men INTEGER,
// women INTEGER,
// hispanic DOUBLE,
// white DOUBLE,
// black DOUBLE,
// native DOUBLE,
// asian DOUBLE,
// pacific DOUBLE,
// voters INTEGER,
// income DOUBLE,
// incomeerr DOUBLE,
// incomepercap DOUBLE,
// incomepercaperr DOUBLE,
// poverty DOUBLE,
// childpoverty DOUBLE,
// professional DOUBLE,
// service DOUBLE,
// office DOUBLE,
// construction DOUBLE,
// production DOUBLE,
// drive DOUBLE,
// carpool DOUBLE,
// transit DOUBLE,
// walk DOUBLE,
// othertransport DOUBLE,
// workathome DOUBLE,
// meancommute DOUBLE,
// employed INTEGER,
// privatework DOUBLE,
// publicwork DOUBLE,
// selfemployed DOUBLE,
// familywork DOUBLE,
// PRIMARY KEY (country, zip)
// )`,
// `CREATE TABLE IF NOT EXISTS accounts (
// uid UUID PRIMARY KEY,
// pwd VARCHAR NOT NULL
// )`,
// `CREATE TABLE IF NOT EXISTS queues (
// id UUID PRIMARY KEY,
// src VARCHAR,
// sid UUID,
// skey VARCHAR,
// ip VARCHAR,
// host VARCHAR,
// schedule TIMESTAMP,
// started TIMESTAMP,
// completed TIMESTAMP,
// updated TIMESTAMP,
// updater UUID,
// created TIMESTAMP,
// owner UUID
// )`,
// `CREATE TABLE IF NOT EXISTS action_names (
// name VARCHAR PRIMARY KEY
// )`,
// `CREATE TABLE IF NOT EXISTS actions (
// sid UUID,
// src VARCHAR,
// did UUID,
// dsrc VARCHAR,
// meta JSON,
// exqid UUID,
// created TIMESTAMP,
// started TIMESTAMP,
// completed TIMESTAMP,
// PRIMARY KEY (sid, did)
// )`,
// `CREATE TABLE IF NOT EXISTS actions_ext (
// sid VARCHAR,
// svc VARCHAR,
// iid UUID,
// uid UUID,
// created TIMESTAMP,
// updated TIMESTAMP,
// meta JSON,
// PRIMARY KEY (sid, svc)
// )`,
// `CREATE TABLE IF NOT EXISTS cohorts (
// name VARCHAR PRIMARY KEY,
// uids_url VARCHAR,
// imported INTEGER,
// started TIMESTAMP,
// completed TIMESTAMP,
// created TIMESTAMP,
// owner UUID
// )`,
// `CREATE TABLE IF NOT EXISTS messages (
// id UUID PRIMARY KEY,
// subject VARCHAR,
// template VARCHAR,
// app VARCHAR,
// rel VARCHAR,
// ver INTEGER,
// schedule TIMESTAMP,
// started TIMESTAMP,
// completed TIMESTAMP,
// ptyp VARCHAR,
// auth VARCHAR,
// xid VARCHAR,
// cohorts JSON,
// ehashes JSON,
// chashes JSON,
// split DOUBLE,
// splitn VARCHAR,
// source VARCHAR,
// medium VARCHAR,
// campaign VARCHAR,
// term VARCHAR,
// sink VARCHAR,
// score DOUBLE,
// promo VARCHAR,
// ref UUID,
// aff VARCHAR,
// repl JSON,
// created TIMESTAMP,
// owner UUID,
// updated TIMESTAMP,
// updater UUID
// )`,
}
for _, query := range queries {
if _, err := i.Session.Exec(query); err != nil {
return err
}
}
return nil
}
func (i *DuckService) prune() error {
return fmt.Errorf("[ERROR] Not implemented pruning in duck")
// if !i.AppConfig.PruneLogsOnly {
// // Prune old records from main tables
// tables := []string{"visitors", "sessions", "events", "events_recent"}
// // Default TTL of 30 days if not specified
// ttl := 2592000
// if i.AppConfig.PruneLogsTTL > 0 {
// ttl = i.AppConfig.PruneLogsTTL
// }
// pruneTime := time.Now().Add(-time.Duration(ttl) * time.Second)
// for _, table := range tables {
// var total, pruned int64
// // First count total records
// err := i.Session.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", table)).Scan(&total)
// if err != nil {
// fmt.Printf("Error counting records in %s: %v\n", table, err)
// continue
// }
// if i.AppConfig.PruneUpdateConfig {
// // Update approach - set fields to null
// result, err := i.Session.Exec(fmt.Sprintf(`
// UPDATE %s
// SET updated = ?,
// params = NULL
// WHERE created < ?`, table),
// time.Now().UTC(), pruneTime)
// if err != nil {
// fmt.Printf("Error updating records in %s: %v\n", table, err)
// continue
// }
// pruned, _ = result.RowsAffected()
// } else {
// // Delete approach
// result, err := i.Session.Exec(fmt.Sprintf("DELETE FROM %s WHERE created < ?", table), pruneTime)
// if err != nil {
// fmt.Printf("Error deleting from %s: %v\n", table, err)
// continue
// }
// pruned, _ = result.RowsAffected()
// }
// if i.AppConfig.Debug {
// fmt.Printf("Pruned [DuckDB].[%s]: %d/%d rows\n", table, pruned, total)
// }
// }
// }
// // Prune logs table if enabled
// if !i.AppConfig.PruneLogsSkip {
// var total, pruned int64
// // Get total count
// err := i.Session.QueryRow("SELECT COUNT(*) FROM logs").Scan(&total)
// if err != nil {
// fmt.Printf("Error counting logs: %v\n", err)
// return err
// }
// // Use logs TTL from config
// ttl := 2592000 // Default 30 days
// if i.AppConfig.PruneLogsTTL > 0 {
// ttl = i.AppConfig.PruneLogsTTL
// }
// cutoffTime := time.Now().Add(-time.Duration(ttl) * time.Second)
// // Delete old logs
// result, err := i.Session.Exec("DELETE FROM logs WHERE created < ?", cutoffTime)
// if err != nil {
// fmt.Printf("Error pruning logs: %v\n", err)
// return err
// }
// pruned, _ = result.RowsAffected()
// if i.AppConfig.Debug {
// fmt.Printf("Pruned [DuckDB].[logs]: %d/%d rows\n", pruned, total)
// }
// }
// // Update config file if needed
// if i.AppConfig.PruneUpdateConfig {
// s, err := ioutil.ReadFile(i.AppConfig.ConfigFile)
// if err != nil {
// return err
// }
// var j interface{}
// if err := json.Unmarshal(s, &j); err != nil {
// return err
// }
// SetValueInJSON(j, "PruneSkipToTimestamp", time.Now().Unix())
// s, _ = json.Marshal(j)
// var prettyJSON bytes.Buffer
// if err := json.Indent(&prettyJSON, s, "", " "); err != nil {
// return err
// }
// if err := ioutil.WriteFile(i.AppConfig.ConfigFile, prettyJSON.Bytes(), 0644); err != nil {
// return err
// }
// }
// return nil
}
// Add this method to handle the background health check
func (i *DuckService) runHealthCheck() {
if i.AppConfig.Debug {
fmt.Println("[HealthCheck] Starting background health check service")
}
for {
select {
case <-i.HealthCheckDone:
if i.AppConfig.Debug {
fmt.Println("[HealthCheck] Stopping background health check service")
}
return
case <-i.HealthCheckTicker.C:
if err := i.healthCheck(); err != nil {
fmt.Printf("[HealthCheck] Error during health check: %v\n", err)
}
}
}
}
// Add a new method for health checks, checks that the database is reachable
// We also check the size of each table, if the size of any table is greater than 100MB we write the data in the table to s3
// OR if the table has not been modified in the past 15 minutes
// We then truncate the table and reset the auto increment id
func (i *DuckService) healthCheck() error {
// Check database connection
if i.Session == nil {
return fmt.Errorf("database connection not initialized")
}
// Verify S3 configuration if needed
if i.AppConfig.S3Bucket == "" || i.AppConfig.S3Prefix == "" {
return fmt.Errorf("S3 configuration missing for table exports")
}
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(i.AppConfig.WriteTimeoutSeconds)*time.Second)
defer cancel()
// Test connection
if err := i.Session.PingContext(ctx); err != nil {
return fmt.Errorf("database ping failed: %v", err)
}
// Get list of tables
tables, err := i.Session.Query(`
SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'main'
`)
if err != nil {
return fmt.Errorf("failed to query tables: %v", err)
}
defer tables.Close()
inactivityLimit := time.Duration(i.AppConfig.InactivityTimeoutSeconds) * time.Second
for tables.Next() {
var tableName string
if err := tables.Scan(&tableName); err != nil {
return fmt.Errorf("failed to scan table name: %v", err)
}
if tableName == "table_versions" {
continue
}
// Check table size
var sizeBytes int64
row := i.Session.QueryRow(`select estimated_size from duckdb_tables() where internal=false and table_name=?`, tableName)
err = row.Scan(&sizeBytes)
if err != nil {
return fmt.Errorf("failed to get size for table %s: %v", tableName, err)
}
if sizeBytes == 0 {
continue
}
// Check last modification time
lastModified := time.Now().UTC()
lastSize := int64(-1)
isNew := false
err = i.Session.QueryRow(`
SELECT COALESCE(modified, ?), COALESCE(estimated_size, 0)
FROM table_versions where table_name=?`, lastModified, tableName).Scan(&lastModified, &lastSize)
if err != nil {
isNew = true
}
if lastSize == sizeBytes {
continue
}
// Export based on condition
if sizeBytes > i.AppConfig.MaxShardSizeBytes {
if err := i.exportAndTruncateTable(tableName, true, sizeBytes, lastModified); err != nil {
return fmt.Errorf("failed to process table %s: %v", tableName, err)
}
} else if time.Since(lastModified) > inactivityLimit || isNew {
if err := i.exportAndTruncateTable(tableName, false, sizeBytes, lastModified); err != nil {
return fmt.Errorf("failed to process table %s: %v", tableName, err)
}
}
if i.AppConfig.Debug {
fmt.Printf("[HealthCheck] Processed table %s (size: %.2f, last modified: %v)\n",
tableName,
float64(sizeBytes)/(1024*1024),
lastModified)
}
}
return nil
}
// Modified to handle different version behavior
func (i *DuckService) exportAndTruncateTable(tableName string, incrementVersion bool, sizeBytes int64, lastModified time.Time) error {
tx, err := i.Session.Begin()
if err != nil {
return fmt.Errorf("failed to start transaction: %v", err)
}
defer tx.Rollback()
// Get current version or create new entry
var version int
currentTime := time.Now().UTC()
// Force version increment if we've ticked over to a new day
if incrementVersion {
// Increment version for size-based exports
err = tx.QueryRow(`
INSERT INTO table_versions (table_name, version, modified, estimated_size)
VALUES (?, 1, CURRENT_TIMESTAMP, ?)
ON CONFLICT (table_name) DO UPDATE
SET version = table_versions.version + 1,
modified = ?,
estimated_size = ?
RETURNING version`, tableName, sizeBytes, currentTime, sizeBytes).Scan(&version)
} else {
// Use existing version for inactivity-based exports
err = tx.QueryRow(`
INSERT INTO table_versions (table_name, version, modified, estimated_size)
VALUES (?, 1, CURRENT_TIMESTAMP, ?)
ON CONFLICT (table_name) DO UPDATE
SET version = table_versions.version,
modified = ?,
estimated_size = ?
RETURNING version`, tableName, sizeBytes, currentTime, sizeBytes).Scan(&version)
}
if err != nil {
return fmt.Errorf("failed to handle version: %v", err)
}
existingVersion := version
if incrementVersion {
existingVersion = version - 1
}
// Generate export path with the existing version
s3Path := fmt.Sprintf("s3://%s/%s/%s/year=%d/month=%d/day=%d/%s_v%d.parquet",
i.AppConfig.S3Bucket,
i.AppConfig.S3Prefix,
tableName,
currentTime.Year(),
currentTime.Month(),
currentTime.Day(),
i.AppConfig.NodeId,
existingVersion)
// Export to S3
_, err = tx.Exec(fmt.Sprintf(`
COPY (SELECT * FROM %s)
TO '%s' (FORMAT 'parquet')
`, tableName, s3Path))
if err != nil {
return fmt.Errorf("failed to export to S3: %v", err)
}
//Remove the old version if we've ticked over to a new day
if lastModified.Day() != currentTime.Day() {
oldKey := fmt.Sprintf("%s/%s/year=%d/month=%d/day=%d/%s_v%d.parquet",
i.AppConfig.S3Bucket,
i.AppConfig.S3Prefix,
tableName,
lastModified.Year(),
lastModified.Month(),
lastModified.Day(),
i.AppConfig.NodeId,
existingVersion)
//Delete old version
_, err = i.S3Client.DeleteObject(&s3.DeleteObjectInput{
Bucket: &i.AppConfig.S3Bucket,
Key: &oldKey,
})
}
if incrementVersion {
// Truncate table after successful export
_, err = tx.Exec(fmt.Sprintf("TRUNCATE TABLE %s", tableName))
if err != nil {
return fmt.Errorf("failed to truncate table: %v", err)
}
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("failed to commit transaction: %v", err)
}
return nil
}
// ////////////////////////////////////// DuckDB
func (i *DuckService) write(w *WriteArgs) error {
//First make a deep copy of the values using JSON marshal/unmarshal
v := make(map[string]interface{})
b, _ := json.Marshal(*w.Values)
json.Unmarshal(b, &v)
//Write to proxy if configured
if i.Configuration.ProxyRealtimeStorageService != nil && i.Configuration.ProxyRealtimeStorageServiceTables != 0 && i.Configuration.ProxyRealtimeStorageService.Session != nil {
w.CallingService = i.Configuration
i.Configuration.ProxyRealtimeStorageService.Session.write(w)
}
err := fmt.Errorf("[ERROR] Could not write to duck")
switch w.WriteType {
case WRITE_UPDATE:
if i.AppConfig.Debug {
fmt.Printf("UPDATE %s\n", w)
}
timestamp := time.Now().UTC()
updated, ok := v["updated"].(string)
if ok {
millis, err := strconv.ParseInt(updated, 10, 64)
if err == nil {
timestamp = time.Unix(0, millis*int64(time.Millisecond))
}
}
tx, err := i.Session.Begin()
if err != nil {
return err
}
defer tx.Rollback()
_, err = tx.Exec(`INSERT INTO updates (id, updated, msg)
VALUES (?, ?, ?)`,
v["id"], timestamp, v["msg"])
if err != nil && i.AppConfig.Debug {
fmt.Println("[ERROR] DuckDB[updates]:", err)
}
return tx.Commit()
case WRITE_LOG:
if i.AppConfig.Debug {
fmt.Printf("LOG %s\n", w)
}
//////////////////////////////////////////////
//FIX VARS
//////////////////////////////////////////////
//[params]
if ps, ok := v["params"].(string); ok {
temp := make(map[string]string)
json.Unmarshal([]byte(ps), &temp)
v["params"] = &temp
}
//[ltimenss] ltime as nanosecond string
var ltime time.Duration
if lts, ok := v["ltimenss"].(string); ok {
ns, _ := strconv.ParseInt(lts, 10, 64)
ltime = time.Duration(ns)
}
//[level]
var level *int64
if lvl, ok := v["level"].(float64); ok {
temp := int64(lvl)
level = &temp
}
var topic string
if ttemp1, ok := v["topic"].(string); ok {
topic = ttemp1
} else {
if ttemp2, ok2 := v["id"].(string); ok2 {
topic = ttemp2
}
}
cleanInterfaceString(v["ip"])
cleanInterfaceString(v["topic"])
cleanInterfaceString(v["name"])
cleanInterfaceString(v["host"])
cleanInterfaceString(v["hostname"])
cleanInterfaceString(v["msg"])
var iphash string
if temp, ok := v["ip"].(string); ok && temp != "" {
//128 bits = ipv6
iphash = strconv.FormatInt(int64(hash(temp)), 36)
iphash = iphash + strconv.FormatInt(int64(hash(temp+iphash)), 36)
iphash = iphash + strconv.FormatInt(int64(hash(temp+iphash)), 36)
iphash = iphash + strconv.FormatInt(int64(hash(temp+iphash)), 36)
}
tx, err := i.Session.Begin()
if err != nil {
return err
}
defer tx.Rollback()
_, err = tx.Exec(`INSERT INTO logs
(id, ldate, created, ltime, topic, name, host, hostname, owner,
ip, iphash, level, msg, params)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?)`,
uuid.New(),
v["ldate"],
time.Now().UTC(),
ltime,
topic,
v["name"],
v["host"],
v["hostname"],
v["owner"],
v["ip"],
iphash,
level,
v["msg"],
v["params"])
if err != nil && i.AppConfig.Debug {
fmt.Println("[ERROR] DuckDB[logs]:", err)
}
return tx.Commit()
case WRITE_EVENT:
//TODO: Commented for AWS, perhaps non-optimal, CHECK
//go func() {
//////////////////////////////////////////////
//FIX CASE
//////////////////////////////////////////////
delete(v, "cleanIP")
cleanString(&(w.Browser))
cleanString(&(w.Host))
cleanInterfaceString(v["app"])
cleanInterfaceString(v["rel"])
cleanInterfaceString(v["ptyp"])
cleanInterfaceString(v["xid"])
cleanInterfaceString(v["split"])
cleanInterfaceString(v["ename"])
cleanInterfaceString(v["etyp"])
cleanInterfaceString(v["sink"])
cleanInterfaceString(v["source"])
cleanInterfaceString(v["medium"])
cleanInterfaceString(v["campaign"])
cleanInterfaceString(v["term"])
cleanInterfaceString(v["rcode"])
cleanInterfaceString(v["aff"])
cleanInterfaceString(v["device"])
cleanInterfaceString(v["os"])
cleanInterfaceString(v["relation"])
//////////////////////////////////////////////
//FIX VARS
//////////////////////////////////////////////
//[hhash]
var hhash *string
if w.Host != "" {
temp := strconv.FormatInt(int64(hash(w.Host)), 36)
hhash = &temp
}
//[iphash]
var iphash string
if w.IP != "" {
//128 bits = ipv6
iphash = strconv.FormatInt(int64(hash(w.IP)), 36)
iphash = iphash + strconv.FormatInt(int64(hash(w.IP+iphash)), 36)
iphash = iphash + strconv.FormatInt(int64(hash(w.IP+iphash)), 36)
iphash = iphash + strconv.FormatInt(int64(hash(w.IP+iphash)), 36)
}
//check host account id
//don't track without it
//SEVERELY LIMITING SO DON'T USE IT
var hAccountID *string
if w.Host != "" && i.AppConfig.AccountHashMixer != "" {
temp := strconv.FormatInt(int64(hash(w.Host+i.AppConfig.AccountHashMixer)), 36)
hAccountID = &temp
if v["acct"].(string) != *hAccountID {
err := fmt.Errorf("[ERROR] Host: %s Account-ID: %s Incorrect for (acct): %s", w.Host, *hAccountID, v["acct"])
return err
}
}
//[updated]
updated := time.Now().UTC()
//[rid]
var rid *uuid.UUID
if temp, ok := v["rid"].(string); ok {
if temp2, err := uuid.Parse(temp); err == nil {
rid = &temp2
}
}
//[auth]
var auth *uuid.UUID
if temp, ok := v["auth"].(string); ok {
if temp2, err := uuid.Parse(temp); err == nil {
auth = &temp2
}
}
//[country]
var country *string
var region *string
var city *string
zip := v["zip"]
ensureInterfaceString(zip)
if tz, ok := v["tz"].(string); ok {
if ct, oktz := countries[tz]; oktz {
country = &ct
}
}