-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathcluster.go
70 lines (58 loc) · 1.24 KB
/
cluster.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
package obligator
import (
"fmt"
"net/http"
"os"
)
type Cluster struct {
onFly bool
localId string
}
func NewCluster() *Cluster {
c := &Cluster{}
flyIoId := os.Getenv("FLY_ALLOC_ID")
if flyIoId != "" {
c.onFly = true
c.localId = flyIoId
} else {
var err error
c.localId, err = genRandomKey()
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
}
}
return c
}
func (c *Cluster) LocalId() string {
return c.localId
}
func (c *Cluster) GetLocalId() string {
return c.localId
}
func (c *Cluster) IAmThePrimary() bool {
_, err := c.PrimaryHost()
if err != nil {
return true
} else {
return false
}
}
// TODO: currently hits filesystem for every request. Might be able to listen
// for primary change events and only update periodically
func (c *Cluster) PrimaryHost() (string, error) {
bytes, err := os.ReadFile("/litefs/.primary")
if err != nil {
return "", err
}
return string(bytes), nil
}
func (c *Cluster) RedirectOrForward(host string, w http.ResponseWriter, r *http.Request) bool {
if c.onFly {
// Running on fly.io. Set replay header and indicate we're done
w.Header().Set("fly-replay", fmt.Sprintf("instance=%s", host))
return true
} else {
// TODO: handle other cluster environments
}
return false
}