Showing posts with label upon demand. Show all posts
Showing posts with label upon demand. Show all posts

Tuesday, May 28, 2013

External Components – Database Query Implementation Update

External Components – Database Query Implementation Update

Background:

As mentioned in the last post, my Framework and database interface component were unable to handle the publish and delivery of a query response when the database interface component sent a database query to the external database component/application process.  The publish of the query response was successful but its delivery back to the requesting component failed.

At the time I thought it was because the request topic message had been released when the database interface component returned control to the Framework after sending the query to the external database component/application.  Therefore, I added code to the Framework to detect that the requesting component had subscribed for a response but that the response had yet to be published.  This to avoid releasing the request too soon.

This required a number of changes to keep track of components that subscribed for a response versus those that hadn’t and set when the response was published so that the release code could avoid the release when the response had yet to be published.

Before I had finished with these changes I recognized that they were not going to provide the solution.

That is, first of all, the fact that the request had been released was not the reason that the Framework lacked the ability to determine which component was the requestor.  This had been based upon the consumer of the request producing and publishing the response before returning to the Framework.  Therefore, when published, the Framework could determine the publisher of the last request topic message that it had delivered to the consumer.  And hence could forward the response to it when it was published.

Prior to the publish of the delayed response, the consumer component had been activated once again by the publish of the wakeup topic by the Named Pipe Receive component as it queued the received response message from the external database.  Since the receive thread is really a subcomponent of the database interface component (that is, DBI1 – see diagram of the April 29 post "External Components – Database Queries") the producer of this request message is the same as the consumer.  Therefore, the Framework in checking the producer of the last request that activated the consumer component, no longer was able to determine the producer of the original query request.

To solve this problem while allowing delayed responses (that is, responses that are published after the consumer component has returned control to the framework following receipt of the request) would require further changes.

And, to complicate matters further, multiple request producers are allowed.  Therefore, a number of requestors could concurrently publish a request.  With immediate response the framework, via the framework component Scheduler, queues these requests to the run queue for the thread priority of the consumer component.  When the consumer returns to the framework, the Scheduler activates the message topic callback of the next component in the particular run queue.  Therefore, if multiple requestors concurrently published request topics, the other requestors would have their requests in the queue and the consumer component would be immediately reactivated to treat the next request in the queue and the framework would save this requestor as the one to which to return a response.

If delayed responses were to become allowed, the framework would deliver the next request before the response to the previous request had been received by the DBI1 component (acting as the middle man between the requesting component and the external database component).  This new query could then be sent to the external database component or it would be necessary to queue it in the DBI1 component.  If allowed to be sent to the external database component it might interfere with the previous query or be for a different database.  If for a different database, that database might provide faster results than that of the previous query causing its response to be returned to the receive queue before that of the first query.  Then the responses would be published out of order of the requests requiring further solutions to be developed.

Better to change the framework to avoid selecting the next request topic of the run queue until the delayed response is published.  This would continue to keep track of all the requestors that had concurrently published by the existing mechanism – as changed to wait until the response was published.

Before I thought of the above possibility as a fix, a different solution occurred to me and I decided to implement it.  I completed and retained the delayed response changes that I had already made in case I might continue with them later.  That is, those changes that would avoid the release of the request until the response was published which would prevent the requestor from writing and publishing a new request until its previous request had completed.

It’s well that I did since further reflection reveals that such a change wouldn’t have worked anyway.  That is, a change to avoid examining the run queue until the response was sent would also prevent the receive of the Read the Receive Queue wakeup event.

The Alternative Solution:

In the alternative solution the Database Interface component has another subcomponent in addition to the instantiation of the Named Pipe Receive thread.  This additional subcomponent is the thread that communicates with the external database component while the main component thread waits for the query response so that the query response can be interpreted and published as the response to the request topic.  The main component is the one that subscribes to consume the requests and publishes the responses to be returned to the requesting component by the framework. That is, it is the interface to the requesting components. 

Since the main component waits for the completion of the query, the publish of the delayed response acts the same as an immediately published response to the framework.  That is, it doesn’t exit back to the framework until after it has published the response. 

Therefore, any concurrent requests by other requesting components remain in the Scheduler run queue of the thread priority level.  And the component that made the request (along with those that made the queued concurrent requests) cannot use the request buffer to write and publish a new request.

It’s just that the main component becomes a long duration component the same as if it had complicated time-consuming computations to perform.

I implemented this as in the following diagram.

    +––––-––––-––––-––––--+ 
    |                     |
    |      Framework      |
    |                     |
    +––––-––––-––––-––––--+ 
               Λ         \
               |          \
  +-–––––––––––|–––––––––––\––––--–––––––––––––––––––––––-–––––––-+
  |            |            \    DBI1 Package/Component           |
  |            |             \                                    |
  |            V              \                                   |
  |   +----–––––––----–––-+    V+----–––––––----––-+              |
  |   |      Message      |     |     Database     |              |
  |   |      Portal       |     |     Manager      |  +––––––––-  |
  |   |       sub         |     |       sub        |  | Receive   |
  |   |     component     |     |     component    |  |  Queue    |
  |   |             /---\ |     |                  |  +––––––––-  |
  |   |             | P |<-–\   |                  |      Λ       |
  |   |             \––-/ |  ––-|                  |      |       |
  |   +----–––––––----–––-+  C  +----–––––––----––-+     /        |
  |                                          |          /         |
  |                                          |         /          |
  +-––––––––––––––––––––––––––––--–––––––––––|––––––––/––––––––-–-+
                                             |       /
         P = Pause                           V      /
         C = Continue event             +––––-––––-–––––-+
                                        |    External    |
                                        |    Database    |
                                        |    component   |
                                        |                |
                                        +––––-––––-–––––-+

In the diagram the main component is called the Message Portal subcomponent while the subcomponent that communicates with the External Database component is the Database Manager subcomponent.  (Architecture-wise, the main component is just the initially registered component that is assigned the initial component key.)

The main component was named the Message Portal since it is the subcomponent to subscribe to consume the message request topics that the Database Interface Ada package (C++/C# class) treats and then to publish the response to be delivered back to the requesting component.

The Database Manager subcomponent is the one that manages the databases and communicates with the External Database component.  It is the subcomponent that tracks when both the connection to the named pipe has occurred and when power up processing has completed such that queries can be sent to access the database.  Eventually it will also monitor the External Database component, receive notifications when a connection between the External Database component and a particular database has been completed or lost, and send commands to establish such a connection or close it.

As such, as illustrated in the diagram, it also has an interface to the framework to receive instances of topics such as power up complete or a periodic wakeup to perform monitoring.  Likewise, to receive the wakeup that indicates that a message from the External Database component has been received and queued.  But, to avoid the delayed response problem, it must not subscribe to treat query requests or any other request that needs a response unless it can publish an immediate response (– meaning before the callback returns to the framework).

The Message Portal is activated by the framework when it is able to deliver a query request of another component.  The Message Portal will then interpret the request topic and form a query message formatted correctly for the particular database that will obtain the data from which a response can be created.  It then buffers the query message, sends a wakeup message to the Database Manager subcomponent and enters its Pause to await the response. 

The Database Manager is run by the framework via the callback for the particular wakeup topic and then retrieves the query message and transmits it to the External Database component via the named pipe that will cause the particular database to be accessed that will obtain the response.  When the External Database transmits the response the External Pipe receives it, queues it, and sends a read the queue wakeup request to the framework.  The framework than causes the Database Manager to run via its callback for this topic and the Database Manager buffers the response and signals the Message Portal to Continue.

The Message Portal then retrieves the buffered query response and extracts the necessary data to publish the response to the original request.  Upon doing the Publish the callback procedure for the original request returns to the framework completing the processing of the request.

Instead of the Message Portal buffering the query message for retrieval by the Database Manager, the interface between them could be to publish a query request topic message for which the Database Manager would subscribe to consume (as long as no response is involved).  However, the response still must be buffered for retrieval by the Message Portal since it is waiting for the response to be ready as it cannot receive a wakeup message.  The ability to react to a wakeup message would revert to the original problem.  Therefore, for symmetry, I buffered both the query and the query response for retrieval by the opposite subcomponent.

The two messages can be buffered since only one request will be treated at a time.  Therefore, the access of the buffer is thread safe since the Message Portal will buffer the query message and then wake the Database Manager to treat it.  Likewise, the Database Manager will buffer the query response and then signal the Message Portal subcomponent to treat it.  Neither will use the buffers again until the next request is received by the Message Portal.

Unexpected Problem:

In my initial implementation to try this idea, the Message Portal did the Pause as a delay loop using the Ada delay statement while checking a Continue boolean as the signal to exit the delay loop.  Although I didn’t intend to retain this mechanism it worked as anticipated and was thread safe since a unary object was being monitored and set. 

However an unexpected problem occurred when the Message Portal received the request topic and sent the wakeup to the Database Manager.  The Database Manager didn’t run.

Luckily I soon thought of the reason.  Deadlock. 

The two subcomponents had been registered with the same expected time interval for processing.  Therefore, their threads were assigned to the same priority level and to the same Scheduler run queue.  Because of this the wakeup for the Database Manager subcomponent was added to the run queue behind the request that was being treated by the Message Portal subcomponent.  As such it would stay there until the Message Portal returned control to the framework.  Which it wasn’t going to do until it was informed that the query response was ready for interpretation.

The problem occurred since the Message Portal should have been assigned a longer expected time interval for processing.  Although it can handle its interpretation of the request quickly enough it is going to wait until the External Database component receives the query message, presents the query to the database, and the response is transmitted back to the Database Manager subcomponent.  Therefore, the Message Portal subcomponent needed to be assigned to a longer duration thread and the topic message to its associated run queue.

With this fix everything worked fine.

Subcomponent Pause Resources:

The next modification was to implement a Pause/Continue resource similar to a semaphore for use by subcomponents. 

Components can only communicate with each other via the framework topics where one component can signal any other component that’s interested (that is, has subscribed to consume the particular topic) that there is new data to be read.  Or the consuming component can just read the latest values whenever it runs.

To retain this component independence a Pause/Continue resource was added where a particular resource can only exist for use by the subcomponents of a component. 

To implement this resource the registration of components was adjusted such that a subcomponent can supply the key of the previously registered component/subcomponent so that all the fields of the private key began to be used.  This allowed the recognition of a subcomponent group by the framework while assigning a unique key to each subcomponent.

Then a new register interface was added to request a Pause/Continue resource be assigned by supplying the component key.  The Pause and Continue interfaces are supplied the resource key which, by programming convention, is to be privately retained within the Ada package body similar to the private code of a C++ or C# class.  The framework checks that the key supplied to create the resource refers to a component and that the resource key used by a Pause or Continue request is for a subcomponent of the component that owns the resource.  Therefore, subcomponents can signal each other within a component but not other components.

Otherwise, the Pause/Continue resource is just another event as far as the framework is concerned and so was simple to implement.

The implementation allows multiple resources to be assigned to a component since more than one subcomponent might need to Pause.  Also, a resource kind was specified so that other kinds of resources can be added in the future if warranted.  

The Pause/Continue resource allowed me to replace the Ada delay loop with the invocation of a Pause and the Database Manager to signal that the query response was available by invoking the Continue.

Finishing Up:

Because of these problems I also recognized that long duration upon demand components could block each other if assigned to the same thread priority run queue.  To prevent this from happening (so that they would have to share computer execution by round robin or other means of the operating system) I modified the allocation of run queues such that only short duration components could be assigned to a shared run queue.  Therefore, upon demand (that is, event driven) long duration components will run, except for how initiated, the same as aperiodic and pseudo periodic components.




Saturday, September 18, 2010

Service-Oriented Architecture Attributes

 Service-Oriented Architecture Attributes

After reading Messaging Patterns in Service-Oriented Architecture, Part 1 by Soumen Chatterjee {http://msdn.microsoft.com/en-us/library/aa480027.aspx} and various online patterns of Enterprise Integration Patterns by Gregor Hohpe and Bobby Woolf {http://www.eaipatterns.com or http://www.eaipatterns.com/eaipatterns.html} I have decided to try to make my terminology better conform to that of the Service-Oriented Architecture (SOA) publications. 

From my recent reading of this material it seems to me that the following classifications make sense.

First, to separate the SOA attributes into the following four categories.
I:   Those that are attributes of a component,
II:  Those that are attributes of a message topic,
III: Those that are attributes of a subscription by a component to a topic, and
IV: Those that are attributes of topic readers and writers.

For instance, an attribute of a component is how it is run or scheduled.  Whether it is run upon demand such as by an event or whether it runs periodically.  An attribute of periodically scheduled as can be further described as strictly periodic as scheduled by the operating system or aperiodic such as scheduled in a forever loop with a delay.

An example of a message topic attribute could be publish-subscribe versus point-to-point.

An example of a subscription attribute could be whether the subscribing component does so as the producer or the consumer of the topic.

Therefore, based upon my reading and the attributes that I have used in my exploratory project I propose to try to make my exploratory project more consistent with the literature by using the following attribute categories.

I:   Component Attributes

The components are independent services that are loosely coupled via the message framework.  The components can be distributed among a number of different separately built and executable applications / Windows processes.  As such, a component can be moved from one application to another.  Within a particular application a component installs itself into the message controller framework.  To do so, it supplies a number of attributes to the framework.  Each application must be built upon the message controller framework.

Components of an application that cannot have all of their topic subscriptions satisfied by other components of the application will have their subscriptions dispatched to the other applications of the distributed network to find a component that can satisfy the subscription.  These pairings will be maintained by the distributed framework such that instances of a topic will be routed from one application to another and then forwarded to the remote component.

1)  Component Name

The name of the component.  This attribute is used to describe the component and to avoid the registration of duplicate components – at least, those with the same name – and for lookup in the framework tables.

2)  Activation

The Activation criteria used to activate/schedule the component.  The exploratory project options are
·        Upon Demand – the component is only run when an event is sent to it via the publishing of an Event Driven message.
·        Periodic – the component is run by the use of the operating system to begin at intervals specified at the time the component registered itself.
·        Aperiodic – the component is run via a forever loop of the framework with a following delay prior to return to the top of the loop to run the component again.  So the interval between invocations is the time the component took to finish (including when suspended due to a lower priority) and the delay specified when the component registered itself.

3)  Component Category

The Component Category attribute declares whether the component is part of the framework or not, as well, as whether it is a time-critical framework component. The options are
·        Time-Critical
·        Framework
·        User
where User is the default.

4)  Time Interval

The Time Interval attribute declares the time interval between activations of the component if it is Periodic or the delay time if it is Aperiodic.  Otherwise, for Upon Demand, it is meaningless.  The units of the time interval depend upon the operating system being used by the framework.

5)  Time Capacity

The Time Capacity attribute declares the expected execution time of the component.  The units of the time capacity are the same as for the time interval and depend upon the operating system being used by the framework.

6)  Compatibility

The Compatibility attribute is used to determine the compatibility of the component to the framework.  As yet it is unused in the exploratory project.

7)  Stack Space

The amount of stack space to be allocated for the component – if non-standard.

8)  Initialize Entry Point

This attribute is the address of / pointer to the callback to be used to allow the component to initialize itself.  Null if no initialize is necessary beyond that done when the component installs / registers itself with the framework.

9)  Main Entry Point

The Main Entry Point attribute is the address of / pointer to the callback to be used to invoke the component each time it is executed / activated.  If the component is entirely executed upon demand via event driven topics where the Topic Subscription for each topic supplies the callback to be used to notify the component of the event, then this callback should be null since no Main entry point is required.

10) Return Attributes

The Install / Register of a component with the framework returns two attributes.
a)      Whether or not the install was successful.  The possible values are
·        Valid – The component was installed,
·        Duplicate – The component was previously registered,
·        Invalid – One or more of the supplied attributes were not valid,
·        Inconsistent – The supplied attributes were inconsistent, or
·        Incomplete – Insufficient attributes were supplied
The component was not registered if the return value is anything except Valid.
b)      The private key assigned to the component by the framework to identify the component if the install was successful.  Such as to identify the component when it subscribes to a topic.  The format of the key is not visible to the component.


II:  Message Topic Attributes

Message topics are described in a topic contract Ada package / C# class.  Such a class constitutes a contract between the producer component(s) and the consumer component(s).  It includes a number of attributes, some of which will be defaulted by the framework if not supplied.  It must also provide the format of the topic message and a validation method.  Some topic contracts are paired with both a request topic and a response topic each of which has its own attributes and message format.  Each message format has a data format and a hidden header.  The hidden header has data that is only used by the framework.  The validation method can check various data items for correctness or, at a minimum, only specify whether there is a valid pointer to a data buffer.

1)  Topic identifier and name to be used to identify the topic of a message.  The topic name is used to describe the topic and to avoid the registration of duplicate topics – at least, those with the same name – and for lookup in the framework tables.  Similarly for the topic identifier in regards to duplication and lookup as well as to insert into the private message headers of the topics that are distributed between applications of the network.

2)  Topic Distribution

This category distinguishes between general topics and those that are only to have participants that are components that are part of the framework.  The options are
·        General
·        Framework Only
where General is the default.

3)  Delivery Protocol

The delivery protocol or pattern has the options
·        Point-to-Point (PPP)
·        Publish/Subscribe
For Publish/Subscribe all subscribing consumer components can read any particular instance of the topic message.  For Point-to-Point, even if there are multiple consumers registered for a topic, a particular instance of the topic is only delivered to one of the consumers (for instance, for a Delivery Identifier message exchange topic).

4)  Topic Permanence

This attribute deals with the permanence / persistence of an instance of the topic.  The options are
·        MRP for Most Recently Published – When a component runs, it can only read the most recently published instance of the topic.  The use of this attribute means that the framework can allocate message buffers based upon the number of consumers such that a consumer can examine the most recently published instance of the topic without the need for a copy of the message to be made for it to be thread-safe.  Of course this is only if the consumers are in the same application – otherwise, a copy is made to transmit the instance to another application for distribution to its consumers.
·        Queued – A copy of the topic instance is queued to be read by each consumer.  When the component runs it can read the FIFO queue to obtain the oldest entry in the queue and can continue reading until the queue becomes empty or wait until it runs again.  The size of the queue is specified for a particular consumer when it registers for the topic.

The framework may default this attribute based upon other attributes if it is able.

5)  Message Exchange

The Message Exchange attribute specifies whether or not the topic expects an exchange between a requesting component and a responding component.  The options are
·        No Exchange
·        Delivery Identifier
·        Request-Response
·        Content Filtered
No Exchange is the default where the topic contract only specifies the format of a topic to be published by one or more components and consumed by other components. 

The Delivery Identifier is a topic contract that specifies the format of a topic to be published by one component and consumed by the particular component, if any, that subscribed for the delivery identifier specified by the topic writer.  This is content filtering via the framework since the instance of the topic is only delivered to the component that subscribed for both the topic and the particular delivery id.  If no component has subscribed for the delivery identifier of the topic instance, it is discarded.

Request-Response means the topic has a paired contract consisting of a Request contract and a Response contract and that one of N different components can publish the request version of the topic and the consuming component will synchronously respond to the request with the framework only delivering the response to the requesting component.  Therefore, the topic must have Permanence of Queued and Delivery Protocol of Point-to-Point.  If the requestor did not subscribe for the response, the framework will discard the response.  Although the component that consumes the request will synchronously respond, the requestor (if it subscribed) may have to wait for the response if it does not have Upon Demand activation.  However, if the requestor subscribes for a response, it will need to have Topic Permanence of Queued.  In many cases, the Request will be used to send a command and the Response will be used to indicate whether the command was successfully performed.

Content Filtered is similar to Request-Response except that the response is not synchronous and it is implied that the request consumer will filter the data that it treats and only publish a response for the requestor when the filter conditions are satisfied.  Since the response is asynchronous, the request consumer does not need to have Upon Demand activation.  The request will specify the filter conditions that the component needs to have satisfied before a response is sent.  Such conditions can be a trigger to start sending the response when the conditions are satisfied, to only send once when the conditions are first satisfied, to send as long as the conditions are satisfied, etc.  Different requesting components can supply different values for the request filter conditions with the request consumer publishing a response for that requestor when its conditions are satisfied.  Therefore, the request topic must have the requesting component key as part of the contracted data.  Also, the request consumer / response producer component must maintain a table of the requests along with the requesting component’s private key and supply the key when it instantiates a Writer for the response.

If other versions of Content Filtered become desirable, the above described version can become Consumer Filtered since it is the consumer component that is doing the filtering.

6)  Buffer Storage Allocation

The topic buffer storage allocation attribute specifies how data buffers for instances of the topic are to be allocated.  The options are
·        Fixed
·        Reusable

Fixed allocations of the buffers are made at subscription time whereas Reusable allocations come from a buffer pool and the buffer can be reused for writing another topic when all components to read an instance of a topic have instantiated a reader and then finished running and returned to the framework.


III: Subscription Attributes

Topic subscriptions are usually (always until now) registered by a component just after it has installed itself.  The topic subscription supplies a number of attributes mating the component and the topic in the specified way.  Some of the attributes are defaulted if not supplied.

1)  Component Key

The private key that was assigned to the component by the framework to identify it at the time it successfully installed itself with the framework.  The format of the key is not visible to the component but is used by the framework to identify the subscribing component.

2)  Topic Participant Role

The role of the component in its subscription for the topic.  The options are
·        Producer – the component is registering to write and publish; that is, produce, the topic.
·        Consumer – the component is registering to read; that is, consume, the topic.

3)  New instance Detection

How the component detects a new instance of a topic.  The options are
·        Event Driven – the component is run via a notify event.  Therefore, the component must be an On Demand component.
·        Polling – the component attempts to read the topic each time it is run.  The component can be either On Demand such that it reads the particular topic when initiated for another reason or cyclic (that is, Periodic or Aperiodic).

4)  Permanence Queue Size

The size of the queue to retain instances of a topic for a particular consumer if the Topic Permanence is Queued rather than Most Recently Published.  This is a Quality of Service (QoS) value.  If not supplied, a default value is used.  When the queue becomes full, the oldest entry will be discarded and its buffer released for reuse.

5)  Subscription Duration

Whether the instances of the topic are to be durable for the consumer.  That is, whether the consumer can detect / read an instance of the topic that was published while its application had lost power or became disconnected from the network.  The use of this attribute would mean writing the instances to permanent storage such as to disk or to flash memory so they could be delivered later.

6)  Return Attributes

The subscription to the framework of a component for a topic returns one attribute as to whether the subscription was successful.  The possible values are
·        Success – the subscription succeeded,
·        Duplicate – the subscription failed due to being the duplicate of a previous subscription, or
·        Failure – the subscription failed for other reasons.


IV:  Topic Reader or Writer Attributes

An instantiated construct is returned to allow access to the current buffer for the topic each time the component requests to read or write the topic.  The construct allows access to the validation method of the topic (a callback) and supplies a pointer to the topic data in a particular message buffer. 

1)  For a Reader, the validation method can be invoked to determine if the topic data successfully passes the common verify method provided by the topic contract and whether the pointer is valid.  If so, then the component can examine and/or copy the buffered data according to the topic format supplied by the contract.  The component only needs to copy that data that the component needs to be persistent from one activation to the next.  The validation will fail if there is no new instance of the topic to be read so the component can skip the topic for the particular activation.

2)  For a Writer, a determination must be made as to whether the buffer pointer is valid using the Valid function of the Writer.  That is, if the framework was able to supply a buffer to be written to.  If so, the component can copy data to the buffer via the supplied pointer according to the topic format supplied by the contract.  When complete, the component can Publish the new instance of the topic.  The Publish has no attributes except for being the callback for the particular Publish method of the Writer.  The published topic data is not validated when published.  It is up to the Reader to validate that all necessary data was supplied and is consistent.