Java

Java のランタイムは、パッケージ comatype(packages/java)です。外部依存はありません(JSON も自前、HTTP は java.net.http、サーバは JDK の com.sun.net.httpserver)。JDK 21 以上が必要です(record・sealed interface・パターンマッチ)。

生成されるもの#

<out>/                       既定は src/main/java/comatype/gen(パッケージ名は out から決める。target の package で指定もできる)
├─ Types.java                名前付きの型(record・enum)
├─ Init.java                 ラッパー・ctx・ラッパーのステータス
└─ UserPutId.java            エンドポイントごと(クラス名は PascalCase の連結名)

ビルドは javac -d out $(find packages/java/src/main -name '*.java') $(find <out> -name '*.java') ... のように、ランタイムと生成物を一緒にコンパイルします。

クライアント#

Api.java
package app;

import comatype.C;
import comatype.gen.Types;
import comatype.gen.UserPutId;

public final class Api {
    private Api() {}

    /** PUT /user/:id. Request has params / headers / body, typed from the params block of put__id.comat */
    public static void putUser(java.util.UUID id, Types.UserData user) {
        UserPutId.Response res = C.put(UserPutId.ENDPOINT,
                new UserPutId.Request(new UserPutId.Params(id), UserPutId.RequestHeaders.empty(), user));

        if (res instanceof UserPutId.S200 ok) {
            Types.UserData data = ok.body(); // ok.headers() is S200Headers
        } else if (res instanceof UserPutId.S404 notFound) {
            Types.ApiError error = notFound.body();
        }
    }
}
  • 引数は、params / search / ヘッダがあれば Request、body だけならボディそのもの、無ければ comatype.NoArg.INSTANCE。
  • 戻り値は Response(sealed interface)。S200 S404 ... の record で、instanceof やパターンマッチで絞り込めます。
  • .comat に無いステータスは ComatypeException.UnexpectedStatus、検証エラーは ValidationException(path と reason)。
InitComatype.java
package app;

import comatype.C;
import comatype.CookieJar;
import comatype.gen.Init;

public final class InitComatype {
    private InitComatype() {}

    /** Call once at startup. The base url defaults to baseUrl in init.comat (override with the COMATYPE_BASE_URL environment variable or Config.baseUrl) */
    public static void init() {
        C.init(new C.Config()
                // With the generated Wrappers, a missing wrapper declared in init.comat is a compile error
                .wrappers(new Init.Wrappers(Auth.auth))
                // Used by `cookie on` endpoints. The cookie jar keeps the httpOnly cookie
                .cookieJar(new CookieJar()));
    }
}
Auth.java
package app;

import comatype.C;

/** Implement a wrapper as a C.ComatypeWrap value (corresponds to the `wrapper auth` of init.comat) */
public final class Auth {
    private Auth() {}

    public static final C.ComatypeWrap auth = (req, next) -> {
        req.headers.set("Authorization", "Bearer " + System.getenv("API_TOKEN"));
        return next.call(req);
    };
}

サーバ#

UserPutIdHandler.java
package app;

import comatype.S;
import comatype.gen.Types;
import comatype.gen.UserPutId;

public final class UserPutIdHandler {
    private UserPutIdHandler() {}

    public static void register(S s, Db db) {
        s.put(UserPutId.ENDPOINT, req -> {
            // req.params().id(): UUID, req.body(): UserData, req.ctx().auth().user() (wrap auth is on)
            Types.UserData user = db.update(req.params().id(), req.body()); // the app's own storage
            if (user == null) {
                return S.Reply.of(new UserPutId.S404(new Types.ApiError("not_found", "user not found"), UserPutId.S404Headers.empty()));
            }
            // headerRes (X-Resource-Version) of user/defaults.comat
            return S.Reply.of(new UserPutId.S200(user, UserPutId.S200Headers.empty().withXResourceVersion("v2")));
        });
    }

    /** the app's own storage */
    public interface Db {
        Types.UserData update(java.util.UUID id, Types.UserData user);
    }
}
  • S のインスタンスにハンドラを登録します(s.put(ENDPOINT, req -> ...))。cookie on のエンドポイントでは S.Reply<Response>(S.Reply.of(res).withCookie(CookieValue.of(v).maxAge(3600)))。
  • s.handle(method, target, headers, body) は任意のフレームワークから呼べる入口、s.serve("127.0.0.1", 3000) は JDK のサーバです。
InitComatype.java
package app;

import comatype.S;
import comatype.gen.Init;

public final class InitComatype {
    private InitComatype() {}

    /** Call once at startup. The cookie settings (name, httpOnly, etc.) are in init.comat */
    public static void init(S s) {
        // With the generated Wrappers, a missing wrapper declared in init.comat, or a wrong type, is a compile error
        s.init(new Init.Wrappers(Auth.auth));
    }
}
Auth.java
package app;

import comatype.S;
import comatype.gen.Init;
import comatype.gen.Types;

/** Implement a wrapper as an S.ComatypeWrap<AuthCtx> value (corresponds to the `wrapper auth` of init.comat) */
public final class Auth {
    private Auth() {}

    public static final S.ComatypeWrap<Init.AuthCtx> auth = (req, next) -> {
        Types.UserData user = verifySession(req.cookie("session")); // the app's own logic
        if (user == null) return 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.call(req.withCtx(new Init.AuthCtx(user)));
    };

    static Types.UserData verifySession(String session) {
        return null;
    }
}

型の対応#

  • uuid uuidv4 uuidv7 は java.util.UUID(バージョンは検証)、date は LocalDate、time は LocalTime、datetime は Instant、decimal は BigDecimal、url は URI、bytes は byte[]、json は Object(パース済みの木)。
  • email phone は comatype.Email / comatype.Phone(record)。
  • int と int64 は long(省略可能なら Long)。int64 は通信上は文字列です。
  • 省略可能(?)と T | null は null になれる箱の型。各 record には withXxx() と、全部任意なら empty() があります。