
Framework simplifies development of event-driven, scalable systems using Command and Query Responsibility Segregation (CQRS) architecture. Offers tools for HTTP and RSocket communication, supporting serverless functions with Spring Cloud Function and Ktor client integration.
F2 is a framework built using the Kotlin programming language that is built on top of Spring Cloud Function for the server side and ktor for multiplatform client. It aims to make it easier to develop Command and Query Responsibility Segregation (CQRS) based applications.
The goal of F2 is to help developers build event-driven, scalable, and resilient systems that are easy to understand and maintain. It provides tools and abstractions to handle the different parts of a CQRS-based architecture.
The Command and Query Responsibility Segregation (CQRS) architecture is a pattern that separates the responsibilities of handling commands, which change the state of an application, and queries, which retrieve information from the application.
HTTP is a widely-used protocol for sending and receiving information over the internet, and is a popular choice for building RESTful web services. By supporting HTTP, F2 and its client can easily integrate with a wide range of other technologies and services that use HTTP for communication.
The project is organized into several modules:
f2.versions.toml) providing library aliases, plugin aliases, and the BOM reference for consumer projects.Add the F2 version catalog and BOM in your settings.gradle.kts:
dependencyResolutionManagement {
versionCatalogs {
create("f2") {
from("io.komune.f2:f2-gradle-catalog:${VERSION}")
}
}
}Apply the BOM to all subprojects in your root build.gradle.kts:
subprojects {
pluginManager.withPlugin("org.jetbrains.kotlin.jvm") {
dependencies {
"api"(platform(f2.bom))
}
}
pluginManager.withPlugin("org.jetbrains.kotlin.multiplatform") {
dependencies {
"commonMainApi"(platform(f2.bom))
}
}
}The version catalog provides plugin aliases with compatible versions:
plugins {
alias(f2.plugins.fixers.gradle.config)
alias(f2.plugins.fixers.gradle.check)
alias(f2.plugins.kotlin.spring) apply false
alias(f2.plugins.spring.boot) apply false
}With the BOM applied, F2 dependencies require no explicit version:
dependencies {
implementation(f2.dsl.function)
implementation(f2.dsl.cqrs)
implementation(f2.spring.boot.starter.function.http.mvc)
}Third-party dependencies managed by the BOM (Spring Boot, Ktor, coroutines, etc.) also resolve their versions automatically.
Since 0.47.0 these modules are no longer published, and the BOM and the f2 catalog no longer name them. No
Komune or Bois Local repository depended on them:
| Coordinate | Since |
|---|---|
io.komune.f2:f2-dsl-event (and f2-dsl-event-jvm, f2-dsl-event-js) |
0.47.0 |
io.komune.f2:f2-spring-boot-openapi-mvc |
0.47.0 |
io.komune.f2:f2-spring-boot-openapi-webflux |
0.47.0 |
io.komune.f2:f2-spring-boot-starter-observability-opentelemetry |
0.47.0 |
io.komune.f2:f2-bdd-blockhound |
0.47.0 |
Releases up to 0.46 stay on Maven Central. To use one of these modules with 0.47.0 or later, open an issue, or build
it from this repository (./gradlew :f2-dsl:f2-dsl-event:publishToMavenLocal with the publish plugin added back to its
build file). f2-spring-boot-openapi is still published: add org.springdoc:springdoc-openapi-starter-webmvc-ui or
-webflux-ui next to it for what the two dropped modules brought.
Clone the repository:
git clone https://github.com/komune-io/fixers-f2.git
cd fixers-f2The project uses make and gradle for build operations.
Note: The
Makefilein the root currently points tolibs.mkanddocs.mk. Usemake -f make_libs.mk <target>ormake -f make_docs.mk <target>if the defaultmakecommand fails.
| Command | Description |
|---|---|
./gradlew build |
Build the project. |
./gradlew test |
Run unit tests. |
./gradlew detekt |
Run code linting. |
make -f make_libs.mk build |
Build libraries (clean, build, publishToMavenLocal). |
make -f make_libs.mk test |
Run tests via Make. |
make -f make_libs.mk lint |
Run linter via Make. |
make -f make_docs.mk build-storybook |
Build Storybook documentation. |
| Variable | Description |
|---|---|
VERSION |
Project version (default: experimental-SNAPSHOT). |
FIXERS_PUBLISH_NPM_GITHUB_TOKEN |
Auth token for NPM/Yarn against GitHub Packages (required for Storybook publishing). Renamed from NPM_AUTH_TOKEN. |
This project is licensed under the Apache 2.0 License - see the LICENSE file for details.
Spring Cloud Function provides a functional programming model for building cloud-native applications, enabling you to write simple, single-purpose functions that can be easily composed and deployed in a cloud environment. It allows you to take advantage of the many features of the Spring framework, such as data access, transaction management, security, and more, while still enjoying the scalability and cost-effectiveness of a serverless architecture. It supports multiple communication protocols, including HTTP and gRPC, and the choice of protocol will depend on the specific requirements of your application and the type of function being written.
F2 provides a multiplatform client using the Ktor client for HTTP. The Ktor client is a high-performance HTTP client for the Kotlin language that makes it easy to perform HTTP requests from your Kotlin applications. It supports both synchronous and asynchronous programming, and provides a wide range of features for working with HTTP, including connection pooling, request and response streaming, and automatic decompression of response bodies.
In Java, a Function, Supplier, and Consumer are functional interfaces that are part of the Java 8 functional programming API. They are used to represent functions that take one or more arguments, produce a result, or consume a value, respectively. These functional interfaces can be used to implement functional programming concepts such as higher-order functions and lambda expressions, making it easier to write concise, readable, and maintainable code. For example, you could use a Function to map a list of integers to a list of strings, or a Consumer to iterate over a list of values and perform an action on each one. By using these functional interfaces, you can write code that is more functional and less imperative, resulting in a more declarative and maintainable codebase.
implementation("io.komune.f2:f2-dsl-function:${Versions.f2}")<dependency>
<groupId>io.komune.f2</groupId>
<artifactId>f2-dsl-function</artifactId>
<version>${Versions.f2}</version>
</dependency>
A F2Supplier does not take any input and produces a result.
For example, you might write a Supplier that returns a random number.
The get method of a Supplier returns the result.
fun interface F2Supplier<R> : suspend () -> Flow<R> {
override suspend operator fun invoke(): Flow<R>
}A F2Function takes one or more inputs and produces a result.
For example, you might write a Function that takes an Integer and returns a String.
The apply method of a Function takes the input and returns the result.
fun interface F2Function<T, R>: suspend (Flow<T>) -> Flow<R> {
override suspend operator fun invoke(msgs: Flow<T>): Flow<R>
}A F2Consumer takes a value as input and does not produce a result.
For example, you might write a Consumer that prints a message to the console.
The accept method of a Consumer takes the input and performs an action,
but does not return a value.
fun interface F2Consumer<T>: suspend (Flow<T>) -> Unit {
override suspend operator fun invoke(msg: Flow<T>)
}The three interfaces are Kotlin API, not exported: a Flow and a suspend call have no JS form. A JS caller
reaches an F2 server through the JS client of f2-client-ktor-http: each function is an object whose invoke
takes JSON messages and an optional AbortSignal and returns a promise of JSON results (Json<T> is the JSON of
T, declared at the head of the contract):
The client runs from the .mjs modules Kotlin/JS emits; f2 publishes no npm package, and ts/ holds the
declarations only, for review. A front gets the modules from the Kotlin/JS build of a project that depends on
io.komune.f2:f2-client-ktor-http (its jsBrowserProductionLibraryDistribution writes them to
build/dist/js/productionLibrary/, one .mjs per module), or from the npm package that build publishes. Import
from that module; TypeScript reads the .d.mts beside it:
// The emitted modules, here copied to src/f2/.
import { httpF2JsClient } from "./f2/fixers-f2-f2-client-f2-client-ktor-f2-client-ktor-http.mjs";
import type { HttpF2JsFailure, Json, PageQuery, PageQueryResult } from "./f2/fixers-f2-f2-client-f2-client-ktor-f2-client-ktor-http.mjs";
// Your function's result type: an exported Kotlin class, or any TypeScript type of its JSON.
type Item = { id: string; name: string };
const client = httpF2JsClient("https://f2.example");
const itemPage = client.function<PageQuery, PageQueryResult<Item>>("itemPage"); // an F2JsFunction
// itemPage.invoke(msgs: Json<PageQuery>[], signal?: AbortSignal | null): Promise<Json<PageQueryResult<Item>>[]>
const controller = new AbortController();
try {
const [page] = await itemPage.invoke([{ pagination: { offset: 0, limit: 10 } }], controller.signal);
const items: Json<Item>[] = page.items;
} catch (e) {
if (e instanceof Error && "kind" in e) {
const failure = e as Json<HttpF2JsFailure>; // kind, message, status, error, body
if (failure.kind === "F2") console.log(failure.error?.refusal?.parameters["id"]);
} else if (e instanceof TypeError) {
// the messages are no plain JSON: refused before any request
} else {
// the signal's reason (an AbortError by default, or whatever was passed to abort()), or a defect of the client
}
}
client.close();client.supplier<R>(route) is an F2JsSupplier whose invoke(signal?) returns a Promise<Json<R>[]>,
client.consumer<Q>(route) an F2JsConsumer whose invoke(msgs, signal?) returns a Promise<void>. invoke is a
method: call it on its function, never detached (const run = itemPage.invoke loses its object); where a plain JS
function is wanted, an arrow adapts it: (msgs) => itemPage.invoke(msgs). Import values (httpF2JsClient) from
the module that declares them, and the rest with import type: a module's .d.mts declares its whole program, its
.mjs exports only its own.
Type arguments: always give them. TypeScript cannot require them on what Kotlin emits; without them a function
takes any message and its results are unknown.
Messages are an array of plain JSON: anything else rejects with a TypeError before any request — no array,
an instance of a class at any depth (an exported Kotlin object, a Date), a cycle, or a number that is not
finite (NaN, Infinity, which JSON would write as null). Json<T> refuses a Kotlin object at type level too,
where it implements an exported interface or is a data class. Each property is read once, and what was checked is
what is sent. A value shared by two messages is fine.
Every call settles once. A failure rejects with an Error carrying Json<HttpF2JsFailure>, no Kotlin object:
kind |
When | status |
error |
body |
|---|---|---|---|---|
F2 |
an error status whose body is a JSON error object (an F2 error, a Spring error body) | the status | that error as JSON: refusal.parameters an object, refusal.citers an array |
null |
HTTP |
an error status whose body is text or empty (message is the text, or HTTP <status>) |
the status | null |
the text, "" when empty |
NETWORK |
no response, or one not read whole: the server is unreachable, the connection broke, the call was cancelled by anything but its signal or close()
|
null |
null |
null |
UNREADABLE |
a success status whose body is no JSON | the status | null |
the text |
CLOSED |
the client was closed before or during the call | null |
null |
null |
A defect of the client itself rejects with a plain Error that has no kind, rather than leaving the promise
pending.
Headers: httpF2JsClient(url, headers) takes an optional async provider, called before each request; every
header it answers is sent, so a token is refreshed where it lives. With keycloak-js, where keycloak.token is
undefined until a login:
const client = httpF2JsClient("https://f2.example", async () => {
await keycloak.updateToken(30);
return keycloak.token === undefined ? {} : { Authorization: `Bearer ${keycloak.token}` };
});TypeError before any request, which names the header and never quotes its value: a number, a list of
pairs, a name that is no HTTP token, a value holding a control character (a tab aside) or a character beyond
Latin-1.Content-Type, Content-Length, Transfer-Encoding,
Upgrade and Accept, which the client writes itself, and the headers a browser's fetch drops without a word
(Cookie, Host, Origin, Referer, Accept-Charset, any Proxy- or Sec- header, the rest of the Fetch
standard's forbidden request headers).invoke a signal with a timeout
(AbortSignal.timeout(ms)) where that matters.Authorization but carries
every other header the provider answered. Point the client at the API's own URL, and keep secrets in
Authorization.Cancellation, as with fetch: each invoke takes an optional AbortSignal last; an aborted call rejects
with the signal's reason, and its listener is removed when the call ends. client.close() ends every pending
call (CLOSED) and releases the connections; a closed client rejects every later call as CLOSED, an aborted
signal included. AbortSignal is the platform's: the DOM library or Node's types.
Command Query Responsibility Segregation is a pattern that performs segregate operations that read data from operations that update data by using separate interfaces.
The package f2-dsl-cqrs provide kotlin multplatform interfaces for f2.dsl.cqrs.Event, f2.dsl.cqrs.Command, f2.dsl.cqrs.Query
It also interface for querying a page o result f2.dsl.cqrs.PageRequest and Pagef2.dsl.cqrs
implementation("io.komune.f2:f2-dsl-cqrs:${Versions.f2}")<dependency>
<groupId>io.komune.f2</groupId>
<artifactId>f2-dsl-cqrs</artifactId>
<version>${Versions.f2}</version>
</dependency>
interface Message
interface Event: Message
interface Command: Message
interface Query : Messagesealed interface Pagination
class OffsetPagination(
override val offset: Int,
override val limit: Int,
) : OffsetPaginationDTO, Pagination
interface OffsetPaginationDTO {
val offset: Int
val limit: Int
}
class PagePagination(
override val page: Int?,
override val size: Int?
): PagePaginationDTO, Pagination
interface PagePaginationDTO {
val page: Int?
val size: Int?
}interface PageDTO<out OBJECT> {
val total: Int
val items: List<OBJECT>
}
class Page<out OBJECT>(
override val total: Int,
override val items: List<OBJECT>,
) : PageDTO<OBJECT>
interface PageQueryDTO : Query {
val pagination: OffsetPaginationDTO?
}
interface PageQueryResultDTO<out OBJECT> : Event, PageDTO<OBJECT> {
override val total: Int
override val items: List<OBJECT>
val pagination: OffsetPaginationDTO?
}
class PageQuery(
override val pagination: OffsetPaginationDTO?,
) : PageQueryDTO
class PageQueryResult<out OBJECT>(
override val pagination: OffsetPagination?,
override val total: Int,
override val items: List<OBJECT>,
) : PageQueryResultDTO<OBJECT>
fun <OBJECT> OffsetPaginationDTO.result(items: List<OBJECT>, total: Int): PageQueryResultDTO<OBJECT>
inline fun <T, reified R> PageDTO<T>.map(transform: (T) -> R): PageDTO<R>
inline fun <T, reified R> Page<T>.map(transform: (T) -> R): Page<R>inline fun <T, reified R: Any> PageDTO<T>.mapNotNull(transform: (T) -> R?): PageDTO<R>
inline fun OffsetPagination?.toPageRequest(): PageRequestfun <T, R> f2Function(fnc: suspend (t: T) -> R): F2Function<T, R>
suspend operator fun <T, R> F2Function<T, R>.invoke(t: T): R
suspend fun <T, R> T.invokeWith(f2: F2Function<T, R>): R
fun <R> f2Supplier(fnc: suspend () -> Flow<R>): F2Supplier<R>
fun <R> f2SupplierSingle(fnc: suspend () -> R): F2Supplier<R>
fun <R> Iterable<R>.asF2Supplier(): F2Supplier<R>
fun <R> f2Consumer(fnc: suspend (R) -> Unit): F2Consumer<R>F2 provide basic configuration for spring cloud function
implementation("io.komune.f2:f2-spring-boot-starter-function:${Versions.f2}")<dependency>
<groupId>io.komune.f2</groupId>
<artifactId>f2-spring-boot-starter-function</artifactId>
<version>${Versions.f2}</version>
</dependency>
implementation("io.komune.f2:f2-spring-boot-starter-function-http:${Versions.f2}")<dependency>
<groupId>io.komune.f2</groupId>
<artifactId>f2-spring-boot-starter-function-http</artifactId>
<version>${Versions.f2}</version>
</dependency>
import f2.dsl.fnc.F2Consumer
import f2.dsl.fnc.F2Function
import f2.dsl.fnc.F2Supplier
import f2.dsl.fnc.f2Consumer
import f2.dsl.fnc.f2Function
import f2.dsl.fnc.f2Supplier
import f2.dsl.fnc.f2SupplierSingle
import java.security.MessageDigest
import java.util.Base64
import java.util.UUID
import kotlinx.coroutines.channels.ticker
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.map
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
@SpringBootApplication
class F2SampleHttpApp {
@Bean
fun sha256(): F2Function<String, String> = f2Function { bytes ->
val md = MessageDigest.getInstance("SHA-256")
val hash = md.digest(bytes.toByteArray())
Base64.getEncoder().encodeToString(hash)
}
@Bean
fun uuid(): F2Supplier<String> = f2SupplierSingle {
UUID.randomUUID().toString()
}
@Bean
fun uuids(): F2Supplier<String> = f2Supplier {
ticker(1000).consumeAsFlow().map { UUID.randomUUID().toString() }
}
@Bean
fun println(): F2Consumer<String> = f2Consumer(::println)
}
/**
* Main method to start Spring Boot Application
*/
fun main(args: Array<String>) {
runApplication<F2SampleHttpApp>(*args)
}expect fun didClient(url: String): F2Supplier<DIDFunctionClient>
open class DIDFunctionClient constructor(private val client: F2Client) : DidAggregate {
override fun sha256(): F2Function<String, String> = client.function("sha256")
override fun uuid(): F2Supplier<String> = client.function("uuid")
override fun uuids(): F2Supplier<String> = client.function("uuids")
override fun println(): F2Consumer<String> = client.function("println")
}Integration with Springdoc to generate open api documentation.
<dependency>
<groupId>io.komune.f2</groupId>
<artifactId>f2-spring-boot-openapi</artifactId>
<version>${Versions.f2}</version>
</dependency>
implementation("io.komune.f2:f2-spring-boot-openapi:${Versions.f2}")Three serializer can be used via the spring parameter spring.cloud.function.preferred-json-mapper
f2-spring-boot-exception-http-webflux and -mvc answer every error with one body:
{"timestamp":"…","path":"/itemDelete","status":409,"error":"Conflict","requestId":"…",
"refusal":"item.CITED","message":"Cited by A: it stays","parameters":{"id":"i-1"},"citers":["A"]}refusal is always there: the rule a refusal names (F2Refusal.code), or the meaning of the status
(HttpRefusal, http.NOT_FOUND…).message, parameters and citers travel only with a refusal — an F2Exception whose F2Error carries an
F2Refusal. Any other error says nothing it was raised with, whatever server.error.include-* asks for.F2Error names, wherever the F2Exception sits in the cause chain.http.INVALID_PAYLOAD; a 401 or 403 of f2's security starters gets
the same body, with WWW-Authenticate: Bearer alone.JsonMapper bean.spring.webflux.problemdetails.enabled and spring.mvc.problemdetails.enabled must stay false (their
default): enabled, Spring's ProblemDetail handler answers the exceptions it knows (ResponseStatusException,
ServerWebInputException, HttpMessageNotReadableException…) raised in a controller before F2's error body is
written, with its own body and their detail message.
Not published since 0.47.0 (see "Modules not published"). f2-bdd-blockhound installs BlockHound for a JUnit session. The test JVM needs
-XX:+AllowRedefinitionToAddDeleteMethods (JDK 13 and later), or BlockHound cannot instrument the JDK:
tasks.withType<Test>().configureEach { jvmArgs("-XX:+AllowRedefinitionToAddDeleteMethods") }F2 is a framework built using the Kotlin programming language that is built on top of Spring Cloud Function for the server side and ktor for multiplatform client. It aims to make it easier to develop Command and Query Responsibility Segregation (CQRS) based applications.
The goal of F2 is to help developers build event-driven, scalable, and resilient systems that are easy to understand and maintain. It provides tools and abstractions to handle the different parts of a CQRS-based architecture.
The Command and Query Responsibility Segregation (CQRS) architecture is a pattern that separates the responsibilities of handling commands, which change the state of an application, and queries, which retrieve information from the application.
HTTP is a widely-used protocol for sending and receiving information over the internet, and is a popular choice for building RESTful web services. By supporting HTTP, F2 and its client can easily integrate with a wide range of other technologies and services that use HTTP for communication.
The project is organized into several modules:
f2.versions.toml) providing library aliases, plugin aliases, and the BOM reference for consumer projects.Add the F2 version catalog and BOM in your settings.gradle.kts:
dependencyResolutionManagement {
versionCatalogs {
create("f2") {
from("io.komune.f2:f2-gradle-catalog:${VERSION}")
}
}
}Apply the BOM to all subprojects in your root build.gradle.kts:
subprojects {
pluginManager.withPlugin("org.jetbrains.kotlin.jvm") {
dependencies {
"api"(platform(f2.bom))
}
}
pluginManager.withPlugin("org.jetbrains.kotlin.multiplatform") {
dependencies {
"commonMainApi"(platform(f2.bom))
}
}
}The version catalog provides plugin aliases with compatible versions:
plugins {
alias(f2.plugins.fixers.gradle.config)
alias(f2.plugins.fixers.gradle.check)
alias(f2.plugins.kotlin.spring) apply false
alias(f2.plugins.spring.boot) apply false
}With the BOM applied, F2 dependencies require no explicit version:
dependencies {
implementation(f2.dsl.function)
implementation(f2.dsl.cqrs)
implementation(f2.spring.boot.starter.function.http.mvc)
}Third-party dependencies managed by the BOM (Spring Boot, Ktor, coroutines, etc.) also resolve their versions automatically.
Since 0.47.0 these modules are no longer published, and the BOM and the f2 catalog no longer name them. No
Komune or Bois Local repository depended on them:
| Coordinate | Since |
|---|---|
io.komune.f2:f2-dsl-event (and f2-dsl-event-jvm, f2-dsl-event-js) |
0.47.0 |
io.komune.f2:f2-spring-boot-openapi-mvc |
0.47.0 |
io.komune.f2:f2-spring-boot-openapi-webflux |
0.47.0 |
io.komune.f2:f2-spring-boot-starter-observability-opentelemetry |
0.47.0 |
io.komune.f2:f2-bdd-blockhound |
0.47.0 |
Releases up to 0.46 stay on Maven Central. To use one of these modules with 0.47.0 or later, open an issue, or build
it from this repository (./gradlew :f2-dsl:f2-dsl-event:publishToMavenLocal with the publish plugin added back to its
build file). f2-spring-boot-openapi is still published: add org.springdoc:springdoc-openapi-starter-webmvc-ui or
-webflux-ui next to it for what the two dropped modules brought.
Clone the repository:
git clone https://github.com/komune-io/fixers-f2.git
cd fixers-f2The project uses make and gradle for build operations.
Note: The
Makefilein the root currently points tolibs.mkanddocs.mk. Usemake -f make_libs.mk <target>ormake -f make_docs.mk <target>if the defaultmakecommand fails.
| Command | Description |
|---|---|
./gradlew build |
Build the project. |
./gradlew test |
Run unit tests. |
./gradlew detekt |
Run code linting. |
make -f make_libs.mk build |
Build libraries (clean, build, publishToMavenLocal). |
make -f make_libs.mk test |
Run tests via Make. |
make -f make_libs.mk lint |
Run linter via Make. |
make -f make_docs.mk build-storybook |
Build Storybook documentation. |
| Variable | Description |
|---|---|
VERSION |
Project version (default: experimental-SNAPSHOT). |
FIXERS_PUBLISH_NPM_GITHUB_TOKEN |
Auth token for NPM/Yarn against GitHub Packages (required for Storybook publishing). Renamed from NPM_AUTH_TOKEN. |
This project is licensed under the Apache 2.0 License - see the LICENSE file for details.
Spring Cloud Function provides a functional programming model for building cloud-native applications, enabling you to write simple, single-purpose functions that can be easily composed and deployed in a cloud environment. It allows you to take advantage of the many features of the Spring framework, such as data access, transaction management, security, and more, while still enjoying the scalability and cost-effectiveness of a serverless architecture. It supports multiple communication protocols, including HTTP and gRPC, and the choice of protocol will depend on the specific requirements of your application and the type of function being written.
F2 provides a multiplatform client using the Ktor client for HTTP. The Ktor client is a high-performance HTTP client for the Kotlin language that makes it easy to perform HTTP requests from your Kotlin applications. It supports both synchronous and asynchronous programming, and provides a wide range of features for working with HTTP, including connection pooling, request and response streaming, and automatic decompression of response bodies.
In Java, a Function, Supplier, and Consumer are functional interfaces that are part of the Java 8 functional programming API. They are used to represent functions that take one or more arguments, produce a result, or consume a value, respectively. These functional interfaces can be used to implement functional programming concepts such as higher-order functions and lambda expressions, making it easier to write concise, readable, and maintainable code. For example, you could use a Function to map a list of integers to a list of strings, or a Consumer to iterate over a list of values and perform an action on each one. By using these functional interfaces, you can write code that is more functional and less imperative, resulting in a more declarative and maintainable codebase.
implementation("io.komune.f2:f2-dsl-function:${Versions.f2}")<dependency>
<groupId>io.komune.f2</groupId>
<artifactId>f2-dsl-function</artifactId>
<version>${Versions.f2}</version>
</dependency>
A F2Supplier does not take any input and produces a result.
For example, you might write a Supplier that returns a random number.
The get method of a Supplier returns the result.
fun interface F2Supplier<R> : suspend () -> Flow<R> {
override suspend operator fun invoke(): Flow<R>
}A F2Function takes one or more inputs and produces a result.
For example, you might write a Function that takes an Integer and returns a String.
The apply method of a Function takes the input and returns the result.
fun interface F2Function<T, R>: suspend (Flow<T>) -> Flow<R> {
override suspend operator fun invoke(msgs: Flow<T>): Flow<R>
}A F2Consumer takes a value as input and does not produce a result.
For example, you might write a Consumer that prints a message to the console.
The accept method of a Consumer takes the input and performs an action,
but does not return a value.
fun interface F2Consumer<T>: suspend (Flow<T>) -> Unit {
override suspend operator fun invoke(msg: Flow<T>)
}The three interfaces are Kotlin API, not exported: a Flow and a suspend call have no JS form. A JS caller
reaches an F2 server through the JS client of f2-client-ktor-http: each function is an object whose invoke
takes JSON messages and an optional AbortSignal and returns a promise of JSON results (Json<T> is the JSON of
T, declared at the head of the contract):
The client runs from the .mjs modules Kotlin/JS emits; f2 publishes no npm package, and ts/ holds the
declarations only, for review. A front gets the modules from the Kotlin/JS build of a project that depends on
io.komune.f2:f2-client-ktor-http (its jsBrowserProductionLibraryDistribution writes them to
build/dist/js/productionLibrary/, one .mjs per module), or from the npm package that build publishes. Import
from that module; TypeScript reads the .d.mts beside it:
// The emitted modules, here copied to src/f2/.
import { httpF2JsClient } from "./f2/fixers-f2-f2-client-f2-client-ktor-f2-client-ktor-http.mjs";
import type { HttpF2JsFailure, Json, PageQuery, PageQueryResult } from "./f2/fixers-f2-f2-client-f2-client-ktor-f2-client-ktor-http.mjs";
// Your function's result type: an exported Kotlin class, or any TypeScript type of its JSON.
type Item = { id: string; name: string };
const client = httpF2JsClient("https://f2.example");
const itemPage = client.function<PageQuery, PageQueryResult<Item>>("itemPage"); // an F2JsFunction
// itemPage.invoke(msgs: Json<PageQuery>[], signal?: AbortSignal | null): Promise<Json<PageQueryResult<Item>>[]>
const controller = new AbortController();
try {
const [page] = await itemPage.invoke([{ pagination: { offset: 0, limit: 10 } }], controller.signal);
const items: Json<Item>[] = page.items;
} catch (e) {
if (e instanceof Error && "kind" in e) {
const failure = e as Json<HttpF2JsFailure>; // kind, message, status, error, body
if (failure.kind === "F2") console.log(failure.error?.refusal?.parameters["id"]);
} else if (e instanceof TypeError) {
// the messages are no plain JSON: refused before any request
} else {
// the signal's reason (an AbortError by default, or whatever was passed to abort()), or a defect of the client
}
}
client.close();client.supplier<R>(route) is an F2JsSupplier whose invoke(signal?) returns a Promise<Json<R>[]>,
client.consumer<Q>(route) an F2JsConsumer whose invoke(msgs, signal?) returns a Promise<void>. invoke is a
method: call it on its function, never detached (const run = itemPage.invoke loses its object); where a plain JS
function is wanted, an arrow adapts it: (msgs) => itemPage.invoke(msgs). Import values (httpF2JsClient) from
the module that declares them, and the rest with import type: a module's .d.mts declares its whole program, its
.mjs exports only its own.
Type arguments: always give them. TypeScript cannot require them on what Kotlin emits; without them a function
takes any message and its results are unknown.
Messages are an array of plain JSON: anything else rejects with a TypeError before any request — no array,
an instance of a class at any depth (an exported Kotlin object, a Date), a cycle, or a number that is not
finite (NaN, Infinity, which JSON would write as null). Json<T> refuses a Kotlin object at type level too,
where it implements an exported interface or is a data class. Each property is read once, and what was checked is
what is sent. A value shared by two messages is fine.
Every call settles once. A failure rejects with an Error carrying Json<HttpF2JsFailure>, no Kotlin object:
kind |
When | status |
error |
body |
|---|---|---|---|---|
F2 |
an error status whose body is a JSON error object (an F2 error, a Spring error body) | the status | that error as JSON: refusal.parameters an object, refusal.citers an array |
null |
HTTP |
an error status whose body is text or empty (message is the text, or HTTP <status>) |
the status | null |
the text, "" when empty |
NETWORK |
no response, or one not read whole: the server is unreachable, the connection broke, the call was cancelled by anything but its signal or close()
|
null |
null |
null |
UNREADABLE |
a success status whose body is no JSON | the status | null |
the text |
CLOSED |
the client was closed before or during the call | null |
null |
null |
A defect of the client itself rejects with a plain Error that has no kind, rather than leaving the promise
pending.
Headers: httpF2JsClient(url, headers) takes an optional async provider, called before each request; every
header it answers is sent, so a token is refreshed where it lives. With keycloak-js, where keycloak.token is
undefined until a login:
const client = httpF2JsClient("https://f2.example", async () => {
await keycloak.updateToken(30);
return keycloak.token === undefined ? {} : { Authorization: `Bearer ${keycloak.token}` };
});TypeError before any request, which names the header and never quotes its value: a number, a list of
pairs, a name that is no HTTP token, a value holding a control character (a tab aside) or a character beyond
Latin-1.Content-Type, Content-Length, Transfer-Encoding,
Upgrade and Accept, which the client writes itself, and the headers a browser's fetch drops without a word
(Cookie, Host, Origin, Referer, Accept-Charset, any Proxy- or Sec- header, the rest of the Fetch
standard's forbidden request headers).invoke a signal with a timeout
(AbortSignal.timeout(ms)) where that matters.Authorization but carries
every other header the provider answered. Point the client at the API's own URL, and keep secrets in
Authorization.Cancellation, as with fetch: each invoke takes an optional AbortSignal last; an aborted call rejects
with the signal's reason, and its listener is removed when the call ends. client.close() ends every pending
call (CLOSED) and releases the connections; a closed client rejects every later call as CLOSED, an aborted
signal included. AbortSignal is the platform's: the DOM library or Node's types.
Command Query Responsibility Segregation is a pattern that performs segregate operations that read data from operations that update data by using separate interfaces.
The package f2-dsl-cqrs provide kotlin multplatform interfaces for f2.dsl.cqrs.Event, f2.dsl.cqrs.Command, f2.dsl.cqrs.Query
It also interface for querying a page o result f2.dsl.cqrs.PageRequest and Pagef2.dsl.cqrs
implementation("io.komune.f2:f2-dsl-cqrs:${Versions.f2}")<dependency>
<groupId>io.komune.f2</groupId>
<artifactId>f2-dsl-cqrs</artifactId>
<version>${Versions.f2}</version>
</dependency>
interface Message
interface Event: Message
interface Command: Message
interface Query : Messagesealed interface Pagination
class OffsetPagination(
override val offset: Int,
override val limit: Int,
) : OffsetPaginationDTO, Pagination
interface OffsetPaginationDTO {
val offset: Int
val limit: Int
}
class PagePagination(
override val page: Int?,
override val size: Int?
): PagePaginationDTO, Pagination
interface PagePaginationDTO {
val page: Int?
val size: Int?
}interface PageDTO<out OBJECT> {
val total: Int
val items: List<OBJECT>
}
class Page<out OBJECT>(
override val total: Int,
override val items: List<OBJECT>,
) : PageDTO<OBJECT>
interface PageQueryDTO : Query {
val pagination: OffsetPaginationDTO?
}
interface PageQueryResultDTO<out OBJECT> : Event, PageDTO<OBJECT> {
override val total: Int
override val items: List<OBJECT>
val pagination: OffsetPaginationDTO?
}
class PageQuery(
override val pagination: OffsetPaginationDTO?,
) : PageQueryDTO
class PageQueryResult<out OBJECT>(
override val pagination: OffsetPagination?,
override val total: Int,
override val items: List<OBJECT>,
) : PageQueryResultDTO<OBJECT>
fun <OBJECT> OffsetPaginationDTO.result(items: List<OBJECT>, total: Int): PageQueryResultDTO<OBJECT>
inline fun <T, reified R> PageDTO<T>.map(transform: (T) -> R): PageDTO<R>
inline fun <T, reified R> Page<T>.map(transform: (T) -> R): Page<R>inline fun <T, reified R: Any> PageDTO<T>.mapNotNull(transform: (T) -> R?): PageDTO<R>
inline fun OffsetPagination?.toPageRequest(): PageRequestfun <T, R> f2Function(fnc: suspend (t: T) -> R): F2Function<T, R>
suspend operator fun <T, R> F2Function<T, R>.invoke(t: T): R
suspend fun <T, R> T.invokeWith(f2: F2Function<T, R>): R
fun <R> f2Supplier(fnc: suspend () -> Flow<R>): F2Supplier<R>
fun <R> f2SupplierSingle(fnc: suspend () -> R): F2Supplier<R>
fun <R> Iterable<R>.asF2Supplier(): F2Supplier<R>
fun <R> f2Consumer(fnc: suspend (R) -> Unit): F2Consumer<R>F2 provide basic configuration for spring cloud function
implementation("io.komune.f2:f2-spring-boot-starter-function:${Versions.f2}")<dependency>
<groupId>io.komune.f2</groupId>
<artifactId>f2-spring-boot-starter-function</artifactId>
<version>${Versions.f2}</version>
</dependency>
implementation("io.komune.f2:f2-spring-boot-starter-function-http:${Versions.f2}")<dependency>
<groupId>io.komune.f2</groupId>
<artifactId>f2-spring-boot-starter-function-http</artifactId>
<version>${Versions.f2}</version>
</dependency>
import f2.dsl.fnc.F2Consumer
import f2.dsl.fnc.F2Function
import f2.dsl.fnc.F2Supplier
import f2.dsl.fnc.f2Consumer
import f2.dsl.fnc.f2Function
import f2.dsl.fnc.f2Supplier
import f2.dsl.fnc.f2SupplierSingle
import java.security.MessageDigest
import java.util.Base64
import java.util.UUID
import kotlinx.coroutines.channels.ticker
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.map
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
@SpringBootApplication
class F2SampleHttpApp {
@Bean
fun sha256(): F2Function<String, String> = f2Function { bytes ->
val md = MessageDigest.getInstance("SHA-256")
val hash = md.digest(bytes.toByteArray())
Base64.getEncoder().encodeToString(hash)
}
@Bean
fun uuid(): F2Supplier<String> = f2SupplierSingle {
UUID.randomUUID().toString()
}
@Bean
fun uuids(): F2Supplier<String> = f2Supplier {
ticker(1000).consumeAsFlow().map { UUID.randomUUID().toString() }
}
@Bean
fun println(): F2Consumer<String> = f2Consumer(::println)
}
/**
* Main method to start Spring Boot Application
*/
fun main(args: Array<String>) {
runApplication<F2SampleHttpApp>(*args)
}expect fun didClient(url: String): F2Supplier<DIDFunctionClient>
open class DIDFunctionClient constructor(private val client: F2Client) : DidAggregate {
override fun sha256(): F2Function<String, String> = client.function("sha256")
override fun uuid(): F2Supplier<String> = client.function("uuid")
override fun uuids(): F2Supplier<String> = client.function("uuids")
override fun println(): F2Consumer<String> = client.function("println")
}Integration with Springdoc to generate open api documentation.
<dependency>
<groupId>io.komune.f2</groupId>
<artifactId>f2-spring-boot-openapi</artifactId>
<version>${Versions.f2}</version>
</dependency>
implementation("io.komune.f2:f2-spring-boot-openapi:${Versions.f2}")Three serializer can be used via the spring parameter spring.cloud.function.preferred-json-mapper
f2-spring-boot-exception-http-webflux and -mvc answer every error with one body:
{"timestamp":"…","path":"/itemDelete","status":409,"error":"Conflict","requestId":"…",
"refusal":"item.CITED","message":"Cited by A: it stays","parameters":{"id":"i-1"},"citers":["A"]}refusal is always there: the rule a refusal names (F2Refusal.code), or the meaning of the status
(HttpRefusal, http.NOT_FOUND…).message, parameters and citers travel only with a refusal — an F2Exception whose F2Error carries an
F2Refusal. Any other error says nothing it was raised with, whatever server.error.include-* asks for.F2Error names, wherever the F2Exception sits in the cause chain.http.INVALID_PAYLOAD; a 401 or 403 of f2's security starters gets
the same body, with WWW-Authenticate: Bearer alone.JsonMapper bean.spring.webflux.problemdetails.enabled and spring.mvc.problemdetails.enabled must stay false (their
default): enabled, Spring's ProblemDetail handler answers the exceptions it knows (ResponseStatusException,
ServerWebInputException, HttpMessageNotReadableException…) raised in a controller before F2's error body is
written, with its own body and their detail message.
Not published since 0.47.0 (see "Modules not published"). f2-bdd-blockhound installs BlockHound for a JUnit session. The test JVM needs
-XX:+AllowRedefinitionToAddDeleteMethods (JDK 13 and later), or BlockHound cannot instrument the JDK:
tasks.withType<Test>().configureEach { jvmArgs("-XX:+AllowRedefinitionToAddDeleteMethods") }