Why Nestjs + Firebase Cloud Functions will "Starting Nest application" multiple times - google-cloud-functions

Main problem
Why nestjs on firebase cloud function has to initialize once at firebase serve --only functions, and re-initialize again on the first API request.
Details
This is my main.ts:
import { NestFactory } from '#nestjs/core';
import {
ExpressAdapter,
NestExpressApplication,
} from '#nestjs/platform-express';
import * as express from 'express';
import { HttpsFunction, https, pubsub } from 'firebase-functions';
import { AppModule } from './app/app.module';
const server: express.Express = express();
export const createNestServer = async (expressInstance: express.Express) => {
const adapter = new ExpressAdapter(expressInstance);
const app = await NestFactory.create<NestExpressApplication>(
AppModule,
adapter,
{},
);
app.enableCors();
return app.init();
};
createNestServer(server)
.then((v) => console.log('Nest Ready'))
.catch((err) => console.error('Nest broken', err));
export const api: HttpsFunction = https.onRequest(server);
And app/test/test.service.ts:
import { Injectable } from '#nestjs/common';
#Injectable()
export class TestService {
constructor(
) {
console.log(11, 'constructor');
}
async testApi() {
console.log(22, 'gotten api')
return `Hello World!!!`;
}
}
When I firebase serve --only functions here are the logs:
> firebase serve --only functions
i functions: Watching "/Users/jingles/GitHub/pixelhead-backend" for Cloud Functions...
✔ functions[us-central1-api]: http function initialized (http://localhost:5000/test-application/us-central1/api).
> [Nest] 26036 - 27/04/2022, 04:06:30 LOG [NestFactory] Starting Nest application...
> 11 constructor
> [Nest] 26036 - 27/04/2022, 04:06:30 LOG [InstanceLoader] AppModule dependencies initialized +41ms
> [Nest] 26036 - 27/04/2022, 04:06:30 LOG [InstanceLoader] DiscoveryModule dependencies initialized +0ms
> [Nest] 26036 - 27/04/2022, 04:06:30 LOG [InstanceLoader] TestModule dependencies initialized +0ms
> [Nest] 26036 - 27/04/2022, 04:06:30 LOG [RoutesResolver] TestController {/test}: +1ms
> [Nest] 26036 - 27/04/2022, 04:06:30 LOG [RouterExplorer] Mapped {/test, GET} route +0ms
> [Nest] 26036 - 27/04/2022, 04:06:31 LOG [NestApplication] Nest application successfully started +1033ms
> Nest Ready
As you can see here Starting Nest application, 11 constructor and Nest Ready. All good.
But when I make a request /test/ this is the log I get:
> [Nest] 26052 - 27/04/2022, 04:06:53 LOG [NestFactory] Starting Nest application...
i functions: Beginning execution of "us-central1-api"
> 11 constructor
> [Nest] 26052 - 27/04/2022, 04:06:53 LOG [InstanceLoader] AppModule dependencies initialized +44ms
> [Nest] 26052 - 27/04/2022, 04:06:53 LOG [InstanceLoader] DiscoveryModule dependencies initialized +1ms
> [Nest] 26036 - 27/04/2022, 04:06:30 LOG [InstanceLoader] TestModule dependencies initialized +0ms
> [Nest] 26036 - 27/04/2022, 04:06:30 LOG [RoutesResolver] TestController {/test}: +1ms
> [Nest] 26036 - 27/04/2022, 04:06:30 LOG [RouterExplorer] Mapped {/test, GET} route +0ms
> 22 gotten api
i functions: Finished "us-central1-api" in ~1s
> [Nest] 26052 - 27/04/2022, 04:06:54 LOG [NestApplication] Nest application successfully started +985ms
> Nest Ready
The problem here you can see, it Starting Nest application again. Also Nest Ready comes after 22 gotten api.
What is the issue?

I believe you have two separates issues here:
Having "Starting Nest application" 2 times: Firebase functions are a serverless environment, that said you have no guarantees on which instance in the cloud will serve your request: an already initialized or not.
The emulator is simply emulating a "cold start" in this case, on the "/test/" request arrival, which means the index code is executed (env boostrapped) and then the request is served.
"Nest Ready comes after 22 gotten api"
This is basically due to these two lines of code:
createNestServer(server)
.then((v) => console.log('Nest Ready'))
.catch((err) => console.error('Nest broken', err));
export const api: HttpsFunction = https.onRequest(server);
the first initializes the Nest app on the Express instance, but does not stop the second line from serving the requests arriving at "/test/" endpoint. The app is probably "half" initialized when the request reaches the code so you don't get any error and the request is served anyways, but in general you should organize your code in a way that firstly bootstraps the Nest app AND THEN serve the requests.
Important note: As we are talking about a serverless environment, each time a request comes in you could be either in a situation in which the Nest app is already initialized or not. You should then organize your code accordingly.
Check here for reference:
https://docs.nestjs.com/faq/serverless

Related

How to run Karate and Gatling with Gradle build system for performance testing

I'm trying to run a Karate test as a Gatling performance test. I am being use Gradle however. When trying to run under Gradle the below disaster unfolds.
Appreciate any ideas what might be causing KarateAction to crash.
i have added Gatling dependencies in gradle build
BUILD GRADLE:
plugins {
// id 'org.springframework.boot' version '2.5.5'
// id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id 'net.researchgate.release' version '2.8.1'
}
group 'org.ikano'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
ext {
cucumberVersion = "5.7.0"
karateVersion = '1.1.0'
// kafkaProducer = "3.2.0"
// kafkaConsumer = "3.2.0"
// kafkaCommonModel = "3.2.0"
dbUtilsVersion = "1.7"
}
apply plugin: 'scala'
configurations {
gatling
}
sourceSets {
test {
resources {
srcDir file('src/test/java')
exclude '**/*.java'
exclude '**/*.scala'
}
}
}
test {
useJUnitPlatform()
systemProperty "karate.options", System.properties.getProperty("karate.options")
systemProperty "karate.env", System.properties.getProperty("karate.env")
outputs.upToDateWhen { false }
}
repositories {
maven {
url "https://artifacts.le.tnt.bank.*****/repository/maven-****"
credentials {
username '*******'
password '**********'
}
mavenCentral()
}
}
task karateDebug(type: JavaExec) {
classpath = sourceSets.test.runtimeClasspath
main = 'com.intuit.karate.cli.Main'
}
dependencies {
implementation("commons-configuration:commons-configuration:1.10")
implementation("org.json:json:20180813")
implementation("javax.mail:mail:1.5.0-b01")
implementation("com.jayway.jsonpath:json-path:2.6.0")
implementation("com.googlecode.json-simple:json-simple:1.1.1")
// implementation("org.springframework:spring-context:5.3.13")
implementation("org.apache.poi:poi-ooxml:4.1.1")
// implementation("org.springframework:spring-webmvc:4.3.0.RELEASE")
testImplementation("com.intuit.karate:karate-core:1.2.0")
testImplementation("junit:junit:4.13.2")
testImplementation("com.intuit.karate:karate-junit5:1.1.0")
testImplementation("com.intuit.karate:karate-gatling:1.1.0")
testImplementation("com.intuit.karate:karate-apache:0.9.6")
testImplementation("net.masterthought:cucumber-reporting:3.8.0")
testImplementation("hu.blackbelt.bundles.poi:org.apache.poi:4.1.2_2")
testImplementation("org.apache.poi:poi:4.1.1")
testImplementation("io.rest-assured:rest-assured:4.3.0")
testCompile 'com.intuit.karate:karate-junit5:1.1.0'
testCompile "com.intuit.karate:karate-gatling:${karateVersion}"
// compile group: 'org.springframework.boot', name: 'spring-boot-starter-parent', version: '2.5.5', ext: 'pom'
//implementation group: 'org.springframework', name: 'spring-websocket', version: '5.2.9.RELEASE'
//implementation group: 'org.springframework', name: 'spring-messaging', version: '5.2.9.RELEASE'
// implementation 'org.springframework.boot:spring-boot-starter-web'
// implementation 'org.springframework.boot:spring-boot-starter'
// testImplementation('org.springframework.boot:spring-boot-starter-test')
//{exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'}
compile group: 'joda-time', name: 'joda-time', version: '2.10.6'
// implementation "com.ikano.ipay.eem.kafka:kafka-producer:${kafkaProducer}"
// implementation "com.ikano.ipay.eem.kafka:kafka-consumer:${kafkaConsumer}"
// implementation "com.ikano.ipay.eem.kafka:kafka-common-model:${kafkaCommonModel}"
implementation group: 'redis.clients', name: 'jedis', version: '2.9.0'
implementation group: 'org.redisson', name: 'redisson', version: "3.16.3"
compile group: 'org.apache.poi', name: 'poi', version: '4.1.2'
compile group: 'org.apache.poi', name: 'poi-ooxml', version: '4.1.2'
compile group: 'commons-dbutils', name: 'commons-dbutils', version: "$dbUtilsVersion"
task gatlingRun(type: JavaExec) {
group = 'Web Tests'
description = 'Run Gatling Tests'
new File("${buildDir}/reports/gatling").mkdirs()
classpath = sourceSets.test.runtimeClasspath
main = "io.gatling.app.Gatling"
args = [
// change this to suit your simulation entry-point
'-s', 'performance2.userSimulation',
'-rf', "${buildDir}/reports/gatling"
]
systemProperties System.properties
}
group = "org.ikano"
version = "1.0-SNAPSHOT"
description = "IPay"
java.sourceCompatibility = JavaVersion.VERSION_1_8
FOR SCALA
package performance
import com.intuit.karate.gatling.PreDef._
import io.gatling.core.Predef._
import io.gatling.core.structure.ScenarioBuilder
import scala.concurrent.duration._
class UserSimulation extends Simulation{
val getSingleUser: ScenarioBuilder = scenario("UK Onboarding - Verify user is able to onboard successfully").exec(karateFeature("classpath:performance/onboarding.feature"))
setUp(
getSingleUser.inject(rampUsers(10).during(5 seconds))
)
}
Command Line :gradle gatlingRun
Starting a Gradle Daemon (subsequent builds will be faster)
> Task :gatlingRun
16:10:18.039 [main] INFO i.g.c.config.GatlingConfiguration$ - Gatling will try to use 'gatling.conf' as config file.
16:10:20.052 [GatlingSystem-akka.actor.default-dispatcher-6] INFO akka.event.slf4j.Slf4jLogger - Slf4jLogger started
16:10:22.818 [main] ERROR io.gatling.app.Gatling$ - Run crashed
java.lang.IllegalArgumentException: User defined Simulation class performance2.userSimulation could not be loaded
at io.gatling.app.Selection$Selector.findUserDefinedSimulationInClassloader$1(Selection.scala:80)
at io.gatling.app.Selection$Selector.$anonfun$singleSimulationFromConfig$4(Selection.scala:85)
at scala.Option.orElse(Option.scala:477)
at io.gatling.app.Selection$Selector.$anonfun$singleSimulationFromConfig$3(Selection.scala:85)
at scala.Option.flatMap(Option.scala:283)
at io.gatling.app.Selection$Selector.singleSimulationFromConfig(Selection.scala:83)
at io.gatling.app.Selection$Selector.$anonfun$selection$1(Selection.scala:52)
at scala.Option.getOrElse(Option.scala:201)
at io.gatling.app.Selection$Selector.selection(Selection.scala:44)
at io.gatling.app.Selection$.apply(Selection.scala:36)
at io.gatling.app.Runner.run0(Runner.scala:61)
at io.gatling.app.Runner.run(Runner.scala:49)
at io.gatling.app.Gatling$.start(Gatling.scala:83)
at io.gatling.app.Gatling$.fromArgs(Gatling.scala:45)
at io.gatling.app.Gatling$.main(Gatling.scala:37)
at io.gatling.app.Gatling.main(Gatling.scala)
Caused by: java.lang.ClassNotFoundException: performance2.userSimulation
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at io.gatling.app.Selection$Selector.$anonfun$singleSimulationFromConfig$2(Selection.scala:71)
at scala.util.Try$.apply(Try.scala:210)
at io.gatling.app.Selection$Selector.findUserDefinedSimulationInClassloader$1(Selection.scala:71)
... 15 common frames omitted
Exception in thread "main" java.lang.IllegalArgumentException: User defined Simulation class performance2.userSimulation could not be loaded
at io.gatling.app.Selection$Selector.findUserDefinedSimulationInClassloader$1(Selection.scala:80)
at io.gatling.app.Selection$Selector.$anonfun$singleSimulationFromConfig$4(Selection.scala:85)
at scala.Option.orElse(Option.scala:477)
at io.gatling.app.Selection$Selector.$anonfun$singleSimulationFromConfig$3(Selection.scala:85)
at scala.Option.flatMap(Option.scala:283)
at io.gatling.app.Selection$Selector.singleSimulationFromConfig(Selection.scala:83)
at io.gatling.app.Selection$Selector.$anonfun$selection$1(Selection.scala:52)
at scala.Option.getOrElse(Option.scala:201)
at io.gatling.app.Selection$Selector.selection(Selection.scala:44)
at io.gatling.app.Selection$.apply(Selection.scala:36)
at io.gatling.app.Runner.run0(Runner.scala:61)
at io.gatling.app.Runner.run(Runner.scala:49)
at io.gatling.app.Gatling$.start(Gatling.scala:83)
at io.gatling.app.Gatling$.fromArgs(Gatling.scala:45)
at io.gatling.app.Gatling$.main(Gatling.scala:37)
at io.gatling.app.Gatling.main(Gatling.scala)
Caused by: java.lang.ClassNotFoundException: performance2.userSimulation
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at io.gatling.app.Selection$Selector.$anonfun$singleSimulationFromConfig$2(Selection.scala:71)
at scala.util.Try$.apply(Try.scala:210)
at io.gatling.app.Selection$Selector.findUserDefinedSimulationInClassloader$1(Selection.scala:71)
... 15 more
> Task :gatlingRun FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':gatlingRun'.
> Process 'command 'C:\Program Files\Amazon Corretto\jdk1.8.0_282\bin\java.exe'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.9.1/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 44s
3 actionable tasks: 1 executed, 2 up-to-date
The package name is performance but inside the log it says:
performance2.userSimulation
Can you change it to in the run command:
performance.userSimulation
I think that is the issue you are facing. It cant find the simulation class.

invalid json response body error, while deploying Next.js app to Vercel

App builds fine locally and works on local production server + development server.
The api used to fetch data is working fine.
Code which is producing the error
export const getStaticProps = async () => {
const resp = await fetch(
'https://cdn-api.co-vin.in/api/v2/admin/location/states',
{
headers: {
'User-Agent': '*',
}, //this is required by api provider
}
);
const data = await resp.json();
//console.log('states in getStaticProps : ', data);
return { props: { data: JSON.parse(JSON.stringify(data)) } };
};
const Ninjas = ({ data: { states } }) => {
console.log('Ninjas : ', states);
return (
<>
<Head>
<title> Listing</title>
</Head>
<div>
{states.map((ei) => (
<div key={ei.state_id}>
<a className={styles.single}>
<h3>{ei.state_name}</h3>
</a>
</div>
))}
</div>
</>
);
};
export default Ninjas;
Following is the vercel log.
20:17:40.644 Cloning github.com/user-name/co2-app (Branch: main, Commit: 8ab0e48)
20:17:41.349 Cloning completed: 704.592ms
20:17:41.374 Analyzing source code...
20:17:42.573 Installing build runtime...
20:17:45.235 Build runtime installed: 2.662s
20:17:48.104 Looking up build cache...
20:17:48.453 Build cache not found
20:17:49.697 Installing dependencies...
20:18:04.559 > ejs#2.7.4 postinstall /vercel/path0/node_modules/ejs
20:18:04.559 > node ./postinstall.js
20:18:05.113 npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents#2.3.2 (node_modules/fsevents):
20:18:05.113 npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents#2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
20:18:05.116 added 600 packages from 352 contributors in 14.87s
20:18:05.426 64 packages are looking for funding
20:18:05.426 run `npm fund` for details
20:18:05.492 Detected Next.js version: 10.2.0
20:18:05.492 Running "npm run build"
20:18:05.756 > we2-cowax#0.1.0 build /vercel/path0
20:18:05.757 > next build
20:18:07.292 info - Using webpack 4. Reason: custom webpack configuration in next.config.js https://nextjs.org/docs/messages/webpack5
20:18:08.224 info - Checking validity of types...
20:18:08.244 Attention: Next.js now collects completely anonymous telemetry regarding usage.
20:18:08.245 This information is used to shape Next.js' roadmap and prioritize features.
20:18:08.245 You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
20:18:08.245 https://nextjs.org/telemetry
20:18:08.326 info - Creating an optimized production build...
20:18:08.748 > [PWA] Compile client (static)
20:18:08.748 > [PWA] Auto register service worker with: /vercel/path0/node_modules/next-pwa/register.js
20:18:08.750 > [PWA] Service worker: /vercel/path0/public/service-worker.js
20:18:08.750 > [PWA] url: /service-worker.js
20:18:08.750 > [PWA] scope: /
20:18:08.860 > [PWA] Compile server
20:18:25.603 info - Compiled successfully
20:18:25.604 info - Collecting page data...
20:18:26.366 info - Generating static pages (0/3)
20:18:26.918 error : invalid json response body at https://cdn-api.co-vin.in/api/v2/admin/location/states reason: Unexpected token < in JSON at position 0
20:18:26.919 Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
20:18:26.919 Error: Error serializing props returned from `getStaticProps` in "/".
20:18:26.919 Reason: Props must be returned as a plain object from getStaticProps: `{ props: { ... } }`.
20:18:26.919 at isSerializableProps (/vercel/path0/node_modules/next/dist/lib/is-serializable-props.js:1:462)
20:18:26.919 at renderToHTML (/vercel/path0/node_modules/next/dist/next-server/server/render.js:30:1730)
20:18:26.919 at processTicksAndRejections (internal/process/task_queues.js:93:5)
20:18:26.919 at async /vercel/path0/node_modules/next/dist/export/worker.js:26:6
20:18:26.919 at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
20:18:26.920 info - Generating static pages (3/3)
20:18:26.921 > Build error occurred
20:18:26.926 Error: Export encountered errors on following paths:
20:18:26.926 /
20:18:26.926 at /vercel/path0/node_modules/next/dist/export/index.js:31:1106
20:18:26.926 at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
20:18:26.927 at async /vercel/path0/node_modules/next/dist/build/index.js:43:49
20:18:26.927 at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
20:18:26.927 at async /vercel/path0/node_modules/next/dist/build/index.js:25:1475
20:18:26.927 at async Span.traceAsyncFn (/vercel/path0/node_modules/next/dist/telemetry/trace/trace.js:6:584)
20:18:26.954 npm ERR! code ELIFECYCLE
20:18:26.954 npm ERR! errno 1
20:18:26.958 npm ERR! co2-app#0.1.0 build: `next build`
20:18:26.958 npm ERR! Exit status 1
20:18:26.958 npm ERR!
20:18:26.959 npm ERR! Failed at the we2-cowax#0.1.0 build script.
20:18:26.959 npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
20:18:26.968 npm ERR! A complete log of this run can be found in:
20:18:26.968 npm ERR! /vercel/.npm/_logs/2021-05-17T14_48_26_959Z-debug.log
20:18:26.982 Error: Command "npm run build" exited with 1
I am using next-pwa for PWA functionality and hence custom webpack version
Have delete the app at Vercel and re-deploy, even removed the cache build but still can't resolve the error
Problem
The API is returning a 403 forbidden error:
!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>
</HEAD>
<BODY>
<H1>403 ERROR</H1>
<H2>The request could not be satisfied.</H2>
<HR noshade size="1px">
Request blocked.
We can't connect to the server for this app or website at this time. There might be too much traffic or a
configuration error. Try again later, or contact the app or website owner.
<BR clear="all">
If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.
<BR clear="all">
<HR noshade size="1px">
<PRE>
Generated by cloudfront (CloudFront)
Request ID: BqNxi8x1nTA3YKM_N3JSCyjGVDYnMUDNFvS_HgJGB8glTFr1uVh6Ug==
</PRE>
<ADDRESS>
</ADDRESS>
</BODY>
</HTML>
which is not then being handled correctly by your getStaticProps function (in this case, an invalid response can't be turned into JSON; also, your User-Agent is not valid):
export const getStaticProps = async () => {
const resp = await fetch(
'https://cdn-api.co-vin.in/api/v2/admin/location/states',
{
headers: {
'User-Agent': '*',
}, //this is required by api provider
}
);
// this throws an error because you can't turn
// the invalid server response into JSON
const data = await resp.json();
return { props: { data: JSON.parse(JSON.stringify(data)) } };
};
which is also not being handled correctly by your Ninjas component -- states would be undefined because the server doesn't respond with valid data and you can't map an undefined variable. Instead you should check that states is a non-empty Array before mapping over it by either using lodash's isEmpty: !isEmpty(states) && states.map(...) or by checking that it's defined and has length: Array.isArray(states) && states.length > 0 && states.map(...).
Solution
import Head from "next/head";
import isEmpty from "lodash.isempty";
export const getStaticProps = async () => {
let data = [];
let error = "";
try {
const res = await fetch(
"https://cdn-api.co-vin.in/api/v2/admin/location/states",
{
method: "GET",
headers: {
// update with your user-agent
"User-Agent":
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
Accept: "application/json; charset=UTF-8",
},
}
);
if (res.status !== 200)
throw String(`Invalid server response: ${res.status} ${res.statusText}`);
data = await res.json();
if (isEmpty(data)) throw String("No data was found!");
data = JSON.parse(JSON.stringify(data));
} catch (e) {
error = e.toString();
}
return {
props: {
data,
error,
},
};
};
const Ninjas = ({ data, error }) => (
<>
<Head>
<title> Listing</title>
</Head>
<div>
{error && <p style={{ color: "red" }}>{error}</p>}
{!isEmpty(data) && !isEmpty(data.states) &&
data.states.map((ei) => (
<div key={ei.state_id}>
<a className={styles.single}>
<h3>{ei.state_name}</h3>
</a>
</div>
))}
</div>
</>
);
export default Ninjas;

Truffle Smart Contract Error: Invalid number of parameter

I followed the tutorial of quorum with truffle: https://truffleframework.com/tutorials/building-dapps-for-quorum-private-enterprise-blockchains
Now I want to migrate the SimpleStorage.sol Smart Contract to the blockchain, but I want to make it to add the "PrivateFor" parameter.
This is my Smart Contract:
pragma solidity ^0.4.17;
contract SimpleStorage {
uint public storedData;
constructor(uint initVal) public {
storedData = initVal;
}
function set(uint x) public {
storedData = x;
}
function get() view public returns (uint retVal) {
return storedData;
}
}
This is my: 2_deploy_simplestorage.js
var SimpleStorage = artifacts.require("SimpleStorage");
module.exports = function(deployer) {
deployer.deploy(SimpleStorage, 42, {privateFor: ["ROAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc="]})
};
But when I do truffle migrate, I get this error:
$ truffle migrate
⚠️ Important ⚠️
If you're using an HDWalletProvider, it must be Web3 1.0 enabled or your migration will hang.
Starting migrations...
======================
> Network name: 'development'
> Network id: 10
> Block gas limit: 3758096384
1_initial_migration.js
======================
Deploying 'Migrations'
----------------------
> transaction hash: 0x0a55cd010bb30247c3ae303e54be8dd13177b520af5967728cf77e07ca9efe76
- Blocks: 0 Seconds: 0
> Blocks: 0 Seconds: 0
> contract address: 0x1932c48b2bF8102Ba33B4A6B545C32236e342f34
> account: 0xed9d02e382b34818e88B88a309c7fe71E65f419d
> balance: 1000000000
> gas used: 245462
> gas price: 0 gwei
> value sent: 0 ETH
> total cost: 0 ETH
- Saving migration to chain.
> Saving migration to chain.
> Saving artifacts
-------------------------------------
> Total cost: 0 ETH
2_deploy_simplestorage.js
=========================
Deploying 'SimpleStorage'
-------------------------
Error: *** Deployment Failed ***
"SimpleStorage" -- Invalid number of parameters for "undefined". Got 2 expected 1!.
at C:\Users\dany.vandermeij\AppData\Roaming\npm\node_modules\truffle\build\webpack:\packages\truffle-deployer\src\deployment.js:364:1
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
Truffle v5.0.1 (core: 5.0.1)
Node v8.11.4
When I don't add the "privateFor" parameter, it works:
var SimpleStorage = artifacts.require("SimpleStorage");
module.exports = function(deployer) {
deployer.deploy(SimpleStorage, 42)
};
But I need this privateFor parameter..
Does someone know how to fix this?
Hey #BlockChainProgrammer. Thanks for guiding me on how to use the Quorum proxy. It worked.
For this error, Try to upgrade/downgrade your truffle version to v4.1.
$ npm install -g truffle#4.1.10
and change the version of solidity to 0.4.24 in your truffle-config.js and the SimpleStorage.sol and add back privateFor in your migration file.
In this case of quorum, the
{
privateFor: ["ROAZBWtSacxXQrOe3FGAqJDyJjFePR5ce4TSIzmJ0Bc="]})
};
was not defined in the contract, and at such the error, but that particular truffle compiler is compatible with Quorum features.
But For non-Quorum users like myself
The error Usually means, define a variable in your contract and not a compiler problem. Most likely a parameter not set in the constructor.
Open to corrections
Problem solved!
What I had to do is to downgrade truffle to "4.1.10" with:
truffle uninstall -g
and then
npm install -g truffle#4.1.10
Many thanks to #TS28

ClassNotFoundException when trying to deploy a DataSource with #DataSourceDefinition

I'm trying to deploy a datasource with the #DataSourceDefinition-Annotation.
When wildfly deploys the jar, it throws a ClassNotFoundException.
I put the mysql-jdbc-Driver in the deployment-directory. I already use the com.mysql.jdbc.Driver class in Datasources configured in standalone.xml. I havn't created a module with the jdbc-driver under "modules\system\layers\base"
Here is the Class with the Annotation:
#Stateless
#DataSourceDefinition(name = "java:global/jdbc/testingDS",
className = "com.mysql.jdbc.Driver",
portNumber = 3306,
serverName = "localhost",
databaseName = "testing",
user = "testing",
password = "testing")
public class DataSourceDeployment {
public void someMethod() { }
}
And here is the Exception (this is the *.failed-File):
{
"JBAS014671: Failed services" => {"jboss.deployment.unit.\"DatasourceDeploymentTest-1.jar\".INSTALL" => "org.jboss.msc.service.StartException in service jboss.deployment.unit.\"DatasourceDeploymentTest-1.jar\".INSTALL: JBAS018733: Failed to process phase INSTALL of deployment \"DatasourceDeploymentTest-1.jar\"
Caused by: org.jboss.as.server.deployment.DeploymentUnitProcessingException: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver from [Module \"deployment.DatasourceDeploymentTest-1.jar:main\" from Service Module Loader]
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver from [Module \"deployment.DatasourceDeploymentTest-1.jar:main\" from Service Module Loader]"},
"JBAS014771: Services with missing/unavailable dependencies" => [
"jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment.InstanceName is missing [jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment]",
"jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment.ORB is missing [jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment]",
"jboss.deployment.unit.\"DatasourceDeploymentTest-1.jar\".weld.weldClassIntrospector is missing [jboss.deployment.unit.\"DatasourceDeploymentTest-1.jar\".beanmanager]",
"jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment.HandleDelegate is missing [jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment]",
"jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment.ValidatorFactory is missing [jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment]",
"jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment.InAppClientContainer is missing [jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment]",
"jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment.Validator is missing [jboss.naming.context.java.comp.DatasourceDeploymentTest-1.DatasourceDeploymentTest-1.DataSourceDeployment]"
]
}
CFNE is just as it should be.
You have mysql jdbc driver in module but your deployment and it's #DataSourceDefinition know noting about it.
#DataSourceDefinition uses deployments classloader to load the jdbc driver but it is not available to it as it is in module.
To solve this you should either
1) add deployment's dependency to your mysql driver module via manifest.mf / jboss-deployment-structure.xml, see https://docs.jboss.org/author/display/WFLY8/Class+Loading+in+WildFly for details how
2) add jdbc driver to your war's lib directory
but I would definitely go with 1)

Logging errors in a grails application in the logs

When my Grails application crashes, it shows the error and the stacktrace on the error page because the error.gsp page has the following snippet <g:renderException exception="${exception}" />. However nothing gets logged in the log file.
How can I change this? because for the production application I plan to remove the renderException because I don't want users to see the entire stacktrace.
My log4j settings are as follows:
appenders {
rollingFile name:'catalinaOut', maxFileSize:1024, fileName:"${System.properties.getProperty('catalina.home')}/logs/mylog.log"
}
root {
error 'catalinaOut'
debug 'catalinaOut'
additivity = true
}
error 'org.codehaus.groovy.grails.web.servlet', // controllers
'org.codehaus.groovy.grails.web.pages', // GSP
'org.codehaus.groovy.grails.web.sitemesh', // layouts
'org.codehaus.groovy.grails.web.mapping.filter', // URL mapping
'org.codehaus.groovy.grails.web.mapping', // URL mapping
'org.codehaus.groovy.grails.commons', // core / classloading
'org.codehaus.groovy.grails.plugins', // plugins
'org.codehaus.groovy.grails.orm.hibernate', // hibernate integration
'org.springframework',
'org.hibernate',
'net.sf.ehcache.hibernate',
'grails.app'
debug 'grails.app'
}
I'm running the app in development as grails run-app
I use these settings for console and file based logging. You can remove stdout if you don't want/need console. Just copy all your error classes in the corresponding list.
log4j = {
def loggerPattern = '%d %-5p >> %m%n'
def errorClasses = [] // add more classes if needed
def infoClasses = ['grails.app.controllers.myController'] // add more classes if needed
def debugClasses = [] // add more classes if needed
appenders {
console name:'stdout', layout:pattern(conversionPattern: loggerPattern)
rollingFile name: "file", maxFileSize: 1024, file: "./tmp/logs/logger.log", layout:pattern(conversionPattern: loggerPattern)
}
error stdout: errorClasses, file: errorClasses
info stdout: infoClasses, file: infoClasses
debug stdout: debugClasses, file: debugClasses
}