How to create 'globally' scoped variables that are global only during one request? - perl

When a request hits my dancer2 app I want to set up an object that is accessible by all packages involved in handling this request.
How can I make sure that this object has a scope only within this individual request and is not accessible by other requests?
Specifically this object should be filled with messages of all kinds (errors, warnings, debug messages, etc.) as execution travels through my libraries.
Obviously, those messages are request-specific and I am afraid that naively declaring a global reference to this message object is exposing it to all requests hitting the app.
I was thinking about creating an instance of this message class in the router and then passing a reference to it throughout all methods involved in handling this request.
My gut feeling tells me that I am missing something fundamentally here architecture-wise regarding dancer2, so I decided to ask you. It's my first post here, by the way, so I apologize for any shortcomings my question may have.

It looks to me like you could use a var to hold your object.
See https://metacpan.org/pod/distribution/Dancer2/lib/Dancer2/Manual.pod#var
If you need it to be accessible even from methods that aren't aware of Dancer, you could use a var and also store your object in a global variable using a weak reference.

Related

Where was global scope in playframework and what are the benefits of it going away?

I am reading that the playframework is removing global state that is in older 2.4.x versions.
Can someone explain where the global state currently is and what are the benefits of removing global state?
What is the global state?
There is an object play.api.Play with the following field:
#volatile private[play] var _currentApp: Application = _
Where is it used?
Whenever you do Play.current you refer to that single mutable global field. This is used all across the framework to access things such as:
play.api.Play.configuration takes an implicit app
play.api.libs.concurrent.Execution.defaultContext calls the internal context, which uses the currently running app to get the actor system
play.api.libs.concurrent.Akka.system takes an implicit app
play.api.libs.ws.WS.url takes an implicit app
and many more places..
Why is that bad?
A number of functions just take an implicit app, so that's not really global state, right? I mean, you could just pass in that app. However where do you get it from? Typically, people would import play.api.Play.current.
Another example: Let's say you want to develop a component that calls a webservice. What are the dependencies of such a class? The WSClient. Now if you want to get an instance of that, you need to call play.api.libs.ws.WS.client and pass in an application. So your pretty little component that logically only relies on a webservice client, now relies on the entire application.
Another big factor and a direct consequence of the previous point is testing. Let's say you want to test your webservice component. In theory, you'd only need to mock (or provide some dummy implementation of) the webservice client. However now that somewhere in your code you're calling play.api.Play.current, you need to make sure that that field is set at the time it is called. And the easiest way to ensure that is to start the play application. So you're starting an entire application just to test your little component.

asp.net mvc accessing class fields from a custom auth attribute

I am using a custom AuthAttribute to determine whether a user can access a controller and/or actions. The problem is I have to duplicate information and EFx connections in the attribute that already exist on the class that is being adorned.
My question is whether there is a way to access the fields on the adorned class from the custom AuthAttribute? I am trying to avoid having to re-architect the software in a way that would provide a single point of access since that would open up a different can of worms.
I believe I have found an answer that works. I welcome all comments on this solution.
Rather than have the attribute gain access to the properties and fields on the controller it adorns you can share values between them in a thread-safe way through the common HttpContext object. So if you are being extreme like I am and are trying to cut down on duplicate calls to your database in both the authattribute and the adorned controller action then pass the results forward. What that means is the authattribute will be called first and you can stash the retrieved values in the "Items" collection off the HttpContext object passed into the AuthorizeCore(..) method. You can then retrieve the same value in a THREAD-SAFE way through the HttpContext object in the controller.
example to save value within the AuthorizeCore(..) override of the AuthAttribute:
httpContext.Items.Add("fester", "bester");
example to retrieve value inside the subsequent call to the Controller/Action:
this.HttpContext.ApplicationInstance.Context.Items["fester"];
I have to warn you this is only a possible implementation that appears to work in simple testing. Personally it feels like a hack and there has to be a better way. I would also state this is in pursuit of a dubious performance benefit. It should cut down on the number of database and/or network calls by cache'ing retrieved data in the HttpContext so you don't have to repeat the calls in both the authattribute and the adorned Controller/Action. If you don't have a web site that gets a huge volume of calls then I would warn you against this.
I hope someone recommends something better on this page. I will keep an eye on how this works on my web site and let y'all know if it behaves and is truly thread-safe.

Managing non-serializable objects at the session level

My Wicket application integrates a couple of third party services. When a user authenticates to the app, one of the services instantiates a client object tied to that particular user.
Instantiating the client is quite expensive, so re-instantiating it with every request isn't quite an option. Were the client serializable, I'd keep a reference in the session, but since it isn't, I'm maintaining a map of clients at the application level, keyed by session. It works, but it's a little kludgy, particularly when a session expires or something else misbehave and the map is out of sync.
I'm wondering if there might be any other options to that problem. I was thinking along the line of intercepting the serialization of the session, and maintaining the client instances in memory instead.
Any suggestions?
DON'T DO THIS!
As per tetsuo's comment, this approach wouldn't work.
Original, non-working proposition
Besides an HttpSessionListener, you could also use a WeakHashMap in your application. You can then keep the key to your client objects in the Wicket Session. When the session is destroyed, the corresponding key-value entry in the map will be garbage-collected automatically.
See this explanation of weak references in Java.

iOS/Objective-C Multiple URL Connections

I have a few apps that I am trying to develop a reusable URL connection layer. I have done some research and am struggling between architectures. Specifically the APIs this layer utilizes.
In the past, I have used NSURLConnection and NSOperation on a separate RunLoop. This seems overkill. I've seen libraries that subclass NSURLConnection. Others have a singleton Engine object that manages all requests.
The Engine and/or NSURLConnection seem best to me. But I am asking for input before I go too far down one road. My goals would be:
Ability to cancel a request
Concurrent requests
Non-blocking
Data object of current open requests
Any direction or existing references with code samples would be greatly appreciated.
I'm not sure about a "data object of current open requests", but ASIHTTPRequest does the first three and is very easy to use.
Update
Actually, it looks like ASINetworkQueue may fulfill your last bullet point.
I personally use a singleton engine with my large Apps though it might not always be the best case. All the URL's I use require signing in first, figured it would be best if one Class handles all of the requests to prevent multiple URLS from signing into the one location.
I basically create a protocol for all my different connection classes into my singleton and pass the delegate of both the calling class and the singleton into it. If an error occurs its passed to the singleton so it can deal with it, if it completes it returns the data to the calling class.

iphone RESTful webservices

Not even sure if the title is correct, however, what I'm trying to do is use the standard NSURLConnection class to handle responses from calling my webservice. I am using the POST method to update a database and the GET method to retrieve rows from the database. The problem I have is that these 2 actions may occur simultaneously so that the methods to handle the request may step on each other. In other words in my "connection didReceiveData" method I have 2 paths through the code depending on whether I'm handling a response from a GET or POST request.
I keep track on which request in being processed by an instance variable called requestType. The problem is that since the requests are being executed simultaneously the instance variable is being changed from GET to POST before the GET completes (or vice-versa). My question is how do I maintain 2 separate requests in this scenario? Do I synchronize the requests? Is there a way for threads to work here? Do I create 2 separate objects for each of the requests and have the logic in "didRecieveData" query for which object is being processed? Any help would be much appreciated!!
Dealt with a similar issue in one of our apps. The solution involved creating a class that represents a webservice call, responsible for calling its own url, loading its own data, etc. The call class had a delegate that would handle parsing the responses (in our case, a web service controller). Wound up getting rather complicated, but prevented the issue of NSURLConnections stepping on each other.
Seems like you've created a messy problem by having a class that tries to do too many things. I would suggest taking one of the following three approaches:
1) Write two classes, one for updates and one for retrievals. Each class creates it's own private NSURLConnection object and acts as the delegate for the async notifications received from the NSURLConnection. The classes could possible share some utility parsing code or extend a base object that has that parsing code in it. But the key being that the code calling these classes would instantiate one of them, make the call, and then release it. This will keep your code cleaner and will insure that the event notifications don't get intermingled.
2) Create a single class that, depending on initialization, does either a post or a get with it's own private instance of NSURLConnection. When a call needs to be made, instantiate the class, get the results, and then release the class.
3) Write your connection handling classes so they use the synchronous NSURLConnection method and call that call that class in a background thread.
Either way, clean code and clear object orientation will prevent messy scenarios like the one you're describing.
Create separate objects that handle the calls. If you want to issue multiple requests at once I would strongly recommend looking at NSOperationQueue, and making these objects subclasses of NSOperation... much nicer way to deal with multiple background requests.
A good example is here:
http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/
The idea there is that you use the non-asyncronous web calls, in operations that are run on separate threads. You can still use asynch calls in NSOperation as well, but doing so is a little trickier and for simple calls you probably do not need to.