keycompat.go
2.5 KB
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
// Copyright 2019 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 datastore
import (
"sync"
"golang.org/x/net/context"
"google.golang.org/appengine/datastore/internal/cloudkey"
"google.golang.org/appengine/internal"
)
var keyConversion struct {
mu sync.RWMutex
appID string // read using getKeyConversionAppID
}
// EnableKeyConversion enables encoded key compatibility with the Cloud
// Datastore client library (cloud.google.com/go/datastore). Encoded keys
// generated by the Cloud Datastore client library will be decoded into App
// Engine datastore keys.
//
// The context provided must be an App Engine context if running in App Engine
// first generation runtime. This can be called in the /_ah/start handler. It is
// safe to call multiple times, and is cheap to call, so can also be inserted as
// middleware.
//
// Enabling key compatibility does not affect the encoding format used by
// Key.Encode, it only expands the type of keys that are able to be decoded with
// DecodeKey.
func EnableKeyConversion(ctx context.Context) {
// Only attempt to set appID if it's unset.
// If already set, ignore.
if getKeyConversionAppID() != "" {
return
}
keyConversion.mu.Lock()
// Check again to avoid race where another goroutine set appID between the call
// to getKeyConversionAppID above and taking the write lock.
if keyConversion.appID == "" {
keyConversion.appID = internal.FullyQualifiedAppID(ctx)
}
keyConversion.mu.Unlock()
}
func getKeyConversionAppID() string {
keyConversion.mu.RLock()
appID := keyConversion.appID
keyConversion.mu.RUnlock()
return appID
}
// decodeCloudKey attempts to decode the given encoded key generated by the
// Cloud Datastore client library (cloud.google.com/go/datastore), returning nil
// if the key couldn't be decoded.
func decodeCloudKey(encoded string) *Key {
appID := getKeyConversionAppID()
if appID == "" {
return nil
}
k, err := cloudkey.DecodeKey(encoded)
if err != nil {
return nil
}
return convertCloudKey(k, appID)
}
// convertCloudKey converts a Cloud Datastore key and converts it to an App
// Engine Datastore key. Cloud Datastore keys don't include the project/app ID,
// so we must add it back in.
func convertCloudKey(key *cloudkey.Key, appID string) *Key {
if key == nil {
return nil
}
k := &Key{
intID: key.ID,
kind: key.Kind,
namespace: key.Namespace,
parent: convertCloudKey(key.Parent, appID),
stringID: key.Name,
appID: appID,
}
return k
}