Untitled

mail@pastecode.io avatar
unknown
plain_text
25 days ago
3.0 kB
2
Indexable
Never
// Metric Sys
// Inject data
// Output Ts based Matric - Time Taken, Errors, Successes: Put, Get

//Put -> Params, { Duration, Errors, Successes...}

//Get-> Time range, Group: Minute, Hourwise, 
// Average, Max, Min
// 
const data = [];

/**
 * 
 * @param {*} ts Timestamp (millisecond)
 * @param {*} datum Map of duration, success etc. for the timestamp
 */
exports.put = (ts, datum) => {
    data.push({ ts, datum });
}

const MS_TO_M = 1000 * 60;
const MS_TO_H = 1000 * 3600;
// put(300, { duration: 2000 })
/**
 * 
 * @param {*} start Start timestamp inclusive
 * 
 * keys: One or more of duration, error etc., 
 * metric  : avg, max, min , one of
 * grouping: hourly, daily, minutewise
 */ // duration max every minute
exports.get = ({ start, end, key, metric, grouping }) => {
    const result = {};
    for (let i = 0; i < data.length; i++) {
        const entry = data[i];
        if (entry.ts < start || entry.ts > end) {
            continue;
        }
        const { datum, ts } = entry;
        const value = datum[key];
        let th;
        switch (grouping) {
            case 'minute':
                th = parseInt(ts / MS_TO_M);
                break;
            case 'hourly':
                th = parseInt(ts / MS_TO_H);
                break;

            default:
                break;
        }
        let tmp = result[th];
        if (!tmp) {
            tmp = result[th] = [];
        }
        tmp.push(value);
    }
    // { th : [v1,v2..], th1: [v3,v4..]}
    switch (metric) {
        case 'avg':
            Object.entries(result).forEach(([th, values]) => {
                const add = values.reduce((a, b) => a + b);
                result[th] = add / values.length;
            });
            break;
        case 'max':
            Object.entries(result).forEach(([th, values]) => {
                const max = Math.max(...values);
                result[th] = max;
            });
            break;
        case 'min':
            Object.entries(result).forEach(([th, values]) => {
                const min = Math.min(...values);
                result[th] = min;
            });
            break;
        default:
            break;
    }
    // result: Map: th -> value
    // console.log({result})
    return result;
}

// Exports
const file = exports;

function test1() {
    file.put(1725876666440, { duration: 1000 });
    file.put(1725876666441, { duration: 1500 });
    file.put(1725876860875, { duration: 3000 });
    file.put(1725877040875, { duration: 7000 });
    file.put(1725878840875, { duration: 3000 });
    file.put(1725882440875, { duration: 5000 });
    file.put(1725889640875, { duration: 3000 });

    const m = file.get({ start: 1725876666440, end: 1725889640875, key: 'duration', metric: 'min', grouping: 'hourly' });
    //const displayVals = Object.entries(m).map(([timeX, value]));
    console.log({m})
}

test1();
Leave a Comment