Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

feat(server): the Concat API on a socket, JSON-RPC lines and gRPC

Jareer65e43fb78189
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2df023f8..197576bb 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -87,6 +87,12 @@ jobs:
working-directory: src
- run: cargo test --workspace
working-directory: src
+ # The gRPC transport is a feature nothing else in the workspace turns
+ # on, so it is linted and tested here on its own. See concat-server.
+ - run: cargo clippy -p concat-server -p concat-cli --features grpc --all-targets -- -D warnings
+ working-directory: src
+ - run: cargo test -p concat-server --features grpc
+ working-directory: src
# The engine crates that carry no native library build for the web. This
# job is what keeps that true: a std::thread or a blocking wait that
diff --git a/src/Cargo.lock b/src/Cargo.lock
index 7c1799c0..a09670c4 100644
--- a/src/Cargo.lock
+++ b/src/Cargo.lock
@@ -300,7 +300,7 @@ checksum = "f211a51805bc641f3ad5b7664c77d2547af685cc33b4cd8d31964027a46f13f1"
dependencies = [
"anstyle",
"memchr",
- "unicode-width",
+ "unicode-width 0.2.2",
]
[[package]]
@@ -650,6 +650,49 @@ dependencies = [
"arrayvec",
]
+[[package]]
+name = "axum"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
+dependencies = [
+ "axum-core",
+ "bytes",
+ "futures-util",
+ "http",
+ "http-body",
+ "http-body-util",
+ "itoa",
+ "matchit",
+ "memchr",
+ "mime",
+ "percent-encoding",
+ "pin-project-lite",
+ "serde_core",
+ "sync_wrapper",
+ "tower",
+ "tower-layer",
+ "tower-service",
+]
+
+[[package]]
+name = "axum-core"
+version = "0.5.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "http-body-util",
+ "mime",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tower-layer",
+ "tower-service",
+]
+
[[package]]
name = "base64"
version = "0.22.1"
@@ -668,6 +711,12 @@ version = "1.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
+[[package]]
+name = "beef"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a8241f3ebb85c056b509d4327ad0358fbbba6ffb340bf388f26350aeda225b1"
+
[[package]]
name = "bincode"
version = "2.0.1"
@@ -1116,7 +1165,7 @@ checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
dependencies = [
"serde",
"termcolor",
- "unicode-width",
+ "unicode-width 0.2.2",
]
[[package]]
@@ -1145,12 +1194,14 @@ dependencies = [
name = "concat"
version = "0.2.2"
dependencies = [
+ "concat-api",
"concat-core",
"concat-effects",
"concat-export",
"concat-host",
"concat-media",
"concat-project",
+ "concat-server",
"concat-speech",
"concat-vision",
"image",
@@ -1206,6 +1257,7 @@ dependencies = [
"concat-media",
"concat-project",
"concat-render",
+ "concat-server",
"serde_json",
]
@@ -1288,6 +1340,22 @@ dependencies = [
"wgpu",
]
+[[package]]
+name = "concat-server"
+version = "0.2.2"
+dependencies = [
+ "concat-api",
+ "prost",
+ "protox",
+ "serde_json",
+ "tempfile",
+ "tokio",
+ "tokio-stream",
+ "tonic",
+ "tonic-prost",
+ "tonic-prost-build",
+]
+
[[package]]
name = "concat-speech"
version = "0.2.2"
@@ -2021,6 +2089,12 @@ dependencies = [
"writeable",
]
+[[package]]
+name = "fixedbitset"
+version = "0.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
+
[[package]]
name = "flate2"
version = "1.1.10"
@@ -2325,7 +2399,7 @@ version = "0.2.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"
dependencies = [
- "unicode-width",
+ "unicode-width 0.2.2",
]
[[package]]
@@ -2509,6 +2583,25 @@ version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b40ca9252762c466af32d0b1002e91e4e1bc5398f77455e55474deb466355ff5"
+[[package]]
+name = "h2"
+version = "0.4.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "fnv",
+ "futures-core",
+ "futures-sink",
+ "http",
+ "indexmap",
+ "slab",
+ "tokio",
+ "tokio-util",
+ "tracing",
+]
+
[[package]]
name = "half"
version = "2.7.1"
@@ -2629,12 +2722,96 @@ dependencies = [
"itoa",
]
+[[package]]
+name = "http-body"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
+dependencies = [
+ "bytes",
+ "http",
+]
+
+[[package]]
+name = "http-body-util"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "pin-project-lite",
+]
+
[[package]]
name = "httparse"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+[[package]]
+name = "httpdate"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+
+[[package]]
+name = "hyper"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "h2",
+ "http",
+ "http-body",
+ "httparse",
+ "httpdate",
+ "itoa",
+ "pin-project-lite",
+ "smallvec",
+ "tokio",
+ "want",
+]
+
+[[package]]
+name = "hyper-timeout"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b90d566bffbce6a75bd8b09a05aa8c2cb1fabb6cb348f8840c9e4c90a0d83b0"
+dependencies = [
+ "hyper",
+ "hyper-util",
+ "pin-project-lite",
+ "tokio",
+ "tower-service",
+]
+
+[[package]]
+name = "hyper-util"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
+dependencies = [
+ "bytes",
+ "futures-channel",
+ "futures-util",
+ "http",
+ "http-body",
+ "hyper",
+ "libc",
+ "pin-project-lite",
+ "socket2",
+ "tokio",
+ "tower-service",
+ "tracing",
+]
+
[[package]]
name = "i-slint-backend-android-activity"
version = "1.17.1"
@@ -3606,6 +3783,72 @@ version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+[[package]]
+name = "logos"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff472f899b4ec2d99161c51f60ff7075eeb3097069a36050d8037a6325eb8154"
+dependencies = [
+ "logos-derive 0.15.1",
+]
+
+[[package]]
+name = "logos"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb2c55a318a87600ea870ff8c2012148b44bf18b74fad48d0f835c38c7d07c5f"
+dependencies = [
+ "logos-derive 0.16.1",
+]
+
+[[package]]
+name = "logos-codegen"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "192a3a2b90b0c05b27a0b2c43eecdb7c415e29243acc3f89cc8247a5b693045c"
+dependencies = [
+ "beef",
+ "fnv",
+ "lazy_static",
+ "proc-macro2",
+ "quote",
+ "regex-syntax",
+ "rustc_version",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "logos-codegen"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "58b3ffaa284e1350d017a57d04ada118c4583cf260c8fb01e0fe28a2e9cf8970"
+dependencies = [
+ "fnv",
+ "proc-macro2",
+ "quote",
+ "regex-automata",
+ "regex-syntax",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "logos-derive"
+version = "0.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "605d9697bcd5ef3a42d38efc51541aa3d6a4a25f7ab6d1ed0da5ac632a26b470"
+dependencies = [
+ "logos-codegen 0.15.1",
+]
+
+[[package]]
+name = "logos-derive"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52d3a9855747c17eaf4383823f135220716ab49bea5fbea7dd42cc9a92f8aa31"
+dependencies = [
+ "logos-codegen 0.16.1",
+]
+
[[package]]
name = "loop9"
version = "0.1.5"
@@ -3692,6 +3935,12 @@ dependencies = [
"libc",
]
+[[package]]
+name = "matchit"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
+
[[package]]
name = "matrixmultiply"
version = "0.3.11"
@@ -3736,6 +3985,34 @@ dependencies = [
"autocfg",
]
+[[package]]
+name = "miette"
+version = "7.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f98efec8807c63c752b5bd61f862c165c115b0a35685bdcfd9238c7aeb592b7"
+dependencies = [
+ "cfg-if",
+ "miette-derive",
+ "unicode-width 0.1.14",
+]
+
+[[package]]
+name = "miette-derive"
+version = "7.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db5b29714e950dbb20d5e6f74f9dcec4edbcc1067bb7f8ed198c097b8c1a818b"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "mime"
+version = "0.3.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
+
[[package]]
name = "minimal-lexical"
version = "0.2.1"
@@ -3762,6 +4039,17 @@ dependencies = [
"simd-adler32",
]
+[[package]]
+name = "mio"
+version = "1.2.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8"
+dependencies = [
+ "libc",
+ "wasi",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "moxcms"
version = "0.8.1"
@@ -3791,6 +4079,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "multimap"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084"
+
[[package]]
name = "naga"
version = "29.0.4"
@@ -4710,6 +5004,17 @@ version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+[[package]]
+name = "petgraph"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"
+dependencies = [
+ "fixedbitset",
+ "hashbrown 0.15.5",
+ "indexmap",
+]
+
[[package]]
name = "phf"
version = "0.13.1"
@@ -4972,6 +5277,98 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "prost"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1"
+dependencies = [
+ "bytes",
+ "prost-derive",
+]
+
+[[package]]
+name = "prost-build"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "03da047801ff44bb6a4d407d4860c05fd70bb81714e6b2f3812603d5b145b042"
+dependencies = [
+ "heck",
+ "itertools 0.14.0",
+ "log",
+ "multimap",
+ "petgraph",
+ "prettyplease",
+ "prost",
+ "prost-types",
+ "pulldown-cmark",
+ "pulldown-cmark-to-cmark",
+ "regex",
+ "syn 2.0.119",
+ "tempfile",
+]
+
+[[package]]
+name = "prost-derive"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b570b25f7617e43d59005d0990ccb79e950a423952cea19671b7a876da390adf"
+dependencies = [
+ "anyhow",
+ "itertools 0.14.0",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "prost-reflect"
+version = "0.16.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01b80ea363c31af2de2b92e3c07ed1156628f7838c4afb4df75ee78a37fedbd1"
+dependencies = [
+ "logos 0.16.1",
+ "miette",
+ "prost",
+ "prost-types",
+]
+
+[[package]]
+name = "prost-types"
+version = "0.14.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f94967dc7688f3054c7fac87473ffae4cc4c3904800e2d9f5b857246d8963b0a"
+dependencies = [
+ "prost",
+]
+
+[[package]]
+name = "protox"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4f25a07a73c6717f0b9bbbd685918f5df9815f7efba450b83d9c9dea41f0e3a1"
+dependencies = [
+ "bytes",
+ "miette",
+ "prost",
+ "prost-reflect",
+ "prost-types",
+ "protox-parse",
+ "thiserror 2.0.20",
+]
+
+[[package]]
+name = "protox-parse"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "072eee358134396a4643dff81cfff1c255c9fbd3fb296be14bdb6a26f9156366"
+dependencies = [
+ "logos 0.15.1",
+ "miette",
+ "prost-types",
+ "thiserror 2.0.20",
+]
+
[[package]]
name = "pulldown-cmark"
version = "0.13.4"
@@ -4991,6 +5388,15 @@ version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
+[[package]]
+name = "pulldown-cmark-to-cmark"
+version = "22.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab1ad36992cead65f02aa399a373a42730922f1525d988172634fdefdecb8a60"
+dependencies = [
+ "pulldown-cmark",
+]
+
[[package]]
name = "pulp"
version = "0.22.3"
@@ -5396,7 +5802,7 @@ dependencies = [
"natord",
"snafu",
"unicode-linebreak",
- "unicode-width",
+ "unicode-width 0.2.2",
]
[[package]]
@@ -5981,6 +6387,16 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "socket2"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "socks"
version = "0.3.4"
@@ -6139,6 +6555,12 @@ dependencies = [
"unicode-ident",
]
+[[package]]
+name = "sync_wrapper"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
+
[[package]]
name = "synstructure"
version = "0.13.2"
@@ -6385,6 +6807,57 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
+[[package]]
+name = "tokio"
+version = "1.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
+dependencies = [
+ "bytes",
+ "libc",
+ "mio",
+ "pin-project-lite",
+ "socket2",
+ "tokio-macros",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "tokio-macros"
+version = "2.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.4",
+]
+
+[[package]]
+name = "tokio-stream"
+version = "0.1.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b"
+dependencies = [
+ "futures-core",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "tokio-util"
+version = "0.7.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "futures-sink",
+ "libc",
+ "pin-project-lite",
+ "tokio",
+]
+
[[package]]
name = "toml"
version = "1.1.5+spec-1.1.0"
@@ -6437,6 +6910,105 @@ version = "1.1.2+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
+[[package]]
+name = "tonic"
+version = "0.14.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef"
+dependencies = [
+ "async-trait",
+ "axum",
+ "base64 0.22.1",
+ "bytes",
+ "h2",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-timeout",
+ "hyper-util",
+ "percent-encoding",
+ "pin-project",
+ "socket2",
+ "sync_wrapper",
+ "tokio",
+ "tokio-stream",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "tonic-build"
+version = "0.14.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c68f61875ac5293cf72e6c8cf0158086428c82c37229e98c840878f1706b0322"
+dependencies = [
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "tonic-prost"
+version = "0.14.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0"
+dependencies = [
+ "bytes",
+ "prost",
+ "tonic",
+]
+
+[[package]]
+name = "tonic-prost-build"
+version = "0.14.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "654e5643eff75d7f8c99197ce1440ed19a3474eada74c12bbac488b2cafdae27"
+dependencies = [
+ "prettyplease",
+ "proc-macro2",
+ "prost-build",
+ "prost-types",
+ "quote",
+ "syn 2.0.119",
+ "tempfile",
+ "tonic-build",
+]
+
+[[package]]
+name = "tower"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
+dependencies = [
+ "futures-core",
+ "futures-util",
+ "indexmap",
+ "pin-project-lite",
+ "slab",
+ "sync_wrapper",
+ "tokio",
+ "tokio-util",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "tower-layer"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
+
+[[package]]
+name = "tower-service"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
+
[[package]]
name = "tracing"
version = "0.1.44"
@@ -6469,6 +7041,12 @@ dependencies = [
"once_cell",
]
+[[package]]
+name = "try-lock"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+
[[package]]
name = "ttf-parser"
version = "0.25.1"
@@ -6577,6 +7155,12 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94"
+[[package]]
+name = "unicode-width"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7dd6e30e90baa6f72411720665d41d89b9a3d039dc45b8faea1ddd07f617f6af"
+
[[package]]
name = "unicode-width"
version = "0.2.2"
@@ -6773,6 +7357,15 @@ dependencies = [
"winapi-util",
]
+[[package]]
+name = "want"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
+dependencies = [
+ "try-lock",
+]
+
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
diff --git a/src/Cargo.toml b/src/Cargo.toml
index eb1db0fe..fbe5587d 100644
--- a/src/Cargo.toml
+++ b/src/Cargo.toml
@@ -16,6 +16,7 @@ concat-render = { path = "crates/concat-render" }
concat-export = { path = "crates/concat-export" }
concat-host = { path = "crates/concat-host" }
concat-api = { path = "crates/concat-api" }
+concat-server = { path = "crates/concat-server" }
concat-speech = { path = "crates/concat-speech" }
concat-effects = { path = "crates/concat-effects" }
concat-text = { path = "crates/concat-text" }
@@ -24,7 +25,7 @@ concat = { path = "crates/concat" }
serde_json = "1"
thiserror = "2"
-clap = { version = "4", features = ["derive"] }
+clap = { version = "4", features = ["derive", "env"] }
# The GPU compositor, behind concat-render's `gpu` feature. A heavy tree, which
# is exactly why it is optional: engine-only work never pays for it. Pinned to
diff --git a/src/README.md b/src/README.md
index 6e67ef9b..9730b2c6 100644
--- a/src/README.md
+++ b/src/README.md
@@ -12,8 +12,9 @@ The video engine behind Concat. Rust, no GC, no hidden control flow.
| `concat-render` | Turning a timeline plus a timestamp into one finished frame. | `concat-core`, wgpu (optional) |
| `concat-effects` | Effect packages: manifests, chain templates, the catalogue. Each built-in effect is a folder under `packages/`. | `concat-project`, serde, toml |
| `concat-export` | Timeline to file: flatten, the frame-by-frame render loop, the paused monitor's true frame. | `concat-core`, `concat-media`, `concat-render`, `concat-project`, `concat-effects` |
-| `concat-api` | The Concat API: JSON requests in, responses and events out. Projects, edits, media, the catalogue, templates, exports, frames. | `concat-host`, `concat-export`, `concat-effects`, `concat-project` |
-| `concat-cli` | A binary to drive the above: `probe`, `render`, and `api`, the API over stdin and stdout. | `concat-api`, the engine crates |
+| `concat-api` | The Concat API: JSON requests in, responses and events out. Projects, edits, media, the catalogue, templates, exports as jobs, frames. | `concat-host`, `concat-export`, `concat-effects`, `concat-project` |
+| `concat-server` | The API on a socket: JSON-RPC lines over TCP or a Unix socket, and gRPC behind the `grpc` feature. One dispatcher, many callers. | `concat-api`; tonic and tokio with `grpc` |
+| `concat-cli` | A binary to drive the above: `probe`, `render`, `api` (the API over stdin and stdout) and `serve` (the API on a socket). | `concat-server`, `concat-api`, the engine crates |
| `concat-host` | What the window needs that is not the edit: sessions, project folders, previews, playback, templates, job slots. | `concat-media`, `concat-project`, `concat-export`, cpal |
| `concat-speech` | Transcription (whisper.cpp, in-process) and text to speech (Kokoro via sherpa-onnx). | `concat-host`, `concat-media`, whisper-rs, sherpa-onnx |
| `concat` | The editor window: every pane, dialog and primitive, in Slint. The app a user launches. | slint, `concat-host`, `concat-speech` |
@@ -25,7 +26,7 @@ The dependency arrows point one way:
concat -> concat-speech -> concat-host -> {export, project, media} -> core
-> render -> core
export -> effects -> project
-concat-cli -> concat-api -> concat-host
+concat-cli -> concat-server -> concat-api -> concat-host
```
If you ever find yourself wanting `core` to depend on `media`, something has
@@ -43,7 +44,9 @@ cargo test
cargo run -p concat-cli -- probe some-video.mp4
cargo run -p concat-cli -- render some-video.mp4 out.mp4 --frames 120
cargo run -p concat-cli -- api '{"method":"catalogue.list","kind":"filter"}'
-cargo run -p concat-cli -- api < edits.jsonl # one request per line; see concat-api
+cargo run -p concat-cli -- api < edits.jsonl # one JSON-RPC call per line; see below
+cargo run -p concat-cli -- serve # the same API on 127.0.0.1:7420
+cargo run -p concat-cli --features grpc -- serve --grpc 127.0.0.1:7421
cargo run -p concat # the editor window, debug
cargo run --profile quick -p concat # optimised, rebuilds in seconds: for trying changes
cargo build --profile app -p concat # the shipping binary: fat LTO, panic=abort, stripped
@@ -116,6 +119,41 @@ activity's `android_main`, and `crates/concat/src/platform.rs` is where
the three differ - how the backend is chosen, how files are picked, and
whether there is a title strip to drag.
+## Driving Concat without the window
+
+Everything the window does to a project, a script can do through the Concat
+API: `concat-api` is the one dispatcher, and the transports only carry it.
+On a line - stdin, TCP, a Unix socket - a call is JSON-RPC 2.0, one object
+per line, and the response comes back with the call's id:
+
+```jsonl
+{"jsonrpc":"2.0","id":1,"method":"project.open","params":{"path":"/edits/Reel"}}
+{"jsonrpc":"2.0","id":1,"result":{"project":{...},"canUndo":false,...}}
+{"jsonrpc":"2.0","id":2,"method":"edit.apply","params":{"path":"/edits/Reel","command":{"op":"addTextClip","start":1.5}}}
+{"jsonrpc":"2.0","id":2,"result":{...}}
+{"jsonrpc":"2.0","id":3,"method":"export.run","params":{"path":"/edits/Reel","output":"/edits/reel.mp4"}}
+{"jsonrpc":"2.0","id":3,"result":{"job":"j1","path":"/edits/Reel","output":"/edits/reel.mp4"}}
+{"jsonrpc":"2.0","method":"export.progress","params":{"job":"j1","path":"/edits/Reel","frame":30,"total":900,"stage":"video"}}
+{"jsonrpc":"2.0","method":"export.done","params":{"job":"j1","path":"/edits/Reel","output":"/edits/reel.mp4","width":1920,"height":1080}}
+```
+
+An `edit.apply` carries a `concat-project` command as it is, so every edit
+the window can make is one a caller can make, with the same refusals. An
+error is `{"code": -32001, "message": "...", "data": {"code": "notOpen"}}`:
+the number is JSON-RPC's, the name in `data` is the API's - `parse`,
+`invalid`, `notOpen`, `notFound`, `refused`, `busy`, `cancelled`, `failed`,
+`unauthorized`. Exports are jobs: the response names one at once and its
+events follow, to every connected caller, each naming its job and project.
+
+`concat-cli serve` puts the same lines on a socket. It binds loopback unless
+told otherwise and refuses any other address without `--token` (or
+`CONCAT_API_TOKEN`), which a connection then presents as its first line,
+`{"jsonrpc":"2.0","id":0,"method":"auth","params":{"token":"..."}}`. There
+is no encryption; a bind off loopback belongs behind something that has it.
+With the `grpc` feature the same API is served over HTTP/2 from
+`crates/concat-server/proto/concat.proto`, a thin envelope carrying the
+same JSON, with the token as `authorization: Bearer ...` metadata.
+
## Reading this codebase cold
1. [`../ARCHITECTURE.md`](../ARCHITECTURE.md) - the map of the whole system. Read it first.
diff --git a/src/crates/concat-api/src/lib.rs b/src/crates/concat-api/src/lib.rs
index ca88b382..1eebe109 100644
--- a/src/crates/concat-api/src/lib.rs
+++ b/src/crates/concat-api/src/lib.rs
@@ -40,12 +40,13 @@ use base64::Engine as _;
use concat_effects::Catalogue;
use concat_effects::manifest::Kind;
use concat_export::{ExportClip, ExportRequest};
+pub use concat_host::AppDirs;
use concat_host::cutout::{self, AnalyseRequest, Cutouts};
use concat_host::export::{self, Exporter};
use concat_host::preview::{FrameSpec, Monitor};
use concat_host::session::EditorView;
use concat_host::templates::{self, SlotFill};
-use concat_host::{AppDirs, ProjectInfo, Session, Titles, media, projects};
+use concat_host::{ProjectInfo, Session, Titles, media, projects};
use concat_project::Command;
use concat_project::model::VideoSettings;
diff --git a/src/crates/concat-api/src/message.rs b/src/crates/concat-api/src/message.rs
index daf20a4e..b7f60a3a 100644
--- a/src/crates/concat-api/src/message.rs
+++ b/src/crates/concat-api/src/message.rs
@@ -449,6 +449,9 @@ pub enum ErrorCode {
Busy,
/// The job was stopped by [`Request::ExportCancel`].
Cancelled,
+ /// The transport wanted a token and did not get the right one. Never
+ /// raised by the API itself.
+ Unauthorized,
/// Everything else: a file that could not be read or written, a decode
/// that failed, a model that did not download.
Failed,
@@ -467,6 +470,7 @@ impl ErrorCode {
ErrorCode::Refused => -32003,
ErrorCode::Busy => -32004,
ErrorCode::Cancelled => -32005,
+ ErrorCode::Unauthorized => -32006,
}
}
}
diff --git a/src/crates/concat-cli/Cargo.toml b/src/crates/concat-cli/Cargo.toml
index 02d614bf..8e07b729 100644
--- a/src/crates/concat-cli/Cargo.toml
+++ b/src/crates/concat-cli/Cargo.toml
@@ -15,8 +15,10 @@ path = "src/main.rs"
concat-core.workspace = true
concat-media.workspace = true
concat-render.workspace = true
-# The `api` command: the Concat API over stdin and stdout.
+# The `api` command: the Concat API over stdin and stdout. The `serve`
+# command: the same on a socket.
concat-api.workspace = true
+concat-server.workspace = true
serde_json.workspace = true
# `preview` renders one effect at its defaults: the catalogue for the
# chain, the document model for the applied entry it takes.
@@ -24,5 +26,9 @@ concat-effects.workspace = true
concat-project.workspace = true
clap.workspace = true
+[features]
+# `serve --grpc`. Off by default; see concat-server.
+grpc = ["concat-server/grpc"]
+
[lints]
workspace = true
diff --git a/src/crates/concat-cli/src/main.rs b/src/crates/concat-cli/src/main.rs
index 52f2592a..3dc0a18a 100644
--- a/src/crates/concat-cli/src/main.rs
+++ b/src/crates/concat-cli/src/main.rs
@@ -7,12 +7,14 @@
//! `render` command is the vertical slice: probe, build a timeline, plan every
//! frame, decode, composite, encode. The `api` command is the Concat API's
//! first transport: JSON-RPC requests in, responses and events out, one per
-//! line, so a script in any language edits and exports a project. `preview`
-//! is how the window's effect cards get their pictures: one still through one
-//! package at its defaults.
+//! line, so a script in any language edits and exports a project; `serve`
+//! is the same API on a socket, for callers that are other processes.
+//! `preview` is how the window's effect cards get their pictures: one still
+//! through one package at its defaults.
use std::error::Error;
use std::io::{BufRead, Write};
+use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
@@ -62,6 +64,25 @@ enum Command {
request: Option<String>,
},
+ /// Serve the Concat API on a socket until the process is stopped:
+ /// JSON-RPC lines over TCP or a Unix socket, and gRPC in a build that
+ /// has it. With no address given, JSON-RPC on 127.0.0.1:7420.
+ Serve {
+ /// The TCP address for JSON-RPC lines, e.g. 127.0.0.1:7420.
+ #[arg(long)]
+ json: Option<SocketAddr>,
+ /// A Unix socket path for JSON-RPC lines.
+ #[arg(long)]
+ socket: Option<PathBuf>,
+ /// The TCP address for gRPC. Needs a build with the `grpc` feature.
+ #[arg(long)]
+ grpc: Option<SocketAddr>,
+ /// The token every connection presents first. Required for any
+ /// address that is not loopback.
+ #[arg(long, env = "CONCAT_API_TOKEN")]
+ token: Option<String>,
+ },
+
/// Run one picture through an effect at its defaults and write the
/// result as a JPEG - how the effect cards' previews are made:
/// `concat-cli preview assets/effect-preview-source.jpg out.jpg --effect concat.emboss`.
@@ -93,6 +114,12 @@ fn main() -> Result<(), Box<dyn Error>> {
fade,
} => render(&input, &output, frames, fade),
Command::Api { request } => api(request),
+ Command::Serve {
+ json,
+ socket,
+ grpc,
+ token,
+ } => serve(json, socket, grpc, token),
Command::Preview {
input,
output,
@@ -143,6 +170,48 @@ fn emit(message: &Message) {
let _ = out.flush();
}
+/// The socket transports, until the process is stopped. Where they listen
+/// is printed, one line each, so a script that started this knows where
+/// to connect.
+fn serve(
+ json: Option<SocketAddr>,
+ socket: Option<PathBuf>,
+ grpc: Option<SocketAddr>,
+ token: Option<String>,
+) -> Result<(), Box<dyn Error>> {
+ let nothing_asked = json.is_none() && socket.is_none() && grpc.is_none();
+ let config = concat_server::Config {
+ json: json.or_else(|| nothing_asked.then(|| DEFAULT_JSON.parse().expect("an address"))),
+ socket,
+ grpc,
+ token,
+ };
+ let server = concat_server::Server::start(config, concat_api::Api::new)?;
+ if let Some(address) = server.json_addr() {
+ println!(
+ "Concat API {}: JSON-RPC on {address}",
+ concat_api::API_VERSION
+ );
+ }
+ if let Some(path) = server.socket_path() {
+ println!(
+ "Concat API {}: JSON-RPC on {}",
+ concat_api::API_VERSION,
+ path.display()
+ );
+ }
+ if let Some(address) = server.grpc_addr() {
+ println!("Concat API {}: gRPC on {address}", concat_api::API_VERSION);
+ }
+ loop {
+ std::thread::park();
+ }
+}
+
+/// Where `serve` listens when not told: loopback, on a port nothing else
+/// is known to use.
+const DEFAULT_JSON: &str = "127.0.0.1:7420";
+
/// One frame of `input`, scaled to the card's size, through `effect` at its
/// defaults, as a JPEG at `output`.
fn preview(
diff --git a/src/crates/concat-server/Cargo.toml b/src/crates/concat-server/Cargo.toml
new file mode 100644
index 00000000..b46bb703
--- /dev/null
+++ b/src/crates/concat-server/Cargo.toml
@@ -0,0 +1,42 @@
+[package]
+name = "concat-server"
+version.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+license.workspace = true
+description = "The Concat API served on a socket: JSON-RPC lines over TCP or a Unix socket, and gRPC behind a feature. One dispatcher, any number of callers."
+
+[features]
+default = []
+# gRPC over HTTP/2 through tonic. Off by default: it brings tokio and
+# hyper, which nothing else in the workspace needs, and a JSON-RPC line is
+# enough for a script. Built and tested in CI so it does not rot.
+grpc = [
+ "dep:tonic",
+ "dep:tonic-prost",
+ "dep:prost",
+ "dep:tokio",
+ "dep:tokio-stream",
+ "dep:tonic-prost-build",
+ "dep:protox",
+]
+
+[dependencies]
+concat-api.workspace = true
+serde_json.workspace = true
+tonic = { version = "0.14", optional = true }
+tonic-prost = { version = "0.14", optional = true }
+prost = { version = "0.14", optional = true }
+tokio = { version = "1", features = ["rt-multi-thread", "sync", "net", "time", "macros"], optional = true }
+tokio-stream = { version = "0.1", optional = true }
+
+[build-dependencies]
+tonic-prost-build = { version = "0.14", optional = true }
+# A protoc written in Rust, so the build needs nothing installed.
+protox = { version = "0.9", optional = true }
+
+[dev-dependencies]
+tempfile = "3"
+
+[lints]
+workspace = true
diff --git a/src/crates/concat-server/build.rs b/src/crates/concat-server/build.rs
new file mode 100644
index 00000000..c94374a3
--- /dev/null
+++ b/src/crates/concat-server/build.rs
@@ -0,0 +1,18 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! Generates the gRPC service from `proto/concat.proto` when the `grpc`
+//! feature is on. protox compiles the proto in Rust, so nothing needs
+//! installing.
+
+fn main() {
+ #[cfg(feature = "grpc")]
+ {
+ let proto = "proto/concat.proto";
+ println!("cargo:rerun-if-changed={proto}");
+ let descriptors = protox::compile([proto], ["proto"]).expect("concat.proto compiles");
+ tonic_prost_build::configure()
+ .compile_fds(descriptors)
+ .expect("the gRPC service generates");
+ }
+}
diff --git a/src/crates/concat-server/proto/concat.proto b/src/crates/concat-server/proto/concat.proto
new file mode 100644
index 00000000..45abcaab
--- /dev/null
+++ b/src/crates/concat-server/proto/concat.proto
@@ -0,0 +1,54 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+// The Concat API over gRPC.
+//
+// This is an envelope, not a second contract. The methods, their params
+// and their replies are the API's own and travel as the JSON text the
+// line transport would carry, so a method added to the API reaches gRPC
+// with no change here, and a caller reads one set of docs. What gRPC adds
+// is HTTP/2, generated clients, and a streamed reply for events.
+syntax = "proto3";
+
+package concat.v1;
+
+service Concat {
+ // One call, one response.
+ rpc Call (Request) returns (Response);
+ // Every event from every job, for as long as the stream is open. Each
+ // names its job and its project.
+ rpc Events (EventsRequest) returns (stream Event);
+}
+
+message Request {
+ // The method, e.g. "edit.apply".
+ string method = 1;
+ // The params object as JSON text. Empty for a method that takes none.
+ string params = 2;
+}
+
+message Response {
+ oneof outcome {
+ // The reply as JSON text: the same object a JSON-RPC result holds.
+ string result = 1;
+ Error error = 2;
+ }
+}
+
+message Error {
+ // The API's code: "notOpen", "refused", "busy", ...
+ string code = 1;
+ // The same code as its JSON-RPC number.
+ int32 number = 2;
+ // The sentence a person would be shown.
+ string message = 3;
+}
+
+message EventsRequest {}
+
+message Event {
+ // The event, e.g. "export.progress".
+ string event = 1;
+ // Its fields as JSON text.
+ string params = 2;
+}
diff --git a/src/crates/concat-server/src/grpc.rs b/src/crates/concat-server/src/grpc.rs
new file mode 100644
index 00000000..ebeb7765
--- /dev/null
+++ b/src/crates/concat-server/src/grpc.rs
@@ -0,0 +1,283 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! gRPC over HTTP/2, through tonic.
+//!
+//! The service is two methods: `Call`, one request in and one response
+//! out, and `Events`, a stream of every job's events for as long as the
+//! caller keeps it open. Payloads are the API's JSON as text, so this is
+//! the line transport's contract in a protobuf envelope; `proto/concat.proto`
+//! says so at length.
+//!
+//! tonic needs tokio, and the rest of the workspace does not, so the
+//! runtime lives here: one, on its own thread, doing nothing but I/O. A
+//! call is handed to the [`Hub`] from a blocking task, the same way a
+//! JSON-RPC connection thread hands one over, and waits there.
+//!
+//! With a token, every call carries it as `authorization: Bearer ...`
+//! metadata; one without is `UNAUTHENTICATED`.
+
+use std::net::SocketAddr;
+use std::sync::Arc;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::thread::JoinHandle;
+use std::time::Duration;
+
+use concat_api::rpc::{Call, Message};
+use concat_api::{ApiError, Event, Response};
+use serde_json::{Value, json};
+use tokio_stream::wrappers::ReceiverStream;
+use tonic::{Request, Status};
+
+use crate::Hub;
+
+/// The generated messages and service.
+pub mod proto {
+ #![allow(missing_docs)]
+ tonic::include_proto!("concat.v1");
+}
+
+use proto::concat_server::{Concat, ConcatServer};
+
+/// The service: the hub, and nothing else.
+struct Service {
+ hub: Hub,
+}
+
+#[tonic::async_trait]
+impl Concat for Service {
+ async fn call(
+ &self,
+ request: Request<proto::Request>,
+ ) -> Result<tonic::Response<proto::Response>, Status> {
+ let proto::Request { method, params } = request.into_inner();
+ let hub = self.hub.clone();
+ let response = tokio::task::spawn_blocking(move || match parse(&method, &params) {
+ Ok(call) => hub.call(call.request),
+ Err(error) => Response::Error(error),
+ })
+ .await
+ .map_err(|error| Status::internal(error.to_string()))?;
+ Ok(tonic::Response::new(encode(response)))
+ }
+
+ type EventsStream = ReceiverStream<Result<proto::Event, Status>>;
+
+ async fn events(
+ &self,
+ _request: Request<proto::EventsRequest>,
+ ) -> Result<tonic::Response<Self::EventsStream>, Status> {
+ let (sender, receiver) = tokio::sync::mpsc::channel(64);
+ // Called on the job's thread, where blocking is fine; a send that
+ // fails is a caller that hung up.
+ self.hub.subscribe(Box::new(move |event: &Event| {
+ sender.blocking_send(Ok(encode_event(event))).is_ok()
+ }));
+ Ok(tonic::Response::new(ReceiverStream::new(receiver)))
+ }
+}
+
+/// The request the method and params text name, by way of the JSON-RPC
+/// parser so the two transports refuse the same things the same way.
+fn parse(method: &str, params: &str) -> Result<Call, ApiError> {
+ let params: Value = if params.trim().is_empty() {
+ Value::Null
+ } else {
+ serde_json::from_str(params)
+ .map_err(|error| ApiError::invalid(format!("params is not JSON: {error}")))?
+ };
+ let line = json!({ "jsonrpc": "2.0", "method": method, "params": params }).to_string();
+ Call::parse(&line).map_err(|(_, error)| error)
+}
+
+fn encode(response: Response) -> proto::Response {
+ use proto::response::Outcome;
+ let outcome = match response {
+ Response::Result(reply) => {
+ Outcome::Result(serde_json::to_string(&reply).unwrap_or_else(|_| "{}".to_owned()))
+ }
+ Response::Error(error) => Outcome::Error(proto::Error {
+ code: serde_json::to_value(error.code)
+ .ok()
+ .and_then(|code| code.as_str().map(str::to_owned))
+ .unwrap_or_default(),
+ number: error.code.number() as i32,
+ message: error.message,
+ }),
+ };
+ proto::Response {
+ outcome: Some(outcome),
+ }
+}
+
+fn encode_event(event: &Event) -> proto::Event {
+ // The notification's method and params, exactly as the line transport
+ // would write them.
+ let notification = Message::Event(event.clone()).to_value();
+ proto::Event {
+ event: notification["method"]
+ .as_str()
+ .unwrap_or_default()
+ .to_owned(),
+ params: notification["params"].to_string(),
+ }
+}
+
+/// Serves gRPC on `address` until `stop` is set. Returns the address
+/// bound, port resolved, and the runtime's thread.
+pub(crate) fn serve(
+ address: SocketAddr,
+ hub: Hub,
+ token: Option<String>,
+ stop: Arc<AtomicBool>,
+) -> Result<(SocketAddr, JoinHandle<()>), String> {
+ let could_not =
+ |error: &dyn std::fmt::Display| format!("could not listen on {address}: {error}");
+ let listener = std::net::TcpListener::bind(address).map_err(|error| could_not(&error))?;
+ listener
+ .set_nonblocking(true)
+ .map_err(|error| could_not(&error))?;
+ let bound = listener.local_addr().map_err(|error| could_not(&error))?;
+
+ let runtime = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .thread_name("concat grpc")
+ .enable_all()
+ .build()
+ .map_err(|error| format!("could not start the gRPC runtime: {error}"))?;
+
+ // Everything the runtime runs, it runs from its own thread: a block_on
+ // from a caller that is itself inside a runtime - a test, an embedder
+ // with one of its own - would panic.
+ let thread = std::thread::Builder::new()
+ .name("concat grpc".to_owned())
+ .spawn(move || {
+ runtime.block_on(async move {
+ let Ok(listener) = tokio::net::TcpListener::from_std(listener) else {
+ return;
+ };
+ let incoming = tokio_stream::wrappers::TcpListenerStream::new(listener);
+ let service = ConcatServer::with_interceptor(Service { hub }, bearer(token));
+ let stopped = async move {
+ while !stop.load(Ordering::SeqCst) {
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ };
+ let _ = tonic::transport::Server::builder()
+ .add_service(service)
+ .serve_with_incoming_shutdown(incoming, stopped)
+ .await;
+ });
+ })
+ .map_err(|error| format!("could not start the gRPC thread: {error}"))?;
+ Ok((bound, thread))
+}
+
+/// The check every call passes through: the token as a bearer, when
+/// there is one.
+fn bearer(token: Option<String>) -> impl Fn(Request<()>) -> Result<Request<()>, Status> + Clone {
+ let expected = token.map(|token| format!("Bearer {token}"));
+ move |request: Request<()>| match &expected {
+ None => Ok(request),
+ Some(expected) => {
+ let presented = request
+ .metadata()
+ .get("authorization")
+ .and_then(|value| value.to_str().ok());
+ if presented == Some(expected.as_str()) {
+ Ok(request)
+ } else {
+ Err(Status::unauthenticated("the token is missing or wrong"))
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::{Config, Server};
+ use concat_api::{Api, AppDirs};
+ use proto::concat_client::ConcatClient;
+
+ fn server(token: Option<&str>) -> (Server, tempfile::TempDir) {
+ let scratch = tempfile::tempdir().expect("scratch");
+ let dirs = AppDirs {
+ config: scratch.path().join("config"),
+ data: scratch.path().join("data"),
+ };
+ let config = Config {
+ grpc: Some("127.0.0.1:0".parse().expect("an address")),
+ token: token.map(str::to_owned),
+ ..Config::default()
+ };
+ let server =
+ Server::start(config, move |events| Ok(Api::with_dirs(dirs, events))).expect("starts");
+ (server, scratch)
+ }
+
+ #[tokio::test]
+ async fn a_call_answers_in_json_text_and_an_error_carries_its_code() {
+ let (server, _scratch) = server(None);
+ let address = server.grpc_addr().expect("listening");
+ let mut client = ConcatClient::connect(format!("http://{address}"))
+ .await
+ .expect("connects");
+ let version = client
+ .call(proto::Request {
+ method: "version".to_owned(),
+ params: String::new(),
+ })
+ .await
+ .expect("answers")
+ .into_inner();
+ let Some(proto::response::Outcome::Result(text)) = version.outcome else {
+ panic!("not a result: {version:?}");
+ };
+ let value: Value = serde_json::from_str(&text).expect("JSON");
+ assert_eq!(value["apiVersion"], concat_api::API_VERSION);
+
+ let refused = client
+ .call(proto::Request {
+ method: "project.get".to_owned(),
+ params: r#"{"path":"/none"}"#.to_owned(),
+ })
+ .await
+ .expect("answers")
+ .into_inner();
+ let Some(proto::response::Outcome::Error(error)) = refused.outcome else {
+ panic!("not an error: {refused:?}");
+ };
+ assert_eq!((error.code.as_str(), error.number), ("notOpen", -32001));
+ drop(client);
+ tokio::task::spawn_blocking(move || server.stop())
+ .await
+ .expect("stops");
+ }
+
+ #[tokio::test]
+ async fn a_token_travels_as_a_bearer() {
+ let (server, _scratch) = server(Some("open sesame"));
+ let address = server.grpc_addr().expect("listening");
+ let mut client = ConcatClient::connect(format!("http://{address}"))
+ .await
+ .expect("connects");
+ let version = || proto::Request {
+ method: "version".to_owned(),
+ params: String::new(),
+ };
+ let refused = client.call(version()).await.expect_err("no token");
+ assert_eq!(refused.code(), tonic::Code::Unauthenticated);
+
+ let mut request = Request::new(version());
+ request.metadata_mut().insert(
+ "authorization",
+ "Bearer open sesame".parse().expect("a value"),
+ );
+ assert!(client.call(request).await.is_ok());
+ drop(client);
+ tokio::task::spawn_blocking(move || server.stop())
+ .await
+ .expect("stops");
+ }
+}
diff --git a/src/crates/concat-server/src/hub.rs b/src/crates/concat-server/src/hub.rs
new file mode 100644
index 00000000..ddd0fcbd
--- /dev/null
+++ b/src/crates/concat-server/src/hub.rs
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! The one API, and the queue every caller stands in.
+//!
+//! [`Api`] is not thread-safe, and this is where that is honoured: it
+//! lives on one thread, made there and dropped there, and a [`Hub::call`]
+//! from any other thread is a message to it and a wait for the answer. A
+//! transport thread blocks in `call` for as long as the method takes,
+//! which is what it would do anyway; the long ones are jobs and return at
+//! once.
+//!
+//! Events leave the other way. The API's sink is a fan-out over every
+//! [`Subscriber`] a transport registered, called on the job's thread; a
+//! subscriber that can no longer deliver says so by returning false and is
+//! forgotten.
+
+use std::sync::mpsc::{self, Sender};
+use std::sync::{Arc, Mutex};
+use std::thread::JoinHandle;
+
+use concat_api::{Api, ApiError, ErrorCode, Event, EventSink, Request, Response};
+
+/// A way to hand an event to one caller. Returns false once the caller is
+/// gone, after which it is dropped.
+pub type Subscriber = Box<dyn Fn(&Event) -> bool + Send>;
+
+/// One call waiting its turn.
+struct Task {
+ request: Request,
+ respond: Box<dyn FnOnce(Response) + Send>,
+}
+
+/// The API's front door, shared by every transport. Cheap to clone.
+#[derive(Clone)]
+pub struct Hub {
+ tasks: Arc<Mutex<Option<Sender<Task>>>>,
+ subscribers: Arc<Mutex<Vec<Subscriber>>>,
+}
+
+impl Hub {
+ /// Starts the API's thread. `make` runs on it, given the sink; if it
+ /// fails, so does this.
+ pub(crate) fn start(
+ make: impl FnOnce(EventSink) -> Result<Api, String> + Send + 'static,
+ ) -> Result<(Hub, JoinHandle<()>), String> {
+ let (tasks, queue) = mpsc::channel::<Task>();
+ let subscribers: Arc<Mutex<Vec<Subscriber>>> = Arc::new(Mutex::new(Vec::new()));
+ let sink: EventSink = {
+ let subscribers = Arc::clone(&subscribers);
+ Arc::new(move |event: Event| {
+ if let Ok(mut subscribers) = subscribers.lock() {
+ subscribers.retain(|subscriber| subscriber(&event));
+ }
+ })
+ };
+ let (made, ready) = mpsc::channel::<Result<(), String>>();
+ let thread = std::thread::Builder::new()
+ .name("concat api".to_owned())
+ .spawn(move || {
+ let mut api = match make(sink) {
+ Ok(api) => {
+ let _ = made.send(Ok(()));
+ api
+ }
+ Err(error) => {
+ let _ = made.send(Err(error));
+ return;
+ }
+ };
+ for task in queue {
+ let response = api.dispatch(task.request);
+ (task.respond)(response);
+ }
+ api.finish();
+ })
+ .map_err(|error| format!("could not start the API's thread: {error}"))?;
+ ready
+ .recv()
+ .unwrap_or_else(|_| Err("the API's thread ended before it began".to_owned()))?;
+ Ok((
+ Hub {
+ tasks: Arc::new(Mutex::new(Some(tasks))),
+ subscribers,
+ },
+ thread,
+ ))
+ }
+
+ /// Runs one request on the API's thread and waits for its response.
+ pub fn call(&self, request: Request) -> Response {
+ let gone = || {
+ Response::Error(ApiError::new(
+ ErrorCode::Failed,
+ "the server is shutting down",
+ ))
+ };
+ let (answer, wait) = mpsc::channel::<Response>();
+ let task = Task {
+ request,
+ respond: Box::new(move |response| {
+ let _ = answer.send(response);
+ }),
+ };
+ let sent = match self.tasks.lock() {
+ Ok(tasks) => tasks.as_ref().is_some_and(|tasks| tasks.send(task).is_ok()),
+ Err(_) => false,
+ };
+ if !sent {
+ return gone();
+ }
+ wait.recv().unwrap_or_else(|_| gone())
+ }
+
+ /// Registers a way to hand events to one caller.
+ pub fn subscribe(&self, subscriber: Subscriber) {
+ if let Ok(mut subscribers) = self.subscribers.lock() {
+ subscribers.push(subscriber);
+ }
+ }
+
+ /// How many callers are receiving events.
+ pub fn subscribers(&self) -> usize {
+ self.subscribers.lock().map(|list| list.len()).unwrap_or(0)
+ }
+
+ /// Ends the queue. Calls after this are refused, and the API's thread
+ /// finishes its jobs and returns.
+ pub(crate) fn close(&self) {
+ if let Ok(mut tasks) = self.tasks.lock() {
+ tasks.take();
+ }
+ }
+}
diff --git a/src/crates/concat-server/src/json.rs b/src/crates/concat-server/src/json.rs
new file mode 100644
index 00000000..40deb8da
--- /dev/null
+++ b/src/crates/concat-server/src/json.rs
@@ -0,0 +1,320 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! JSON-RPC lines on a socket: the stdin transport, for several callers at
+//! once.
+//!
+//! A connection is two threads: one reads lines and answers each through
+//! the [`Hub`], one writes whatever is put in the connection's outbox -
+//! responses and events alike - so a job's event from another thread never
+//! interleaves with a response half-written. The wire is exactly what
+//! `concat-cli api` reads and writes; see `concat_api::rpc`.
+//!
+//! When the server has a token, a connection's first line must be
+//! `{"jsonrpc": "2.0", "id": 1, "method": "auth", "params": {"token":
+//! "..."}}`. Anything else first is answered with an `unauthorized` error
+//! and the connection is closed. `auth` is the transport's word, not the
+//! API's: it never reaches the hub.
+
+use std::io::{BufRead, BufReader, Write};
+use std::net::TcpListener;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::mpsc::{self, Sender};
+use std::sync::{Arc, Mutex};
+use std::thread::JoinHandle;
+
+use concat_api::rpc::{Call, Id, Message};
+use concat_api::{ApiError, Done, ErrorCode, Reply, Response};
+use serde_json::Value;
+
+use crate::{Connections, Hub};
+
+/// Accepts JSON-RPC connections on `listener` until `stop` is set.
+pub(crate) fn serve_tcp(
+ listener: TcpListener,
+ hub: Hub,
+ token: Option<String>,
+ stop: Arc<AtomicBool>,
+ connections: Connections,
+) -> JoinHandle<()> {
+ std::thread::spawn(move || {
+ for stream in listener.incoming() {
+ if stop.load(Ordering::SeqCst) {
+ break;
+ }
+ let Ok(stream) = stream else { continue };
+ let _ = stream.set_nodelay(true);
+ let Ok(reader) = stream.try_clone() else {
+ continue;
+ };
+ let Ok(closer) = stream.try_clone() else {
+ continue;
+ };
+ let Ok(ender) = stream.try_clone() else {
+ continue;
+ };
+ if let Ok(mut connections) = connections.lock() {
+ connections.push(Box::new(move || {
+ let _ = closer.shutdown(std::net::Shutdown::Both);
+ }));
+ }
+ let hub = hub.clone();
+ let token = token.clone();
+ std::thread::spawn(move || {
+ connection(BufReader::new(reader), stream, hub, token);
+ // The registry above still holds a handle, so the socket is
+ // shut here rather than merely dropped: the caller sees EOF.
+ let _ = ender.shutdown(std::net::Shutdown::Both);
+ });
+ }
+ })
+}
+
+/// Accepts JSON-RPC connections on a Unix socket until `stop` is set.
+#[cfg(unix)]
+pub(crate) fn serve_unix(
+ listener: std::os::unix::net::UnixListener,
+ hub: Hub,
+ token: Option<String>,
+ stop: Arc<AtomicBool>,
+ connections: Connections,
+) -> JoinHandle<()> {
+ std::thread::spawn(move || {
+ for stream in listener.incoming() {
+ if stop.load(Ordering::SeqCst) {
+ break;
+ }
+ let Ok(stream) = stream else { continue };
+ let Ok(reader) = stream.try_clone() else {
+ continue;
+ };
+ let Ok(closer) = stream.try_clone() else {
+ continue;
+ };
+ let Ok(ender) = stream.try_clone() else {
+ continue;
+ };
+ if let Ok(mut connections) = connections.lock() {
+ connections.push(Box::new(move || {
+ let _ = closer.shutdown(std::net::Shutdown::Both);
+ }));
+ }
+ let hub = hub.clone();
+ let token = token.clone();
+ std::thread::spawn(move || {
+ connection(BufReader::new(reader), stream, hub, token);
+ // The registry above still holds a handle, so the socket is
+ // shut here rather than merely dropped: the caller sees EOF.
+ let _ = ender.shutdown(std::net::Shutdown::Both);
+ });
+ }
+ })
+}
+
+/// One caller, start to end: the handshake, then a call per line.
+fn connection(
+ reader: impl BufRead,
+ writer: impl Write + Send + 'static,
+ hub: Hub,
+ token: Option<String>,
+) {
+ let outbox = Outbox::start(writer);
+ let mut lines = reader.lines().map_while(Result::ok);
+
+ if let Some(token) = token {
+ let Some(first) = lines.find(|line| !line.trim().is_empty()) else {
+ outbox.close();
+ return;
+ };
+ let (id, outcome) = handshake(&first, &token);
+ let ok = outcome.is_ok();
+ outbox.send(Message::Reply {
+ id,
+ response: outcome.into(),
+ });
+ if !ok {
+ outbox.close();
+ return;
+ }
+ }
+
+ // Events reach this caller from here on: the outbox is shared with the
+ // hub's fan-out, which drops it once a send fails.
+ let events = outbox.clone();
+ hub.subscribe(Box::new(move |event| {
+ events.send(Message::Event(event.clone()))
+ }));
+
+ for line in lines {
+ if line.trim().is_empty() {
+ continue;
+ }
+ let (id, response) = match Call::parse(&line) {
+ Ok(call) => (call.id, hub.call(call.request)),
+ Err((id, error)) => (id, Response::Error(error)),
+ };
+ if !outbox.send(Message::Reply { id, response }) {
+ break;
+ }
+ }
+ outbox.close();
+}
+
+/// Reads the first line as the `auth` call and checks its token.
+fn handshake(line: &str, token: &str) -> (Option<Id>, Result<Reply, ApiError>) {
+ let refuse = |id: Option<Id>, why: &str| {
+ (
+ id,
+ Err(ApiError::new(ErrorCode::Unauthorized, why.to_owned())),
+ )
+ };
+ let Ok(Value::Object(mut object)) = serde_json::from_str::<Value>(line) else {
+ return refuse(None, "the first line is the auth call");
+ };
+ let id = object.remove("id");
+ if object.get("method").and_then(Value::as_str) != Some("auth") {
+ return refuse(id, "the first line is the auth call");
+ }
+ let presented = object
+ .get("params")
+ .and_then(|params| params.get("token"))
+ .or_else(|| object.get("token"))
+ .and_then(Value::as_str);
+ if presented == Some(token) {
+ (id, Ok(Reply::Done(Done {})))
+ } else {
+ refuse(id, "wrong token")
+ }
+}
+
+/// The connection's one writer: a queue and the thread that drains it.
+#[derive(Clone)]
+struct Outbox {
+ queue: Arc<Mutex<Option<Sender<Message>>>>,
+ writer: Arc<Mutex<Option<JoinHandle<()>>>>,
+}
+
+impl Outbox {
+ fn start(mut writer: impl Write + Send + 'static) -> Outbox {
+ let (queue, messages) = mpsc::channel::<Message>();
+ let thread = std::thread::spawn(move || {
+ for message in messages {
+ if writeln!(writer, "{}", message.to_json()).is_err() || writer.flush().is_err() {
+ break;
+ }
+ }
+ });
+ Outbox {
+ queue: Arc::new(Mutex::new(Some(queue))),
+ writer: Arc::new(Mutex::new(Some(thread))),
+ }
+ }
+
+ /// Queues one line. False once the caller is gone.
+ fn send(&self, message: Message) -> bool {
+ match self.queue.lock() {
+ Ok(queue) => queue
+ .as_ref()
+ .is_some_and(|queue| queue.send(message).is_ok()),
+ Err(_) => false,
+ }
+ }
+
+ /// Ends the queue and waits for the writer to finish what is left, so
+ /// the last reply is on the wire when this returns. The fan-out forgets
+ /// this caller at its next event.
+ fn close(&self) {
+ if let Ok(mut queue) = self.queue.lock() {
+ queue.take();
+ }
+ let thread = self.writer.lock().ok().and_then(|mut writer| writer.take());
+ if let Some(thread) = thread {
+ let _ = thread.join();
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::tests::server;
+ use std::net::TcpStream;
+
+ /// A client on `server`: a line in, a line out.
+ struct Client {
+ reader: BufReader<TcpStream>,
+ writer: TcpStream,
+ }
+
+ impl Client {
+ fn connect(server: &crate::Server) -> Client {
+ let stream =
+ TcpStream::connect(server.json_addr().expect("listening")).expect("connects");
+ Client {
+ reader: BufReader::new(stream.try_clone().expect("clone")),
+ writer: stream,
+ }
+ }
+
+ fn ask(&mut self, line: &str) -> Value {
+ writeln!(self.writer, "{line}").expect("writes");
+ let mut reply = String::new();
+ self.reader.read_line(&mut reply).expect("reads");
+ serde_json::from_str(&reply).expect("a JSON line")
+ }
+ }
+
+ #[test]
+ fn a_call_over_tcp_is_answered_with_its_id() {
+ let (server, _scratch) = server(None);
+ let mut client = Client::connect(&server);
+ let reply = client.ask(r#"{"jsonrpc":"2.0","id":41,"method":"version"}"#);
+ assert_eq!(reply["id"], 41);
+ assert_eq!(reply["result"]["apiVersion"], concat_api::API_VERSION);
+ let refused = client
+ .ask(r#"{"jsonrpc":"2.0","id":42,"method":"project.get","params":{"path":"/none"}}"#);
+ assert_eq!(refused["error"]["data"]["code"], "notOpen");
+ server.stop();
+ }
+
+ #[test]
+ fn two_callers_share_one_api() {
+ let (server, scratch) = server(None);
+ let location = scratch.path().to_string_lossy().into_owned();
+ let mut first = Client::connect(&server);
+ let mut second = Client::connect(&server);
+ let created = first.ask(&format!(
+ r#"{{"jsonrpc":"2.0","id":1,"method":"project.create","params":{{"location":"{location}","name":"Shared"}}}}"#
+ ));
+ assert!(created["result"]["project"].is_object(), "{created}");
+ let seen = second.ask(&format!(
+ r#"{{"jsonrpc":"2.0","id":2,"method":"project.get","params":{{"path":"{location}/Shared"}}}}"#
+ ));
+ assert!(seen["result"]["project"].is_object(), "{seen}");
+ assert_eq!(server.connections(), 2);
+ server.stop();
+ }
+
+ #[test]
+ fn a_token_is_presented_first_or_the_connection_ends() {
+ let (server, _scratch) = server(Some("open sesame"));
+ let mut wrong = Client::connect(&server);
+ let refused = wrong.ask(r#"{"jsonrpc":"2.0","id":1,"method":"version"}"#);
+ assert_eq!(refused["error"]["data"]["code"], "unauthorized");
+ let mut after = String::new();
+ assert_eq!(
+ wrong.reader.read_line(&mut after).expect("eof"),
+ 0,
+ "closed"
+ );
+
+ let mut right = Client::connect(&server);
+ let welcomed = right
+ .ask(r#"{"jsonrpc":"2.0","id":1,"method":"auth","params":{"token":"open sesame"}}"#);
+ assert_eq!(welcomed["result"], serde_json::json!({}));
+ let reply = right.ask(r#"{"jsonrpc":"2.0","id":2,"method":"version"}"#);
+ assert_eq!(reply["id"], 2);
+ assert_eq!(server.connections(), 1);
+ server.stop();
+ }
+}
diff --git a/src/crates/concat-server/src/lib.rs b/src/crates/concat-server/src/lib.rs
new file mode 100644
index 00000000..d9fe2f15
--- /dev/null
+++ b/src/crates/concat-server/src/lib.rs
@@ -0,0 +1,290 @@
+// SPDX-License-Identifier: AGPL-3.0-or-later
+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors
+
+//! The Concat API on a socket, for a caller that is another process: a
+//! script, an editor plugin, a service on the same machine.
+//!
+//! One [`Hub`] owns the one [`Api`] on a thread of its own and serialises
+//! every caller through it, the way the window's event loop does; the
+//! transports are threads that read a call, hand it to the hub, and write
+//! the response back. Two transports speak the same API:
+//!
+//! - **JSON-RPC lines** over TCP or a Unix socket: the stdin transport's
+//! protocol, one JSON object a line, so what works in a pipe works on a
+//! socket unchanged. [`json`] is the whole of it.
+//! - **gRPC** over HTTP/2, behind the `grpc` feature: the same methods and
+//! the same JSON payloads inside a thin protobuf envelope, for a caller
+//! that wants generated clients and a streamed reply. [`grpc`] says how.
+//!
+//! Events - an export's progress, how it ended - go to every connected
+//! caller; each names its job and its project, so a caller keeps the ones
+//! it asked for.
+//!
+//! The API reads and writes whatever paths it is given, so a server is a
+//! door into the machine. It binds loopback unless told otherwise, and it
+//! refuses to bind anything else without a token every connection must
+//! present before its first call. There is no encryption: a bind off
+//! loopback belongs behind something that provides it.
+
+mod hub;
+pub mod json;
+
+#[cfg(feature = "grpc")]
+pub mod grpc;
+
+use std::net::{SocketAddr, TcpListener, TcpStream};
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+use std::thread::JoinHandle;
+
+use concat_api::{Api, EventSink};
+
+pub use hub::{Hub, Subscriber};
+
+/// Where to listen, and who may connect.
+#[derive(Clone, Debug, Default)]
+pub struct Config {
+ /// A TCP address for JSON-RPC lines.
+ pub json: Option<SocketAddr>,
+ /// A Unix socket path for JSON-RPC lines. Unix only; a file already
+ /// there is replaced.
+ pub socket: Option<PathBuf>,
+ /// A TCP address for gRPC. Needs the `grpc` feature.
+ pub grpc: Option<SocketAddr>,
+ /// What a connection presents before its first call. Required for
+ /// any address that is not loopback.
+ pub token: Option<String>,
+}
+
+impl Config {
+ /// Refuses a configuration that would open the machine: a TCP bind
+ /// off loopback with no token.
+ pub fn check(&self) -> Result<(), String> {
+ for (what, address) in [("JSON-RPC", self.json), ("gRPC", self.grpc)] {
+ if let Some(address) = address
+ && !address.ip().is_loopback()
+ && self.token.as_deref().is_none_or(str::is_empty)
+ {
+ return Err(format!(
+ "{what} on {address} is reachable from other machines: set a token, or bind 127.0.0.1"
+ ));
+ }
+ }
+ #[cfg(not(unix))]
+ if self.socket.is_some() {
+ return Err("a Unix socket needs a Unix".to_owned());
+ }
+ #[cfg(not(feature = "grpc"))]
+ if self.grpc.is_some() {
+ return Err(
+ "this build has no gRPC: build concat-server with --features grpc".to_owned(),
+ );
+ }
+ Ok(())
+ }
+}
+
+/// A running server: its listeners and the hub behind them.
+pub struct Server {
+ hub: Hub,
+ dispatcher: Option<JoinHandle<()>>,
+ json: Option<SocketAddr>,
+ socket: Option<PathBuf>,
+ grpc: Option<SocketAddr>,
+ stop: Arc<AtomicBool>,
+ listeners: Vec<JoinHandle<()>>,
+ connections: Connections,
+}
+
+/// Every open connection's way of being closed, so a stop reaches the
+/// threads blocked reading them.
+pub(crate) type Connections = Arc<Mutex<Vec<Box<dyn Fn() + Send>>>>;
+
+impl Server {
+ /// Binds every address in `config` and starts serving. `make` builds
+ /// the API on the hub's thread, given the sink its jobs report through.
+ pub fn start(
+ config: Config,
+ make: impl FnOnce(EventSink) -> Result<Api, String> + Send + 'static,
+ ) -> Result<Server, String> {
+ config.check()?;
+ let (hub, dispatcher) = Hub::start(make)?;
+ let stop = Arc::new(AtomicBool::new(false));
+ let connections: Connections = Arc::new(Mutex::new(Vec::new()));
+ let mut server = Server {
+ hub,
+ dispatcher: Some(dispatcher),
+ json: None,
+ socket: None,
+ grpc: None,
+ stop: Arc::clone(&stop),
+ listeners: Vec::new(),
+ connections: Arc::clone(&connections),
+ };
+ let token = config.token.filter(|token| !token.is_empty());
+
+ if let Some(address) = config.json {
+ let listener = TcpListener::bind(address)
+ .map_err(|error| format!("could not listen on {address}: {error}"))?;
+ server.json = Some(
+ listener
+ .local_addr()
+ .map_err(|error| format!("could not listen on {address}: {error}"))?,
+ );
+ server.listeners.push(json::serve_tcp(
+ listener,
+ server.hub.clone(),
+ token.clone(),
+ Arc::clone(&stop),
+ Arc::clone(&connections),
+ ));
+ }
+
+ #[cfg(unix)]
+ if let Some(path) = config.socket {
+ let _ = std::fs::remove_file(&path);
+ let listener = std::os::unix::net::UnixListener::bind(&path)
+ .map_err(|error| format!("could not listen on {}: {error}", path.display()))?;
+ server.listeners.push(json::serve_unix(
+ listener,
+ server.hub.clone(),
+ token.clone(),
+ Arc::clone(&stop),
+ Arc::clone(&connections),
+ ));
+ server.socket = Some(path);
+ }
+
+ #[cfg(feature = "grpc")]
+ if let Some(address) = config.grpc {
+ let (bound, thread) =
+ grpc::serve(address, server.hub.clone(), token, Arc::clone(&stop))?;
+ server.grpc = Some(bound);
+ server.listeners.push(thread);
+ }
+
+ Ok(server)
+ }
+
+ /// The hub, for an embedder that calls the API from the same process.
+ pub fn hub(&self) -> &Hub {
+ &self.hub
+ }
+
+ /// The JSON-RPC address bound, port resolved.
+ pub fn json_addr(&self) -> Option<SocketAddr> {
+ self.json
+ }
+
+ /// The Unix socket path listened on.
+ pub fn socket_path(&self) -> Option<&PathBuf> {
+ self.socket.as_ref()
+ }
+
+ /// The gRPC address bound, port resolved.
+ pub fn grpc_addr(&self) -> Option<SocketAddr> {
+ self.grpc
+ }
+
+ /// How many callers are connected.
+ pub fn connections(&self) -> usize {
+ self.hub.subscribers()
+ }
+
+ /// Closes every listener and connection, waits for the jobs still
+ /// running, and returns when the API's thread has ended.
+ pub fn stop(mut self) {
+ self.shut();
+ }
+
+ fn shut(&mut self) {
+ self.stop.store(true, Ordering::SeqCst);
+ // A blocked accept wakes for a connection; make one.
+ if let Some(address) = self.json {
+ let _ = TcpStream::connect(address);
+ }
+ #[cfg(unix)]
+ if let Some(path) = &self.socket {
+ let _ = std::os::unix::net::UnixStream::connect(path);
+ }
+ #[cfg(feature = "grpc")]
+ if let Some(address) = self.grpc {
+ let _ = TcpStream::connect(address);
+ }
+ for thread in self.listeners.drain(..) {
+ let _ = thread.join();
+ }
+ if let Ok(mut connections) = self.connections.lock() {
+ for close in connections.drain(..) {
+ close();
+ }
+ }
+ #[cfg(unix)]
+ if let Some(path) = self.socket.take() {
+ let _ = std::fs::remove_file(path);
+ }
+ self.hub.close();
+ if let Some(dispatcher) = self.dispatcher.take() {
+ let _ = dispatcher.join();
+ }
+ }
+}
+
+impl Drop for Server {
+ fn drop(&mut self) {
+ if self.dispatcher.is_some() {
+ self.shut();
+ }
+ }
+}
+
+#[cfg(test)]
+pub(crate) mod tests {
+ use super::*;
+ use concat_api::AppDirs;
+
+ /// A server over a scratch home, on loopback, on any free port.
+ pub(crate) fn server(token: Option<&str>) -> (Server, tempfile::TempDir) {
+ let scratch = tempfile::tempdir().expect("scratch");
+ let dirs = AppDirs {
+ config: scratch.path().join("config"),
+ data: scratch.path().join("data"),
+ };
+ let config = Config {
+ json: Some("127.0.0.1:0".parse().expect("an address")),
+ token: token.map(str::to_owned),
+ ..Config::default()
+ };
+ let server =
+ Server::start(config, move |events| Ok(Api::with_dirs(dirs, events))).expect("starts");
+ (server, scratch)
+ }
+
+ #[test]
+ fn a_bind_off_loopback_needs_a_token() {
+ let open = Config {
+ json: Some("0.0.0.0:0".parse().expect("an address")),
+ ..Config::default()
+ };
+ assert!(open.check().is_err());
+ let closed = Config {
+ token: Some("s".to_owned()),
+ ..open.clone()
+ };
+ assert!(closed.check().is_ok());
+ let local = Config {
+ json: Some("127.0.0.1:0".parse().expect("an address")),
+ ..Config::default()
+ };
+ assert!(local.check().is_ok());
+ }
+
+ #[test]
+ fn a_server_stops_cleanly_with_nobody_connected() {
+ let (server, _scratch) = server(None);
+ assert!(server.json_addr().is_some());
+ assert_eq!(server.connections(), 0);
+ server.stop();
+ }
+}