forked from cshum/imagor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimagor.go
328 lines (306 loc) · 7.94 KB
/
imagor.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
package imagor
import (
"context"
"encoding/json"
"errors"
"fmt"
"github.com/cshum/imagor/imagorpath"
"go.uber.org/zap"
"net/http"
"reflect"
"strconv"
"strings"
"time"
)
type LoadFunc func(string) ([]byte, error)
type Meta struct {
Format string `json:"format"`
ContentType string `json:"content_type"`
Width int `json:"width"`
Height int `json:"height"`
Orientation int `json:"orientation"`
}
// Loader Load image from image source
type Loader interface {
Load(r *http.Request, image string) ([]byte, error)
}
// Storage save image buffer
type Storage interface {
Save(ctx context.Context, image string, buf []byte) error
}
// Store both a Loader and Storage
type Store interface {
Loader
Storage
}
// Processor process image buffer
type Processor interface {
Startup(ctx context.Context) error
Process(ctx context.Context, buf []byte, p imagorpath.Params, load LoadFunc) ([]byte, *Meta, error)
Shutdown(ctx context.Context) error
}
// Imagor image resize HTTP handler
type Imagor struct {
Version string
Unsafe bool
Secret string
Loaders []Loader
Storages []Storage
Processors []Processor
RequestTimeout time.Duration
LoadTimeout time.Duration
SaveTimeout time.Duration
CacheHeaderTTL time.Duration
Logger *zap.Logger
Debug bool
}
// New create new Imagor
func New(options ...Option) *Imagor {
app := &Imagor{
Version: "dev",
Logger: zap.NewNop(),
RequestTimeout: time.Second * 30,
LoadTimeout: time.Second * 20,
SaveTimeout: time.Second * 20,
CacheHeaderTTL: time.Hour * 24,
}
for _, option := range options {
option(app)
}
if app.LoadTimeout > app.RequestTimeout || app.LoadTimeout == 0 {
app.LoadTimeout = app.RequestTimeout
}
if app.Debug {
app.debugLog()
}
return app
}
func (app *Imagor) Startup(ctx context.Context) (err error) {
for _, processor := range app.Processors {
if err = processor.Startup(ctx); err != nil {
return
}
}
return
}
func (app *Imagor) Shutdown(ctx context.Context) (err error) {
for _, processor := range app.Processors {
if err = processor.Shutdown(ctx); err != nil {
return
}
}
return
}
func (app *Imagor) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := r.URL.EscapedPath()
if path == "/" {
resJSON(w, json.RawMessage(fmt.Sprintf(
`{"imagor":{"version":"%s"}}`, app.Version,
)))
return
}
p := imagorpath.Parse(path)
if p.Params {
resJSONIndent(w, p)
return
}
buf, meta, err := app.Do(r, p)
ln := len(buf)
if meta != nil {
if p.Meta {
resJSON(w, meta)
return
} else {
w.Header().Set("Content-Type", meta.ContentType)
}
} else if ln > 0 {
w.Header().Set("Content-Type", http.DetectContentType(buf))
}
if err != nil {
if e, ok := WrapError(err).(Error); ok {
if e == ErrPass {
// passed till the end means not found
e = ErrNotFound
}
w.WriteHeader(e.Code)
if ln > 0 {
w.Header().Set("Content-Length", strconv.Itoa(ln))
_, _ = w.Write(buf)
return
}
resJSON(w, e)
} else {
resJSON(w, ErrInternal)
}
return
}
setCacheHeaders(w, app.CacheHeaderTTL)
w.Header().Set("Content-Length", strconv.Itoa(ln))
_, _ = w.Write(buf)
return
}
func (app *Imagor) Do(r *http.Request, p imagorpath.Params) (buf []byte, meta *Meta, err error) {
var cancel func()
ctx := r.Context()
if app.RequestTimeout > 0 {
ctx, cancel = context.WithTimeout(ctx, app.RequestTimeout)
defer cancel()
}
if !(app.Unsafe && p.Unsafe) && imagorpath.Sign(p.Path, app.Secret) != p.Hash {
err = ErrSignatureMismatch
if app.Debug {
app.Logger.Debug("sign-mismatch", zap.Any("params", p), zap.String("expected", imagorpath.Sign(p.Path, app.Secret)))
}
return
}
if buf, err = app.load(r, p.Image); err != nil {
app.Logger.Debug("load", zap.Any("params", p), zap.Error(err))
return
}
load := func(image string) ([]byte, error) {
return app.load(r, image)
}
for _, processor := range app.Processors {
b, m, e := processor.Process(ctx, buf, p, load)
if e == nil {
buf = b
meta = m
if app.Debug {
app.Logger.Debug("processed", zap.Any("params", p), zap.Any("meta", meta), zap.Int("size", len(buf)))
}
break
} else {
if e == ErrPass {
if len(b) > 0 {
// pass to next processor
buf = b
}
if app.Debug {
app.Logger.Debug("process", zap.Any("params", p), zap.Error(e))
}
} else {
err = e
app.Logger.Warn("process", zap.Any("params", p), zap.Error(e))
}
}
}
return
}
func (app *Imagor) load(r *http.Request, image string) (buf []byte, err error) {
ctx := r.Context()
var cancel func()
if app.LoadTimeout > 0 {
ctx, cancel = context.WithTimeout(ctx, app.LoadTimeout)
defer cancel()
r = r.WithContext(ctx)
}
for _, loader := range app.Loaders {
b, e := loader.Load(r, image)
if len(b) > 0 {
buf = b
}
if e == nil {
err = nil
break
}
// should not log expected error as of now, as it has not reached the end
if e != nil && e != ErrPass && e != ErrNotFound && !errors.Is(e, context.Canceled) {
app.Logger.Warn("load", zap.String("image", image), zap.Error(e))
} else if app.Debug {
app.Logger.Debug("load", zap.String("image", image), zap.Error(e))
}
err = e
}
if err == nil {
if app.Debug {
app.Logger.Debug("loaded", zap.String("image", image), zap.Int("size", len(buf)))
}
if len(app.Storages) > 0 {
app.save(ctx, app.Storages, image, buf)
}
} else if !errors.Is(err, context.Canceled) {
if err == ErrPass {
err = ErrNotFound
}
// log non user-initiated error finally
app.Logger.Warn("load", zap.String("image", image), zap.Error(err))
}
return
}
func (app *Imagor) save(
ctx context.Context, storages []Storage, image string, buf []byte,
) {
for _, storage := range storages {
var cancel func()
sCtx := DetachContext(ctx)
if app.SaveTimeout > 0 {
sCtx, cancel = context.WithTimeout(sCtx, app.SaveTimeout)
}
go func(s Storage) {
defer cancel()
if err := s.Save(sCtx, image, buf); err != nil {
app.Logger.Warn("save", zap.String("image", image), zap.Error(err))
} else if app.Debug {
app.Logger.Debug("saved", zap.String("image", image), zap.Int("size", len(buf)))
}
}(storage)
}
}
func (app *Imagor) debugLog() {
if !app.Debug {
return
}
var loaders, storages, processors []string
for _, v := range app.Loaders {
loaders = append(loaders, getType(v))
}
for _, v := range app.Storages {
storages = append(storages, getType(v))
}
for _, v := range app.Processors {
processors = append(processors, getType(v))
}
app.Logger.Debug("imagor",
zap.Bool("unsafe", app.Unsafe),
zap.Duration("request_timeout", app.RequestTimeout),
zap.Duration("load_timeout", app.LoadTimeout),
zap.Duration("save_timeout", app.SaveTimeout),
zap.Duration("cache_header_ttl", app.CacheHeaderTTL),
zap.Strings("loaders", loaders),
zap.Strings("storages", storages),
zap.Strings("processors", processors),
)
}
func setCacheHeaders(w http.ResponseWriter, ttl time.Duration) {
expires := time.Now().Add(ttl)
w.Header().Add("Expires", strings.Replace(expires.Format(time.RFC1123), "UTC", "GMT", -1))
w.Header().Add("Cache-Control", getCacheControl(ttl))
}
func getCacheControl(ttl time.Duration) string {
if ttl == 0 {
return "private, no-cache, no-store, must-revalidate"
}
ttlSec := int(ttl.Seconds())
return fmt.Sprintf("public, s-maxage=%d, max-age=%d, no-transform", ttlSec, ttlSec)
}
func resJSON(w http.ResponseWriter, v interface{}) {
buf, _ := json.Marshal(v)
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(buf)))
_, _ = w.Write(buf)
return
}
func resJSONIndent(w http.ResponseWriter, v interface{}) {
buf, _ := json.MarshalIndent(v, "", " ")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", strconv.Itoa(len(buf)))
_, _ = w.Write(buf)
return
}
func getType(v interface{}) string {
if t := reflect.TypeOf(v); t.Kind() == reflect.Ptr {
return t.Elem().Name()
} else {
return t.Name()
}
}