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

fix(functions): Fix/update GCF Memorystore sample #2780

Merged
merged 4 commits into from
Nov 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions .github/workflows/functions-memorystore.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
name: functions-memorystore
on:
push:
branches:
- main
paths:
- 'functions/memorystore/redis/**'
pull_request:
paths:
- 'functions/memorystore/redis/**'
pull_request_target:
types: [labeled]
schedule:
- cron: '0 0 * * 0'
jobs:
test:
if: ${{ github.event.action != 'labeled' || github.event.label.name == 'actions:force-run' }}
runs-on: ubuntu-latest
timeout-minutes: 60
permissions:
contents: 'write'
pull-requests: 'write'
id-token: 'write'
steps:
- uses: actions/checkout@v3
with:
ref: ${{github.event.pull_request.head.ref}}
repository: ${{github.event.pull_request.head.repo.full_name}}
- uses: google-github-actions/auth@v1.0.0
with:
workload_identity_provider: 'projects/1046198160504/locations/global/workloadIdentityPools/github-actions-pool/providers/github-actions-provider'
service_account: 'kokoro-system-test@long-door-651.iam.gserviceaccount.com'
create_credentials_file: 'true'
access_token_lifetime: 600s
- uses: actions/setup-node@v3
with:
node-version: 14
- run: npm install
working-directory: functions/memorystore/redis
- run: npm test
working-directory: functions/memorystore/redis
env:
MOCHA_REPORTER_SUITENAME: functions_memorystore
MOCHA_REPORTER_OUTPUT: functions_memorystore_sponge_log.xml
MOCHA_REPORTER: xunit
- if: ${{ github.event.action == 'labeled' && github.event.label.name == 'actions:force-run' }}
uses: actions/github-script@v6
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
try {
await github.rest.issues.removeLabel({
name: 'actions:force-run',
owner: 'GoogleCloudPlatform',
repo: 'nodejs-docs-samples',
issue_number: context.payload.pull_request.number
});
} catch (e) {
if (!e.message.includes('Label does not exist')) {
throw e;
}
}
- if: ${{ github.event_name == 'schedule' && always() }}
run: |
curl https://github.com/googleapis/repo-automation-bots/releases/download/flakybot-1.1.0/flakybot -o flakybot -s -L
chmod +x ./flakybot
./flakybot --repo GoogleCloudPlatform/nodejs-docs-samples --commit_hash ${{github.sha}} --build_url https://github.com/${{github.repository}}/actions/runs/${{github.run_id}}
2 changes: 2 additions & 0 deletions functions/memorystore/redis/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@
See:

* [Cloud Functions Cloud Memorystore sample source code][code]
* [Connecting to a Redis instance from Cloud Functions][tutorial]

[code]: index.js
[tutorial]: https://cloud.google.com/memorystore/docs/redis/connect-redis-instance-functions
14 changes: 6 additions & 8 deletions functions/memorystore/redis/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,32 +16,30 @@

// [START functions_memorystore_redis]

const {promisify} = require('util');
const functions = require('@google-cloud/functions-framework');
const redis = require('redis');

const REDISHOST = process.env.REDISHOST || 'localhost';
const REDISPORT = process.env.REDISPORT || 6379;

const redisClient = redis.createClient({
socket: {
port: REDISPORT,
host: REDISHOST,
port: REDISPORT,
},
});
redisClient.connect();
redisClient.on('error', err => console.error('ERR:REDIS:', err));
redisClient.connect();

const incrAsync = promisify(redisClient.incr).bind(redisClient);

exports.visitCount = async (req, res) => {
functions.http('visitCount', async (req, res) => {
try {
const response = await incrAsync('visits');
const response = await redisClient.incr('visits');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(`Visit count: ${response}`);
} catch (err) {
console.log(err);
res.status(500).send(err.message);
}
};
});

// [END functions_memorystore_redis]
1 change: 1 addition & 0 deletions functions/memorystore/redis/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"test": "mocha test/*.test.js --timeout=20000 --exit"
},
"dependencies": {
"@google-cloud/functions-framework": "^3.1.2",
"redis": "^4.0.0"
},
"devDependencies": {
Expand Down
35 changes: 28 additions & 7 deletions functions/memorystore/redis/test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,13 @@

'use strict';

const sinon = require('sinon');
const assert = require('assert');
const sinon = require('sinon');
const {getFunction} = require('@google-cloud/functions-framework/testing');

const redis = require('redis');

const getMocks = () => {
const getHttpMocks = () => {
return {
req: {},
res: {
Expand All @@ -29,21 +32,39 @@ const getMocks = () => {
};
};

const stubRedis = () => {
sinon.stub(redis, 'createClient').callsFake(() => {
return {
on: sinon.stub(),
connect: sinon.stub(),
incr: sinon.stub().resolves(42),
};
});
};

const restoreRedis = () => {
redis.createClient.restore();
};

describe('functions_memorystore_redis', () => {
describe('visitCount', () => {
it('should successfully increment the Redis counter', async () => {
const program = require('../');
const mocks = getMocks();
beforeEach(stubRedis);
afterEach(restoreRedis);

it('should respond with current visit count', async () => {
require('..');
const visitCount = getFunction('visitCount');
const mocks = getHttpMocks();

await program.visitCount(mocks.req, mocks.res);
await visitCount(mocks.req, mocks.res);

assert(!mocks.res.status.called);
assert(!mocks.res.send.called);
assert(mocks.res.writeHead.calledWith(200));
assert(mocks.res.end.calledOnce);

const [response] = mocks.res.end.firstCall.args;
assert(response.startsWith('Visit count:'));
assert(response === 'Visit count: 42');
});
});
});