Skip to content

Commit 0669848

Browse files
committed
new version
1 parent 8f63e77 commit 0669848

File tree

19 files changed

+899
-242
lines changed

19 files changed

+899
-242
lines changed
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
INSTRUMENTATIONKEY=
2-
APPINSIGHTS_INSTRUMENTATIONKEY=
3-
PORT=
1+
AIC_STRING=
2+
PORT=8082
3+
VERSION=blue 1

apps/js-calc-backend/app/config.js

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,17 @@
11
var config = {}
2+
const fs = require('fs');
3+
const OS = require('os');
24

3-
config.instrumentationKey = process.env.INSTRUMENTATIONKEY;
4-
if (config.instrumentationKey && config.instrumentationKey == "dummyValue")
5+
config.aicstring = process.env.AIC_STRING;
6+
if (config.aicstring && config.aicstring == "dummyValue")
57
{
6-
config.instrumentationKey = null;
8+
config.aicstring = null;
79
}
8-
config.port = process.env.PORT || 8080;
9-
config.laggy = process.env.LAGGY;
10-
config.buggy = process.env.BUGGY;
1110

11+
config.port = process.env.PORT || 8080;
12+
config.laggy = process.env.LAGGY || true;
13+
config.buggy = process.env.BUGGY || true;
14+
config.writepath = process.env.WRITEPATH;
1215
config.version = "default - latest";
1316

1417
if (process.env.VERSION && process.env.VERSION.length > 0)
@@ -24,4 +27,15 @@ else {
2427
}
2528
}
2629

30+
if (config.writepath && fs.existsSync(config.writepath)){
31+
var startDate = new Date();
32+
const content = startDate.toLocaleDateString() + "-" + startDate.toLocaleTimeString() + '-' + OS.hostname() + "-starting-" + process.pid + "\r\n";
33+
fs.writeFile(config.writepath + 'lifecycle.txt', content, { flag: 'a+' }, err => { console.log(err); })
34+
process.on('SIGTERM', function () {
35+
var endDate = new Date();
36+
const content = endDate.toLocaleDateString() + "-" + endDate.toLocaleTimeString() + '-' + OS.hostname() + "-stopping-" + process.pid + "\r\n";
37+
fs.writeFile(config.writepath + 'lifecycle.txt', content, { flag: 'a+' }, err => { console.log(err); })
38+
});
39+
}
40+
2741
module.exports = config;
Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,135 @@
1+
openapi: 3.0.0
2+
servers:
3+
- url: 'http://calc-backend.swagger.io/'
4+
info:
5+
description: >-
6+
This is a backend api for the prime factor calculator demo app.
7+
version: 1.0.0
8+
title: OpenAPI Calculator Backend
9+
license:
10+
name: Apache-2.0
11+
url: 'https://www.apache.org/licenses/LICENSE-2.0.html'
12+
tags:
13+
- name: calculator
14+
description: Calculator app
15+
- name: backend
16+
description: Backend app
17+
paths:
18+
/ping:
19+
get:
20+
tags:
21+
- ping
22+
summary: Ping the app for a response
23+
description: ''
24+
responses:
25+
'200':
26+
description: successful operation
27+
content:
28+
application/json:
29+
schema:
30+
$ref: '#/components/schemas/Ping'
31+
'500':
32+
description: Invalid Ping
33+
/healthz:
34+
get:
35+
tags:
36+
- health
37+
summary: Check application health status
38+
description: ''
39+
responses:
40+
'200':
41+
description: successful operation
42+
content:
43+
application/json:
44+
schema:
45+
$ref: '#/components/schemas/Health'
46+
'500':
47+
description: Invalid Health
48+
/api/calculate:
49+
post:
50+
tags:
51+
- backend
52+
summary: Calculates the prime factors for a given number
53+
description: ''
54+
operationId: calculalate
55+
responses:
56+
'200':
57+
description: successful operation
58+
content:
59+
application/json:
60+
schema:
61+
$ref: '#/components/schemas/CalculationResponse'
62+
'405':
63+
description: Invalid input
64+
requestBody:
65+
$ref: '#/components/requestBodies/CalculationRequest'
66+
components:
67+
requestBodies:
68+
CalculationRequest:
69+
description: A calculation request
70+
content:
71+
application/json:
72+
schema:
73+
$ref: '#/components/schemas/CalculationRequest'
74+
schemas:
75+
Ping:
76+
title: Ping
77+
description: A ping for application level response
78+
type: object
79+
properties:
80+
response:
81+
type: string
82+
correlation:
83+
type: string
84+
host:
85+
type: string
86+
source:
87+
type: string
88+
forwarded:
89+
type: string
90+
version:
91+
type: string
92+
Health:
93+
title: Health
94+
description: A health probe response
95+
type: object
96+
properties:
97+
uptime:
98+
type: string
99+
message:
100+
type: string
101+
date:
102+
type: string
103+
format: date-time
104+
CalculationResponse:
105+
title: Calculation Response
106+
description: A prime factor calculation result
107+
type: object
108+
properties:
109+
host:
110+
type: string
111+
correlation:
112+
type: string
113+
timestamp:
114+
type: string
115+
format: date-time
116+
remote:
117+
type: string
118+
forwarded:
119+
type: string
120+
version:
121+
type: string
122+
values:
123+
type: array
124+
items:
125+
type: string
126+
CalculationRequest:
127+
title: Calculation Request
128+
description: A prime factor calculation request
129+
type: object
130+
properties:
131+
number:
132+
type: integer
133+
format: int32
134+
randomvictim:
135+
type: boolean

apps/js-calc-backend/app/package.json

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,10 @@
1010
"name": "dzielke"
1111
},
1212
"dependencies": {
13-
"express": "^4.17.3",
13+
"express": "^4.18.2",
1414
"morgan": "^1.10.0",
15-
"applicationinsights": "^2.2.2",
15+
"applicationinsights": "^2.5.1",
1616
"dotenv-extended": "^2.9.0",
17-
"swagger-ui-express": "^4.3.0"
17+
"swagger-ui-express": "^4.6.2"
1818
}
1919
}

apps/js-calc-backend/app/server.js

Lines changed: 43 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,32 @@
11
require('dotenv-extended').load();
22
const config = require('./config');
3-
var appInsights = require("applicationinsights");
43

5-
if (config.instrumentationKey){
6-
appInsights.setup(config.instrumentationKey)
4+
const appInsights = require("applicationinsights");
5+
6+
if (config.aicstring){
7+
appInsights.setup(config.aicstring)
78
.setAutoDependencyCorrelation(true)
9+
.setAutoCollectRequests(true)
10+
.setAutoCollectPerformance(true, true)
11+
.setAutoCollectExceptions(true)
812
.setAutoCollectDependencies(true)
9-
.setAutoCollectPerformance(true)
13+
.setAutoCollectConsole(true)
14+
.setUseDiskRetryCaching(true)
1015
.setSendLiveMetrics(true)
1116
.setDistributedTracingMode(appInsights.DistributedTracingModes.AI_AND_W3C);
12-
appInsights.defaultClient.context.tags[appInsights.defaultClient.context.keys.cloudRole] = "http-calcback";
17+
appInsights.defaultClient.context.tags[appInsights.defaultClient.context.keys.cloudRole] = "http-backend";
1318
appInsights.start();
14-
var client = appInsights.defaultClient;
15-
client.commonProperties = {
19+
appInsights.defaultClient.commonProperties = {
1620
slot: config.version
1721
};
1822
}
19-
20-
var client = appInsights.defaultClient;
23+
const swaggerUi = require('swagger-ui-express'), swaggerDocument = require('./swagger.json');
24+
const OS = require('os');
2125

2226
const express = require('express');
2327
const app = express();
28+
app.use(express.json())
2429
const morgan = require('morgan');
25-
26-
var swaggerUi = require('swagger-ui-express'),
27-
swaggerDocument = require('./swagger.json');
28-
29-
const OS = require('os');
30-
31-
// add logging middleware
3230
app.use(morgan('dev'));
3331

3432
// Routes
@@ -40,12 +38,19 @@ app.get('/', function(req, res) {
4038
});
4139
app.get('/ping', function(req, res) {
4240
console.log('received ping');
43-
var pong = { response: "pong!", host: OS.hostname(), version: config.version };
41+
const sourceIp = req.connection.remoteAddress;
42+
const forwardedFrom = (req.headers['x-forwarded-for'] || '').split(',').pop();
43+
const pong = { response: "pong!", correlation: "", timestamp: new Date(), host: OS.hostname(), source: sourceIp, forwarded: forwardedFrom, version: config.version };
4444
console.log(pong);
45-
res.send(pong);
45+
res.status(200).send(pong);
4646
});
4747
app.get('/healthz', function(req, res) {
48-
res.send('OK');
48+
const data = {
49+
uptime: process.uptime(),
50+
message: 'Ok',
51+
date: new Date()
52+
}
53+
res.status(200).send(data);
4954
});
5055

5156
var primeFactors = function getAllFactorsFor(remainder) {
@@ -70,64 +75,50 @@ var primeFactors = function getAllFactorsFor(remainder) {
7075
return factors;
7176
}
7277

73-
// curl -X POST --header "number: 3" --header "randomvictim: true" http://localhost:3002/api/calculation
74-
app.post('/api/calculation', function(req, res) {
78+
// curl -X POST --header "number: 3" --header "randomvictim: true" http://localhost:8082/api/calculate
79+
// curl -X POST --url http://localhost:8082/api/calculate --header 'content-type: application/json' --data '{"number": "42", "randomvictim": "true", "laggy": "true"}'
80+
app.post('/api/calculate', function(req, res) {
7581
console.log("received client request:");
7682
console.log(req.headers);
77-
if (config.instrumentationKey){
78-
var startDate = new Date();
79-
client.trackEvent( { name: "calculation-js-backend-call"});
80-
}
83+
console.log(req.body);
84+
console.log(req.body.number);
85+
const requestId = req.headers['traceparent'] || '';
8186
var resultValue = [0];
8287
try{
83-
resultValue = primeFactors(req.headers.number);
88+
resultValue = primeFactors(req.body.number);
8489
console.log("calculated:");
8590
console.log(resultValue);
8691
}catch(e){
92+
console.log("correlation: " + requestId);
8793
console.log(e);
88-
if (config.instrumentationKey){
89-
client.trackException(e);
90-
}
9194
resultValue = [0];
9295
}
93-
var endDate = new Date();
94-
if (config.instrumentationKey){
95-
var duration = endDate - startDate;
96-
client.trackEvent({ name: "calculation-js-backend-result"});
97-
client.trackMetric({ name:"calculation-js-backend-duration", value: duration });
98-
}
99-
if (req.headers.joker){
100-
resultValue = "42";
101-
}
96+
const endDate = new Date();
10297

103-
var randomNumber = Math.floor((Math.random() * 20) + 1);
98+
const randomNumber = Math.floor((Math.random() * 20) + 1);
99+
const remoteAddress = req.connection.remoteAddress;
100+
const forwardedFrom = (req.headers['x-forwarded-for'] || '').split(',').pop();
104101

105-
if ((req.headers.randomvictim && req.headers.randomvictim ===true ) || (config.buggy && randomNumber > 19)){
102+
if ((req.body.randomvictim && req.body.randomvictim ===true ) || (config.buggy && randomNumber > 19)){
106103
console.log("looks like a 19 bug");
107-
res.status(500).send({ value: "[ b, u, g]", error: "looks like a 19 bug", host: OS.hostname(), remote: remoteAddress, version: config.version });
104+
res.status(500).send({ timestamp: endDate, correlation: requestId, values: [ 'b', 'u', 'g'], host: OS.hostname(), remote: remoteAddress, forwarded: forwardedFrom, version: config.version });
108105
}
109106
else{
110-
var remoteAddress = req.connection.remoteAddress;
111-
var serverResult = JSON.stringify({ timestamp: endDate, value: resultValue, host: OS.hostname(), remote: remoteAddress, version: config.version } );
107+
const serverResult = { timestamp: endDate, correlation: requestId, values: resultValue, host: OS.hostname(), remote: remoteAddress, forwarded: forwardedFrom, version: config.version };
112108
console.log(serverResult);
113-
res.send(serverResult.toString());
109+
res.status(200).send(serverResult);
114110
}
115111
});
116112

117113
app.post('/api/dummy', function(req, res) {
118114
console.log("received dummy request:");
119-
console.log(req.headers)
120-
if (config.instrumentationKey){
121-
client.trackEvent({ name: "dummy-js-backend-call"});
122-
}
115+
console.log(req.headers);
116+
console.log(req.body);
123117
res.send('42');
124118
});
125119

126120
console.log(config);
127121
console.log(OS.hostname());
128-
// Listen
129-
if (config.instrumentationKey){
130-
client.trackEvent({ name: "js-backend-initializing"});
131-
}
122+
132123
app.listen(config.port);
133124
console.log('Listening on localhost:'+ config.port);

0 commit comments

Comments
 (0)