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(server): add connection stats to the access key metrics #1634

Merged
merged 13 commits into from
Feb 10, 2025
Merged
15 changes: 15 additions & 0 deletions package-lock.json

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

101 changes: 96 additions & 5 deletions src/shadowbox/infrastructure/prometheus_scraper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,84 @@ import * as path from 'path';

import * as logging from '../infrastructure/logging';

/**
* Represents a Unix timestamp in seconds.
* @typedef {number} Timestamp
*/
type Timestamp = number;

/**
* Represents a Prometheus metric's labels.
* Each key in the object is a label name, and the corresponding value is the label's value.
*
* @typedef {Object<string, string>} PrometheusMetric
*/
export type PrometheusMetric = {[labelValue: string]: string};

/**
* Represents a Prometheus value, which is a tuple of a timestamp and a string value.
* @typedef {[Timestamp, string]} PrometheusValue
*/
export type PrometheusValue = [Timestamp, string];

/**
* Represents a Prometheus result, which can be a time series (values) or a single value.
* @typedef {Object} PrometheusResult
* @property {Object.<string, string>} metric - Labels associated with the metric.
* @property {Array<PrometheusValue>} [values] - Time series data (for range queries).
* @property {PrometheusValue} [value] - Single value (for instant queries).
*/
export type PrometheusResult = {
metric: PrometheusMetric;
values?: PrometheusValue[];
value?: PrometheusValue;
};

/**
* Represents the data part of a Prometheus query result.
* @interface QueryResultData
*/
export interface QueryResultData {
resultType: 'matrix' | 'vector' | 'scalar' | 'string';
result: Array<{
metric: {[labelValue: string]: string};
value: [number, string];
}>;
result: PrometheusResult[];
}

// From https://prometheus.io/docs/prometheus/latest/querying/api/
/**
* Represents the full JSON response from a Prometheus query. This interface
* is based on the Prometheus API documentation:
* https://prometheus.io/docs/prometheus/latest/querying/api/
* @interface QueryResult
*/
interface QueryResult {
status: 'success' | 'error';
data: QueryResultData;
errorType: string;
error: string;
}

/**
* Interface for a Prometheus client.
* @interface PrometheusClient
*/
export interface PrometheusClient {
/**
* Performs an instant query against the Prometheus API.
* @function query
* @param {string} query - The PromQL query string.
* @returns {Promise<QueryResultData>} A Promise that resolves to the query result data.
*/
query(query: string): Promise<QueryResultData>;

/**
* Performs a range query against the Prometheus API.
* @function queryRange
* @param {string} query - The PromQL query string.
* @param {Date} start - The start time for the query range.
* @param {Date} end - The end time for the query range.
* @param {string} step - The step size for the query range (e.g., "1m", "5m"). This controls the resolution of the returned data.
* @returns {Promise<QueryResultData>} A Promise that resolves to the query result data.
*/
queryRange(query: string, start: Date, end: Date, step: string): Promise<QueryResultData>;
}

export class ApiPrometheusClient implements PrometheusClient {
Expand Down Expand Up @@ -71,6 +131,37 @@ export class ApiPrometheusClient implements PrometheusClient {
});
});
}

queryRange(query: string, start: Date, end: Date, step: string): Promise<QueryResultData> {
return new Promise<QueryResultData>((fulfill, reject) => {
const url = `${this.address}/api/v1/query_range?query=${encodeURIComponent(
query
)}&start=${start.toISOString()}&end=${end.toISOString()}&step=${step}`;
http
.get(url, (response) => {
if (response.statusCode < 200 || response.statusCode > 299) {
reject(new Error(`Got error ${response.statusCode}`));
response.resume();
return;
}
let body = '';
response.on('data', (data) => {
body += data;
});
response.on('end', () => {
const result = JSON.parse(body) as QueryResult;
if (result.status !== 'success') {
console.log(result);
return reject(new Error(`Error ${result.errorType}: ${result.error}`));
}
fulfill(result.data);
});
})
.on('error', (e) => {
reject(new Error(`Failed to query prometheus API: ${e}`));
});
});
}
}

export async function startPrometheus(
Expand Down
1 change: 1 addition & 0 deletions src/shadowbox/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"Using https:// for ShadowsocksConfig to avoid adding git in the Docker image"
],
"dependencies": {
"heap-js": "^2.6.0",
"ip-regex": "^4.1.0",
"js-yaml": "^3.12.0",
"outline-shadowsocksconfig": "github:Jigsaw-Code/outline-shadowsocksconfig#v0.2.0",
Expand Down
Loading
Loading