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(google_cloud_function): refactor destination #2568

Closed
wants to merge 9 commits into from
Closed
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
16 changes: 3 additions & 13 deletions src/v0/destinations/google_cloud_function/transform.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,19 @@
const _ = require('lodash');
const {
defaultRequestConfig,
defaultPostRequestConfig,
getSuccessRespEvents,
checkInvalidRtTfEvents,
handleRtTfSingleEventError,
} = require('../../util');

const { generateBatchedPayload, validateDestinationConfig, addHeader } = require('./util');
const { generateBatchedPayload, validateDestinationConfig } = require('./util');

// Main process Function to handle transformation
function process(event) {
const { message, destination } = event;
const { googleCloudFunctionUrl } = destination.Config;

// Config Validation
validateDestinationConfig(destination);

const response = defaultRequestConfig();
// adding header
addHeader(response, destination.Config);
response.method = defaultPostRequestConfig.requestMethod;
response.body.JSON = message;
response.endpoint = googleCloudFunctionUrl;

const response = message;
return response;
}

Expand All @@ -37,7 +27,7 @@ function batchEvents(successRespList, maxBatchSize = 10) {
const batchEventResponse = generateBatchedPayload(chunk);
batchedResponseList.push(
getSuccessRespEvents(
batchEventResponse.batchedRequest,
batchEventResponse.message,
batchEventResponse.metadata,
batchEventResponse.destination,
true,
Expand Down
62 changes: 25 additions & 37 deletions src/v0/destinations/google_cloud_function/util.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
const { defaultBatchRequestConfig } = require('../../util');
const { JSON_MIME_TYPE } = require('../../util/constant');
const { ConfigurationError } = require('../../util/errorTypes');

const { TRIGGERTYPE } = require('./config');

/**
* validate destination config
* @param {*} param0
Expand All @@ -13,65 +9,57 @@ const validateDestinationConfig = ({ Config }) => {
if (!Config.googleCloudFunctionUrl) {
throw new ConfigurationError('[GCF]:: Url not found. Aborting');
}
if (
Config.triggerType === 'https' && // for triggerType https gcloud Authorization is mandatory
!Config.gcloudAuthorization
) {
throw new ConfigurationError('[GCF]:: Access Token not found. Aborting');
if (Config.requireAuthentication && !Config.credentials) {
throw new ConfigurationError(
'[GCF]:: Service Account credentials are required if your function required authentication. Aborting',
);
}
};

/**
* add headers in the payload that is provided in destination config
* @param {*} response
* @param {*} Config
*/
function addHeader(response, Config) {
const { triggerType, apiKeyId, gcloudAuthorization } = Config;
// /**
// * add headers in the payload that is provided in destination config
// * @param {*} response
// * @param {*} Config
// */
// function addHeader(response, Config) {
// const { triggerType, apiKeyId, gcloudAuthorization } = Config;

response.headers = { 'content-type': JSON_MIME_TYPE };
if (apiKeyId) {
const basicAuth = Buffer.from(`apiKey:${apiKeyId}`).toString('base64');
response.headers.ApiKey = `Basic ${basicAuth}`;
}
if (TRIGGERTYPE.HTTPS === triggerType.toLowerCase()) {
response.headers.Authorization = `bearer ${gcloudAuthorization}`;
}
}
// response.headers = { 'content-type': JSON_MIME_TYPE };
// if (apiKeyId) {
// const basicAuth = Buffer.from(`apiKey:${apiKeyId}`).toString('base64');
// response.headers.ApiKey = `Basic ${basicAuth}`;
// }
// if (TRIGGERTYPE.HTTPS === triggerType.toLowerCase()) {
// response.headers.Authorization = `bearer ${gcloudAuthorization}`;
// }
// }

/**
* Create GoogleCloudFunction Batch payload based on the passed events
* @param {*} events
* @returns
*/

function generateBatchedPayload(events) {
const batchResponseList = [];
const metadata = [];
// extracting destination
// from the first event in a batch
const { destination } = events[0];
const { googleCloudFunctionUrl } = destination.Config;
let batchEventResponse = defaultBatchRequestConfig();
let batchEventResponse = events.map((event) => event.message);
// Batch event into dest batch structure
events.forEach((ev) => {
batchResponseList.push(ev.message.body.JSON);
// batchResponseList.push(ev.message.body.JSON);
metadata.push(ev.metadata);
});
batchEventResponse.batchedRequest.body.JSON_ARRAY = {
batch: JSON.stringify(batchResponseList),
};
batchEventResponse.batchedRequest.endpoint = googleCloudFunctionUrl;
addHeader(batchEventResponse.batchedRequest, destination.Config);
batchEventResponse = {
...batchEventResponse,
metadata,
message: batchEventResponse,
destination,
metadata,
};
return batchEventResponse;
}

module.exports = {
validateDestinationConfig,
addHeader,
generateBatchedPayload,
};
157 changes: 157 additions & 0 deletions test/__tests__/data/google_cloud_function.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
[
{
"description": "Successful request",
"input": {
"destination": {
"Config": {
"functionEnvironment": "gen1",
"requireAuthentication": false,
"enableBatchInput": false,
"googleCloudFunctionUrl": "https://us-central1-big-query-integration-poc.cloudfunctions.net/rudderv1"
}
},
"message": {
"channel": "web",
"context": {
"app": {
"build": "1.0.0",
"name": "RudderLabs JavaScript SDK",
"namespace": "com.rudderlabs.javascript",
"version": "1.0.0"
},
"library": {
"name": "RudderLabs JavaScript SDK",
"version": "1.0.0"
},
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"locale": "en-US",
"ip": "0.0.0.0",
"os": {
"name": "",
"version": ""
},
"screen": {
"density": 2
}
},
"messageId": "84e26acc-56a5-4835-8233-591137fca468",
"session_id": "3049dc4c-5a95-4ccd-a3e7-d74a7e411f22",
"originalTimestamp": "2019-10-14T09:03:17.562Z",
"anonymousId": "anon_id",
"type": "identify",
"traits": {
"email": "[email protected]",
"name": "Cosmo Krammer",
"linkedinUrl": "https://linkedin.com/cosmo-krammer",
"location": "New York",
"emailOptOut": true,
"masterAvatarTypeCode": 10
},
"integrations": {
"All": true
},
"sentAt": "2019-10-14T09:03:22.563Z"
}
},
"output": {
"channel": "web",
"context": {
"app": {
"build": "1.0.0",
"name": "RudderLabs JavaScript SDK",
"namespace": "com.rudderlabs.javascript",
"version": "1.0.0"
},
"library": {
"name": "RudderLabs JavaScript SDK",
"version": "1.0.0"
},
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"locale": "en-US",
"ip": "0.0.0.0",
"os": {
"name": "",
"version": ""
},
"screen": {
"density": 2
}
},
"messageId": "84e26acc-56a5-4835-8233-591137fca468",
"session_id": "3049dc4c-5a95-4ccd-a3e7-d74a7e411f22",
"originalTimestamp": "2019-10-14T09:03:17.562Z",
"anonymousId": "anon_id",
"type": "identify",
"traits": {
"email": "[email protected]",
"name": "Cosmo Krammer",
"linkedinUrl": "https://linkedin.com/cosmo-krammer",
"location": "New York",
"emailOptOut": true,
"masterAvatarTypeCode": 10
},
"integrations": {
"All": true
},
"sentAt": "2019-10-14T09:03:22.563Z"
}
},
{
"description": "credentials not provided for function which require authentication",
"input": {
"destination": {
"Config": {
"functionEnvironment": "gen1",
"requireAuthentication": true,
"enableBatchInput": false,
"googleCloudFunctionUrl": "https://us-central1-big-query-integration-poc.cloudfunctions.net/rudderv1"
}
},
"message": {
"channel": "web",
"context": {
"app": {
"build": "1.0.0",
"name": "RudderLabs JavaScript SDK",
"namespace": "com.rudderlabs.javascript",
"version": "1.0.0"
},
"library": {
"name": "RudderLabs JavaScript SDK",
"version": "1.0.0"
},
"userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36",
"locale": "en-US",
"ip": "0.0.0.0",
"os": {
"name": "",
"version": ""
},
"screen": {
"density": 2
}
},
"messageId": "84e26acc-56a5-4835-8233-591137fca468",
"session_id": "3049dc4c-5a95-4ccd-a3e7-d74a7e411f22",
"originalTimestamp": "2019-10-14T09:03:17.562Z",
"anonymousId": "anon_id",
"type": "identify",
"traits": {
"email": "[email protected]",
"name": "Cosmo Krammer",
"linkedinUrl": "https://linkedin.com/cosmo-krammer",
"location": "New York",
"emailOptOut": true,
"masterAvatarTypeCode": 10
},
"integrations": {
"All": true
},
"sentAt": "2019-10-14T09:03:22.563Z"
}
},
"output": {
"error": "[GCF]:: Service Account credentials are required if your function required authentication. Aborting"
}
}
]
Loading