Class: SolidObjects::Executor

Inherits:
Object
  • Object
show all
Defined in:
lib/solid_objects/executor.rb,
sig/generated/lib/solid_objects/executor.rbs

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(activation:, message:) ⇒ Executor

Returns a new instance of Executor.

RBS:

  • (activation: Activation, message: Message) -> void

Parameters:



9
10
11
12
# File 'lib/solid_objects/executor.rb', line 9

def initialize(activation:, message:)
  @activation = activation
  @message = message
end

Instance Attribute Details

#activationObject (readonly)

Returns the value of attribute activation.

Returns:

  • (Object)


54
55
56
# File 'lib/solid_objects/executor.rb', line 54

def activation
  @activation
end

#messageObject (readonly)

Returns the value of attribute message.

Returns:

  • (Object)


54
55
56
# File 'lib/solid_objects/executor.rb', line 54

def message
  @message
end

Instance Method Details

#actorActor

RBS:

  • () -> Actor

Returns:



57
58
59
# File 'lib/solid_objects/executor.rb', line 57

def actor
  activation.actor
end

#callBoolean

RBS:

  • () -> bool

Returns:

  • (Boolean)


15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/solid_objects/executor.rb', line 15

def call
  state_before = actor.state.to_h
  observables_before = actor.observable_values
  message_context = MessageContext.new(
    id: message.id,
    attempt: message.attempt_count,
    enqueued_at: message.enqueued_at,
    idempotency_key: message.idempotency_key,
    request_id: message.request_id
  )

  SolidObjects.instrument(:"message.started", **instrumentation_payload)
  result = invoke_actor(message_context)
  observable_changes = changed_observables(observables_before, actor.observable_values)
  state_after = actor.state.to_h
  ensure_query_did_not_mutate_state!(state_before, state_after)
  complete(
    result,
    observable_changes,
    state_after:,
    state_changed: state_after != state_before
  )
  true
rescue LostActivation
  raise
rescue Rejected => rejection
  activation.restore_state(state_before) if state_before
  actor.discard_intents
  reject_message(rejection)
  false
rescue => error
  activation.restore_state(state_before) if state_before
  actor.discard_intents
  fail_message(error)
  false
end

#changed_observables(before, after) ⇒ Hash[String, untyped]

RBS:

  • (Hash[String, untyped], Hash[String, untyped]) -> Hash[String, untyped]

Parameters:

  • (Hash[String, untyped])
  • (Hash[String, untyped])

Returns:

  • (Hash[String, untyped])


78
79
80
81
82
# File 'lib/solid_objects/executor.rb', line 78

def changed_observables(before, after)
  after.each_with_object({}) do |(name, value), changes|
    changes[name] = value unless before[name] == value
  end
end

#complete(result, observable_changes, state_after:, state_changed:) ⇒ void

This method returns an undefined value.

RBS:

  • (untyped, Hash[String, untyped], state_after: Hash[String, untyped], state_changed: bool) -> void

Parameters:

  • (Object)
  • (Hash[String, untyped])
  • state_after: (Hash[String, untyped])
  • state_changed: (Boolean)


85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
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
# File 'lib/solid_objects/executor.rb', line 85

def complete(result, observable_changes, state_after:, state_changed:)
  dumped_state = Serialization.dump_with_byte_size(
    state_after,
    max_bytes: SolidObjects.configuration.max_state_bytes
  )
  serialized_result = Serialization.dump(
    (message.delivery_mode == "sync") ? result : nil,
    max_bytes: SolidObjects.configuration.max_result_bytes
  )
  effect_intents = actor.drain_effect_intents
  commit_action_intents = actor.drain_commit_action_intents
  reminder_intents = actor.drain_reminder_intents
  outbound_message_intents = actor.drain_outbound_message_intents
  enqueued_effects = []
  moved_reminders = []

  activation.lease.fenced_transaction do |instance|
    # A busy database makes the adapter retry this whole block, so an
    # attempt that was rolled back must not leave its work in the lists the
    # reporting below reads. Each attempt starts from empty.
    enqueued_effects.clear
    moved_reminders.clear
    claimed_message = matching_claim!
    locked_message = Message.lock.find(message.id)
    execute_commit_actions(commit_action_intents)
    instance.update!(
      state: dumped_state.value,
      state_version: actor.class.state_version,
      state_revision: locked_message.sequence,
      last_used_at: SolidObjects.database_adapter.database_now
    )
    locked_message.update!(
      result: serialized_result,
      error: nil,
      completed_at: SolidObjects.database_adapter.database_now
    )
    enqueued_effects.concat(
      enqueue_effects(message: locked_message, instance:, intents: effect_intents)
    )
    moved_reminders.concat(schedule_reminders(instance, reminder_intents))
    enqueued_effects.concat(
      enqueue_actor_messages(message: locked_message, instance:, intents: outbound_message_intents)
    )
    enqueue_broadcasts(
      message: locked_message,
      instance:,
      observable_changes:,
      state_changed:
    )
    claimed_message.destroy!
  end

  observable_changes.each_key do |observable_name|
    SolidObjects.instrument_after_commit(
      :"broadcast.enqueued",
      **instrumentation_payload,
      observable_name:
    )
  end
  moved_reminders.each do |moved|
    SolidObjects.instrument_after_commit(:"reminder.replaced", **moved)
  end
  enqueued_effects.each do |effect|
    SolidObjects.instrument_after_commit(
      :"effect.enqueued",
      effect_id: effect.effect_id,
      effect_name: effect.name,
      message_id: effect.message_id,
      actor_type: message.actor_type,
      actor_id: message.actor_id
    )
  end
  report_large_state(dumped_state.byte_size)
  SolidObjects.instrument_after_commit(:"message.completed", **instrumentation_payload)
  SolidObjects.wake_up.signal
end

#create_dead_letter(message:, error_details:, now:) ⇒ DeadLetter

RBS:

  • (message: Message, error_details: Hash[String, untyped], now: Time) -> DeadLetter

Parameters:

  • message: (Message)
  • error_details: (Hash[String, untyped])
  • now: (Time)

Returns:



443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'lib/solid_objects/executor.rb', line 443

def create_dead_letter(message:, error_details:, now:)
  DeadLetter.create!(
    message:,
    instance: message.instance,
    actor_type: message.actor_type,
    actor_id: message.actor_id,
    operation: message.operation,
    arguments: message.arguments,
    attempts: message.attempt_count,
    exception_class: error_details.fetch("class"),
    exception_message: error_details.fetch("message"),
    backtrace: error_details.fetch("backtrace"),
    first_failed_at: message.last_failed_at || now,
    last_failed_at: now
  )
end

#enqueue_actor_messages(message:, instance:, intents:) ⇒ Array[Effect]

RBS:

  • (message: Message, instance: Instance, intents: Array[Actor::OutboundMessageIntent]) -> Array[Effect]

Parameters:

Returns:



295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/solid_objects/executor.rb', line 295

def enqueue_actor_messages(message:, instance:, intents:)
  intents.map do |intent|
    Effect.create!(
      message:,
      instance:,
      effect_id: SecureRandom.uuid,
      name: EffectExecutor::ACTOR_MESSAGE_EFFECT,
      arguments: {
        "actor_type" => intent.actor_type,
        "actor_id" => intent.actor_id,
        "operation" => intent.operation,
        "arguments" => intent.arguments,
        "available_at" => intent.available_at&.iso8601(6),
        "idempotency_key" => intent.idempotency_key
      },
      status: "pending",
      max_attempts: SolidObjects.configuration.max_attempts,
      available_at: SolidObjects.database_adapter.database_now
    )
  end
end

#enqueue_broadcasts(message:, instance:, observable_changes:, state_changed:) ⇒ void

This method returns an undefined value.

RBS:

  • (message: Message, instance: Instance, observable_changes: Hash[String, untyped], state_changed: bool) -> void

Parameters:

  • message: (Message)
  • instance: (Instance)
  • observable_changes: (Hash[String, untyped])
  • state_changed: (Boolean)


318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/solid_objects/executor.rb', line 318

def enqueue_broadcasts(message:, instance:, observable_changes:, state_changed:)
  broadcasts = observable_changes
  if broadcasts.empty? && state_changed && payload_broadcasts?
    broadcasts = { PayloadBroadcast::REVISION_OBSERVABLE => {} }
  end

  broadcasts.each do |observable_name, value|
    stored_value = if observable_name != PayloadBroadcast::REVISION_OBSERVABLE &&
        actor.class.definition.broadcasts_observable_value?(observable_name)
      value
    else
      {}
    end
    Broadcast.create!(
      message:,
      instance:,
      broadcast_id: SecureRandom.uuid,
      observable_name:,
      value: stored_value,
      state_version: actor.class.state_version,
      activation_generation: activation.lease.generation,
      status: "pending",
      available_at: SolidObjects.database_adapter.database_now
    )
  end
end

#enqueue_effects(message:, instance:, intents:) ⇒ Array[Effect]

RBS:

  • (message: Message, instance: Instance, intents: Array[Actor::EffectIntent]) -> Array[Effect]

Parameters:

Returns:



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/solid_objects/executor.rb', line 229

def enqueue_effects(message:, instance:, intents:)
  intents.map do |intent|
    Effect.create!(
      message:,
      instance:,
      effect_id: SecureRandom.uuid,
      name: intent.name,
      arguments: intent.arguments,
      success_operation: intent.success_operation,
      failure_operation: intent.failure_operation,
      status: "pending",
      max_attempts: SolidObjects.configuration.max_attempts,
      available_at: SolidObjects.database_adapter.database_now
    )
  end
end

#ensure_application_database_is_shared!void

This method returns an undefined value.

RBS:

  • () -> void



218
219
220
221
222
223
224
225
226
# File 'lib/solid_objects/executor.rb', line 218

def ensure_application_database_is_shared!
  return if SolidObjects::Record.connection_pool.equal?(ActiveRecord::Base.connection_pool)

  raise CommitActionUnavailable.new(
    actor_type: message.actor_type,
    actor_id: message.actor_id,
    operation: message.operation
  )
end

#ensure_query_did_not_mutate_state!(state_before, state_after) ⇒ void

This method returns an undefined value.

RBS:

  • (Hash[String, untyped], Hash[String, untyped]) -> void

Parameters:

  • (Hash[String, untyped])
  • (Hash[String, untyped])


69
70
71
72
73
74
75
# File 'lib/solid_objects/executor.rb', line 69

def ensure_query_did_not_mutate_state!(state_before, state_after)
  return unless message.delivery_mode == "sync"
  return unless actor.class.definition.queries.key?(message.operation.to_sym)
  return if state_after == state_before

  raise InvalidActor, "query #{message.operation.inspect} mutated actor state"
end

#execute_commit_action(intent:, handler:, context:) ⇒ Object

RBS:

  • (intent: Actor::CommitActionIntent, handler: Proc, context: CommitActionContext) -> untyped

Parameters:

Returns:

  • (Object)


194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/solid_objects/executor.rb', line 194

def execute_commit_action(intent:, handler:, context:)
  payload = {
    commit_action_name: intent.name,
    message_id: message.id,
    request_id: message.request_id,
    actor_type: message.actor_type,
    actor_id: message.actor_id,
    activation_generation: activation.lease.generation
  }
  SolidObjects.instrument(:"commit_action.started", **payload)
  handler.call(intent.arguments, context).tap do
    SolidObjects.instrument(:"commit_action.completed", **payload)
  end
rescue => error
  SolidObjects.instrument(
    :"commit_action.failed",
    **payload,
    error_class: error.class.name,
    error_message: error.message
  )
  raise
end

#execute_commit_actions(intents) ⇒ void

This method returns an undefined value.

RBS:

  • (Array[Actor::CommitActionIntent]) -> void

Parameters:



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/solid_objects/executor.rb', line 177

def execute_commit_actions(intents)
  ensure_application_database_is_shared! if intents.any?
  context = CommitActionContext.new(
    message_id: message.id,
    request_id: message.request_id,
    actor_type: message.actor_type,
    actor_id: message.actor_id,
    activation_generation: activation.lease.generation
  )

  intents.each do |intent|
    handler = SolidObjects.commit_action_registry.fetch(intent.name)
    execute_commit_action(intent:, handler:, context:)
  end
end

#fail_message(error) ⇒ void

This method returns an undefined value.

RBS:

  • (Exception) -> void

Parameters:

  • (Exception)


351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'lib/solid_objects/executor.rb', line 351

def fail_message(error)
  error_details = serialized_error(error)
  dead = false

  activation.lease.fenced_transaction do
    claimed_message = matching_claim!
    locked_message = Message.lock.find(message.id)
    now = SolidObjects.database_adapter.database_now
    locked_message.update!(error: error_details, last_failed_at: now)
    claimed_message.destroy!

    if error.is_a?(NonRetryableError) ||
        locked_message.attempt_count >= locked_message.max_attempts
      create_dead_letter(message: locked_message, error_details:, now:)
      dead = true
    else
      ReadyMessage.create!(
        message: locked_message,
        instance: locked_message.instance,
        sequence: locked_message.sequence,
        available_at: now + SolidObjects.configuration.retry_delay.call(locked_message.attempt_count)
      )
    end
  end

  SolidObjects.instrument_after_commit(
    :"message.failed",
    **instrumentation_payload,
    error_class: error.class.name,
    dead:
  )
  SolidObjects.wake_up.signal
end

#instrumentation_payloadHash[Symbol, untyped]

RBS:

  • () -> Hash[Symbol, untyped]

Returns:

  • (Hash[Symbol, untyped])


461
462
463
464
465
466
467
468
469
470
# File 'lib/solid_objects/executor.rb', line 461

def instrumentation_payload
  {
    message_id: message.id,
    actor_type: message.actor_type,
    actor_id: message.actor_id,
    sequence: message.sequence,
    attempt: message.attempt_count,
    request_id: message.request_id
  }
end

#invoke_actor(message_context) ⇒ Object

RBS:

  • (MessageContext) -> untyped

Parameters:

Returns:

  • (Object)


62
63
64
65
66
# File 'lib/solid_objects/executor.rb', line 62

def invoke_actor(message_context)
  Context.with(actor:, message: message_context) do
    actor.invoke(message.operation, message.arguments)
  end
end

#matching_claim!ClaimedMessage

RBS:

  • () -> ClaimedMessage

Returns:



420
421
422
423
424
425
426
427
428
429
# File 'lib/solid_objects/executor.rb', line 420

def matching_claim!
  ClaimedMessage.lock.find_by!(
    message_id: message.id,
    process_id: activation.lease.owner_id,
    activation_token: activation.lease.activation_token,
    activation_generation: activation.lease.generation
  )
rescue ActiveRecord::RecordNotFound
  raise LostActivation, "message claim changed"
end

#moved_reminder_payload(reminder, previous_run_at) ⇒ Hash[Symbol, untyped]?

Arguments are omitted deliberately: a reminder carries application data and this event exists to be logged.

RBS:

  • (Reminder, Time?) -> Hash[Symbol, untyped]?

Parameters:

Returns:

  • (Hash[Symbol, untyped], nil)


281
282
283
284
285
286
287
288
289
290
291
292
# File 'lib/solid_objects/executor.rb', line 281

def moved_reminder_payload(reminder, previous_run_at)
  return nil unless previous_run_at
  return nil if previous_run_at == reminder.next_run_at

  {
    actor_type: reminder.actor_type,
    actor_id: reminder.actor_id,
    name: reminder.name,
    previous_run_at:,
    next_run_at: reminder.next_run_at
  }
end

#payload_broadcasts?Boolean

RBS:

  • () -> bool

Returns:

  • (Boolean)


346
347
348
# File 'lib/solid_objects/executor.rb', line 346

def payload_broadcasts?
  actor.class.definition.payload_broadcasts.any?
end

#reject_message(rejection) ⇒ void

This method returns an undefined value.

RBS:

  • (Rejected) -> void

Parameters:



386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/solid_objects/executor.rb', line 386

def reject_message(rejection)
  rejection_data = Serialization.dump(
    {
      "code" => rejection.code,
      "message" => rejection.message.to_s.byteslice(0, 8_192),
      "details" => rejection.details
    },
    max_bytes: SolidObjects.configuration.max_result_bytes
  )

  activation.lease.fenced_transaction do |instance|
    claimed_message = matching_claim!
    locked_message = Message.lock.find(message.id)
    now = SolidObjects.database_adapter.database_now
    instance.update!(last_used_at: now)
    locked_message.update!(
      result: nil,
      rejection: rejection_data,
      error: nil,
      rejected_at: now,
      completed_at: now
    )
    claimed_message.destroy!
  end

  SolidObjects.instrument_after_commit(
    :"message.rejected",
    **instrumentation_payload,
    code: rejection.code
  )
  SolidObjects.wake_up.signal
end

#report_large_state(byte_count) ⇒ void

This method returns an undefined value.

RBS:

  • (Integer) -> void

Parameters:

  • (Integer)


163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/solid_objects/executor.rb', line 163

def report_large_state(byte_count)
  threshold = SolidObjects.configuration.warn_state_bytes
  return if byte_count <= threshold

  SolidObjects.instrument_after_commit(
    :"state.large",
    actor_type: message.actor_type,
    actor_id: message.actor_id,
    byte_count:,
    threshold_bytes: threshold
  )
end

#schedule_reminders(instance, intents) ⇒ Array[Hash[Symbol, untyped]]

A reminder is one named alarm per actor, so scheduling a name that is already armed moves it rather than adding a second. Without a key that name is the operation, so an actor arming a reminder per queued item keeps only the last; passing schedule a key gives each item its own name and so its own alarm. Moves are returned rather than reported here, so the report happens after the turn commits. A rolled back turn would otherwise announce an alarm that never moved, which is the opposite of the visibility this event exists to provide.

RBS:

  • (Instance, Array[Actor::ReminderIntent]) -> Array[Hash[Symbol, untyped]]

Parameters:

Returns:

  • (Array[Hash[Symbol, untyped]])


256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/solid_objects/executor.rb', line 256

def schedule_reminders(instance, intents)
  intents.filter_map do |intent|
    reminder = Reminder.find_or_initialize_by(instance:, name: intent.name)
    previous_run_at = reminder.next_run_at
    reminder.assign_attributes(
      actor_type: instance.actor_type,
      actor_id: instance.actor_id,
      operation: intent.operation,
      arguments: intent.arguments,
      next_run_at: intent.at,
      interval_seconds: intent.interval_seconds,
      missed_policy: intent.missed_policy,
      status: "scheduled",
      claimed_by: nil,
      claimed_at: nil
    )
    moved = moved_reminder_payload(reminder, previous_run_at)
    reminder.save!
    moved
  end
end

#serialized_error(error) ⇒ Hash[String, untyped]

RBS:

  • (Exception) -> Hash[String, untyped]

Parameters:

  • (Exception)

Returns:

  • (Hash[String, untyped])


432
433
434
435
436
437
438
439
440
# File 'lib/solid_objects/executor.rb', line 432

def serialized_error(error)
  Serialization.dump(
    {
      "class" => error.class.name,
      "message" => error.message.to_s.byteslice(0, 8_192),
      "backtrace" => Array(error.backtrace).first(50)
    }
  )
end