From 821f9d32e2d2c51375eba2d8fca66c423d6671a5 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sat, 18 Jul 2026 18:37:02 +0100 Subject: [PATCH] Make Brokkr editor commands multiprocess safe --- brokkr-command/Brokkr.Command.csproj | 16 ++ brokkr-command/Program.cs | 94 +++++++++++ brokkr-contracts/Brokkr.Contracts.csproj | 16 ++ brokkr-daemon/src/main.rs | 155 +----------------- docs/provider-contract.md | 8 +- .../Editor/BrokkrCultMeshMirror.cs | 14 +- .../Editor/BrokkrEditorDaemonBridge.cs | 7 +- .../Runtime/BrokkrHostSnapshot.cs | 2 +- surfaces/unity/README.md | 6 +- 9 files changed, 152 insertions(+), 166 deletions(-) create mode 100644 brokkr-command/Brokkr.Command.csproj create mode 100644 brokkr-command/Program.cs create mode 100644 brokkr-contracts/Brokkr.Contracts.csproj diff --git a/brokkr-command/Brokkr.Command.csproj b/brokkr-command/Brokkr.Command.csproj new file mode 100644 index 0000000..d6bd71e --- /dev/null +++ b/brokkr-command/Brokkr.Command.csproj @@ -0,0 +1,16 @@ + + + Exe + net10.0 + enable + enable + ..\..\CultLib-codex-cultmesh-reliability + + + + + + + + + diff --git a/brokkr-command/Program.cs b/brokkr-command/Program.cs new file mode 100644 index 0000000..e35ed76 --- /dev/null +++ b/brokkr-command/Program.cs @@ -0,0 +1,94 @@ +using GameCult.Brokkr; +using GameCult.Caching; +using GameCult.Caching.MessagePack; + +var options = Options.Parse(args); +using var cache = await CultCacheMessagePack.OpenAsync(options.CachePath, new CultCacheOpenOptions +{ + UseDirectoryStore = true +}); +var command = new BrokkrUnityCommand +{ + commandId = options.CommandId, + action = options.Action, + value = options.Value, + viewKind = options.ViewKind, + outputPath = options.OutputPath, + width = options.Width, + height = options.Height +}; +var commandKey = new CultRecordKey($"unity/commands/{command.commandId}"); +await cache.AddAsync(command, new CultRecordHandle(commandKey)); +await cache.FlushAsync(); + +if (options.WaitMilliseconds <= 0) +{ + Console.WriteLine(command.commandId); + return; +} + +var receiptKey = new CultRecordKey($"unity/receipts/{command.commandId}"); +var deadline = DateTimeOffset.UtcNow.AddMilliseconds(options.WaitMilliseconds); +while (DateTimeOffset.UtcNow < deadline) +{ + await Task.Delay(100); + await cache.PullAllBackingStoresAsync(); + if (!cache.TryGet(receiptKey, out BrokkrUnityCommandReceipt? receipt) || receipt == null) + { + continue; + } + + Console.WriteLine($"{receipt.status}: {receipt.message}"); + if (!string.IsNullOrWhiteSpace(receipt.objectId)) + { + Console.WriteLine(receipt.objectId); + } + Environment.ExitCode = string.Equals(receipt.status, "accepted", StringComparison.Ordinal) ? 0 : 1; + return; +} + +throw new TimeoutException($"Timed out waiting for Brokkr receipt '{receiptKey.Value}'."); + +internal sealed record Options( + string CachePath, + string Action, + string Value, + string ViewKind, + string OutputPath, + int Width, + int Height, + string CommandId, + int WaitMilliseconds) +{ + internal static Options Parse(string[] args) + { + var values = new Dictionary(StringComparer.Ordinal); + for (var index = 0; index < args.Length; index += 2) + { + if (index + 1 >= args.Length || !args[index].StartsWith("--", StringComparison.Ordinal)) + { + throw new ArgumentException("Arguments must be --name value pairs."); + } + values[args[index]] = args[index + 1]; + } + + string Required(string name) => values.TryGetValue(name, out var value) && !string.IsNullOrWhiteSpace(value) + ? value + : throw new ArgumentException($"{name} is required."); + string Optional(string name) => values.TryGetValue(name, out var value) ? value : ""; + int Integer(string name, int fallback) => values.TryGetValue(name, out var value) + ? int.Parse(value, System.Globalization.CultureInfo.InvariantCulture) + : fallback; + + return new Options( + Path.GetFullPath(Required("--unity-cache")), + Required("--action"), + Optional("--value"), + Optional("--view"), + Optional("--output"), + Integer("--width", 0), + Integer("--height", 0), + values.TryGetValue("--command-id", out var commandId) ? commandId : Guid.NewGuid().ToString("N"), + Integer("--wait-ms", 10000)); + } +} diff --git a/brokkr-contracts/Brokkr.Contracts.csproj b/brokkr-contracts/Brokkr.Contracts.csproj new file mode 100644 index 0000000..877b3ec --- /dev/null +++ b/brokkr-contracts/Brokkr.Contracts.csproj @@ -0,0 +1,16 @@ + + + netstandard2.1 + enable + enable + latest + false + ..\..\CultLib-codex-cultmesh-reliability + + + + + + + + diff --git a/brokkr-daemon/src/main.rs b/brokkr-daemon/src/main.rs index ca3107e..2b25df0 100644 --- a/brokkr-daemon/src/main.rs +++ b/brokkr-daemon/src/main.rs @@ -131,12 +131,11 @@ fn main() -> Result<()> { match command.as_str() { "provider" | "smoke" => print_provider(), "sync-contract" => print_sync_contract(), - "unity-command" => unity_command(UnityCommandArgs::parse(args.collect())?), "sync-once" => sync_once(SyncArgs::parse(args.collect())?), "sync-loop" => sync_loop(SyncLoopArgs::parse(args.collect())?), _ => { eprintln!( - "usage: brokkr-daemon [provider|smoke|sync-contract|unity-command --unity-cache PATH --action ACTION [--value VALUE] [--view game|scene] [--output PATH] [--width N] [--height N] [--command-id ID]|sync-once --unity-cache PATH --blender-cache PATH [--dry-run]|sync-loop --unity-cache PATH --blender-cache PATH [--interval-ms N] [--max-passes N] [--dry-run]]" + "usage: brokkr-daemon [provider|smoke|sync-contract|sync-once --unity-cache PATH --blender-cache PATH [--dry-run]|sync-loop --unity-cache PATH --blender-cache PATH [--interval-ms N] [--max-passes N] [--dry-run]]" ); std::process::exit(2); } @@ -181,42 +180,6 @@ fn sync_loop(args: SyncLoopArgs) -> Result<()> { } } -fn unity_command(args: UnityCommandArgs) -> Result<()> { - let command_id = args - .command_id - .unwrap_or_else(|| stable_id(["unity-command", &args.action, &chrono_like_timestamp_id()])); - let command = json!([ - "brokkr.unity.command_intent.v0", - command_id, - args.action, - "", - "", - "", - "", - args.value, - "", - "", - "", - "", - "", - args.view_kind, - args.output_path, - args.width, - args.height - ]); - let mut store = MirrorStore::open(&args.unity_cache)?; - let command_id = command[1] - .as_str() - .ok_or_else(|| anyhow!("generated Unity command has no command id"))?; - store.put_messagepack_document( - "brokkr.unity.command_intent.v0", - &format!("unity/commands/{command_id}"), - &command, - )?; - println!("{command_id}"); - Ok(()) -} - fn build_provider_advertisement() -> ProviderAdvertisement { ProviderAdvertisement { schema: PROVIDER_SCHEMA, @@ -541,76 +504,6 @@ struct SyncArgs { dry_run: bool, } -#[derive(Debug, Clone)] -struct UnityCommandArgs { - unity_cache: PathBuf, - action: String, - value: String, - view_kind: String, - output_path: String, - width: i64, - height: i64, - command_id: Option, -} - -impl UnityCommandArgs { - fn parse(args: Vec) -> Result { - let mut unity_cache = None; - let mut action = None; - let mut value = String::new(); - let mut view_kind = String::new(); - let mut output_path = String::new(); - let mut width = 0; - let mut height = 0; - let mut command_id = None; - let mut index = 0; - - while index < args.len() { - let option = args[index].as_str(); - index += 1; - let required_value = |index: usize| { - args.get(index) - .cloned() - .ok_or_else(|| anyhow!("{option} requires a value")) - }; - match option { - "--unity-cache" => unity_cache = Some(PathBuf::from(required_value(index)?)), - "--action" => action = Some(required_value(index)?), - "--value" => value = required_value(index)?, - "--view" => view_kind = required_value(index)?, - "--output" => output_path = required_value(index)?, - "--width" => { - let raw = required_value(index)?; - width = raw - .parse() - .with_context(|| format!("invalid --width value: {raw}"))?; - } - "--height" => { - let raw = required_value(index)?; - height = raw - .parse() - .with_context(|| format!("invalid --height value: {raw}"))?; - } - "--command-id" => command_id = Some(required_value(index)?), - other => return Err(anyhow!("unknown unity-command argument: {other}")), - } - index += 1; - } - - Ok(Self { - unity_cache: unity_cache - .ok_or_else(|| anyhow!("unity-command requires --unity-cache"))?, - action: action.ok_or_else(|| anyhow!("unity-command requires --action"))?, - value, - view_kind, - output_path, - width, - height, - command_id, - }) - } -} - impl SyncArgs { fn parse(args: Vec) -> Result { let parsed = ParsedSyncCli::parse(args, false)?; @@ -2102,52 +1995,6 @@ fn chrono_like_timestamp_id() -> String { mod tests { use super::*; - #[test] - fn unity_command_writes_typed_editor_lifecycle_intent() -> Result<()> { - let temp = tempfile::tempdir()?; - let cache = temp.path().join("unity-editor.ccmp"); - let args = UnityCommandArgs::parse(vec![ - "--unity-cache".into(), - cache.display().to_string(), - "--action".into(), - "captureEditorView".into(), - "--view".into(), - "scene".into(), - "--output".into(), - "artifacts/scene.png".into(), - "--width".into(), - "1280".into(), - "--height".into(), - "720".into(), - "--command-id".into(), - "capture-scene-test".into(), - ])?; - - unity_command(args)?; - - let mut store = MirrorStore::open(&cache)?; - let document = store - .documents()? - .into_iter() - .find(|item| item.key == "unity/commands/capture-scene-test") - .expect("Unity editor command should be written"); - assert_eq!( - field_string(&document.value, 2, "action").as_deref(), - Some("captureEditorView") - ); - assert_eq!( - field_string(&document.value, 13, "viewKind").as_deref(), - Some("scene") - ); - assert_eq!( - field_string(&document.value, 14, "outputPath").as_deref(), - Some("artifacts/scene.png") - ); - assert_eq!(field_i64(&document.value, 15, "width"), Some(1280)); - assert_eq!(field_i64(&document.value, 16, "height"), Some(720)); - Ok(()) - } - #[test] fn provider_advertises_muninn_owned_quest_routes_for_unity() { let provider = build_provider_advertisement(); diff --git a/docs/provider-contract.md b/docs/provider-contract.md index ddba865..c62b56b 100644 --- a/docs/provider-contract.md +++ b/docs/provider-contract.md @@ -75,10 +75,10 @@ Primary sync documents: Operational commands: -- `brokkr-daemon unity-command --unity-cache .brokkr/unity-editor.ccmp --action setEditorPlayState --value true` -- `brokkr-daemon unity-command --unity-cache .brokkr/unity-editor.ccmp --action setEditorPaused --value true` -- `brokkr-daemon unity-command --unity-cache .brokkr/unity-editor.ccmp --action refreshAssets` -- `brokkr-daemon unity-command --unity-cache .brokkr/unity-editor.ccmp --action captureEditorView --view scene --output artifacts/scene.png` +- `dotnet run --project brokkr-command/Brokkr.Command.csproj -- --unity-cache .brokkr/unity-editor.ccmp --action setEditorPlayState --value true` +- `dotnet run --project brokkr-command/Brokkr.Command.csproj -- --unity-cache .brokkr/unity-editor.ccmp --action setEditorPaused --value true` +- `dotnet run --project brokkr-command/Brokkr.Command.csproj -- --unity-cache .brokkr/unity-editor.ccmp --action refreshAssets` +- `dotnet run --project brokkr-command/Brokkr.Command.csproj -- --unity-cache .brokkr/unity-editor.ccmp --action captureEditorView --view scene --output artifacts/scene.png` - `brokkr-daemon sync-once --unity-cache .brokkr/unity-editor.ccmp --blender-cache .brokkr/blender-editor.ccmp` - `brokkr-daemon sync-loop --unity-cache .brokkr/unity-editor.ccmp --blender-cache .brokkr/blender-editor.ccmp --interval-ms 500` diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs index df584da..f0f3aa5 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrCultMeshMirror.cs @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using System.Threading.Tasks; using GameCult.Caching; +using GameCult.Caching.MessagePack; using GameCult.Mesh; using GameCult.Networking; using R3; @@ -33,8 +34,13 @@ namespace GameCult.Brokkr.Editor CachePath = cachePath; Directory.CreateDirectory(Path.GetDirectoryName(cachePath) ?? "."); - node = await CultMesh.StartNodeAsync(cachePath, new CultMeshNodeOptions + node = await CultMesh.CreateNodeAsync(cachePath, new CultMeshNodeOptions { + StartServer = false, + CacheOptions = new CultCacheOpenOptions + { + UseDirectoryStore = true + }, EnableDurableShardLogs = true, DatabaseOptions = new CultNetDatabaseOptions { @@ -69,6 +75,12 @@ namespace GameCult.Brokkr.Editor await node.FlushAsync(soft: true); } + internal Task PullExternalUpdatesAsync() + { + RequireRunning(); + return node.Cache.PullAllBackingStoresAsync(); + } + internal async Task PublishPrefabMirrorSnapshotAsync(BrokkrUnityPrefabMirrorSnapshot snapshot) { RequireRunning(); diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorDaemonBridge.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorDaemonBridge.cs index 0c1d247..b57b011 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorDaemonBridge.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Editor/BrokkrEditorDaemonBridge.cs @@ -6,7 +6,7 @@ namespace GameCult.Brokkr.Editor [InitializeOnLoad] public static class BrokkrEditorDaemonBridge { - private const string AutoStartKey = "GameCult.Brokkr.AutoStartMirror"; + private static string AutoStartKey => $"GameCult.Brokkr.AutoStartMirror.{UnityEngine.Application.dataPath}"; private static readonly BrokkrCultMeshMirror Mirror = new(); private static double nextPollAt; private static bool startQueued; @@ -37,14 +37,14 @@ namespace GameCult.Brokkr.Editor } [MenuItem("GameCult/Brokkr/Start Daemon Bridge")] - private static void StartDaemonBridge() + public static void StartDaemonBridge() { AutoStart = true; EnsureStarted(); } [MenuItem("GameCult/Brokkr/Stop Daemon Bridge")] - private static void StopDaemonBridge() + public static void StopDaemonBridge() { AutoStart = false; Mirror.Dispose(); @@ -104,6 +104,7 @@ namespace GameCult.Brokkr.Editor } nextPollAt = EditorApplication.timeSinceStartup + 1.0; + Mirror.PullExternalUpdatesAsync().GetAwaiter().GetResult(); DrainCommands(); DrainSyncReceipts(); } diff --git a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs index 8a8d00b..684c7f9 100644 --- a/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs +++ b/surfaces/unity/Packages/com.gamecult.brokkr/Runtime/BrokkrHostSnapshot.cs @@ -173,7 +173,7 @@ namespace GameCult.Brokkr [Serializable] public sealed class BrokkrUnityCommandEnvelope { - [Key(0)] public BrokkrUnityCommand command; + [Key(0)] public BrokkrUnityCommand command = new(); } [CultDocument("brokkr.unity.command_receipt", "brokkr.unity.command_receipt.v0")] diff --git a/surfaces/unity/README.md b/surfaces/unity/README.md index dd3c37d..32c8123 100644 --- a/surfaces/unity/README.md +++ b/surfaces/unity/README.md @@ -40,9 +40,9 @@ same CultCache mirror. Common lifecycle commands can be issued without UI automation: ```powershell -cargo run --manifest-path E:/Projects/Brokkr/brokkr-daemon/Cargo.toml -- unity-command --unity-cache .brokkr/unity-editor.ccmp --action setEditorPlayState --value true -cargo run --manifest-path E:/Projects/Brokkr/brokkr-daemon/Cargo.toml -- unity-command --unity-cache .brokkr/unity-editor.ccmp --action setEditorPaused --value true -cargo run --manifest-path E:/Projects/Brokkr/brokkr-daemon/Cargo.toml -- unity-command --unity-cache .brokkr/unity-editor.ccmp --action captureEditorView --view scene --output artifacts/scene.png +dotnet run --project E:/Projects/Brokkr/brokkr-command/Brokkr.Command.csproj -- --unity-cache .brokkr/unity-editor.ccmp --action setEditorPlayState --value true +dotnet run --project E:/Projects/Brokkr/brokkr-command/Brokkr.Command.csproj -- --unity-cache .brokkr/unity-editor.ccmp --action setEditorPaused --value true +dotnet run --project E:/Projects/Brokkr/brokkr-command/Brokkr.Command.csproj -- --unity-cache .brokkr/unity-editor.ccmp --action captureEditorView --view scene --output artifacts/scene.png ``` 6. Click `Publish Mirror`. 7. To create a ScriptableObject through the mirror, fill `ScriptableObject Type`,