Java

The Java runtime is the package comatype (packages/java). It has no external dependencies (JSON is our own, HTTP is java.net.http, and the server is the JDK's com.sun.net.httpserver). It needs JDK 21 or later (records, sealed interfaces and pattern matching).

What is generated#

<out>/                       default is src/main/java/comatype/gen (the package name is decided from out; you can also set it with the target's package)
├─ Types.java                Named types (records and enums)
├─ Init.java                 Wrappers, ctx and wrapper statuses
└─ UserPutId.java            One per endpoint (the class name is a PascalCase joined name)

To build, compile the runtime and the generated code together, as in javac -d out $(find packages/java/src/main -name '*.java') $(find <out> -name '*.java') ....

Client#

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();
        }
    }
}
  • The argument is Request if there are params / search / headers, the body itself if there is only a body, and comatype.NoArg.INSTANCE if there is neither.
  • The return value is Response (a sealed interface) made of records S200 S404 ..., which you can narrow with instanceof or pattern matching.
  • A status that is not in the .comat is ComatypeException.UnexpectedStatus, and a validation error is ValidationException (path and 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);
    };
}

Server#

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);
    }
}
  • Register handlers on an instance of S (s.put(ENDPOINT, req -> ...)). For an endpoint with cookie on it is S.Reply<Response> (S.Reply.of(res).withCookie(CookieValue.of(v).maxAge(3600))).
  • s.handle(method, target, headers, body) is an entry point you can call from any framework, and s.serve("127.0.0.1", 3000) is the JDK server.
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;
    }
}

Type mapping#

  • uuid uuidv4 uuidv7 are java.util.UUID (the version is validated), date is LocalDate, time is LocalTime, datetime is Instant, decimal is BigDecimal, 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 (Long if optional). int64 is a string on the wire.
  • Optional (?) and T | null use boxed types that can be null. Every record has withXxx(), and empty() if everything is optional.