Skip to content

Commit 8d21038

Browse files
authored
appengine/php72/tasks: update create task and add task handler app (GoogleCloudPlatform#746)
This PR updates the Cloud Tasks create task sample to Beta v2.3 and moves it inside AppEngine in alignment with other Cloud Tasks for App Engine Queue samples. Additional, there is a "task handler" app which demonstrates how to handle a Cloud Tasks http request for work to be done. The snippet is following new structural trends demonstrated in Bigquery.
1 parent 00f6623 commit 8d21038

File tree

14 files changed

+354
-201
lines changed

14 files changed

+354
-201
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Google Cloud Tasks Handler on App Engine Standard for PHP 7.2
2+
3+
The Task Handler sample application demonstrates how to handle a task from a Cloud Tasks Appengine Queue.
4+
5+
## Setup the sample
6+
7+
- Install [`composer`](https://getcomposer.org)
8+
- Install dependencies by running:
9+
```sh
10+
composer install
11+
```
12+
- Install the [Google Cloud SDK](https://developers.google.com/cloud/sdk/).
13+
14+
## Deploy the sample
15+
16+
### Deploy with `gcloud`
17+
18+
Deploy the samples by doing the following:
19+
20+
```
21+
gcloud config set project YOUR_PROJECT_ID
22+
gcloud app deploy
23+
gcloud app browse
24+
```
25+
26+
The last command will open `https://{YOUR_PROJECT_ID}.appspot.com/`
27+
in your browser. Browse to `/` to send in some logs.
28+
29+
### Run Locally
30+
31+
Run the sample locally using PHP's build-in web server:
32+
33+
```
34+
# export environemnt variables locally which are set by App Engine when deployed
35+
export GOOGLE_APPLICATION_CREDENTIALS=/path/to/credentials.json
36+
export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID
37+
38+
# Run PHP's built-in web server
39+
php -S localhost:8000
40+
```
41+
42+
Browse to `localhost:8000` to send in the logs.
43+
44+
> Note: These logs will show up under the `Global` resource since you are not
45+
actually sending these from App Engine.
46+
47+
## Contributing changes
48+
49+
* See [CONTRIBUTING.md](../../CONTRIBUTING.md)
50+
51+
## Licensing
52+
53+
* See [LICENSE](../../LICENSE)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
runtime: php72
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{
2+
"require": {
3+
"google/cloud-tasks": "^0.4.1",
4+
"google/cloud-logging": "^1.14"
5+
},
6+
"require-dev": {
7+
"phpunit/phpunit": "^5",
8+
"google/cloud-tools": "^0.8.5"
9+
}
10+
}
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
<?php
2+
/**
3+
* Copyright 2018 Google LLC.
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
// [START cloud_tasks_appengine_quickstart]
19+
20+
require __DIR__ . '/vendor/autoload.php';
21+
22+
use Google\Cloud\Logging\LoggingClient;
23+
24+
// Create the logging client.
25+
$logging = new LoggingClient();
26+
// Create a PSR-3-compatible logger.
27+
$logger = $logging->psrLogger('app', ['batchEnabled' => true]);
28+
29+
// Front-controller to route requests.
30+
switch (@parse_url($_SERVER['REQUEST_URI'])['path']) {
31+
case '/':
32+
print "Hello, World!\n";
33+
break;
34+
case '/task_handler':
35+
// Taskname and Queuename are two of several useful Cloud Tasks headers available on the request.
36+
$taskName = $_SERVER['HTTP_X_APPENGINE_TASKNAME'] ?? '';
37+
$queueName = $_SERVER['HTTP_X_APPENGINE_QUEUENAME'] ?? '';
38+
39+
try {
40+
handle_task(
41+
$queueName,
42+
$taskName,
43+
file_get_contents('php://input')
44+
);
45+
} catch (Exception $e) {
46+
http_response_code(400);
47+
exit($e->getMessage());
48+
}
49+
break;
50+
default:
51+
http_response_code(404);
52+
exit('Not Found');
53+
}
54+
55+
/**
56+
* Process a Cloud Tasks HTTP Request.
57+
*
58+
* @param string $queueName provides the name of the queue which dispatched the task.
59+
* @param string $taskName provides the identifier of the task.
60+
* @param string $body The task details from the HTTP request.
61+
*/
62+
function handle_task($queueName, $taskName, $body = '')
63+
{
64+
global $logger;
65+
66+
if (empty($taskName)) {
67+
// You may use the presence of the X-Appengine-Taskname header to validate
68+
// the request comes from Cloud Tasks.
69+
$logger->warning('Invalid Task: No X-Appengine-Taskname request header found');
70+
throw new Exception('Bad Request - Invalid Task');
71+
}
72+
73+
$output = sprintf('Completed task: task queue(%s), task name(%s), payload(%s)', $queueName, $taskName, $body);
74+
$logger->info($output);
75+
76+
// Set a non-2xx status code to indicate a failure in task processing that should be retried.
77+
// For example, http_response_code(500) to indicate a server error.
78+
print $output;
79+
}
80+
81+
// [END cloud_tasks_appengine_quickstart]
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
Copyright 2018 Google LLC.
4+
5+
Licensed under the Apache License, Version 2.0 (the "License");
6+
you may not use this file except in compliance with the License.
7+
You may obtain a copy of the License at
8+
9+
http://www.apache.org/licenses/LICENSE-2.0
10+
11+
Unless required by applicable law or agreed to in writing, software
12+
distributed under the License is distributed on an "AS IS" BASIS,
13+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
See the License for the specific language governing permissions and
15+
limitations under the License.
16+
-->
17+
<phpunit bootstrap="vendor/autoload.php">
18+
<testsuites>
19+
<testsuite name="AppEngine for PHP 7.2 tasks test">
20+
<directory>test</directory>
21+
</testsuite>
22+
</testsuites>
23+
<logging>
24+
<log type="coverage-clover" target="build/logs/clover.xml"/>
25+
</logging>
26+
<filter>
27+
<whitelist>
28+
<file>index.php</file>
29+
</whitelist>
30+
</filter>
31+
</phpunit>
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
<?php
2+
/**
3+
* Copyright 2018 Google LLC
4+
*
5+
* Licensed under the Apache License, Version 2.0 (the "License");
6+
* you may not use this file except in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
use Google\Cloud\TestUtils\TestTrait;
19+
use Google\Cloud\TestUtils\AppEngineDeploymentTrait;
20+
use Google\Cloud\TestUtils\EventuallyConsistentTestTrait;
21+
use GuzzleHttp\Exception\ClientException;
22+
23+
use PHPUnit\Framework\TestCase;
24+
25+
class DeployTest extends TestCase
26+
{
27+
use TestTrait;
28+
use AppEngineDeploymentTrait;
29+
use EventuallyConsistentTestTrait;
30+
31+
public function testIndex()
32+
{
33+
// Access the modules app top page.
34+
$response = $this->client->get('');
35+
$this->assertEquals('200', $response->getStatusCode());
36+
$this->assertContains(
37+
'Hello, World!',
38+
$response->getBody()->getContents()
39+
);
40+
}
41+
42+
public function testTaskHandlerInvalid() {
43+
$this->expectException(ClientException::class);
44+
$response = $this->client->get('/task_handler');
45+
}
46+
}
Lines changed: 36 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,10 @@
1-
# Google Cloud Tasks Pull Queue Samples
1+
# Google Cloud Tasks App Engine Queue Samples
22

3-
## THIS SAMPLE IS CURRENTLY INCOMPLETE. PLEASE REFER TO [THE DOCUMENTATION](https://cloud.google.com/tasks/docs/)
3+
## Description
44

5-
Sample command-line program for interacting with the Google Cloud Tasks API.
6-
7-
`tasks.php` is a simple command-line program to demonstrate listing queues,
8-
creating tasks, and pulling and acknowledging tasks.
9-
10-
`src/create_task.php` is a simple function to create pull queue tasks.
5+
Al code in the snippets directory demonstrate how to invoke Cloud Tasks from PHP.
116

7+
`src/create_task.php` is a simple function to create app engine queue tasks.
128

139
## Setup:
1410

@@ -22,17 +18,45 @@ Sample command-line program for interacting with the Google Cloud Tasks API.
2218

2319
```sh
2420
$ git clone https://github.com/GoogleCloudPlatform/php-docs-samples
25-
$ cd php-docs-samples/tasks
21+
$ cd php-docs-samples/appengine/php72/tasks
2622
```
2723
4. **Install dependencies** via [Composer](http://getcomposer.org/doc/00-intro.md).
2824
Run `php composer.phar install` (if composer is installed locally) or `composer install`
2925
(if composer is installed globally).
3026

31-
## Creating a queue
27+
5. Create a Queue
28+
To create a queue using the Cloud SDK, use the following gcloud command:
29+
```sh
30+
gcloud beta tasks queues create-app-engine-queue my-appengine-queue
31+
```
32+
6. Identify the Location
3233

33-
To create a queue using the Cloud SDK, use the following gcloud command:
34+
Determine the location ID, which can be discovered with
35+
`gcloud alpha tasks queues describe $QUEUE_ID`, with the location embedded in
36+
the "name" value (for instance, if the name is
37+
"projects/my-project/locations/us-central1/queues/my-pull-queue", then the
38+
location is "us-central1").
39+
40+
7. Run `php src/SNIPPET_NAME.php`. The usage will print for each if no arguments are provided:
41+
42+
```
43+
$> php src/create_task.php
44+
Usage: php src/create_task.php PROJECT_ID LOCATION_ID QUEUE_ID [PAYLOAD]
45+
```
46+
47+
## Contributing changes
48+
49+
* See [CONTRIBUTING.md](../../CONTRIBUTING.md)
50+
51+
## Licensing
52+
53+
* See [LICENSE](../../LICENSE)
54+
55+
56+
57+
58+
## Creating a queue
3459

35-
gcloud beta tasks queues create-app-engine-queue my-appengine-queue
3660

3761
## Running the Samples
3862

@@ -49,14 +73,3 @@ created can be listed with `gcloud alpha tasks queues list`.
4973

5074
export QUEUE_ID=my-appengine-queue
5175

52-
And finally the location ID, which can be discovered with
53-
`gcloud alpha tasks queues describe $QUEUE_ID`, with the location embedded in
54-
the "name" value (for instance, if the name is
55-
"projects/my-project/locations/us-central1/queues/my-pull-queue", then the
56-
location is "us-central1").
57-
58-
export LOCATION_ID=us-central1
59-
60-
Create a task for a queue:
61-
62-
php tasks.php create-task $PROJECT_ID $QUEUE_ID $LOCATION_ID --payload=hello
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"require": {
3+
"google/cloud-tasks": "^0.4.1"
4+
},
5+
"require-dev": {
6+
"phpunit/phpunit": "^5",
7+
"google/cloud-tools": "^0.8.5"
8+
}
9+
}

tasks/phpunit.xml renamed to appengine/php72/tasks/snippets/phpunit.xml.dist

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<?xml version="1.0" encoding="UTF-8"?>
22
<!--
3-
Copyright 2017 Google Inc.
3+
Copyright 2018 Google LLC.
44
55
Licensed under the Apache License, Version 2.0 (the "License");
66
you may not use this file except in compliance with the License.
@@ -25,10 +25,7 @@
2525
</logging>
2626
<filter>
2727
<whitelist>
28-
<file>app.php</file>
28+
<directory suffix=".php">./src</directory>
2929
</whitelist>
3030
</filter>
31-
<php>
32-
<env name="PHPUNIT_TESTS" value="1"/>
33-
</php>
3431
</phpunit>

0 commit comments

Comments
 (0)