Is Corda InitiatingFlow thread safe? - corda

I have been using lateinits in my #InitiatingFlow for Corda, and would like to know does the basis of #InitiatingFlow makes the thread safe?
Hence if another same flow is ran at almost the same time the lateinit variable would not be overwritten by the new value.
This is due to the nature of lateinit does enable the variable to be overwritten if similarly to global variables.

Each flow is a separate instance of the InitiatingFlow class, so they each have their own copy of the lateinit variable. As a result, they are threadsafe.

Related

Best way to call an initator flow that is overriden in another cordapp

Apologies in advance for the basic question and please ignore the mix of kotlin/java!
I’ve spun up a very simple example building upon the example-cordapp and I wish to demonstrate the ability to override flows to put in some additional node operator specific logic from another cordapp. For example: a certain node owner may not want to do business under certain scenarios, so add in some additional checks prior to the initiating or responder signing phase.
I’ve successfully overridden the responder flow fine and I can see it being executed on the node with the extending cordapp however I’m not having much luck with initiator flow.
From reading here: https://www.corda.net/blog/extending-and-overriding-flows-from-external-cordapps/ it suggests that I would have to have my api/rpc client directly invoke the extended version directly, however I was hoping it would work similar to the responder flow and automatically pick it up based on the hops.
Base flow:
public class BondFlow {
#InitiatingFlow
#StartableByRPC
public static class Initiator extends FlowLogic<SignedTransaction> {
// Stuff
public Initiator(int bondValue, Party obligee, Party principal) {
this.bondValue = bondValue;
this.obligee = obligee;
this.principal = principal;
}
// More Stuff
Overridden (in a separate Cordapp):
public class MyCustomFlow {
#StartableByRPC
public static class Initiator extends BondFlow.Initiator {
// Stuff
public Initiator(int bondValue, Party obligee, Party principal) {
super(bondValue, obligee, principal);
}
// More stuff
My RPC client just calls the Initiator as you may expect:
val signedTx = proxy.startTrackedFlow(::Initiator, bondValue, obligeeParty, principalParty).returnValue.getOrThrow()
I could change my api/rpc client call to allow configuration of the initiator flow to be called but I'd like to understand if there is an alternative.
Many Thanks
I would honestly suggest that you give flows different names for each different flows. We had named a couple of our flows simple as initiator and responder out of the simplicity purpose.
However, it is still fine to have same names cross different CorDapps. You just need to call their full name including the package name.
Run flow list in your node shell and you should see it.
For example:
our signature YoFlow in the yo-Cordapp has a full name of net.corda.examples.yo.flows.YoFlow,
but in single cordapp scenario, you can just call it by run flow start YoFlow

Firestore.getInstance(): how to use?

Firebase Firestore provides the getInstance() method, which opens a socket (only one, at any time of execution of the app) and instanciates the Firestore client.
I would want to query and store data, using or not listeners (to get realtime updates, etc.). If I call getInstance as soon as I need to query or store, or if I store this instance in a static class when my app starts and then use this static class attribute as soon as I need to query or store: these 2 cases are technically the same. Because Google uses singleton pattern (getInstance()).
But am I missing something? Is it actually safe to store this instance as a static class attribute, and use it when I need it? And is it really safe to call getInstance whenever I need it? To be more explicit: between 2 calls to getInstance() (or between 2 accesses to the static class attribute), i.e.: between 2 points of execution time, is there any risk to loose network connection, socket connection, realtime listeners (snapshots) connection, etc. ?
If yes: How to handle these problem(s)?
I would want to query and store data, using or not listeners (to get realtime updates, etc.)
There is no way to get data or even get realtime updates without using a listener. Everything in Cloud Firestore is about listeners.
if I store this instance in a static class when my app starts and then use this static class attribute as soon as I need to query or store
Do not place Android context classes in static fields. Static reference to FirebaseFirestore which has field context pointing to Context will lead to a memory leak.
A static field will leak contexts. Non-static inner classes have an implicit reference to their outer class. If that outer class is for example a Fragment or Activity, then this reference means that the long-running handler/loader/task will hold a reference to the activity which prevents it from getting garbage collected.
So instead of storing it as a static variable call getInstance() whenever is needed. Or a more convenient solution would to use dependency injection. Dagger can help you solve that.
And is it really safe to call getInstance whenever I need it?
Yes it is.
between 2 accesses to the static class attribute), i.e.: between 2 points of execution time, is there any risk to loose network connection, socket connection, realtime listeners (snapshots) connection, etc. ?
Please see explanation above.
To complement Alex Mamo's answer, and avoid repeating FirebaseFirestore.getInstance() everywhere, I declared a static method called db which returns the result of the getInstance :
public static FirebaseFirestore db(){
return FirebaseFirestore.getInstance();
};
Then I use it like that :
db().collection(...)

SignalR: sub-classing my hub breaks outside calls

I'm starting from a functioning SignalR web application with an ActivityHub class derived from a SignalR Hub to manage client connections and activities. Similar to the stock ticker tutorial, there is also a singleton ActivityTimer class that uses a System.Threading.Timer to periodically broadcast to all clients via the hub context it gets in its constructor, like this:
activityHubContext = GlobalHost.ConnectionManager.GetHubContext<ActivityHub>();
Now I want to turn my ActivityHub into a base class with sub-classes for different kinds of activities, overriding a few methods in ActivityHub for activity-specific behaviors, and using activity-specific clients which each reference the appropriate activity sub-class (e.g., var activityHub = $.connection.coreActivityHub).
The sub-classing works for the hub server code and clients, and the ActivityTimer fires timer events as intended, but the ActivityTimer calls no longer reach the clients. If I get the hub context for a specific activity sub-class, it works again, but only for that sub-class:
activityHubContext = GlobalHost.ConnectionManager.GetHubContext<CoreActivityHub>();
Is there a way to have a single, generic ActivityTimer that will work with all sub-classes of ActivityHub? Can the ActivityTimer call some method in the base ActivityHub class rather than trying to reach all the clients directly (the base class seems to have no problems calling Clients.All.doSomething())?
In case it simplifies things (or makes possible an otherwise challenging solution), the application will only be running one type of activity at a time -- all clients will be on the same activity at one time.
In working on a different issue in the same project, I came across this, which points to this, where I also found this (all worth a quick read if the topic interests you). They provide one way to do what I was trying to do: have a method in the base class that can be called from "outside" to reach clients of any/all sub-classes. (They also helped me to think more clearly about the hub context, and why I believe my original ActivityTimer cannot work with sub-classes -- see note at the end of this answer for further explanation).
The solution to my problem is to create a method in the base class that does the call to the clients, and then call this new method from the ActivityTimer to reach the clients indirectly. This approach does not rely on having a hub context within ActivityTimer, and it frees us from worry about sub-classes because it calls into the base class explicitly:
Create a static field in the base class to hold the base class's hub context:
private static IHubContext thisHubContext;
Set this hub context in each sub-class's constructor with that class as the type passed to GetHubContext():
thisHubContext =
GlobalHost.ConnectionManager.GetHubContext<CoreActivityHub>();
Create a static method in the base class that calls the desired client-side method(s); note that you could use other options than Clients.All to reach a subset of clients (for example, the arg might designate a SignalR group to reach):
public static void DoSomething(string someArg)
{
thisHubContext.Clients.All.doSomething(someArg);
}
Call this base-class method from any server code that is "outside" the hub. In my case, I call it from the timer event handler in ActivityTimer:
ActivityHub.DoSomething("foo");
The messages will get through to the clients specified in the static method.
NB: this solution only works for the particular case mentioned at the end of the original post, in which only one sub-class is ever in use at a time, because each sub-class sets the base class static hub context to its own context. I have not yet tried to find a way around this limitation.
Note: I don't think it's possible to have "outside-the-hub" server code work with sub-classes by way of a stored hub context. In my original, functioning app (before I tried to create sub-classes of the ActivityHub), the ActivityTimer talks to the clients by means of a hub context that it gets on instantiation:
public ActivityTimer()
{
activityHubContext = GlobalHost.ConnectionManager.GetHubContext<ActivityHub>();
activityTimer = new Timer(DoSomething, null, TimerInterval, TimerInterval);
}
public void DoSomething(object state)
{
activityHubContext.Clients.All.doSomething("foo");
}
Because the hub context is obtained by explicit reference to a particular class (in this case, ActivityHub), it will not work with a sub-class. If instead (as I mentioned trying in my original post) I get the hub context for a particular sub-class, the timer will now work for instances of that sub-class, but not other sub-classes; again, the problem is that the hub context is obtained for a particular sub-class.
I don't think there's any way around this, so I think the only solution is the one outlined above in which the base class method uses the hub context set by the sub-class constructor, and the outside code calls the base class method to get to the clients by way of that sub-class context.
However, I'm still on the SignalR learning curve (among others) so will appreciate any corrections or clarifications!

Why doesn't Kotlin allow to use lateinit with primitive types?

In the Kotlin language we, by default, have to initialize each variable when it is introduced. To avoid this, the lateinit keyword can be used. Referring to a lateinit variable before it has been initialized results in a runtime exception.
lateinit can not, however, be used with the primitive types. Why is it so?
For (non-nullable) object types, Kotlin uses the null value to mark that a lateinit property has not been initialized and to throw the appropriate exception when the property is accessed.
For primitive types, there is no such value, so there is no way to mark a property as non-initialized and to provide the diagnostics that lateinit needs to provide. (We could try to use a separate marker of some kind, but that marker would not be updated when initializing the field through reflection, which is a major use case of lateinit).
Therefore, lateinit is supported for properties of object types only.
A short answer is that with primitives you can always use 0 as the default, and with nullable types null as a default. Only non-nullable non-primitive types may need lateinit to work around the type safety system.
Actually, there is no need for initializing a variable in Kotlin as long as it has a value before the first access and it can be statically proved. Which means this code is perfectly valid:
fun main(args: Array<String>) {
var x: Int
val y: Double
x = 0
y = x + 0.1
println("$x, $y")
}
But there are (rare) cases when the initialisation cannot be statically proved. The most common case is a class field which uses any form of dependency injection:
class Window {
#Inject lateinit parent: Parent
}
I think that in case of primitives it's less resources taking to simply initialise it to let me say 0 and hold the simple value in memory rather than store extra information about the object nullability which is used by lateinit mechanism.
Correct me if it's not the case.

Simple Injector LifetimeScope with DbContext

I am using simpleInjector 2.8.0.0 I would like to construct just one instance of a dbContext during a lifetime scope.
(My dependency chain has 2 dependencies on IDatabaseContext/DbContext)
I have a scope decorator which implements the lifetime scope (The scope decorator is being injected into a SignalRHub):
using (ServiceHost.Container.BeginLifetimeScope())
{
var commandHandler = ServiceHost.Container.GetInstance<ICommandHandler<TCommand>>();
//constructs 2 DbContexts.
commandHandler.Handle(command);
}
I have a lifetime scope registration for the IDatabaseContext:
container.RegisterLifetimeScope<IDatabaseContext, DatabaseContext>();
However, I can see (from a Guid) that I am creating 2 instances of the IDatabaseContext/DbContext within the scope.
Are you sure this is the same scope? Either you are nesting scopes, or you what you see is two actual request being handled. In the debugger, you might be able to view request information, for instance by inspecting the HttpContext.Current.Request.Url property.

Resources