Vincent Bernat: Building a SQL-like language to filter flows
Language parser
PEG grammars are relatively recent2 and are an alternative to
context-free grammars. They are easier to write and they can generate better
error messages. Python switched from an LL(1)-based parser to a PEG-based
parser in Python 3.9.
pigeon generates a parser for Go. A grammar is a set of rules. Each rule is
an identifier, with an optional user-friendly label for error messages, an
expression, and an action in Go to be executed on match. You can find the
complete grammar in parser.peg. Here is a simplified rule:
ConditionIPExpr "condition on IP"
column:("ExporterAddress"i return "ExporterAddress", nil
/ "SrcAddr"i return "SrcAddr", nil
/ "DstAddr"i return "DstAddr", nil ) _
operator:("=" / "!=") _
ip:IP
return fmt.Sprintf("%s %s IPv6StringToNum(%s)",
toString(column), toString(operator), quote(ip)), nil
The rule identifier is ConditionIPExpr. It case-insensitively matches
ExporterAddress, SrcAddr, or DstAddr. The action for each case returns the
proper case for the column name. That s what is stored in the column variable.
Then, it matches one of the possible operators. As there is no code block, it
stores the matched string directly in the operator variable. Then, it tries to
match the IP rule, which is defined elsewhere in the grammar. If it succeeds,
it stores the result of the match in the ip variable and executes the final
action. The action turns the column, operator, and IP into a proper expression
for ClickHouse. For example, if we have ExporterAddress = 203.0.113.15, we
get ExporterAddress = IPv6StringToNum('203.0.113.15').
The IP rule uses a rudimentary regular expression but checks if the matched
address is correct in the action block, thanks to netip.ParseAddr():
IP "IP address" [0-9A-Fa-f:.]+
ip, err := netip.ParseAddr(string(c.text))
if err != nil
return "", errors.New("expecting an IP address")
return ip.String(), nil
Our parser safely turns the filter into a WHERE clause accepted by
ClickHouse:3
WHERE InIfBoundary = 'external'
AND ExporterRegion = 'france'
AND InIfConnectivity = 'transit'
AND SrcAS = 15169
AND DstAddr BETWEEN toIPv6('2a01:e0f:ffff::')
AND toIPv6('2a01:e0f:ffff:ffff:ffff:ffff:ffff:ffff')
Integration in CodeMirror
CodeMirror is a versatile code editor that can be easily integrated into
JavaScript projects. In Akvorado, the Vue.js component,
InputFilter, uses CodeMirror as its foundation and
leverages features such as syntax highlighting, linting, and completion. The
source code for these capabilities can be found in the
codemirror/lang-filter/ directory.
Syntax highlighting
The PEG grammar for Go cannot be utilized directly4 and the requirements
for parsers for editors are distinct: they should be error-tolerant and operate
incrementally, as code is typically updated character by character. CodeMirror
offers a solution through its own parser generator, Lezer.
We don t need this additional parser to fully understand the filter language.
Only the basic structure is needed: column names, comparison and logic
operators, quoted and unquoted values. The grammar is therefore quite short
and does not need to be updated often:
@top Filter
expression
expression
Not expression
"(" expression ")"
"(" expression ")" And expression
"(" expression ")" Or expression
comparisonExpression And expression
comparisonExpression Or expression
comparisonExpression
comparisonExpression
Column Operator Value
Value
String Literal ValueLParen ListOfValues ValueRParen
ListOfValues
ListOfValues ValueComma (String Literal)
String Literal
// [ ]
@tokens
// [ ]
Column std.asciiLetter (std.asciiLetter std.digit)*
Operator $[a-zA-Z!=><]+
String
'"' (![\\\n"] "\\" _)* '"'?
"'" (![\\\n'] "\\" _)* "'"?
Literal (std.digit std.asciiLetter $[.:/])+
// [ ]
The expression SrcAS = 12322 AND (DstAS = 1299 OR SrcAS = 29447) is parsed to:
Filter(Column, Operator, Value(Literal),
And, Column, Operator, Value(Literal),
Or, Column, Operator, Value(Literal))
The last step is to teach CodeMirror how to map each token to a highlighting
tag:
export const FilterLanguage = LRLanguage.define(
parser: parser.configure(
props: [
styleTags(
Column: t.propertyName,
String: t.string,
Literal: t.literal,
LineComment: t.lineComment,
BlockComment: t.blockComment,
Or: t.logicOperator,
And: t.logicOperator,
Not: t.logicOperator,
Operator: t.compareOperator,
"( )": t.paren,
),
],
),
);
Linting
We offload linting to the original parser in Go. The
/api/v0/console/filter/validate endpoint accepts a filter and returns a JSON
structure with the errors that were found:
"message": "at line 1, position 12: string literal not terminated",
"errors": [
"line": 1,
"column": 12,
"offset": 11,
"message": "string literal not terminated",
]
The linter source for CodeMirror queries the API and turns each error into
a diagnostic.
Completion
The completion system takes a hybrid approach. It splits the work between the
frontend and the backend to offer useful suggestions for completing filters.
The frontend uses the parser built with Lezer to determine the context of
the completion: do we complete a column name, an operator, or a value? It also
extracts the column name if we are completing something else. It forwards the
result to the backend through the /api/v0/console/filter/complete endpoint.
Walking the syntax tree was not as easy as I thought, but unit tests helped
a lot.
The backend uses the parser generated by pigeon to complete a column name
or a comparison operator. For values, the completions are either static or
extracted from the ClickHouse database. A user can complete an AS number from
an organization name thanks to the following snippet:
results := []struct
Label string ch:"label"
Detail string ch:"detail"
columnName := "DstAS"
sqlQuery := fmt.Sprintf(
SELECT concat('AS', toString(%s)) AS label, dictGet('asns', 'name', %s) AS detail
FROM flows
WHERE TimeReceived > date_sub(minute, 1, now())
AND detail != ''
AND positionCaseInsensitive(detail, $1) >= 1
GROUP BY label, detail
ORDER BY COUNT(*) DESC
LIMIT 20
, columnName, columnName)
if err := conn.Select(ctx, &results, sqlQuery, input.Prefix); err != nil
c.r.Err(err).Msg("unable to query database")
break
for _, result := range results
completions = append(completions, filterCompletion
Label: result.Label,
Detail: result.Detail,
Quoted: false,
)
In my opinion, the completion system is a major factor in making the field
editor an efficient way to select flows. While a query builder may have been
more beginner-friendly, the completion system s ease of use and functionality
make it more enjoyable to use once you become familiar.
-
Moreover, building a query builder did not seem like a fun task for me.
-
They were introduced in 2004 in Parsing Expression Grammars: A
Recognition-Based Syntactic Foundation. LR parsers were
introduced in 1965, LALR parsers in 1969, and LL parsers in the
1970s. Yacc, a popular parser generator, was written in 1975.
-
The parser returns a string. It does not generate an intermediate AST.
This makes it simpler and it currently fits our needs.
-
It could be manually translated to JavaScript with PEG.js.
ConditionIPExpr "condition on IP" column:("ExporterAddress"i return "ExporterAddress", nil / "SrcAddr"i return "SrcAddr", nil / "DstAddr"i return "DstAddr", nil ) _ operator:("=" / "!=") _ ip:IP return fmt.Sprintf("%s %s IPv6StringToNum(%s)", toString(column), toString(operator), quote(ip)), nil
IP "IP address" [0-9A-Fa-f:.]+ ip, err := netip.ParseAddr(string(c.text)) if err != nil return "", errors.New("expecting an IP address") return ip.String(), nil
WHERE InIfBoundary = 'external' AND ExporterRegion = 'france' AND InIfConnectivity = 'transit' AND SrcAS = 15169 AND DstAddr BETWEEN toIPv6('2a01:e0f:ffff::') AND toIPv6('2a01:e0f:ffff:ffff:ffff:ffff:ffff:ffff')
InputFilter, uses CodeMirror as its foundation and
leverages features such as syntax highlighting, linting, and completion. The
source code for these capabilities can be found in the
codemirror/lang-filter/ directory.
Syntax highlighting
The PEG grammar for Go cannot be utilized directly4 and the requirements
for parsers for editors are distinct: they should be error-tolerant and operate
incrementally, as code is typically updated character by character. CodeMirror
offers a solution through its own parser generator, Lezer.
We don t need this additional parser to fully understand the filter language.
Only the basic structure is needed: column names, comparison and logic
operators, quoted and unquoted values. The grammar is therefore quite short
and does not need to be updated often:
@top Filter
expression
expression
Not expression
"(" expression ")"
"(" expression ")" And expression
"(" expression ")" Or expression
comparisonExpression And expression
comparisonExpression Or expression
comparisonExpression
comparisonExpression
Column Operator Value
Value
String Literal ValueLParen ListOfValues ValueRParen
ListOfValues
ListOfValues ValueComma (String Literal)
String Literal
// [ ]
@tokens
// [ ]
Column std.asciiLetter (std.asciiLetter std.digit)*
Operator $[a-zA-Z!=><]+
String
'"' (![\\\n"] "\\" _)* '"'?
"'" (![\\\n'] "\\" _)* "'"?
Literal (std.digit std.asciiLetter $[.:/])+
// [ ]
The expression SrcAS = 12322 AND (DstAS = 1299 OR SrcAS = 29447) is parsed to:
Filter(Column, Operator, Value(Literal),
And, Column, Operator, Value(Literal),
Or, Column, Operator, Value(Literal))
The last step is to teach CodeMirror how to map each token to a highlighting
tag:
export const FilterLanguage = LRLanguage.define(
parser: parser.configure(
props: [
styleTags(
Column: t.propertyName,
String: t.string,
Literal: t.literal,
LineComment: t.lineComment,
BlockComment: t.blockComment,
Or: t.logicOperator,
And: t.logicOperator,
Not: t.logicOperator,
Operator: t.compareOperator,
"( )": t.paren,
),
],
),
);
Linting
We offload linting to the original parser in Go. The
/api/v0/console/filter/validate endpoint accepts a filter and returns a JSON
structure with the errors that were found:
"message": "at line 1, position 12: string literal not terminated",
"errors": [
"line": 1,
"column": 12,
"offset": 11,
"message": "string literal not terminated",
]
The linter source for CodeMirror queries the API and turns each error into
a diagnostic.
Completion
The completion system takes a hybrid approach. It splits the work between the
frontend and the backend to offer useful suggestions for completing filters.
The frontend uses the parser built with Lezer to determine the context of
the completion: do we complete a column name, an operator, or a value? It also
extracts the column name if we are completing something else. It forwards the
result to the backend through the /api/v0/console/filter/complete endpoint.
Walking the syntax tree was not as easy as I thought, but unit tests helped
a lot.
The backend uses the parser generated by pigeon to complete a column name
or a comparison operator. For values, the completions are either static or
extracted from the ClickHouse database. A user can complete an AS number from
an organization name thanks to the following snippet:
results := []struct
Label string ch:"label"
Detail string ch:"detail"
columnName := "DstAS"
sqlQuery := fmt.Sprintf(
SELECT concat('AS', toString(%s)) AS label, dictGet('asns', 'name', %s) AS detail
FROM flows
WHERE TimeReceived > date_sub(minute, 1, now())
AND detail != ''
AND positionCaseInsensitive(detail, $1) >= 1
GROUP BY label, detail
ORDER BY COUNT(*) DESC
LIMIT 20
, columnName, columnName)
if err := conn.Select(ctx, &results, sqlQuery, input.Prefix); err != nil
c.r.Err(err).Msg("unable to query database")
break
for _, result := range results
completions = append(completions, filterCompletion
Label: result.Label,
Detail: result.Detail,
Quoted: false,
)
In my opinion, the completion system is a major factor in making the field
editor an efficient way to select flows. While a query builder may have been
more beginner-friendly, the completion system s ease of use and functionality
make it more enjoyable to use once you become familiar.
-
Moreover, building a query builder did not seem like a fun task for me.
-
They were introduced in 2004 in Parsing Expression Grammars: A
Recognition-Based Syntactic Foundation. LR parsers were
introduced in 1965, LALR parsers in 1969, and LL parsers in the
1970s. Yacc, a popular parser generator, was written in 1975.
-
The parser returns a string. It does not generate an intermediate AST.
This makes it simpler and it currently fits our needs.
-
It could be manually translated to JavaScript with PEG.js.
@top Filter expression expression Not expression "(" expression ")" "(" expression ")" And expression "(" expression ")" Or expression comparisonExpression And expression comparisonExpression Or expression comparisonExpression comparisonExpression Column Operator Value Value String Literal ValueLParen ListOfValues ValueRParen ListOfValues ListOfValues ValueComma (String Literal) String Literal // [ ] @tokens // [ ] Column std.asciiLetter (std.asciiLetter std.digit)* Operator $[a-zA-Z!=><]+ String '"' (![\\\n"] "\\" _)* '"'? "'" (![\\\n'] "\\" _)* "'"? Literal (std.digit std.asciiLetter $[.:/])+ // [ ]
Filter(Column, Operator, Value(Literal), And, Column, Operator, Value(Literal), Or, Column, Operator, Value(Literal))
export const FilterLanguage = LRLanguage.define( parser: parser.configure( props: [ styleTags( Column: t.propertyName, String: t.string, Literal: t.literal, LineComment: t.lineComment, BlockComment: t.blockComment, Or: t.logicOperator, And: t.logicOperator, Not: t.logicOperator, Operator: t.compareOperator, "( )": t.paren, ), ], ), );
/api/v0/console/filter/validate endpoint accepts a filter and returns a JSON
structure with the errors that were found:
"message": "at line 1, position 12: string literal not terminated", "errors": [ "line": 1, "column": 12, "offset": 11, "message": "string literal not terminated", ]
Completion
The completion system takes a hybrid approach. It splits the work between the
frontend and the backend to offer useful suggestions for completing filters.
The frontend uses the parser built with Lezer to determine the context of
the completion: do we complete a column name, an operator, or a value? It also
extracts the column name if we are completing something else. It forwards the
result to the backend through the /api/v0/console/filter/complete endpoint.
Walking the syntax tree was not as easy as I thought, but unit tests helped
a lot.
The backend uses the parser generated by pigeon to complete a column name
or a comparison operator. For values, the completions are either static or
extracted from the ClickHouse database. A user can complete an AS number from
an organization name thanks to the following snippet:
results := []struct
Label string ch:"label"
Detail string ch:"detail"
columnName := "DstAS"
sqlQuery := fmt.Sprintf(
SELECT concat('AS', toString(%s)) AS label, dictGet('asns', 'name', %s) AS detail
FROM flows
WHERE TimeReceived > date_sub(minute, 1, now())
AND detail != ''
AND positionCaseInsensitive(detail, $1) >= 1
GROUP BY label, detail
ORDER BY COUNT(*) DESC
LIMIT 20
, columnName, columnName)
if err := conn.Select(ctx, &results, sqlQuery, input.Prefix); err != nil
c.r.Err(err).Msg("unable to query database")
break
for _, result := range results
completions = append(completions, filterCompletion
Label: result.Label,
Detail: result.Detail,
Quoted: false,
)
In my opinion, the completion system is a major factor in making the field
editor an efficient way to select flows. While a query builder may have been
more beginner-friendly, the completion system s ease of use and functionality
make it more enjoyable to use once you become familiar.
-
Moreover, building a query builder did not seem like a fun task for me.
-
They were introduced in 2004 in Parsing Expression Grammars: A
Recognition-Based Syntactic Foundation. LR parsers were
introduced in 1965, LALR parsers in 1969, and LL parsers in the
1970s. Yacc, a popular parser generator, was written in 1975.
-
The parser returns a string. It does not generate an intermediate AST.
This makes it simpler and it currently fits our needs.
-
It could be manually translated to JavaScript with PEG.js.
results := []struct Label string ch:"label" Detail string ch:"detail" columnName := "DstAS" sqlQuery := fmt.Sprintf( SELECT concat('AS', toString(%s)) AS label, dictGet('asns', 'name', %s) AS detail FROM flows WHERE TimeReceived > date_sub(minute, 1, now()) AND detail != '' AND positionCaseInsensitive(detail, $1) >= 1 GROUP BY label, detail ORDER BY COUNT(*) DESC LIMIT 20 , columnName, columnName) if err := conn.Select(ctx, &results, sqlQuery, input.Prefix); err != nil c.r.Err(err).Msg("unable to query database") break for _, result := range results completions = append(completions, filterCompletion Label: result.Label, Detail: result.Detail, Quoted: false, )
- Moreover, building a query builder did not seem like a fun task for me.
- They were introduced in 2004 in Parsing Expression Grammars: A Recognition-Based Syntactic Foundation. LR parsers were introduced in 1965, LALR parsers in 1969, and LL parsers in the 1970s. Yacc, a popular parser generator, was written in 1975.
- The parser returns a string. It does not generate an intermediate AST. This makes it simpler and it currently fits our needs.
- It could be manually translated to JavaScript with PEG.js.
And after baking and trying them I liked them, but they had not been planned in any way, and they were a bit too small for the board, so the next time I was using cernit I tried to make a new set.
And while I was doing that I tried a new shape for the dice, as coins marked with a dot in the middle of one of the sides, because I don t really like tetrahedral dice.
And now, I realized this wasn t going to be my last set, and urgently felt the need for some container to keep them in and avoid missing pieces.
(Yes, in the picture above one piece was already missing. While taking it I didn t realize it, and neither I did when picking up everything to put it away, getting the missing piece and storing it safely together with the rest of the set. It must have been hiding in plain sight nearby, but I will never know where.)
Anyway, back to Inkscape, and to a board printed on scrap paper that I tried to fold up until I came up with a layout that folded up in a small drawer, and then I added a case to wrap around it to keep it closed.
I played around with the case until it was big enough to actually slide around the folded board, and this is the result, ready to be printed out on A4 paper, cut, folded and glued. (This takes most of the sheet, and I m not sure that the case would still fit around the board/drawer if printed with scaling, so if you want to print it on Letter paper I d recommend to move the pieces around.)
I still used stone effect cernit, but this time in a red/grey scheme that knew I would have liked more, and while I was doing it I tried a few improvements on the randomization devices.
The tetrahedral dice are still the same: they work, it s what they use in the replica sets, so I keep making them even if they re not my first choice.
I ve changed the coins to make them almost square for two reasons, however: one is that the round one tended to roll away into inconvenient places when throwing them with emphasis, and the other one is to make it easier to recognise them from the tokens with no need to flip each one around before starting the game.
The lozenges were a bit of a failure, instead. They work fine when thrown, but I don t think that there is a self-evident way to decide which side should be counted, and the only intuitive way I can think of (count the ones in the player s colour) would be unbalanced.
Speaking of balance issues: of course the hand-modelled dice and coins aren t perfectly balanced but:

It's been a year since I started exploring 
This is the second part of how I build a read-only root setup for my router. You might want to read
Very few highly-anticipated movies appear in January and February, as the bigger releases are timed so they can be considered for the 










Prologue
For over a year now, Fre(i)e Software GmbH (my company) is involved in Ubuntu Touch development. The development effort currently is handled by a mix of paid and voluntary developers/contributors under the umbrella of the UBports Foundation. We are approaching the official first release of Ubuntu Touch 20.04 with rapid pace.
And, if you are a non-Englisch native speaker, we'd like to ask you for help... Read below.
light+love


