-
Notifications
You must be signed in to change notification settings - Fork 0
/
schema.go
109 lines (98 loc) · 2.48 KB
/
schema.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
package main
import (
"fmt"
"io"
"net/http"
"sync"
"time"
"github.com/loicalleyne/bodkin"
)
type syncBodkin struct {
mu sync.Mutex
u *bodkin.Bodkin
lastAccessed time.Time
}
var schemas sync.Map
func newSyncBodkin() *syncBodkin {
sb := new(syncBodkin)
sb.lastAccessed = time.Now()
return sb
}
func schemasTTL() {
time.Sleep(10 * time.Minute)
for {
var expired []string
today := time.Now()
limit := today.Add(-36 * time.Hour)
schemas.Range(func(k, v interface{}) bool {
v.(*syncBodkin).mu.Lock()
if v.(*syncBodkin).lastAccessed.Before(limit) {
expired = append(expired, k.(string))
}
return true
})
for _, k := range expired {
schemas.Delete(k)
}
time.Sleep(6 * time.Hour)
}
}
func (s *chServer) handleSchemaPost(w http.ResponseWriter, r *http.Request) {
schemaName := r.URL.Query().Get("name")
if schemaName == "" {
http.Error(w, "Missing schema name", http.StatusBadRequest)
return
}
if r.Body != nil {
http.Error(w, "Empty request body", http.StatusBadRequest)
return
}
bodyBytes, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusBadRequest)
return
}
if sb, ok := schemas.Load(schemaName); !ok {
u, err := bodkin.NewBodkin(bodyBytes, bodkin.WithInferTimeUnits(), bodkin.WithTypeConversion())
if err != nil {
http.Error(w, "Error creating schema", http.StatusBadRequest)
return
}
sb := newSyncBodkin()
sb.u = u
schemas.Store(schemaName, sb)
w.WriteHeader(http.StatusOK)
return
} else {
sb.(*syncBodkin).mu.Lock()
sb.(*syncBodkin).lastAccessed = time.Now()
defer sb.(*syncBodkin).mu.Unlock()
err := sb.(*syncBodkin).u.Unify(bodyBytes)
if err != nil {
http.Error(w, "Error unifying schema", http.StatusBadRequest)
return
}
}
}
func (s *chServer) handleSchemaGet(w http.ResponseWriter, r *http.Request) {
schemaName := r.URL.Query().Get("name")
if schemaName == "" {
http.Error(w, "Missing schema name", http.StatusBadRequest)
return
}
if sb, ok := schemas.Load(schemaName); !ok {
http.Error(w, "Error creating schema", http.StatusNotFound)
return
} else {
sb.(*syncBodkin).mu.Lock()
sb.(*syncBodkin).lastAccessed = time.Now()
defer sb.(*syncBodkin).mu.Unlock()
arrSchema, err := sb.(*syncBodkin).u.ExportSchemaBytes()
if err != nil {
http.Error(w, "Error exporting schema", http.StatusInternalServerError)
return
}
w.Header().Add("content-type", "application/octet-stream")
fmt.Fprintf(w, "%b", arrSchema)
}
}