[Why]
Only one key and one value can be used as search criteria.
However, in some scenarios,one-to-many query is required.
Such like:
{"job_id": ["1", "2", "3"]}
{"level": ["error", "warning"]}
Signed-off-by: Wu Zhende <wuzhende666(a)163.com>
---
src/monitoring/filter.cr | 16 ++++++++++++++--
src/monitoring/monitoring.cr | 3 ++-
2 files changed, 16 insertions(+), 3 deletions(-)
diff --git a/src/monitoring/filter.cr b/src/monitoring/filter.cr
index 5cd6532..bc6f901 100644
--- a/src/monitoring/filter.cr
+++ b/src/monitoring/filter.cr
@@ -12,10 +12,21 @@ class Filter
end
def add_filter_rule(query : JSON::Any, socket : HTTP::WebSocket)
+ query = convert_hash_value_to_array(query)
+
@hash[query] = Array(HTTP::WebSocket).new unless @hash[query]?
@hash[query] << socket
end
+ private def convert_hash_value_to_array(query)
+ new_query = Hash(String, Array(JSON::Any)).new
+
+ query.as_h.each do |key, value|
+ new_query[key] = value.as_a? || [value]
+ end
+ JSON.parse(new_query.to_json)
+ end
+
def remove_filter_rule(query : JSON::Any, socket : HTTP::WebSocket)
return unless @hash[query]?
@@ -45,10 +56,11 @@ class Filter
def match_query(query : Hash(String, JSON::Any), msg : Hash(String, JSON::Any))
query.each do |key, value|
- if value == nil
+ value = value.as_a
+ if value.includes?(nil)
return false unless msg.has_key?(key)
else
- return false unless value == msg[key]?
+ return false unless value.includes?(msg[key]?)
end
end
return true
diff --git a/src/monitoring/monitoring.cr b/src/monitoring/monitoring.cr
index e665d5f..dff1902 100644
--- a/src/monitoring/monitoring.cr
+++ b/src/monitoring/monitoring.cr
@@ -15,7 +15,8 @@ module Monitoring
query = JSON::Any.new("")
socket.on_message do |msg|
- # query like {"job_id": 1}
+ # query like {"job_id": "1"}
+ # also can be {"job_id": ["1", "2"]}
query = JSON.parse(msg)
if query.as_h?
filter.add_filter_rule(query, socket)
--
2.23.0