Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add stats routes #1400

Merged
merged 23 commits into from
Mar 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
3e4e6fd
added new stats to metrics endpoint
dashcraft Feb 18, 2022
1518370
chore: added cron job for new metrics
dashcraft Feb 18, 2022
d79024e
working on writing some tests
dashcraft Feb 18, 2022
c77cb2c
left a duplicated function
dashcraft Feb 18, 2022
1168273
fixes database credentials for startup
dashcraft Feb 23, 2022
736325c
updated verbiage
dashcraft Feb 23, 2022
191e535
Rewrote the stats to have a total uploads and also a percent growth rate
dashcraft Feb 24, 2022
749b430
chore: added materialized view that calculates growth rate and establ…
dashcraft Feb 25, 2022
b830a2d
move files to another branch, reset these files
dashcraft Feb 25, 2022
2c450c4
missed a file for the other branch
dashcraft Feb 25, 2022
004b490
tests
dashcraft Feb 25, 2022
0806da3
Added a generic test for the material view
dashcraft Feb 27, 2022
a87ec6f
formatted sql statements
dashcraft Feb 27, 2022
87321e8
updated sql formatting again, it did something weird with dashes
dashcraft Feb 27, 2022
b2e08a2
update stats endpoint to have other stats
dashcraft Feb 28, 2022
523c4a7
Updated to include additional status
dashcraft Feb 28, 2022
340c2a7
additional stats supports
dashcraft Feb 28, 2022
05a8827
Updated stats test
dashcraft Feb 28, 2022
36fcd6b
fix function names
dashcraft Feb 28, 2022
76a86ed
Updated to use metrics table isntead
dashcraft Mar 2, 2022
123bb20
Updated verbiage to be consistent.
dashcraft Mar 2, 2022
8343718
Can no longer test since metrics get generated on cron
dashcraft Mar 2, 2022
cabf531
add timelog to stats
dashcraft Mar 7, 2022
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
3 changes: 1 addition & 2 deletions packages/api/db/cargo.testing.sql
Original file line number Diff line number Diff line change
Expand Up @@ -48,5 +48,4 @@ INSERT INTO cargo.deals ("deal_id", "aggregate_cid", "client", "provider", "stat

INSERT INTO public."user" (magic_link_id, github_id, name, email, public_address) VALUES ('did:ethr:0x65007A739ab7AC5c537161249b81250E49e2853Z', 'github|000000', 'mock user', 'test@gmail.com', '0x65007A739ab7AC5c537161249b81250E49e2853Z');

INSERT INTO public.auth_key (name, secret, user_id) VALUES ('main', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkaWQ6ZXRocjoweDY1MDA3QTczOWFiN0FDNWM1MzcxNjEyNDliODEyNTBFNDllMjg1M0MiLCJpc3MiOiJuZnQtc3RvcmFnZSIsImlhdCI6MTYzOTc1NDczNjYzOCwibmFtZSI6Im1haW4ifQ.wKwJIRXXHsgwVp8mOQp6r3_F4Lz5lnoAkgVP8wqwA_Y', 1);

INSERT INTO public.auth_key (name, secret, user_id) VALUES ('main', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkaWQ6ZXRocjoweDY1MDA3QTczOWFiN0FDNWM1MzcxNjEyNDliODEyNTBFNDllMjg1M0MiLCJpc3MiOiJuZnQtc3RvcmFnZSIsImlhdCI6MTYzOTc1NDczNjYzOCwibmFtZSI6Im1haW4ifQ.wKwJIRXXHsgwVp8mOQp6r3_F4Lz5lnoAkgVP8wqwA_Y', 1);
3 changes: 2 additions & 1 deletion packages/api/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { notFound } from './utils/utils.js'
import { HTTPError } from './errors.js'
import { cors, postCors } from './routes/cors.js'
import { JSONResponse } from './utils/json-response.js'
import { metrics } from './routes/metrics.js'
import { getStats, metrics } from './routes/metrics.js'
import { tokensDelete } from './routes/tokens-delete.js'
import { tokensCreate } from './routes/tokens-create.js'
import { tokensList } from './routes/tokens-list.js'
Expand Down Expand Up @@ -45,6 +45,7 @@ const r = new Router(getContext, {

// Monitoring
r.add('get', '/metrics', withMode(metrics, RO))
r.add('get', '/stats', withMode(getStats, RO))

// CORS
r.add('options', '*', cors)
Expand Down
14 changes: 14 additions & 0 deletions packages/api/src/routes/metrics.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { UPLOAD_TYPES, PIN_SERVICES, PIN_STATUSES } from '../utils/db-client.js'
import { JSONResponse } from '../utils/json-response.js'

/**
* TODO: basic auth
Expand All @@ -8,6 +9,19 @@ export async function metrics(_, { db }) {
return new Response(await exportPromMetrics(db))
}

/** @type {import('../bindings').Handler} */
export async function getStats(_, { db }) {
let stats = await db.getStats()

return new JSONResponse(
{
ok: true,
data: stats,
},
{ status: 200 }
)
}

/**
* Exports metrics in prometheus exposition format.
* https://prometheus.io/docs/instrumenting/exposition_formats/
Expand Down
30 changes: 30 additions & 0 deletions packages/api/src/utils/db-client.js
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,36 @@ export class DBClient {

return data[0].value
}

async getStats() {
/** @type {PostgrestQueryBuilder<definitions['upload_stats']>} */
const query = this.client.from('metric')
const { data, error } = await query
.select('name, value')
.in('name', [
'deals_total',
'deals_size_total',
'uploads_past_7_total',
'uploads_blob_total',
'uploads_car_total',
'uploads_nft_total',
'uploads_remote_total',
'uploads_multipart_total',
])

if (error) {
throw new DBError(error)
}

if (!data || !data.length) {
return undefined
}

return data.reduce((obj, curr) => {
obj[curr.name] = curr.value
return obj
}, {})
}
}

export class DBError extends Error {
Expand Down
15 changes: 15 additions & 0 deletions packages/api/src/utils/db-types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,18 @@ export interface paths {
}
}
}
'/stats': {
get: {
responses: {
/** OK */
200: {
schema: definitions['upload_stats'][]
}
/** Partial Content */
206: unknown
}
}
}
'/metric': {
get: {
parameters: {
Expand Down Expand Up @@ -857,6 +869,9 @@ export interface definitions {
/** Format: timestamp with time zone */
deleted_at?: string
}
upload_stats: {
[key: string]: string
}
backup: {
/**
* Format: bigint
Expand Down
46 changes: 46 additions & 0 deletions packages/cron/src/jobs/metrics.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ const COUNT_USERS = 'SELECT COUNT(*) AS total FROM public.user'

const COUNT_UPLOADS = 'SELECT COUNT(*) AS total FROM upload WHERE type = $1'

const UPLOADS_PAST_7_TOTAL =
'SELECT COUNT(*) FROM upload WHERE inserted_at > CURRENT_DATE - 7'

const DEALS_TOTAL = 'SELECT COUNT(*) from cargo.deals'

const DEALS_SIZE_TOTAL =
'SELECT SUM(export_size) as deals_size_total from cargo.aggregates'

const COUNT_PINS =
'SELECT COUNT(*) AS total FROM pin WHERE service = $1 AND status = $2'

Expand Down Expand Up @@ -45,6 +53,11 @@ export async function updateMetrics({ roPg, rwPg }) {
updateUploadsCount(roPg, rwPg, t)
)
),
withTimeLog('updateTotalUploadPast7', () =>
updateTotalUploadPast7(roPg, rwPg)
),
withTimeLog('updateTotalDeals', () => updateTotalDeals(roPg, rwPg)),
withTimeLog('updateTotalDealsSize', () => updateTotalDealsSize(roPg, rwPg)),
...PIN_SERVICES.map((svc) =>
PIN_STATUSES.map((s) =>
withTimeLog(`updatePinsCount[${svc}][${s}]`, () =>
Expand Down Expand Up @@ -85,6 +98,39 @@ async function updateUsersCount(roPg, rwPg) {
await rwPg.query(UPDATE_METRIC, ['users_total', rows[0].total])
}

/**
* @param {Client} roPg
* @param {Client} rwPg
*/
async function updateTotalUploadPast7(roPg, rwPg) {
const { rows } = await roPg.query(UPLOADS_PAST_7_TOTAL)
if (!rows.length) throw new Error('no rows returned counting uploads')
await rwPg.query(UPDATE_METRIC, ['uploads_past_7_total', rows[0].count])
}

/**
* @param {Client} roPg
* @param {Client} rwPg
*/
async function updateTotalDeals(roPg, rwPg) {
const { rows } = await roPg.query(DEALS_TOTAL)
if (!rows.length) throw new Error(`no rows returned counting total deals`)
await rwPg.query(UPDATE_METRIC, [`deals_total`, rows[0].count])
}

/**
* @param {Client} roPg
* @param {Client} rwPg
*/
async function updateTotalDealsSize(roPg, rwPg) {
const { rows } = await roPg.query(DEALS_SIZE_TOTAL)
if (!rows.length) throw new Error(`no rows returned counting total deal size`)
await rwPg.query(UPDATE_METRIC, [
`deals_size_total`,
rows[0].deals_size_total,
])
}

/**
* @param {Client} roPg
* @param {Client} rwPg
Expand Down