quill-sql 0.1.8 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/quill-sql.rb CHANGED
@@ -1,21 +1,26 @@
1
1
  # Ruby 2.3 Compatible Implementation
2
2
  require 'json'
3
3
  require 'net/http'
4
+ require_relative 'client_token'
4
5
  require 'uri'
5
- require 'dotenv'
6
+ require 'digest'
6
7
  require_relative './db/cached_connection'
7
8
  require_relative './db/db_helper'
8
9
  require_relative 'utils/tenants'
9
10
  require_relative 'models/filters'
10
11
  require_relative 'utils/schema'
11
12
  require_relative 'utils/run_query_processes'
12
-
13
- Dotenv.load(File.expand_path('../.env', __dir__))
13
+ require_relative 'utils/pivot_template'
14
14
 
15
15
  module DatabaseType
16
16
  POSTGRESQL = 'postgresql'.freeze
17
+ REDSHIFT = 'redshift'.freeze
17
18
  CLICKHOUSE = 'clickhouse'.freeze
18
19
  DATABRICKS = 'databricks'.freeze
20
+ MYSQL = 'mysql'.freeze
21
+ MSSQL = 'mssql'.freeze
22
+ SNOWFLAKE = 'snowflake'.freeze
23
+ BIGQUERY = 'bigquery'.freeze
19
24
 
20
25
  def self.valid?(type)
21
26
  constants.map { |c| const_get(c) }.include?(type)
@@ -25,23 +30,87 @@ end
25
30
  SINGLE_TENANT = "QUILL_SINGLE_TENANT".freeze
26
31
  ALL_TENANTS = "QUILL_ALL_TENANTS".freeze
27
32
 
28
- HOST = (ENV['ENV'] == 'development' ?
33
+ HOST = ((ENV['QUILL_ENV'] == 'development' || ENV['ENV'] == 'development') ?
29
34
  'http://localhost:8080' :
30
- 'https://quill-344421.uc.r.appspot.com').freeze
31
-
32
- FLAG_TASKS = Set.new(['dashboard', 'report', 'item', 'report-info', 'filter-options']).freeze
33
-
34
- class QuillAPIError < StandardError; end
35
+ 'https://api.quill.co').freeze
36
+
37
+ FLAG_TASKS = Set.new(['dashboard', 'report', 'report-info', 'filter-options']).freeze
38
+
39
+ # Metadata-server tasks whose responses may be served from Redis (quill:post:<task>:<sha256(payload)>).
40
+ # These are pure data reads; everything else -- writes, listings (dashboard, ...),
41
+ # sessions and AI -- always hits the network. Entries are tagged with the report / dashboard they were
42
+ # resolved for (see Quill.post_cache_tags) so a write to that report or dashboard drops them (see
43
+ # WRITE_TASKS); environment holds every dashboard's sections, so it is tagged by client and any write
44
+ # drops it. The SQL results underneath stay in the SQL-text-keyed cache and are reused while the
45
+ # SQL is unchanged.
46
+ CACHEABLE_TASKS = Set.new([
47
+ 'environment',
48
+ 'report',
49
+ 'pivot-template',
50
+ 'filter-options',
51
+ 'query',
52
+ 'query-view',
53
+ 'test-view',
54
+ 'report-builder-query',
55
+ 'report-builder-unique-values',
56
+ 'report-builder-counts',
57
+ 'report-builder-date-ranges',
58
+ 'report-builder-state',
59
+ 'report-name',
60
+ 'sqlify',
61
+ 'astify',
62
+ 'referenced-tables-map',
63
+ ]).freeze
64
+
65
+ # Tasks backed by an LLM. The server answers only once the model produces
66
+ # output, so these are never timed. Same set as Node and PHP.
67
+ AI_TASKS = %w[
68
+ ai
69
+ chat
70
+ agent
71
+ agent-chat
72
+ ai-from-client-schema
73
+ sqlviewai
74
+ pivotai
75
+ sql-generator
76
+ magic
77
+ magic-edit
78
+ ].freeze
79
+
80
+ # Metadata-server tasks that modify a saved report or dashboard. After one of these is posted, every
81
+ # cached quill:post:* entry tagged with the same report / dashboard (post_cache_tags of the write payload)
82
+ # is deleted, so the next read refetches the updated definition instead of serving the pre-save copy.
83
+ WRITE_TASKS = Set.new([
84
+ 'create',
85
+ 'create-report',
86
+ 'create-alert',
87
+ 'delete',
88
+ 'edit-dashboard',
89
+ 'set-section-order',
90
+ 'delete-dashboard',
91
+ 'add-from-template',
92
+ ]).freeze
35
93
 
36
94
  class Quill
37
95
  attr_reader :target_connection, :base_url, :config
38
96
 
97
+ # `task` is interpolated into the request path and comes from the browser;
98
+ # restrict it to one path segment so the private key cannot be sent elsewhere.
99
+ TASK_NAME = /\A[a-z0-9-]+\z/
100
+ def self.valid_task_name?(task)
101
+ task.is_a?(String) && TASK_NAME.match?(task)
102
+ end
103
+
39
104
  def initialize(options = {})
40
105
  validate_options(options)
41
106
  @base_url = options[:metadata_server_url] || HOST
107
+ @private_key = options[:private_key]
42
108
  @config = { headers: { 'Authorization' => "Bearer #{options[:private_key]}" } }
43
109
 
44
110
  credentials = options[:database_config]
111
+ # The process connection. A client created during onboarding does not have
112
+ # this stored yet, and BigQuery schema lookup needs it.
113
+ @database_connection_string = options[:database_connection_string]
45
114
  if options[:database_connection_string]
46
115
  credentials = DatabaseHelper.get_database_credentials(
47
116
  options[:database_type],
@@ -57,65 +126,79 @@ class Quill
57
126
  end
58
127
 
59
128
  def query(params = {})
60
- validate_query_params(params)
61
-
62
- tenants = params[:tenants]
63
- flags = params[:flags]
64
- metadata = params[:metadata]
65
- metadata = metadata.transform_keys(&:to_sym)
66
- filters = params[:filters]
67
-
68
- # TODO: Add support for multiple tenants
69
- if tenants&.any?
129
+ begin
130
+ validate_query_params(params)
131
+
132
+ tenants = params[:tenants]
133
+ flags = params[:flags]
134
+ metadata = params[:metadata].transform_keys(&:to_sym)
135
+ filters = params[:filters]
136
+ # Fail closed: only a strict `true` from the caller grants admin. Anything
137
+ # in `metadata` (browser-controlled) is overridden in the payloads below.
138
+ admin_enabled = params[:adminEnabled] == true
139
+
140
+ # TODO: Add support for multiple tenants
141
+ raise 'You may not pass an empty tenants array.' if tenants.empty?
70
142
  @target_connection.tenant_ids = TenantUtils.extract_tenant_ids(tenants)
71
- end
72
-
73
- response_metadata = {}
74
-
75
- unless metadata[:task]
76
- return { error: "Missing task.", status: "error", data: {} }
77
- end
78
-
79
- tenant_flags = nil
143
+ raise 'You may not pass an empty flags array.' if flags && flags.empty?
144
+ raise 'Missing task.' unless metadata[:task]
145
+ raise 'Invalid task.' unless Quill.valid_task_name?(metadata[:task])
146
+ raise 'preQueries requires adminEnabled.' if metadata[:preQueries]&.any? && !admin_enabled
147
+
148
+ response_metadata = {}
149
+ tenant_flags = nil
150
+ overwrite_cache = metadata[:overwriteCache] ? true : false
151
+
152
+ # Pivot queries: fetch the template, run the distinct-values query, hydrate, run.
153
+ if metadata[:task] == 'pivot-template'
154
+ return query_pivot_template(metadata, tenants, flags, filters, admin_enabled)
155
+ end
80
156
 
81
- begin
82
157
  # If the task requires flags to be synthesized from tenants
83
158
  if FLAG_TASKS.include?(metadata[:task]) &&
84
159
  tenants&.first != ALL_TENANTS &&
85
160
  tenants&.first != SINGLE_TENANT
86
161
 
87
- response = post_quill('tenant-mapped-flags', {
162
+ flags_payload = {
88
163
  reportId: metadata[:reportId] || metadata[:dashboardItemId],
89
164
  clientId: metadata[:clientId],
90
165
  dashboardName: metadata[:name],
91
166
  tenants: tenants.map { |tenant| TenantUtils.deep_camelize_keys(tenant) },
92
167
  flags: flags&.map { |flag| TenantUtils.deep_camelize_keys(flag) }
93
- })
94
-
95
- return {
96
- status: "error",
97
- error: response[:error],
98
- data: response[:metadata] || {}
99
- } if response[:error]
100
-
101
- flag_query_results = run_queries(response[:queries], @target_connection.database_type)
102
- tenant_flags = response[:metadata][:queryOrder].map.with_index do |tenant_field, index|
103
- {
104
- tenant_field: tenant_field,
105
- flags: Set.new(
106
- flag_query_results[:queryResults][index][:rows].map do |row|
107
- row['quill_flag']
108
- end
109
- ).to_a
110
- }
168
+ }
169
+ flags_payload[:adminEnabled] = admin_enabled
170
+ tenant_flags_cache_key = tenant_mapped_flags_cache_key(
171
+ metadata[:clientId], tenants, metadata[:reportId] || ''
172
+ )
173
+ tenant_flags = tenant_mapped_flags_from_cache(tenant_flags_cache_key, overwrite_cache)
174
+
175
+ if tenant_flags.nil?
176
+ response = post_quill('tenant-mapped-flags', flags_payload, false)
177
+
178
+ return {
179
+ status: "error",
180
+ error: response[:error],
181
+ data: response[:metadata] || {}
182
+ } if response[:error]
183
+
184
+ flag_query_results = run_queries(response[:queries], @target_connection.database_type, nil, nil, overwrite_cache)
185
+ tenant_flags = response[:metadata][:queryOrder].map.with_index do |tenant_field, index|
186
+ {
187
+ tenant_field: tenant_field,
188
+ flags: Set.new(
189
+ flag_query_results[:queryResults][index][:rows].map do |row|
190
+ row['quill_flag']
191
+ end
192
+ ).to_a
193
+ }
194
+ end
195
+ set_tenant_mapped_flags_cache(tenant_flags_cache_key, tenant_flags)
111
196
  end
112
197
  elsif tenants&.first == SINGLE_TENANT && flags
113
- if flags.length && flags[0].is_a?(Hash)
198
+ if flags.length > 0 && flags[0].is_a?(Hash)
114
199
  tenant_flags = [{ tenant_field: SINGLE_TENANT, flags: flags }]
115
200
  else
116
- tenant_flags = flags.map do |flag|
117
- { tenant_field: SINGLE_TENANT, flags: flag }
118
- end
201
+ tenant_flags = flags
119
202
  end
120
203
  end
121
204
 
@@ -124,30 +207,50 @@ class Quill
124
207
  metadata[:preQueries],
125
208
  @target_connection.database_type,
126
209
  metadata[:databaseType],
127
- metadata[:runQueryConfig]
210
+ metadata[:runQueryConfig],
211
+ overwrite_cache
128
212
  )
129
213
  else
130
214
  {}
131
215
  end
132
216
 
133
- if metadata.dig(:runQueryConfig, "overridePost")
217
+ if metadata.dig(:runQueryConfig, :overridePost) || metadata.dig(:runQueryConfig, "overridePost")
134
218
  return {
135
- data: { queryResults: pre_query_results },
219
+ data: pre_query_results,
136
220
  status: "success"
137
221
  }
138
222
  end
139
223
 
140
- sdk_filters = filters&.map { |filter| FilterUtils.convert_custom_filter(filter) }
224
+ sdk_filters = filters&.map { |filter| TenantUtils.deep_camelize_keys(FilterUtils.convert_custom_filter(filter)) }
141
225
 
142
226
  payload = {
143
227
  **metadata,
144
- **pre_query_results,
145
228
  tenants: tenants.map { |tenant| TenantUtils.deep_camelize_keys(tenant) },
146
229
  flags: tenant_flags&.map { |flag| TenantUtils.deep_camelize_keys(flag) },
147
230
  viewQuery: metadata[:preQueries]&.first
148
231
  }
149
232
  payload[:sdkFilters] = sdk_filters if sdk_filters # So it's undefined instead of nil
150
-
233
+ run_query_config = metadata[:runQueryConfig]
234
+ if run_query_config && (run_query_config[:getColumns] || run_query_config['getColumns'])
235
+ payload[:preQueryResultsColumns] = pre_query_results[:columns]
236
+ end
237
+ payload[:adminEnabled] = admin_enabled
238
+ if metadata[:task] == "create-client" && payload[:databaseType].to_s.strip.empty?
239
+ payload[:databaseType] = @target_connection.database_type
240
+ end
241
+ # Schema SQL runs on this process's connection. Onboarding defaults the
242
+ # form to PostgreSQL, which would skip the lookup on every other engine.
243
+ database_type = metadata[:databaseType]
244
+ if ["get-schema-names", "get-tables-by-schemas", "get-schema-table-columns"].include?(metadata[:task])
245
+ database_type = @target_connection.database_type
246
+ payload[:databaseType] = database_type
247
+ end
248
+ if metadata[:task] == "get-schema-names" && @database_connection_string && !@database_connection_string.empty?
249
+ payload[:databaseConnectionString] = @database_connection_string
250
+ end
251
+ apply_engine_database_type(payload, @target_connection.database_type)
252
+ database_type = payload[:databaseType] if payload[:databaseType]
253
+
151
254
  response = post_quill(metadata[:task], payload)
152
255
 
153
256
  return {
@@ -161,8 +264,9 @@ class Quill
161
264
  results = run_queries(
162
265
  response[:queries],
163
266
  @target_connection.database_type,
164
- metadata[:database_type],
165
- response_metadata.dig(:runQueryConfig)
267
+ database_type,
268
+ response_metadata.dig(:runQueryConfig),
269
+ overwrite_cache
166
270
  )
167
271
  if results[:mappedArray] && response_metadata.dig(:runQueryConfig, :arrayToMap)
168
272
  array_to_map = response_metadata.dig(:runQueryConfig, :arrayToMap)
@@ -181,23 +285,23 @@ class Quill
181
285
  response_metadata[:fields] = query_results[:fields] if query_results[:fields]
182
286
  end
183
287
 
184
- {
185
- data: response_metadata,
186
- queries: results,
187
- status: "success"
188
- }
288
+ query_result(response_metadata, results)
189
289
  rescue StandardError => e
190
- if metadata[:task] == "update-view"
191
- post_quill("set-broken-view", {
192
- table: metadata[:name],
193
- clientId: metadata[:clientId],
194
- error: e.message
195
- })
290
+ failure = ReportError.report_request('sdk', 'query', e)
291
+ # Only an answer from the database says the view's SQL is broken.
292
+ if metadata&.dig(:task) == "update-view" && ReportError.origin_of(failure.origin) != 'sdk' && !failure.unreachable
293
+ posted = begin
294
+ post_sdk("set-broken-view", { table: metadata[:name], clientId: metadata[:clientId],
295
+ error: failure.public_message, adminEnabled: admin_enabled }, 30)
296
+ rescue StandardError => post_error
297
+ post_error
298
+ end
299
+ ReportError.report_background('metadata', 'set-broken-view', posted) unless posted.is_a?(Net::HTTPSuccess)
196
300
  end
197
301
 
198
302
  {
199
303
  status: "error",
200
- error: e.message,
304
+ error: failure.public_message,
201
305
  data: response_metadata || {}
202
306
  }
203
307
  end
@@ -205,6 +309,74 @@ class Quill
205
309
 
206
310
  private
207
311
 
312
+ # Handles the "pivot-template" task (mirrors node-sdk):
313
+ # 1. POST /v1/sdk/pivot-template to get the template, config and helper queries
314
+ # 2. run distinctValuesQuery against the customer database
315
+ # 3. hydrate the template (and rowCountQuery) with the distinct values
316
+ # 4. run the hydrated queries and attach rows/fields to the response metadata
317
+ def query_pivot_template(metadata, tenants, flags, filters, admin_enabled)
318
+ payload = {
319
+ **metadata,
320
+ tenants: tenants.map { |tenant| TenantUtils.deep_camelize_keys(tenant) },
321
+ flags: flags&.map { |flag| TenantUtils.deep_camelize_keys(flag) }
322
+ }
323
+ payload[:sdkFilters] = filters.map { |filter| FilterUtils.convert_custom_filter(filter) } if filters
324
+ payload[:adminEnabled] = admin_enabled
325
+
326
+ response = post_quill('pivot-template', payload)
327
+ return { status: "error", error: response[:error], data: response[:metadata] || {} } if response[:error]
328
+
329
+ response_metadata = response[:metadata] || {}
330
+ template = response_metadata[:template].to_s
331
+ config = response_metadata[:config] || {}
332
+ distinct_values_query = response_metadata[:distinctValuesQuery]
333
+ row_count_query = response_metadata[:rowCountQuery]
334
+
335
+ # Step 2: distinct values for the pivot columns
336
+ distinct_values = []
337
+ if distinct_values_query
338
+ distinct_results = run_queries([distinct_values_query], @target_connection.database_type)
339
+ distinct_values = PivotTemplate.parse_distinct_values(
340
+ distinct_results[:queryResults]&.first,
341
+ config[:databaseType] || @target_connection.database_type
342
+ )
343
+ end
344
+
345
+ # Step 3: hydrate
346
+ queries_to_run = [PivotTemplate.hydrate_pivot_template(template, distinct_values, config)]
347
+ queries_to_run << PivotTemplate.hydrate_pivot_template(row_count_query, distinct_values, config) if row_count_query
348
+
349
+ # Step 4: run the pivot query (and optional row count query)
350
+ results = run_queries(
351
+ queries_to_run,
352
+ @target_connection.database_type,
353
+ metadata[:databaseType],
354
+ response_metadata[:runQueryConfig]
355
+ )
356
+
357
+ if results[:queryResults]&.any?
358
+ query_results = results[:queryResults].first
359
+ response_metadata[:rows] = query_results[:rows] if query_results[:rows]
360
+ response_metadata[:fields] = query_results[:fields] if query_results[:fields]
361
+ end
362
+
363
+ # Remove internal SDK fields before returning to the frontend
364
+ response_metadata.delete(:template)
365
+ response_metadata.delete(:distinctValuesQuery)
366
+ response_metadata.delete(:rowCountQuery)
367
+
368
+ query_result(response_metadata, results)
369
+ end
370
+
371
+ # An engine mismatch ran no SQL, so the call failed.
372
+ def query_result(response_metadata, queries)
373
+ result = { data: response_metadata, queries: queries, status: "success" }
374
+ return result unless queries.is_a?(Hash) && queries[:dbMismatched]
375
+
376
+ mismatch = "Query database type does not match the connected database (connected: #{queries[:backendDatabaseType]})."
377
+ result.merge(status: "error", error: ReportError.report_request('sdk', 'query', mismatch).public_message)
378
+ end
379
+
208
380
  def validate_options(options)
209
381
  if !options[:private_key]
210
382
  raise ArgumentError, "Private key is required"
@@ -229,10 +401,46 @@ class Quill
229
401
  end
230
402
  end
231
403
 
232
- def run_queries(queries, pk_database_type, database_type = nil, run_query_config = nil)
404
+ def default_database_type?(database_type)
405
+ value = database_type.to_s.strip.downcase
406
+ value.empty? || %w[postgres postgresql].include?(value)
407
+ end
408
+
409
+ # "Postgres" and "PostgreSQL" name one engine. A client record stores either.
410
+ def engine_of(database_type)
411
+ value = database_type.to_s.downcase
412
+ value == 'postgres' ? 'postgresql' : value
413
+ end
414
+
415
+ def apply_engine_database_type(payload, engine)
416
+ return if default_database_type?(engine)
417
+
418
+ payload[:databaseType] = engine if default_database_type?(payload[:databaseType])
419
+ client = payload[:client]
420
+ return unless client.is_a?(Hash) && default_database_type?(client[:databaseType] || client['databaseType'])
421
+
422
+ client = client.dup
423
+ client[:databaseType] = engine
424
+ client.delete('databaseType')
425
+ payload[:client] = client
426
+ end
427
+
428
+ def apply_limit(query, limit)
429
+ # Mirrors node's applyLimit (always appends; strips the first ';'; MSSQL rewrites SELECT TOP).
430
+ if @target_connection.database_type.to_s.downcase.include?('mssql')
431
+ if query.match?(/SELECT TOP \d+/i)
432
+ return query
433
+ end
434
+ return query.sub(/select/i, "SELECT TOP #{limit}")
435
+ end
436
+
437
+ "#{query.sub(/;/, '')} limit #{limit}"
438
+ end
439
+
440
+ def run_queries(queries, pk_database_type, database_type = nil, run_query_config = nil, overwrite_cache = false)
233
441
  return { queryResults: [] } unless queries
234
442
 
235
- if database_type && database_type.downcase != pk_database_type.downcase
443
+ if database_type && engine_of(database_type) != engine_of(pk_database_type)
236
444
  return {
237
445
  dbMismatched: true,
238
446
  backendDatabaseType: pk_database_type,
@@ -245,12 +453,12 @@ class Quill
245
453
  run_query_config = run_query_config.transform_keys(&:to_sym) if run_query_config
246
454
 
247
455
  if run_query_config&.dig(:arrayToMap)
248
- mapped_array = RunQueryProcesses.map_queries(queries, @target_connection)
456
+ mapped_array = RunQueryProcesses.map_queries(queries, @target_connection, overwrite_cache)
249
457
  results[:queryResults] = []
250
458
  results[:mappedArray] = mapped_array
251
459
 
252
460
  elsif run_query_config&.dig(:getColumns)
253
- query_result = @target_connection.query("#{queries[0].gsub(/;/, '')} limit 1000")
461
+ query_result = @target_connection.query(apply_limit(queries[0], 1000), overwrite_cache)
254
462
  columns = query_result[:fields].map do |field|
255
463
  {
256
464
  fieldType: Schema.convert_type_to_postgres(field[:dataTypeID]),
@@ -266,9 +474,9 @@ class Quill
266
474
  if table[:viewQuery].nil? || (!table[:isSelectStar] && !table[:customFieldInfo])
267
475
  table
268
476
  else
269
- limit = run_query_config[:limitBy] ? " limit #{run_query_config[:limitBy]}" : ""
477
+ limited_view_query = run_query_config[:limitBy] ? apply_limit(table[:viewQuery], run_query_config[:limitBy]) : table[:viewQuery]
270
478
  begin
271
- query_result = @target_connection.query("#{table[:viewQuery].gsub(/;/, '')} #{limit}")
479
+ query_result = @target_connection.query(limited_view_query, overwrite_cache)
272
480
  columns = query_result[:fields].map do |field|
273
481
  {
274
482
  fieldType: Schema.convert_type_to_postgres(field[:dataTypeID]),
@@ -280,7 +488,7 @@ class Quill
280
488
  end
281
489
  table.merge(columns: columns, rows: query_result[:rows])
282
490
  rescue StandardError => e
283
- table.merge(error: "Error fetching columns: #{e.message}")
491
+ table.merge(error: ReportError.report_request('sdk', 'query', e).public_message)
284
492
  end
285
493
  end
286
494
  end
@@ -299,16 +507,30 @@ class Quill
299
507
  tables_info = DatabaseHelper.get_tables_by_schema_by_database(@target_connection.database_type, @target_connection.pool, schema_names)
300
508
  schema_info = DatabaseHelper.get_column_info_by_schema_by_database(@target_connection.database_type, @target_connection.pool, run_query_config[:schema], tables_info)
301
509
  return schema_info
302
-
510
+ elsif run_query_config&.dig(:runIndividualQueries)
511
+ # so that one query doesn't fail the whole thing
512
+ # the only reason this isn't the default behavior is for backwards compatibility
513
+ query_results = queries.map do |query|
514
+ begin
515
+ run_query = query
516
+ if run_query_config[:limitBy]
517
+ run_query = apply_limit(query, run_query_config[:limitBy])
518
+ end
519
+ @target_connection.query(run_query, overwrite_cache)
520
+ rescue StandardError => e
521
+ { query: query, error: ReportError.report_request('sdk', 'query', e).public_message }
522
+ end
523
+ end
524
+ results[:queryResults] = query_results
303
525
  else
304
526
  modified_queries = queries
305
527
  if run_query_config&.dig(:limitThousand)
306
- modified_queries = queries.map { |q| "#{q.gsub(/;/, '')} limit 1000;" }
528
+ modified_queries = queries.map { |q| apply_limit(q, 1000) }
307
529
  elsif run_query_config&.dig(:limitBy)
308
- modified_queries = queries.map { |q| "#{q.gsub(/;/, '')} limit #{run_query_config[:limitBy]};" }
530
+ modified_queries = queries.map { |q| apply_limit(q, run_query_config[:limitBy]) }
309
531
  end
310
532
 
311
- query_results = modified_queries.map { |query| @target_connection.query(query) }
533
+ query_results = modified_queries.map { |query| @target_connection.query(query, overwrite_cache) }
312
534
  results[:queryResults] = query_results
313
535
 
314
536
  if run_query_config&.dig(:fieldsToRemove)
@@ -318,7 +540,7 @@ class Quill
318
540
  end
319
541
 
320
542
  if run_query_config&.dig(:convertDatatypes)
321
- results = query_results.map do |result|
543
+ results[:queryResults] = results[:queryResults].map do |result|
322
544
  {
323
545
  fields: result[:fields].map do |field|
324
546
  field.merge(
@@ -338,29 +560,175 @@ class Quill
338
560
  results
339
561
  end
340
562
 
341
- def post_quill(path, payload)
342
- uri = URI("#{@base_url}/sdk/#{path}")
563
+ # Mirrors node: tenant-mapped-flags:<clientId>:<reportId>:<normalized tenants JSON>.
564
+ # Returns nil when the tenants are not object-shaped (nothing to cache).
565
+ def tenant_mapped_flags_cache_key(client_id, tenants, report_id)
566
+ return nil if client_id.nil? || client_id.to_s.empty? || !tenants.is_a?(Array) || tenants.empty?
567
+ return nil unless tenants.first.is_a?(Hash)
568
+
569
+ normalized = tenants.map do |tenant|
570
+ tenant = TenantUtils.deep_camelize_keys(tenant)
571
+ tenant = tenant.transform_keys(&:to_s)
572
+ {
573
+ 'tenantField' => tenant['tenantField'],
574
+ 'tenantIds' => (tenant['tenantIds'] || []).sort_by(&:to_s)
575
+ }
576
+ end
577
+ normalized = normalized.sort_by { |tenant| tenant['tenantField'].to_s }
578
+ "tenant-mapped-flags:#{client_id}:#{report_id}:#{JSON.generate(normalized)}"
579
+ end
580
+
581
+ def tenant_mapped_flags_from_cache(cache_key, overwrite_cache)
582
+ return nil if overwrite_cache || cache_key.nil? || @target_connection.cache.nil?
583
+
584
+ cached = @target_connection.get_cached_value(cache_key)
585
+ return nil if cached.nil?
586
+
587
+ parsed = JSON.parse(cached)
588
+ valid = parsed.is_a?(Array) && parsed.all? do |item|
589
+ item.is_a?(Hash) && item['tenantField'].is_a?(String) && item['flags'].is_a?(Array)
590
+ end
591
+ unless valid
592
+ @target_connection.delete_cached_value(cache_key)
593
+ return nil
594
+ end
595
+ parsed.map { |item| { tenant_field: item['tenantField'], flags: item['flags'] } }
596
+ rescue JSON::ParserError
597
+ @target_connection.delete_cached_value(cache_key)
598
+ nil
599
+ end
600
+
601
+ def set_tenant_mapped_flags_cache(cache_key, tenant_flags)
602
+ return if cache_key.nil? || @target_connection.cache.nil?
603
+
604
+ payload = tenant_flags.map { |item| { tenantField: item[:tenant_field], flags: item[:flags] } }
605
+ @target_connection.set_cached_value(cache_key, JSON.generate(payload))
606
+ end
607
+
608
+ # Posts to the metadata server. When use_cache is true and a cache is configured, the response is
609
+ # cached under quill:post:<path>:<sha256(payload sans overwriteCache and draftSessionId)>.
610
+ # Tags identifying which saved report(s) / dashboard(s) a metadata-server payload refers to, scoped
611
+ # to the client (the hosted engine shares one Redis across every client, and dashboard names are only
612
+ # unique per client): <clientId>:report:<id> for reportId / dashboardItemId / id, and
613
+ # <clientId>:dashboard:<name> for dashboardName / newDashboardName (or `name`, which is the dashboard
614
+ # name on dashboard tasks, when no dashboardName is present), plus <clientId>:environment on the
615
+ # environment read and on every write. Reads are indexed under these tags; writes invalidate them.
616
+ def self.post_cache_tags(payload, path = nil)
617
+ return [] unless payload.is_a?(Hash)
618
+
619
+ fetch = ->(field) { payload[field.to_sym] || payload[field] }
620
+ client_id = fetch.call('clientId')
621
+ client_id = '' unless client_id.is_a?(String)
622
+ tags = []
623
+ tags << "#{client_id}:environment" if path == 'environment' || WRITE_TASKS.include?(path)
624
+ dashboard_name = fetch.call('dashboardName')
625
+ dashboard_fields = %w[dashboardName newDashboardName]
626
+ dashboard_fields << 'name' unless dashboard_name.is_a?(String) && !dashboard_name.empty?
627
+
628
+ { 'report' => %w[reportId dashboardItemId id], 'dashboard' => dashboard_fields }.each do |kind, fields|
629
+ fields.each do |field|
630
+ value = fetch.call(field)
631
+ tags << "#{client_id}:#{kind}:#{value}" if value.is_a?(String) && !value.empty?
632
+ end
633
+ end
634
+ tags.uniq
635
+ end
636
+
637
+ def self.payload_string(payload, key)
638
+ return nil unless payload.is_a?(Hash)
639
+ value = payload[key.to_sym]
640
+ value = payload[key] if value.nil?
641
+ value.is_a?(String) && !value.empty? ? value : nil
642
+ end
643
+
644
+ # Posts /v1/sdk/record-usage without waiting. An environment load counts as a
645
+ # dashboard view, including when the response is served from cache.
646
+ def record_usage(path, payload)
647
+ client_id = Quill.payload_string(payload, 'clientId')
648
+ return if client_id.nil?
649
+ body = { clientId: client_id, scope: 'dashboard' }
650
+ if path == 'report' || path == 'pivot-template'
651
+ report_id = Quill.payload_string(payload, 'reportId') || Quill.payload_string(payload, 'dashboardItemId')
652
+ return if report_id.nil?
653
+ body[:scope] = 'report'
654
+ body[:reportId] = report_id
655
+ body[:requestType] = path
656
+ elsif path != 'environment'
657
+ return
658
+ end
659
+ Thread.new do
660
+ begin
661
+ post_sdk('record-usage', body, 2)
662
+ rescue StandardError
663
+ nil
664
+ end
665
+ end
666
+ end
667
+
668
+ def post_quill(path, payload, use_cache = true)
669
+ raise ReportError.report_request('sdk', 'query', 'Invalid task.') unless Quill.valid_task_name?(path)
670
+ record_usage(path, payload)
671
+ has_cache = !@target_connection.cache.nil?
672
+ can_use_cache = use_cache && has_cache && CACHEABLE_TASKS.include?(path)
673
+ is_write = has_cache && WRITE_TASKS.include?(path)
674
+ tags = can_use_cache || is_write ? Quill.post_cache_tags(payload, path) : []
675
+ cache_key = nil
676
+ if can_use_cache
677
+ payload_hash = payload.is_a?(Hash) ? payload : {}
678
+ # A new draftSessionId arrives on every mount and no response depends on it.
679
+ key_payload = payload_hash.reject { |k, _| %w[overwriteCache draftSessionId].include?(k.to_s) }
680
+ cache_key = "quill:post:#{path}:#{Digest::SHA256.hexdigest(key_payload.to_json)}"
681
+ overwrite = payload_hash[:overwriteCache] || payload_hash['overwriteCache']
682
+ unless overwrite
683
+ cached = @target_connection.get_cached_value(cache_key)
684
+ if cached
685
+ begin
686
+ return JSON.parse(cached, symbolize_names: true)
687
+ rescue JSON::ParserError
688
+ @target_connection.delete_cached_value(cache_key)
689
+ end
690
+ end
691
+ end
692
+ end
693
+
694
+ response = post_sdk(path, payload, AI_TASKS.include?(path) ? nil : 120)
695
+ raise ReportError.report_request('metadata', path, response) unless response.is_a?(Net::HTTPSuccess)
696
+
697
+ parsed = JSON.parse(response.body, symbolize_names: true)
698
+ # The write reached the server: drop every cached read of the report / dashboard it touched so
699
+ # the next fetch sees the saved definition.
700
+ @target_connection.invalidate_cached_tags(tags) if is_write
701
+ if parsed[:error]
702
+ # The request failed: it is logged, and `error` is always a string.
703
+ parsed[:error] = ReportError.report_request('metadata', path, response).public_message
704
+ elsif can_use_cache && cache_key
705
+ @target_connection.set_cached_value(cache_key, response.body)
706
+ @target_connection.tag_cached_value(cache_key, tags)
707
+ end
708
+ parsed
709
+ rescue StandardError => e
710
+ raise ReportError.report_request('metadata', path, e)
711
+ end
712
+
713
+ # The bare POST to the metadata server. It raises the socket's own errors and returns any response.
714
+ # timeout is seconds for both connect and the wait for a response. Usage recording passes 2.
715
+ def post_sdk(path, payload, timeout = 120)
716
+ uri = URI("#{@base_url}/v1/sdk/#{path}")
343
717
  http = Net::HTTP.new(uri.host, uri.port)
344
718
  http.use_ssl = uri.scheme == 'https'
719
+ if timeout
720
+ http.open_timeout = timeout if http.respond_to?(:open_timeout=)
721
+ http.read_timeout = timeout if http.respond_to?(:read_timeout=)
722
+ end
345
723
  request = Net::HTTP::Post.new(uri)
346
- request['Authorization'] = @config[:headers]["Authorization"]
724
+ request['Authorization'] = "Bearer #{@private_key}"
347
725
  request['Content-Type'] = 'application/json'
348
726
  request.body = payload.to_json
349
-
350
- response = http.request(request)
351
-
352
- if !response.is_a?(Net::HTTPSuccess)
353
- body = JSON.parse(response.body, symbolize_names: true)
354
- raise QuillAPIError.new("#{body[:error]}")
355
- end
356
-
357
- JSON.parse(response.body, symbolize_names: true)
358
- rescue JSON::ParserError => e
359
- raise QuillAPIError.new("Invalid JSON response: #{e.message}")
360
- rescue => e
361
- raise QuillAPIError.new(e.message)
727
+ http.request(request)
362
728
  end
363
729
 
730
+ public
731
+
364
732
  def async_dispose
365
733
  close
366
734
  end