Skip to content

Latest commit

 

History

History
320 lines (258 loc) · 17.1 KB

fsharp.md

File metadata and controls

320 lines (258 loc) · 17.1 KB

F#

Only one part of Scry's client is tied to C#: the source generator. It is a Roslyn generator, so it runs only in a C# project. Everything after it is language-neutral. The capture provider, the translator, the terminals and the wire all work on expression trees, and an F# lambda passed to a LINQ extension method is converted into the same expression tree as a C# lambda. So an F# client needs one C# project between it and the model, and nothing else changes.

The sample includes a working example. Sample.QueryModels contains the generator's output, Sample.FSharp writes queries against it, and Sample.FSharp.Tests runs them through the real server.

The query models project

This is a C# class library with no source files of its own. It points at the model DLL by path and references Scry.Client, which includes the generator:

<PropertyGroup>
  <TargetFramework>net11.0</TargetFramework>
  <Nullable>enable</Nullable>
  <ImplicitUsings>enable</ImplicitUsings>
  <IsPackable>false</IsPackable>
  <!-- The server model, pointed at by path. NOT referenced. -->
  <ScryModelDll>$(MSBuildThisFileDirectory)..\Sample.Model\bin\$(Configuration)\net11.0\Sample.Model.dll</ScryModelDll>
</PropertyGroup>

<ItemGroup>
  <ProjectReference Include="..\..\src\Scry.Client\Scry.Client.csproj" />
</ItemGroup>

snippet source | anchor

The project's whole public surface is what the generator emits: a query model per source, the re-emitted enums, and the ScryQuery entry point. The generator wiring is the same as for any C# client. It is automatic with the NuGet package, and written out in the sample because the sample uses project references (Source generator).

The generated types always go into the Scry.Generated namespace, so a consumer can reference only one such project. The sample's Blazor client generates its own copy. That is why the F# tests host the server themselves rather than referencing Sample.WebServer: Sample.WebServer includes the Blazor client, and the compiler rejects two copies of Scry.Generated.ScryQuery among one assembly's references as ambiguous.

The F# project

The F# project references the query models project, and through it Scry.Client. It does not reference the model:

<ItemGroup>
  <!-- The generated query models, and through them Scry.Client. The model itself is not referenced. -->
  <ProjectReference Include="..\Sample.QueryModels\Sample.QueryModels.csproj" />
</ItemGroup>

snippet source | anchor

One F#-specific note: under central package management, the F# SDK turns off its implicit FSharp.Core reference, so a project in such a tree has to reference it explicitly. Without that reference the assembly still builds, because the compiler falls back to the SDK's own copy, but every type then fails to load at runtime.

Writing queries

Queries use the LINQ extension methods with F# lambdas. Where the body is a member chain, the _.Member shorthand can be the whole lambda. A body that constructs a record or applies an operator needs a named parameter. A projection is a record, named or anonymous, and its field names are the keys the response comes back with:

/// A shape the client declares for itself, as the Blazor sample's EmployeeRow is. The constructor's
/// parameters name the projection's members, so the response comes back keyed by these names.
type EmployeeRow =
    { Name: string
      Status: Status
      Manager: string
      Department: string }

snippet source | anchor

/// A filter, an ordering, and a projection that reaches through two navigations. Each lambda is
/// converted to an expression tree at the call site, as a C# lambda is, so the request that
/// leaves is the one the C# spelling sends.
let activeEmployees (query: ScryQuery) =
    query.Employee
        .Where(_.Active)
        .OrderBy(_.Name)
        .Select(fun e ->
            { Name = e.Name
              Status = e.Status
              Manager = e.Manager.Name
              Department = e.Department.Name })

snippet source | anchor

An F# record compiles to a constructor that takes every field. The translator reads member names from the constructor's parameters, capitalized, which is the same rule a C# record follows (Projections).

An anonymous record needs no declaration:

/// An anonymous record declares nothing. Its fields may be written in any order — the compiler
/// sorts them by name, and the query is the same either way.
let headcount (query: ScryQuery) =
    query.Employee
        .GroupBy(_.Department.Name)
        .Select(fun g -> {| Headcount = g.Count(); Department = g.Key |})

snippet source | anchor

The compiler sorts an anonymous record's fields by name. When the fields are written in a different order, the compiler first binds each field to a variable, with one let per field in the order written, and then constructs the record from the variables. That way the fields are still evaluated in the order written. The translator inlines those bindings. A query only reads the row and computes nothing else, so replacing each read of a variable with the expression bound to it gives the same query. The same inlining covers a let written by hand:

/// A let inside the lambda is inlined: wherever the binding is read, the query reads what was
/// bound to it, so the row is read twice here and nothing is computed on the client.
let namedLike (query: ScryQuery) (fragment: string) =
    query.Employee
        .Where(fun e ->
            let name = e.Name.ToLower()
            name.Contains fragment && name.Length > 2)
        .OrderBy(_.Name)
        .Select(fun e -> {| Id = e.Id; Name = e.Name |})

snippet source | anchor

Values captured from the enclosing scope are evaluated on the client and sent as constants, as with C# closures. The generated models declare an optional column as Nullable<int> rather than int option, so comparisons on it use the nullable operators:

/// Parameterized by values captured from the enclosing scope, which are evaluated here and sent
/// as constants. A nullable member is compared with the nullable operators, which lift the
/// constant the way C# lifts it.
let reportsTo (query: ScryQuery) (managerId: int) (top: int) =
    query.Employee
        .Where(fun e -> e.ManagerId ?= managerId)
        .OrderBy(_.Name)
        .Take(top)
        .Select(fun e -> {| Name = e.Name; Status = e.Status |})

snippet source | anchor

The terminals are the client's own, so a query runs inside a task like any other awaitable. A terminal that takes a predicate translates it the same way:

/// The terminals are the client's own, so a query runs inside a task like any other awaitable.
let activeEmployeesAsync (query: ScryQuery) =
    task {
        let! rows = (activeEmployees query).ToListAsync()
        return rows
    }

/// A terminal that takes a predicate of its own translates it the same way.
let activeCountAsync (query: ScryQuery) =
    query.Employee.CountAsync(_.Active)

snippet source | anchor

A live query can be read as the IObservable<T> that ships with .NET, which is the interface FSharp.Core's Observable module works with. So F# can compose a live query without any reactive package:

/// A live query as an observable, composed with FSharp.Core's own Observable module. There is no
/// reactive package here: Scry hands over the IObservable that ships with .NET, and F# already
/// knows what to do with one. Each answer is the whole current result.
let activeNames (query: ScryQuery) : IObservable<string list> =
    (Queries.activeEmployees query).Live().AsObservable()
    |> Observable.map (fun rows -> rows |> Seq.map _.Name |> List.ofSeq)

snippet source | anchor

Read as a stream, a live query is an IAsyncEnumerable<T>. F# has no for loop over one inside a task, so the code advances the enumerator by hand:

/// The same live query read as a stream: an IAsyncEnumerable, pulled one answer at a time until
/// the token is cancelled, which is also what tells the server the subscription is over.
let watch (query: ScryQuery) (onAnswer: EmployeeRow list -> unit) (cancel: CancellationToken) =
    task {
        use answers =
            (Queries.activeEmployees query).Live().GetAsyncEnumerator cancel

        let mutable more = true

        while more do
            let! next = answers.MoveNextAsync()
            more <- next

            if more then
                onAnswer (List.ofSeq answers.Current)
    }

snippet source | anchor

Sending commands

F# sends a command the same way C# does: create the generated class, set its properties in the constructor call, and await the facade method like any Task. For a command with a result, read the result through the typed outcome.

/// A command from F#: the generated class, its properties set in the constructor call, sent through
/// the generated facade. The outcome is a Task like any other — Completed where the server decided
/// it within its sync window, Pending with its Completion to await where it did not.
let rename (query: ScryQuery) (id: int) (name: string) =
    query.Commands.RenameEmployee(RenameEmployee(Id = id, Name = name))

/// A command that answers with a result: the typed outcome's Value is the class the handler
/// answered with, read only once EnsureCompleted has said the command did complete.
let hire (query: ScryQuery) (name: string) (departmentId: int) =
    task {
        let! outcome =
            query.Commands.CreateEmployee(CreateEmployee(Name = name, DepartmentId = departmentId, Status = Status.FullTime))

        return outcome.EnsureCompleted().Value.Id
    }

snippet source | anchor

Sample.FSharp.Tests/CommandTests.fs sends both to the sample's own handlers, and checks that a live query receives the rename.

What to avoid

query { }. F#'s query builder rewrites a select of a record or a tuple into two Selects: one into an intermediate object of its own, and one back. The server accepts only one Select per query, so it rejects the request. A query { } that only filters and orders translates; a projection needs the extension methods.

Nullness checking. The sample leaves F#'s nullness checking off. With it on, reading a navigation inside a query lambda produces a warning that the navigation may be null. That is true of the model, but not a problem for the query: a null navigation is null in SQL too, and the translated query reads through it the same way the C# _.Manager!.Name does.

Bare values. A projection must construct an object. Select(fun e -> e.Name) is rejected, as it is in C# (Projections).

Testing from F#

Sample.FSharp.Tests hosts the sample server in-process, against LocalDB, and registers it from F#:

/// The sample server hosted in-process, as Sample.Tests hosts it, against a LocalDB database cloned
/// from a seeded template. Registered from F# to show that the server side reads the same either way.
type ScryServer private (app: WebApplication, database: SqlDatabase<SampleContext>) =
    // A LocalDB instance of its own. The instance is named after the context by default, which
    // Sample.Tests already uses, and the two projects run in parallel under one dotnet test: both
    // rebuilding the one template at once deadlocks inside SQL Server.
    static let sqlInstance =
        new SqlInstance<SampleContext>(
            constructInstance = (fun builder -> new SampleContext(builder.Options)),
            buildTemplate =
                (fun context ->
                    SampleContext.Initialize context
                    Task.CompletedTask),
            storage = Storage.FromSuffix<SampleContext> "FSharp")

    /// A suffix gives a fixture that writes a database of its own, so the fixtures that snapshot the
    /// seed never see what it changed.
    static member StartAsync(?databaseSuffix: string) =
        task {
            let! database = sqlInstance.Build(databaseSuffix = defaultArg databaseSuffix null)
            let builder = WebApplication.CreateBuilder()
            builder.WebHost.UseTestServer() |> ignore

            // The interceptor reports what this context saves, which is what makes a live query hear
            // of it. Resolved rather than constructed, so it reports to the place the server listens.
            builder.Services.AddDbContext<SampleContext>(fun (services: IServiceProvider) (options: DbContextOptionsBuilder) ->
                options
                    .UseSqlServer(database.ConnectionString)
                    .AddInterceptors(services.GetRequiredService<ScryChangeInterceptor>())
                |> ignore)
            |> ignore

            // The sample's command handlers: the C# project every host with commands on shares.
            builder.Services.AddSampleCommandHandlers() |> ignore

            builder.Services.AddScry<SampleContext>(fun options ->
                options.AddPocoSource(fun _ -> Holiday.Seed())
                options.AddAttachmentPolicy<Department, HandbookPolicy>()
                options.AddAttachmentPolicy<Employee, PhotoPolicy>()

                // Live queries are off until a server says how many it will hold open, and commands
                // until it says how many it may have in flight.
                options.MaxSubscriptions <- 10
                options.SubscriptionThrottle <- TimeSpan.Zero
                options.UseSampleCommands() |> ignore)
            |> ignore

            let app = builder.Build()
            app.MapScry "/api/query" |> ignore
            do! app.StartAsync()
            return new ScryServer(app, database)
        }

    /// The generated entry point over an HTTP client into the hosted server.
    member this.Query = ScryQuery(ScryClient.ForHttp(this.Http, "/api/query"))

    /// An HTTP client into the hosted server.
    member _.Http = app.GetTestClient()

    interface IAsyncDisposable with
        member _.DisposeAsync() =
            ValueTask(
                task {
                    do! app.DisposeAsync()
                    do! database.DisposeAsync()
                }
                :> Task)

snippet source | anchor

Each query has two snapshots: the request as it would be sent, and the rows the server returns for it.