Quentin Smith | de87f13 | 2016-08-29 18:58:31 -0400 | [diff] [blame] | 1 | // Copyright 2016 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package devapp |
| 6 | |
| 7 | import ( |
| 8 | "bytes" |
| 9 | "compress/gzip" |
| 10 | "encoding/gob" |
| 11 | |
| 12 | "golang.org/x/net/context" |
Quentin Smith | de87f13 | 2016-08-29 18:58:31 -0400 | [diff] [blame] | 13 | ) |
| 14 | |
| 15 | // Cache is a datastore entity type that contains serialized data for dashboards. |
| 16 | type Cache struct { |
| 17 | // Value contains a gzipped gob'd serialization of the object |
| 18 | // to be cached. It must be []byte to avail ourselves of the |
| 19 | // datastore's 1 MB size limit. |
| 20 | Value []byte |
| 21 | } |
| 22 | |
Quentin Smith | de87f13 | 2016-08-29 18:58:31 -0400 | [diff] [blame] | 23 | func unpackCache(cache *Cache, data interface{}) error { |
| 24 | if len(cache.Value) > 0 { |
| 25 | gzr, err := gzip.NewReader(bytes.NewReader(cache.Value)) |
| 26 | if err != nil { |
| 27 | return err |
| 28 | } |
| 29 | defer gzr.Close() |
| 30 | if err := gob.NewDecoder(gzr).Decode(data); err != nil { |
| 31 | return err |
| 32 | } |
| 33 | } |
| 34 | return nil |
| 35 | } |
| 36 | |
| 37 | func loadCache(ctx context.Context, name string, data interface{}) error { |
| 38 | cache, err := getCache(ctx, name) |
| 39 | if err != nil { |
| 40 | return err |
| 41 | } |
| 42 | return unpackCache(cache, data) |
| 43 | } |
| 44 | |
| 45 | func writeCache(ctx context.Context, name string, data interface{}) error { |
| 46 | var cache Cache |
| 47 | var cacheout bytes.Buffer |
| 48 | cachegz := gzip.NewWriter(&cacheout) |
| 49 | e := gob.NewEncoder(cachegz) |
| 50 | if err := e.Encode(data); err != nil { |
| 51 | return err |
| 52 | } |
| 53 | if err := cachegz.Close(); err != nil { |
| 54 | return err |
| 55 | } |
| 56 | cache.Value = cacheout.Bytes() |
| 57 | log.Infof(ctx, "Cache %q update finished; writing %d bytes", name, cacheout.Len()) |
Kevin Burke | 310c021 | 2017-01-07 21:05:57 -0800 | [diff] [blame] | 58 | return putCache(ctx, name, &cache) |
Quentin Smith | de87f13 | 2016-08-29 18:58:31 -0400 | [diff] [blame] | 59 | } |