Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs

name: Node.js CI
name: Unit and integration tests

on:
push:
Expand All @@ -17,7 +17,6 @@ jobs:
strategy:
matrix:
node-version: [18.x, 20.x, 22.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/

steps:
- uses: actions/checkout@v4
Expand All @@ -28,5 +27,6 @@ jobs:
cache: 'npm'
- run: npm install
- run: docker compose -f docker-compose.dev.yaml up -d
- run: sleep 3
- run: npm run unit-test
- run: npm run integration-test
136 changes: 136 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# vitepress build output
**/.vitepress/dist

# vitepress cache directory
**/.vitepress/cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
32 changes: 32 additions & 0 deletions docker-compose.metrics.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
version: "3"
services:
prometheus:
image: prom/prometheus
ports:
- 9090:9090
volumes:
- ./prometheus_data:/prometheus
- ./prometheus.yml:/etc/prometheus/prometheus.yml
command:
- "--config.file=/etc/prometheus/prometheus.yml"
extra_hosts:
- "host.docker.internal:192.168.1.120"
networks:
- localprom

grafana:
image: grafana/grafana-enterprise
ports:
- 3000:3000
volumes:
- ./grafana_data:/var/lib/grafana
extra_hosts:
- "host.docker.internal:192.168.1.120"
networks:
- localprom
depends_on:
- prometheus

networks:
localprom:
driver: bridge
34 changes: 34 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
"mysql": "^2.18.1",
"knex": "^3.1.0",
"js-yaml": "^4.1.0",
"yargs": "17.7.2"
"yargs": "17.7.2",
"prom-client": "^15.1.3"
},

"devDependencies": {
Expand Down
11 changes: 11 additions & 0 deletions prometheus.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
global:
scrape_interval: 5s

scrape_configs:
- job_name: "prometheus_service"
static_configs:
- targets: ["host.docker.internal:9090"]

- job_name: "nodejs_service"
static_configs:
- targets: ["host.docker.internal:8080"]
44 changes: 44 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,54 @@ const express = require('express');

const cities = require('./route/cities');
const { config } = require('./config/configuration');
const promClient = require('prom-client');
const { httpRequestDurationSeconds, httpRequestsTotal, inFlightRequests } = require('./config/metrics'); // Use direct imports

const app = express();
app.use(express.json());

// Recoge métricas por defecto
promClient.collectDefaultMetrics();
// Recoger las métricas configuradas en config/metrics
app.use((req, res, next) => {
// Anota la request en vuelo
inFlightRequests.inc();

// Inicia un timer para comenzar a calcular la duración de la request
const end = httpRequestDurationSeconds.startTimer();

const method = req.method;
const path = req.route ? req.route.path : req.path;

// Cada vez que una request termina, se recogen las métricas configuradas
res.on('finish', () => {
const statusCode = res.statusCode;

// Captura la duración de la petición
end({ method, path, code: statusCode });
// Incrementa el contador de peticiones HTTP
httpRequestsTotal.inc({
code: statusCode,
method: method.toLowerCase(),
path: path
});

// Decrementa el contador de peticiones en vuelo
inFlightRequests.dec();
});

next();
});

app.get('/metrics', async(req, res) => {
try {
res.set('Content-Type', promClient.register.contentType);
res.end(await promClient.register.metrics());
} catch (error) {
res.status(500).end(error);
}
});

app.use('/', cities);

app.listen(config.service.port, () => {
Expand Down
28 changes: 28 additions & 0 deletions src/config/metrics.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
'use strict';
const promClient = require('prom-client');

// Crea un histograma para registrar la duración de las peticiones HTTP en segundos
const httpRequestDurationSeconds = new promClient.Histogram({
name: 'http_request_duration_seconds',
help: 'Duration of HTTP requests in seconds',
labelNames: ['method', 'path', 'code'],
});

// Crea un contador de peticiones HTTP totales
const httpRequestsTotal = new promClient.Counter({
name: 'http_requests_total',
help: 'How many HTTP requests processed, partitioned by status code, method, and HTTP path',
labelNames: ['method', 'path', 'code'],
});

// Crea una medición de las peticiones HTTP en vuelo
const inFlightRequests = new promClient.Gauge({
name: 'http_requests_in_flight',
help: 'Current number of in-flight HTTP requests',
});

module.exports = {
httpRequestDurationSeconds,
httpRequestsTotal,
inFlightRequests,
};
6 changes: 4 additions & 2 deletions src/service/cities.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,9 @@ const cityExists = (async (name) => {
const registerCity = (async (name, population, altitude, foundationDate, area) => {
const age = getYearsFromNow(new Date(foundationDate));
const density = getDensity(population, area);
let cityId;

const returning = await db('cities')
.returning("id") // TODO Revisar cómo funciona para MariaDB
.insert({
name: name,
population: population,
Expand All @@ -47,10 +47,12 @@ const registerCity = (async (name, population, altitude, foundationDate, area) =
age: age,
area: area,
density: density
}).then( async (ids) => {
cityId = ids[0];
});

const result = {
id: returning[0].id,
id: cityId,
age: age,
density: density
};
Expand Down
Loading