Skip to content

Commit a8693a9

Browse files
averikitschgrayside
authored andcommitted
docs(samples): Add HTTP Push Queue Sample (#199)
1 parent 9926469 commit a8693a9

File tree

7 files changed

+133
-82
lines changed

7 files changed

+133
-82
lines changed

cloud-tasks/README.md

+30-12
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,21 @@
11
# Node.js Google Cloud Tasks sample for Google App Engine
22

33
This sample application shows how to use [Google Cloud Tasks](https://cloud.google.com/cloud-tasks/)
4-
on Google App Engine [flexible environment][appengine-flex].
4+
on [Google App Engine][appengine].
55

6-
App Engine queues push tasks to an App Engine HTTP target. This directory
6+
This directory
77
contains both the App Engine app to deploy, as well as the snippets to run
88
locally to push tasks to it, which could also be called on App Engine.
99

1010
`createTask.js` is a simple command-line program to create tasks to be pushed to
1111
the App Engine app.
1212

13+
`createHttpTask.js` is a simple command-line program to create tasks to be pushed to
14+
a HTTP endpoint.
15+
1316
`server.js` is the main App Engine app. This app serves as an endpoint to
1417
receive App Engine task attempts.
1518

16-
`app.flexible.yaml` configures the app for App Engine Node.js flexible
17-
environment.
18-
1919
* [Setup](#setup)
2020
* [Running locally](#running-locally)
2121
* [Deploying to App Engine](#deploying-to-app-engine)
@@ -48,11 +48,11 @@ To create a queue using the Cloud SDK, use the following gcloud command:
4848
Note: A newly created queue will route to the default App Engine service and
4949
version unless configured to do otherwise.
5050

51-
## Deploying the app to App Engine flexible environment
51+
## Deploying the app to App Engine
5252

53-
Deploy the App Engine app with gcloud:
53+
Deploy to App Engine Standard environment with gcloud:
5454

55-
gcloud app deploy app.flexible.yaml
55+
gcloud app deploy
5656

5757
Verify the index page is serving:
5858

@@ -85,10 +85,12 @@ location is "us-central1").
8585
export LOCATION_ID=us-central1
8686
```
8787

88-
Create a task, targeted at the `log_payload` endpoint, with a payload specified:
88+
### Using App Engine Queues
89+
Running the sample will create a task, targeted at the `/log_payload`
90+
endpoint, with a payload specified:
8991

9092
```
91-
node createTask.js --project=$PROJECT_ID --queue=$QUEUE_ID --location=$LOCATION_ID --payload=hello
93+
node createTask.js $PROJECT_ID $LOCATION_ID $QUEUE_ID hello
9294
```
9395

9496
The App Engine app serves as a target for the push requests. It has an
@@ -101,9 +103,25 @@ Create a task that will be scheduled for a time in the future using the
101103
`--in_seconds` flag:
102104

103105
```
104-
node createTask.js --project=$PROJECT_ID --queue=$QUEUE_ID --location=$LOCATION_ID --payload=hello --in_seconds=30
106+
node createTask.js $PROJECT_ID $LOCATION_ID $QUEUE_ID hello 30
107+
```
108+
109+
### Using HTTP Push Queues
110+
111+
Set an environment variable for the endpoint to your task handler. This is an
112+
example url to send requests to the App Engine task handler:
113+
```
114+
export URL=https://<project_id>.appspot.com/log_payload
115+
```
116+
117+
Running the sample will create a task and send the task to the specific URL
118+
endpoint, with a payload specified:
119+
120+
```
121+
node createHttpTask $PROJECT_ID $LOCATION_ID $QUEUE_ID $URL hello
105122
```
106123

124+
## More Info
107125

108126
To get usage information: `node createTask.js --help`
109127

@@ -125,5 +143,5 @@ Examples:
125143
For more information, see https://cloud.google.com/cloud-tasks
126144
```
127145

128-
[appengine-flex]: https://cloud.google.com/appengine/docs/flexible/nodejs
146+
[appengine]: https://cloud.google.com/appengine/docs/nodejs
129147
[appengine-std]: https://cloud.google.com/appengine/docs/standard/nodejs

cloud-tasks/app.flexible.yaml renamed to cloud-tasks/app.yaml

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright 2018, Google, Inc.
1+
# Copyright 2019 Google LLC
22
# Licensed under the Apache License, Version 2.0 (the "License");
33
# you may not use this file except in compliance with the License.
44
# You may obtain a copy of the License at
@@ -11,5 +11,4 @@
1111
# See the License for the specific language governing permissions and
1212
# limitations under the License.
1313

14-
env: flex
15-
runtime: nodejs
14+
runtime: nodejs10

cloud-tasks/createHttpTask.js

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/**
2+
* Copyright 2019 Google LLC
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*/
15+
16+
'use strict';
17+
18+
/**
19+
* Create a task with an HTTP target for a given queue with an arbitrary payload.
20+
*/
21+
async function createHttpTask(
22+
project,
23+
location,
24+
queue,
25+
url,
26+
payload,
27+
inSeconds
28+
) {
29+
// [START cloud_tasks_create_http_task]
30+
// Imports the Google Cloud Tasks library.
31+
const {v2beta3} = require('@google-cloud/tasks');
32+
33+
// Instantiates a client.
34+
const client = new v2beta3.CloudTasksClient();
35+
36+
// TODO(developer): Uncomment these lines and replace with your values.
37+
// const project = 'my-project-id';
38+
// const queue = 'my-appengine-queue';
39+
// const location = 'us-central1';
40+
// const url = 'https://<project-id>.appspot.com/log_payload'
41+
// const options = {payload: 'hello'};
42+
43+
// Construct the fully qualified queue name.
44+
const parent = client.queuePath(project, location, queue);
45+
46+
const task = {
47+
httpRequest: {
48+
httpMethod: 'POST',
49+
url, //The full url path that the request will be sent to.
50+
},
51+
};
52+
53+
if (payload) {
54+
task.httpRequest.body = Buffer.from(payload).toString('base64');
55+
}
56+
57+
if (inSeconds) {
58+
task.scheduleTime = {
59+
seconds: inSeconds + Date.now() / 1000,
60+
};
61+
}
62+
63+
const request = {
64+
parent: parent,
65+
task: task,
66+
};
67+
68+
console.log('Sending task:');
69+
console.log(task);
70+
// Send create task request.
71+
const [response] = await client.createTask(request);
72+
const name = response.name;
73+
console.log(`Created task ${name}`);
74+
75+
// [END cloud_tasks_create_http_task]
76+
}
77+
78+
createHttpTask(...process.argv.slice(2)).catch(console.error);

cloud-tasks/createTask.js

+11-64
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* Copyright 2018, Google, Inc.
2+
* Copyright 2019 Google LLC
33
* Licensed under the Apache License, Version 2.0 (the "License");
44
* you may not use this file except in compliance with the License.
55
* You may obtain a copy of the License at
@@ -18,14 +18,14 @@
1818
/**
1919
* Create a task for a given queue with an arbitrary payload.
2020
*/
21-
async function createTask(project, location, queue, options) {
21+
async function createTask(project, location, queue, payload, inSeconds) {
2222
// [START cloud_tasks_appengine_create_task]
2323
// [START tasks_quickstart]
2424
// Imports the Google Cloud Tasks library.
25-
const cloudTasks = require('@google-cloud/tasks');
25+
const {CloudTasksClient} = require('@google-cloud/tasks');
2626

2727
// Instantiates a client.
28-
const client = new cloudTasks.CloudTasksClient();
28+
const client = new CloudTasksClient();
2929

3030
// TODO(developer): Uncomment these lines and replace with your values.
3131
// const project = 'my-project-id';
@@ -43,15 +43,13 @@ async function createTask(project, location, queue, options) {
4343
},
4444
};
4545

46-
if (options.payload !== undefined) {
47-
task.appEngineHttpRequest.body = Buffer.from(options.payload).toString(
48-
'base64'
49-
);
46+
if (payload) {
47+
task.appEngineHttpRequest.body = Buffer.from(payload).toString('base64');
5048
}
5149

52-
if (options.inSeconds !== undefined) {
50+
if (inSeconds) {
5351
task.scheduleTime = {
54-
seconds: options.inSeconds + Date.now() / 1000,
52+
seconds: inSeconds + Date.now() / 1000,
5553
};
5654
}
5755

@@ -60,7 +58,8 @@ async function createTask(project, location, queue, options) {
6058
task: task,
6159
};
6260

63-
console.log('Sending task %j', task);
61+
console.log('Sending task:');
62+
console.log(task);
6463
// Send create task request.
6564
const [response] = await client.createTask(request);
6665
const name = response.name;
@@ -70,56 +69,4 @@ async function createTask(project, location, queue, options) {
7069
// [END tasks_quickstart]
7170
}
7271

73-
const cli = require(`yargs`)
74-
.options({
75-
location: {
76-
alias: 'l',
77-
description: 'Location of the queue to add the task to.',
78-
type: 'string',
79-
requiresArg: true,
80-
required: true,
81-
},
82-
queue: {
83-
alias: 'q',
84-
description: 'ID (short name) of the queue to add the task to.',
85-
type: 'string',
86-
requiresArg: true,
87-
required: true,
88-
},
89-
project: {
90-
alias: 'p',
91-
description: 'Project of the queue to add the task to.',
92-
default: process.env.GCLOUD_PROJECT,
93-
type: 'string',
94-
requiresArg: true,
95-
required: true,
96-
},
97-
payload: {
98-
alias: 'd',
99-
description: '(Optional) Payload to attach to the push queue.',
100-
type: 'string',
101-
requiresArg: true,
102-
},
103-
inSeconds: {
104-
alias: 's',
105-
description:
106-
'(Optional) The number of seconds from now to schedule task attempt.',
107-
type: 'number',
108-
requiresArg: true,
109-
},
110-
})
111-
.example(`node $0 --project my-project-id`)
112-
.wrap(120)
113-
.recommendCommands()
114-
.epilogue(`For more information, see https://cloud.google.com/cloud-tasks`)
115-
.strict();
116-
117-
if (module === require.main) {
118-
const opts = cli.help().parse(process.argv.slice(2));
119-
process.env.GCLOUD_PROJECT = opts.project;
120-
createTask(opts.project, opts.location, opts.queue, opts).catch(
121-
console.error
122-
);
123-
}
124-
125-
exports.createTask = createTask;
72+
createTask(...process.argv.slice(2)).catch(console.error);

cloud-tasks/package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,8 @@
88
"node": ">=8"
99
},
1010
"scripts": {
11-
"test": "mocha"
11+
"test": "mocha",
12+
"start": "node server.js"
1213
},
1314
"dependencies": {
1415
"@google-cloud/tasks": "^0.5.0",

cloud-tasks/server.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
/**
2-
* Copyright 2018, Google, Inc.
2+
* Copyright 2019 Google LLC
33
* Licensed under the Apache License, Version 2.0 (the "License");
44
* you may not use this file except in compliance with the License.
55
* You may obtain a copy of the License at

cloud-tasks/test/test.samples.js

+9-1
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});
2222

2323
const PROJECT_ID = process.env.GCLOUD_PROJECT;
2424
const queueName = `gcloud-${uuid.v4().split('-')[0]}`;
25+
const URL = `https://${PROJECT_ID}.appspot.com/log_payload`;
2526

2627
describe('Cloud Task Sample Tests', () => {
2728
it('should create a queue', () => {
@@ -31,7 +32,14 @@ describe('Cloud Task Sample Tests', () => {
3132

3233
it('should create a task', () => {
3334
const stdout = execSync(
34-
`node createTask --project=${PROJECT_ID} --location=us-central1 --queue=${queueName}`
35+
`node createTask ${PROJECT_ID} us-central1 ${queueName}`
36+
);
37+
assert.match(stdout, /Created task/);
38+
});
39+
40+
it('should create a HTTP task', () => {
41+
const stdout = execSync(
42+
`node createHttpTask ${PROJECT_ID} us-central1 my-appengine-queue ${URL}`
3543
);
3644
assert.match(stdout, /Created task/);
3745
});

0 commit comments

Comments
 (0)