Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(149)

Side by Side Diff: go/src/infra/gae/libs/wrapper/memory/key.go

Issue 1152383003: Simple memory testing for gae/wrapper (Closed) Base URL: https://chromium.googlesource.com/infra/infra.git@better_context_lite
Patch Set: be internally consistent Created 5 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 package memory
6
7 import (
8 "bytes"
9 "errors"
10 "fmt"
11
12 "github.com/golang/protobuf/proto"
13 "github.com/luci/luci-go/common/funnybase"
14 "github.com/mjibson/goon"
15
16 "appengine/datastore"
17 "appengine_internal"
18 basepb "appengine_internal/base"
19 )
20
21 const keyNumToksReasonableLimit = 50
22
23 ///////////////////////////// fakeGAECtxForNewKey //////////////////////////////
24
25 type fakeGAECtxForNewKey string
26
27 func (fakeGAECtxForNewKey) Debugf(format string, args ...interface{}) {}
28 func (fakeGAECtxForNewKey) Infof(format string, args ...interface{}) {}
29 func (fakeGAECtxForNewKey) Warningf(format string, args ...interface{}) {}
30 func (fakeGAECtxForNewKey) Errorf(format string, args ...interface{}) {}
31 func (fakeGAECtxForNewKey) Criticalf(format string, args ...interface{}) {}
32 func (fakeGAECtxForNewKey) Request() interface{} { retur n nil }
33 func (f fakeGAECtxForNewKey) Call(service, method string, in, out appengine_inte rnal.ProtoMessage, opts *appengine_internal.CallOptions) error {
34 if service != "__go__" || method != "GetNamespace" {
35 panic(fmt.Errorf("fakeGAECtxForNewKey: cannot facilitate Call(%q , %q, ...)", service, method))
36 }
37 out.(*basepb.StringProto).Value = proto.String(string(f))
38 return nil
39 }
40 func (fakeGAECtxForNewKey) FullyQualifiedAppID() string { return "dev~my~app" }
41
42 /////////////////////////////// Key construction ///////////////////////////////
43
44 func newKey(ns, kind, stringID string, intID int64, parent *datastore.Key) *data store.Key {
45 return datastore.NewKey(fakeGAECtxForNewKey(ns), kind, stringID, intID, parent)
46 }
47 func newKeyObjError(ns string, knr goon.KindNameResolver, src interface{}) (*dat astore.Key, error) {
48 return (&goon.Goon{
49 Context: fakeGAECtxForNewKey(ns),
50 KindNameResolver: knr}).KeyError(src)
51 }
52 func newKeyObj(ns string, knr goon.KindNameResolver, obj interface{}) *datastore .Key {
53 k, err := newKeyObjError(ns, knr, obj)
54 if err != nil {
55 panic(err)
56 }
57 return k
58 }
59 func kind(ns string, knr goon.KindNameResolver, src interface{}) string {
60 return newKeyObj(ns, knr, src).Kind()
61 }
62
63 /////////////////////////////// Binary Encoding ////////////////////////////////
64
65 type keyTok struct {
66 kind string
67 intID uint64
68 stringID string
69 }
70
71 func keyToToks(key *datastore.Key) (namespace string, ret []*keyTok) {
72 var inner func(*datastore.Key)
73 inner = func(k *datastore.Key) {
74 if k.Parent() != nil {
75 inner(k.Parent())
76 }
77 ret = append(ret, &keyTok{k.Kind(), uint64(k.IntID()), k.StringI D()})
78 }
79 inner(key)
80 namespace = key.Namespace()
81 return
82 }
83
84 func toksToKey(ns string, toks []*keyTok) (ret *datastore.Key) {
85 for _, t := range toks {
86 ret = newKey(ns, t.kind, t.stringID, int64(t.intID), ret)
87 }
88 return
89 }
90
91 type nsOption bool
92
93 const (
94 withNS nsOption = true
95 noNS = false
96 )
97
98 func keyBytes(nso nsOption, k *datastore.Key) []byte {
99 buf := &bytes.Buffer{}
100 writeKey(buf, nso, k)
101 return buf.Bytes()
102 }
103
104 func keyFromByteString(nso nsOption, d string) (*datastore.Key, error) {
105 return readKey(bytes.NewBufferString(d), nso)
106 }
107
108 func writeKey(buf *bytes.Buffer, nso nsOption, k *datastore.Key) {
109 // namespace ++ #tokens ++ [tok.kind ++ tok.stringID ++ tok.intID?]*
110 namespace, toks := keyToToks(k)
111 if nso == withNS {
112 writeString(buf, namespace)
113 }
114 funnybase.WriteUint(buf, uint64(len(toks)))
115 for _, tok := range toks {
116 writeString(buf, tok.kind)
117 writeString(buf, tok.stringID)
118 if tok.stringID == "" {
119 funnybase.WriteUint(buf, tok.intID)
120 }
121 }
122 }
123
124 func readKey(buf *bytes.Buffer, nso nsOption) (*datastore.Key, error) {
125 namespace := ""
126 if nso == withNS {
127 err := error(nil)
128 if namespace, err = readString(buf); err != nil {
129 return nil, err
130 }
131 }
132
133 numToks, err := funnybase.ReadUint(buf)
134 if err != nil {
135 return nil, err
136 }
137 if numToks > keyNumToksReasonableLimit {
138 return nil, fmt.Errorf("readKey: tried to decode huge key of len gth %d", numToks)
139 }
140
141 toks := make([]*keyTok, numToks)
142 for i := uint64(0); i < numToks; i++ {
143 tok := &keyTok{}
144 if tok.kind, err = readString(buf); err != nil {
145 return nil, err
146 }
147 if tok.stringID, err = readString(buf); err != nil {
148 return nil, err
149 }
150 if tok.stringID == "" {
151 if tok.intID, err = funnybase.ReadUint(buf); err != nil {
152 return nil, err
153 }
154 if tok.intID == 0 {
155 return nil, errors.New("readKey: decoded key wit h empty stringID and empty intID.")
156 }
157 }
158 toks[i] = tok
159 }
160
161 return toksToKey(namespace, toks), nil
162 }
163
164 //////////////////////////////// Key utilities /////////////////////////////////
165
166 func rootKey(key *datastore.Key) *datastore.Key {
167 for key.Parent() != nil {
168 key = key.Parent()
169 }
170 return key
171 }
172
173 type keyValidOption bool
174
175 const (
176 // UserKeyOnly is used with KeyValid, and ensures that the key is only o ne
177 // that's valid for a user program to write to.
178 UserKeyOnly keyValidOption = false
179
180 // AllowSpecialKeys is used with KeyValid, and allows keys for special
181 // metadata objects (like "__entity_group__").
182 AllowSpecialKeys = true
183 )
184
185 // KeyValid checks to see if a key is valid by applying a bunch of constraint
186 // rules to it (e.g. can't have StringID and IntID set at the same time, can't
187 // have a parent key which is Incomplete(), etc.)
188 //
189 // It verifies that the key is also in the provided namespace. It can also
190 // reject keys which are 'special' e.g. have a Kind starting with "__". This
191 // behavior is controllable with opt.
192 func KeyValid(ns string, k *datastore.Key, opt keyValidOption) bool {
193 // copied from the appengine SDK because why would any user program need to
194 // see if a key is valid? /s
195 if k == nil {
196 return false
197 }
198 // since we do "client-side" validation of namespaces, check this here.
199 if k.Namespace() != ns {
200 return false
201 }
202 for ; k != nil; k = k.Parent() {
203 if opt == UserKeyOnly && len(k.Kind()) >= 2 && k.Kind()[:2] == " __" { // reserve all Kinds starting with __
204 return false
205 }
206 if k.Kind() == "" || k.AppID() == "" {
207 return false
208 }
209 if k.StringID() != "" && k.IntID() != 0 {
210 return false
211 }
212 if k.Parent() != nil {
213 if k.Parent().Incomplete() {
214 return false
215 }
216 if k.Parent().AppID() != k.AppID() || k.Parent().Namespa ce() != k.Namespace() {
217 return false
218 }
219 }
220 }
221 return true
222 }
223
224 // KeyCouldBeValid is like KeyValid, but it allows for the possibility that the
225 // last token of the key is Incomplete(). It returns true if the Key will become
226 // valid once it recieves an automatically-assigned ID.
227 func KeyCouldBeValid(ns string, k *datastore.Key, opt keyValidOption) bool {
228 // adds an id to k if it's incomplete.
229 if k.Incomplete() {
230 k = newKey(ns, k.Kind(), "", 1, k.Parent())
231 }
232 return KeyValid(ns, k, opt)
233 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698