forked from GoogleCloudPlatform/golang-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
counter.go
58 lines (50 loc) · 1.26 KB
/
counter.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
// Copyright 2011 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package sharded_counter
import (
"fmt"
"math/rand"
"golang.org/x/net/context"
"google.golang.org/appengine/datastore"
)
type simpleCounterShard struct {
Count int
}
const (
numShards = 20
shardKind = "SimpleCounterShard"
)
// Count retrieves the value of the counter.
func Count(ctx context.Context) (int, error) {
total := 0
q := datastore.NewQuery(shardKind)
for t := q.Run(ctx); ; {
var s simpleCounterShard
_, err := t.Next(&s)
if err == datastore.Done {
break
}
if err != nil {
return total, err
}
total += s.Count
}
return total, nil
}
// Increment increments the counter.
func Increment(ctx context.Context) error {
return datastore.RunInTransaction(ctx, func(ctx context.Context) error {
shardName := fmt.Sprintf("shard%d", rand.Intn(numShards))
key := datastore.NewKey(ctx, shardKind, shardName, 0, nil)
var s simpleCounterShard
err := datastore.Get(ctx, key, &s)
// A missing entity and a present entity will both work.
if err != nil && err != datastore.ErrNoSuchEntity {
return err
}
s.Count++
_, err = datastore.Put(ctx, key, &s)
return err
}, nil)
}