Lwt promise local storage, is it possible? - ocaml

I'm building an application using Lwt, and it would be nice for me to be able to have some sort of context, or promise local static storage for the life cycle of the promise. Is there any way to do this? Ideally it could be a simple Map that is available to each promise.
Ideally it would be like:
val get_lwt_context : 'a Lwt.t -> 'a Map.t
This would return the storage context for promise t. Is this possible? Is there another library that implements this?

There is indeed such a mechanism in Lwt, called implicit callback argument, see Documentation. It is considered deprecated, because it is too easy to make mistakes with it, but sometimes this is really useful for some things like logging for instance.
Such a mechanism can't be implemented by a library outside of Lwt, this needs to be handled in some way by the scheduler.

Related

Should we always use a hook or is it ok to directly call it from the client?

In React, we can use the useMutation or useQuery inside components. But let's say we want to run the query or the mutation inside a helper file (Let's say we extract the part where we format the data and execute the mutation to a helper function away from the component function). In here, we have two options:
Pass the mutation function obtained from useMutation to the helper function
Call the mutation directly inside the helper function like apolloClient.mutate
What is the most recommended way of doing things and what do you recommend?
The hooks expose additional component state for the returned data, loading state and error state. This is really just a convenience because it means you don't have to call useState yourself. As such, it's perfectly fine to use client.mutate if you don't need to keep track of those states. In a sense, it may be better since you're not needlessly using memory for variables you won't use anyway.
The same could be said for useQuery, which really just uses client.watchQuery under the hood and saves you from having to use useState and useEffect.

Events, double dispatching and abstract event handling

Imaging a simple double-dispatch event handling scheme:
It's cool. Moreover it works. However I see several issues here:
EventHandlerInterface must explicitly know all the events.
As a result of (1) handlers may have large space overhead because of subscribing for unused events.
What I want this structure to be, looks more like this:
As you can see, I want separate event types produced by different modules and I want for each module to implement only necessary event handling interfaces. I am not sure how to tie this all together. Ideally I would like to have a list of EventServices ready to accept any event.
One thing, I can think of here, is to have an inherited EventService for each EventHandlerInterface type and downcast event handlers to the certain type inside notify method. However it is not type safe and looks like an ugly idea.
Second approach, I can see, is to make EventService a template and statically check template argument to be a child of EventHandlerInterface. That would be type safe and will almost do what I want. However this way I can not store all EventServices into one list/vector as I would like to. Therefore this approach is not preferable.
Actually it feels like I am looking the wrong way but how to find the right one I don't know.
Thanks!
I am not sure the visitor pattern is the right approach for this problem. Sure it gives you a mechanism to achieve double dispatch but that's about it, and as you said it has drawbacks, e.g. the visitor (EventHandlerInterface) has to provide an overload for every different type of host (EventInterface). This creates a tight coupling and only makes sense if you add classes to the host hierarchy very infrequently.
Why not go for a solution according to the publish-subscribe pattern? It allows loose coupling and avoids the need of redundant interfaces. In brief, the publisher offers some events, to which subscribers can subscribe. When an event is triggerd, subscribers are notified and handle it. Subscribers only subscribe to events they find relevant. Different subscribers can provide different handling for the same type of event, which seems to be the purpose of double dispatch in your case.
In many languages (e.g. C#) there is special syntax for supporting this pattern easily. In C++ you need to use a library such as boost signals although there are others too. See also here for an example.

What use is the future param in NDB's _post_delete_hook method?

The signature for an NDB _post_delete_hook in GAE is:
def _post_delete_hook(cls, key, future):
I am wondering what benefit the future parameter gives. According to the docs on Key.delete, this Future will always be None. The docs even say you cannot use the Future to determine if a delete succeeded. Here they are (from Key.delete in key.py):
"""
This returns a Future, whose result becomes available once the
deletion is complete. If no such entity exists, a Future is still
returned. In all cases the Future's result is None (i.e. there is
no way to tell whether the entity existed or not).
"""
So, my question is, what use is this future parameter? Should I block on it to ensure an NDB delete is done before calling my delete hook? Or is it just a holdover/remnant from the _post_delete_hook's initial implementation and the method now has to take 3 parameters no matter what?
It's a very open ended question, so I would just like to bolster my app engine knowledge and see what you guys have in mind/how you've used it in the past.
According to documentation [1]:
If you use post-hooks with asynchronous APIs, the hooks are triggered by calling check_result(), get_result() or yielding (inside a tasklet) an async method's future. Post hooks do not check whether the RPC was successful; the hook runs regardless of failure.
All post- hooks have a Future argument at the end of the call signature. This Future object holds the result of the action. You can call get_result() on this Future to retrieve the result; you can be sure that get_result() won't block, since the Future is complete by the time the hook is called.
For me, the arg Future this is just a remanent.
[1] https://cloud.google.com/appengine/docs/standard/python/ndb/creating-entity-models#using_model_hooks

Best design pattern for event listeners

Using C++ & MFC I've created a class which makes it easier to add drag/drop functionality to a CWnd object. There is nothing special about it really. Currently it is used like so:
Create CDropListener object
Call a method on the CDropListener object saying which file extension you want it to react to and a function pointer of what to call when a file is dropped
Register this with the CWnd object
Delete the CDropListener object when the window is destroyed
Repeat all of the above steps if you want different file extensions for a different CWnd
It is a bit cumbersome having to create a class member variable for each listener, and I was just wondering which design pattern would be more suitable for this. I only need the member objects so that I can delete them at the end. I thought I could just use an array to store them in and it would simplify it a bit, but I also thought there might be a better way where you can just call a static function similar to DropListener::RegisterListener(CWnd* wnd, CString& extension, void(*callback) callback) and it handles all of the creating / registering / deleting for you.
I'm not familiar with MFC but from an OO point of view your design can be improved.
First identify what aspects of your requirements are most likely to change and then identify what the interfaces needed to isolate those changes are:
Changes:
The thing you want to listen for (the event)
The action you want to take (the callback)
Interfaces:
The mechanism of adding a callback related to an event to the event notifier
The mechanism of calling the callback from the notifier
So you need an Event interface, a Callback interface, and a Notifier interface.
In C++ there is a handy thing called std::function<T> where T is any callable type (a pointer to a function, a functor, a lambda). So you should probably use that for encapsulating your callbacks to give your user more freedom.
Then how may event types do you want to support? This will tell you whether you need to support different Event objects as well as how your registration will look:
// For example if you support just `Drop` events:
void addDropListener(std::function<T> callback);
// If you support many events:
void addListener(Event::Type evType, std::function<T> callback);
Once you have answered that you need to decide what a "callback" looks like (T in the above examples). This could return a value (if you want success verification) or throw a particular exception type (make sure to document the contract). Then ask if you want a copy of the event that was fired (usually you would). Assuming you are happy to only be notified of errors via exceptions then you can typedef the expected std::function like this:
typedef std::function<void (const Event&)> EventCallback;
I recommend then that your Notifier implementer use a std::vector<EventCallback> or std::map<Event::Type, std:vector<EventCallback>. The first one is useful if you want to only support one event type or to call all listeners for all events. The second is handy when you want to only notify listeners of certain types of event.
In any case if you are finding that you need to change your class code to accommodate minor changes to behaviour then you need some refactoring.
Hope that helped. :)

thread-safe timer for C++ callback

In a unix pthreads based app I'm working on, I have objects of a particular class (call it class foo) being created in multiple threads. I need a specific public method of class foo invoked at or after 60s of the object coming into existence (it is not imperative that it happens at precisely 60s, just that it happens at either 60s or very shortly thereafter).
Any ideas on what timers are available that could I use to achieve this? Looking for either something that I could just drop right in to my class foo or which I could derive from.
The only real requirement is that it be thread-safe.
There are various platform specific mechanisms which will allow you to force an interruption of a thread at a given time, depending on various platform specific preconditions relating to the state of the thread. These are a bad idea unless you really need them and know why.
The correct solution, given the information in your question, would be to simply check elapsed time. Presumably these threads do some work in some sort of loop. As part of this loop, you should call e.g. foo::tick() and then let tick check to see if 60s has elapsed.
Rather than using timer, why not define a static member within the class that is incremented in the constructor (with proper protection of course)? When the static member reaches 60, either invoke the member or flag that the condition has occurred and invoke elsewhere.