diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..55b9e8c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,50 @@ +name: CI + +# Builds and tests the published libraries and the sample on every pull request and on +# main. The Linux job covers the JVM and Android targets (including apiCheck); the macOS +# job runs the iOS simulator tests of the two libraries. +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +jobs: + jvm-android: + runs-on: ubuntu-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 21 + - uses: gradle/actions/setup-gradle@v4 + - name: Validate Gradle wrapper + uses: gradle/actions/wrapper-validation@v4 + - name: Libraries (tests, apiCheck, Android lint) + run: ./gradlew :crdt:check :sync:check + - name: Sample (JVM tests) + run: ./gradlew :shared:jvmTest :server:test + - name: Sample app compiles (desktop and Android) + run: ./gradlew :composeApp:jvmJar :composeApp:assembleDebug + + ios: + runs-on: macos-latest + timeout-minutes: 45 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 21 + - uses: gradle/actions/setup-gradle@v4 + - name: Library iOS simulator tests + run: ./gradlew :crdt:iosSimulatorArm64Test :sync:iosSimulatorArm64Test diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 42dd7e1..e41079b 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -19,12 +19,14 @@ jobs: build: # macOS so that Dokka can analyse the iOS source sets. runs-on: macos-latest + timeout-minutes: 45 steps: - uses: actions/checkout@v4 - uses: actions/setup-java@v4 with: distribution: temurin - java-version: 17 + # :composeApp requires a JDK 21 toolchain at configuration time. + java-version: 21 - uses: gradle/actions/setup-gradle@v4 - run: ./gradlew dokkaGenerate - uses: actions/upload-pages-artifact@v3 diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml new file mode 100644 index 0000000..09e32f6 --- /dev/null +++ b/.github/workflows/publish.yml @@ -0,0 +1,40 @@ +name: Publish + +# Publishes :crdt and :sync to Maven Central (Central Portal) when a v* tag is pushed. +# The tag gives the version: v0.1.0 publishes 0.1.0. +# +# Required repository secrets: +# MAVEN_CENTRAL_USERNAME / MAVEN_CENTRAL_PASSWORD Central Portal user token +# SIGNING_KEY ASCII-armored GPG private key +# SIGNING_KEY_PASSWORD its passphrase +on: + push: + tags: ["v*"] + workflow_dispatch: + +permissions: + contents: read + +jobs: + publish: + # macOS so that the iOS klibs are built and published too. + runs-on: macos-latest + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: 21 + - uses: gradle/actions/setup-gradle@v4 + - name: Version from tag + if: startsWith(github.ref, 'refs/tags/v') + run: echo "VERSION_NAME=${GITHUB_REF_NAME#v}" >> "$GITHUB_ENV" + - name: Publish to Maven Central + env: + ORG_GRADLE_PROJECT_VERSION_NAME: ${{ env.VERSION_NAME }} + ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.MAVEN_CENTRAL_USERNAME }} + ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.MAVEN_CENTRAL_PASSWORD }} + ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.SIGNING_KEY }} + ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_KEY_PASSWORD }} + run: ./gradlew :crdt:publishToMavenCentral :sync:publishToMavenCentral --no-configuration-cache diff --git a/.gitignore b/.gitignore index 3b0a9f5..8db3e89 100644 --- a/.gitignore +++ b/.gitignore @@ -17,5 +17,11 @@ captures !*.xcworkspace/contents.xcworkspacedata **/xcshareddata/WorkspaceSettings.xcsettings -server/src/main/resources/audio +# Runtime state written by the sample server (JsonFileStorage, default ./data) +data/ +server/data/ + +# Per-user Claude Code files +.claude/settings.local.json +.claude/worktrees/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b9820c..172d767 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,13 @@ public API may evolve; breaking changes are called out below. `api` dependency. ### Fixed +- `:sync` no longer compiles with `-Xexplicit-backing-fields`, which flagged every + class of the published artifact as built by a pre-release Kotlin compiler and + forced consumers to pass `-Xskip-prerelease-check`. +- Both libraries now pin the JVM bytecode level of their `-jvm` artifact to + Java 11 (previously inherited from the JDK running Gradle), enable Kotlin's + explicit API mode, and are configured for Maven Central (Central Portal, + signed publications). - The server no longer sends the full state after every push: an up-to-date client now gets no catch-up message. - A client further behind than the server's delta log now receives the full diff --git a/CLAUDE.md b/CLAUDE.md index bb2dc24..54d6e9a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -53,8 +53,8 @@ domain-agnostic. Todo-specific concepts belong in `:shared`. - `SyncMessage` - sealed: `PushDelta`, `PullRequest`, `PullResponse`. Serialize with `SyncMessage.serializer(deltaSerializer)`. - `SyncEngine>` - client WebSocket engine. Constructor takes a - `KSerializer`, four suspending callbacks (`onRemoteDelta`, - `getPendingDelta`, `restorePendingDelta`, `getLocalClock`), and an optional + `KSerializer`, four callbacks (`onRemoteDelta`, `getPendingDelta` and + `restorePendingDelta` are suspending, `getLocalClock` is not), and an optional `SyncLogger` (defaults to `Noop`). `stop()` is suspending and joins the connect loop before returning. Exponential backoff reconnect. - `SyncLogger` - `fun interface` sink for diagnostics. Replaces all internal @@ -98,5 +98,5 @@ domain-agnostic. Todo-specific concepts belong in `:shared`. ## `design.pen` -Pencil design file at the repo root. Read only via the Pencil MCP tools, not +Pencil design file at `design/design.pen`. Read only via the Pencil MCP tools, not standard file tools. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8e87622..6af119f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -50,7 +50,10 @@ To run the demo end-to-end locally: - One logical change per PR. - Run `./gradlew check` before opening - it covers tests and `apiCheck` for the - published libraries. + published libraries. CI (`.github/workflows/ci.yml`) runs the same on every + pull request, plus the iOS simulator tests of both libraries on macOS. +- `:crdt` and `:sync` compile in Kotlin's explicit API mode: every public + declaration needs a `public` modifier and an explicit return type. - If your change touches `:crdt` or `:sync` public surface, mention it in the PR description and include the `apiDump` diff. diff --git a/README.md b/README.md index 64eb5b4..a91a0f2 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,10 @@ Architecture deep-dive: [docs/crdt-implementation.md](docs/crdt-implementation.m ## Using the libraries +The libraries are not on Maven Central yet. Until the first release, publish them +locally with `./gradlew :crdt:publishToMavenLocal :sync:publishToMavenLocal` and +consume them from `mavenLocal()`: + ```kotlin // settings.gradle.kts dependencyResolutionManagement { @@ -65,8 +69,9 @@ Quickstarts: [`:crdt` README](crdt/README.md) (build a CRDT aggregate), ## Running the sample app -Prereqs: JDK 11+, Android Studio / IntelliJ with KMP plugin, two devices or -emulators for the sync demo. +Prereqs: JDK 17+ to run Gradle (the desktop app asks for a JDK 21 toolchain, +provisioned automatically), Android Studio / IntelliJ with KMP plugin, two devices +or emulators for the sync demo. ```shell ./gradlew :server:run # Port 8080 @@ -78,7 +83,9 @@ emulators for the sync demo. Server config (env vars): - `SYNCDO_PORT` - bind port (default `8080`). -- `SYNCDO_STATE_DIR` - directory for the persisted JSON state (default `./data`). +- `SYNCDO_STATE_DIR` - directory for the persisted JSON state (default `./data`, + relative to the working directory, so `server/data/` under `./gradlew :server:run`; + not tracked in version control). On first launch each client asks for the server host. Enter: diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index 1547152..2a68960 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -10,10 +10,6 @@ plugins { } kotlin { - compilerOptions { - freeCompilerArgs.add("-Xexplicit-backing-fields") - } - androidTarget { compilerOptions { jvmTarget.set(JvmTarget.JVM_11) diff --git a/composeApp/src/jvmMain/kotlin/com/doppio/syncdo/main.kt b/composeApp/src/jvmMain/kotlin/com/doppio/syncdo/main.kt index deac29d..5795648 100644 --- a/composeApp/src/jvmMain/kotlin/com/doppio/syncdo/main.kt +++ b/composeApp/src/jvmMain/kotlin/com/doppio/syncdo/main.kt @@ -18,7 +18,7 @@ fun main() { runBlocking { AppModule.shutdown() } exitApplication() }, - title = "SyncDO — $instanceName", + title = "SyncDO - $instanceName", state = WindowState( width = 412.dp, height = 942.dp, diff --git a/crdt/README.md b/crdt/README.md index 17a2959..80638b6 100644 --- a/crdt/README.md +++ b/crdt/README.md @@ -83,7 +83,7 @@ sync engine and Ktor server endpoint: add a `clock` and implement its `ClockedSt - All types are `@Serializable` (kotlinx.serialization). JSON is the default wire format; binary formats work too. -- `LwwRegister` uses `kotlin.time.Instant` (stdlib, Kotlin 2.1+) - no extra +- `LwwRegister` uses `kotlin.time.Instant` (stdlib, stable since Kotlin 2.2) - no extra datetime dependency required. - `OrSet` is the most subtle type. Each add attaches a fresh unique tag; a remove tombstones only the tags observed at remove time. This is what gives concurrent diff --git a/crdt/build.gradle.kts b/crdt/build.gradle.kts index 58d188c..429b608 100644 --- a/crdt/build.gradle.kts +++ b/crdt/build.gradle.kts @@ -1,5 +1,6 @@ import com.vanniktech.maven.publish.JavadocJar import com.vanniktech.maven.publish.KotlinMultiplatform +import com.vanniktech.maven.publish.SonatypeHost import org.jetbrains.kotlin.gradle.dsl.JvmTarget plugins { @@ -12,6 +13,9 @@ plugins { } kotlin { + // Published library: every public declaration must say so, and must have an explicit type. + explicitApi() + androidTarget { publishLibraryVariants("release") compilerOptions { @@ -22,9 +26,13 @@ kotlin { iosArm64() iosSimulatorArm64() - jvm() - - applyDefaultHierarchyTemplate() + jvm { + // Pin the bytecode level of the published -jvm artifact instead of inheriting it + // from whichever JDK runs Gradle. Matches the Android target. + compilerOptions { + jvmTarget.set(JvmTarget.JVM_11) + } + } sourceSets { commonMain.dependencies { @@ -64,6 +72,13 @@ dokka { mavenPublishing { configure(KotlinMultiplatform(javadocJar = JavadocJar.Dokka("dokkaGeneratePublicationHtml"))) + // Maven Central through the Central Portal. Credentials and the signing key come from + // ORG_GRADLE_PROJECT_mavenCentralUsername / mavenCentralPassword / signingInMemoryKey / + // signingInMemoryKeyPassword (see .github/workflows/publish.yml). Signing is skipped for + // SNAPSHOT versions and for publishToMavenLocal when no key is configured. + publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL, automaticRelease = true) + signAllPublications() + pom { name.set("SyncDO CRDT") description.set( diff --git a/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/CrdtState.kt b/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/CrdtState.kt index 19edee4..f0c8b71 100644 --- a/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/CrdtState.kt +++ b/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/CrdtState.kt @@ -35,8 +35,8 @@ package com.doppio.syncdo.crdt * @param T the implementing type itself (`class Foo : CrdtState`), so that [merge] * takes and returns the concrete type. */ -interface CrdtState> { +public interface CrdtState> { /** Combine this state with [other] and return the result. Neither operand is modified. */ - fun merge(other: T): T + public fun merge(other: T): T } diff --git a/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/LwwRegister.kt b/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/LwwRegister.kt index b8c68e8..4ba5eaa 100644 --- a/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/LwwRegister.kt +++ b/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/LwwRegister.kt @@ -33,10 +33,10 @@ import kotlinx.serialization.Serializable * @property nodeId the node that wrote [value], used as a tie-breaker. */ @Serializable -data class LwwRegister( - val value: T, - val timestamp: Instant, - val nodeId: NodeId +public data class LwwRegister( + public val value: T, + public val timestamp: Instant, + public val nodeId: NodeId ) : CrdtState> { /** diff --git a/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/MapMerge.kt b/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/MapMerge.kt index 3e98281..680b6c9 100644 --- a/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/MapMerge.kt +++ b/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/MapMerge.kt @@ -14,7 +14,7 @@ package com.doppio.syncdo.crdt * } * ``` */ -fun > Map.mergeStates(other: Map): Map = +public fun > Map.mergeStates(other: Map): Map = mergeValues(other) { a, b -> a.merge(b) } /** Merge two maps of sets by taking the union at each key. */ diff --git a/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/OrSet.kt b/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/OrSet.kt index 7396df7..bb7b327 100644 --- a/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/OrSet.kt +++ b/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/OrSet.kt @@ -12,9 +12,9 @@ import kotlinx.serialization.Serializable * @property counter a number that [nodeId] never uses twice. */ @Serializable -data class UniqueTag( - val nodeId: NodeId, - val counter: Long +public data class UniqueTag( + public val nodeId: NodeId, + public val counter: Long ) /** @@ -59,45 +59,45 @@ data class UniqueTag( * @property tombstones the removed tags of each element that was ever removed. */ @Serializable -data class OrSet( - val entries: Map> = emptyMap(), - val tombstones: Map> = emptyMap() +public data class OrSet( + public val entries: Map> = emptyMap(), + public val tombstones: Map> = emptyMap() ) : CrdtState> { /** True if [element] is in the set. */ - fun contains(element: E): Boolean = element in entries + public fun contains(element: E): Boolean = element in entries /** The elements currently in the set. */ - fun elements(): Set = entries.keys + public fun elements(): Set = entries.keys /** * True if this set holds no tag at all, live or tombstoned. Useful to detect an empty * delta; note that a set whose elements were all removed is not empty. */ - fun isEmpty(): Boolean = entries.isEmpty() && tombstones.isEmpty() + public fun isEmpty(): Boolean = entries.isEmpty() && tombstones.isEmpty() /** * The change "add [element] with [tag]", as a delta to [merge]. * * @param tag a tag never used before, see [UniqueTag]. */ - fun addDelta(element: E, tag: UniqueTag): OrSet = + public fun addDelta(element: E, tag: UniqueTag): OrSet = OrSet(entries = mapOf(element to setOf(tag))) /** * The change "remove [element]", as a delta to [merge]: it tombstones every tag this * set has observed for [element]. Empty (see [isEmpty]) if [element] is not in the set. */ - fun removeDelta(element: E): OrSet { + public fun removeDelta(element: E): OrSet { val observedTags = entries[element] ?: return OrSet() return OrSet(tombstones = mapOf(element to observedTags)) } /** This set with [element] added. Shorthand for `merge(addDelta(element, tag))`. */ - fun add(element: E, tag: UniqueTag): OrSet = merge(addDelta(element, tag)) + public fun add(element: E, tag: UniqueTag): OrSet = merge(addDelta(element, tag)) /** This set with [element] removed. Shorthand for `merge(removeDelta(element))`. */ - fun remove(element: E): OrSet = merge(removeDelta(element)) + public fun remove(element: E): OrSet = merge(removeDelta(element)) /** Union of both sets: union of the tombstones, union of the tags minus the tombstoned ones. */ override fun merge(other: OrSet): OrSet { diff --git a/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/VectorClock.kt b/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/VectorClock.kt index c0cd19c..a9546f4 100644 --- a/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/VectorClock.kt +++ b/crdt/src/commonMain/kotlin/com/doppio/syncdo/crdt/VectorClock.kt @@ -3,7 +3,7 @@ package com.doppio.syncdo.crdt import kotlinx.serialization.Serializable /** Identifier of a replica (a device, a server). Must be unique and stable over time. */ -typealias NodeId = String +public typealias NodeId = String /** * Vector clock: one event counter per node, used to track causality between replicas. @@ -29,15 +29,15 @@ typealias NodeId = String * @property entries the counter of each node. A missing node counts as 0. */ @Serializable -data class VectorClock( - val entries: Map = emptyMap() +public data class VectorClock( + public val entries: Map = emptyMap() ) : CrdtState { /** The counter of [nodeId], or 0 if this clock has never seen it. */ - operator fun get(nodeId: NodeId): Long = entries.getOrElse(nodeId) { 0L } + public operator fun get(nodeId: NodeId): Long = entries.getOrElse(nodeId) { 0L } /** A copy of this clock where the counter of [nodeId] is increased by one. */ - fun increment(nodeId: NodeId): VectorClock = + public fun increment(nodeId: NodeId): VectorClock = copy(entries = entries + (nodeId to this[nodeId] + 1)) /** The pointwise max of both clocks. */ @@ -49,6 +49,6 @@ data class VectorClock( * has seen every event this clock has seen. Two concurrent clocks are each false for * the other. */ - fun isLessThanOrEqual(other: VectorClock): Boolean = + public fun isLessThanOrEqual(other: VectorClock): Boolean = (entries.keys + other.entries.keys).all { this[it] <= other[it] } } diff --git a/data/syncdo-state.json b/data/syncdo-state.json deleted file mode 100644 index 07098b0..0000000 --- a/data/syncdo-state.json +++ /dev/null @@ -1 +0,0 @@ -{"itemIds":{"entries":{"ca758fa1-e256-4bef-a1b5-7681cda22c2a":[{"nodeId":"86e996f7-529d-4495-844d-7f2f48bae400","counter":4}]},"tombstones":{"c62bc9e7-e847-402c-88a5-5e145bb3be7e":[{"nodeId":"86e996f7-529d-4495-844d-7f2f48bae400","counter":1}],"139e1852-8151-425c-9337-f617a96dbf0f":[{"nodeId":"86e996f7-529d-4495-844d-7f2f48bae400","counter":3}],"ea704c82-bfea-4294-919a-0287e561c417":[{"nodeId":"86e996f7-529d-4495-844d-7f2f48bae400","counter":2}]}},"items":{"ca758fa1-e256-4bef-a1b5-7681cda22c2a":{"id":"ca758fa1-e256-4bef-a1b5-7681cda22c2a","title":{"value":"Test 3","timestamp":"2026-06-07T20:15:48.790077Z","nodeId":"86e996f7-529d-4495-844d-7f2f48bae400"},"note":{"value":"","timestamp":"2026-06-07T20:15:36.164053Z","nodeId":"86e996f7-529d-4495-844d-7f2f48bae400"},"completed":{"value":false,"timestamp":"2026-06-07T20:15:36.164053Z","nodeId":"86e996f7-529d-4495-844d-7f2f48bae400"},"position":{"value":1.0,"timestamp":"2026-06-07T20:15:36.164053Z","nodeId":"86e996f7-529d-4495-844d-7f2f48bae400"},"createdAt":"2026-06-07T20:15:36.164053Z"}},"clock":{"entries":{"86e996f7-529d-4495-844d-7f2f48bae400":22,"19abba2c-17c0-4379-8a47-86726ad51ec3":5}}} \ No newline at end of file diff --git a/server/build.gradle.kts b/server/build.gradle.kts index 41310e2..0efd1f7 100644 --- a/server/build.gradle.kts +++ b/server/build.gradle.kts @@ -5,14 +5,6 @@ plugins { application } -kotlin { - compilerOptions { - // Kotlin 2.3.x is a pre-release; skip the check so the JVM-only server module - // can load classes produced by the KMP-compiled shared module. - freeCompilerArgs.add("-Xskip-prerelease-check") - } -} - group = "com.doppio.syncdo" version = "1.0.0" application { diff --git a/server/src/main/kotlin/com/doppio/syncdo/Application.kt b/server/src/main/kotlin/com/doppio/syncdo/Application.kt index 173635c..12cd094 100644 --- a/server/src/main/kotlin/com/doppio/syncdo/Application.kt +++ b/server/src/main/kotlin/com/doppio/syncdo/Application.kt @@ -19,7 +19,8 @@ private val logger = LoggerFactory.getLogger("com.doppio.syncdo.Application") fun main() { val port = System.getenv("SYNCDO_PORT")?.toIntOrNull() ?: SERVER_PORT - val server = embeddedServer(Netty, port = port, host = "0.0.0.0", module = Application::module) + val stateDir = System.getenv("SYNCDO_STATE_DIR") ?: "./data" + val server = embeddedServer(Netty, port = port, host = "0.0.0.0") { module(stateDir) } Runtime.getRuntime().addShutdownHook(Thread { logger.info("Shutting down SyncDO server…") @@ -30,12 +31,18 @@ fun main() { server.start(wait = true) } -fun Application.module() { +/** + * Ktor module of the sample server. + * + * @param stateDir directory holding the persisted JSON state. Relative paths resolve against + * the working directory (`server/` under `./gradlew :server:run`); tests pass a temp dir. + */ +fun Application.module(stateDir: String) { configureSockets() configureSerialization() val storage = JsonFileStorage( - basePath = System.getenv("SYNCDO_STATE_DIR") ?: "./data", + basePath = stateDir, logger = { msg, err -> logger.warn("storage: {}", msg, err) }, ) val initial = runBlocking { storage.load() } ?: TodoListCrdt() diff --git a/server/src/main/resources/logback.xml b/server/src/main/resources/logback.xml index 3e11d78..c91a53a 100644 --- a/server/src/main/resources/logback.xml +++ b/server/src/main/resources/logback.xml @@ -4,7 +4,7 @@ %d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n - + diff --git a/server/src/test/kotlin/com/doppio/syncdo/ApplicationTest.kt b/server/src/test/kotlin/com/doppio/syncdo/ApplicationTest.kt index f86071c..a702986 100644 --- a/server/src/test/kotlin/com/doppio/syncdo/ApplicationTest.kt +++ b/server/src/test/kotlin/com/doppio/syncdo/ApplicationTest.kt @@ -4,17 +4,20 @@ import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import io.ktor.server.testing.* +import kotlin.io.path.createTempDirectory import kotlin.test.* class ApplicationTest { @Test fun testRoot() = testApplication { + // A fresh directory per run: the test must not read or write the developer's state. + val stateDir = createTempDirectory("syncdo-test").toString() application { - module() + module(stateDir) } val response = client.get("/") assertEquals(HttpStatusCode.OK, response.status) assertEquals("SyncDO Server is running", response.bodyAsText()) } -} \ No newline at end of file +} diff --git a/shared/build.gradle.kts b/shared/build.gradle.kts index 4d93f15..c53e50a 100644 --- a/shared/build.gradle.kts +++ b/shared/build.gradle.kts @@ -7,10 +7,6 @@ plugins { } kotlin { - compilerOptions { - freeCompilerArgs.add("-Xexplicit-backing-fields") - } - androidTarget { compilerOptions { jvmTarget.set(JvmTarget.JVM_11) @@ -22,8 +18,6 @@ kotlin { jvm() - applyDefaultHierarchyTemplate() - sourceSets { commonMain.dependencies { api(projects.crdt) diff --git a/shared/src/commonMain/kotlin/com/doppio/syncdo/repository/OfflineFirstTodoRepository.kt b/shared/src/commonMain/kotlin/com/doppio/syncdo/repository/OfflineFirstTodoRepository.kt index a46c210..588ec68 100644 --- a/shared/src/commonMain/kotlin/com/doppio/syncdo/repository/OfflineFirstTodoRepository.kt +++ b/shared/src/commonMain/kotlin/com/doppio/syncdo/repository/OfflineFirstTodoRepository.kt @@ -38,14 +38,14 @@ class OfflineFirstTodoRepository( initialValue = initialState.toTodoItems() ) - override val syncStatus: StateFlow - field = MutableStateFlow(SyncStatus.Offline) + private val _syncStatus = MutableStateFlow(SyncStatus.Offline) + override val syncStatus: StateFlow = _syncStatus.asStateFlow() fun attachSyncEngine(engine: SyncEngine, scope: CoroutineScope) { statusCollectionJob?.cancel() syncEngine = engine statusCollectionJob = scope.launch { - engine.syncStatus.collect { status -> syncStatus.update { status } } + engine.syncStatus.collect { status -> _syncStatus.value = status } } } diff --git a/sync/Module.md b/sync/Module.md index b278699..ed61dda 100644 --- a/sync/Module.md +++ b/sync/Module.md @@ -18,8 +18,8 @@ Multiplatform. The client engine runs on Android, iOS and JVM; the server helper Three [SyncMessage][com.doppio.syncdo.sync.SyncMessage]s travel over one WebSocket: -- `PullRequest(clock)`, client to server, on connect: "here is what I have seen"; -- `PushDelta(delta)`, client to server, after each local change; +- `PullRequest(clock, nodeId)`, client to server, on connect: "here is what I have seen"; +- `PushDelta(delta, nodeId)`, client to server, after each local change; - `PullResponse(delta)`, server to client: what the client is missing (recent deltas merged into one, or the full state when the server's log is too short), and every peer's pushed delta. diff --git a/sync/build.gradle.kts b/sync/build.gradle.kts index 735756a..23b81a4 100644 --- a/sync/build.gradle.kts +++ b/sync/build.gradle.kts @@ -1,5 +1,6 @@ import com.vanniktech.maven.publish.JavadocJar import com.vanniktech.maven.publish.KotlinMultiplatform +import com.vanniktech.maven.publish.SonatypeHost import org.jetbrains.kotlin.gradle.dsl.JvmTarget plugins { @@ -12,9 +13,8 @@ plugins { } kotlin { - compilerOptions { - freeCompilerArgs.add("-Xexplicit-backing-fields") - } + // Published library: every public declaration must say so, and must have an explicit type. + explicitApi() androidTarget { publishLibraryVariants("release") @@ -26,9 +26,13 @@ kotlin { iosArm64() iosSimulatorArm64() - jvm() - - applyDefaultHierarchyTemplate() + jvm { + // Pin the bytecode level of the published -jvm artifact instead of inheriting it + // from whichever JDK runs Gradle. Matches the Android target. + compilerOptions { + jvmTarget.set(JvmTarget.JVM_11) + } + } sourceSets { commonMain.dependencies { @@ -37,8 +41,6 @@ kotlin { implementation(libs.kotlinx.serialization.json) implementation(libs.ktor.client.core) implementation(libs.ktor.client.websockets) - implementation(libs.ktor.client.contentNegotiation) - implementation(libs.ktor.serialization.json) } commonTest.dependencies { implementation(libs.kotlin.test) @@ -89,6 +91,13 @@ dokka { mavenPublishing { configure(KotlinMultiplatform(javadocJar = JavadocJar.Dokka("dokkaGeneratePublicationHtml"))) + // Maven Central through the Central Portal. Credentials and the signing key come from + // ORG_GRADLE_PROJECT_mavenCentralUsername / mavenCentralPassword / signingInMemoryKey / + // signingInMemoryKeyPassword (see .github/workflows/publish.yml). Signing is skipped for + // SNAPSHOT versions and for publishToMavenLocal when no key is configured. + publishToMavenCentral(SonatypeHost.CENTRAL_PORTAL, automaticRelease = true) + signAllPublications() + pom { name.set("SyncDO Sync") description.set( diff --git a/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/ClockedState.kt b/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/ClockedState.kt index eda2567..9a6288c 100644 --- a/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/ClockedState.kt +++ b/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/ClockedState.kt @@ -10,10 +10,10 @@ import com.doppio.syncdo.crdt.VectorClock * The same type is used for full states and for deltas (a delta is just a small state), * and [clock] tells which deltas a peer has not seen yet. */ -interface ClockedState> : CrdtState { +public interface ClockedState> : CrdtState { /** * The events this state contains: the clock of the replica that produced it. For a delta, * the clock of its author right after the change. */ - val clock: VectorClock + public val clock: VectorClock } diff --git a/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/DeltaBuffer.kt b/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/DeltaBuffer.kt index b9607ea..8cd6142 100644 --- a/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/DeltaBuffer.kt +++ b/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/DeltaBuffer.kt @@ -11,18 +11,18 @@ import kotlinx.coroutines.sync.withLock * To put back a delta whose push failed, simply [record] it again: [CrdtState.merge] is * commutative, so the order in which deltas are recorded does not matter. */ -class DeltaBuffer> { +public class DeltaBuffer> { private val mutex = Mutex() private var pending: D? = null /** Add [delta] to the pending changes (merged with what is already pending). */ - suspend fun record(delta: D): Unit = mutex.withLock { + public suspend fun record(delta: D): Unit = mutex.withLock { pending = pending?.merge(delta) ?: delta } /** Atomically take the pending delta and empty the buffer. Null if nothing is pending. */ - suspend fun flush(): D? = mutex.withLock { + public suspend fun flush(): D? = mutex.withLock { pending.also { pending = null } } } diff --git a/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncEngine.kt b/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncEngine.kt index 166c82d..e8973f2 100644 --- a/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncEngine.kt +++ b/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncEngine.kt @@ -15,6 +15,7 @@ import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.isActive import kotlinx.coroutines.launch @@ -42,7 +43,7 @@ import kotlinx.serialization.json.Json * - [getLocalClock]: read on connect to build the initial [SyncMessage.PullRequest]. * Must reflect every delta the application has already applied locally. */ -class SyncEngine>( +public class SyncEngine>( deltaSerializer: KSerializer, private val serverHost: String, private val serverPort: Int, @@ -61,9 +62,10 @@ class SyncEngine>( install(WebSockets) } + private val _syncStatus = MutableStateFlow(SyncStatus.Offline) + /** Current connection and sync state, for the UI. Starts as [SyncStatus.Offline]. */ - val syncStatus: StateFlow - field = MutableStateFlow(SyncStatus.Offline) + public val syncStatus: StateFlow = _syncStatus.asStateFlow() private var session: WebSocketSession? = null private var connectJob: Job? = null @@ -73,12 +75,12 @@ class SyncEngine>( * exponential backoff (1 s up to 30 s). On each connection, pulls what was missed and * pushes pending changes. */ - fun start() { + public fun start() { connectJob = scope.launch { var backoff = 1_000L while (isActive) { try { - syncStatus.update { SyncStatus.Syncing } + _syncStatus.update { SyncStatus.Syncing } client.webSocket(host = serverHost, port = serverPort, path = path) { session = this backoff = 1_000L @@ -90,7 +92,7 @@ class SyncEngine>( send(Frame.Text(json.encodeToString(messageSerializer, pullRequest))) pushPendingDelta() - syncStatus.update { SyncStatus.Synced } + _syncStatus.update { SyncStatus.Synced } for (frame in incoming) { if (frame is Frame.Text) { @@ -101,7 +103,7 @@ class SyncEngine>( } } catch (e: Exception) { logger.log(SyncLogLevel.Warn, "SyncEngine: connection error: ${e.message}", e) - syncStatus.update { SyncStatus.Offline } + _syncStatus.update { SyncStatus.Offline } } session = null delay(backoff) @@ -116,36 +118,36 @@ class SyncEngine>( is SyncMessage.PushDelta -> onRemoteDelta(message.delta) is SyncMessage.PullRequest -> return // Server-bound; ignore on client. } - syncStatus.update { SyncStatus.Synced } + _syncStatus.update { SyncStatus.Synced } } /** * Push the pending local changes now, if connected. Call it after each local mutation. * When offline, the changes stay pending and are pushed on the next connection. */ - suspend fun pushPendingDelta() { + public suspend fun pushPendingDelta() { val ws = session ?: run { - syncStatus.update { SyncStatus.PendingChanges } + _syncStatus.update { SyncStatus.PendingChanges } return } val delta = getPendingDelta() ?: return try { - syncStatus.update { SyncStatus.Syncing } + _syncStatus.update { SyncStatus.Syncing } val message: SyncMessage = SyncMessage.PushDelta(delta = delta, nodeId = nodeId) ws.send(Frame.Text(json.encodeToString(messageSerializer, message))) } catch (e: Exception) { logger.log(SyncLogLevel.Warn, "SyncEngine: failed to push delta: ${e.message}", e) restorePendingDelta(delta) - syncStatus.update { SyncStatus.PendingChanges } + _syncStatus.update { SyncStatus.PendingChanges } } } /** Disconnect and wait until the connection loop has stopped. */ - suspend fun stop() { + public suspend fun stop() { connectJob?.cancelAndJoin() connectJob = null runCatching { session?.close() } session = null - syncStatus.update { SyncStatus.Offline } + _syncStatus.update { SyncStatus.Offline } } } diff --git a/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncLogger.kt b/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncLogger.kt index 9e367ce..2a8be8f 100644 --- a/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncLogger.kt +++ b/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncLogger.kt @@ -1,7 +1,7 @@ package com.doppio.syncdo.sync /** Severity of a [SyncLogger] event. */ -enum class SyncLogLevel { +public enum class SyncLogLevel { /** Verbose details, useful while developing. */ Debug, @@ -21,14 +21,14 @@ enum class SyncLogLevel { * Logcat on Android) to surface connection errors, push failures, and merge * activity without dragging an SLF4J dependency into common code. */ -fun interface SyncLogger { +public fun interface SyncLogger { /** Record one event; [error] is the exception that caused it, if any. */ - fun log(level: SyncLogLevel, message: String, error: Throwable?) + public fun log(level: SyncLogLevel, message: String, error: Throwable?) /** Ready-made loggers. */ - companion object { + public companion object { /** Discards every event. */ - val Noop: SyncLogger = SyncLogger { _, _, _ -> } + public val Noop: SyncLogger = SyncLogger { _, _, _ -> } } } diff --git a/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncMessage.kt b/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncMessage.kt index 395ac22..f205cf7 100644 --- a/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncMessage.kt +++ b/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncMessage.kt @@ -17,7 +17,7 @@ import kotlinx.serialization.Serializable * something is missing), and to broadcast every peer's pushed delta. */ @Serializable -sealed interface SyncMessage { +public sealed interface SyncMessage { /** * Client to server: a local change to merge into the server state and forward to peers. @@ -27,9 +27,9 @@ sealed interface SyncMessage { */ @Serializable @SerialName("push_delta") - data class PushDelta( - val delta: D, - val nodeId: NodeId, + public data class PushDelta( + public val delta: D, + public val nodeId: NodeId, ) : SyncMessage /** @@ -40,9 +40,9 @@ sealed interface SyncMessage { */ @Serializable @SerialName("pull_request") - data class PullRequest( - val clock: VectorClock, - val nodeId: NodeId, + public data class PullRequest( + public val clock: VectorClock, + public val nodeId: NodeId, ) : SyncMessage /** @@ -52,7 +52,7 @@ sealed interface SyncMessage { */ @Serializable @SerialName("pull_response") - data class PullResponse( - val delta: D, + public data class PullResponse( + public val delta: D, ) : SyncMessage } diff --git a/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncStatus.kt b/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncStatus.kt index 92331d5..44df75b 100644 --- a/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncStatus.kt +++ b/sync/src/commonMain/kotlin/com/doppio/syncdo/sync/SyncStatus.kt @@ -3,7 +3,7 @@ package com.doppio.syncdo.sync /** * State of a [SyncEngine]. Exposed as a `StateFlow` on the engine for UI binding. */ -enum class SyncStatus { +public enum class SyncStatus { /** Connected to the server and caught up. */ Synced, /** Actively pushing or pulling. */ diff --git a/sync/src/jvmMain/kotlin/com/doppio/syncdo/sync/server/SyncRoute.kt b/sync/src/jvmMain/kotlin/com/doppio/syncdo/sync/server/SyncRoute.kt index e00cb20..9e712b5 100644 --- a/sync/src/jvmMain/kotlin/com/doppio/syncdo/sync/server/SyncRoute.kt +++ b/sync/src/jvmMain/kotlin/com/doppio/syncdo/sync/server/SyncRoute.kt @@ -27,7 +27,7 @@ import kotlinx.serialization.json.Json * } * ``` */ -fun > Route.syncEndpoint( +public fun > Route.syncEndpoint( server: SyncServer, deltaSerializer: KSerializer, path: String = "/sync", diff --git a/sync/src/jvmMain/kotlin/com/doppio/syncdo/sync/server/SyncServer.kt b/sync/src/jvmMain/kotlin/com/doppio/syncdo/sync/server/SyncServer.kt index f195966..a7b3ac1 100644 --- a/sync/src/jvmMain/kotlin/com/doppio/syncdo/sync/server/SyncServer.kt +++ b/sync/src/jvmMain/kotlin/com/doppio/syncdo/sync/server/SyncServer.kt @@ -20,7 +20,7 @@ import kotlinx.coroutines.sync.withLock * in-memory writes, or `launch`-and-return). Use for persistence, metrics, or audit * logs. Exceptions propagate to the caller of [mergeDelta]. */ -class SyncServer>( +public class SyncServer>( initialState: S, maxLogSize: Int = 100, private val onStateChanged: suspend (S) -> Unit = {}, @@ -30,7 +30,7 @@ class SyncServer>( private val deltaLog = DeltaLog(initialState.clock, maxLogSize) /** Merge a client-pushed delta into the canonical state and record it in the log. */ - suspend fun mergeDelta(delta: S): Unit = mutex.withLock { + public suspend fun mergeDelta(delta: S): Unit = mutex.withLock { state = state.merge(delta) deltaLog.append(delta) onStateChanged(state) @@ -41,7 +41,7 @@ class SyncServer>( * covers the gap, the full state otherwise (a full state is a valid delta). Null if * the client is up to date. */ - suspend fun getDeltaSince(clientClock: VectorClock): S? = mutex.withLock { + public suspend fun getDeltaSince(clientClock: VectorClock): S? = mutex.withLock { when { state.clock.isLessThanOrEqual(clientClock) -> null deltaLog.covers(clientClock) -> deltaLog.missedSince(clientClock) @@ -50,5 +50,5 @@ class SyncServer>( } /** Current authoritative state. Read-only snapshot. */ - suspend fun currentState(): S = mutex.withLock { state } + public suspend fun currentState(): S = mutex.withLock { state } }