C#

The C# runtime is the NuGet package Comatype (packages/csharp). It has no external dependencies (JSON is our own, the client is System.Net.Http.HttpClient, and the server is System.Net.HttpListener). It needs .NET 8 or later (records, pattern matching and nullable reference types). The generated code is in the namespace ComatypeGen by default (set the target's package to change it) and is compiled with the nullable context turned on.

What is generated#

<out>/                       default is ComatypeGen
├─ Types.cs                  Named types (records and enums), in the static class Types
├─ Init.cs                   Wrappers, ctx and wrapper statuses, in the static class Init
└─ UserPutId.cs              One per endpoint (the static class name is a PascalCase joined name)

Add the generated directory to your project and the package to its references:

shell
dotnet add package Comatype

Client#

UserPutId.cs
using Comatype;
using ComatypeGen;

public static class UserPutIdSample
{
    public static async Task PutUser(Guid id, Types.UserData user)
    {
        // Request has params / headers / body, typed from the params block of put_[id].comat
        UserPutId.Response res = await C.PutAsync(
            UserPutId.Endpoint,
            new UserPutId.Request(new UserPutId.Params(id), UserPutId.RequestHeaders.Empty(), user)
        );

        switch (res)
        {
            case UserPutId.S200 ok:
                Types.UserData data = ok.Body; // ok.Headers is S200Headers
                break;
            case UserPutId.S404 notFound:
                Types.ApiError error = notFound.Body;
                break;
        }
    }
}
  • Calls are async (C.GetAsync, PostAsync, PutAsync, PatchAsync, DeleteAsync, OptionsAsync, QueryAsync, HeadAsync) and return Task<Response>.
  • The argument is Request if there are params / search / headers, the body itself if there is only a body, and NoArg.Instance if there is neither.
  • Response is an abstract record with one sealed record per status (S200, S404, ...), which you narrow with switch or is.
  • A status that is not in the .comat is ComatypeException.UnexpectedStatus, and a validation error is ValidationException (Path and Reason).
Init.cs
// Client init file: pass the implemented ComatypeWrap
// The base url defaults to baseUrl in init.comat. Override with the COMATYPE_BASE_URL environment variable or Config.BaseUrl
// Call InitComatype.Run() once at startup (whether a wrapper is on or off is decided by defaults.comat and `wrap` in each .comat)
using Comatype;
using ComatypeGen;

public static class InitComatype
{
    public static void Run()
    {
        C.Init(
            new C.Config()
                // With the generated types, a missing wrapper declared in init.comat, or a wrong type, is a compile error
                .WithWrappers(new Init.Wrappers(Auth.Wrap))
                // Used by `cookie on` endpoints. The cookie jar keeps the httpOnly cookie
                .WithCookieJar(new CookieJar())
        );
    }
}
Wrappers/Auth.cs
// Implement a wrapper as a C.ComatypeWrap value (corresponds to the `wrapper auth` of init.comat)
using Comatype;

public static class Auth
{
    public static readonly C.ComatypeWrap Wrap = (req, next) =>
    {
        req.Headers.Set("Authorization", "Bearer " + Environment.GetEnvironmentVariable("API_TOKEN"));
        return next(req);
    };
}

Server#

UserPutId.cs
using Comatype;
using ComatypeGen;

public static class UserPutIdHandler
{
    public static void Register(S s)
    {
        s.Put(
            UserPutId.Endpoint,
            req =>
            {
                // req.Params.Id: Guid, req.Body: Types.UserData, req.Ctx.Auth.User (wrap auth is on)
                Types.UserData? user = Db.User.Update(req.Params.Id, req.Body); // the app's own storage
                if (user == null)
                    return new UserPutId.S404(new Types.ApiError("not_found", "user not found"), UserPutId.S404Headers.Empty());
                // headerRes (X-Resource-Version) of user/defaults.comat
                return new UserPutId.S200(user, UserPutId.S200Headers.Empty() with { XResourceVersion = "v2" });
            }
        );
    }
}
  • Register handlers on an instance of S (s.Put(Endpoint, req => ...)). A handler can be synchronous or async. For an endpoint with cookie on it returns S.Reply<Response> (S.Reply<Response>.Of(res).WithCookie(CookieValue.Of(v).WithMaxAge(3600))); a plain Response converts to it.
  • s.Serve("127.0.0.1", 3000) runs on HttpListener (port 0 picks a free port, and the returned Server has Port and Stop()). It has no TLS, so terminate TLS at a proxy in front. await s.HandleAsync(method, target, headers, body) is the entry point you can call from any framework.
Init.cs
// Server init file: pass the implemented ComatypeWrap
// The cookie settings (name, httpOnly, etc.) are in init.comat
using Comatype;
using ComatypeGen;

public static class InitComatype
{
    public static void Run(S s)
    {
        // With the generated types, a missing wrapper declared in init.comat, or a wrong type, is a compile error
        s.Init(new Init.Wrappers(Auth.Wrap));
    }
}
Wrappers/Auth.cs
// Implement a wrapper as an S.ComatypeWrap<AuthCtx> value (corresponds to the `wrapper auth` of init.comat)
using Comatype;
using ComatypeGen;

public static class Auth
{
    public static readonly S.ComatypeWrap<Init.AuthCtx> Wrap = (req, next) =>
    {
        Types.UserData? user = VerifySession(req.Cookie("session")); // the app's own logic
        if (user == null)
            return Task.FromResult(Init.S401(new Types.ApiError("unauthorized", "login required")));
        // On endpoints with `wrap auth` on, a handler can read req.Ctx.Auth.User, typed
        return next(req.WithCtx(new Init.AuthCtx(user)));
    };

    private static Types.UserData? VerifySession(string? token) => null;
}

Type mapping#

  • uuid uuidv4 uuidv7 are Guid (the version is validated), date is DateOnly, time is TimeOnly, datetime is DateTimeOffset (in UTC), decimal is decimal (up to 28 digits), url is Uri, bytes is byte[], and json is object? (the parsed tree).
  • email and phone are Comatype.Email / Comatype.Phone (records).
  • int and int64 are long. int64 is a string on the wire.
  • Optional (?) and T | null are T?. Every record can be copied with with (Search.Empty() with { Limit = 10 }), and has Empty() if everything is optional.
  • An enum is a C# enum whose members carry [WireName("...")]; a union of string literals is a string that is validated.
  • Arrays are List<T>.

Notes#

  • Generated records and enums are named in PascalCase (xResourceVersion becomes XResourceVersion). A field whose name would clash with its record (or with Validate, Encode, Decode, Empty) gets a trailing _.