Class: OpenC3::QueueModel

Inherits:
Model show all
Defined in:
lib/openc3/models/queue_model.rb

Constant Summary collapse

PRIMARY_KEY =
'openc3__queue'.freeze
@@class_mutex =
Mutex.new

Instance Attribute Summary collapse

Attributes inherited from Model

#plugin, #scope, #updated_at

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Model

#check_disable_erb, #destroyed?, #diff, filter, find_all_by_plugin, from_json, get_all_models, get_model, handle_config, set, store, store_queued, #update

Constructor Details

#initialize(name:, scope:, state: 'HOLD', updated_at: nil) ⇒ QueueModel

Returns a new instance of QueueModel.



79
80
81
82
83
84
85
86
87
# File 'lib/openc3/models/queue_model.rb', line 79

def initialize(name:, scope:, state: 'HOLD', updated_at: nil)
  super("#{scope}__#{PRIMARY_KEY}", name: name, updated_at: updated_at, scope: scope)
  @microservice_name = "#{scope}__QUEUE__#{name}"
  if %w(HOLD RELEASE DISABLE).include?(state)
    @state = state
  else
    @state = 'HOLD'
  end
end

Instance Attribute Details

#nameObject

Returns the value of attribute name.



77
78
79
# File 'lib/openc3/models/queue_model.rb', line 77

def name
  @name
end

#stateObject

Returns the value of attribute state.



77
78
79
# File 'lib/openc3/models/queue_model.rb', line 77

def state
  @state
end

Class Method Details

.all(scope:) ⇒ Object



38
39
40
# File 'lib/openc3/models/queue_model.rb', line 38

def self.all(scope:)
  super("#{scope}__#{PRIMARY_KEY}")
end

.get(name:, scope:) ⇒ Object

NOTE: The following three class methods are used by the ModelController and are reimplemented to enable various Model class methods to work



30
31
32
# File 'lib/openc3/models/queue_model.rb', line 30

def self.get(name:, scope:)
  super("#{scope}__#{PRIMARY_KEY}", name: name)
end

.names(scope:) ⇒ Object



34
35
36
# File 'lib/openc3/models/queue_model.rb', line 34

def self.names(scope:)
  super("#{scope}__#{PRIMARY_KEY}")
end

.queue_command(name, command: nil, target_name: nil, cmd_name: nil, cmd_params: nil, validate: true, timeout: nil, username:, scope:) ⇒ Object

END NOTE

Raises:



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/openc3/models/queue_model.rb', line 43

def self.queue_command(name, command: nil, target_name: nil, cmd_name: nil, cmd_params: nil, validate: true, timeout: nil, username:, scope:)
  model = get_model(name: name, scope: scope)
  raise QueueError, "Queue '#{name}' not found in scope '#{scope}'" unless model

  if model.state != 'DISABLE'
    result = Store.zrevrange("#{scope}:#{name}", 0, 0, with_scores: true)
    if result.empty?
      id = 1.0
    else
      id = result[0][1].to_f + 1
    end

    # Build command data with support for both formats
    command_data = { username: username, timestamp: Time.now.to_nsec_from_epoch, validate: validate, timeout: timeout }
    if target_name && cmd_name
      # New format: store target_name, cmd_name, and cmd_params separately
      command_data[:target_name] = target_name
      command_data[:cmd_name] = cmd_name
      command_data[:cmd_params] = JSON.generate(cmd_params.as_json, allow_nan: true) if cmd_params
    elsif command
      # Legacy format: store command string for backwards compatibility
      command_data[:value] = command
    else
      raise QueueError, "Must provide either command string or target_name/cmd_name parameters"
    end

    Store.zadd("#{scope}:#{name}", id, command_data.to_json)
    model.notify(kind: 'command')
  else
    error_msg = command || "#{target_name} #{cmd_name}"
    raise QueueError, "Queue '#{name}' is disabled. Command '#{error_msg}' not queued."
  end
end

Instance Method Details

#as_json(*a) ⇒ Hash

Returns generated from the QueueModel.

Returns:

  • (Hash)

    generated from the QueueModel



100
101
102
103
104
105
106
107
# File 'lib/openc3/models/queue_model.rb', line 100

def as_json(*a)
  return {
    'name' => @name,
    'scope' => @scope,
    'state' => @state,
    'updated_at' => @updated_at
  }
end

#create(update: false, force: false, queued: false) ⇒ Object



89
90
91
92
93
94
95
96
97
# File 'lib/openc3/models/queue_model.rb', line 89

def create(update: false, force: false, queued: false)
  super(update: update, force: force, queued: queued)
  if update
    notify(kind: 'updated')
  else
    deploy()
    notify(kind: 'created')
  end
end

#create_microservice(topics:) ⇒ Object



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
# File 'lib/openc3/models/queue_model.rb', line 206

def create_microservice(topics:)
  # queue Microservice
  microservice = MicroserviceModel.new(
    name: @microservice_name,
    folder_name: nil,
    cmd: ['ruby', 'queue_microservice.rb', @microservice_name],
    work_dir: '/openc3/lib/openc3/microservices',
    options: [
      ["QUEUE_STATE", @state],
    ],
    topics: topics,
    target_names: [],
    plugin: nil,
    scope: @scope
  )
  microservice.create
end

#deployObject



224
225
226
227
228
229
# File 'lib/openc3/models/queue_model.rb', line 224

def deploy
  topics = ["#{@scope}__#{QueueTopic::PRIMARY_KEY}"]
  if MicroserviceModel.get_model(name: @microservice_name, scope: @scope).nil?
    create_microservice(topics: topics)
  end
end

#destroyObject

Delete the model from the Store



250
251
252
253
254
# File 'lib/openc3/models/queue_model.rb', line 250

def destroy
  undeploy()
  Store.zremrangebyrank("#{@scope}:#{@name}", 0, -1)
  super()
end

#insert_command(id, command_data) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/openc3/models/queue_model.rb', line 118

def insert_command(id, command_data)
  if @state == 'DISABLE'
    if command_data['value']
      command_name = command_data['value']
    else
      command_name = "#{command_data['target_name']} #{command_data['cmd_name']}"
    end
    raise QueueError, "Queue '#{@name}' is disabled. Command '#{command_name}' not queued."
  end

  unless id
    result = Store.zrevrange("#{@scope}:#{@name}", 0, 0, with_scores: true)
    if result.empty?
      id = 1.0
    else
      id = result[0][1].to_f + 1
    end
  end

  # Convert cmd_params values to JSON-safe format if present
  if command_data['cmd_params']
    command_data['cmd_params'] = JSON.generate(command_data['cmd_params'].as_json, allow_nan: true)
  end
  Store.zadd("#{@scope}:#{@name}", id, command_data.to_json)
  notify(kind: 'command')
end

#listObject



198
199
200
201
202
203
204
# File 'lib/openc3/models/queue_model.rb', line 198

def list
  return Store.zrange("#{@scope}:#{@name}", 0, -1, with_scores: true).map do |item|
    result = JSON.parse(item[0])
    result['id'] = item[1].to_f
    result
  end
end

#notify(kind:) ⇒ Object

Returns [] update the redis stream / queue topic that something has changed.

Returns:

  • update the redis stream / queue topic that something has changed



110
111
112
113
114
115
116
# File 'lib/openc3/models/queue_model.rb', line 110

def notify(kind:)
  notification = {
    'kind' => kind,
    'data' => JSON.generate(as_json, allow_nan: true),
  }
  QueueTopic.write_notification(notification, scope: @scope)
end

#remove_command(id = nil) ⇒ Object



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/openc3/models/queue_model.rb', line 165

def remove_command(id = nil)
  if @state == 'DISABLE'
    raise QueueError, "Queue '#{@name}' is disabled. Command not removed."
  end

  if id
    # Remove specific id
    result = Store.zrangebyscore("#{@scope}:#{@name}", id, id)
    if result.empty?
      return nil
    else
      Store.zremrangebyscore("#{@scope}:#{@name}", id, id)
      command_data = JSON.parse(result[0])
      command_data['id'] = id.to_f
      notify(kind: 'command')
      return command_data
    end
  else
    # Remove first element (lowest score)
    result = Store.zrange("#{@scope}:#{@name}", 0, 0, with_scores: true)
    if result.empty?
      return nil
    else
      score = result[0][1]
      Store.zremrangebyscore("#{@scope}:#{@name}", score, score)
      command_data = JSON.parse(result[0][0], allow_nan: true)
      command_data['id'] = score.to_f
      notify(kind: 'command')
      return command_data
    end
  end
end

#undeployObject



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
# File 'lib/openc3/models/queue_model.rb', line 231

def undeploy
  model = MicroserviceModel.get_model(name: @microservice_name, scope: @scope)
  if model
    # Let the frontend know that the microservice is shutting down
    # Custom event which matches the 'deployed' event in QueueMicroservice
    notification = {
      'kind' => 'undeployed',
      # name and updated_at fields are required for Event formatting
      'data' => JSON.generate({
        'name' => @microservice_name,
        'updated_at' => Time.now.to_nsec_from_epoch,
      }),
    }
    QueueTopic.write_notification(notification, scope: @scope)
    model.destroy
  end
end

#update_command(id:, command:, username:, validate: nil, timeout: nil) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# File 'lib/openc3/models/queue_model.rb', line 145

def update_command(id:, command:, username:, validate: nil, timeout: nil)
  if @state == 'DISABLE'
    raise QueueError, "Queue '#{@name}' is disabled. Command at id #{id} not updated."
  end

  # Check if command exists at the given id
  existing = Store.zrangebyscore("#{@scope}:#{@name}", id, id)
  if existing.empty?
    raise QueueError, "No command found at id #{id} in queue '#{@name}'"
  end

  # Remove the existing command and add the new one at the same id
  Store.zremrangebyscore("#{@scope}:#{@name}", id, id)
  command_data = { username: username, value: command, timestamp: Time.now.to_nsec_from_epoch }
  command_data[:validate] = validate unless validate.nil?
  command_data[:timeout] = timeout unless timeout.nil?
  Store.zadd("#{@scope}:#{@name}", id, command_data.to_json)
  notify(kind: 'command')
end