C#

C# のランタイムは、NuGet のパッケージ Comatype(packages/csharp)です。外部への依存はありません(JSON は独自実装、クライアントは System.Net.Http.HttpClient、サーバは System.Net.HttpListener)。.NET 8 以上が必要です(record・パターンマッチ・null 許容参照型)。生成物は、既定では名前空間 ComatypeGen に入ります(ターゲットの package で変えられます)。nullable コンテキストを有効にしてコンパイルされます。

生成されるもの#

<out>/                       既定は ComatypeGen
├─ Types.cs                  名前付きの型(record・enum)。static クラス Types の中
├─ Init.cs                   ラッパー・ctx・ラッパーのステータス。static クラス Init の中
└─ UserPutId.cs              エンドポイントごと(static クラス名は PascalCase の連結名)

生成したディレクトリをプロジェクトに入れ、パッケージを参照に足します。

shell
dotnet add package Comatype

クライアント#

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;
        }
    }
}
  • 呼び出しは async です(C.GetAsync、PostAsync、PutAsync、PatchAsync、DeleteAsync、OptionsAsync、QueryAsync、HeadAsync)。戻り値は Task<Response> です。
  • 引数は、params / search / ヘッダがあれば Request、body だけならボディそのもの、無ければ NoArg.Instance。
  • Response は abstract record で、ステータスごとの sealed な record(S200、S404 ...)があります。switch や is で絞り込めます。
  • .comat に無いステータスは ComatypeException.UnexpectedStatus、検証エラーは ValidationException(Path と 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);
    };
}

サーバ#

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" });
            }
        );
    }
}
  • S のインスタンスに、ハンドラを登録します(s.Put(Endpoint, req => ...))。ハンドラは同期でも async でも書けます。cookie on のエンドポイントでは S.Reply<Response> を返し(S.Reply<Response>.Of(res).WithCookie(CookieValue.Of(v).WithMaxAge(3600)))、ただの Response はそのまま変換されます。
  • s.Serve("127.0.0.1", 3000) は HttpListener で動きます(ポート 0 で空いているポートを選び、戻り値の Server に Port と Stop() があります)。TLS は無いので、前段のプロキシで終端してください。await s.HandleAsync(method, target, headers, body) は任意のフレームワークから呼べる入口です。
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;
}

型の対応#

  • uuid uuidv4 uuidv7 は Guid(バージョンも検証)、date は DateOnly、time は TimeOnly、datetime は DateTimeOffset(UTC)、decimal は decimal(28 桁まで)、url は Uri、bytes は byte[]、json は object?(パースした木)。
  • email phone は Comatype.Email / Comatype.Phone(record)。
  • int と int64 は long。int64 は通信上は文字列です。
  • 省略可能(?)と T | null は T?。record は with でコピーでき(Search.Empty() with { Limit = 10 })、全部が省略可能なら Empty() があります。
  • enum は、メンバーに [WireName("...")] が付いた C# の enum。文字列リテラルのユニオンは、検証付きの string です。
  • 配列は List<T> です。

注意#

  • 生成される record と enum は PascalCase の名前です(xResourceVersion は XResourceVersion)。record 自身の名前や Validate / Encode / Decode / Empty と衝突するフィールド名には、末尾に _ が付きます。