I have to trigger multiple templates one by one using Google Cloud function in Google Dataflow Process. After execution of one template, the another template must be called.
const google = require('googleapis');
exports.goWithTheDataFlow = function(event, callback) {
const file = event.data;
if (file.resourceState === 'exists' && file.name) {
google.auth.getApplicationDefault(function (err, authClient, projectId) {
if (err) {
throw err;
}
if (authClient.createScopedRequired && authClient.createScopedRequired()) {
authClient = authClient.createScoped([
'https://www.googleapis.com/auth/cloud-platform',
'https://www.googleapis.com/auth/userinfo.email'
]);
}
const dataflow = google.dataflow({ version: 'v1b3', auth: authClient });
dataflow.projects.templates.create({
projectId: 'testing1-180111',
resource: {
parameters: {
},
jobName: 'cloud-fn-dataflow-test',
gcsPath: 'gs://kishan-configuration/templates/FinalConfigTable'
}
}, function(err, response) {
if (err) {
console.error("problem running dataflow template, error was: ", err);
}
console.log("Dataflow template response: ", response);
callback();
});
});
}
};
package.json file code is this
{
"name": "kishan_kumar464",
"version": "1.0.0",
"main": "index.js",
"dependencies": {
"google-cloud": "^0.56.0",
"googleapis": "^22.2.0"
},
"devDependencies": {},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Kishan",
"license": "ISC",
"description": ""
}
If I understand correctly, you'd like to create a job from a template and wait until finish. After that, you can create the next job from the template. Correct?
I think you can probably poll the job status after the job is created (job id is in the response of dataflow.projects.templates.create.
To check the status of a job, please use projects.jobs.get API.
Related
I am trying to deploy an upgradable smart contract on polygon Mumbai tesnet. I am getting this error
smart-contract/node_modules/#openzeppelin/hardhat-upgrades/dist/index.js:108
compiler.settings ?? (compiler.settings = {});
^
SyntaxError: Unexpected token '?'
at wrapSafe (internal/modules/cjs/loader.js:915:16)
at Module._compile (internal/modules/cjs/loader.js:963:27)
at Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Object.require.extensions.<computed> [as .js] (/Users/jagdish/workspace/speedrun-simple-nft-example/smart-contract/node_modules/ts-node/src/index.ts:1587:43)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module.require (internal/modules/cjs/loader.js:887:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/Users/jagdish/workspace/speedrun-simple-nft-example/smart-contract/hardhat.config.ts:4:1)
at Module._compile (internal/modules/cjs/loader.js:999:30)
while trying to run the deploy script.
here are my configs and deploy scripts:
hardhart.config.ts
import { task } from "hardhat/config";
// import "#nomiclabs/hardhat-waffle";
import 'hardhat-watcher';
import '#openzeppelin/hardhat-upgrades';
import '#nomiclabs/hardhat-ethers';
import dotenv from "dotenv"
dotenv.config()
// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
const accounts = await hre.ethers.getSigners();
for (const account of accounts) {
console.log(account.address);
}
});
// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more
/**
* #type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: "0.8.4",
watcher: {
compilation: {
tasks: ['compile'],
},
node: {
tasks: ['node'],
},
},
networks: {
matic: {
url: "https://polygon-rpc.com/",
accounts: [process.env.ACCOUNT_PRIVATE_KEY]
},
matic_mumbai: {
url: "https://rpc-mumbai.maticvigil.com",
accounts: [process.env.ACCOUNT_PRIVATE_KEY]
}
}
};
deploy.ts
import { ethers, upgrades } from "hardhat";
async function main() {
const contract = await ethers.getContractFactory("YourCollectible");
console.log("Deploying Contract ...");
const c = await upgrades.deployProxy(contract, { constructorArgs: ["Your Collectables", "YCB"] })
// const c = await contract.deploy("Your Collectable", "YCB");
await c.deployed();
console.log("Contract deployed to:", c.address);
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
package.json
{
"name": "smart-contract",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"run": "hardhat compile",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"#nomiclabs/hardhat-ethers": "^2.0.6",
"#nomiclabs/hardhat-waffle": "^2.0.3",
"#openzeppelin/hardhat-upgrades": "^1.20.0",
"#typechain/hardhat": "^6.1.2",
"chai": "^4.3.6",
"ethereum-waffle": "^3.4.4",
"ethers": "^5.6.9",
"hardhat": "^2.9.9",
"hardhat-watcher": "^2.3.0",
"ts-node": "^10.8.1",
"typescript": "^4.7.4"
},
"dependencies": {
"#openzeppelin/contracts": "^4.7.0",
"dotenv": "^16.0.1"
}
}
I am not sure whether it is the node version issue in my local or do I have to downgrade the #openzeppelin/hardhat-upgrades version (I have tried that).
Node version: v12.22.10
Can anyone help on this
I had the same problem with node 12. Problem solved after updating to node 16 and running yarn again.
Good afternoon, hope you guys have a good day, i'm already building some apps using expo bare workflow, and need to use Expo Notification, i'm following all the instruction, from expo notification documentations, and fcm configurations, to setup firebase, but, when i'm tryin to get expoToken, i got this warning, looks like this:
Error: Encountered an exception while calling native method: Exception occurred while executing exported method getDevicePushTokenAsync on module ExpoPushTokenManager: Failed resolution of: Lcom/google/firebase/iid/FirebaseInstanceId;
and I've made sure that my package name is the same as the package I registered in firebase, can you guys help me? pleasee :slight_smile:
this is addtional information:
Getting Expo Token
const getToken = async () => {
console.log("TOKEN CHECK");
const { status: existingStatus } =
await Notifications.getPermissionsAsync();
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Notifications.requestPermissionsAsync();
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification!");
return;
}
token = (await Notifications.getExpoPushTokenAsync()).data;
console.log(token);
};
App.js
{
"name": "myapp",
"displayName": "myapp",
"expo": {
"name": "myapp",
"slug": "myapp",
"version": "1.0.0",
"assetBundlePatterns": [
"**/*"
]
},
"android": {
"googleServicesFile": "./google-services.json",
"useNextNotificationsApi": true
}
}
Package.json
{
"main": "index.js",
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"web": "expo start --web",
"start": "react-native start"
},
"dependencies": {
"#dudigital/react-native-zoomable-view": "^1.0.16",
"#react-native-async-storage/async-storage": "^1.15.5",
"#react-native-community/masked-view": "^0.1.11",
"#react-native-community/netinfo": "^6.0.0",
"#react-native-firebase/app": "^12.0.0",
"#react-native-firebase/firestore": "^12.0.0",
"#react-native-firebase/storage": "^12.0.0",
"#react-native-picker/picker": "^1.16.1",
"#react-navigation/material-bottom-tabs": "^5.3.15",
"#react-navigation/native": "^5.9.4",
"#react-navigation/stack": "^5.14.5",
"expo": "~41.0.1",
"expo-av": "~9.1.2",
"expo-image-manipulator": "~9.1.0",
"expo-image-picker": "~10.1.4",
"expo-notifications": "~0.11.6",
"expo-splash-screen": "~0.10.2",
"expo-status-bar": "~1.0.4",
"expo-updates": "~0.5.4",
"expo-web-browser": "~9.1.0",
"firebase": "^8.6.5",
"moment": "^2.29.1",
"react": "16.13.1",
"react-dom": "16.13.1",
"react-native": "~0.63.4",
"react-native-calendars": "^1.1263.0",
"react-native-custom-qr-codes-expo": "^2.2.0",
"react-native-datepicker": "^1.7.2",
"react-native-gesture-handler": "~1.10.2",
"react-native-linear-gradient": "^2.5.6",
"react-native-orientation-locker": "^1.3.1",
"react-native-paper": "^4.9.1",
"react-native-raw-bottom-sheet": "^2.2.0",
"react-native-reanimated": "~2.1.0",
"react-native-render-html": "^5.1.1",
"react-native-responsive-screen": "^1.4.2",
"react-native-safe-area-context": "^3.2.0",
"react-native-screens": "~3.0.0",
"react-native-shimmer-placeholder": "^2.0.7",
"react-native-svg": "12.1.0",
"react-native-unimodules": "~0.13.3",
"react-native-vector-icons": "^8.1.0",
"react-native-web": "~0.13.12",
"react-native-webview": "^11.6.2"
},
"devDependencies": {
"#babel/core": "^7.9.0"
},
"private": true
}
screenshot:
someImages
You have to do two things:
In bare workflow, the Notifications.getExpoPushTokenAsync() method needs to provide the experienceId attributes.
const expoPushToken = await Notifications.getExpoPushTokenAsync({ experienceId });
console.log({ expoPushToken });
return expoPushToken.data;
You have to modify your /android/app/build.gradle to add 'com.google.firebase:firebase-iid:17.0.2'
dependencies {
implementation 'com.google.firebase:firebase-iid:17.0.2'
...
}
I have created step functions and invoked them as specified in AWS documentation. For output, I am getting
{
"executionArn": "arn:aws:states:us-east-1:123456789012:execution:HelloWorld:MyExecution", "startDate": 1385732956.878
}
But, instead of above response I want my API response
{ response: DATA}
How can I achieve this?
EDIT:
This is the lambda that triggers the state machine:
import * as AWS from 'aws-sdk';
import {APIGatewayEvent} from 'aws-lambda';
const stepFunctions = new AWS.StepFunctions();
export const handler = (event: APIGatewayEvent) => {
console.log('event: ' + JSON.stringify(event));
const stateMachineARN = process.env.MACHINE_ARN;
const params = {
stateMachineArn: stateMachineARN,
input: JSON.stringify(event),
};
const request = stepFunctions.startExecution(params);
request.on('error', err => {
console.log('aca' + err.message);
});
request.send();
};
And the output of the state machine:
{
"ExecutedVersion": "$LATEST",
"Payload": {
"isBase64Encoded": false,
"statusCode": 200,
"headers": {},
"body": {
"endpoint": {
"url": "xxx",
"method": "POST",
"request": "xxx"
}
}
},
I need to grab that Payload.
The DescribeExecution function returns the output of a Step Function.
See: https://docs.aws.amazon.com/step-functions/latest/apireference/API_DescribeExecution.html
How to invoke this will depend on your SDK of choice (AWS CLI, Boto3, Java SDK, etc.)
If you are using express workflow you can invoke it synchronously to get the result of execution.
For standard workflows you need to use DescribeExecution api from sdk or cli for which input is executionArn.
I am trying to integrate dialogflow with firestore but I can't get the required output. Diagnostic Info provides the below error. I need to get the response from the firestore according to the given input from the agent that's the basic requirement but I get this error while integrating.
{
"responseId": "a6a119a8-c406-4af2-aab0-b6863fb091a4-59c3eb0f",
"queryResult": {
"queryText": "15APC2375",
"parameters": {
"regno": "15APC2375"
},
"allRequiredParamsPresent": true,
"intent": {
"name": "projects/cis-bot-yhrvph/agent/intents/e3b1292b-89b1-48b7-b4b4-805a63d08168",
"displayName": "request-results"
},
"intentDetectionConfidence": 0.3,
"diagnosticInfo": {
"webhook_latency_ms": 4892
},
"languageCode": "en"
},
"webhookStatus": {
"code": 4,
"message": "Webhook call failed. Error: DEADLINE_EXCEEDED."
}
}
My Package.json includes the below code.
{
"name": "dialogflowFirebaseFulfillment",
"description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "10"
},
"scripts": {
"start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
"deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
},
"dependencies": {
"firebase": "^7.13.2",
"actions-on-google": "^2.2.0",
"firebase-admin": "^5.13.1",
"firebase-functions": "^2.0.2",
"dialogflow": "^0.6.0",
"dialogflow-fulfillment": "^0.5.0"
}
}
As well as index.js includes the below code.
'use strict';
const firebase = require('firebase');
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
admin.initializeApp();
const db = admin.firestore();
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function welcome(agent) {
agent.add(`Welcome to CIS BOT!`);
}
function fallback(agent) {
agent.add(`Please Contact the Front Desk for more information`);
}
function getResults(agent){
const regno=agent.parameters.regno;
const dialogflowAgentDoc = db.collection('results').where("reg_id","==",'15APC2375')
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
agent.add(doc.data().grade);
});
}).catch(() => {
agent.add('Error reading entry from the Firestore database.');
agent.add('Please add a entry to the database first by saying, "Write <your phrase> to the database"');
});
}
let intentMap = new Map();
intentMap.set('Default Welcome Intent', welcome);
intentMap.set('Default Fallback Intent', fallback);
intentMap.set('request-results', getResults);
// intentMap.set('your intent name here', googleAssistantHandler);
agent.handleRequest(intentMap);
});
I want to return connectionId to a client after the client connect to aws websocket.
I'm using apigwManagementApi.postToConnection to send a response to a client, but I always get an absurd error message.
I already try to debug & search in google, but I can't find a solution for this.
patch.js
require('aws-sdk/lib/node_loader');
var AWS = require('aws-sdk/lib/core');
var Service = AWS.Service;
var apiLoader = AWS.apiLoader;
apiLoader.services['apigatewaymanagementapi'] = {};
AWS.ApiGatewayManagementApi = Service.defineService('apigatewaymanagementapi', ['2018-11-29']);
Object.defineProperty(apiLoader.services['apigatewaymanagementapi'], '2018-11-29', {
get: function get() {
var model = {
"metadata": {
"apiVersion": "2018-11-29",
"endpointPrefix": "execute-api",
"signingName": "execute-api",
"serviceFullName": "AmazonApiGatewayManagementApi",
"serviceId": "ApiGatewayManagementApi",
"protocol": "rest-json",
"jsonVersion": "1.1",
"uid": "apigatewaymanagementapi-2018-11-29",
"signatureVersion": "v4"
},
"operations": {
"PostToConnection": {
"http": {
"requestUri": "/#connections/{connectionId}",
"responseCode": 200
},
"input": {
"type": "structure",
"members": {
"Data": {
"type": "blob"
},
"ConnectionId": {
"location": "uri",
"locationName": "connectionId"
}
},
"required": [
"ConnectionId",
"Data"
],
"payload": "Data"
}
}
},
"shapes": {}
}
model.paginators = {
"pagination": {}
}
return model;
},
enumerable: true,
configurable: true
});
module.exports = AWS.ApiGatewayManagementApi;
index.js
const AWS = require('aws-sdk');
require('./patch.js');
exports.handler = async(event) => {
const connectionId = event.requestContext.connectionId;
const apigwManagementApi = new AWS.ApiGatewayManagementApi({
apiVersion: '2018-11-29',
endpoint: event.requestContext.domainName + '/' + event.requestContext.stage
});
await apigwManagementApi.postToConnection({ ConnectionId: connectionId, Data: connectionId }).promise();
return {};
};
client.js
const WebSocket = require('ws');
const ws = new WebSocket('wss://****');
ws.on('open', () => {
console.log('connected ===================>')
ws.on('message', data => console.warn(`From server: ${data}`));
});
Error in cloudwatch
{
"errorMessage": "410",
"errorType": "UnknownError",
"stackTrace": [
"Object.extractError (/var/runtime/node_modules/aws-sdk/lib/protocol/json.js:48:27)",
"Request.extractError (/var/runtime/node_modules/aws-sdk/lib/protocol/rest_json.js:52:8)",
"Request.callListeners (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:105:20)",
"Request.emit (/var/runtime/node_modules/aws-sdk/lib/sequential_executor.js:77:10)",
"Request.emit (/var/runtime/node_modules/aws-sdk/lib/request.js:683:14)",
"Request.transition (/var/runtime/node_modules/aws-sdk/lib/request.js:22:10)",
"AcceptorStateMachine.runTo (/var/runtime/node_modules/aws-sdk/lib/state_machine.js:14:12)",
"/var/runtime/node_modules/aws-sdk/lib/state_machine.js:26:10",
"Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:38:9)",
"Request.<anonymous> (/var/runtime/node_modules/aws-sdk/lib/request.js:685:12)"
]
}
I don't know why, but if I'm trying in a custom route, this code can work.
Does anyone know how to solve this?
I'd suggest to look into this example from AWS, there is on connect response for subprotocol confirmation, but I think any payload can be provided.
The most important bit is the route integration settings in the template, basically, the following two lines in the route integration properties:
IntegrationMethod: POST
ConnectionType: INTERNET
then response will be sent to the connected client.
The only way I've found to make this work is to use a DynamoDB table to store connections, then set up a trigger from the table back to a Lambda function.
There are a few catches though. This Lambda function wont work like your index.js file above. You'll have to use NPM install --save aws-sdk on a folder with your index.js file, zip it and upload it to the lambda function, so that the SDK is localized.
You will also need to set up a user with proper access and put the credentials into a your Lambda function.
Note, if you see a 410 error, that means the connection is no longer there, so you're going in the right direction at that point.
const AWS = require('aws-sdk');
require('./patch.js');
var log = console.log;
AWS.config.update({
accessKeyId: "YOURDATAHERE",
secretAccessKey: "YOURDATAHERE"
});
let send = undefined;
function init() {
const apigwManagementApi = new AWS.ApiGatewayManagementApi({
apiVersion: '2018-11-29',
endpoint: "HARDCODEYOURENDPOINTHERE"
});
send = async (connectionId, data) => {
await apigwManagementApi.postToConnection({ ConnectionId: connectionId, Data: `${data}` }).promise();
}
}
exports.handler = async (event, context) => {
init();
console.log('Received event:', JSON.stringify(event, null, 2));
for (const record of event.Records) {
//console.log(record.eventID);
console.log(record.eventName);
console.log('DynamoDB Record: %j', record.dynamodb);
if(record.eventName == "INSERT"){
var connectionId = record.dynamodb.NewImage.connectionId.S;
try{
await send(connectionId, connectionId);
}catch(err){
log("Error", err);
}
log("sent");
}
}
return `Successfully processed ${event.Records.length} records.`;
};