Class: Hoodoo::Services::Middleware
- Inherits:
-
Object
- Object
- Hoodoo::Services::Middleware
- Defined in:
- lib/hoodoo/services/middleware/middleware.rb,
lib/hoodoo/services/middleware/interaction.rb,
lib/hoodoo/services/middleware/amqp_log_writer.rb,
lib/hoodoo/services/middleware/endpoints/inter_resource_local.rb,
lib/hoodoo/services/middleware/endpoints/inter_resource_remote.rb,
lib/hoodoo/services/middleware/exception_reporting/base_reporter.rb,
lib/hoodoo/services/middleware/exception_reporting/exception_reporting.rb,
lib/hoodoo/services/middleware/exception_reporting/reporters/raygun_reporter.rb,
lib/hoodoo/services/middleware/exception_reporting/reporters/airbrake_reporter.rb
Overview
Just used as a namespace here
Defined Under Namespace
Classes: AMQPLogWriter, ExceptionReporting, InterResourceLocal, InterResourceRemote, Interaction
Constant Summary collapse
- ALLOWED_ACTIONS =
:category: Public constants
All allowed action names in implementations, used for internal checks. This is also the default supported set of actions. Symbols.
[ :list, :show, :create, :update, :delete, ]
- ALLOWED_HTTP_METHODS =
All allowed HTTP methods, related to ALLOWED_ACTIONS.
Set.new( %w( GET POST PATCH DELETE ) )
- ALLOWED_QUERIES_LIST =
Allowed common fields in query strings (list actions only). Strings.
Only ever add to this list. As the API evolves, legacy clients will be calling with previously documented query strings and removing any entries from the list below could cause their requests to be rejected with a ‘platform.malformed’ error.
[ 'offset', 'limit', 'sort', 'direction', 'search', 'filter' ]
- ALLOWED_QUERIES_ALL =
Allowed common fields in query strings (all actions). Strings. Adds to the ::ALLOWED_QUERIES_LIST for list actions.
Only ever add to this list. As the API evolves, legacy clients will be calling with previously documented query strings and removing any entries from the list below could cause their requests to be rejected with a ‘platform.malformed’ error.
[ '_embed', '_reference' ]
- SUPPORTED_MEDIA_TYPES =
Allowed media types in Content-Type headers.
[ 'application/json' ]
- SUPPORTED_ENCODINGS =
Allowed (required) charsets in Content-Type headers.
[ 'utf-8' ]
- PROHIBITED_INBOUND_FIELDS =
Prohibited fields in creations or updates - these are the common fields specified in the API, which are emergent in the platform or are set via other routes (e.g. “language” comes from HTTP headers in requests). This is obtained via the Hoodoo::Presenters::CommonResourceFields class and its described field schema, so see that for details.
Hoodoo::Presenters::CommonResourceFields.get_schema().properties.keys
- MAXIMUM_PAYLOAD_SIZE =
Somewhat arbitrary maximum incoming payload size to prevent ham-fisted DOS attempts to consume RAM.
1048576
- MAXIMUM_LOGGED_PAYLOAD_SIZE =
Maximum logged payload (inbound data) size.
1024
- MAXIMUM_LOGGED_RESPONSE_SIZE =
Maximum logged response (outbound data) size.
1024
- DEFAULT_TEST_SESSION =
The default test session; a Hoodoo::Services::Session instance with the following characteristics:
- Session ID
-
01234567890123456789012345678901
- Caller ID
-
c5ea12fb7f414a46850e73ee1bf6d95e
- Caller Version
-
1
- Permissions
-
Default/else/“allow” to allow all actions
- Identity
-
Has
caller_id
as its only field - Scoping
-
All secured HTTP headers are allowed
Expires at: Now plus 2 days
See also ::test_session and ::set_test_session.
Hoodoo::Services::Session.new
Class Method Summary collapse
-
.de_facto_path_for(resource, version) ⇒ Object
For a given resource name and version, return the de facto routing path based on version and name with no modifications.
-
.environment ⇒ Object
Utility - returns the execution environment as a Rails-like environment object which answers queries like
production?
orstaging?
withtrue
orfalse
according to theRACK_ENV
environment variable setting. -
.flush_services_for_test ⇒ Object
For test purposes, dump the internal service records and flush the DRb service, if it is running.
-
.has_memcached? ⇒ Boolean
Do we have Memcached available? If not, assume local development with higher level queue services not available.
-
.logger ⇒ Object
Access the middleware’s logging instance.
-
.memcached_host ⇒ Object
Return a Memcached host (IP address/port combination) as a String if defined in environment variable MEMCACHED_HOST (with MEMCACHE_URL also accepted as a legacy fallback).
-
.on_queue? ⇒ Boolean
Are we running on the queue, else (implied) a local HTTP server?.
-
.record_host_and_port(options = {}) ⇒ Object
Record internally the HTTP host and port during local development via e.g
rackup
or testing with rspec. -
.service_name ⇒ Object
Return a service ‘name’ derived from the service’s collection of declared resources.
-
.set_log_folder(base_path) ⇒ Object
If using the middleware logger (see ::logger) with no external custom logger set up (see ::set_logger), call here to configure the folder used for logs when file output is active.
-
.set_logger(logger) ⇒ Object
The middleware sets up a logger itself (see ::logger) with various log mechanisms set up (mostly) without service author intervention.
-
.set_test_session(session) ⇒ Object
Set the test session instance.
-
.set_verbose_logging(verbose) ⇒ Object
Set verbose logging.
-
.test_session ⇒ Object
A Hoodoo::Services::Session instance to use for tests or when no local Memcached instance is known about (environment variable
MEMCACHED_HOST
is not set). -
.verbose_logging? ⇒ Boolean
Returns
true
if verbose logging is enabled, elsefalse
.
Instance Method Summary collapse
-
#call(env) ⇒ Object
Run a Rack request, returning the [status, headers, body-array] data as per the Rack protocol requirements.
-
#initialize(app) ⇒ Middleware
constructor
Initialize the middleware instance.
-
#inter_resource_endpoint_for(resource, version, interaction) ⇒ Object
Return something that behaves like a Hoodoo::Client::Endpoint subclass instance which can be used for inter-resource communication, whether the target endpoint implementation is local or remote.
-
#inter_resource_local(source_interaction:, discovery_result:, endpoint:, action:, ident: nil, body_hash: nil, query_hash: nil) ⇒ Object
Make a local (non-HTTP local Ruby method call) inter-resource call.
Constructor Details
#initialize(app) ⇒ Middleware
Initialize the middleware instance.
app
Rack app instance to which calls should be passed.
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 405 def initialize( app ) service_container = app if defined?( NewRelic ) && defined?( NewRelic::Agent ) && defined?( NewRelic::Agent::Instrumentation ) && defined?( NewRelic::Agent::Instrumentation::MiddlewareProxy ) && service_container.is_a?( NewRelic::Agent::Instrumentation::MiddlewareProxy ) if service_container.respond_to?( :target ) newrelic_wrapper = service_container service_container = service_container.target() else raise "Hoodoo::Services::Middleware instance created with NewRelic-wrapped Service entity, but NewRelic API is not as expected by Hoodoo; incompatible NewRelic version." end end unless service_container.is_a?( Hoodoo::Services::Service ) raise "Hoodoo::Services::Middleware instance created with non-Service entity of class '#{ service_container.class }' - is this the last middleware in the chain via 'use()' and is Rack 'run()'-ing the correct thing?" end # Collect together the implementation instances and the matching regexps # for endpoints. An array of hashes. # # Key Value # ======================================================================= # regexp Regexp for +String#match+ on the URI path component # interface Hoodoo::Services::Interface subclass associated with # the endpoint regular expression in +regexp+ # actions Set of symbols naming allowed actions # implementation Hoodoo::Services::Implementation subclass *instance* to # use on match # # @@services = service_container.component_interfaces.map do | interface | if interface.nil? || interface.endpoint.nil? || interface.implementation.nil? raise "Hoodoo::Services::Middleware encountered invalid interface class #{ interface } via service class #{ service_container.class }" end # If anything uses a public interface, we need to tell ourselves that # the early exit session check can't be done. # interfaces_have_public_methods() unless interface.public_actions.empty? # There are two routes to an implementation - one via the custom path # given through its 'endpoint' declaration, the other a de facto path # determined from the unmodified version and resource name. Both lead # to the same implementation instance. # implementation_instance = interface.implementation.new # Regexp explanation: # # Match "/", the version text, "/", the endpoint text, then either # another "/", a "." or the end of the string, followed by capturing # everything else. Match data index 1 will be whatever character (if # any) followed after the endpoint ("/" or ".") while index 2 contains # everything else. # custom_path = "/v#{ interface.version }/#{ interface.endpoint }" custom_regexp = /\/v#{ interface.version }\/#{ interface.endpoint }(\.|\/|$)(.*)/ # Same as above, but for the de facto routing. # de_facto_path = self.class.de_facto_path_for( interface.resource, interface.version ) de_facto_regexp = /\/#{ interface.version }\/#{ interface.resource }(\.|\/|$)(.*)/ Hoodoo::Services::Discovery::ForLocal.new( :resource => interface.resource, :version => interface.version, :base_path => custom_path, :routing_regexp => custom_regexp, :de_facto_base_path => de_facto_path, :de_facto_routing_regexp => de_facto_regexp, :interface_class => interface, :implementation_instance => implementation_instance ) end # Determine the service name from the resources above then announce # the whole collection to any interested discovery engines. sorted_resources = @@services.map() { | service | service.resource }.sort() @@service_name = "service.#{ sorted_resources.join( '_' ) }" announce_presence_of( @@services ) end |
Class Method Details
.de_facto_path_for(resource, version) ⇒ Object
For a given resource name and version, return the de facto routing path based on version and name with no modifications.
resource
-
Resource name for the endpoint, e.g.
:Purchase
. String or symbol. version
-
Implemented version of the endpoint. Integer.
242 243 244 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 242 def self.de_facto_path_for( resource, version ) "/#{ version }/#{ resource }" end |
.environment ⇒ Object
Utility - returns the execution environment as a Rails-like environment object which answers queries like production?
or staging?
with true
or false
according to the RACK_ENV
environment variable setting.
Example:
if Hoodoo::Services::Middleware.environment.production?
# ...do something only if RACK_ENV="production"
end
188 189 190 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 188 def self.environment @@environment ||= Hoodoo::StringInquirer.new( ENV[ 'RACK_ENV' ] || 'development' ) end |
.flush_services_for_test ⇒ Object
For test purposes, dump the internal service records and flush the DRb service, if it is running. Existing middleware instances will be invalidated. New instances must be created to re-scan their services internally and (where required) inform the DRb process of the endpoints.
391 392 393 394 395 396 397 398 399 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 391 def self.flush_services_for_test @@services = [] @@service_name = nil ObjectSpace.each_object( self ) do | middleware_instance | discoverer = middleware_instance.instance_variable_get( '@discoverer' ) discoverer.flush_services_for_test() if discoverer.respond_to?( :flush_services_for_test ) end end |
.has_memcached? ⇒ Boolean
Do we have Memcached available? If not, assume local development with higher level queue services not available. Most service authors should not ever need to check this.
196 197 198 199 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 196 def self.has_memcached? m = self.memcached_host() m.nil? == false && m.empty? == false end |
.logger ⇒ Object
Access the middleware’s logging instance. Call report
on this to make structured log entries. See Hoodoo::Logger::WriterMixin#report along with Hoodoo::Logger for other calls you can use.
The logging system ‘wakes up’ in stages. Initially, only console based output is added, as the Middleware Ruby code is parsed and configures a basic logger. If you call ::set_log_folder, file-based logging may be available. In AMQP based environments, queue based logging will become automatically available via Rack and the Alchemy gem once the middleware starts handling its very first request, but not before.
With this in mind, the logger is ultimately configured with a set of writers as follows:
-
If off queue:
-
All RACK_ENV values (including “test”):
-
File “log/environment.log”
-
-
RACK_ENV “development”
-
Also to $stdout
-
-
-
If on queue:
-
RACK ENV “test”
-
File “log/test.log”
-
-
All other RACK_ENV values
-
AMQP writer (see below)
-
-
RACK_ENV “development”
-
Also to $stdout
-
-
Or to put it another way, in test mode only file output to ‘test.log’ happens; in development mode $stdout always happens; and in addition for non-test environment, you’ll get a queue-based or file-based logger depending on whether or not a queue is available.
See Hoodoo::Services::Interface#secure_logs_for for information about security considerations when using logs.
282 283 284 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 282 def self.logger @@logger # See self.set_up_basic_logging and self.set_logger end |
.memcached_host ⇒ Object
Return a Memcached host (IP address/port combination) as a String if defined in environment variable MEMCACHED_HOST (with MEMCACHE_URL also accepted as a legacy fallback).
If this returns nil
or an empty string, there’s no defined Memcached host available.
208 209 210 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 208 def self.memcached_host ENV[ 'MEMCACHED_HOST' ] || ENV[ 'MEMCACHE_URL' ] end |
.on_queue? ⇒ Boolean
Are we running on the queue, else (implied) a local HTTP server?
214 215 216 217 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 214 def self.on_queue? q = ENV[ 'AMQ_URI' ] q.nil? == false && q.empty? == false end |
.record_host_and_port(options = {}) ⇒ Object
Record internally the HTTP host and port during local development via e.g rackup
or testing with rspec. This is usually not called directly except via the Rack startup monkey patch code in rack_monkey_patch.rb
.
Options hash :Host
and :Port
entries are recorded.
380 381 382 383 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 380 def self.record_host_and_port( = {} ) @@recorded_host = [ :Host ] @@recorded_port = [ :Port ] end |
.service_name ⇒ Object
Return a service ‘name’ derived from the service’s collection of declared resources. The name will be the same across any instances of the service that implement the same resources. This can be used for e.g. AMQP-based queue-named operations, that want to target the same resource collection regardless of instance.
This method will not work unless the middleware has parsed the set of service interface declarations (during instance initialisation). If a least one middleware instance has already been created, it is safe to call.
230 231 232 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 230 def self.service_name @@service_name end |
.set_log_folder(base_path) ⇒ Object
If using the middleware logger (see ::logger) with no external custom logger set up (see ::set_logger), call here to configure the folder used for logs when file output is active.
If you don’t do this at least once, no log file output can occur.
You can call more than once to output to more than one log folder.
See Hoodoo::Services::Interface#secure_logs_for for information about security considerations when using logs.
base_path
-
Path to folder to use for logs; file “#environment.log” may be written inside (see ::environment).
322 323 324 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 322 def self.set_log_folder( base_path ) self.send( :add_file_logging, base_path ) end |
.set_logger(logger) ⇒ Object
The middleware sets up a logger itself (see ::logger) with various log mechanisms set up (mostly) without service author intervention.
If you want to completely override the middleware’s logger and replace it with your own at any time (not recommended), call here.
See Hoodoo::Services::Interface#secure_logs_for for information about security considerations when using logs.
logger
-
Alternative Hoodoo::Logger instance to use for all middleware logging from this point onwards. The value will subsequently be returned by the ::logger class method.
299 300 301 302 303 304 305 306 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 299 def self.set_logger( logger ) unless logger.is_a?( Hoodoo::Logger ) raise "Hoodoo::Communicators::set_logger must be called with an instance of Hoodoo::Logger only" end @@external_logger = true @@logger = logger end |
.set_test_session(session) ⇒ Object
Set the test session instance. See ::test_session for details.
session
-
A Hoodoo::Services::Session instance to use as the test session instance for any subsequently-made requests. If
nil
, the test session system acts as if an invalid or missing session ID had been supplied.
367 368 369 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 367 def self.set_test_session( session ) @@test_session = session end |
.set_verbose_logging(verbose) ⇒ Object
Set verbose logging. With verbose logging enabled, additional payload data is added - most notably, full session details (where possible) are included in each log message. These can increase log data size considerably, but may be useful if you encounter session-related errors or general operational issues and need log data to provide more insights.
Verbose logging is disabled by default.
verbose
-
true
to enable verbose logging,false
to disable it. The default isfalse
.
338 339 340 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 338 def self.set_verbose_logging( verbose ) @@verbose_logging = verbose end |
.test_session ⇒ Object
A Hoodoo::Services::Session instance to use for tests or when no local Memcached instance is known about (environment variable MEMCACHED_HOST
is not set). The session is (eventually) read each time a request is made via Rack (through #call).
“Out of the box”, DEFAULT_TEST_SESSION is used.
356 357 358 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 356 def self.test_session @@test_session end |
.verbose_logging? ⇒ Boolean
Returns true
if verbose logging is enabled, else false
. For more, see ::set_verbose_logging.
345 346 347 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 345 def self.verbose_logging? defined?( @@verbose_logging ) ? @@verbose_logging : false end |
Instance Method Details
#call(env) ⇒ Object
Run a Rack request, returning the [status, headers, body-array] data as per the Rack protocol requirements.
env
Rack environment.
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 501 def call( env ) # Global exception handler - catch problems in service implementations # and send back a 500 response as per API documentation (if possible). # begin enable_alchemy_logging_from( env ) interaction = Hoodoo::Services::Middleware::Interaction.new( env, self ) debug_log( interaction ) early_response = preprocess( interaction ) return early_response unless early_response.nil? response = interaction.context.response process( interaction ) unless response.halt_processing? postprocess( interaction ) unless response.halt_processing? return respond_for( interaction ) rescue => exception begin if interaction && interaction.context ExceptionReporting.contextual_report( exception, interaction.context ) else ExceptionReporting.report( exception, env ) end record_exception( interaction, exception ) return respond_for( interaction ) rescue => inner_exception begin backtrace = '' inner_backtrace = '' if self.class.environment.test? || self.class.environment.development? backtrace = exception.backtrace inner_backtrace = inner_exception.backtrace else '' end @@logger.error( 'Hoodoo::Services::Middleware#call', 'Middleware exception in exception handler', inner_exception.to_s, inner_backtrace.to_s, '...while handling...', exception.to_s, backtrace.to_s ) rescue # Ignore logger exceptions. Can't do anything about them. Just # try and get the response back to the client now. end # An exception in the exception handler! Oh dear. # rack_response = Rack::Response.new rack_response.status = 500 rack_response.write( 'Middleware exception in exception handler' ) return rack_response.finish end end end |
#inter_resource_endpoint_for(resource, version, interaction) ⇒ Object
Return something that behaves like a Hoodoo::Client::Endpoint subclass instance which can be used for inter-resource communication, whether the target endpoint implementation is local or remote.
resource
-
Resource name for the endpoint, e.g.
:Purchase
. String or symbol. version
-
Required implemented version for the endpoint. Integer.
interaction
-
The Hoodoo::Services::Interaction instance describing the inbound call, the processing of which is leading to a request for an inter-resource call by an endpoint implementation.
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 586 def inter_resource_endpoint_for( resource, version, interaction ) resource = resource.to_sym version = version.to_i # Build a Hash of any options which should be transferred from one # endpoint to another for inter-resource calls, along with other # options common to local and remote endpoints. = { :interaction => interaction, :locale => interaction.context.request.locale, } Hoodoo::Client::Headers::HEADER_TO_PROPERTY.each do | rack_header, description | property = description[ :property ] if description[ :auto_transfer ] == true [ property ] = interaction.context.request.send( property ) end end if @discoverer.is_local?( resource, version ) # For local inter-resource calls, return the middleware's endpoint # for that. In turn, if used this calls into #inter_resource_local. discovery_result = @@services.find do | entry | interface = entry.interface_class interface.resource == resource && interface.version == version end if discovery_result.nil? raise "Hoodoo::Services::Middleware\#inter_resource_endpoint_for: Internal error - version #{ version } of resource #{ resource } endpoint is local according to the discovery engine, but no local service discovery record can be found" end [ :discovery_result ] = discovery_result return Hoodoo::Services::Middleware::InterResourceLocal.new( resource, version, ) else # For remote inter-resource calls, use Hoodoo::Client's endpoint # factory to get a (say) HTTP or AMQP contact endpoint, but then # wrap it with the middleware's remote call endpoint, since the # request requires extra processing before it goes to the Client # (e.g. session permission augmentation) and the result needs # extra processing before it is returned to the caller (e.g. # delete an augmented session, annotate any errors from call). [ :discoverer ] = @discoverer [ :session ] = interaction.context.session wrapped_endpoint = Hoodoo::Client::Endpoint.endpoint_for( resource, version, ) if wrapped_endpoint.is_a?( Hoodoo::Client::Endpoint::AMQP ) && defined?( @@alchemy ) wrapped_endpoint.alchemy = @@alchemy end # Using "ForRemote" here is redundant - we could just as well # pass wrapped_endpoint directly to an option in the # InterResourceRemote class - but keeping "with the pattern" # just sort of 'seems right' and might be useful in future. discovery_result = Hoodoo::Services::Discovery::ForRemote.new( :resource => resource, :version => version, :wrapped_endpoint => wrapped_endpoint ) return Hoodoo::Services::Middleware::InterResourceRemote.new( resource, version, { :interaction => interaction, :discovery_result => discovery_result } ) end end |
#inter_resource_local(source_interaction:, discovery_result:, endpoint:, action:, ident: nil, body_hash: nil, query_hash: nil) ⇒ Object
Make a local (non-HTTP local Ruby method call) inter-resource call. This is fast compared to any remote resource call, even though there is still a lot of overhead involved in setting up data so that the target resource “sees” the call in the same way as any other.
Named parameters are as follows:
source_interaction
-
A Hoodoo::Services::Interaction instance for the inbound call which is being processed right now by some resource endpoint implementation and this implementation is now making an inter-resource call as part of its processing;
discovery_result
-
A Hoodoo::Services::Discovery::ForLocal instance describing the target of the inter-resource call;
endpoint
-
The calling Hoodoo::Client::Endpoint subclass instance (used for e.g. locale, dated-at);
action
-
A Hoodoo::Services::Middleware::ALLOWED_ACTIONS entry;
ident
-
UUID or other unique identifier of a resource instance. Required for
show
,update
anddelete
actions, ignored for others; query_hash
-
Optional Hash of query data to be turned into a query string - applicable to any action;
body_hash
-
Hash of data to convert to a body string using the source interaction’s described content type. Required for
create
andupdate
actions, ignored for others.
A Hoodoo::Client::AugmentedArray or Hoodoo::Client::AugmentedHash is returned from these methods; @response or the wider processing context is not automatically modified. Callers MUST use the methods provided by Hoodoo::Client::AugmentedBase to detect and handle error conditions, unless for some reason they wish to ignore inter-resource call errors.
714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 |
# File 'lib/hoodoo/services/middleware/middleware.rb', line 714 def inter_resource_local( source_interaction:, discovery_result:, endpoint:, action:, ident: nil, body_hash: nil, query_hash: nil ) # We must construct a call context for the local service. This means # a local request object which we fill in with data just as if we'd # parsed an inbound HTTP request and a response object that contains # the usual default data. interface = discovery_result.interface_class implementation = discovery_result.implementation_instance # Need to possibly augment the caller's session - same rationale # as #local_service_remote, so see that for details. session = source_interaction.context.session unless session.nil? || source_interaction.using_test_session? session = session.( source_interaction ) end if session == false hash = Hoodoo::Client::AugmentedHash.new hash.platform_errors.add_error( 'platform.invalid_session' ) return hash end mock_rack_env = { 'HTTP_X_INTERACTION_ID' => source_interaction.interaction_id } local_interaction = Hoodoo::Services::Middleware::Interaction.new( mock_rack_env, self, session ) local_interaction.target_interface = interface local_interaction.target_implementation = implementation local_interaction.requested_content_type = source_interaction.requested_content_type local_interaction.requested_content_encoding = source_interaction.requested_content_encoding # For convenience... local_request = local_interaction.context.request local_response = local_interaction.context.response # Carry through any endpoint-specified request orientated attributes. local_request.locale = endpoint.locale Hoodoo::Client::Headers::HEADER_TO_PROPERTY.each do | rack_header, description | property = description[ :property ] property_writer = description[ :property_writer ] value = endpoint.send( property ) local_request.send( property_writer, value ) unless value.nil? end # Initialise the response data. set_common_response_headers( local_interaction ) update_response_for( local_response, interface ) # Work out what kind of result the caller is expecting. result_class = if action == :list Hoodoo::Client::AugmentedArray else Hoodoo::Client::AugmentedHash end # Add errors from the local service response into an augmented object # for responding early (via a Proc for internal reuse later). add_local_errors = Proc.new { result = result_class.new result. = Hoodoo::Client::Headers.( local_response.headers ) result.platform_errors.merge!( local_response.errors ) result } # Figure out initial action / authorisation results for this request. # We may still have to construct a context and ask the service after. upc = [] upc << ident unless ident.nil? || ident.empty? local_interaction.requested_action = action = ( local_interaction ) # In addition, check security on any would-have-been-a-secured-header # property. return add_local_errors.call() if local_response.halt_processing? Hoodoo::Client::Headers::HEADER_TO_PROPERTY.each do | rack_header, description | next if description[ :secured ] != true next if endpoint.send( description[ :property ] ).nil? real_header = description[ :header ] if ( session.respond_to?( :scoping ) == false || session.scoping.respond_to?( :authorised_http_headers ) == false || session.scoping..respond_to?( :include? ) == false || ( session.scoping..include?( rack_header ) == false && session.scoping..include?( real_header ) == false ) ) local_response.errors.add_error( 'platform.forbidden' ) break end end return add_local_errors.call() if local_response.halt_processing? deal_with_x_assume_identity_of( local_interaction ) return add_local_errors.call() if local_response.halt_processing? # Construct the local request details. local_request.uri_path_components = upc local_request.uri_path_extension = '' unless query_hash.nil? query_hash = Hoodoo::Utilities.stringify( query_hash ) # This is for inter-resource local calls where a service author # specifies ":_embed => 'foo'" accidentally, forgetting that it # should be a single element array. It's such a common mistake # that we tolerate it here. Same for "_reference". data = query_hash[ '_embed' ] query_hash[ '_embed' ] = [ data ] if data.is_a?( ::String ) || data.is_a?( ::Symbol ) data = query_hash[ '_reference' ] query_hash[ '_reference' ] = [ data ] if data.is_a?( ::String ) || data.is_a?( ::Symbol ) # Regardless, make sure embed/reference array data contains strings. query_hash[ '_embed' ].map!( &:to_s ) unless query_hash[ '_embed' ].nil? query_hash[ '_reference' ].map!( &:to_s ) unless query_hash[ '_reference' ].nil? process_query_hash( local_interaction, query_hash ) end local_request.body = body_hash # The inter-resource local backend does not accept or process the # equivalent of the X-Resource-UUID "set the ID to <this>" HTTP # header, so we do not call "maybe_update_body_data_for()" here; # we only need to validate it. # if ( action == :create || action == :update ) validate_body_data_for( local_interaction ) end return add_local_errors.call() if local_response.halt_processing? # Can now, if necessary, do a final check with the target endpoint # for authorisation. if == Hoodoo::Services::Permissions::ASK ( local_interaction ) return add_local_errors.call() if local_response.halt_processing? end # Dispatch the call. debug_log( local_interaction, 'Dispatching local inter-resource call', local_request.body ) dispatch( local_interaction ) # If we get this far the interim session isn't needed. We might have # exited early due to errors above and left this behind, but that's not # the end of the world - it'll expire out of Memcached eventually. if session && source_interaction.context && source_interaction.context.session && session.session_id != source_interaction.context.session.session_id # Ignore errors, there's nothing much we can do about them and in # the worst case we just have to wait for this to expire naturally. session.delete_from_memcached() end # Extract the returned data, handling error conditions. if local_response.halt_processing? result = result_class.new result.set_platform_errors( annotate_errors_from_other_resource( local_response.errors ) ) else body = local_response.body if action == :list && body.is_a?( ::Array ) result = Hoodoo::Client::AugmentedArray.new( body ) result.dataset_size = local_response.dataset_size result.estimated_dataset_size = local_response.estimated_dataset_size elsif action != :list && body.is_a?( ::Hash ) result = Hoodoo::Client::AugmentedHash[ body ] elsif local_request.deja_vu && body == '' result = result_class.new else raise "Hoodoo::Services::Middleware: Unexpected response type '#{ body.class.name }' received from a local inter-resource call for action '#{ action }'" end end result. = Hoodoo::Client::Headers.( local_response.headers ) return result end |