aboutsummaryrefslogtreecommitdiffstats
path: root/actionservice/lib/action_service/container.rb
blob: b2317fc941a7ade9a2859c03ff8161ce4bc16caa (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
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
76
77
78
79
80
81
82
83
84
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
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
module ActionService # :nodoc:
  module Container # :nodoc:
    class ContainerError < ActionService::ActionServiceError # :nodoc:
    end

    def self.append_features(base) # :nodoc:
      super
      base.class_inheritable_option(:service_dispatching_mode, :direct)
      base.class_inheritable_option(:service_exception_reporting, true)
      base.extend(ClassMethods)
      base.send(:include, ActionService::Container::InstanceMethods)
    end

    module ClassMethods
      # Declares a service that will provides access to the API of the given
      # service +object+. +object+ must be an ActionService::Base derivative.
      #
      # Service object creation can either be _immediate_, where the object
      # instance is given at class definition time, or _deferred_, where
      # object instantiation is delayed until request time.
      #
      # ==== Immediate service object example
      #
      #   class ApiController < ApplicationController
      #     service_dispatching_mode :delegated
      #
      #     service :person, PersonService.new
      #   end
      #
      # For deferred instantiation, a block should be given instead of an
      # object instance. This block will be executed in controller instance
      # context, so it can rely on controller instance variables being present.
      #
      # ==== Deferred service object example
      #
      #   class ApiController < ApplicationController
      #     service_dispatching_mode :delegated
      #
      #     service(:person) { PersonService.new(@request.env) }
      #   end
      def service(name, object=nil, &block)
        if (object && block_given?) || (object.nil? && block.nil?)
          raise(ContainerError, "either service, or a block must be given")
        end
        name = name.to_sym
        if block_given?
          info = { name => { :block => block } }
        else
          info = { name => { :object => object } }
        end
        write_inheritable_hash("action_services", info)
        call_service_definition_callbacks(self, name, info)
      end

      # Whether this service contains a service with the given +name+
      def has_service?(name)
        services.has_key?(name.to_sym)
      end

      def services # :nodoc:
        read_inheritable_attribute("action_services") || {}
      end

      def add_service_definition_callback(&block) # :nodoc:
        write_inheritable_array("service_definition_callbacks", [block])
      end

      private
        def call_service_definition_callbacks(container_class, service_name, service_info)
          (read_inheritable_attribute("service_definition_callbacks") || []).each do |block|
            block.call(container_class, service_name, service_info)
          end
        end
    end

    module InstanceMethods # :nodoc:
      def service_object(service_name)
        info = self.class.services[service_name.to_sym]
        unless info
          raise(ContainerError, "no such service '#{service_name}'")
        end
        service = info[:block]
        service ? instance_eval(&service) : info[:object]
      end

      private
        def dispatch_service_request(protocol_request)
          case service_dispatching_mode
          when :direct
            dispatch_direct_service_request(protocol_request)
          when :delegated
            dispatch_delegated_service_request(protocol_request)
          else
            raise(ContainerError, "unsupported dispatching mode '#{service_dispatching_mode}'")
          end
        end

        def dispatch_direct_service_request(protocol_request)
          public_method_name = protocol_request.public_method_name
          api = self.class.service_api
          method_name = api.api_method_name(public_method_name)
          block = nil
          expects = nil
          if method_name
            signature = api.api_methods[method_name]
            expects = signature[:expects]
            protocol_request.type = Protocol::CheckedMessage
            protocol_request.signature = expects
            protocol_request.return_signature = signature[:returns]
          else
            protocol_request.type = Protocol::UncheckedMessage
            system_methods = self.class.read_inheritable_attribute('default_system_methods') || {}
            protocol = protocol_request.protocol
            block = system_methods[protocol.class]
            unless block
              method_name = api.default_api_method
              unless method_name && respond_to?(method_name)
                raise(ContainerError, "no such method ##{public_method_name}")
              end
            end
          end

          @method_params = protocol_request.unmarshal
          @params ||= {}
          if expects
            (1..@method_params.size).each do |i|
              i -= 1
              if expects[i].is_a?(Hash)
                @params[expects[i].keys.shift.to_s] = @method_params[i]
              else
                @params["param#{i}"] = @method_params[i]
              end
            end
          end

          if respond_to?(:before_action)
            @params['action'] = method_name.to_s
            return protocol_request.marshal(nil) if before_action == false
          end

          perform_invoke = lambda do
            if block
              block.call(public_method_name, self.class, *@method_params)
            else
              send(method_name)
            end
          end
          try_default = true
          result = nil
          catch(:try_default) do
            result = perform_invoke.call
            try_default = false
          end
          if try_default
            method_name = api.default_api_method
            if method_name
              protocol_request.type = Protocol::UncheckedMessage
            else
              raise(ContainerError, "no such method ##{public_method_name}")
            end
            result = perform_invoke.call
          end
          after_action if respond_to?(:after_action)
          protocol_request.marshal(result)
        end

        def dispatch_delegated_service_request(protocol_request)
          service_name = protocol_request.service_name
          service = service_object(service_name)
          api = service.class.service_api
          public_method_name = protocol_request.public_method_name
          method_name = api.api_method_name(public_method_name)

          invocation = ActionService::Invocation::InvocationRequest.new(
            ActionService::Invocation::ConcreteInvocation,
            public_method_name,
            method_name)

          if method_name
            protocol_request.type = Protocol::CheckedMessage
            signature = api.api_methods[method_name]
            protocol_request.signature = signature[:expects]
            protocol_request.return_signature = signature[:returns]
            invocation.params = protocol_request.unmarshal
          else
            protocol_request.type = Protocol::UncheckedMessage
            invocation.type = ActionService::Invocation::VirtualInvocation
            system_methods = self.class.read_inheritable_attribute('default_system_methods') || {}
            protocol = protocol_request.protocol
            block = system_methods[protocol.class]
            if block
              invocation.block = block
              invocation.block_params << service.class
            else
              method_name = api.default_api_method
              if method_name && service.respond_to?(method_name)
                invocation.params = protocol_request.unmarshal
                invocation.method_name = method_name.to_sym
              else
                raise(ContainerError, "no such method /#{service_name}##{public_method_name}")
              end
            end
          end

          canceled_reason = nil
          canceled_block = lambda{|r| canceled_reason = r}
          perform_invoke = lambda do
            service.perform_invocation(invocation, &canceled_block)
          end
          try_default = true
          result = nil
          catch(:try_default) do
            result = perform_invoke.call
            try_default = false
          end
          if try_default
            method_name = api.default_api_method
            if method_name
              protocol_request.type = Protocol::UncheckedMessage
              invocation.params = protocol_request.unmarshal
              invocation.method_name = method_name.to_sym
              invocation.type = ActionService::Invocation::UnpublishedConcreteInvocation
            else
              raise(ContainerError, "no such method /#{service_name}##{public_method_name}")
            end
            result = perform_invoke.call
          end
          protocol_request.marshal(result)
        end
    end
  end
end