开发者

Rails w/custom TCP data service

开发者 https://www.devze.com 2023-01-08 20:54 出处:网络
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

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>开发者_C百科;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:

  1. 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.
  2. 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.


Consider moving the API access to a new class, and store the TcpSocket instance and the context ID there. Change your models to talk to this API access class instead of talking to the socket themselves.

Add an around_filter to your controller(s) that pulls the context ID out of the session, stores it into the API access class, and nils it after running the action. As long as your Rails processes remain single-threaded, you'll be fine. If you switch to a multi-threaded model, you'll also need to change the API access class to store the context ID and the TcpSocket in thread-local storage, and you'll need one TcpSocket per thread.

0

精彩评论

暂无评论...
验证码 换一张
取 消