-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
199 lines (166 loc) · 5.01 KB
/
main.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
package main
import (
"context"
"database/sql"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/benbjohnson/litestream"
lss3 "github.com/benbjohnson/litestream/s3"
_ "github.com/mattn/go-sqlite3"
)
// addr is the bind address for the web server.
const addr = ":8080"
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run() error {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM)
defer stop()
// Parse command line flags.
dsn := flag.String("dsn", "", "datasource name")
bucket := flag.String("bucket", "", "s3 replica bucket")
flag.Parse()
if *dsn == "" {
flag.Usage()
return fmt.Errorf("required: -dsn PATH")
} else if *bucket == "" {
flag.Usage()
return fmt.Errorf("required: -bucket NAME")
}
// Create a Litestream DB and attached replica to manage background replication.
lsdb, err := replicate(ctx, *dsn, *bucket)
if err != nil {
return err
}
defer lsdb.SoftClose()
// Open database file.
db, err := sql.Open("sqlite3", *dsn)
if err != nil {
return err
}
defer db.Close()
// Create table for storing page views.
if _, err := db.Exec(`CREATE TABLE IF NOT EXISTS page_views (id INTEGER PRIMARY KEY, timestamp TEXT);`); err != nil {
return fmt.Errorf("cannot create table: %w", err)
}
// Run web server.
fmt.Printf("listening on %s\n", addr)
go http.ListenAndServe(addr,
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Start a transaction.
tx, err := db.Begin()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer tx.Rollback()
// Store page view.
if _, err := tx.ExecContext(r.Context(), `INSERT INTO page_views (timestamp) VALUES (?);`, time.Now().Format(time.RFC3339)); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Sync litestream with current state.
if err := lsdb.Sync(r.Context()); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Grab current position.
pos, err := lsdb.Pos()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Read total page views.
var n int
if err := tx.QueryRowContext(r.Context(), `SELECT COUNT(1) FROM page_views;`).Scan(&n); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Commit transaction.
if err := tx.Commit(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Sync litestream with current state again.
if err := lsdb.Sync(r.Context()); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Grab new transaction position.
newPos, err := lsdb.Pos()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Sync litestream with S3.
startTime := time.Now()
if err := lsdb.Replicas[0].Sync(r.Context()); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
log.Printf("new transaction: pre=%s post=%s elapsed=%s", pos.String(), newPos.String(), time.Since(startTime))
// Print total page views.
fmt.Fprintf(w, "This server has been visited %d times.\n", n)
}),
)
// Wait for signal.
<-ctx.Done()
log.Print("myapp received signal, shutting down")
return nil
}
func replicate(ctx context.Context, dsn, bucket string) (*litestream.DB, error) {
// Create Litestream DB reference for managing replication.
lsdb := litestream.NewDB(dsn)
// Build S3 replica and attach to database.
client := lss3.NewReplicaClient()
client.Bucket = bucket
replica := litestream.NewReplica(lsdb, "s3")
replica.Client = client
lsdb.Replicas = append(lsdb.Replicas, replica)
if err := restore(ctx, replica); err != nil {
return nil, err
}
// Initialize database.
if err := lsdb.Open(); err != nil {
return nil, err
}
return lsdb, nil
}
func restore(ctx context.Context, replica *litestream.Replica) (err error) {
// Skip restore if local database already exists.
if _, err := os.Stat(replica.DB().Path()); err == nil {
fmt.Println("local database already exists, skipping restore")
return nil
} else if !os.IsNotExist(err) {
return err
}
// Configure restore to write out to DSN path.
opt := litestream.NewRestoreOptions()
opt.OutputPath = replica.DB().Path()
opt.Logger = log.New(os.Stderr, "", log.LstdFlags|log.Lmicroseconds)
// Determine the latest generation to restore from.
if opt.Generation, _, err = replica.CalcRestoreTarget(ctx, opt); err != nil {
return err
}
// Only restore if there is a generation available on the replica.
// Otherwise we'll let the application create a new database.
if opt.Generation == "" {
fmt.Println("no generation found, creating new database")
return nil
}
fmt.Printf("restoring replica for generation %s\n", opt.Generation)
if err := replica.Restore(ctx, opt); err != nil {
return err
}
fmt.Println("restore complete")
return nil
}