Skip to content

Commit acb6e80

Browse files
authored
updates flex datastore for google/cloud and region tags (GoogleCloudPlatform#280)
1 parent 3948959 commit acb6e80

File tree

5 files changed

+225
-291
lines changed

5 files changed

+225
-291
lines changed

appengine/flexible/datastore/app.php

Lines changed: 48 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -15,29 +15,65 @@
1515
* limitations under the License.
1616
*/
1717

18+
use Google\Cloud\Datastore\DatastoreClient;
1819
use Silex\Application;
1920
use Symfony\Component\HttpFoundation\Request;
2021
use Symfony\Component\HttpFoundation\Response;
2122

2223
// create the Silex application
2324
$app = new Application();
2425

25-
$app['datastore'] = function () {
26-
// Datastore API has intermittent failures, so we set the
27-
// Google Client to retry in the event of a 503 Backend Error
28-
$retryConfig = ['retries' => 2 ];
29-
$client = new \Google_Client(['retry' => $retryConfig ]);
30-
$client->setScopes([
31-
Google_Service_Datastore::CLOUD_PLATFORM,
32-
Google_Service_Datastore::DATASTORE,
26+
$app['datastore'] = function () use ($app) {
27+
$projectId = $app['project_id'];
28+
# [START create_client]
29+
$datastore = new DatastoreClient([
30+
'projectId' => $projectId
3331
]);
34-
$client->useApplicationDefaultCredentials();
35-
return new \Google_Service_Datastore($client);
32+
# [END create_client]
33+
return $datastore;
3634
};
3735

3836
$app->get('/', function (Application $app, Request $request) {
37+
if (empty($app['project_id'])) {
38+
return 'Set the GCLOUD_PROJECT environment variable to run locally';
39+
}
3940
/** @var \Google_Service_Datastore $datastore */
4041
$datastore = $app['datastore'];
42+
43+
// determine the user's IP
44+
$user_ip = get_user_ip($request);
45+
46+
# [START insert_entity]
47+
// Create an entity to insert into datastore.
48+
$key = $datastore->key('visit');
49+
$entity = $datastore->entity($key, [
50+
'user_ip' => $user_ip,
51+
'timestamp' => new DateTime(),
52+
]);
53+
$datastore->insert($entity);
54+
# [END insert_entity]
55+
56+
# [START run_query]
57+
// Query recent visits.
58+
$query = $datastore->query()
59+
->kind('visit')
60+
->order('timestamp', 'DESCENDING')
61+
->limit(10);
62+
$results = $datastore->runQuery($query);
63+
$visits = [];
64+
foreach ($results as $entity) {
65+
$visits[] = sprintf('Time: %s Addr: %s',
66+
$entity['timestamp']->format('Y-m-d H:i:s'),
67+
$entity['user_ip']);
68+
}
69+
# [END run_query]
70+
array_unshift($visits, "Last 10 visits:");
71+
return new Response(implode("\n", $visits), 200,
72+
['Content-Type' => 'text/plain']);
73+
});
74+
75+
function get_user_ip(Request $request)
76+
{
4177
$ip = $request->GetClientIp();
4278
// Keep only the first two octets of the IP address.
4379
$octets = explode($separator = ':', $ip);
@@ -52,60 +88,7 @@
5288
return $x == '' ? '0' : $x;
5389
}, $octets);
5490
$user_ip = $octets[0] . $separator . $octets[1];
55-
// Create an entity to insert into datastore.
56-
$key = new \Google_Service_Datastore_Key(['path' => ['kind' => 'visit']]);
57-
$date = new DateTime();
58-
$date->setTimezone(new DateTimeZone('UTC'));
59-
$properties = [
60-
'user_ip' => ['stringValue' => $user_ip],
61-
'timestamp' => ['timestampValue' => $date->format("Y-m-d\TH:i:s\Z")]
62-
];
63-
$entity = new \Google_Service_Datastore_Entity([
64-
'key' => $key,
65-
'properties' => $properties
66-
]);
67-
68-
// Use "NON_TRANSACTIONAL" for simplicity. However, it means that we may
69-
// not see this result in the query below.
70-
$request = new \Google_Service_Datastore_CommitRequest([
71-
'mode' => 'NON_TRANSACTIONAL',
72-
'mutations' => [
73-
[
74-
'insert' => $entity,
75-
]
76-
]
77-
]);
78-
$dataset_id = $app['google.dataset_id'];
79-
$datastore->projects->commit($dataset_id, $request);
80-
81-
$query = new \Google_Service_Datastore_Query([
82-
'kind' => [
83-
[
84-
'name' => 'visit',
85-
],
86-
],
87-
'order' => [
88-
'property' => [
89-
'name' => 'timestamp',
90-
],
91-
'direction' => 'DESCENDING',
92-
],
93-
'limit' => 10,
94-
]);
95-
$request = new \Google_Service_Datastore_RunQueryRequest();
96-
$request->setQuery($query);
97-
$response = $datastore->projects->runQuery($dataset_id, $request);
98-
/** @var \Google_Service_Datastore_QueryResultBatch $batch */
99-
$batch = $response->getBatch();
100-
$visits = ["Last 10 visits:"];
101-
foreach ($batch->getEntityResults() as $entityResult) {
102-
$properties = $entityResult->getEntity()->getProperties();
103-
array_push($visits, sprintf('Time: %s Addr: %s',
104-
$properties['timestamp']['timestampValue'],
105-
$properties['user_ip']['stringValue']));
106-
}
107-
return new Response(implode("\n", $visits), 200,
108-
['Content-Type' => 'text/plain']);
109-
});
91+
return $user_ip;
92+
}
11093

11194
return $app;

appengine/flexible/datastore/composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"require": {
33
"silex/silex": "^1.3",
4-
"google/apiclient": "^2.0"
4+
"google/cloud": "^0.20"
55
},
66
"require-dev": {
77
"google/cloud-tools": "^0.6",

0 commit comments

Comments
 (0)