module RailsToolViews
Registers trusted Rails views and orchestrates persistent, authorized interactions.
Constants
- Access
-
Policy and handler context populated by the runtime.
- Action
- Transition
-
Handler result containing persistent UI state, an optional agent flag and plain-text notice (at most 500 bytes) displayed for this action response.
- VERSION
Public Class Methods
# File lib/rails_tool_views/lifecycle.rb, line 12 def abandon(id, scope:, retain_until: nil) finish_surface(id, scope: scope, retain_until: retain_until, abandon: true) end
Explicitly abandons pending/failed continuation work before closing a view. In-flight or historically uncertain delivery is never abandoned implicitly.
# File lib/rails_tool_views/lifecycle.rb, line 6 def close(id, scope:, retain_until: nil) finish_surface(id, scope: scope, retain_until: retain_until, abandon: false) end
Closes a view after host authorization. Outstanding continuation work blocks closure. nil retain_until keeps data indefinitely; the first closure wins.
Source
# File lib/rails_tool_views/core.rb, line 291 def configuration @configuration ||= Configuration.new end
Returns the process-local configuration.
# File lib/rails_tool_views/core.rb, line 295 def configure yield configuration end
Yields configuration to the host initializer.
# File lib/rails_tool_views/runtime.rb, line 96 def deliver(id, scope:, adapter: configuration.agent_adapter, retry_failed: false) raise Error.new("DELIVERY_IN_TRANSACTION", status: 409) if AgentInteraction.connection.transaction_open? interaction = AgentInteraction.find_by(id: id) raise Error.new("NOT_FOUND", status: 404) unless interaction surface = restore(interaction.surface_id, scope: scope) claimed = false # Coordinate the claim with close/abandon/purge, using the same lock order # as actions. Never hold a database transaction during the adapter call. surface.with_lock do ensure_not_purged!(surface) component = compatible_component!(surface) component.authorize!(access(scope, :read, surface: surface, props: surface.props, context_ref: surface.context_ref)) interaction.with_lock do definition = component.actions.fetch(interaction.payload.fetch("action")) { raise Error.new("INCOMPATIBLE_COMPONENT", status: 422) } arguments = definition.schema.validate!(interaction.payload.fetch("values"), code: "INVALID_ARGUMENTS") request = access(scope, :action, surface: surface, props: surface.props, action: definition.key, arguments: arguments, context_ref: surface.context_ref) raise Error.new("NOT_ALLOWED", status: 403) unless definition.policy&.call(request) == true next if %w[completed skipped abandoned].include?(interaction.status) raise Error.new("SURFACE_CLOSED", status: 410) if surface.closed? if interaction.status == "delivering" && interaction.claimed_at && interaction.claimed_at > Time.current - configuration.delivery_lease next end next if interaction.status == "failed" && !retry_failed # Reclaiming a lease does not prove that the previous callback ended. # This durable flag cannot be cleared by a stale worker's completion. uncertain = interaction.delivery_uncertain? || interaction.status == "delivering" # A worker without an adapter must not turn committed work terminal; # the interaction stays as it is for a configured worker. raise Error.new("AGENT_NOT_CONFIGURED", status: 503) if adapter.nil? interaction.update!(status: "delivering", claimed_at: Time.current, attempts: interaction.attempts + 1, error_code: nil, delivery_uncertain: uncertain) claimed = true end end return interaction.reload unless claimed attempt = interaction.attempts failure = nil begin adapter.call(Data.freeze_deep(Data.normalize(interaction.payload)), delivery_key: interaction.delivery_key) rescue StandardError => error failure = error end # Compare-and-set fences both success and failure. The lease may expire # while the callback runs; its acknowledgment belongs only to its attempt. acknowledged = AgentInteraction.where(id: interaction.id, status: "delivering", attempts: attempt).update_all( status: failure ? "failed" : "completed", error_code: failure ? "AGENT_UNAVAILABLE" : nil, claimed_at: nil, updated_at: Time.current) if acknowledged == 1 metadata = { surface_id: interaction.surface_id, interaction_id: interaction.id } failure ? report(failure, "agent_failed", **metadata) : notify("agent_returned", **metadata) end interaction.reload end
The adapter must deduplicate by delivery_key. A crash after remote acceptance can leave a lease in delivering state; retry is explicit and keeps the key. Delivers a saved interaction after authorization; retry_failed explicitly retries failed delivery. Call only after the host transaction commits. Stale attempts cannot acknowledge a newer claim.
# File lib/rails_tool_views/runtime.rb, line 29 def dispatch(id, scope:, action:, arguments:, base_revision:, idempotency_key:, source_component: nil, target: nil) surface = restore(id, scope: scope) raise Error.new("INVALID_SOURCE") if source_component && source_component.to_s != surface.component_key raise Error.new("INVALID_TARGET") if target && target != surface.dom_id component = compatible_component!(surface) definition = component.actions.fetch(action.to_s) { raise Error.new("UNKNOWN_ACTION") } arguments = definition.schema.validate!(arguments, code: "INVALID_ARGUMENTS") raise Error.new("INVALID_REVISION") unless base_revision.is_a?(Integer) && base_revision.positive? idempotency_key = Data.identifier(idempotency_key, code: "INVALID_IDEMPOTENCY_KEY") request_digest = Data.digest(action: definition.key, arguments: arguments, base_revision: base_revision) result = nil replayed = false surface.with_lock do ensure_not_purged!(surface) compatible_component!(surface).authorize!(access(scope, :read, surface: surface, props: surface.props, context_ref: surface.context_ref)) request = access(scope, :action, surface: surface, props: surface.props, action: definition.key, arguments: arguments, context_ref: surface.context_ref) raise Error.new("NOT_ALLOWED", status: 403) unless definition.policy&.call(request) == true prior = ActionExecution.find_by(surface_id: surface.id, idempotency_key: idempotency_key) if prior # A non-binary collation could match a different key; only replay the # exact key, and keep the digest check as the second gate. raise Error.new("IDEMPOTENCY_CONFLICT", status: 409) unless prior.idempotency_key == idempotency_key && prior.request_digest == request_digest result = prior.result.symbolize_keys replayed = true next end raise Error.new("SURFACE_CLOSED", status: 410) if surface.closed? raise Error.new("CONFLICT", status: 409) unless surface.revision == base_revision if surface.action_executions.where("created_at >= ?", 1.minute.ago).count >= configuration.max_actions_per_minute raise Error.new("RATE_LIMITED", status: 429) end transition = definition.handler.call(request) raise Error.new("INVALID_TRANSITION", status: 422) unless transition.is_a?(Transition) && transition.state.is_a?(Hash) state = Data.bounded(transition.state) notice = normalize_notice(transition.notice) surface.update!(state: state, revision: base_revision + 1) result = { status: "completed", surface_id: surface.id, revision: surface.revision } result[:notice] = notice unless notice.nil? execution = ActionExecution.create!(surface: surface, actor_ref: scope.actor, action_key: definition.key, base_revision: base_revision, idempotency_key: idempotency_key, request_digest: request_digest, result: result) if transition.agent interaction = AgentInteraction.create!(surface: surface, action_execution: execution, payload: { type: "agent_interaction", surface_id: surface.id, action: definition.key, values: arguments, context_ref: surface.context_ref, revision: surface.revision }, status: configuration.agent_adapter ? "pending" : "skipped") result[:interaction_id] = interaction.id execution.update!(result: result) end end notify("action.executed", surface_id: surface.id, revision: result[:revision], action: definition.key, replayed: replayed) result rescue ActiveRecord::StaleObjectError, ActiveRecord::TransactionRollbackError, ActiveRecord::LockWaitTimeout # The database rolled the whole action back (deadlock, serialization failure, # lock timeout); retrying with the same key is safe. raise_action_conflict! rescue ActiveRecord::StatementInvalid => error raise_action_conflict! if error.cause.class.name.include?("Busy") || error.cause.class.name.include?("Locked") raise rescue Error => error notify(error.code == "CONFLICT" ? "action.conflict" : "action.rejected", code: error.code) raise end
Commits an authorized action and returns its receipt. Matching retries replay without executing the handler.
# File lib/rails_tool_views/runtime.rb, line 5 def present(key, props:, scope:, context: nil, correlation: nil) present_surface(key, props, scope, context, correlation) rescue Error => error notify("presentation.rejected", code: error.code) raise end
Validates and authorizes props, then returns a persisted Surface. Correlation replays the original presentation.
# File lib/rails_tool_views/lifecycle.rb, line 20 def purge_closed(scope:, closed_before:, batch_size: 100, dry_run: true, after: nil) check_scope!(scope) valid_time = closed_before.is_a?(Time) || closed_before.is_a?(ActiveSupport::TimeWithZone) unless valid_time && closed_before <= Time.current && batch_size.is_a?(Integer) && batch_size.between?(1, 1000) && [true, false].any? { |v| dry_run.equal?(v) } raise Error.new("INVALID_RETENTION_REQUEST") end position = retention_position(after) unless after.nil? policy = configuration.retention_policy raise Error.new("NOT_ALLOWED", status: 403) unless policy.respond_to?(:call) now = Time.current relation = Surface.where(actor_ref: scope.actor, tenant_ref: scope.tenant, purged_at: nil) .where("closed_at < ? AND retain_until <= ?", closed_before, now) # Keyset paging only narrows the scoped query; a forged cursor can skip # rows but never reach another scope. relation = relation.where("closed_at > ? OR (closed_at = ? AND id > ?)", position[0], position[0], position[1]) if position rows = relation.order(:closed_at, :id).limit(batch_size).pluck(:id, :closed_at) counts = { examined: 0, eligible: 0, purged: 0, protected: 0, dry_run: dry_run, next_after: rows.length == batch_size ? retention_cursor(*rows.last) : nil } rows.each do |id, _closed_at| surface = Surface.find_by(id: id) next unless surface surface.with_lock do counts[:examined] += 1 eligible = exact_match?(surface, actor_ref: scope.actor, tenant_ref: scope.tenant) && !surface.purged? && surface.closed? && surface.closed_at < closed_before && surface.retain_until && surface.retain_until <= now if eligible request = access(scope, :purge, surface: surface, props: surface.props, context_ref: surface.context_ref) eligible = policy.call(request) == true && !protected_interactions?(surface, abandon: false) end unless eligible counts[:protected] += 1 next end counts[:eligible] += 1 next if dry_run # The Surface lock excludes action commits, delivery claims and other # cleanup workers. Only known terminal children are removed together. surface.agent_interactions.delete_all surface.action_executions.delete_all surface.update!(props: {}, state: {}, context_ref: nil, purged_at: now) counts[:purged] += 1 end end counts end
Scrubs eligible closed payloads in one bounded batch, preserving replay tombstones. Requires an explicit scope, cutoff and host retention policy. Defaults to a read-only preview. Each applied Surface commits atomically. Pass the returned next_after as after: to continue past this batch.
# File lib/rails_tool_views/runtime.rb, line 155 def reconcile_delivery(id, scope:, outcome:) check_scope!(scope) raise Error.new("INVALID_RECONCILIATION") unless %i[completed failed].include?(outcome) policy = configuration.reconciliation_policy raise Error.new("NOT_ALLOWED", status: 403) unless policy.respond_to?(:call) interaction = AgentInteraction.find_by(id: id) # Ownership, not component policy: an obsolete component's history stays resolvable. surface = interaction && Surface.find_by(id: interaction.surface_id, actor_ref: scope.actor, tenant_ref: scope.tenant) raise Error.new("NOT_FOUND", status: 404) unless surface && exact_match?(surface, actor_ref: scope.actor, tenant_ref: scope.tenant) reconciled = false surface.with_lock do ensure_not_purged!(surface) interaction.with_lock do request = access(scope, :reconcile, surface: surface, props: surface.props, action: interaction.payload["action"], context_ref: surface.context_ref) raise Error.new("NOT_ALLOWED", status: 403) unless policy.call(request) == true stale = interaction.status == "delivering" if stale && interaction.claimed_at && interaction.claimed_at > Time.current - configuration.delivery_lease raise Error.new("DELIVERY_ACTIVE", status: 409) end unless stale || interaction.delivery_uncertain? next if interaction.status == outcome.to_s raise Error.new("RECONCILIATION_CONFLICT", status: 409) end # Attempts stay unchanged, so the acknowledgment fence still rejects # a callback that outlived its lease. interaction.update!(status: outcome.to_s, error_code: outcome == :failed ? "AGENT_UNAVAILABLE" : nil, claimed_at: nil, delivery_uncertain: false) reconciled = true end end notify("agent_reconciled", surface_id: surface.id, interaction_id: interaction.id, outcome: outcome.to_s) if reconciled interaction.reload end
Records the hostโs attested outcome for an uncertain delivery, or for a delivering row whose lease expired: :completed when the hostโs durable deduplication record shows the effect, :failed when it shows none. The host must also know that no attempt is still running. Authorized by configuration.reconciliation_policy; a fresh lease is never overridden.
Source
# File lib/rails_tool_views/core.rb, line 299 def register(key, **options) registry.register(key, **options) end
Registers a component; duplicate keys raise DUPLICATE_COMPONENT.
Source
# File lib/rails_tool_views/core.rb, line 287 def registry @registry ||= Registry.new end
Returns the process-local component registry.
# File lib/rails_tool_views/runtime.rb, line 192 def render(surface, view_context:, scope:, error: nil, notice: nil) # Never trust an already-loaded object as an authorization decision. surface = restore(surface.id, scope: scope) component = compatible_component!(surface) view_context.render(partial: "rails_tool_views/surfaces/surface", formats: [:html], locals: { surface: surface, definition: component, error: error, notice: normalize_notice(notice) }) rescue Error => failure view_context.render(partial: "rails_tool_views/surfaces/error", formats: [:html], locals: { error: failure }) end
Renders the trusted component after fresh authorization. Optional notice is plain-text response feedback; it never changes the Surface snapshot.
Source
# File lib/rails_tool_views/core.rb, line 307 def reset! @registry, @configuration = Registry.new, Configuration.new end
Clears definitions and configuration; intended for isolated tests.
Source
# File lib/rails_tool_views/core.rb, line 303 def reset_registry! @registry = Registry.new end
Clears definitions while retaining configuration; use in Rails reload hooks.
Source
# File lib/rails_tool_views/runtime.rb, line 13 def restore(id, scope:) check_scope!(scope) surface = Surface.find_by(id: id, actor_ref: scope.actor, tenant_ref: scope.tenant) # A database collation that is not binary (for example a case-insensitive # MySQL or PostgreSQL collation) can match a stored actor, tenant or id # that merely compares equal to the requested one. Only a byte-exact # match may stand in for this scope's Surface, or a lookup could disclose # another actor's or tenant's record. raise Error.new("NOT_FOUND", status: 404) unless surface && exact_match?(surface, id: id.to_s, actor_ref: scope.actor, tenant_ref: scope.tenant) ensure_not_purged!(surface) component = compatible_component!(surface) component.authorize!(access(scope, :read, surface: surface, props: surface.props, context_ref: surface.context_ref)) surface end
Returns a compatible Surface after checking scope and current read policy.