blob: 2bfd49a0bd17b40e16811022803497cd9dd4a49b [file] [log] [blame]
Quentin Smithde87f132016-08-29 18:58:31 -04001// 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
5package devapp
6
7import (
8 "bytes"
9 "compress/gzip"
10 "encoding/gob"
11
12 "golang.org/x/net/context"
Quentin Smithde87f132016-08-29 18:58:31 -040013)
14
15// Cache is a datastore entity type that contains serialized data for dashboards.
16type 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 Smithde87f132016-08-29 18:58:31 -040023func 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
37func 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
45func 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 Burke310c0212017-01-07 21:05:57 -080058 return putCache(ctx, name, &cache)
Quentin Smithde87f132016-08-29 18:58:31 -040059}