Tunneling socket could not be established in Bot Framework Emulator - botframework

I have found that I am no longer able to use Bot Framework Emulator on local (not using ngrok, not allowed at my company) after upgrading botbuilder packages to something higher than 4.7 (EDIT: I've now checked and the error appears to be introduced in 4.10. It works fine at version 4.9 and keeping only the botbuilder-testing package at 4.9 doesn't help). Can anyone tell me what has changed that makes this not work, and if there is a way to continue testing locally? This is failing any time I use await context.sendActivity (I'm sure other things don't work as well, but that's as far as I can get). Here is how I set up the bot adapter. AppId and Password are NULL since I am running this locally and not using ngrok.
const adapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId, // this variable is null for local/emulator
appPassword: process.env.MicrosoftAppPassword // this variable is null for local/emulator
});
And here is the full error message. Yes, I know I'm not catching the error but I'm not going to put a try catch block for every sendActivity statement. The error details are no different.
(node:19488) UnhandledPromiseRejectionWarning: Error: BotFrameworkAdapter.processActivity(): 500 ERROR
Error: tunneling socket could not be established, statusCode=403
at new RestError (C:\Users\e0077301\Documents\DevOps Projects\TRaCy nanorep\node_modules\#azure\ms-rest-js\dist\msRest.node.js:1403:28)
at AxiosHttpClient.<anonymous> (C:\Users\e0077301\Documents\DevOps Projects\TRaCy nanorep\node_modules\#azure\ms-rest-js\dist\msRest.node.js:2194:35)
at step (C:\Users\e0077301\Documents\DevOps Projects\TRaCy nanorep\node_modules\tslib\tslib.js:133:27)
at Object.throw (C:\Users\e0077301\Documents\DevOps Projects\TRaCy nanorep\node_modules\tslib\tslib.js:114:57)
at rejected (C:\Users\e0077301\Documents\DevOps Projects\TRaCy nanorep\node_modules\tslib\tslib.js:105:69)
at process._tickCallback (internal/process/next_tick.js:68:7)
at BotFrameworkAdapter.<anonymous> (C:\Users\e0077301\Documents\DevOps Projects\TRaCy nanorep\node_modules\botbuilder\lib\botFrameworkAdapter.js:736:27)
at Generator.throw (<anonymous>)
at rejected (C:\Users\e0077301\Documents\DevOps Projects\TRaCy nanorep\node_modules\botbuilder\lib\botFrameworkAdapter.js:13:65)
at process._tickCallback (internal/process/next_tick.js:68:7)
Here are the full index.js and package.json files:
index.js
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
const path = require('path');
const ENV_FILE = path.join(__dirname, '.env');
require('dotenv').config({ path: ENV_FILE });
const request = require('request-promise-native');
// Import and start application insights
const appInsights = require('applicationinsights');
appInsights.setup(process.env.APPINSIGHTS_INSTRUMENTATIONKEY).start();
const appInsightsClient = appInsights.defaultClient;
// Import required packages
const restify = require('restify');
const { CustomLogger } = require('./helpers/CustomLogger');
// Import required bot services. See https://aka.ms/bot-services to learn more about the different parts of a bot.
const { BotFrameworkAdapter, MemoryStorage, ConversationState, UserState, TranscriptLoggerMiddleware } = require('botbuilder');
const { BlobStorage } = require('botbuilder-azure');
// This bot's main dialog.
const { DispatchBot } = require('./bots/dispatchBot');
// Create adapter.
// See https://aka.ms/about-bot-adapter to learn more about adapters.
const adapter = new BotFrameworkAdapter({
appId: process.env.MicrosoftAppId,
appPassword: process.env.MicrosoftAppPassword
});
// Catch-all for errors.
adapter.onTurnError = async (context, error) => {
console.error(`\n [onTurnError]: ${ error }`);
// Log to Application Insights
appInsightsClient.trackTrace({
message: `${error.name} - ${path.basename(__filename)}`,
severity: 4,
properties: {'error':error.message,'callStack':error.stack,'botName': process.env.BOTNAME}
});
// Send a message to the user
await context.sendActivity(`Sorry, I've encountered an unexpected error and I had to cancel our last activity. If you continue to receive this error, please contact your support team.`);
// Clear out state
await conversationState.delete(context);
};
if (process.env.BOTNAME == 'Bot_Local') {
// Memory storage - for development only
console.log(`\nUsing MemoryStorage for state storage`);
const memoryStorage = new MemoryStorage();
var conversationState = new ConversationState(memoryStorage);
var userState = new UserState(memoryStorage);
} else {
// Blob storage - for production
console.log(`\nUsing BlobStorage for state storage`);
const blobStorage = new BlobStorage({
containerName: 'bot-storage',
storageAccountOrConnectionString: process.env.blobStorageServiceName,
storageAccessKey: process.env.blobStorageAccessKey
});
var conversationState = new ConversationState(blobStorage);
var userState = new UserState(blobStorage);
}
// Set up transcript logger
const transcriptLogger = new TranscriptLoggerMiddleware(new CustomLogger(appInsightsClient));
adapter.use(transcriptLogger);
// Pass in a logger to the bot.
//const logger = console;
const logger = appInsightsClient;
// Create the main dialog
let bot = new DispatchBot(conversationState, userState, logger);
// Create HTTP server
let server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function() {
console.log(`\n${ server.name } listening to ${ server.url }`);
console.log(`\nGet Bot Framework Emulator: https://aka.ms/botframework-emulator`);
console.log(`\nSee https://aka.ms/connect-to-bot for more information`);
});
const restifyBodyParser = require('restify').plugins.bodyParser;
server.use(restifyBodyParser());
// Listen for incoming activities and route them to your bot main dialog.
server.post('/api/messages', (req, res) => {
// Route received a request to adapter for processing
adapter.processActivity(req, res, async (turnContext) => {
// route to bot activity handler.
await bot.run(turnContext);
});
});
// Respond to pings
server.get('/api/ping', (req, res) => {
res.send('Ping acknowledged');
});
// Listen for incoming notifications and send proactive messages to users.
server.post('/api/notify', async (req, res) => {
console.log(req.body);
try {
const conversationReference = req.body.conversationReference;
await adapter.continueConversation(conversationReference, async turnContext => {
// If you encounter permission-related errors when sending this message, see
// https://aka.ms/BotTrustServiceUrl
await turnContext.sendActivity(req.body.message);
});
res.setHeader('Content-Type', 'text/html');
res.writeHead(200);
res.write('<html><body><h1>Proactive messages have been sent.</h1></body></html>');
res.end();
} catch (error) {
console.log('Bad request');
appInsightsClient.trackTrace({
message: `${error.name} - ${path.basename(__filename)} /api/notify`,
severity: 4,
properties: {'error':error.message,'callStack':error.stack,'botName': process.env.BOTNAME}
});
res.setHeader('Content-Type', 'text/html');
res.writeHead(400);
res.write('<html><body><h1>Bad Request. Please ensure your message contains the conversation reference and message text.</h1></body></html>');
res.end();
}
});
server.post('/directline/token', async (req, res) => {
try {
var body = {User:{Id:req.body.userId}};
const response = await request({
url: 'https://directline.botframework.com/v3/directline/tokens/generate',
method: 'POST',
headers: { Authorization: `Bearer ${process.env.DIRECTLINE_SECRET}`},
json: body,
rejectUnauthorized: false
});
const token = response.token;
res.setHeader('Content-Type', 'text/plain');
res.writeHead(200);
res.write(token);
res.end();
} catch(err) {
console.log(err);
res.setHeader('Content-Type', 'text/plain');
res.writeHead(500);
res.write('Call to retrieve token from Direct Line failed');
res.end();
}
})
package.json (with botbuilder packages updated to latest. If I downgrade all of them to 4.7.0 it works)
{
"name": "core-bot",
"version": "1.0.0",
"description": "A bot that demonstrates core AI capabilities",
"author": "Microsoft",
"license": "MIT",
"main": "index.js",
"nyc": {
"exclude": [
"test",
"helpers/cardHelper.js"
]
},
"scripts": {
"start": "node ./index.js",
"watch": "nodemon ./index.js",
"lint": "eslint .",
"test:dev": "mocha test/**/*test.js",
"test": "nyc --reporter=text --reporter=cobertura mocha test/**/*test.js --timeout 10000 --reporter mocha-multi-reporters --reporter-options configFile=./mocha-reporter-config.json",
"test:inspect": "mocha test/**/*test.js --inspect-brk",
"testList": "node ./node_modules/mocha-list-tests/mocha-list-tests.js test/"
},
"repository": {
"type": "git",
"url": "https://github.com/Microsoft/BotBuilder-Samples.git"
},
"dependencies": {
"#microsoft/recognizers-text-data-types-timex-expression": "^1.1.4",
"#sendgrid/mail": "^6.4.0",
"applicationinsights": "^1.6.0",
"azure-storage": "^2.10.3",
"botbuilder": "^4.12.0",
"botbuilder-ai": "^4.12.0",
"botbuilder-azure": "^4.12.0",
"botbuilder-dialogs": "^4.12.0",
"botbuilder-testing": "^4.12.0",
"crypto": "^1.0.1",
"dotenv": "^6.1.0",
"mocha": "^6.2.2",
"mocha-list-tests": "^1.0.2",
"nock": "^11.7.0",
"remove-markdown": "^0.3.0",
"restify": "^7.2.3",
"turndown": "^5.0.3",
"xml2js": "^0.4.22"
},
"devDependencies": {
"eslint": "^5.16.0",
"eslint-config-standard": "^12.0.0",
"eslint-plugin-import": "^2.19.1",
"eslint-plugin-node": "^8.0.0",
"eslint-plugin-promise": "^4.2.1",
"eslint-plugin-standard": "^4.0.1",
"https-proxy-agent": "^5.0.0",
"mocha-junit-reporter": "^1.23.1",
"mocha-multi-reporters": "^1.1.7",
"nodemon": "^1.19.4",
"nyc": "^14.1.1",
"source-map-support": "^0.5.16"
}
}

If you are on windows machine, try setting this system environment variable – NODE_TLS_REJECT_UNAUTHORIZED=0 instead of HTTPS_PROXY. This resolves emulator localhost issue running on http protocol to start communicating with the services that are on https. The proxy setting no longer works with botbuilder packages 4.10 and greater.

Related

How to get websocket url (subscripionsUrl) from apolloserver constructor

I have this code and i try to charge the subscription in apollo playground but i cant it, I also tried to import 'PubSub' from apollo-server but this didn't work, I also tried to follow the documentation but it gave the same result, I have been reading in many places but no solutions; I must emphasize that the subscriptionsUrl returns me undefined and according to what I investigate it should be something like 'ws://...',
not if my code is a bit old or what happens
i'm trying make the subscription executed in loop but i receive the response
{
"message": "server must support graphql-ws or subscriptions-transport-ws protocol"
}
the typeDefs and resolvers is declared in the same file that server variable, does anyone know what to do?
import * as dotenv from 'dotenv'
dotenv.config()
import './mongo.js'
import {
ApolloServer,
AuthenticationError,
gql,
UserInputError
} from 'apollo-server'
import { PubSub } from 'graphql-subscriptions'
import Person from './models/person.js'
import User from './models/user.js'
import jwt from 'jsonwebtoken'
const { JWT_SECRET } = process.env
const SUBS_EVENTS = {
PERSON_ADDED: 'PERSON_ADDED'
}
const pubsub = new PubSub()
const typeDefs = gql`...`
const resolvers = {...}
const server = new ApolloServer({
typeDefs,
resolvers,
context: async ({ req }) => {
const auth = req ? req.headers.authorization : null
if (auth && auth.toLowerCase().startsWith(`bearer `)) {
const token = auth.substring(7)
const { id } = jwt.verify(token, JWT_SECRET)
const currentUser = await User.findById(id).populate('friends')
return { currentUser }
}
}
})
server.listen().then(({ url, subscriptionsUrl }) => {
console.log(`Server ready at ${url}`)
console.log(`Subscriptions ready at ${subscriptionsUrl}`)
})
// in the json
{
"name": "graphql-server",
"version": "1.0.0",
"description": "",
"type": "module",
"main": "index.js",
"scripts": {
"jsonserver": "json-server --watch db.json",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"apollo-server": "3.10.3",
"axios": "1.1.3",
"dotenv": "16.0.3",
"express": "^4.18.2",
"graphql": "^16.6.0",
"graphql-subscriptions": "^2.0.0",
"jsonwebtoken": "8.5.1",
"mongoose": "6.7.0",
"mongoose-unique-validator": "3.1.0",
"uuid": "9.0.0"
},
"devDependencies": {
"json-server": "0.17.0"
}
}

Transparent proxy tests - Error: missing revert data in call exception; Transaction reverted without a reason string;

I am trying to create a new token contract using the ERC20 Upgradeable contracts provided from Openzeppelin (OZ). I created the token contract and then made some basic unit tests. However, in one of the tests, I expect to see "TransparentUpgradeableProxy: admin cannot fallback to proxy target", when calling an implementation method from the Proxy admin. In one of my projects it works fine, but in another made from scratch - it does not. The error that I receive is "Error: missing revert data in call exception; Transaction reverted without a reason string..."
Here is the code for the one that is failing:
// the contract ---
contract TokenName is ERC20PresetMinterPauserUpgradeable {
/**
* #dev Used to prevent implementation manipulation
*/
constructor() initializer {}
/**
* #dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, `PAUSER_ROLE` to the owner
* specified in the owner param.
* #param owner is the owner of the contract after initialization
* See {ERC20-constructor}.
*/
function initialize(string memory name, string memory symbol, address owner) public initializer {
require(owner != address(0x0), "New owner cannot be 0");
__ERC20PresetMinterPauser_init(name, symbol);
__ERC20_init(name, symbol);
_setupRole(DEFAULT_ADMIN_ROLE, owner);
_setupRole(MINTER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
revokeRole(PAUSER_ROLE, _msgSender());
revokeRole(MINTER_ROLE, _msgSender());
revokeRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20PresetMinterPauserUpgradeable) {
ERC20PresetMinterPauserUpgradeable._beforeTokenTransfer(from, to, amount);
}
}
// token unit tests ---
describe.only("Upgradeable token tests", function () {
let accounts;
let deployer;
let owner;
let tokenInstance;
let tokenName = "Token Name";
let tokenSymbol = "symbol";
const tokenAmount = '10000000000000000000';
before(async function() {
accounts = await ethers.getSigners();
deployer = accounts[0];
owner = accounts[1];
user = accounts[2];
})
it("should throw error when calling the implementation contract with the proxy admin", async function() {
const tokenContract = await ethers.getContractFactory(tokenSymbol);
tokenInstance = await upgrades.deployProxy(tokenContract, [tokenName, tokenSymbol, owner.address], { initializer: 'initialize(string,string,address)', unsafeAllow: ['constructor'] });
await tokenInstance.deployed();
console.log("default admin addr: ", await upgrades.erc1967.getAdminAddress(tokenInstance.address));
console.log("token instance addr: ", tokenInstance.address);
await upgrades.admin.changeProxyAdmin(tokenInstance.address, owner.address);
console.log("changed admin addr: ", await upgrades.erc1967.getAdminAddress(tokenInstance.address));
expect(await upgrades.erc1967.getAdminAddress(tokenInstance.address)).to.equal(owner.address);
//console.log("tokenInstance", tokenInstance);
console.log("owner addr: ", owner.address);
console.log("deployer addr: ", deployer.address);
console.log("admin changed ---");
await expect(tokenInstance.connect(owner).name()).to.be.revertedWith('TransparentUpgradeableProxy: admin cannot fallback to proxy target');
});
})
There is no much need to add the code of the other project, because it is exactly the same, but I will do in order to have it as comparison.
// token contract ---
contract MarsCoin is ERC20PresetMinterPauserUpgradeable {
uint counter;
function increment() public {
counter += 1;
}
function getCounter() public view returns (uint) {
return counter;
}
/**
* #dev Used to prevent implementation manipulation
*/
constructor() initializer {}
/**
* #dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, `PAUSER_ROLE` to the owner
* specified in the owner param.
* #param owner is the owner of the contract after initialization
* See {ERC20-constructor}.
*/
function initialize(string memory name, string memory symbol, address owner) public initializer {
require(owner != address(0x0), "New owner cannot be 0");
counter = 0;
__ERC20PresetMinterPauser_init(name, symbol);
__ERC20_init(name, symbol);
_setupRole(DEFAULT_ADMIN_ROLE, owner);
_setupRole(MINTER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
revokeRole(PAUSER_ROLE, _msgSender());
revokeRole(MINTER_ROLE, _msgSender());
revokeRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20PresetMinterPauserUpgradeable) {
ERC20PresetMinterPauserUpgradeable._beforeTokenTransfer(from, to, amount);
}
}
// token unit tests ---
const { expect } = require("chai");
const { ethers, upgrades } = require("hardhat");
describe.only("Mars Coin tests", function () {
let accounts;
let deployer;
let owner;
let tokenInstance;
let tokenName = "Mars Coin";
let tokenSymbol = "MARS";
const tokenAmount = '10000000000000000000';
before(async function() {
accounts = await ethers.getSigners();
deployer = accounts[0];
owner = accounts[1];
user = accounts[2];
})
it("Should deploy MARS token with correct owner set", async function () {
const MarsCoin = await ethers.getContractFactory("MarsCoin");
tokenInstance = await upgrades.deployProxy(MarsCoin, [tokenName, tokenSymbol, owner.address], { initializer: 'initialize(string,string,address)', unsafeAllow: ['constructor'] });
await tokenInstance.deployed();
const adminRole = await tokenInstance.DEFAULT_ADMIN_ROLE();
const minterRole = await tokenInstance.MINTER_ROLE();
const pauserRole = await tokenInstance.PAUSER_ROLE();
expect(await tokenInstance.name()).to.equal(tokenName);
expect(await tokenInstance.symbol()).to.equal(tokenSymbol);
expect(await tokenInstance.hasRole(adminRole, deployer.address)).to.equal(false);
expect(await tokenInstance.hasRole(minterRole, deployer.address)).to.equal(false);
expect(await tokenInstance.hasRole(pauserRole, deployer.address)).to.equal(false);
expect(await tokenInstance.hasRole(adminRole, owner.address)).to.equal(true);
expect(await tokenInstance.hasRole(minterRole, owner.address)).to.equal(true);
expect(await tokenInstance.hasRole(pauserRole, owner.address)).to.equal(true);
});
it("Should mint tokens to user account", async function() {
const tokenInstanceWithOwner = tokenInstance.connect(owner);
await tokenInstanceWithOwner.mint(user.address, tokenAmount);
const accountBalance = (await tokenInstance.balanceOf(user.address)).toString();
expect(accountBalance).to.equal(tokenAmount)
})
it("Should try to call contract implementation contract with deployer", async function () {
const tokenInstanceWithDeployer = tokenInstance.connect(deployer);
expect(await tokenInstanceWithDeployer.name()).to.equal(tokenName)
})
it("Should change the MARS token proxy admin correctly", async function() {
await upgrades.admin.changeProxyAdmin(tokenInstance.address, owner.address);
expect(await upgrades.erc1967.getAdminAddress(tokenInstance.address)).to.equal(owner.address);
})
it.only("Should throw on trying to call contract implementation from new proxy admin owner", async function () {
const MarsCoin = await ethers.getContractFactory("MarsCoin");
tokenInstance = await upgrades.deployProxy(MarsCoin, [tokenName, tokenSymbol, owner.address], { initializer: 'initialize(string,string,address)', unsafeAllow: ['constructor'] });
await tokenInstance.deployed();
await upgrades.admin.changeProxyAdmin(tokenInstance.address, owner.address);
expect(await upgrades.erc1967.getAdminAddress(tokenInstance.address)).to.equal(owner.address);
await expect(tokenInstance.connect(owner).name()).to.be.revertedWith('TransparentUpgradeableProxy: admin cannot fallback to proxy target');
})
});
Keep in mind the .only test that I am running, thus, the rest can be skipped, but I just paste it to have the exact code.
Okay, I succeeded to fix this by just creating the project from scratch.
npm init -> then follow the basic instructions
npm install hardhat
npx hardhat init -> create an advanced sample project and follow the instructions
npm install - all the necessary packages that are missing (some of the existing ones were re-installed with older version, because it seems the problem comes from a newer version library)
Very interesting stuff.. previously I just tried to delete all the folders like .cache, node_module, the built folder, package-lock.json and then to hit the npm install, but without success. I could not understand what was exactly the issue.
However, these are the packages that I am using:
"devDependencies": {
"#nomiclabs/hardhat-ethers": "^2.0.2",
"#nomiclabs/hardhat-etherscan": "^3.0.3",
"#nomiclabs/hardhat-waffle": "^2.0.1",
"chai": "^4.3.4",
"dotenv": "^10.0.0",
"eslint": "^7.32.0",
"eslint-config-prettier": "^8.5.0",
"eslint-config-standard": "^16.0.3",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-node": "^11.1.0",
"eslint-plugin-prettier": "^3.4.1",
"eslint-plugin-promise": "^5.2.0",
"ethereum-waffle": "^3.4.0",
"ethers": "^5.4.5",
"hardhat": "^2.6.1",
"hardhat-gas-reporter": "^1.0.8",
"prettier": "^2.6.2",
"prettier-plugin-solidity": "^1.0.0-beta.13",
"solhint": "^3.3.7",
"solidity-coverage": "^0.7.20"
},
"dependencies": {
"#openzeppelin/contracts": "^4.3.0",
"#openzeppelin/contracts-upgradeable": "^4.3.2",
"#openzeppelin/hardhat-upgrades": "^1.10.0"
}

Why am I getting a 400 Bad request when calling Plaid's linkTokenCreate function?

I am attempting to set up Plaid in my app, and am following the Quickstart guide for Node.js and Express. When I call the client.linkTokenCreate function I am getting a status 400 Bad Request response. I believe my code exactly matches the quickstart, and I am using sandbox mode, so I am unsure where I am going wrong.
const { Configuration, PlaidApi, PlaidEnvironments, Products, CountryCode } = require("plaid");
const configuration = new Configuration({
basePath: PlaidEnvironments[process.env.PLAID_ENV],
baseOptions: {
headers: {
"PLAID-CLIENT-ID": process.env.PLAID_CLIENT_ID,
"PLAID-SECRET": process.env.PLAID_SECRET,
},
},
});
console.log(configuration)
const client = new PlaidApi(configuration);
router.post("/create_link_token", async (req, res) => {
// Get the client_user_id by searching for the current user
// const user = await User.find(...);
// const clientUserId = user.id;
const request = {
user: {
// This should correspond to a unique id for the current user.
client_user_id: "test123",
},
client_name: "Name Of App",
products: [Products.Auth],
language: "en",
webhook: 'https://app.com',
country_codes: [CountryCode.Us],
};
try {
console.log("request",process.env.PLAID_CLIENT_ID,process.env.PLAID_SECRET)
const createTokenResponse = await client.linkTokenCreate(request);
console.log("createTokenResponse", createTokenResponse);
res.status(200).json(createTokenResponse);
} catch (error) {
console.log("error", error.message)
res.send(error.message)
}
});

My friend is making a websocket server and it's not working

My friend made this WebSocket server for MineCraft and it doesn't work. He won't be on for a while so I decided to come to here. Can anyone help?
// Minecraft Bedrock WebSocket Server
const webSocket = require('websocket');
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const wss = new webSocket.server({port: 8000 });
try {
console.log("Server is running on your_ip:8000");
wss.on('connection', socket => {
console.log("A client is opening a connection");
const command = () => {
return new Promise((resolve) => {
rl.question(`Command: /`, (cmd) => {
// log user details
//console.log(`\nYour INPUT: /${cmd}`);
// Send command
socket.send(JSON.stringify(
{
"body": {
"origin": {
"type": "player"
},
"commandLine": `${cmd}`,
"version": 1
},
"header": {
"requestId": "00000000-0000-0000-0000-000000000000",
"messagePurpose": "commandRequest",
"version": 1,
"messageType": "commandRequest"
}
}
));
console.log("Command sent\n\n");
resolve();
});
});
}
async function askCommands() {
while (true) {
await command();
}
}
// Run async function
askCommands();
socket.on('message', function incoming(message) {
console.log('\nreceived: %s', message);
});
process.on('SIGINT', function() {
console.log("\nInterrupt Ctrl-C");
process.exit();
});
});
wss.off;
} catch(E) {
console.log(E);
}
This is the error in Visual Studio Code:
Debugger attached.
Waiting for the debugger to disconnect...
c:\Users\*****\Downloads\wsserver-bedrock-master\wsserver-bedrock-master\node_modules\websocket\lib\WebSocketServer.js:150
throw new Error('You must specify an httpServer on which to mount the WebSocket server.');
^
Error: You must specify an httpServer on which to mount the WebSocket server.
at WebSocketServer.mount (c:\Users\*****\Downloads\wsserver-bedrock-master\wsserver-bedrock-master\node_modules\websocket\lib\WebSocketServer.js:150:15)
at new WebSocketServer (c:\Users\*****\Downloads\wsserver-bedrock-master\wsserver-bedrock-master\node_modules\websocket\lib\WebSocketServer.js:36:14)
at Object.<anonymous> (c:\Users\*****\Downloads\wsserver-bedrock-master\wsserver-bedrock-master\wsserver.js:11:13)
at Module._compile (internal/modules/cjs/loader.js:1068:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:933:32)
at Function.Module._load (internal/modules/cjs/loader.js:774:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
Process exited with code 1
Uncaught Error: You must specify an httpServer on which to mount the WebSocket server.
No debugger available, can not send 'variables'
Hi you just code like this.
In Client Side code should be like
REF
And Server will be like this
REF 2:

Openwhisk: Request Entity Too Large

I have a local docker-based setup of Apache Openwhisk (https://github.com/apache/incubator-openwhisk-devtools), and when I'm trying to create an action from of a zip containing a packaged nodejs app with
wsk -i action create test --kind nodejs:6 test.zip -v
I get the following response:
413 Request Entity Too Large
The test.zip is only 5 MB large. What causes this issue? Is there any way to make openwhisk process larger requests?
UPD: the content of the test.zip is generated from a nodejs project, which has only 1 .js, which has a simple kafka topic consumer functionality.
function main(params) {
var kafka = require('kafka-node');
var HighLevelConsumer = kafka.HighLevelConsumer;
var Client = kafka.Client;
if (!(params && params.host)) {
return {error: 'host is required'};
}
if (!(params && params.port)) {
return {error: 'port is required'};
}
if (!(params && params.topic)) {
return {error: 'topic is required'};
}
var host = params.host;
var port = params.port;
var topic = params.topic;
var client = new Client(`${host}:${port}`);
var topics = [{
topic: topic
}];
var options = {
autoCommit: true,
fetchMaxWaitMs: 1000,
fetchMaxBytes: 1024 * 1024,
encoding: 'utf8'
};
var consumer = new HighLevelConsumer(client, topics, options);
consumer.on('message', function(message) {
console.log(message.value);
});
consumer.on('error', function(err) {
console.log('error', err);
});
process.on('SIGINT', function() {
consumer.close(true, function() {
process.exit();
});
});
}
exports.main = main;
And the package.json is the following:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "test.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node test.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"kafka-node": "^2.6.1"
}
}
It works correctly if I simply run it with npm start.
It looks like the NGINX proxy used to expose the API interface for the OpenWhisk platform defaults to a small value for the maximum request body size.
I have managed to re-produce the issue locally, anything above 512KB returns that error.
I've opened a ticket to see if the default limit can be increased: https://github.com/apache/incubator-openwhisk-devtools/issues/124

Resources