How to create a ClusterSingleton actor in F# - f#

It is simple to create Akka.NET actors in F# using the functional pattern, like actorOf2:
let aref = spawn system "my-actor" (actorOf2 myFunction)
but there are other actors like the ClusterSingleton that require using an OO approach so I can get the actor by type:
type MySingletonActor() =
inherit UntypedActor()
// then something like
system.ActorOf(ClusterSingletonManager.Props(Props.Create<MySingletonActor>() ... )
Is there any way to use the functional pattern from F# to create an actor for use as a ClusterSingleton?

Related

F# code quotations: can I define my own concrete and abstract syntax?

In Haskell I can use the quasiquoter to produce a custom AST using concrete syntax defined by custom parser, as described here: https://wiki.haskell.org/Quasiquotation
Is this possible in F#?
The closest thing I can think of is F#'s TypeProviders.
It allows provider code to be part of the compiler pipeline, and constructs types to be injected.
For example, there's the XML type provider:
type Author = XmlProvider<"""<author name="Paul Feyerabend" born="1924" />""">
let sample = Author.Parse("""<author name="Karl Popper" born="1902" />""")
printfn "%s (%d)" sample.Name sample.Born
For more, see the FSharp.Data project.

NSubstitute and FSharp - Mocking an FSharp Function

Given an interface that has a FSharp style function.
type IUseless =
abstract member Listify: string -> int -> string list
How would you mock the function?
let substitute = NSubstitute.Substitute.For<IUseless>()
substitute.Listify.Returns(??? what would even go here ???)
I wouldn't expect to be able to mock it like a normal method, or a value that contains a function (although that's sort of what it represents).
So I'm curious if anyone has successfully mocked an FSharp function with a typical .NET mocking library.
First: yes, you can totally mock this like a normal method:
let substitute = NSubstitute.Substitute.For<IUseless>()
(substitute.Listify "abc" 5).Returns ["whatevs"]
This works, because F# compiles this definition like a normal .NET method, despite the curried syntax. This is done partly for interop and partly for performance.
But second: if I were you, I would rather skip the whole NSubstitute business altogether and use inline interface implementation instead:
let substitute = { new IUseless with member x.Listify a b = ["whatevs"] }
This is cleaner, better typechecked, and a lot faster at runtime.

ocaml, Functors : dependency injection

In Real World Ocaml Chapter 9 which is about functors :
Dependency injection
Makes the implementations of some components of a system swappable. This is particularly useful when you want to mock up parts
of your system for testing and simulation purposes.
But I fail to grasp the idea.
I also looked at Wikipedia about DI - but I actually do not catch the relaton with testing and simulation purposes.
Dependency injection is a software engineering technique, whose purpose is to reduce the interdependencies between two subsystems of a program. A very important detail of this technique, is that it involves not two, but three subsystems:
a service,
a client using a
an injector, whose responsibility is to prepare a service for a client.
The latter subsystem, with its responsibility, an often overlooked but crucial detail: this implies that the client knows as little about the service as its public interface, which means that one can easily use a mocked service to test the client.
Assume that we write an application communicating with a key-value store over the network. The key-value store has the following signature:
module type AbstractKeyValueStoreService =
sig
exception NetworkError
type t
val list : t -> string
val find : t -> string -> string option
val set : t -> string -> string -> unit
end
If we write our client code as a client parametrise by a module of type AbstractKeyValueStoreService we can test the resilience of our application to network errors when using the set function by just providing a mocked service, without needing to actually create the network error:
module KeyValueStoreServiceFailingOnSet =
struct
exception NetworkError
type t = unit
let list () = [ "a"; "b"]
let find = function
| "a" -> Some("x")
| "b" -> Some("y")
| _ -> None
let set _ _ = raise NetworkError
end
If our client is written as functor parametrised by a module of type AbstractKeyValueStoreService it is easy to write tests for this software component, where a mocking service follow a more-or-less complex interaction script with the client.
Using modules as parameters might not be an “earth shaking idea” it is nevertheless important to be aware of how this idea can be used to solve important software engineering problems. This is what the authors of “real world OCaml” seem to do.
It seems to me they're just trying to show how the term "dependency injection" can be seen to refer to parameters that are full modules. And that's what OCaml functors are: modules with parameters that are also modules.
This has many uses, not just testing and simulation. But certainly you can use it for those. For example, you can use it to supply a "mock" module during testing, to replace some part of the system that's difficult to reproduce exactly in the test environment.
One way to look at this is that "dependency injection" isn't as interesting or novel as its adherents might want you to think. At least that's what I think personally. Using modules as parameters isn't an earth shaking idea, it's been around for decades in the ML languages. In Angular (at least), this is mixed up with a separate notion, that of having the names of function parameters be semantically meaningful. That (IMHO) is a mistake.

Why is FSharp.Data.SqlClient record exposed as object?

I'm working on a demo where I can show how easy it is to use the SqlClient type provider in a F# library and then consume it from C#, I think this might be one way to get things into projects. Since many people using C# want to use interfaces etc. I thought I show them that it is possible to combine everything, but I don't get the expected result. I have the following F# code which works as expected in F#:
module Orders =
[<Literal>]
let connStr = """XXXXXXXXXXXX"""
type OrdersPerEmployee = SqlCommandProvider<"OrdersPerEmployee.sql", connStr>
open Orders
type IOrdersRepo =
abstract member getOrdersPerEmployee : int -> OrdersPerEmployee.Record seq
type OrdersRepo() =
interface IOrdersRepo with
member this.getOrdersPerEmployee(employeeId) =
let query = new OrdersPerEmployee()
query.Execute(employeeId)
But when I try to use it from my C# app I don't get that the getOrdersPerEmployee returns an enumerable of records, instead it returns an enumerable of objects:
IOrdersRepo repo = new OrdersRepo();
var data = repo.getOrdersPerEmployee(4).ToList();
data.ForEach(y => Console.WriteLine(y));
Console.ReadLine();
In the code above I expceted to get intellisense on y in the lambda, but nothing. Any ideas?
Because SqlCommandProvider is erasing types kind. It means types it generates can be consumed only from F#. Contrary, SqlEnumProvider from the same FSharp.Data.SqlClient library is generated types kind and can be consumed by C# (via proxy project). It works especially nice when CLIEnum=true.
For a deeper discussion on erased vs generated types see
How do I create an F# Type Provider that can be used from C#?

Pluggability in a functional paradigm

What is the proper functional way to handle pluggability in projects? I am working on a new opensource project in F# and can not seem to get the object oriented idea of plugins and interfaces out of my mind. Things I would like to be able to swap out are loggers, datastoring, and authentication.
I have been searching quite a bit for an answer to this and havent come up with much except for this:
http://flyingfrogblog.blogspot.com/2010/12/extensibility-in-functional-programming.html
The answer to this question would be different for different functional languages. F# is not purely functional - it takes the best from functional, imperative and also object-oriented worlds.
For things like logging and authentication, the most pragmatic approach would be to use interfaces (in F#, it is perfectly fine to use interfaces, but people do not generally use inheritance and prefer composition instead).
A simple interface makes sense when you have multiple different functions that you can invoke:
type IAuthentication =
abstract Authenticate : string * string -> bool
abstract ResetPassword : string * string -> void
You can use object expressions, which is a really nice way to implement interfaces in F#.
If you have just a single function (like logging a message), then you can parameterize your code by a function (which is like an interface with just a single method):
type Logger = string -> unit
For things like authentication and logging (that probably do not change while the application is running), you can use a global mutable value. Although if you want to synchronize requests from multiple threads and there is some mutable state, it might be a good idea to write an F# agent.

Resources