All files / src/Batch LokiGetQueryListBatch.ts

66.66% Statements 34/51
43.18% Branches 19/44
66.66% Functions 6/9
78.04% Lines 32/41

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 2391x 1x   1x 1x   1x   1x 1x 1x     1x     1x       1x   1x   1x   1x     1x     1x 1x 1x 1x 1x   1x             1x   1x   1x         1x 1x 3x 1x 15x       9x 1x                   1x                                                                                                                                                                                                                                                                                                                                          
import ABatchNode from '@orchesty/nodejs-sdk/dist/lib/Batch/ABatchNode';
import { HttpMethods } from '@orchesty/nodejs-sdk/dist/lib/Transport/HttpMethods';
import BatchProcessDto from '@orchesty/nodejs-sdk/dist/lib/Utils/BatchProcessDto';
import ResultCode from '@orchesty/nodejs-sdk/dist/lib/Utils/ResultCode';
import { NAME as APPLICATION_NAME } from '../LokiApplication';
 
export const NAME = `${APPLICATION_NAME}-get-query-list-batch`;
 
enum Direction {
    FORWARD = 'forward',
    BACKWARD = 'backward',
}
 
export default class LokiGetQueryListBatch extends ABatchNode {
 
    public getName(): string {
        return NAME;
    }
 
    public async processAction(dto: BatchProcessDto<IInput>): Promise<BatchProcessDto> {
        const boundaryTimestamp = dto.getBatchCursor();
 
        const { query, limit, start, end, since, interval, step, direction } = dto.getJsonData();
 
        const params = new URLSearchParams({ query });
 
        Iif (start || (boundaryTimestamp && direction === Direction.FORWARD)) {
            params.set('start', (direction === Direction.FORWARD ? boundaryTimestamp || String(start) : String(start)));
        }
        Iif (end || (boundaryTimestamp && direction !== Direction.FORWARD)) {
            params.set('end', (direction === Direction.FORWARD ? String(end) : boundaryTimestamp || String(end)));
        }
        Iif (limit) params.set('limit', String(limit));
        Iif (since) params.set('since', since);
        Iif (interval) params.set('interval', String(interval));
        Iif (step) params.set('step', String(step));
        Iif (direction) params.set('direction', direction);
 
        const requestDto = await this.getApplication().getRequestDto(
            dto,
            await this.getApplicationInstallFromProcess(dto),
            HttpMethods.GET,
            `/loki/api/v1/query_range?${params}`,
        );
 
        const responseDto = await this.getSender().send<IOutput>(requestDto);
 
        const { status, data } = responseDto.getJsonBody();
 
        Iif (status !== 'success') {
            dto.setStopProcess(ResultCode.STOP_AND_FAILED, 'Unexpected error occurred during LogQL query execution');
            return dto;
        }
 
        const items: string[] = [];
        if (data.resultType === 'streams') {
            const result = data.result.flatMap((item) => item.values);
            result.sort((a, b) => (
                direction === Direction.FORWARD
                    ? Number(a[0]) - Number(b[0])
                    : Number(b[0]) - Number(a[0])
            ));
            items.push(...result.map((item) => item[1]));
            Iif (result.length === (limit ?? 100)) {
                const timestamp = Number(result[result.length - 1][0]);
                dto.setBatchCursor(String(timestamp + (direction === Direction.FORWARD ? 1 : -1)));
            }
        } else E{
            const result = data.result.flatMap((item) => item.values);
            result.sort((a, b) => (direction === Direction.FORWARD ? a[0] - b[0] : b[0] - a[0]));
            items.push(...result.map((item) => item[1]));
        }
 
        return dto.setItemList(items);
    }
 
}
 
type Duration = `${number}${'ns' | 'us' | 'µs' | 'ms' | 's' | 'm' | 'h'}`;
 
export interface IInput {
    /** LogQL query to retrieve data */
    query: string;
    /**
     * Applied only to `streams` (log lines) response type. Reduces amount of log entries to specified number.
     *
     * - This defaults to 100
     */
    limit?: number;
    /**
     * The unix epoch timestamp in nanoseconds or unix epoch timestamp in seconds with fractions (for floating point numbers)
     * or string in `RFC3339` format which represents timestamp.
     *
     * - This defaults to 1 hour ago
     */
    start?: number | string;
    /**
     * The unix epoch timestamp in nanoseconds or unix epoch timestamp in seconds with fractions (for floating point numbers)
     * or string in `RFC3339` format which represents timestamp.
     *
     * - This defaults now
     */
    end?: number | string;
    /**
     * A duration used to calculate `start` relative to `end`. If `start` is specified, then this value is ignored.
     * If `end` is not specified or targets to future timestamp, then the `start` is calculated relatively to now.
     *
     * - This defaults to 1h
     */
    since?: Duration;
    /**
     * Applied only to `matrix` response type. Query resolution step width in `duration` format or float number of seconds.
     * The `duration` refers to Prometheus duration strings of the form `[0-9]+[smhdwy]`.
     *
     * - Defaults to a dynamic value based on start and end
     */
    step?: string | number;
    /**
     * Applied only to `streams` response type. This iterates through logs by specified interval and returns one log entry
     * at time. That means it takes first log entry within `start` then omits other entries until `start` + `interval` boundary
     * is reached. Then repeats the step until `end` of interval.
     */
    interval?: Duration | number;
    /**
     * Determines the sort order of logs.
     *
     * - This defaults to `backward`
     */
    direction?: Direction;
}
 
export interface IOutput {
    status: string;
    data: ({
        resultType: 'matrix';
        result: {
            metric: Record<string, unknown>;
            values: [number, string][]
        }[];
    } | {
        resultType: 'streams';
        result: {
            stream: Record<string, unknown>;
            values: [string, string][]
        }[];
    }) & { stats: Statistics };
}
 
interface Statistics {
    summary: {
        bytesProcessedPerSecond: number;
        linesProcessedPerSecond: number;
        totalBytesProcessed: number;
        totalLinesProcessed: number;
        execTime: number;
        queueTime: number;
        subqueries: number;
        totalEntriesReturned: number;
        splits: number;
        shards: number;
        totalPostFilterLines: number;
        totalStructuredMetadataBytesProcessed: number;
    };
    querier: {
        store: Store;
    };
    ingester: {
        totalReached: number;
        totalChunksMatched: number;
        totalBatches: number;
        totalLinesSent: number;
        store: Store;
    }
    cache: {
        chunk: CacheStatistic;
        index: CacheStatistic;
        result: CacheStatistic;
        statsResult: CacheStatistic;
        volumeResult: CacheStatistic;
        seriesResult: CacheStatistic;
        labelResult: CacheStatistic;
        instantMetricResult: CacheStatistic;
    };
    index: {
        totalChunks: number;
        postFilterChunks: number;
        shardsDuration: number;
        usedBloomFilters: boolean;
    };
}
 
interface Store {
    totalChunksRef: number;
    totalChunksDownloaded: number;
    chunksDownloadTime: number;
    queryReferencedStructuredMetadata: boolean;
    queryUsedV2Engine: boolean;
    chunk: {
        headChunkBytes: number;
        headChunkLines: number;
        decompressedBytes: number;
        decompressedLines: number;
        compressedBytes: number;
        totalDuplicates: number;
        postFilterLines: number;
        headChunkStructuredMetadataBytes: number;
        decompressedStructuredMetadataBytes: number;
    };
    chunkRefsFetchTime: number;
    congestionControlLatency: number;
    pipelineWrapperFilteredLines: number;
    dataobj: {
        prePredicateDecompressedRows: number;
        prePredicateDecompressedBytes: number;
        prePredicateDecompressedStructuredMetadataBytes: number;
        postPredicateRows: number;
        postPredicateDecompressedBytes: number;
        postPredicateStructuredMetadataBytes: number;
        postFilterRows: number;
        pagesScanned: number;
        pagesDownloaded: number;
        pagesDownloadedBytes: number;
        pageBatches: number;
        totalRowsAvailable: number;
        totalPageDownloadTime: number;
    };
}
 
interface CacheStatistic {
    entriesFound: number;
    entriesRequested: number;
    entriesStored: number;
    bytesReceived: number;
    bytesSent: number;
    requests: number;
    downloadTime: number;
    queryLengthServed: number;
}