Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add run_events_pubsub #1809

Merged
merged 11 commits into from
May 20, 2020
2 changes: 2 additions & 0 deletions run/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
|[Cloud SQL (MySQL)][mysql] | Use MySQL with Cloud Run | - |
|[Cloud SQL (Postgres)][postgres] | Use Postgres with Cloud Run | - |
|[Hello Broken][hello_broken] | Something is wrong, how do you fix it? | [<img src="https://storage.googleapis.com/cloudrun/button.svg" alt="Run on Google Cloud" height="30"/>][run_button_hello_broken] |
|[Events – Pub/Sub][events_pubsub] | Use Pub/Sub with Cloud Run | - |
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we should have this description parallel the Pub/Sub description more, and be moved right under it. Might want to flag it as alpha if we're going to "advertise" it here.

Suggested change
|[Events – Pub/Sub][events_pubsub] | Use Pub/Sub with Cloud Run | - |
|[Events – Pub/Sub][events_pubsub] | Event-driven service with Events for Cloud Run for Pub/Sub | - |

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree we can move the Pub/Sub trigger next to the other Pub/Sub sample.

I disagree that we should change the title in this way.
Cloud Run is not_for_ Pub/Sub.
Pub/Sub is a trigger/event type for Cloud Run.

Once public, we should remove the non-native Pub/Sub sample.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The core feedback here is that the two samples should be listed next to each other, and with similar enough structure in their descriptions to make differentiation easy.

Whether one of them is removed at GA is a good question.


For more Cloud Run samples beyond Node.js, see the main list in the [Cloud Run Samples repository](https://github.com/GoogleCloudPlatform/cloud-run-samples).

Expand Down Expand Up @@ -127,3 +128,4 @@ for more information.
[run_button_image_processing]: https://deploy.cloud.run/?git_repo=https://github.com/GoogleCloudPlatform/nodejs-docs-samples&dir=run/image-processing
[run_button_manual_logging]: https://deploy.cloud.run/?git_repo=https://github.com/GoogleCloudPlatform/nodejs-docs-samples&dir=run/logging-manual
[run_button_hello_broken]: https://deploy.cloud.run/?git_repo=https://github.com/GoogleCloudPlatform/nodejs-docs-samples&dir=run/hello-broken
[events_pubsub]: https://deploy.cloud.run/?git_repo=https://github.com/GoogleCloudPlatform/nodejs-docs-samples&dir=run/events-pubsub
4 changes: 4 additions & 0 deletions run/events-pubsub/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Dockerfile
.dockerignore
node_modules
npm-debug.log
3 changes: 3 additions & 0 deletions run/events-pubsub/.gcloudignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.git
node_modules
npm-debug.log
1 change: 1 addition & 0 deletions run/events-pubsub/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
grant marked this conversation as resolved.
Show resolved Hide resolved
30 changes: 30 additions & 0 deletions run/events-pubsub/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Copyright 2019 Google LLC. All rights reserved.
grant marked this conversation as resolved.
Show resolved Hide resolved
# Use of this source code is governed by the Apache 2.0
# license that can be found in the LICENSE file.

# [START run_pubsub_dockerfile]
grant marked this conversation as resolved.
Show resolved Hide resolved

# Use the official lightweight Node.js 10 image.
# https://hub.docker.com/_/node
FROM node:10-slim

# Create and change to the app directory.
WORKDIR /usr/src/app

# Copy application dependency manifests to the container image.
# A wildcard is used to ensure both package.json AND package-lock.json are copied.
# Copying this separately prevents re-running npm install on every code change.
COPY package*.json ./

# Install dependencies.
# If you add a package-lock.json speed your build by switching to 'npm ci'.
# RUN npm ci --only=production
RUN npm install --production

# Copy local code to the container image.
COPY . .

# Run the web service on container startup.
CMD [ "npm", "start" ]

# [END run_pubsub_dockerfile]
35 changes: 35 additions & 0 deletions run/events-pubsub/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Events for Cloud Run – Pub/Sub tutorial
grant marked this conversation as resolved.
Show resolved Hide resolved

This sample shows how to create a service that processes Pub/Sub messages.

For more details on how to work with this sample read the [Google Cloud Run Node.js Samples README](https://github.com/GoogleCloudPlatform/nodejs-docs-samples/tree/master/run).

## Dependencies

* **express**: Web server framework.
* **body-parser**: express middleware for request payload processing.
* **mocha**: [development] Test running framework.
* **supertest**: [development] HTTP assertion test client.

## Quickstart

```sh
grant marked this conversation as resolved.
Show resolved Hide resolved
gcloud pubsub topics create my-topic

gcloud alpha events triggers create pubsub-trigger \
--target-service cloudrun-events \
--type com.google.cloud.pubsub.topic.publish \
--parameters topic=my-topic

gcloud builds submit \
--tag gcr.io/$(gcloud config get-value project)/"$MY_RUN_CONTAINER"
gcloud run deploy "$MY_RUN_SERVICE" \
grant marked this conversation as resolved.
Show resolved Hide resolved
--image gcr.io/$(gcloud config get-value project)/"$MY_RUN_CONTAINER" \
--allow-unauthenticated # Note: The "allowed unauthenticated requests" flag is not needed in production.
grant marked this conversation as resolved.
Show resolved Hide resolved
```

Test:

```
gcloud pubsub topics publish my-topic --message="Hello there"
```
37 changes: 37 additions & 0 deletions run/events-pubsub/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// Copyright 2019 Google LLC. All rights reserved.
grant marked this conversation as resolved.
Show resolved Hide resolved
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.

// [START run_events_pubsub_server_setup]
const express = require('express');
const bodyParser = require('body-parser');
grant marked this conversation as resolved.
Show resolved Hide resolved
const app = express();

app.use(bodyParser.json());
// [END run_events_pubsub_server_setup]

// [START run_events_pubsub_handler]
app.post('/', (req, res) => {
if (!req.body) {
const msg = 'no Pub/Sub message received';
res.status(400).send(`Bad Request: ${msg}`);
return;
}
if (!req.body.message) {
const msg = 'invalid Pub/Sub message format';
res.status(400).send(`Bad Request: ${msg}`);
return;
}
const pubSubMessage = req.body.message;
const name = pubSubMessage.data
? Buffer.from(pubSubMessage.data, 'base64').toString().trim()
: 'World';

res.send({
grant marked this conversation as resolved.
Show resolved Hide resolved
message: `Hello, ${name}!`,
id: req.get('ce-id')
});
});

module.exports = app;
// [END run_events_pubsub_handler]
12 changes: 12 additions & 0 deletions run/events-pubsub/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// Copyright 2019 Google LLC. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.

// [START run_pubsub_server]
const app = require('./app.js');
const PORT = process.env.PORT || 8080;

app.listen(PORT, () =>
console.log(`nodejs-run-events-pubsub listening on port ${PORT}`)
);
// [END run_pubsub_server]
30 changes: 30 additions & 0 deletions run/events-pubsub/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "cloud-run-events-pubsub",
"version": "1.0.0",
"private": true,
"description": "Simple Events for Cloud Run – Pub/Sub sample",
"main": "index.js",
"author": "Google LLC",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git"
},
"engines": {
"node": ">= 8.0.0"
},
"scripts": {
"start": "node index.js",
"test": "mocha test/*.test.js --check-leaks"
},
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.16.4"
},
"devDependencies": {
"mocha": "^7.0.0",
"sinon": "^9.0.0",
"supertest": "^4.0.2",
"uuid": "^8.0.0"
}
}
73 changes: 73 additions & 0 deletions run/events-pubsub/test/app.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// Copyright 2019, Google LLC.
// 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.

// NOTE:
// This app can only be fully tested when deployed, because
// Pub/Sub requires a live endpoint URL to hit. Nevertheless,
// these tests mock it and partially test it locally.

'use strict';

const assert = require('assert');
const path = require('path');
const supertest = require('supertest');

let request;

describe('Unit Tests', () => {
before(() => {
const app = require(path.join(__dirname, '..', 'app'));
request = supertest(app);
});

describe('should fail', () => {
it(`on a Bad Request with an empty payload`, async () => {
await request.post('/').type('json').send('').expect(400);
});

it(`on a Bad Request with an invalid payload`, async () => {
await request
.post('/')
.type('json')
.send({nomessage: 'invalid'})
.expect(400);
});

it(`on a Bad Request with an invalid mimetype`, async () => {
await request.post('/').type('text').send('{message: true}').expect(400);
});
});

describe('should succeed', () => {
it(`with a minimally valid Pub/Sub Message`, async () => {
await request
.post('/')
.type('json')
.send({message: true})
.expect((res) => {
assert.equal(res.body.message, 'Hello, World!');
});
});

it(`with CloudEvent HTTP headers`, async () => {
await request
.post('/')
.type('json')
.set('ce-id', 1234)
.send({message: true})
.expect((res) => {
assert.equal(res.body.id, 1234);
});
});
});
});