forked from googleapis/google-cloud-php-datastore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DatastoreSessionHandler.php
327 lines (309 loc) · 11 KB
/
DatastoreSessionHandler.php
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
<?php
/**
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Cloud\Datastore;
use Exception;
use InvalidArgumentException;
use SessionHandlerInterface;
/**
* Custom session handler backed by Cloud Datastore.
*
* Instead of storing the session data in a local file, it stores the data to
* Cloud Datastore. The biggest benefit of doing this is the data can be
* shared by multiple instances, so it's suitable for cloud applications.
*
* The downside of using Cloud Datastore is the write operations will cost you
* some money, so it is highly recommended to minimize the write operations
* with your session data with this handler. In order to do so, keep the data
* in the session as limited as possible; for example, it is ok to put only
* signed-in state and the user id in the session with this handler. However,
* for example, it is definitely not recommended that you store your
* application's whole undo history in the session, because every user
* operations will cause the Datastore write and then it will cost you lot of
* money.
*
* This handler doesn't provide pessimistic lock for session data. Instead, it
* uses Datastore Transaction for data consistency. This means that if
* multiple requests are modifying the same session data simultaneously, there
* will be more probablity that some of the `write` operations will fail.
*
* If you are building an ajax application which may issue multiple requests
* to the server, please design the session data carefully, in order to avoid
* possible data contentions. Also please see the 2nd example below for how to
* properly handle errors on `write` operations.
*
* It uses the session.save_path as the Datastore namespace for isolating the
* session data from your application data, it also uses the session.name as
* the Datastore kind, the session id as the Datastore id. By default, it
* does nothing on gc for reducing the cost. Pass positive value up to 1000
* for $gcLimit parameter to delete entities in gc.
*
* Note: The datastore transaction only lasts 60 seconds. If this handler is
* used for long running requests, it will fail on `write`.
*
* Example without error handling:
* ```
* use Google\Cloud\Datastore\DatastoreClient;
*
* $datastore = new DatastoreClient();
*
* $handler = new DatastoreSessionHandler($datastore);
*
* session_set_save_handler($handler, true);
* session_save_path('sessions');
* session_start();
*
* // Then read and write the $_SESSION array.
*
* ```
*
* The above example automatically writes the session data. It's handy, but
* the code doesn't stop even if it fails to write the session data, because
* the `write` happens when the code exits. If you want to know the session
* data is correctly written to the Datastore, you need to call
* `session_write_close()` explicitly and then handle `E_USER_WARNING`
* properly like the following example.
*
* Example with error handling:
*
* ```
* use Google\Cloud\Datastore\DatastoreClient;
*
* $datastore = new DatastoreClient;
*
* $handler = new DatastoreSessionHandler($datastore);
* session_set_save_handler($handler, true);
* session_save_path('sessions');
* session_start();
*
* // Then read and write the $_SESSION array.
*
* function handle_session_error($errNo, $errStr, $errFile, $errLine) {
* # We throw an exception here, but you can do whatever you need.
* throw new Exception("$errStr in $errFile on line $errLine", $errNo);
* }
* set_error_handler('handle_session_error', E_USER_WARNING);
* // If `write` fails for any reason, an exception will be thrown.
* session_write_close();
* restore_error_handler();
* // You can still read the $_SESSION array after closing the session.
* ```
* @see http://php.net/manual/en/class.sessionhandlerinterface.php SessionHandlerInterface
*/
class DatastoreSessionHandler implements SessionHandlerInterface
{
const DEFAULT_GC_LIMIT = 0;
/*
* @see https://cloud.google.com/datastore/docs/reference/rpc/google.datastore.v1#google.datastore.v1.PartitionId
*/
const NAMESPACE_ALLOWED_PATTERN = '/^[A-Za-z\d\.\-_]{0,100}$/';
const NAMESPACE_RESERVED_PATTERN = '/^__.*__$/';
/* @var int */
private $gcLimit;
/* @var DatastoreClient */
private $datastore;
/* @var string */
private $kind;
/* @var string */
private $namespaceId;
/* @var Transaction */
private $transaction;
/* @var array */
private $options;
/**
* Create a custom session handler backed by Cloud Datastore.
*
* @param DatastoreClient $datastore Datastore client.
* @param int $gcLimit [optional] A number of entities to delete in the
* garbage collection. Defaults to 0 which means it does nothing.
* The value larger than 1000 will be cut down to 1000.
* @param array $options [optional] {
* Configuration Options
*
* @type array $entityOptions Default options to be passed to the
* {@see \Google\Cloud\Datastore\DatastoreClient::entity()} method when writing session data to Datastore.
* If not specified, defaults to `['excludeFromIndexes' => ['data']]`.
* }
*/
public function __construct(
DatastoreClient $datastore,
$gcLimit = self::DEFAULT_GC_LIMIT,
array $options = []
) {
$this->datastore = $datastore;
// Cut down to 1000
$this->gcLimit = min($gcLimit, 1000);
if (!isset($options['entityOptions'])) {
$options['entityOptions'] = [
'excludeFromIndexes' => ['data']
];
}
if (!is_array($options['entityOptions'])) {
throw new InvalidArgumentException(
'Optional argument `entityOptions` must be an array, got ' .
(is_object($options['entityOptions'])
? get_class($options['entityOptions'])
: gettype($options['entityOptions']))
);
}
$this->options = $options;
}
/**
* Start a session, by creating a transaction for the later `write`.
*
* @param string $savePath The value of `session.save_path` setting will be
* used here. It will use this value as the Datastore namespaceId.
* @param string $sessionName The value of `session.name` setting will be
* used here. It will use this value as the Datastore kind.
* @return bool
*/
public function open($savePath, $sessionName)
{
$this->kind = $sessionName;
if (preg_match(self::NAMESPACE_ALLOWED_PATTERN, $savePath) !== 1 ||
preg_match(self::NAMESPACE_RESERVED_PATTERN, $savePath) === 1) {
throw new InvalidArgumentException(
sprintf('The given save_path "%s" not allowed', $savePath)
);
}
$this->namespaceId = $savePath;
$this->transaction = $this->datastore->transaction();
return true;
}
/**
* Just return true for this implementation.
*/
public function close()
{
return true;
}
/**
* Read the session data from Cloud Datastore.
*/
public function read($id)
{
try {
$key = $this->datastore->key(
$this->kind,
$id,
['namespaceId' => $this->namespaceId]
);
$entity = $this->transaction->lookup($key);
if ($entity !== null && isset($entity['data'])) {
return $entity['data'];
}
} catch (Exception $e) {
trigger_error(
sprintf('Datastore lookup failed: %s', $e->getMessage()),
E_USER_WARNING
);
}
return '';
}
/**
* Write the session data to Cloud Datastore.
*
* @param string $id Identifier used to construct a {@see \Google\Cloud\Datastore\Key}
* for the {@see \Google\Cloud\Datastore\Entity} to be written.
* @param string $data The session data to write to the {@see \Google\Cloud\Datastore\Entity}.
* @return bool
*/
public function write($id, $data)
{
try {
$key = $this->datastore->key(
$this->kind,
$id,
['namespaceId' => $this->namespaceId]
);
$entity = $this->datastore->entity(
$key,
[
'data' => $data,
't' => time()
],
$this->options['entityOptions']
);
$this->transaction->upsert($entity);
$this->transaction->commit();
} catch (Exception $e) {
trigger_error(
sprintf('Datastore upsert failed: %s', $e->getMessage()),
E_USER_WARNING
);
return false;
}
return true;
}
/**
* Delete the session data from Cloud Datastore.
*/
public function destroy($id)
{
try {
$key = $this->datastore->key(
$this->kind,
$id,
['namespaceId' => $this->namespaceId]
);
$this->transaction->delete($key);
$this->transaction->commit();
} catch (Exception $e) {
trigger_error(
sprintf('Datastore delete failed: %s', $e->getMessage()),
E_USER_WARNING
);
return false;
}
return true;
}
/**
* Delete the old session data from Cloud Datastore.
*/
public function gc($maxlifetime)
{
if ($this->gcLimit === 0) {
return true;
}
try {
$query = $this->datastore->query()
->kind($this->kind)
->filter('t', '<', time() - $maxlifetime)
->order('t')
->keysOnly()
->limit($this->gcLimit);
$result = $this->datastore->runQuery(
$query,
['namespaceId' => $this->namespaceId]
);
$keys = [];
/* @var Entity $e */
foreach ($result as $e) {
$keys[] = $e->key();
}
if (!empty($keys)) {
$this->datastore->deleteBatch($keys);
}
} catch (Exception $e) {
trigger_error(
sprintf('Session gc failed: %s', $e->getMessage()),
E_USER_WARNING
);
return false;
}
return true;
}
}