Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Make it possible to create/change Events adapte
Damian Legawiec57d248379269
diff --git a/core/app/models/spree/events.rb b/core/app/models/spree/events.rbindex 668d4c0f04..e6d0262f92 100644--- a/core/app/models/spree/events.rb+++ b/core/app/models/spree/events.rb@@ -86,9 +86,12 @@ module Spree# Get the adapter instance#- # @return [Spree::Events::Adapters::ActiveSupportNotifications]+ # The adapter class can be configured via Spree.events_adapter_class+ # Default: Spree::Events::Adapters::ActiveSupportNotifications+ #+ # @return [Object] the configured adapter instancedef adapter- @adapter ||= Adapters::ActiveSupportNotifications.new(registry)+ @adapter ||= Spree.events_adapter_class.new(registry)end# Activate the event system (called during Rails initialization)diff --git a/core/app/models/spree/events/adapters/active_support_notifications.rb b/core/app/models/spree/events/adapters/active_support_notifications.rbindex f5afbc9581..3138c961be 100644--- a/core/app/models/spree/events/adapters/active_support_notifications.rb+++ b/core/app/models/spree/events/adapters/active_support_notifications.rb@@ -14,13 +14,11 @@ module Spree# adapter = ActiveSupportNotifications.new(registry)# adapter.publish('order.complete', { id: 1 })#- class ActiveSupportNotifications+ class ActiveSupportNotifications < BaseNAMESPACE = 'spree'- attr_reader :registry-def initialize(registry)- @registry = registry+ super@as_subscription = nil@mutex = Mutex.newend@@ -32,12 +30,7 @@ module Spree# @param metadata [Hash] Additional metadata# @return [Spree::Event] The published eventdef publish(event_name, payload, metadata = {})- event = Spree::Event.new(- name: event_name,- payload: payload,- metadata: metadata- )-+ event = build_event(event_name, payload, metadata)instrument_name = namespaced_event(event_name)::ActiveSupport::Notifications.instrument(instrument_name, event: event) do@@ -113,54 +106,6 @@ module Spreeendend- def invoke_subscribers(event)- # Check if events are enabled (can be disabled via Spree::Events.disable)- return unless Spree::Events.enabled?-- subscriptions = registry.subscriptions_for(event.name)-- subscriptions.each do |subscription|- invoke_subscriber(subscription.subscriber, event, subscription.options)- rescue StandardError => e- handle_subscriber_error(e, event, subscription)- end- end-- def invoke_subscriber(subscriber, event, options)- async = options.fetch(:async, true)-- if subscriber.is_a?(Proc)- # Block subscribers run synchronously- subscriber.call(event)- elsif subscriber.respond_to?(:call)- # Callable objects (including subscriber instances)- if async && defined?(Spree::Events::SubscriberJob)- Spree::Events::SubscriberJob.perform_later(subscriber.name, event.to_h)- else- subscriber.call(event)- end- elsif subscriber.is_a?(Class) && subscriber < Spree::Subscriber- # Subscriber classes- if async && defined?(Spree::Events::SubscriberJob)- Spree::Events::SubscriberJob.perform_later(subscriber.name, event.to_h)- else- subscriber.new.call(event)- end- else- raise ArgumentError, "Invalid subscriber: #{subscriber.inspect}. Must be a Proc, callable, or Spree::Subscriber subclass."- end- end-- def handle_subscriber_error(error, event, subscription)- Rails.error.report(error, context: {- event_name: event.name,- subscriber: subscription.subscriber.to_s,- event_id: event.metadata['event_id']- })-- # Re-raise in development/test for visibility- raise if Rails.env.development? || Rails.env.test?- endendendenddiff --git a/core/app/models/spree/events/adapters/base.rb b/core/app/models/spree/events/adapters/base.rbnew file mode 100644index 0000000000..3fec86149c--- /dev/null+++ b/core/app/models/spree/events/adapters/base.rb@@ -0,0 +1,193 @@+# frozen_string_literal: true++module Spree+ module Events+ module Adapters+ # Base class for event adapters.+ #+ # Adapters are responsible for the actual publishing and subscription+ # management of events. The default adapter uses ActiveSupport::Notifications,+ # but you can create custom adapters for other backends like Kafka, RabbitMQ,+ # or Redis Pub/Sub.+ #+ # @example Creating a custom adapter+ # class MyApp::Events::KafkaAdapter < Spree::Events::Adapters::Base+ # def publish(event_name, payload, metadata = {})+ # event = Spree::Event.new(name: event_name, payload: payload, metadata: metadata)+ # kafka_producer.produce(event.to_json, topic: event_name)+ # event+ # end+ #+ # def activate!+ # @kafka_producer = Kafka.new.producer+ # end+ #+ # def deactivate!+ # @kafka_producer&.shutdown+ # end+ # end+ #+ # @example Configuring Spree to use your adapter+ # # config/initializers/spree.rb+ # Spree.events_adapter_class = 'MyApp::Events::KafkaAdapter'+ #+ class Base+ attr_reader :registry++ # Initialize the adapter with a registry.+ #+ # @param registry [Spree::Events::Registry] the subscription registry+ def initialize(registry)+ @registry = registry+ end++ # Publish an event to all matching subscribers.+ #+ # @param event_name [String] the event name (e.g., 'order.complete')+ # @param payload [Hash] the event payload (should be serializable)+ # @param metadata [Hash] additional metadata for the event+ # @return [Spree::Event] the published event+ #+ # @example+ # adapter.publish('order.complete', order.serializable_hash, { user_id: 1 })+ #+ def publish(event_name, payload, metadata = {})+ raise NotImplementedError, "#{self.class}#publish must be implemented"+ end++ # Subscribe to an event pattern.+ #+ # This method should register the subscriber in the registry.+ # The adapter is responsible for ensuring events are routed to+ # matching subscribers.+ #+ # @param pattern [String] event pattern (supports wildcards like 'order.*')+ # @param subscriber [Class, Proc] the subscriber class or callable+ # @param options [Hash] subscription options+ # @option options [Boolean] :async (true) whether to run async via ActiveJob+ #+ # @example+ # adapter.subscribe('order.complete', MySubscriber)+ # adapter.subscribe('order.*', AuditLogger, async: false)+ #+ def subscribe(pattern, subscriber, options = {})+ raise NotImplementedError, "#{self.class}#subscribe must be implemented"+ end++ # Unsubscribe from an event pattern.+ #+ # @param pattern [String] event pattern+ # @param subscriber [Class, Proc] the subscriber to remove+ # @return [Boolean] true if removed, false if not found+ #+ def unsubscribe(pattern, subscriber)+ raise NotImplementedError, "#{self.class}#unsubscribe must be implemented"+ end++ # Activate the adapter.+ #+ # Called during Rails initialization. Use this to set up connections,+ # start consumers, or perform any initialization needed.+ #+ def activate!+ raise NotImplementedError, "#{self.class}#activate! must be implemented"+ end++ # Deactivate the adapter.+ #+ # Called during shutdown or when resetting the event system.+ # Use this to clean up connections and resources.+ #+ def deactivate!+ raise NotImplementedError, "#{self.class}#deactivate! must be implemented"+ end++ protected++ # Helper to create an event object.+ #+ # @param event_name [String]+ # @param payload [Hash]+ # @param metadata [Hash]+ # @return [Spree::Event]+ def build_event(event_name, payload, metadata)+ Spree::Event.new(+ name: event_name,+ payload: payload,+ metadata: metadata+ )+ end++ # Find and invoke all matching subscribers for an event.+ #+ # Checks if events are enabled and invokes each matching subscriber.+ # Errors are caught and handled via handle_subscriber_error.+ #+ # @param event [Spree::Event] the event to dispatch+ def invoke_subscribers(event)+ return unless Spree::Events.enabled?++ subscriptions = registry.subscriptions_for(event.name)++ subscriptions.each do |subscription|+ invoke_subscriber(subscription.subscriber, event, subscription.options)+ rescue StandardError => e+ handle_subscriber_error(e, event, subscription)+ end+ end++ # Invoke a single subscriber with an event.+ #+ # Handles different subscriber types (Proc, callable, Spree::Subscriber)+ # and async/sync execution via ActiveJob.+ #+ # @param subscriber [Class, Proc, #call] the subscriber+ # @param event [Spree::Event] the event+ # @param options [Hash] subscription options+ def invoke_subscriber(subscriber, event, options)+ async = options.fetch(:async, true)++ if subscriber.is_a?(Proc)+ # Block subscribers run synchronously+ subscriber.call(event)+ elsif subscriber.respond_to?(:call)+ # Callable objects (including subscriber instances)+ if async && defined?(Spree::Events::SubscriberJob)+ Spree::Events::SubscriberJob.perform_later(subscriber.name, event.to_h)+ else+ subscriber.call(event)+ end+ elsif subscriber.is_a?(Class) && subscriber < Spree::Subscriber+ # Subscriber classes+ if async && defined?(Spree::Events::SubscriberJob)+ Spree::Events::SubscriberJob.perform_later(subscriber.name, event.to_h)+ else+ subscriber.new.call(event)+ end+ else+ raise ArgumentError, "Invalid subscriber: #{subscriber.inspect}. Must be a Proc, callable, or Spree::Subscriber subclass."+ end+ end++ # Handle errors that occur during subscriber invocation.+ #+ # Reports the error to Rails.error and re-raises in development/test+ # for visibility. In production, the error is swallowed after reporting.+ #+ # @param error [StandardError] the error that occurred+ # @param event [Spree::Event] the event being processed+ # @param subscription [Spree::Events::Registry::Subscription] the subscription+ def handle_subscriber_error(error, event, subscription)+ Rails.error.report(error, context: {+ event_name: event.name,+ subscriber: subscription.subscriber.to_s,+ event_id: event.metadata['event_id']+ })++ # Re-raise in development/test for visibility+ raise if Rails.env.development? || Rails.env.test?+ end+ end+ end+ end+enddiff --git a/core/lib/spree/core.rb b/core/lib/spree/core.rbindex b3b5222986..eccc638245 100644--- a/core/lib/spree/core.rb+++ b/core/lib/spree/core.rb@@ -40,7 +40,7 @@ StateMachines::Machine.ignore_method_conflicts = truemodule Spreemattr_accessor :base_class, :user_class, :admin_user_class,:private_storage_service_name, :public_storage_service_name,- :cdn_host, :root_domain, :searcher_class, :queues,+ :cdn_host, :root_domain, :searcher_class, :events_adapter_class, :queues,:google_places_api_key, :screenshot_api_tokendef self.base_class(constantize: true)@@ -123,6 +123,23 @@ module Spreeendend+ # Returns the events adapter class used for publishing and subscribing to events.+ #+ # @example Using a custom adapter+ # Spree.events_adapter_class = 'MyApp::Events::KafkaAdapter'+ #+ # @param constantize [Boolean] whether to return the class or the string+ # @return [Class, String] the adapter class or its name+ def self.events_adapter_class(constantize: true)+ @@events_adapter_class ||= 'Spree::Events::Adapters::ActiveSupportNotifications'++ if @@events_adapter_class.is_a?(Class)+ raise 'Spree.events_adapter_class MUST be a String or Symbol object, not a Class object.'+ elsif @@events_adapter_class.is_a?(String) || @@events_adapter_class.is_a?(Symbol)+ constantize ? @@events_adapter_class.to_s.constantize : @@events_adapter_class.to_s+ end+ end+def self.google_places_api_key@@google_places_api_keyend