I'm building a Rails app that needs to connect to a custom TCP data service, which uses XML messages to exchange data. Functionally, this is not a problem, but I'm having trouble architecting it in a way that feels "clean".
Brief overview:
User logs in to the Rails app. At login, the credentials are validated with the data service and a "context id" is returned.
Request:
<login><username>testuser</username><password>mypass</password></login>
Response:
<reply><context_id>123456</context_id></reply>
This context_id is basically a session token. All subsequent requests for this user must supply this context_id in the XML message.
Request:
<history><context_id>123456</context_id><start_date>1/1/2010</start_date><end_date>1/31/2010</end_date></history>
Response:
<reply><history_item>...</history_item><history_item>..</history_item></reply>
I have hidden away all the XML building/parsing in my models, which is working really well. I can store the context_id in the user's session and retrieve it in my controllers, passing it to the model functions.
@transactions = Transaction.find( { :context_id => 123456, :start_date => '1/1/2010', :end_date => '1/31/2010' } )
From a design point of view, I have 2 problems I'd like to solve:
- Passing the context_id to every Model action is a bit of a pain. It would be nice if the model could just retrieve the id from the session itself, but I know this breaks the separation of concerns rule.
- There is a TcpSocket connection that gets created/destroyed by the models on every request. The connection is not tied to the context_id directly, so it would be nice if the socket could be stored somewhere and retrieved by the models, so I'm not reestablishing the connection for every request.
This probably sounds really convoluted, and I'm probably going about this all wrong. If anybody has any ideas I'd love to hear them.
Technical details: I'm running Apache/mod_rails, and I have 0 control over the TCP service and it's architecture.