Class: Scjson::Engine::DocumentContext

Inherits:
Object
  • Object
show all
Defined in:
lib/scjson/engine/context.rb

Overview

Minimal document context and transition logic to support deterministic trace emission for simple charts. This is an iterative scaffold toward full SCXML semantics.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root, parent_link: nil, child_invoke_id: nil, base_dir: nil) ⇒ DocumentContext

Construct a context from a canonical scjson object.

Parameters:

  • root (Hash)

    Canonical scjson root map



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/scjson/engine/context.rb', line 47

def initialize(root, parent_link: nil, child_invoke_id: nil, base_dir: nil)
  @root = root
  @states = {}
  @parent = {}
  @parent_link = parent_link
  @child_invoke_id = child_invoke_id
  @base_dir = base_dir
  @tag_type = {}
  @history_shallow = {}
  @history_deep = {}
  index_states(@root)
  @configuration = initial_configuration
  @time = 0.0
  @timers = [] # array of {time: Float, name: String, data: Object, id?: String}
  @send_seq = 0
  @invocations = {} # id => {state: sid, node: inv_map, status: 'active'|'done'|'canceled'}
  @invocations_by_state = Hash.new { |h, k| h[k] = [] }
  @invoke_seq = 0
  @internal_queue = []
  @deferred_internal = []
  @defer_done = true
  # Schedule invocations for initial configuration
  schedule_invocations_for_entered(@configuration)
end

Instance Attribute Details

#configurationArray<String> (readonly)

Returns Active state configuration.

Returns:

  • (Array<String>)

    Active state configuration



24
25
26
# File 'lib/scjson/engine/context.rb', line 24

def configuration
  @configuration
end

#rootHash{String=>Object} (readonly)

Returns Canonical scjson root map.

Returns:

  • (Hash{String=>Object})

    Canonical scjson root map



22
23
24
# File 'lib/scjson/engine/context.rb', line 22

def root
  @root
end

Class Method Details

.from_file(input_path, xml: false, parent_link: nil, child_invoke_id: nil) ⇒ DocumentContext

Load a document and create a context.

Parameters:

  • input_path (String)

    Path to SCXML or SCJSON document

  • xml (Boolean) (defaults to: false)

    Treat the input as SCXML when true

Returns:



32
33
34
35
36
37
38
39
40
41
# File 'lib/scjson/engine/context.rb', line 32

def self.from_file(input_path, xml: false, parent_link: nil, child_invoke_id: nil)
  data = File.read(input_path)
  json = xml ? Scjson.xml_to_json(data) : data
  new(
    JSON.parse(json),
    parent_link: parent_link,
    child_invoke_id: child_invoke_id,
    base_dir: File.dirname(File.expand_path(input_path))
  )
end

Instance Method Details

#leaf_state_idsArray<String>

Compute the set of leaf state IDs for filtering.

Returns:

  • (Array<String>)

    Sorted list of leaf state IDs



76
77
78
79
80
81
82
83
# File 'lib/scjson/engine/context.rb', line 76

def leaf_state_ids
  leaves = []
  @states.each do |id, node|
    has_children = node.key?('state') || node.key?('parallel')
    leaves << id unless has_children
  end
  leaves.sort
end

#trace_initHash

Produce the initialization trace snapshot (step 0).

Returns:

  • (Hash)

    Trace record for initialization step



89
90
91
92
93
94
95
96
97
98
99
# File 'lib/scjson/engine/context.rb', line 89

def trace_init
  {
    'event' => nil,
    'firedTransitions' => [],
    'enteredStates' => @configuration.dup,
    'exitedStates' => [],
    'configuration' => @configuration.dup,
    'actionLog' => [],
    'datamodelDelta' => {}
  }
end

#trace_step(name:, data: nil) ⇒ Hash

Returns Trace record for this step.

Returns:

  • (Hash)

    Trace record for this step



107
108
109
110
111
112
113
114
115
116
117
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/scjson/engine/context.rb', line 107

def trace_step(name:, data: nil)
  event_obj = { 'name' => name, 'data' => data }
  fired = []
  exited = []
  entered = []
  action_log = []
  datamodel_delta = {}

  @data ||= {}
  @internal_queue ||= []
  # Inject any deferred internal events from previous step
  unless @deferred_internal.nil? || @deferred_internal.empty?
    @internal_queue = (@deferred_internal + @internal_queue)
    @deferred_internal.clear
  end
  # When deferring done.invoke, run any pending finalizers at the start of the next step
  if @defer_done
    a0, d0 = run_pending_finalizers
    action_log.concat(a0)
    datamodel_delta.merge!(d0)
  end
  @current_event_name = name
  @current_event_data = data

  # Process any pending internal events before external one (SCXML internal priority)
  0.upto(100) do
    break if @internal_queue.empty?
    ev = @internal_queue.shift
    if ev.is_a?(Hash)
      # run internal event to quiescence
      process_ev = ev
      internal_name = process_ev['name']
      internal_data = process_ev['data']
      # Use same microstep machinery
      # Inline handler mimicking process_event
      # Note: attributes entered/exited/fired accumulate into this step
      # Handle special invoke completion
      if internal_name == '__invoke_complete'
        iid = internal_data.is_a?(Hash) ? internal_data['invokeid'] : nil
        if iid
          a, d = finalize_invoke(iid, completed: true)
          action_log.concat(a)
          datamodel_delta.merge!(d)
          rec = @invocations[iid]
          order = rec && rec[:order] ? rec[:order] : 0
          (@pending_done_invoke ||= []) << { iid: iid, order: order }
        end
      else
        tx_set = select_transitions_for_event(internal_name)
        unless tx_set.empty?
          e1, x1, f1, a1, d1 = apply_transition_set(tx_set, cause: internal_name)
          entered.concat(e1)
          exited.concat(x1)
          fired.concat(f1)
          action_log.concat(a1)
          datamodel_delta.merge!(d1)
        end
        # Eventless to quiescence after internal
        0.upto(100) do
          tx0 = select_transitions_for_event(nil)
          break if tx0.empty?
          e2, x2, f2, a2, d2 = apply_transition_set(tx0, cause: nil)
          entered.concat(e2)
          exited.concat(x2)
          fired.concat(f2)
          action_log.concat(a2)
          datamodel_delta.merge!(d2)
        end
        enqueue_done_events
      end
      flush_pending_done_invoke
    end
  end

  # First, process one external-event transition (if any)
  process_event = lambda do |ev_name, ev_data|
    @current_event_name = ev_name
    @current_event_data = ev_data
    # Special internal control: invocation completion
    if ev_name == '__invoke_complete'
      iid = ev_data.is_a?(Hash) ? ev_data['invokeid'] : nil
      if iid
        a, d = finalize_invoke(iid, completed: true)
        action_log.concat(a)
        datamodel_delta.merge!(d)
        # buffer done.invoke events for ordered flushing
        rec = @invocations[iid]
        order = rec && rec[:order] ? rec[:order] : 0
        (@pending_done_invoke ||= []) << { iid: iid, order: order }
      end
      return
    end
    # Autoforward external events to active children that requested it
    begin
      if ev_name && !ev_name.to_s.start_with?('__') && !ev_name.to_s.start_with?('done.')
        @invocations.each do |iid, rec|
          next unless rec[:status] == 'active'
          inv_node = rec[:node]
          af = inv_node['autoforward']
          is_true = (af == true) || (af.is_a?(String) && af.to_s.downcase == 'true')
          if is_true && rec[:ctx]
            route_to_child(iid, ev_name.to_s, ev_data, 0.0)
          end
        end
      end
    rescue StandardError
      # ignore autoforward errors
    end
    loop do
      tx_set = select_transitions_for_event(ev_name)
      break if tx_set.empty?
      e1, x1, f1, a1, d1 = apply_transition_set(tx_set, cause: ev_name)
      entered.concat(e1)
      exited.concat(x1)
      fired.concat(f1)
      action_log.concat(a1)
      datamodel_delta.merge!(d1)
      # After a set, enqueue done.state events if any states completed
      enqueue_done_events
      flush_pending_done_invoke
      # After a set, process eventless transitions to quiescence
      0.upto(100) do
        tx0 = select_transitions_for_event(nil)
        break if tx0.empty?
        e2, x2, f2, a2, d2 = apply_transition_set(tx0, cause: nil)
        entered.concat(e2)
        exited.concat(x2)
        fired.concat(f2)
        action_log.concat(a2)
        datamodel_delta.merge!(d2)
        enqueue_done_events
        flush_pending_done_invoke
      end
    end
  end

  # Drain any pending internal events before handling the external event
  0.upto(100) do
    break if @internal_queue.empty?
    ev = @internal_queue.shift
    if ev.is_a?(Hash)
      process_event.call(ev['name'], ev['data'])
    else
      process_event.call(ev.to_s, nil)
    end
    flush_pending_done_invoke
  end

  process_event.call(name, data)

  # Then process internal events, FIFO
  0.upto(100) do
    break if @internal_queue.empty?
    ev = @internal_queue.shift
    if ev.is_a?(Hash)
      process_event.call(ev['name'], ev['data'])
    else
      process_event.call(ev.to_s, nil)
    end
    # After handling one internal event, flush any pending done.invoke for immediate processing
    flush_pending_done_invoke
  end

  {
    'event' => event_obj,
    'firedTransitions' => fired,
    'enteredStates' => entered,
    'exitedStates' => exited,
    'configuration' => @configuration.dup,
    'actionLog' => action_log,
    'datamodelDelta' => datamodel_delta
  }
end