openc3 7.5.0 → 7.6.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.
Files changed (175) hide show
  1. checksums.yaml +4 -4
  2. data/Gemfile +0 -0
  3. data/bin/openc3cli +82 -5
  4. data/data/config/_params.yaml +3 -0
  5. data/data/config/command_modifiers.yaml +5 -3
  6. data/data/config/default_plugins.yaml +1 -0
  7. data/data/config/interface_modifiers.yaml +17 -1
  8. data/data/config/item_modifiers.yaml +24 -1
  9. data/data/config/microservice.yaml +15 -1
  10. data/data/config/parameter_modifiers.yaml +4 -4
  11. data/data/config/plugins.yaml +511 -3
  12. data/data/config/settings.yaml +17 -0
  13. data/data/config/target.yaml +53 -0
  14. data/data/config/telemetry.yaml +58 -2
  15. data/data/config/widgets.yaml +30 -0
  16. data/lib/openc3/accessors/accessor.rb +14 -2
  17. data/lib/openc3/accessors/binary_accessor.rb +25 -5
  18. data/lib/openc3/api/CLAUDE.md +1 -0
  19. data/lib/openc3/api/api.rb +1 -0
  20. data/lib/openc3/api/cmd_api.rb +9 -1
  21. data/lib/openc3/api/interface_api.rb +7 -2
  22. data/lib/openc3/api/limits_api.rb +236 -195
  23. data/lib/openc3/api/router_api.rb +7 -2
  24. data/lib/openc3/api/settings_api.rb +4 -1
  25. data/lib/openc3/api/shared_resource_api.rb +107 -0
  26. data/lib/openc3/api/tlm_api.rb +229 -61
  27. data/lib/openc3/interfaces/http_client_interface.rb +84 -27
  28. data/lib/openc3/interfaces/protocols/preidentified_protocol.rb +6 -2
  29. data/lib/openc3/interfaces/tcpip_server_interface.rb +205 -125
  30. data/lib/openc3/io/json_api.rb +2 -10
  31. data/lib/openc3/io/json_api_object.rb +2 -10
  32. data/lib/openc3/logs/log_writer.rb +9 -8
  33. data/lib/openc3/logs/packet_log_writer.rb +8 -3
  34. data/lib/openc3/microservices/decom_common.rb +4 -1
  35. data/lib/openc3/microservices/decom_microservice.rb +73 -5
  36. data/lib/openc3/microservices/interface_decom_common.rb +16 -1
  37. data/lib/openc3/microservices/interface_microservice.rb +50 -11
  38. data/lib/openc3/microservices/limits_group_microservice.rb +513 -0
  39. data/lib/openc3/microservices/log_microservice.rb +22 -8
  40. data/lib/openc3/microservices/microservice.rb +8 -2
  41. data/lib/openc3/microservices/multi_microservice.rb +76 -22
  42. data/lib/openc3/microservices/queue_microservice.rb +29 -24
  43. data/lib/openc3/migrations/20260704000000_default_bridge.rb +1 -2
  44. data/lib/openc3/migrations/20261103000001_limits_group_backfill.rb +193 -0
  45. data/lib/openc3/models/bridge_model.rb +3 -3
  46. data/lib/openc3/models/cvt_model.rb +10 -3
  47. data/lib/openc3/models/host_interface_microservice_model.rb +4 -4
  48. data/lib/openc3/models/interface_model.rb +27 -7
  49. data/lib/openc3/models/microservice_group.rb +167 -0
  50. data/lib/openc3/models/microservice_model.rb +88 -2
  51. data/lib/openc3/models/panel_model.rb +109 -0
  52. data/lib/openc3/models/plugin_model.rb +1006 -26
  53. data/lib/openc3/models/plugin_store_model.rb +6 -1
  54. data/lib/openc3/models/protected_storage_model.rb +64 -0
  55. data/lib/openc3/models/queue_model.rb +19 -10
  56. data/lib/openc3/models/scope_model.rb +80 -3
  57. data/lib/openc3/models/setting_model.rb +2 -2
  58. data/lib/openc3/models/shared_resource_model.rb +381 -0
  59. data/lib/openc3/models/target_model.rb +333 -74
  60. data/lib/openc3/operators/microservice_operator.rb +76 -9
  61. data/lib/openc3/operators/operator.rb +29 -0
  62. data/lib/openc3/packets/commands.rb +16 -16
  63. data/lib/openc3/packets/limits.rb +2 -0
  64. data/lib/openc3/packets/packet.rb +75 -4
  65. data/lib/openc3/packets/packet_config.rb +152 -13
  66. data/lib/openc3/packets/packet_item.rb +48 -22
  67. data/lib/openc3/packets/packet_item_limits.rb +67 -6
  68. data/lib/openc3/packets/parsers/limits_parser.rb +69 -2
  69. data/lib/openc3/packets/parsers/packet_item_parser.rb +6 -0
  70. data/lib/openc3/packets/parsers/packet_parser.rb +45 -0
  71. data/lib/openc3/packets/parsers/state_parser.rb +1 -1
  72. data/lib/openc3/script/CLAUDE.md +1 -0
  73. data/lib/openc3/script/api_shared.rb +27 -17
  74. data/lib/openc3/script/calendar.rb +18 -6
  75. data/lib/openc3/script/commands.rb +11 -9
  76. data/lib/openc3/script/critical_cmd.rb +22 -2
  77. data/lib/openc3/script/extract.rb +52 -5
  78. data/lib/openc3/script/metadata.rb +30 -4
  79. data/lib/openc3/script/plugins.rb +8 -0
  80. data/lib/openc3/script/script.rb +9 -25
  81. data/lib/openc3/script/web_socket_api.rb +23 -17
  82. data/lib/openc3/system/system.rb +9 -3
  83. data/lib/openc3/top_level.rb +17 -0
  84. data/lib/openc3/topics/command_topic.rb +7 -1
  85. data/lib/openc3/topics/decom_interface_topic.rb +9 -3
  86. data/lib/openc3/topics/discovery_topic.rb +84 -0
  87. data/lib/openc3/topics/limits_event_topic.rb +317 -11
  88. data/lib/openc3/topics/router_topic.rb +6 -2
  89. data/lib/openc3/topics/system_events_topic.rb +9 -6
  90. data/lib/openc3/topics/telemetry_decom_topic.rb +12 -3
  91. data/lib/openc3/topics/topic.rb +9 -1
  92. data/lib/openc3/utilities/authentication.rb +67 -16
  93. data/lib/openc3/utilities/bucket.rb +5 -0
  94. data/lib/openc3/utilities/cli_generator.rb +117 -25
  95. data/lib/openc3/utilities/client_ip_header_filter.rb +38 -0
  96. data/lib/openc3/utilities/config_overlay.rb +24 -1
  97. data/lib/openc3/utilities/cosmos_rails_formatter.rb +18 -10
  98. data/lib/openc3/utilities/hardware_discovery.rb +279 -0
  99. data/lib/openc3/utilities/limits_rollup.rb +81 -0
  100. data/lib/openc3/utilities/local_mode.rb +48 -5
  101. data/lib/openc3/utilities/questdb_client.rb +256 -54
  102. data/lib/openc3/utilities/reingest_job.rb +12 -3
  103. data/lib/openc3/utilities/running_script.rb +206 -49
  104. data/lib/openc3/utilities/script.rb +24 -12
  105. data/lib/openc3/utilities/script_env.rb +164 -0
  106. data/lib/openc3/utilities/script_message_signing.rb +133 -0
  107. data/lib/openc3/utilities/secrets.rb +5 -0
  108. data/lib/openc3/utilities/store_autoload.rb +35 -2
  109. data/lib/openc3/utilities/store_queued.rb +5 -1
  110. data/lib/openc3/version.rb +5 -5
  111. data/templates/command_validator/command_validator.py +9 -9
  112. data/templates/{tool_react/pnpm-workspace.yaml → panel/.prettierrc.cjs} +7 -5
  113. data/templates/panel/Rakefile +24 -0
  114. data/templates/panel/package.json +17 -0
  115. data/templates/{tool_angular → panel}/pnpm-workspace.yaml +5 -0
  116. data/templates/panel/src/Panel.js +52 -0
  117. data/templates/panel/src/Panel.vue +60 -0
  118. data/templates/panel/src/panelSdk.js +24 -0
  119. data/templates/panel/vite-Panel.config.js +43 -0
  120. data/templates/tool_vue/package.json +3 -3
  121. data/templates/widget/package.json +2 -2
  122. metadata +24 -56
  123. data/templates/tool_angular/.editorconfig +0 -16
  124. data/templates/tool_angular/.gitignore +0 -44
  125. data/templates/tool_angular/.vscode/extensions.json +0 -4
  126. data/templates/tool_angular/.vscode/launch.json +0 -20
  127. data/templates/tool_angular/.vscode/tasks.json +0 -42
  128. data/templates/tool_angular/angular.json +0 -111
  129. data/templates/tool_angular/extra-webpack.config.js +0 -8
  130. data/templates/tool_angular/package.json +0 -48
  131. data/templates/tool_angular/src/app/app-routing.module.ts +0 -15
  132. data/templates/tool_angular/src/app/app.component.html +0 -22
  133. data/templates/tool_angular/src/app/app.component.scss +0 -18
  134. data/templates/tool_angular/src/app/app.component.spec.ts +0 -29
  135. data/templates/tool_angular/src/app/app.component.ts +0 -52
  136. data/templates/tool_angular/src/app/app.module.ts +0 -30
  137. data/templates/tool_angular/src/app/custom-overlay-container.ts +0 -17
  138. data/templates/tool_angular/src/app/empty-route/empty-route.component.ts +0 -7
  139. data/templates/tool_angular/src/app/openc3-api.d.ts +0 -1
  140. data/templates/tool_angular/src/assets/.gitkeep +0 -0
  141. data/templates/tool_angular/src/environments/environment.prod.ts +0 -3
  142. data/templates/tool_angular/src/environments/environment.ts +0 -16
  143. data/templates/tool_angular/src/favicon.ico +0 -0
  144. data/templates/tool_angular/src/index.html +0 -13
  145. data/templates/tool_angular/src/main.single-spa.ts +0 -40
  146. data/templates/tool_angular/src/single-spa/asset-url.ts +0 -12
  147. data/templates/tool_angular/src/single-spa/single-spa-props.ts +0 -8
  148. data/templates/tool_angular/src/styles.scss +0 -1
  149. data/templates/tool_angular/tsconfig.app.json +0 -13
  150. data/templates/tool_angular/tsconfig.json +0 -33
  151. data/templates/tool_angular/tsconfig.spec.json +0 -14
  152. data/templates/tool_react/.eslintrc +0 -7
  153. data/templates/tool_react/.gitignore +0 -71
  154. data/templates/tool_react/.prettierignore +0 -8
  155. data/templates/tool_react/babel.config.json +0 -29
  156. data/templates/tool_react/jest.config.js +0 -12
  157. data/templates/tool_react/package.json +0 -51
  158. data/templates/tool_react/src/openc3-tool_name.js +0 -24
  159. data/templates/tool_react/src/root.component.js +0 -88
  160. data/templates/tool_react/src/root.component.test.js +0 -9
  161. data/templates/tool_react/webpack.config.js +0 -27
  162. data/templates/tool_svelte/.gitignore +0 -71
  163. data/templates/tool_svelte/.prettierignore +0 -8
  164. data/templates/tool_svelte/.prettierrc.js +0 -5
  165. data/templates/tool_svelte/babel.config.js +0 -12
  166. data/templates/tool_svelte/build/smui.css +0 -1
  167. data/templates/tool_svelte/jest.config.js +0 -9
  168. data/templates/tool_svelte/package.json +0 -49
  169. data/templates/tool_svelte/pnpm-workspace.yaml +0 -20
  170. data/templates/tool_svelte/rollup.config.js +0 -74
  171. data/templates/tool_svelte/src/App.svelte +0 -42
  172. data/templates/tool_svelte/src/App.test.js +0 -9
  173. data/templates/tool_svelte/src/theme/_smui-theme.scss +0 -25
  174. data/templates/tool_svelte/src/tool_name.js +0 -17
  175. data/templates/widget/LICENSE.md +0 -20
@@ -77,8 +77,9 @@ module OpenC3
77
77
  end
78
78
 
79
79
  # Get or create a thread-local PG connection for the given db_shard with type mapping configured.
80
+ # The port defaults to OPENC3_TSDB_QUERY_PORT.
80
81
  # Returns the thread-local connection - callers should not close it.
81
- def self.connection(db_shard: 0)
82
+ def self.connection(db_shard: 0, port: nil)
82
83
  conns = @thread_conns.value
83
84
  conn = conns[db_shard]
84
85
  if conn and not conn.finished?
@@ -91,7 +92,7 @@ module OpenC3
91
92
  end
92
93
  conn = PG::Connection.new(
93
94
  host: hostname_for_db_shard(db_shard),
94
- port: ENV['OPENC3_TSDB_QUERY_PORT'],
95
+ port: port || ENV.fetch('OPENC3_TSDB_QUERY_PORT', nil),
95
96
  user: ENV['OPENC3_TSDB_USERNAME'],
96
97
  password: ENV['OPENC3_TSDB_PASSWORD'],
97
98
  dbname: 'qdb'
@@ -122,11 +123,12 @@ module OpenC3
122
123
  end
123
124
 
124
125
  # Health check - attempt to connect and immediately close.
126
+ # The port defaults to OPENC3_TSDB_QUERY_PORT.
125
127
  # Returns true if successful, raises on failure.
126
- def self.check_connection(db_shard: 0)
128
+ def self.check_connection(db_shard: 0, port: nil)
127
129
  conn = PG::Connection.new(
128
130
  host: hostname_for_db_shard(db_shard),
129
- port: ENV['OPENC3_TSDB_QUERY_PORT'],
131
+ port: port || ENV.fetch('OPENC3_TSDB_QUERY_PORT', nil),
130
132
  user: ENV['OPENC3_TSDB_USERNAME'],
131
133
  password: ENV['OPENC3_TSDB_PASSWORD'],
132
134
  dbname: 'qdb'
@@ -465,18 +467,45 @@ module OpenC3
465
467
  end
466
468
  end
467
469
 
468
- # Build a SQL WHERE clause for PACKET_TIMESECONDS range filtering.
470
+ # Returns the timestamp column that filters and orders data for a time type.
471
+ #
472
+ # @param time_type [Symbol] :PACKET or :RECEIVED
473
+ # @return [String] PACKET_TIMESECONDS or RECEIVED_TIMESECONDS
474
+ def self.time_column(time_type)
475
+ time_type == :RECEIVED ? 'RECEIVED_TIMESECONDS' : 'PACKET_TIMESECONDS'
476
+ end
477
+
478
+ # Build a SQL WHERE clause for time range filtering.
469
479
  #
470
480
  # @param start_time [Integer, String] Start timestamp (nanoseconds)
471
481
  # @param end_time [Integer, String, nil] End timestamp (nanoseconds), or nil for open-ended
472
482
  # @param prefix [String] Table alias prefix (e.g., 'T0.') — default ''
483
+ # @param time_type [Symbol] :PACKET filters on PACKET_TIMESECONDS, :RECEIVED on RECEIVED_TIMESECONDS
484
+ # @param packet_bounds [Array<Integer, nil>, nil] [min, max] PACKET_TIMESECONDS limits (inclusive,
485
+ # either may be nil) added to a :RECEIVED filter so QuestDB can skip partitions. See packet_time_bounds.
473
486
  # @return [String] SQL WHERE clause fragment (includes leading space)
474
- def self.time_where_clause(start_time, end_time, prefix: '')
475
- where = " WHERE #{prefix}PACKET_TIMESECONDS >= #{start_time}"
476
- where += " AND #{prefix}PACKET_TIMESECONDS < #{end_time}" if end_time
487
+ def self.time_where_clause(start_time, end_time, prefix: '', time_type: :PACKET, packet_bounds: nil)
488
+ column = "#{prefix}#{time_column(time_type)}"
489
+ where = " WHERE #{column} >= #{start_time}"
490
+ where += " AND #{column} < #{end_time}" if end_time
491
+ if time_type == :RECEIVED and packet_bounds
492
+ min_time, max_time = packet_bounds
493
+ where += " AND #{prefix}PACKET_TIMESECONDS >= #{Integer(min_time)}" if min_time
494
+ where += " AND #{prefix}PACKET_TIMESECONDS <= #{Integer(max_time)}" if max_time
495
+ end
477
496
  where
478
497
  end
479
498
 
499
+ # PACKET_TIMESECONDS is the designated timestamp so rows already come back in
500
+ # that order. RECEIVED_TIMESECONDS is a regular column and needs an explicit sort,
501
+ # which also keeps LIMIT pagination stable.
502
+ #
503
+ # @param time_type [Symbol] :PACKET or :RECEIVED
504
+ # @return [String] SQL ORDER BY clause (includes leading space) or ''
505
+ def self.time_order_clause(time_type)
506
+ time_type == :RECEIVED ? " ORDER BY RECEIVED_TIMESECONDS, PACKET_TIMESECONDS" : ''
507
+ end
508
+
480
509
  # Fetch a packet definition from TargetModel, returning nil if not found.
481
510
  #
482
511
  # @param target_name [String] Target name
@@ -561,10 +590,11 @@ module OpenC3
561
590
  # @param value_type [Symbol] :RAW or :CONVERTED
562
591
  # @param existing_columns [Set<String>, nil] Column names that actually exist in the
563
592
  # table, used for CONVERTED-to-raw fallback (see build_aggregation_selects).
593
+ # @param time_type [Symbol] :PACKET or :RECEIVED, which timestamp the samples are bucketed by
564
594
  # @return [Array<String>, Boolean] Two-element array: [select_fragments, has_numeric_items]
565
- # select_fragments includes TIMESTAMP_SELECT as the first element.
566
- def self.build_packet_reduced_selects(packet_def, value_type, existing_columns: nil)
567
- selects = [TIMESTAMP_SELECT]
595
+ # select_fragments includes the timestamp_select as the first element.
596
+ def self.build_packet_reduced_selects(packet_def, value_type, existing_columns: nil, time_type: :PACKET)
597
+ selects = [timestamp_select(time_type)]
568
598
  has_items = false
569
599
  return [selects, false] unless packet_def && packet_def['items']
570
600
 
@@ -600,6 +630,19 @@ module OpenC3
600
630
  # PG wire protocol truncates timestamp_ns to microseconds; CAST AS LONG preserves full precision.
601
631
  TIMESTAMP_SELECT = 'CAST(PACKET_TIMESECONDS AS LONG) as PACKET_TIMESECONDS'
602
632
 
633
+ # SQL: nanosecond-precision timestamp select for the given time type.
634
+ #
635
+ # @param time_type [Symbol] :PACKET or :RECEIVED
636
+ # @return [String] SELECT fragment aliased to the timestamp column name
637
+ def self.timestamp_select(time_type)
638
+ column = time_column(time_type)
639
+ "CAST(#{column} AS LONG) as #{column}"
640
+ end
641
+
642
+ # SQL: nanosecond-precision received timestamp for explicit SELECT lists that
643
+ # order by received time. Aliased to avoid colliding with a RECEIVED_TIMESECONDS item column.
644
+ RECEIVED_TIMESTAMP_SELECT = 'CAST(RECEIVED_TIMESECONDS AS LONG) as "__rx_time_ns"'
645
+
603
646
  # SQL: nanosecond-precision timestamps for SELECT * queries (different aliases avoid column name collision).
604
647
  TIMESTAMP_EXTRAS = 'CAST(PACKET_TIMESECONDS AS LONG) as "__pkt_time_ns", CAST(RECEIVED_TIMESECONDS AS LONG) as "__rx_time_ns"'
605
648
 
@@ -621,17 +664,58 @@ module OpenC3
621
664
  # @param table_name [String] Sanitized table name
622
665
  # @param start_time [Integer] Nanosecond start time
623
666
  # @param end_time [Integer, nil] Nanosecond end time
667
+ # @param time_type [Symbol] :PACKET or :RECEIVED, which timestamp the range applies to
624
668
  # @return [Boolean]
625
- def self.table_has_data?(table_name, start_time, end_time, db_shard: 0)
669
+ def self.table_has_data?(table_name, start_time, end_time, db_shard: 0, time_type: :PACKET)
626
670
  query = "SELECT 1 FROM \"#{table_name}\""
627
- query += time_where_clause(start_time, end_time)
671
+ query += time_where_clause(start_time, end_time, time_type: time_type)
628
672
  query += " LIMIT 1"
629
673
  result = query_with_retry(query, max_retries: 1, label: "table_has_data", db_shard: db_shard)
630
674
  result && result.ntuples > 0
631
- rescue RuntimeError
675
+ rescue QuestDBError, RuntimeError
676
+ # A table which doesn't exist fails the query
632
677
  false
633
678
  end
634
679
 
680
+ # Returns the PACKET_TIMESECONDS range of the rows received in a time range.
681
+ # RECEIVED_TIMESECONDS is a regular column, so QuestDB scans every partition to
682
+ # filter on it. Adding these limits to a received-time query (packet_bounds:) lets
683
+ # QuestDB skip the partitions outside them, so paging through the results doesn't
684
+ # scan the whole table for every page.
685
+ #
686
+ # @param table_name [String] Sanitized table name
687
+ # @param start_time [Integer] Nanosecond received start time
688
+ # @param end_time [Integer, nil] Nanosecond received end time
689
+ # @return [Array<Integer>, nil] [min, max] nanosecond packet times, or nil if no rows were received in the range
690
+ def self.packet_time_bounds(table_name, start_time, end_time, db_shard: 0)
691
+ query = "SELECT CAST(min(PACKET_TIMESECONDS) AS LONG) as min_time, CAST(max(PACKET_TIMESECONDS) AS LONG) as max_time FROM \"#{table_name}\""
692
+ query += time_where_clause(start_time, end_time, time_type: :RECEIVED)
693
+ result = query_with_retry(query, label: "packet_time_bounds", db_shard: db_shard)
694
+ return nil if result.nil? or result.ntuples == 0
695
+ row = result[0]
696
+ return nil if row['min_time'].nil? or row['max_time'].nil?
697
+ [row['min_time'].to_i, row['max_time'].to_i]
698
+ end
699
+
700
+ # Return the telemetry packets which have a table. The TSDB microservice only
701
+ # creates tables for its initial packets so a packet added later has no table
702
+ # until it's received. If the table names can't be fetched assume they all exist.
703
+ #
704
+ # @param packets [Array<Array(String, String)>] [target_name, packet_name] pairs
705
+ # @return [Set<Array(String, String)>] The pairs which have a table
706
+ def self.tlm_packets_with_tables(packets, scope: "DEFAULT")
707
+ existing = Set.new
708
+ packets.group_by { |target_name, _| db_shard_for_target(target_name, scope: scope) }.each do |db_shard, shard_packets|
709
+ names = table_names(db_shard: db_shard)
710
+ shard_packets.each do |target_name, packet_name|
711
+ if names.nil? or names.include?(sanitize_table_name(target_name, packet_name, scope: scope).upcase)
712
+ existing << [target_name, packet_name]
713
+ end
714
+ end
715
+ end
716
+ existing
717
+ end
718
+
635
719
  # Return the names of all tables in a single query. Used to avoid querying
636
720
  # (and failing on) tables that were never created, e.g. commands that have
637
721
  # never been sent, which is the common case for targets with thousands of packets.
@@ -707,14 +791,21 @@ module OpenC3
707
791
  # @param start_time [Integer] Start timestamp in nanoseconds
708
792
  # @param end_time [Integer, nil] End timestamp in nanoseconds
709
793
  # @param include_received_ts [Boolean] Whether to include RECEIVED_TIMESECONDS
794
+ # @param time_type [Symbol] :PACKET or :RECEIVED, which timestamp filters and orders the rows.
795
+ # :RECEIVED also selects the nanosecond received time as "__rx_time_ns".
796
+ # @param include_times [Boolean] Also select the nanosecond received time as "__rx_time_ns"
797
+ # so decode_item_row can return both the packet and received times
798
+ # @param packet_bounds [Array<Integer, nil>, nil] PACKET_TIMESECONDS limits for :RECEIVED (see time_where_clause)
710
799
  # @return [String] Complete SQL query (without LIMIT clause)
711
- def self.build_item_columns_query(table_name, column_names, start_time, end_time, include_received_ts: false)
800
+ def self.build_item_columns_query(table_name, column_names, start_time, end_time, include_received_ts: false, time_type: :PACKET, include_times: false, packet_bounds: nil)
712
801
  names = column_names.dup
713
802
  names << TIMESTAMP_SELECT
714
803
  names << "RECEIVED_TIMESECONDS" if include_received_ts
804
+ names << RECEIVED_TIMESTAMP_SELECT if time_type == :RECEIVED or include_times
715
805
  names << "COSMOS_EXTRA"
716
806
  query = "SELECT #{names.join(', ')} FROM \"#{table_name}\""
717
- query += time_where_clause(start_time, end_time)
807
+ query += time_where_clause(start_time, end_time, time_type: time_type, packet_bounds: packet_bounds)
808
+ query += time_order_clause(time_type)
718
809
  query
719
810
  end
720
811
 
@@ -723,10 +814,13 @@ module OpenC3
723
814
  # @param table_name [String] Sanitized QuestDB table name
724
815
  # @param start_time [Integer] Start timestamp in nanoseconds
725
816
  # @param end_time [Integer, nil] End timestamp in nanoseconds
817
+ # @param time_type [Symbol] :PACKET or :RECEIVED, which timestamp filters and orders the rows
818
+ # @param packet_bounds [Array<Integer, nil>, nil] PACKET_TIMESECONDS limits for :RECEIVED (see time_where_clause)
726
819
  # @return [String] Complete SQL query (without LIMIT clause)
727
- def self.build_packet_query(table_name, start_time, end_time)
820
+ def self.build_packet_query(table_name, start_time, end_time, time_type: :PACKET, packet_bounds: nil)
728
821
  query = "SELECT *, #{TIMESTAMP_EXTRAS} FROM \"#{table_name}\""
729
- query += time_where_clause(start_time, end_time)
822
+ query += time_where_clause(start_time, end_time, time_type: time_type, packet_bounds: packet_bounds)
823
+ query += time_order_clause(time_type)
730
824
  query
731
825
  end
732
826
 
@@ -737,13 +831,26 @@ module OpenC3
737
831
  # @param start_time [Integer] Start timestamp in nanoseconds
738
832
  # @param end_time [Integer, nil] End timestamp in nanoseconds
739
833
  # @param sample_interval [String] QuestDB SAMPLE BY interval ('1m', '1h', '1d')
834
+ # @param time_type [Symbol] :PACKET or :RECEIVED, which timestamp filters and buckets the rows.
835
+ # select_columns should start with timestamp_select(time_type).
836
+ # @param packet_bounds [Array<Integer, nil>, nil] PACKET_TIMESECONDS limits for :RECEIVED (see time_where_clause)
740
837
  # @return [String] Complete SQL query (without LIMIT clause)
741
- def self.build_reduced_query(table_name, select_columns, start_time, end_time, sample_interval)
742
- query = "SELECT #{select_columns.join(', ')} FROM \"#{table_name}\""
743
- query += time_where_clause(start_time, end_time)
838
+ def self.build_reduced_query(table_name, select_columns, start_time, end_time, sample_interval, time_type: :PACKET, packet_bounds: nil)
839
+ column = time_column(time_type)
840
+ query = "SELECT #{select_columns.join(', ')} FROM "
841
+ if time_type == :RECEIVED
842
+ # SAMPLE BY buckets on the designated timestamp (PACKET_TIMESECONDS), so
843
+ # sort a subquery by received time and declare that as its timestamp
844
+ query += "(SELECT * FROM \"#{table_name}\""
845
+ query += time_where_clause(start_time, end_time, time_type: time_type, packet_bounds: packet_bounds)
846
+ query += " ORDER BY #{column}) timestamp(#{column})"
847
+ else
848
+ query += "\"#{table_name}\""
849
+ query += time_where_clause(start_time, end_time, time_type: time_type, packet_bounds: packet_bounds)
850
+ end
744
851
  query += " SAMPLE BY #{sample_interval}"
745
852
  query += " ALIGN TO CALENDAR"
746
- query += " ORDER BY PACKET_TIMESECONDS"
853
+ query += " ORDER BY #{column}"
747
854
  query
748
855
  end
749
856
 
@@ -757,13 +864,19 @@ module OpenC3
757
864
  # :item_types [Array<Hash>] - type info per position ({ 'data_type' =>, 'array_size' => })
758
865
  # :stored_timestamp_item_keys [Hash] - { item_key => { column: col_name } }
759
866
  # :calculated_positions [Hash] - { local_idx => { source: col_name, format: :seconds/:formatted } }
867
+ # @param time_type [Symbol] :PACKET sets __time to the packet time, :RECEIVED to the
868
+ # received time (requires the "__rx_time_ns" column from build_item_columns_query)
869
+ # @param include_times [Boolean] Also set __packet_time and __received_time (requires
870
+ # build_item_columns_query with include_times: true)
760
871
  # @return [Hash] Entry hash with __type, item_key => value, __time, COSMOS_EXTRA
761
- def self.decode_item_row(row, sql_to_local, meta)
872
+ # and optionally __packet_time and __received_time
873
+ def self.decode_item_row(row, sql_to_local, meta, time_type: :PACKET, include_times: false)
762
874
  num_sql_item_cols = sql_to_local.length
763
875
 
764
876
  entry = { "__type" => "ITEMS" }
765
877
  timestamp_values = {}
766
878
  time_ns = nil
879
+ received_time_ns = nil
767
880
  cosmos_extra = nil
768
881
 
769
882
  values = Array.new(meta[:item_keys].length)
@@ -780,6 +893,8 @@ module OpenC3
780
893
  timestamp_values['PACKET_TIMESECONDS'] = nsec_to_utc_time(time_ns)
781
894
  when 'RECEIVED_TIMESECONDS'
782
895
  timestamp_values['RECEIVED_TIMESECONDS'] = value if value
896
+ when '__rx_time_ns'
897
+ received_time_ns = value.to_i if value
783
898
  when 'COSMOS_EXTRA'
784
899
  cosmos_extra = value
785
900
  # No else because we're only interested in these specific extra columns; others can be ignored
@@ -823,7 +938,12 @@ module OpenC3
823
938
  end
824
939
  end
825
940
 
826
- entry['__time'] = time_ns if time_ns
941
+ entry_time = (time_type == :RECEIVED) ? received_time_ns : time_ns
942
+ entry['__time'] = entry_time if entry_time
943
+ if include_times
944
+ entry['__packet_time'] = time_ns if time_ns
945
+ entry['__received_time'] = received_time_ns if received_time_ns
946
+ end
827
947
  entry['COSMOS_EXTRA'] = cosmos_extra if cosmos_extra
828
948
  entry
829
949
  end
@@ -835,8 +955,11 @@ module OpenC3
835
955
  # @param row [PG::Result row] Single row as iterable [col_name, value] pairs
836
956
  # @param value_type [Symbol] :RAW, :CONVERTED, :FORMATTED
837
957
  # @param packet_def [Hash, nil] Packet definition for type-aware decoding
958
+ # @param time_type [Symbol] :PACKET sets __time to the packet time, :RECEIVED to the received time
959
+ # @param include_times [Boolean] Also set __packet_time and __received_time
838
960
  # @return [Hash] Entry hash with item => value, __time, COSMOS_EXTRA, timestamp entries
839
- def self.decode_packet_row(row, value_type, packet_def)
961
+ # and optionally __packet_time and __received_time
962
+ def self.decode_packet_row(row, value_type, packet_def, time_type: :PACKET, include_times: false)
840
963
  entry = {}
841
964
  item_defs = build_item_defs_map(packet_def)
842
965
 
@@ -856,12 +979,13 @@ module OpenC3
856
979
 
857
980
  if column_name == '__pkt_time_ns'
858
981
  cosmos_timestamp_ns = raw_value.to_i
859
- entry['__time'] = cosmos_timestamp_ns
982
+ entry['__time'] = cosmos_timestamp_ns unless time_type == :RECEIVED
860
983
  next
861
984
  end
862
985
 
863
986
  if column_name == '__rx_time_ns'
864
987
  received_timestamp_ns = raw_value.to_i
988
+ entry['__time'] = received_timestamp_ns if time_type == :RECEIVED
865
989
  next
866
990
  end
867
991
 
@@ -907,11 +1031,17 @@ module OpenC3
907
1031
 
908
1032
  add_timestamp_entries!(entry, cosmos_timestamp_ns, 'PACKET')
909
1033
  add_timestamp_entries!(entry, received_timestamp_ns, 'RECEIVED')
1034
+ if include_times
1035
+ entry['__packet_time'] = cosmos_timestamp_ns if cosmos_timestamp_ns
1036
+ entry['__received_time'] = received_timestamp_ns if received_timestamp_ns
1037
+ end
910
1038
  entry
911
1039
  end
912
1040
 
913
1041
  # Decode a single row from a SAMPLE BY aggregation query.
914
1042
  # All non-timestamp columns are decoded as DOUBLE (aggregation results are always numeric).
1043
+ # The bucket timestamp column is PACKET_TIMESECONDS or RECEIVED_TIMESECONDS
1044
+ # depending on the time type passed to timestamp_select.
915
1045
  #
916
1046
  # @param row [PG::Result row] Single row as iterable [col_name, value] pairs
917
1047
  # @return [Hash] { col_name => decoded_value, '__time' => ns_integer }
@@ -920,7 +1050,7 @@ module OpenC3
920
1050
  row.each do |tuple|
921
1051
  col_name = tuple[0]
922
1052
  value = tuple[1]
923
- if col_name == 'PACKET_TIMESECONDS'
1053
+ if STORED_TIMESTAMP_ITEMS.include?(col_name)
924
1054
  entry['__time'] = value.to_i
925
1055
  else
926
1056
  entry[col_name] = decode_value(value, data_type: 'DOUBLE', array_size: nil)
@@ -932,19 +1062,23 @@ module OpenC3
932
1062
  # Query historical telemetry data from QuestDB for a list of items.
933
1063
  # Builds the SQL query, executes it, and decodes all results.
934
1064
  # Supports cross-db_shard queries by grouping items by db_shard, executing
935
- # separate queries per db_shard, and merging results positionally.
1065
+ # separate queries per db_shard, and aligning the results by packet time.
936
1066
  #
937
1067
  # @param items [Array] Array of [target_name, packet_name, item_name, value_type, limits]
938
1068
  # item_name may be nil to indicate a placeholder (non-existent item)
939
1069
  # @param start_time [String, Numeric] Start timestamp for the query
940
1070
  # @param end_time [String, Numeric, nil] End timestamp, or nil for "latest single row"
941
1071
  # @param scope [String] Scope name
1072
+ # @param flatten [Boolean] Whether a single row result is returned as a flat array
942
1073
  # @return [Array, Hash] Array of [value, limits_state] pairs per row, or {} if no results.
943
- # Single-row results return a flat array; multi-row results return array of arrays.
944
- def self.tsdb_lookup(items, start_time:, end_time: nil, scope: "DEFAULT")
1074
+ # Single-row results return a flat array (unless flatten is false); multi-row results return array of arrays.
1075
+ def self.tsdb_lookup(items, start_time:, end_time: nil, scope: "DEFAULT", flatten: true)
945
1076
  # Every item is a placeholder for an item which doesn't exist, so there's
946
1077
  # nothing to query. Return a single row of nil values, one per item.
947
- return Array.new(items.length) { [nil, nil] } if items.all? { |item| item[2].nil? }
1078
+ if items.all? { |item| item[2].nil? }
1079
+ row = Array.new(items.length) { [nil, nil] }
1080
+ return flatten ? row : [row]
1081
+ end
948
1082
 
949
1083
  # Group items by db_shard number while preserving their original positions
950
1084
  db_shard_groups = {} # db_shard => { positions: [], items: [] }
@@ -959,39 +1093,95 @@ module OpenC3
959
1093
  # Single-db_shard fast path (most common case)
960
1094
  if db_shard_groups.length == 1
961
1095
  db_shard, group = db_shard_groups.first
962
- return tsdb_lookup_single_db_shard(group[:items], start_time: start_time, end_time: end_time, scope: scope, db_shard: db_shard)
1096
+ return tsdb_lookup_single_db_shard(group[:items], start_time: start_time, end_time: end_time, scope: scope, db_shard: db_shard, flatten: flatten)
963
1097
  end
964
1098
 
965
- # Cross-db_shard: execute per-db_shard queries (as arrays of rows) and merge results
966
- db_shard_rows = {} # db_shard => rows
967
- db_shard_groups.each do |db_shard, group|
968
- result = tsdb_lookup_single_db_shard(group[:items], start_time: start_time, end_time: end_time, scope: scope, db_shard: db_shard, flatten: false)
969
- db_shard_rows[db_shard] = result.is_a?(Array) ? result : []
970
- end
1099
+ # Cross-db_shard: a single query can't ASOF JOIN tables on different QuestDBs
1100
+ tsdb_lookup_db_shards(items, db_shard_groups, start_time: start_time, end_time: end_time, scope: scope, flatten: flatten)
1101
+ end
971
1102
 
972
- # Merge results positionally back into the original item order. Each db_shard
973
- # may have different row counts so use the maximum row count and fill missing
974
- # positions with [nil, nil]. If all db_shards returned empty, return empty.
975
- max_rows = db_shard_rows.values.map(&:length).max
976
- return {} if max_rows == 0
1103
+ # Cross-db_shard lookup which matches the rows of a single db_shard ASOF JOIN.
1104
+ # The packet of the first item drives the rows (like T0 in a single db_shard query) so
1105
+ # its db_shard is queried as usual. Every packet on another db_shard is queried on its
1106
+ # own and aligned to each driving row's packet time, using its last row at or before
1107
+ # that time (like ASOF JOIN). Each packet is aligned independently and includes its
1108
+ # last row before start_time, so its value carries forward like it would in ASOF JOIN.
1109
+ def self.tsdb_lookup_db_shards(items, db_shard_groups, start_time:, end_time:, scope:, flatten: true)
1110
+ driver = db_shard_for_target(items.find { |item| item[2] }[0], scope: scope)
1111
+ driver_rows = tsdb_lookup_single_db_shard(db_shard_groups[driver][:items], start_time: start_time, end_time: end_time, scope: scope, db_shard: driver, flatten: false, with_time: true)
1112
+ return {} if !driver_rows.is_a?(Array) or driver_rows.empty?
1113
+
1114
+ # The packet time in nanoseconds is the last value of each row
1115
+ times = driver_rows.map { |row| row[-1][0] }
1116
+
1117
+ merged = driver_rows.map do |driver_row|
1118
+ row = Array.new(items.length) { [nil, nil] }
1119
+ db_shard_groups[driver][:positions].each_with_index do |orig_pos, db_shard_idx|
1120
+ row[orig_pos] = driver_row[db_shard_idx] if driver_row[db_shard_idx]
1121
+ end
1122
+ row
1123
+ end
977
1124
 
978
- merged = Array.new(max_rows) { Array.new(items.length) { [nil, nil] } }
979
1125
  db_shard_groups.each do |db_shard, group|
980
- db_shard_rows[db_shard].each_with_index do |row, row_num|
981
- group[:positions].each_with_index do |orig_pos, db_shard_idx|
982
- merged[row_num][orig_pos] = row[db_shard_idx] if row[db_shard_idx]
1126
+ next if db_shard == driver
1127
+
1128
+ # Group the items by packet, leaving placeholders as nils
1129
+ packets = {} # [target_name, packet_name] => { positions: [], items: [] }
1130
+ group[:positions].zip(group[:items]).each do |orig_pos, item|
1131
+ next unless item[2]
1132
+
1133
+ packet = (packets[[item[0], item[1]]] ||= { positions: [], items: [] })
1134
+ packet[:positions] << orig_pos
1135
+ packet[:items] << item
1136
+ end
1137
+
1138
+ packets.each_value do |packet|
1139
+ rows = tsdb_lookup_packet_rows(packet[:items], times, start_time: start_time, end_time: end_time, scope: scope, db_shard: db_shard)
1140
+ index = -1 # Index of the last packet row at or before the driving row
1141
+ times.each_with_index do |driver_time, row_num|
1142
+ index += 1 while index + 1 < rows.length and rows[index + 1][-1][0] <= driver_time
1143
+ next if index < 0
1144
+
1145
+ packet[:positions].each_with_index do |orig_pos, packet_idx|
1146
+ merged[row_num][orig_pos] = rows[index][packet_idx] if rows[index][packet_idx]
1147
+ end
983
1148
  end
984
1149
  end
985
1150
  end
1151
+
986
1152
  # Match the single db_shard behavior of returning a flat array for a single row
987
- return merged[0] if max_rows == 1
1153
+ return merged[0] if flatten and merged.length == 1
1154
+
988
1155
  merged
989
1156
  end
990
1157
 
1158
+ # Query the rows of a single packet needed to align it to the driving row times.
1159
+ # Each row ends with its packet time in nanoseconds.
1160
+ def self.tsdb_lookup_packet_rows(items, times, start_time:, end_time:, scope:, db_shard:)
1161
+ if end_time
1162
+ # The last row before start_time followed by the rows in the range
1163
+ queries = [{ start_time: start_time }, { start_time: start_time, end_time: end_time }]
1164
+ else
1165
+ # The single driving row is before start_time so get the last row at or before it
1166
+ queries = [{ start_time: nsec_to_iso(times[0]), inclusive: true }]
1167
+ end
1168
+ queries.flat_map do |query|
1169
+ result = tsdb_lookup_single_db_shard(items, scope: scope, db_shard: db_shard, flatten: false, with_time: true, **query)
1170
+ result.is_a?(Array) ? result : []
1171
+ end
1172
+ end
1173
+
1174
+ # Convert a nanosecond integer timestamp to an ISO 8601 string with nanosecond precision
1175
+ def self.nsec_to_iso(nsec)
1176
+ Time.at(nsec / 1_000_000_000, nsec % 1_000_000_000, :nsec).utc.strftime('%Y-%m-%dT%H:%M:%S.%9NZ')
1177
+ end
1178
+
991
1179
  # Execute a tsdb_lookup query against a single db_shard.
992
1180
  # This contains the original ASOF JOIN logic for items all on the same QuestDB instance.
993
1181
  # When flatten is true a single row result is returned as a flat array rather than an array of rows.
994
- def self.tsdb_lookup_single_db_shard(items, start_time:, end_time: nil, scope: "DEFAULT", db_shard: 0, flatten: true)
1182
+ # When inclusive is true a query without an end_time returns the last row at or before start_time.
1183
+ # When with_time is true each row ends with its packet time in nanoseconds.
1184
+ def self.tsdb_lookup_single_db_shard(items, start_time:, end_time: nil, scope: "DEFAULT", db_shard: 0, flatten: true, inclusive: false, with_time: false)
995
1185
  tables = {}
996
1186
  names = []
997
1187
  nil_count = 0
@@ -1000,6 +1190,14 @@ module OpenC3
1000
1190
  calculated_items = {}
1001
1191
  needed_timestamps = {}
1002
1192
  current_position = 0
1193
+ # Columns with the same name in different tables come back renamed by QuestDB
1194
+ # (e.g. VALUE and VALUE_2) so alias every column and map it back when decoding
1195
+ aliases = {}
1196
+ add_column = lambda do |col_name|
1197
+ alias_name = "__col#{aliases.length}"
1198
+ aliases[alias_name] = col_name
1199
+ names << "\"#{col_name}\" as #{alias_name}"
1200
+ end
1003
1201
 
1004
1202
  items.each do |item|
1005
1203
  target_name, packet_name, orig_item_name, value_type, limits = item
@@ -1014,7 +1212,7 @@ module OpenC3
1014
1212
  index = tables.find_index {|k,_v| k == table_name }
1015
1213
 
1016
1214
  if STORED_TIMESTAMP_ITEMS.include?(orig_item_name)
1017
- names << "\"T#{index}.#{orig_item_name}\""
1215
+ add_column.call("T#{index}.#{orig_item_name}")
1018
1216
  current_position += 1
1019
1217
  next
1020
1218
  end
@@ -1044,11 +1242,11 @@ module OpenC3
1044
1242
 
1045
1243
  suffix = column_suffix_for_value_type(value_type)
1046
1244
  col_name = "T#{index}.#{safe_item_name}#{suffix}"
1047
- names << "\"#{col_name}\""
1245
+ add_column.call(col_name)
1048
1246
  item_types[col_name] = resolve_item_type(item_def, value_type)
1049
1247
  current_position += 1
1050
1248
  if limits
1051
- names << "\"T#{index}.#{safe_item_name}__L\""
1249
+ add_column.call("T#{index}.#{safe_item_name}__L")
1052
1250
  end
1053
1251
  end
1054
1252
 
@@ -1063,6 +1261,7 @@ module OpenC3
1063
1261
  names << "T#{table_index}.#{ts_col} as T#{table_index}___ts_#{ts_col}"
1064
1262
  end
1065
1263
  end
1264
+ names << "cast(T0.PACKET_TIMESECONDS as long) as __time" if with_time
1066
1265
 
1067
1266
  # Build the SQL query
1068
1267
  query = "SELECT #{names.join(", ")} FROM "
@@ -1075,7 +1274,7 @@ module OpenC3
1075
1274
  end
1076
1275
  query_params = []
1077
1276
  if start_time && !end_time
1078
- query += "WHERE T0.PACKET_TIMESECONDS < $1 LIMIT -1"
1277
+ query += "WHERE T0.PACKET_TIMESECONDS #{inclusive ? '<=' : '<'} $1 LIMIT -1"
1079
1278
  query_params << start_time
1080
1279
  elsif start_time && end_time
1081
1280
  query += "WHERE T0.PACKET_TIMESECONDS >= $1 AND T0.PACKET_TIMESECONDS < $2"
@@ -1094,13 +1293,16 @@ module OpenC3
1094
1293
  row_index = 0
1095
1294
  row_timestamps = {}
1096
1295
  tuples.each do |tuple|
1097
- col_name = tuple[0]
1296
+ col_name = aliases.fetch(tuple[0], tuple[0])
1098
1297
  col_value = tuple[1]
1099
1298
  if col_name.include?("__L")
1100
1299
  data[row_num][row_index - 1][1] = col_value
1101
1300
  elsif col_name =~ /^__nil/
1102
1301
  data[row_num][row_index] = [nil, nil]
1103
1302
  row_index += 1
1303
+ elsif col_name == '__time'
1304
+ data[row_num][row_index] = [Integer(col_value), nil]
1305
+ row_index += 1
1104
1306
  elsif col_name =~ /^T(\d+)___ts_(.+)$/
1105
1307
  table_idx = $1.to_i
1106
1308
  ts_source = $2
@@ -196,7 +196,9 @@ module OpenC3
196
196
  reader.each(local_file, false) do |packet|
197
197
  next unless packet.target_name && packet.packet_name
198
198
  cmd_or_tlm = packet.cmd_or_tlm == :CMD ? 'CMD' : 'TLM'
199
- table_names.add("#{@scope}__#{cmd_or_tlm}__#{packet.target_name}__#{packet.packet_name}")
199
+ # Use the same sanitization as the TSDB writer so names match the
200
+ # real tables and can't break out of the quoted ALTER TABLE literal
201
+ table_names.add(QuestDBClient.sanitize_table_name(packet.target_name, packet.packet_name, cmd_or_tlm, scope: @scope))
200
202
  end
201
203
  ids = reader.instance_variable_get(:@target_ids) || []
202
204
  file_versions[local_file] = ids.first ? ids.first.unpack1('H*') : nil
@@ -320,7 +322,7 @@ module OpenC3
320
322
  if already
321
323
  preexisting << table_name
322
324
  else
323
- conn.exec("ALTER TABLE '#{table_name}' DEDUP ENABLE UPSERT KEYS(PACKET_TIMESECONDS)")
325
+ conn.exec("ALTER TABLE #{quote_table_name(table_name)} DEDUP ENABLE UPSERT KEYS(PACKET_TIMESECONDS)")
324
326
  enabled_by_us << table_name
325
327
  end
326
328
  rescue => e
@@ -331,6 +333,13 @@ module OpenC3
331
333
  [enabled_by_us, preexisting]
332
334
  end
333
335
 
336
+ # DDL can't take bind parameters so the table name is interpolated.
337
+ # sanitize_table_name already strips quotes; refuse anything that slipped through.
338
+ def quote_table_name(table_name)
339
+ raise ArgumentError, "Invalid table name: #{table_name}" if table_name.match?(/['"\\]/)
340
+ "'#{table_name}'"
341
+ end
342
+
334
343
  # QuestDB exposes per-table dedup status via tables() function.
335
344
  # Falls back to false (treat as not-enabled, will issue ALTER) on any error.
336
345
  def dedup_already_enabled?(conn, table_name)
@@ -364,7 +373,7 @@ module OpenC3
364
373
  conn = QuestDBClient.connection(db_shard: db_shard)
365
374
  tables.each_with_index do |table_name, i|
366
375
  begin
367
- conn.exec("ALTER TABLE '#{table_name}' DEDUP DISABLE")
376
+ conn.exec("ALTER TABLE #{quote_table_name(table_name)} DEDUP DISABLE")
368
377
  disabled << table_name
369
378
  rescue => e
370
379
  @logger.warn("Failed to disable DEDUP on #{table_name}: #{e.message}")