Skip to content

Commit

Permalink
feat: support LogQL metric
Browse files Browse the repository at this point in the history
  • Loading branch information
fraxken committed Oct 26, 2023
1 parent 29814c5 commit 431c680
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
25 changes: 21 additions & 4 deletions src/logql/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import { ParserExpression } from "./parserExpression";
export { StreamSelector, LineFilters, LabelFilters, ParserExpression };

export class LogQL {
#type: "metric" | "query" = "query";
#rawInit: string;

streamSelector = new StreamSelector();
lineFilters = new LineFilters();
labelFilters = new LabelFilters();
Expand All @@ -16,10 +19,16 @@ export class LogQL {
init?: string | string[] | StreamSelector | LineFilters | LabelFilters | ParserExpression
) {
if (typeof init === "string") {
this.streamSelector = new StreamSelector(init);
this.lineFilters = new LineFilters(init);
this.labelFilters = new LabelFilters(init);
this.parserExpression = new ParserExpression(init);
this.#type = /[a-zA-Z_]+\(/g.test(init) ? "metric" : "query";

Check failure

Code scanning / CodeQL

Polynomial regular expression used on uncontrolled data High

This
regular expression
that depends on
library input
may run slow on strings with many repetitions of 'A'.

if (this.#type === "metric") {
this.#rawInit = init;
}
const finalInit = this.#type === "query" ? init : void 0;
this.streamSelector = new StreamSelector(finalInit);
this.lineFilters = new LineFilters(finalInit);
this.labelFilters = new LabelFilters(finalInit);
this.parserExpression = new ParserExpression(finalInit);

return this;
}
Expand Down Expand Up @@ -49,6 +58,10 @@ export class LogQL {
}
}

get type() {
return this.#type;
}

lineEq(value: string) {
this.lineFilters.add(value, "lineContains");

Expand All @@ -74,6 +87,10 @@ export class LogQL {
}

toString() {
if (this.#type === "metric") {
return this.#rawInit;
}

return `
${this.streamSelector.toString()}
${this.lineFilters.toString()}
Expand Down
9 changes: 9 additions & 0 deletions src/logql/test/logql.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ describe("LogQL", () => {
const logql = new LogQL();

assert.ok(logql instanceof LogQL);
assert.strictEqual(logql.type, "query");
});

it("should be a lineContains given a string", () => {
Expand Down Expand Up @@ -106,4 +107,12 @@ describe("LogQL", () => {
"{app=\"discussion\",env=\"production\"} |= `returned ` | regexp `((?P<execTime>[0-9.]+)ms)` | execTime > 500"
);
});

it("should preserve metric without modifications", () => {
const originalQL = `count_over_time({job="mysql"}[5m])`;
const logql = new LogQL(originalQL);

assert.strictEqual(logql.type, "metric");
assert.strictEqual(logql.toString(), originalQL);
});
});

0 comments on commit 431c680

Please sign in to comment.