-
Notifications
You must be signed in to change notification settings - Fork 119
Expand file tree
/
Copy pathservice.go
More file actions
465 lines (405 loc) · 10.1 KB
/
Copy pathservice.go
File metadata and controls
465 lines (405 loc) · 10.1 KB
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
package main
import (
"bytes"
"context"
"embed"
"encoding/hex"
"fmt"
"hash/fnv"
"io"
"net/http"
"os"
"path"
"regexp"
"strings"
"sync"
"text/template"
"time"
"github.com/gorilla/mux"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
environ "github.com/ydb-platform/ydb-go-sdk-auth-environ"
ydbMetrics "github.com/ydb-platform/ydb-go-sdk-prometheus/v2"
ydb "github.com/ydb-platform/ydb-go-sdk/v3"
"github.com/ydb-platform/ydb-go-sdk/v3/table"
"github.com/ydb-platform/ydb-go-sdk/v3/table/options"
"github.com/ydb-platform/ydb-go-sdk/v3/table/result"
"github.com/ydb-platform/ydb-go-sdk/v3/table/result/named"
"github.com/ydb-platform/ydb-go-sdk/v3/table/types"
"github.com/ydb-platform/ydb-go-sdk/v3/trace"
)
//go:embed static/index.html
var static embed.FS
var (
short = regexp.MustCompile(`[a-zA-Z0-9]{8}`)
long = regexp.MustCompile(`https?://(?:[-\w.]|%[\da-fA-F]{2})+`)
)
func hash(s string) (string, error) {
hasher := fnv.New32a()
if _, err := hasher.Write([]byte(s)); err != nil {
return "", err
}
return hex.EncodeToString(hasher.Sum(nil)), nil
}
func isShortCorrect(link string) bool {
return short.FindStringIndex(link) != nil
}
func isLongCorrect(link string) bool {
return long.FindStringIndex(link) != nil
}
func render(t *template.Template, data any) string {
var buf bytes.Buffer
if err := t.Execute(&buf, data); err != nil {
panic(err)
}
return buf.String()
}
type templateConfig struct {
TablePathPrefix string
}
type service struct {
db *ydb.Driver
registry *prometheus.Registry
router *mux.Router
calls *prometheus.GaugeVec
callsLatency *prometheus.HistogramVec
callsErrors *prometheus.GaugeVec
}
var once sync.Once
func getService(ctx context.Context, dsn string, opts ...ydb.Option) (s *service, err error) {
once.Do(func() {
var (
registry = prometheus.NewRegistry()
calls = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "app",
Name: "calls",
Help: "application calls counter",
}, []string{
"method",
"success",
})
callsLatency = prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: "app",
Name: "latency",
Help: "application calls latencies",
Buckets: []float64{
(1 * time.Millisecond).Seconds(),
(5 * time.Millisecond).Seconds(),
(10 * time.Millisecond).Seconds(),
(50 * time.Millisecond).Seconds(),
(100 * time.Millisecond).Seconds(),
(500 * time.Millisecond).Seconds(),
(1000 * time.Millisecond).Seconds(),
(5000 * time.Millisecond).Seconds(),
(10000 * time.Millisecond).Seconds(),
},
}, []string{
"success",
"method",
})
callsErrors = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: "app",
Name: "errors",
Help: "application errors counter",
}, []string{
"method",
})
)
registry.MustRegister(calls)
registry.MustRegister(callsLatency)
registry.MustRegister(callsErrors)
opts = append(
opts,
ydbMetrics.WithTraces(
registry,
ydbMetrics.WithSeparator("_"),
ydbMetrics.WithDetailer(
trace.DetailsAll,
),
),
)
s = &service{
registry: registry,
router: mux.NewRouter(),
calls: calls,
callsLatency: callsLatency,
callsErrors: callsErrors,
}
s.db, err = ydb.Open(ctx, dsn, opts...)
if err != nil {
err = fmt.Errorf("connect error: %w", err)
return
}
s.router.Handle("/metrics", promhttp.InstrumentMetricHandler(
registry, promhttp.HandlerFor(registry, promhttp.HandlerOpts{}),
))
s.router.HandleFunc("/", s.handleIndex).Methods(http.MethodGet)
s.router.HandleFunc("/shorten", s.handleShorten).Methods(http.MethodPost)
s.router.HandleFunc("/{[0-9a-fA-F]{8}}", s.handleLonger).Methods(http.MethodGet)
err = s.createTable(ctx)
if err != nil {
_ = s.db.Close(ctx)
err = fmt.Errorf("error on create table: %w", err)
return
}
})
if err != nil {
once = sync.Once{}
return nil, err
}
return s, nil
}
func (s *service) Close(ctx context.Context) {
_ = s.db.Close(ctx)
}
func (s *service) createTable(ctx context.Context) (err error) {
query := render(
template.Must(template.New("").Parse(`
PRAGMA TablePathPrefix("{{ .TablePathPrefix }}");
CREATE TABLE urls (
src Text,
hash Text,
PRIMARY KEY (hash)
);
`)),
templateConfig{
TablePathPrefix: path.Join(s.db.Name(), prefix),
},
)
return s.db.Table().Do(ctx,
func(ctx context.Context, s table.Session) error {
err := s.ExecuteSchemeQuery(ctx, query)
return err
},
)
}
func (s *service) insertShort(ctx context.Context, url string) (h string, err error) {
h, err = hash(url)
if err != nil {
return "", err
}
query := render(
template.Must(template.New("").Parse(`
PRAGMA TablePathPrefix("{{ .TablePathPrefix }}");
DECLARE $hash as Text;
DECLARE $src as Text;
REPLACE INTO
urls (hash, src)
VALUES
($hash, $src);
`)),
templateConfig{
TablePathPrefix: path.Join(s.db.Name(), prefix),
},
)
writeTx := table.TxControl(
table.BeginTx(
table.WithSerializableReadWrite(),
),
table.CommitTx(),
)
err = s.db.Table().Do(ctx,
func(ctx context.Context, s table.Session) (err error) {
_, _, err = s.Execute(ctx, writeTx, query,
table.NewQueryParameters(
table.ValueParam("$hash", types.TextValue(h)),
table.ValueParam("$src", types.TextValue(url)),
),
options.WithCollectStatsModeBasic(),
)
return
},
)
return h, err
}
func (s *service) selectLong(ctx context.Context, hash string) (url string, err error) {
query := render(
template.Must(template.New("").Parse(`
PRAGMA TablePathPrefix("{{ .TablePathPrefix }}");
DECLARE $hash as Text;
SELECT
src
FROM
urls
WHERE
hash = $hash;
`)),
templateConfig{
TablePathPrefix: path.Join(s.db.Name(), prefix),
},
)
readTx := table.TxControl(
table.BeginTx(
table.WithSnapshotReadOnly(),
),
table.CommitTx(),
)
var res result.Result
err = s.db.Table().Do(ctx,
func(ctx context.Context, s table.Session) (err error) {
_, res, err = s.Execute(ctx, readTx, query,
table.NewQueryParameters(
table.ValueParam("$hash", types.TextValue(hash)),
),
options.WithCollectStatsModeBasic(),
)
return err
},
)
if err != nil {
return "", err
}
defer func() {
_ = res.Close()
}()
var src string
for res.NextResultSet(ctx) {
for res.NextRow() {
err = res.ScanNamed(
named.OptionalWithDefault("src", &src),
)
return src, err
}
}
if err := ctx.Err(); err != nil {
return "", err
}
if err := res.Err(); err != nil {
return "", err
}
return "", fmt.Errorf("hash '%s' is not found", hash)
}
func writeResponse(w http.ResponseWriter, statusCode int, body string) {
w.WriteHeader(statusCode)
_, _ = w.Write([]byte(body))
}
func successToString(b bool) string {
if b {
return "true"
}
return "false"
}
func (s *service) handleIndex(w http.ResponseWriter, r *http.Request) {
var (
err error
tpl *template.Template
start = time.Now()
)
defer func() {
if err != nil {
s.callsErrors.With(prometheus.Labels{
"method": "index",
}).Add(1)
}
s.callsLatency.With(prometheus.Labels{
"method": "index",
"success": successToString(err == nil),
}).Observe(time.Since(start).Seconds())
s.calls.With(prometheus.Labels{
"method": "index",
"success": successToString(err == nil),
}).Add(1)
}()
tpl, err = template.ParseFS(static, "static/index.html")
if err != nil {
writeResponse(w, http.StatusInternalServerError, err.Error())
return
}
w.Header().Set("Content-Type", "text/html")
w.WriteHeader(http.StatusOK)
data := map[string]any{
"userAgent": r.UserAgent(),
}
if err = tpl.Execute(w, data); err != nil {
writeResponse(w, http.StatusInternalServerError, err.Error())
return
}
}
func (s *service) handleShorten(w http.ResponseWriter, r *http.Request) {
var (
err error
url []byte
hash string
start = time.Now()
)
defer func() {
if err != nil {
s.callsErrors.With(prometheus.Labels{
"method": "shorten",
}).Add(1)
}
s.callsLatency.With(prometheus.Labels{
"method": "shorten",
"success": successToString(err == nil),
}).Observe(time.Since(start).Seconds())
s.calls.With(prometheus.Labels{
"method": "index",
"success": successToString(err == nil),
}).Add(1)
}()
url, err = io.ReadAll(r.Body)
if err != nil {
writeResponse(w, http.StatusInternalServerError, err.Error())
return
}
if !isLongCorrect(string(url)) {
err = fmt.Errorf("'%s' is not a valid URL", url)
writeResponse(w, http.StatusBadRequest, err.Error())
return
}
hash, err = s.insertShort(r.Context(), string(url))
if err != nil {
writeResponse(w, http.StatusInternalServerError, err.Error())
return
}
w.Header().Set("Content-Type", "application/text")
writeResponse(w, http.StatusOK, hash)
}
func (s *service) handleLonger(w http.ResponseWriter, r *http.Request) {
var (
err error
url string
start = time.Now()
)
defer func() {
if err != nil {
s.callsErrors.With(prometheus.Labels{
"method": "longer",
}).Add(1)
}
s.callsLatency.With(prometheus.Labels{
"method": "longer",
"success": successToString(err == nil),
}).Observe(time.Since(start).Seconds())
s.calls.With(prometheus.Labels{
"method": "index",
"success": successToString(err == nil),
}).Add(1)
}()
path := strings.Split(r.URL.Path, "/")
if !isShortCorrect(path[len(path)-1]) {
err = fmt.Errorf("'%s' is not a valid short path", path[len(path)-1])
writeResponse(w, http.StatusBadRequest, err.Error())
return
}
url, err = s.selectLong(r.Context(), path[len(path)-1])
if err != nil {
writeResponse(w, http.StatusInternalServerError, err.Error())
return
}
http.Redirect(w, r, url, http.StatusSeeOther)
}
// Serverless is an entrypoint for serverless yandex function
func Serverless(w http.ResponseWriter, r *http.Request) {
s, err := getService(
r.Context(),
os.Getenv("YDB"),
environ.WithEnvironCredentials(),
)
if err != nil {
writeResponse(w, http.StatusInternalServerError, err.Error())
return
}
defer s.Close(r.Context())
s.router.ServeHTTP(w, r)
}