From 9244c65f206590fa4bb23974b8a7b73a71ccc1ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Deniz=20=C4=B0rgin?= Date: Mon, 16 Nov 2026 15:00:33 +0300 Subject: [PATCH] feat(hosting): set and unset the background service's config, stopping it first as the CLI does (#213) --- .../Internal/Config/CorsOriginPolicy.cs | 97 ++++ .../Internal/Config/ServiceConfigDocument.cs | 116 ++++- .../Internal/Config/ServiceConfigEditor.cs | 88 +++- .../Registration/ServiceConfigReader.cs | 16 +- .../OpenCodeServer.BackgroundService.cs | 18 +- .../OpenCodeServiceConfiguration.cs | 257 +++++++++- .../OpenCodeServiceSetting.cs | 16 + .../CancellationIdentityTests.cs | 7 + .../Config/CorsOriginPolicyTests.cs | 28 + .../Config/Fixtures/cors-origin-corpus.json | 84 ++- .../Config/Fixtures/cors-origin-expected.json | 327 +++++++++++- .../Fixtures/service-config-corpus.json | 71 ++- .../Fixtures/service-config-expected.json | 483 ++++++++++++++++++ .../ServiceConfigEditorCancellationTests.cs | 46 ++ .../Config/ServiceConfigEditorTests.cs | 110 +++- .../Config/ServiceConfigJsonWriterTests.cs | 20 +- .../ServiceConfigStoreCancellationTests.cs | 2 +- .../Config/ServiceConfigStoreTests.cs | 6 +- .../Config/ServiceConfigStoreWriteTests.cs | 2 +- .../OpenCodeServiceConfigurationLiveTests.cs | 14 +- ...enCodeServiceConfigurationStopLiveTests.cs | 61 +++ .../OpenCodeServiceConfigurationTests.cs | 114 ++++- .../Support/ServiceConfigEditCase.cs | 3 + .../Support/ServiceConfigEditData.cs | 52 ++ .../Support/ServiceConfigLiveScenario.cs | 19 + .../Support/ServiceConfigScenario.cs | 27 +- .../Snapshots/PublicApi.verified.txt | 17 + .../Support/ServiceCancellationDoors.cs | 10 + .../Support/GeneratedSourceCompiler.cs | 1 + .../Generator/Binding/ReservedNamePolicy.cs | 2 + 30 files changed, 2037 insertions(+), 77 deletions(-) create mode 100644 src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/CorsOriginPolicy.cs create mode 100644 src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServiceSetting.cs create mode 100644 tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/CorsOriginPolicyTests.cs create mode 100644 tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigEditorCancellationTests.cs create mode 100644 tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/OpenCodeServiceConfigurationStopLiveTests.cs create mode 100644 tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigEditCase.cs create mode 100644 tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigEditData.cs create mode 100644 tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigLiveScenario.cs diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/CorsOriginPolicy.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/CorsOriginPolicy.cs new file mode 100644 index 000000000..50ebcd9fa --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/CorsOriginPolicy.cs @@ -0,0 +1,97 @@ +using System.Globalization; +using System.Net; + +namespace OpenCode.Sdk.Internal; + +/// The CLI's exact HTTP(S) origin and ECMAScript item-trimming policy. +internal static class CorsOriginPolicy +{ + private static readonly char[] TrimCharacters = + ['\u0009', '\u000a', '\u000b', '\u000c', '\u000d', '\u0020', '\u00a0', '\u1680', + '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008', '\u2009', '\u200a', + '\u2028', '\u2029', '\u202f', '\u205f', '\u3000', '\ufeff']; + + /// Trims exactly JavaScript WhiteSpace and LineTerminator code points. + /// One comma-list item. + /// The trimmed item. + public static string TrimItem(string value) => value.Trim(TrimCharacters); + + /// Tests whether the item equals its canonical HTTP(S) URL origin. + /// The already-trimmed item. + /// Whether the CLI accepts it unchanged as an origin. + public static bool IsOrigin(string origin) + { + if (!Uri.TryCreate(origin, UriKind.Absolute, out var uri) || uri.Scheme is not ("http" or "https")) + { + return false; + } + + var host = uri.IdnHost.ToLowerInvariant(); + if (uri.HostNameType == UriHostNameType.IPv6) + { + if (host.Contains('%', StringComparison.Ordinal) || !IPAddress.TryParse(host, out var address)) + { + return false; + } + + host = "[" + SerializeIpv6(address) + "]"; + } + else if (uri.HostNameType != UriHostNameType.IPv4 && !IsDomain(host)) + { + return false; + } + + var canonical = uri.Scheme + "://" + host + + (uri.IsDefaultPort ? string.Empty : ":" + uri.Port.ToString(CultureInfo.InvariantCulture)); + return string.Equals(origin, canonical, StringComparison.Ordinal); + } + + private static bool IsDomain(string host) + { + var labels = host.TrimEnd('.').Split('.'); + var last = labels[^1]; + // A numeric final label invokes WHATWG's IPv4 parser, not DNS, even when Uri accepts DNS. + if (last.All(static character => character is >= '0' and <= '9') + || (last.StartsWith("0x", StringComparison.Ordinal) && last.Skip(2).All(Uri.IsHexDigit))) + { + return false; + } + + try + { + var idn = new IdnMapping(); + return labels.Where(static label => label.StartsWith("xn--", StringComparison.Ordinal)) + .All(label => string.Equals(idn.GetAscii(idn.GetUnicode(label)), label, StringComparison.Ordinal)); + } + catch (ArgumentException) + { + return false; + } + } + + private static string SerializeIpv6(IPAddress address) + { + var bytes = address.GetAddressBytes(); + var groups = Enumerable.Range(0, 8).Select(index => (bytes[index * 2] << 8) | bytes[(index * 2) + 1]).ToArray(); + var start = -1; + var length = 1; + for (var index = 0; index < groups.Length; index++) + { + var end = index; + while (end < groups.Length && groups[end] == 0) + { + end++; + } + + if (end - index > length) + { + start = index; + length = end - index; + } + } + + var text = groups.Select(static group => group.ToString("x", CultureInfo.InvariantCulture)).ToArray(); + return start < 0 ? string.Join(':', text) + : string.Join(':', text.Take(start)) + "::" + string.Join(':', text.Skip(start + length)); + } +} diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/ServiceConfigDocument.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/ServiceConfigDocument.cs index 9bba6c0f0..574a804de 100644 --- a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/ServiceConfigDocument.cs +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/ServiceConfigDocument.cs @@ -14,11 +14,26 @@ internal sealed class ServiceConfigDocument /// The current remote route, or null when unset. /// The earlier boolean remote setting, or null for the current shape. /// The stored password, or null when unset. - internal ServiceConfigDocument(string? remoteRoute = null, bool? legacyRemote = null, string? password = null) + /// The saved disabled flag. + /// The saved acceptance marker. + /// The saved hostname. + /// The saved port. + /// The saved origins. + /// The saved environment entries. + internal ServiceConfigDocument( + bool? disabled = null, string? remoteRoute = null, bool? legacyRemote = null, bool? remoteAccepted = null, + string? hostname = null, int? port = null, string? password = null, + IReadOnlyList? corsOrigins = null, IReadOnlyDictionary? environment = null) { + Disabled = disabled; RemoteRoute = remoteRoute; LegacyRemote = legacyRemote; + RemoteAccepted = remoteAccepted; + Hostname = hostname; + Port = port; Password = password; + CorsOrigins = corsOrigins; + Environment = environment; } /// Gets present members in the decode's schema order, or the subsequent merge's order. @@ -27,15 +42,92 @@ internal ServiceConfigDocument(string? remoteRoute = null, bool? legacyRemote = /// Assigns without moving an existing password, adding an absent one last. /// The credential to persist. - public void AssignPassword(string password) + public void AssignPassword(string? password) { - var members = Members; - if (Password is null) + SetPresence("password", password is not null); + Password = password; + } + + /// Assigns the hostname without moving an existing member. + /// The value, including an empty string. + public void AssignHostname(string? hostname) + { + SetPresence("hostname", hostname is not null); + Hostname = hostname; + } + + /// Assigns or drops the disabled preference without moving it. + public void AssignDisabled(bool? disabled) + { + SetPresence("disabled", disabled is not null); + Disabled = disabled; + } + + /// Assigns acceptance without moving an existing marker. + public void AssignRemoteAccepted(bool accepted) + { + SetPresence("remoteAccepted", accepted); + RemoteAccepted = accepted ? true : null; + } + + /// Assigns or drops the port without moving it. + public void AssignPort(int? port) + { + SetPresence("port", port is not null); + Port = port; + } + + /// Assigns or drops origins without moving an existing member. + public void AssignCorsOrigins(IReadOnlyList? origins) + { + SetPresence("cors", origins is not null); + CorsOrigins = origins; + } + + /// Assigns or drops environment entries without moving an existing member. + public void AssignEnvironment(IReadOnlyDictionary? environment) + { + SetPresence("env", environment is not null); + Environment = environment; + } + + /// Removes a setting and its value; remote and environment have dedicated operations. + public void RemoveSetting(OpenCodeServiceSetting setting) + { + switch (setting) { - members.Add("password"); + case OpenCodeServiceSetting.Disabled: + AssignDisabled(null); + break; + case OpenCodeServiceSetting.Hostname: + AssignHostname(null); + break; + case OpenCodeServiceSetting.Port: + AssignPort(null); + break; + case OpenCodeServiceSetting.Password: + AssignPassword(null); + break; + case OpenCodeServiceSetting.CorsOrigins: + AssignCorsOrigins(null); + break; } + } - Password = password; + /// Removes env before an unset appends any remaining entries last. + public void RemoveEnvironment() => AssignEnvironment(null); + + private void SetPresence(string member, bool present) + { + var members = Members; + if (!present) + { + _ = members.Remove(member); + } + else if (!members.Contains(member, StringComparer.Ordinal)) + { + members.Add(member); + } } /// Drops a legacy boolean, adding a generated remote object last only when enabled. @@ -66,7 +158,7 @@ public void RepairRemote(string? route) }; /// Gets the saved connection-mode preference, or null when unset. - public bool? Disabled { get; init; } + public bool? Disabled { get; private set; } /// Gets the current remote route, retained only inside the SDK. public string? RemoteRoute { get; private set; } @@ -75,20 +167,20 @@ public void RepairRemote(string? route) public bool? LegacyRemote { get; private set; } /// Gets the acceptance marker, true when present and null otherwise. - public bool? RemoteAccepted { get; init; } + public bool? RemoteAccepted { get; private set; } /// Gets the saved hostname, or null when unset. - public string? Hostname { get; init; } + public string? Hostname { get; private set; } /// Gets the saved port, or null when unset. - public int? Port { get; init; } + public int? Port { get; private set; } /// Gets the stored password, retained only inside the SDK. public string? Password { get; private set; } /// Gets the saved origins in stored order, or null when unset. - public IReadOnlyList? CorsOrigins { get; init; } + public IReadOnlyList? CorsOrigins { get; private set; } /// Gets the saved environment entries, or null when unset. - public IReadOnlyDictionary? Environment { get; init; } + public IReadOnlyDictionary? Environment { get; private set; } } diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/ServiceConfigEditor.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/ServiceConfigEditor.cs index 7e80b60e1..1a9c1eebd 100644 --- a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/ServiceConfigEditor.cs +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Config/ServiceConfigEditor.cs @@ -1,8 +1,92 @@ namespace OpenCode.Sdk.Internal; -/// The non-stopping password edit over the CLI-compatible configuration store. -internal sealed class ServiceConfigEditor(ServiceConfigStore store) +/// The CLI's ordered read, stop, re-read and configuration merges. +internal sealed class ServiceConfigEditor( + ServiceConfigStore store, Func stop) { + /// Changes the saved hostname after stopping the registered service. + /// The guarded value. + /// The captured selection. + /// The caller's token. + /// The completed write. + public Task SetHostnameAsync(string hostname, ServiceSelection selection, CancellationToken cancellationToken) => + ChangeAsync(selection, document => document.AssignHostname(hostname), stopping: true, cancellationToken); + + /// Only enabling the disabled flag stops the service. + public Task SetDisabledAsync(bool disabled, ServiceSelection selection, CancellationToken cancellationToken) => + ChangeAsync(selection, document => document.AssignDisabled(disabled), stopping: disabled, cancellationToken); + + /// Stores the validated port after stopping. + public Task SetPortAsync(int port, ServiceSelection selection, CancellationToken cancellationToken) => + ChangeAsync(selection, document => document.AssignPort(port), stopping: true, cancellationToken); + + /// Stores the given password, including an empty one, after stopping. + public Task SetPasswordAsync(string password, ServiceSelection selection, CancellationToken cancellationToken) => + ChangeAsync(selection, document => document.AssignPassword(password), stopping: true, cancellationToken); + + /// Stores the captured origins in their given order after stopping. + public Task SetCorsOriginsAsync(IReadOnlyList origins, ServiceSelection selection, CancellationToken cancellationToken) => + ChangeAsync(selection, document => document.AssignCorsOrigins(origins), stopping: true, cancellationToken); + + /// Updates a present environment name in place, or appends a new name. + public Task SetEnvironmentVariableAsync(string name, string value, ServiceSelection selection, CancellationToken cancellationToken) => + ChangeAsync(selection, document => + { + var environment = (document.Environment ?? Enumerable.Empty>()) + .ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.Ordinal); + environment[name] = value; + document.AssignEnvironment(environment); + }, stopping: true, cancellationToken); + + /// Forgets remote access, recording acceptance only when it was enabled. + public Task DisableRemoteAsync(ServiceSelection selection, CancellationToken cancellationToken) => + ChangeAsync(selection, document => + { + var enabled = document.RemoteRoute is not null; + document.RepairRemote(null); + if (enabled) + { + document.AssignRemoteAccepted(true); + } + }, stopping: true, cancellationToken); + + /// Removes a setting; only the disabled preference is non-stopping. + public Task UnsetAsync(OpenCodeServiceSetting setting, ServiceSelection selection, CancellationToken cancellationToken) => + ChangeAsync(selection, document => document.RemoveSetting(setting), + stopping: setting != OpenCodeServiceSetting.Disabled, cancellationToken); + + /// Drops env, then appends its remaining entries last when any survive. + public Task UnsetEnvironmentVariableAsync(string name, ServiceSelection selection, CancellationToken cancellationToken) => + ChangeAsync(selection, document => + { + var remaining = (document.Environment ?? Enumerable.Empty>()) + .Where(pair => !string.Equals(pair.Key, name, StringComparison.Ordinal)) + .ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.Ordinal); + document.RemoveEnvironment(); + if (remaining.Count != 0) + { + document.AssignEnvironment(remaining); + } + }, stopping: true, cancellationToken); + + private async Task ChangeAsync( + ServiceSelection selection, Action merge, bool stopping, CancellationToken cancellationToken) + { + var document = await store.ReadForWriteAsync(selection, cancellationToken).ConfigureAwait(false); + if (stopping) + { + await stop(new OpenCodeServerStopOptions + { + Channel = selection.Channel, + InstalledVersion = selection.InstalledVersion, + }, cancellationToken).ConfigureAwait(false); + document = await store.ReadForWriteAsync(selection, cancellationToken).ConfigureAwait(false); + } + + merge(document); + await store.WriteAsync(store.ResolvePaths(selection), document, cancellationToken).ConfigureAwait(false); + } + /// Returns a stored nonempty password, creating and persisting one otherwise. /// The selection, validated before any seam is called. /// The caller's token. diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Registration/ServiceConfigReader.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Registration/ServiceConfigReader.cs index 51fac7376..845cf9829 100644 --- a/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Registration/ServiceConfigReader.cs +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/Internal/Registration/ServiceConfigReader.cs @@ -141,19 +141,17 @@ public static bool IsCurrent(ReadOnlySpan utf8) => _ = StrictJson.TryGetOptionalString(root, "password", out var password); _ = root.TryGetProperty("remote", out var remote); return new ServiceConfigDocument( + disabled: root.TryGetProperty("disabled", out var disabled) ? disabled.GetBoolean() : null, remoteRoute: remote.ValueKind == JsonValueKind.Object ? remote.GetProperty("route").GetString() : null, legacyRemote: remote.ValueKind is JsonValueKind.True or JsonValueKind.False ? remote.GetBoolean() : null, - password: password) - { - Disabled = root.TryGetProperty("disabled", out var disabled) ? disabled.GetBoolean() : null, - RemoteAccepted = root.TryGetProperty("remoteAccepted", out _) ? true : null, - Hostname = hostname, - Port = root.TryGetProperty("port", out var port) ? (int)port.GetDouble() : null, + remoteAccepted: root.TryGetProperty("remoteAccepted", out _) ? true : null, + hostname: hostname, + port: root.TryGetProperty("port", out var port) ? (int)port.GetDouble() : null, + password: password, // The shape has proved these strings non-null; GetString also forces strict decoding. - CorsOrigins = root.TryGetProperty("cors", out var cors) + corsOrigins: root.TryGetProperty("cors", out var cors) ? cors.EnumerateArray().Select(static origin => origin.GetString()!).ToArray() : null, - Environment = root.TryGetProperty("env", out _) ? environment : null, - }; + environment: root.TryGetProperty("env", out _) ? environment : null); } private static Dictionary? Read(JsonElement root, bool admitLegacyRemote) diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServer.BackgroundService.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServer.BackgroundService.cs index 95c83acfe..f0809bd82 100644 --- a/src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServer.BackgroundService.cs +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServer.BackgroundService.cs @@ -209,19 +209,25 @@ internal static Task StopLocatedAsync(ServicePaths paths, OpenCodeServerStopPtyM private static ServiceStopper SystemStopper() { - var timing = ServiceTiming.Default; #pragma warning disable RS0030 // The stop composition root chooses the system clock; its handoff and terminator share it. var time = TimeProvider.System; #pragma warning restore RS0030 - var fileSystem = new ServiceFileSystem(); - return new ServiceStopper( - new ServiceEnvironment(), + return SystemStopper(new ServiceEnvironment(), new ServiceFileSystem(), time); + } + + /// Composes Stop's platform collaborators over the supplied environment, files and clock. + /// The operation's environment. + /// The operation's file access. + /// The existing composition root's clock. + /// The platform stopper. + internal static ServiceStopper SystemStopper(IServiceEnvironment environment, IServiceFileSystem fileSystem, TimeProvider time) => + new( + environment, fileSystem, new ServicePtyHandoff(fileSystem, time, new ServicePtyShutdown()), new ServiceProcessControl(new ChildExitStatusReader()), - timing, + ServiceTiming.Default, time); - } /// /// Ensures a healthy compatible background service is running: reuses a ready daemon, diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServiceConfiguration.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServiceConfiguration.cs index c5eac344e..ec17c4f4e 100644 --- a/src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServiceConfiguration.cs +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServiceConfiguration.cs @@ -27,7 +27,7 @@ public static async Task ReadAsync( OpenCodeServiceConfigOptions? options = null, CancellationToken cancellationToken = default) { using var random = RandomNumberGenerator.Create(); - return await ReadWithSeamsAsync(options, CreateStore(random), cancellationToken).ConfigureAwait(false); + return await ReadWithSeamsAsync(options, CreateStore(random, out _), cancellationToken).ConfigureAwait(false); } /// The CLI's opencode service get password: returns the stored password, creating and storing one when absent or empty. @@ -43,7 +43,246 @@ public static async Task GetOrCreatePasswordAsync( { using var random = RandomNumberGenerator.Create(); return await GetOrCreatePasswordWithSeamsAsync( - options, new ServiceConfigEditor(CreateStore(random)), cancellationToken).ConfigureAwait(false); + options, CreateEditor(random), cancellationToken).ConfigureAwait(false); + } + + /// The CLI's opencode service set hostname; saves even an empty hostname. + /// The hostname for the service's next start. + /// The channel selection. + /// The caller's token. + /// The completed configuration change. + /// is null. + /// An option is blank. + /// No home resolves; the CLI-readable config or donor is refused; stopping or writing fails. + /// Stops as does for this channel, then rewrites the whole file the CLI's way. + /// Nothing restarts the service. A failed stop leaves the requested change unmade. + public static async Task SetHostnameAsync( + string hostname, OpenCodeServiceConfigOptions? options = null, CancellationToken cancellationToken = default) + { + using var random = RandomNumberGenerator.Create(); + await SetHostnameWithSeamsAsync(hostname, options, CreateEditor(random), cancellationToken).ConfigureAwait(false); + } + + /// The hostname door over the same guarded path used by its public composition. + internal static Task SetHostnameWithSeamsAsync( + string hostname, OpenCodeServiceConfigOptions? options, ServiceConfigEditor editor, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(hostname); + return editor.SetHostnameAsync(hostname, ServiceSelection.Snapshot(options), cancellationToken); + } + + /// The CLI's opencode service set disabled; only true stops the registered service. + /// The saved disabled preference. + /// The channel selection. + /// The caller's token. + /// The completed configuration change. + /// An option is blank. + /// No home resolves; the CLI-readable config or donor is refused; stopping or writing fails. + /// When true, stops as does for this channel. False stops nothing. + /// Rewrites the whole file the CLI's way, restarts nothing, and leaves the requested change unmade if stopping fails. + public static async Task SetDisabledAsync( + bool disabled, OpenCodeServiceConfigOptions? options = null, CancellationToken cancellationToken = default) + { + using var random = RandomNumberGenerator.Create(); + await SetDisabledWithSeamsAsync(disabled, options, CreateEditor(random), cancellationToken).ConfigureAwait(false); + } + + /// The disabled door's shared snapshot and forwarding path. + internal static Task SetDisabledWithSeamsAsync( + bool disabled, OpenCodeServiceConfigOptions? options, ServiceConfigEditor editor, CancellationToken cancellationToken) => + editor.SetDisabledAsync(disabled, ServiceSelection.Snapshot(options), cancellationToken); + + /// The CLI's opencode service set port. + /// The listen port, from 1 to 65535. + /// The channel selection. + /// The caller's token. + /// The completed configuration change. + /// The port is outside 1 to 65535. + /// An option is blank. + /// No home resolves; the CLI-readable config or donor is refused; stopping or writing fails. + /// Stops as does for this channel, then rewrites the whole file the CLI's way. + /// Nothing restarts the service. A failed stop leaves the requested change unmade. + public static async Task SetPortAsync(int port, OpenCodeServiceConfigOptions? options = null, CancellationToken cancellationToken = default) + { + using var random = RandomNumberGenerator.Create(); + await SetPortWithSeamsAsync(port, options, CreateEditor(random), cancellationToken).ConfigureAwait(false); + } + + /// The port door's shared range guard and snapshot. + internal static Task SetPortWithSeamsAsync( + int port, OpenCodeServiceConfigOptions? options, ServiceConfigEditor editor, CancellationToken cancellationToken) + { + ArgumentOutOfRangeException.ThrowIfLessThan(port, 1); + ArgumentOutOfRangeException.ThrowIfGreaterThan(port, 65535); + return editor.SetPortAsync(port, ServiceSelection.Snapshot(options), cancellationToken); + } + + /// The CLI's opencode service set password; stores the Basic password of the next start, even an empty string. + /// The password stored as given. + /// The channel selection. + /// The caller's token. + /// The completed configuration change. + /// The password is null. + /// An option is blank. + /// No home resolves; the CLI-readable config or donor is refused; stopping or writing fails. + /// Stops as does for this channel, then rewrites the whole file the CLI's way. + /// Nothing restarts the service. A failed stop leaves the requested change unmade. + public static async Task SetPasswordAsync( + string password, OpenCodeServiceConfigOptions? options = null, CancellationToken cancellationToken = default) + { + using var random = RandomNumberGenerator.Create(); + await SetPasswordWithSeamsAsync(password, options, CreateEditor(random), cancellationToken).ConfigureAwait(false); + } + + /// The password setter's shared guard and snapshot. + internal static Task SetPasswordWithSeamsAsync( + string password, OpenCodeServiceConfigOptions? options, ServiceConfigEditor editor, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(password); + return editor.SetPasswordAsync(password, ServiceSelection.Snapshot(options), cancellationToken); + } + + /// The CLI's opencode service set cors; keeps origin order and duplicates after the CLI's trimming. + /// A nonempty list of exact HTTP(S) origins without commas. + /// The channel selection. + /// The caller's token. + /// The completed configuration change. + /// The list or one item is null. + /// The list is empty, an item is invalid, or an option is blank. + /// No home resolves; the CLI-readable config or donor is refused; stopping or writing fails. + /// Stops as does for this channel, then rewrites the whole file the CLI's way. + /// Nothing restarts the service. A failed stop leaves the requested change unmade. + public static async Task SetCorsOriginsAsync( + IReadOnlyList origins, OpenCodeServiceConfigOptions? options = null, CancellationToken cancellationToken = default) + { + using var random = RandomNumberGenerator.Create(); + await SetCorsOriginsWithSeamsAsync(origins, options, CreateEditor(random), cancellationToken).ConfigureAwait(false); + } + + /// The CORS door captures and validates each item before reading or stopping. + internal static Task SetCorsOriginsWithSeamsAsync( + IReadOnlyList origins, OpenCodeServiceConfigOptions? options, ServiceConfigEditor editor, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(origins); + var snapshot = origins.ToArray(); + if (snapshot.Length == 0) + { + throw new ArgumentException("Origins must contain at least one HTTP(S) origin.", nameof(origins)); + } + for (var index = 0; index < snapshot.Length; index++) + { + if (snapshot[index] is null) + { + throw new ArgumentNullException(nameof(origins)); + } + var item = CorsOriginPolicy.TrimItem(snapshot[index]); + if (item.Contains(',', StringComparison.Ordinal) || !CorsOriginPolicy.IsOrigin(item)) + { + throw new ArgumentException($"Invalid CORS origin '{item}'.", nameof(origins)); + } + snapshot[index] = item; + } + return editor.SetCorsOriginsAsync(snapshot, ServiceSelection.Snapshot(options), cancellationToken); + } + + /// The CLI's opencode service set env; empty names and values are stored as given. + /// The environment name. + /// The saved value. + /// The channel selection. + /// The caller's token. + /// The completed configuration change. + /// The name or value is null. + /// An option is blank. + /// No home resolves; the CLI-readable config or donor is refused; stopping or writing fails. + /// Stops as does for this channel, then rewrites the whole file the CLI's way. + /// Nothing restarts the service. A failed stop leaves the requested change unmade. + public static async Task SetEnvironmentVariableAsync( + string name, string value, OpenCodeServiceConfigOptions? options = null, CancellationToken cancellationToken = default) + { + using var random = RandomNumberGenerator.Create(); + await SetEnvironmentVariableWithSeamsAsync(name, value, options, CreateEditor(random), cancellationToken).ConfigureAwait(false); + } + + /// The environment setter's shared guards and snapshot. + internal static Task SetEnvironmentVariableWithSeamsAsync( + string name, string value, OpenCodeServiceConfigOptions? options, ServiceConfigEditor editor, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(value); + return editor.SetEnvironmentVariableAsync(name, value, ServiceSelection.Snapshot(options), cancellationToken); + } + + /// The CLI's opencode service set remote false and opencode service unset remote. + /// The channel selection. + /// The caller's token. + /// The completed configuration change. + /// An option is blank. + /// No home resolves; the CLI-readable config or donor is refused; stopping or writing fails. + /// Stops as does for this channel and rewrites the whole file the CLI's way. + /// Forgets the route: enabling again issues a new address. Records acceptance when remote was enabled, leaving it unchanged otherwise. + /// Nothing restarts the service. A failed stop leaves the requested change unmade. + public static async Task DisableRemoteAsync(OpenCodeServiceConfigOptions? options = null, CancellationToken cancellationToken = default) + { + using var random = RandomNumberGenerator.Create(); + await DisableRemoteWithSeamsAsync(options, CreateEditor(random), cancellationToken).ConfigureAwait(false); + } + + /// The remote-off door's shared snapshot and forwarding path. + internal static Task DisableRemoteWithSeamsAsync( + OpenCodeServiceConfigOptions? options, ServiceConfigEditor editor, CancellationToken cancellationToken) => + editor.DisableRemoteAsync(ServiceSelection.Snapshot(options), cancellationToken); + + /// The CLI's opencode service unset for a typed setting. + /// The setting to remove; use the dedicated methods for remote and environment. + /// The channel selection. + /// The caller's token. + /// The completed configuration change. + /// The setting is undefined. + /// An option is blank. + /// No home resolves; the CLI-readable config or donor is refused; stopping or writing fails. + /// Except for Disabled, stops as does for this channel. + /// Rewrites the whole file the CLI's way, restarts nothing, and leaves the requested change unmade if stopping fails. + public static async Task UnsetAsync( + OpenCodeServiceSetting setting, OpenCodeServiceConfigOptions? options = null, CancellationToken cancellationToken = default) + { + using var random = RandomNumberGenerator.Create(); + await UnsetWithSeamsAsync(setting, options, CreateEditor(random), cancellationToken).ConfigureAwait(false); + } + + /// The unset door's shared enum guard and snapshot. + internal static Task UnsetWithSeamsAsync( + OpenCodeServiceSetting setting, OpenCodeServiceConfigOptions? options, ServiceConfigEditor editor, CancellationToken cancellationToken) + { + if (setting is < OpenCodeServiceSetting.Disabled or > OpenCodeServiceSetting.CorsOrigins) + { + throw new ArgumentOutOfRangeException(nameof(setting), setting, "The service setting is undefined."); + } + return editor.UnsetAsync(setting, ServiceSelection.Snapshot(options), cancellationToken); + } + + /// The CLI's opencode service unset env; removes the map when its last entry is removed. + /// The name to remove; an empty name is a value. + /// The channel selection. + /// The caller's token. + /// The completed configuration change. + /// The name is null. + /// An option is blank. + /// No home resolves; the CLI-readable config or donor is refused; stopping or writing fails. + /// Stops as does for this channel, then rewrites the whole file the CLI's way. + /// Nothing restarts the service. A failed stop leaves the requested change unmade. + public static async Task UnsetEnvironmentVariableAsync( + string name, OpenCodeServiceConfigOptions? options = null, CancellationToken cancellationToken = default) + { + using var random = RandomNumberGenerator.Create(); + await UnsetEnvironmentVariableWithSeamsAsync(name, options, CreateEditor(random), cancellationToken).ConfigureAwait(false); + } + + /// The environment unsetter's shared guard and snapshot. + internal static Task UnsetEnvironmentVariableWithSeamsAsync( + string name, OpenCodeServiceConfigOptions? options, ServiceConfigEditor editor, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(name); + return editor.UnsetEnvironmentVariableAsync(name, ServiceSelection.Snapshot(options), cancellationToken); } /// The password door over an injected editor, retaining entry-time option validation. @@ -55,10 +294,20 @@ internal static Task GetOrCreatePasswordWithSeamsAsync( OpenCodeServiceConfigOptions? options, ServiceConfigEditor editor, CancellationToken cancellationToken) => editor.GetOrCreatePasswordAsync(options, cancellationToken); - private static ServiceConfigStore CreateStore(RandomNumberGenerator random) + private static ServiceConfigEditor CreateEditor(RandomNumberGenerator random) + { + var store = CreateStore(random, out var stop); + return new ServiceConfigEditor(store, stop); + } + + private static ServiceConfigStore CreateStore( + RandomNumberGenerator random, out Func stop) { var seams = LauncherSeams.ForCurrentProcess(); - return new ServiceConfigStore(new ServiceEnvironment(), new ServiceFileSystem(), seams.Time, new RandomCredential(random)); + var environment = new ServiceEnvironment(); + var fileSystem = new ServiceFileSystem(); + stop = (options, token) => OpenCodeServer.SystemStopper(environment, fileSystem, seams.Time).StopAsync(options, token); + return new ServiceConfigStore(environment, fileSystem, seams.Time, new RandomCredential(random)); } /// The read door over an injected store, retaining entry-time option validation. diff --git a/src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServiceSetting.cs b/src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServiceSetting.cs new file mode 100644 index 000000000..60296557e --- /dev/null +++ b/src/OpenCode.Sdk/Hosting/BackgroundService/OpenCodeServiceSetting.cs @@ -0,0 +1,16 @@ +namespace OpenCode.Sdk; + +/// A setting removed by . +public enum OpenCodeServiceSetting +{ + /// The saved disabled preference. + Disabled = 0, + /// The saved hostname. + Hostname = 1, + /// The saved listen port. + Port = 2, + /// The saved Basic password. + Password = 3, + /// The saved CORS origins. + CorsOrigins = 4, +} diff --git a/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs b/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs index 313787f4e..35f8af443 100644 --- a/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs +++ b/tests/OpenCode.Sdk.Tests/CancellationIdentityTests.cs @@ -60,6 +60,7 @@ private static IEnumerable Cases() yield return new("stop", "pre-cancelled", ServiceDoors.AtStopPreCancelledAsync); yield return new("service-config-read", "pre-cancelled", caller => ServiceDoors.AtConfigPreCancelledAsync("service-config-read", caller)); yield return new("service-config-write", "pre-cancelled", caller => ServiceDoors.AtConfigPreCancelledAsync("service-config-write", caller)); + yield return new("service-config-stop", "pre-cancelled", ServiceDoors.AtConfigStopPreCancelledAsync); foreach (var entry in new[] { "method", "enumeration", "both" }) { @@ -615,6 +616,12 @@ public static string RequireRow(MemberSignature member, IReadOnlyCollection member switch { + _ when member.IsStatic && member.DeclaringType == typeof(OpenCodeServiceConfiguration) && + member.Name is nameof(OpenCodeServiceConfiguration.DisableRemoteAsync) or nameof(OpenCodeServiceConfiguration.SetCorsOriginsAsync) + or nameof(OpenCodeServiceConfiguration.SetDisabledAsync) or nameof(OpenCodeServiceConfiguration.SetEnvironmentVariableAsync) + or nameof(OpenCodeServiceConfiguration.SetHostnameAsync) or nameof(OpenCodeServiceConfiguration.SetPasswordAsync) + or nameof(OpenCodeServiceConfiguration.SetPortAsync) or nameof(OpenCodeServiceConfiguration.UnsetAsync) + or nameof(OpenCodeServiceConfiguration.UnsetEnvironmentVariableAsync) => "service-config-stop", _ when member.Is(typeof(OpenCodeServer), nameof(OpenCodeServer.StartAsync), typeof(Task), typeof(OpenCodeServerOptions), typeof(CancellationToken)) => "start", _ when member.Is(typeof(OpenCodeServer), nameof(OpenCodeServer.DiscoverAsync), typeof(Task), diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/CorsOriginPolicyTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/CorsOriginPolicyTests.cs new file mode 100644 index 000000000..9c33e23de --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/CorsOriginPolicyTests.cs @@ -0,0 +1,28 @@ +using System.Text.Json; +using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Tests.Harness; + +namespace OpenCode.Sdk.Tests.Hosting.BackgroundService.Config; + +public sealed class CorsOriginPolicyTests +{ + [Test] + public async Task IsOrigin_Should_Match_Every_Upstream_Cors_Verdict() + { + using var verdicts = JsonDocument.Parse(new FixtureLoader().LoadJson("BackgroundService.cors-origin-expected.json")); + var disagreements = new List(); + foreach (var row in verdicts.RootElement.EnumerateArray()) + { + var origin = row.GetProperty("origin").GetString()!; + var expected = row.GetProperty("valid").GetBoolean(); + var actual = CorsOriginPolicy.IsOrigin(CorsOriginPolicy.TrimItem(origin)); + if (actual != expected) + { + disagreements.Add($"{row.GetProperty("origin").GetRawText()}: upstream {expected}, SDK {actual}"); + } + } + + await Assert.That(verdicts.RootElement.GetArrayLength()).IsGreaterThanOrEqualTo(60); + await Assert.That(disagreements).IsEmpty(); + } +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/cors-origin-corpus.json b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/cors-origin-corpus.json index fe51488c7..6009fe9d5 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/cors-origin-corpus.json +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/cors-origin-corpus.json @@ -1 +1,83 @@ -[] +[ + "http://example.com", + "https://example.com", + "not-a-url", + "*", + "null", + "", + " ", + "ftp://example.com", + "https://example.com/", + "https://example.com/path", + "https://example.com?query=1", + "https://example.com#fragment", + "https://user:password@example.com", + "HTTP://example.com", + "http://EXAMPLE.com", + "https://Example.COM", + "http://example.com:80", + "https://example.com:443", + "http://example.com:443", + "https://example.com:80", + "http://example.com:0", + "http://example.com:65535", + "http://example.com:65536", + "http://example.com:08080", + "http://example.com:8080", + "http://example.com:", + "http://127.0.0.1", + "http://127.1", + "http://0x7f000001", + "http://0177.0.0.1", + "http://127.000.000.001", + "http://4294967295", + "http://255.255.255.255", + "http://256.0.0.1", + "http://[::1]", + "http://[0:0:0:0:0:0:0:1]", + "http://[2001:db8::1]", + "http://[2001:DB8::1]", + "http://[2001:0db8::1]", + "http://[::ffff:192.0.2.1]", + "http://[::ffff:c000:201]", + "http://[::]", + "http://[1:0:0:2:0:0:3:4]", + "http://[1::2:0:0:3:4]", + "http://[fe80::1%25eth0]", + "http://localhost", + "http://single", + "http://example.com.", + "http://under_score.example", + "http://%65xample.com", + "http://é.example", + "http://xn--9ca.example", + "http://xn--.example", + "http://xn--a.example", + "http://", + "http:/a", + "http:a", + "http://exa mple.com", + "http://exa\tmple.com", + "http://example.com\n", + "http://example.42", + "http://example.0x10", + "http://example.0xg", + "http://09", + "http://a-b.example", + "http://-a.example", + "http://a-.example", + "https://localhost:4096", + "https://[::1]:4096", + "http://[::1]:80", + "http://example.com\\", + "http://example.com//", + "http://example.com/?", + "http://example.com/#", + "http://example.com:000", + "\u00a0https://example.com\u00a0", + "\ufeffhttps://example.com\ufeff", + "\u3000https://example.com\u3000", + "\u2028https://example.com\u2028", + "\u0085https://example.com\u0085", + "\u200bhttps://example.com\u200b" +] diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/cors-origin-expected.json b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/cors-origin-expected.json index fe51488c7..617d34999 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/cors-origin-expected.json +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/cors-origin-expected.json @@ -1 +1,326 @@ -[] +[ + { + "origin": "http://example.com", + "valid": true + }, + { + "origin": "https://example.com", + "valid": true + }, + { + "origin": "not-a-url", + "valid": false + }, + { + "origin": "*", + "valid": false + }, + { + "origin": "null", + "valid": false + }, + { + "origin": "", + "valid": false + }, + { + "origin": " ", + "valid": false + }, + { + "origin": "ftp://example.com", + "valid": false + }, + { + "origin": "https://example.com/", + "valid": false + }, + { + "origin": "https://example.com/path", + "valid": false + }, + { + "origin": "https://example.com?query=1", + "valid": false + }, + { + "origin": "https://example.com#fragment", + "valid": false + }, + { + "origin": "https://user:password@example.com", + "valid": false + }, + { + "origin": "HTTP://example.com", + "valid": false + }, + { + "origin": "http://EXAMPLE.com", + "valid": false + }, + { + "origin": "https://Example.COM", + "valid": false + }, + { + "origin": "http://example.com:80", + "valid": false + }, + { + "origin": "https://example.com:443", + "valid": false + }, + { + "origin": "http://example.com:443", + "valid": true + }, + { + "origin": "https://example.com:80", + "valid": true + }, + { + "origin": "http://example.com:0", + "valid": true + }, + { + "origin": "http://example.com:65535", + "valid": true + }, + { + "origin": "http://example.com:65536", + "valid": false + }, + { + "origin": "http://example.com:08080", + "valid": false + }, + { + "origin": "http://example.com:8080", + "valid": true + }, + { + "origin": "http://example.com:", + "valid": false + }, + { + "origin": "http://127.0.0.1", + "valid": true + }, + { + "origin": "http://127.1", + "valid": false + }, + { + "origin": "http://0x7f000001", + "valid": false + }, + { + "origin": "http://0177.0.0.1", + "valid": false + }, + { + "origin": "http://127.000.000.001", + "valid": false + }, + { + "origin": "http://4294967295", + "valid": false + }, + { + "origin": "http://255.255.255.255", + "valid": true + }, + { + "origin": "http://256.0.0.1", + "valid": false + }, + { + "origin": "http://[::1]", + "valid": true + }, + { + "origin": "http://[0:0:0:0:0:0:0:1]", + "valid": false + }, + { + "origin": "http://[2001:db8::1]", + "valid": true + }, + { + "origin": "http://[2001:DB8::1]", + "valid": false + }, + { + "origin": "http://[2001:0db8::1]", + "valid": false + }, + { + "origin": "http://[::ffff:192.0.2.1]", + "valid": false + }, + { + "origin": "http://[::ffff:c000:201]", + "valid": true + }, + { + "origin": "http://[::]", + "valid": true + }, + { + "origin": "http://[1:0:0:2:0:0:3:4]", + "valid": false + }, + { + "origin": "http://[1::2:0:0:3:4]", + "valid": true + }, + { + "origin": "http://[fe80::1%25eth0]", + "valid": false + }, + { + "origin": "http://localhost", + "valid": true + }, + { + "origin": "http://single", + "valid": true + }, + { + "origin": "http://example.com.", + "valid": true + }, + { + "origin": "http://under_score.example", + "valid": true + }, + { + "origin": "http://%65xample.com", + "valid": false + }, + { + "origin": "http://é.example", + "valid": false + }, + { + "origin": "http://xn--9ca.example", + "valid": true + }, + { + "origin": "http://xn--.example", + "valid": false + }, + { + "origin": "http://xn--a.example", + "valid": false + }, + { + "origin": "http://", + "valid": false + }, + { + "origin": "http:/a", + "valid": false + }, + { + "origin": "http:a", + "valid": false + }, + { + "origin": "http://exa mple.com", + "valid": false + }, + { + "origin": "http://exa\tmple.com", + "valid": false + }, + { + "origin": "http://example.com\n", + "valid": true + }, + { + "origin": "http://example.42", + "valid": false + }, + { + "origin": "http://example.0x10", + "valid": false + }, + { + "origin": "http://example.0xg", + "valid": true + }, + { + "origin": "http://09", + "valid": false + }, + { + "origin": "http://a-b.example", + "valid": true + }, + { + "origin": "http://-a.example", + "valid": true + }, + { + "origin": "http://a-.example", + "valid": true + }, + { + "origin": "https://localhost:4096", + "valid": true + }, + { + "origin": "https://[::1]:4096", + "valid": true + }, + { + "origin": "http://[::1]:80", + "valid": false + }, + { + "origin": "http://example.com\\", + "valid": false + }, + { + "origin": "http://example.com//", + "valid": false + }, + { + "origin": "http://example.com/?", + "valid": false + }, + { + "origin": "http://example.com/#", + "valid": false + }, + { + "origin": "http://example.com:000", + "valid": false + }, + { + "origin": " https://example.com ", + "valid": true + }, + { + "origin": "https://example.com", + "valid": true + }, + { + "origin": " https://example.com ", + "valid": true + }, + { + "origin": "
https://example.com
", + "valid": true + }, + { + "origin": "…https://example.com…", + "valid": false + }, + { + "origin": "​https://example.com​", + "valid": false + } +] diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/service-config-corpus.json b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/service-config-corpus.json index a9fcb110e..f571fc93e 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/service-config-corpus.json +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/service-config-corpus.json @@ -162,5 +162,74 @@ "initial": "{\"cors\":[\"\\ud800\"],\"env\":{\"A\":\"1\"}}", "command": ["get"], "divergence": "Q2-a" - } + }, + { "name": "set-disabled-on", "initial": "{\"port\":4096}", "command": ["set", "disabled", "true"] }, + { "name": "set-disabled-off", "initial": "{\"disabled\":true,\"port\":4096}", "command": ["set", "disabled", "false"] }, + { "name": "set-hostname", "initial": "{\"port\":4096,\"hostname\":\"before\"}", "command": ["set", "hostname", "after"] }, + { "name": "set-port", "initial": "{\"password\":\"kept\",\"port\":4096}", "command": ["set", "port", "4097"] }, + { "name": "set-password", "initial": "{\"password\":\"before\",\"port\":4096}", "command": ["set", "password", "after"] }, + { "name": "set-cors", "initial": "{\"hostname\":\"127.0.0.1\",\"port\":4321,\"password\":\"test-secret\",\"env\":{\"TEST\":\"value\"}}", "command": ["set", "cors", " http://192.0.2.10:3001, https://app.example.com "] }, + { "name": "set-env-present", "initial": "{\"env\":{\"B\":\"b\",\"A\":\"a\",\"C\":\"c\"},\"port\":4096}", "command": ["set", "env", "A", "after"] }, + { "name": "set-env-new", "initial": "{\"env\":{\"B\":\"b\",\"2\":\"two\",\"01\":\"one\"}}", "command": ["set", "env", "A", "after"] }, + { "name": "set-remote-route", "initial": "{\"remote\":{\"route\":\"kept-route\"},\"port\":4096}", "command": ["set", "remote", "false"] }, + { "name": "set-remote-route-accepted", "initial": "{\"remote\":{\"route\":\"kept-route\"},\"remoteAccepted\":true}", "command": ["set", "remote", "false"] }, + { "name": "set-remote-absent", "initial": "{}", "command": ["set", "remote", "false"] }, + { "name": "set-remote-absent-accepted", "initial": "{\"remoteAccepted\":true}", "command": ["set", "remote", "false"] }, + { "name": "unset-remote-route", "initial": "{\"remote\":{\"route\":\"kept-route\"},\"password\":\"kept\"}", "command": ["unset", "remote"] }, + { "name": "unset-remote-route-accepted", "initial": "{\"remote\":{\"route\":\"kept-route\"},\"remoteAccepted\":true}", "command": ["unset", "remote"] }, + { "name": "unset-remote-absent", "initial": "{}", "command": ["unset", "remote"] }, + { "name": "unset-remote-absent-accepted", "initial": "{\"remoteAccepted\":true}", "command": ["unset", "remote"] }, + { "name": "unset-disabled", "initial": "{\"disabled\":true,\"port\":4096}", "command": ["unset", "disabled"] }, + { "name": "unset-hostname", "initial": "{\"hostname\":\"before\",\"port\":4096}", "command": ["unset", "hostname"] }, + { "name": "unset-port", "initial": "{\"port\":4096,\"password\":\"kept\"}", "command": ["unset", "port"] }, + { "name": "unset-password", "initial": "{\"password\":\"before\",\"port\":4096}", "command": ["unset", "password"] }, + { "name": "unset-cors", "initial": "{\"port\":4096,\"cors\":[\"https://a.example\"]}", "command": ["unset", "cors"] }, + { "name": "unset-env-last", "initial": "{\"env\":{\"A\":\"a\"},\"port\":4096}", "command": ["unset", "env", "A"] }, + { "name": "unset-env-absent-name", "initial": "{\"env\":{\"B\":\"b\",\"A\":\"a\"}}", "command": ["unset", "env", "missing"] }, + { "name": "unset-env-remaining", "initial": "{\"env\":{\"B\":\"b\",\"A\":\"a\",\"C\":\"c\"},\"port\":4096}", "command": ["unset", "env", "A"] }, + { "name": "absent-set-disabled-on", "initial": null, "command": ["set", "disabled", "true"] }, + { "name": "absent-set-disabled-off", "initial": null, "command": ["set", "disabled", "false"] }, + { "name": "absent-set-hostname", "initial": null, "command": ["set", "hostname", "localhost"] }, + { "name": "absent-set-port", "initial": null, "command": ["set", "port", "4096"] }, + { "name": "absent-set-password", "initial": null, "command": ["set", "password", "saved"] }, + { "name": "absent-set-cors", "initial": null, "command": ["set", "cors", "https://a.example"] }, + { "name": "absent-set-env", "initial": null, "command": ["set", "env", "A", "a"] }, + { "name": "absent-set-remote", "initial": null, "command": ["set", "remote", "false"] }, + { "name": "absent-unset-disabled", "initial": null, "command": ["unset", "disabled"] }, + { "name": "absent-unset-hostname", "initial": null, "command": ["unset", "hostname"] }, + { "name": "absent-unset-port", "initial": null, "command": ["unset", "port"] }, + { "name": "absent-unset-password", "initial": null, "command": ["unset", "password"] }, + { "name": "absent-unset-cors", "initial": null, "command": ["unset", "cors"] }, + { "name": "absent-unset-env", "initial": null, "command": ["unset", "env", "A"] }, + { "name": "absent-unset-remote", "initial": null, "command": ["unset", "remote"] }, + { "name": "legacy-set-hostname", "initial": "{\"remote\":true,\"hostname\":\"before\",\"env\":{\"A\":\"a\"}}", "command": ["set", "hostname", "after"] }, + { "name": "legacy-set-disabled-off", "initial": "{\"remote\":true,\"hostname\":\"before\",\"env\":{\"A\":\"a\"}}", "command": ["set", "disabled", "false"] }, + { "name": "empty-set-hostname", "initial": "{\"port\":4096}", "command": ["set", "hostname", ""] }, + { "name": "empty-set-password", "initial": "{\"password\":\"before\"}", "command": ["set", "password", ""] }, + { "name": "empty-name-set-env", "initial": "{}", "command": ["set", "env", "", "v"] }, + { "name": "empty-value-set-env", "initial": "{}", "command": ["set", "env", "k", ""] }, + { "name": "cors-duplicates", "initial": "{}", "command": ["set", "cors", "https://b.example,https://a.example,https://b.example"] }, + { "name": "cors-nbsp", "initial": "{}", "command": ["set", "cors", "\u00a0https://a.example\u00a0"] }, + { "name": "cors-bom", "initial": "{}", "command": ["set", "cors", "\ufeffhttps://a.example\ufeff"] }, + { "name": "cors-ideographic", "initial": "{}", "command": ["set", "cors", "\u3000https://a.example\u3000"] }, + { "name": "cors-line-separator", "initial": "{}", "command": ["set", "cors", "\u2028https://a.example\u2028"] }, + { "name": "cors-next-line", "initial": "{}", "command": ["set", "cors", "\u0085https://a.example\u0085"] }, + { "name": "cors-zero-width", "initial": "{}", "command": ["set", "cors", "\u200bhttps://a.example\u200b"] }, + { "name": "cors-empty", "initial": "{\"port\":4096}", "command": ["set", "cors", ""] }, + { "name": "cors-blank", "initial": "{\"port\":4096}", "command": ["set", "cors", " "] }, + { "name": "cors-comma", "initial": "{\"port\":4096}", "command": ["set", "cors", ","] }, + { "name": "cors-trailing-comma", "initial": "{\"port\":4096}", "command": ["set", "cors", "https://a.example,"] }, + { "name": "cors-leading-comma", "initial": "{\"port\":4096}", "command": ["set", "cors", ",https://a.example"] }, + { "name": "cors-double-comma", "initial": "{\"port\":4096}", "command": ["set", "cors", "https://a.example,,https://b.example"] }, + { "name": "cors-default-port", "initial": "{\"port\":4096}", "command": ["set", "cors", "https://a.example:443"] }, + { "name": "cors-path", "initial": "{\"port\":4096}", "command": ["set", "cors", "https://a.example/path"] }, + { "name": "port-zero", "initial": "{\"port\":4096}", "command": ["set", "port", "0"] }, + { "name": "port-negative", "initial": "{\"port\":4096}", "command": ["set", "port", "-1"] }, + { "name": "port-over", "initial": "{\"port\":4096}", "command": ["set", "port", "65536"] }, + { "name": "port-first", "initial": "{}", "command": ["set", "port", "1"] }, + { "name": "port-last", "initial": "{}", "command": ["set", "port", "65535"] }, + { "name": "same-set-port", "initial": "{\n \"port\": 4096\n}\n", "command": ["set", "port", "4096"] }, + { "name": "same-unset-hostname", "initial": "{}\n", "command": ["unset", "hostname"] }, + { "name": "q2-set", "initial": "{\"port\":4096,\"port\":4097}", "command": ["set", "hostname", "after"], "divergence": "Q2-a" }, + { "name": "q2-unset", "initial": "{\"hostname\":\"\\ud800\"}", "command": ["unset", "hostname"], "divergence": "Q2-a" } ] diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/service-config-expected.json b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/service-config-expected.json index 6a92cd007..950d7c31e 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/service-config-expected.json +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/Fixtures/service-config-expected.json @@ -215,5 +215,488 @@ "message": null, "output": "{\n \"cors\": [\n \"\\ud800\"\n ],\n \"env\": {\n \"A\": \"1\"\n }\n}", "file": "{\"cors\":[\"\\ud800\"],\"env\":{\"A\":\"1\"}}" + }, + { + "name": "set-disabled-on", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 4096,\n \"disabled\": true\n}\n" + }, + { + "name": "set-disabled-off", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"disabled\": false,\n \"port\": 4096\n}\n" + }, + { + "name": "set-hostname", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"hostname\": \"after\",\n \"port\": 4096\n}\n" + }, + { + "name": "set-port", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 4097,\n \"password\": \"kept\"\n}\n" + }, + { + "name": "set-password", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 4096,\n \"password\": \"after\"\n}\n" + }, + { + "name": "set-cors", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"hostname\": \"127.0.0.1\",\n \"port\": 4321,\n \"password\": \"test-secret\",\n \"env\": {\n \"TEST\": \"value\"\n },\n \"cors\": [\n \"http://192.0.2.10:3001\",\n \"https://app.example.com\"\n ]\n}\n" + }, + { + "name": "set-env-present", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 4096,\n \"env\": {\n \"B\": \"b\",\n \"A\": \"after\",\n \"C\": \"c\"\n }\n}\n" + }, + { + "name": "set-env-new", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"env\": {\n \"2\": \"two\",\n \"B\": \"b\",\n \"01\": \"one\",\n \"A\": \"after\"\n }\n}\n" + }, + { + "name": "set-remote-route", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 4096,\n \"remoteAccepted\": true\n}\n" + }, + { + "name": "set-remote-route-accepted", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"remoteAccepted\": true\n}\n" + }, + { + "name": "set-remote-absent", + "outcome": "ok", + "message": null, + "output": null, + "file": "{}\n" + }, + { + "name": "set-remote-absent-accepted", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"remoteAccepted\": true\n}\n" + }, + { + "name": "unset-remote-route", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"password\": \"kept\",\n \"remoteAccepted\": true\n}\n" + }, + { + "name": "unset-remote-route-accepted", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"remoteAccepted\": true\n}\n" + }, + { + "name": "unset-remote-absent", + "outcome": "ok", + "message": null, + "output": null, + "file": "{}\n" + }, + { + "name": "unset-remote-absent-accepted", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"remoteAccepted\": true\n}\n" + }, + { + "name": "unset-disabled", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 4096\n}\n" + }, + { + "name": "unset-hostname", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 4096\n}\n" + }, + { + "name": "unset-port", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"password\": \"kept\"\n}\n" + }, + { + "name": "unset-password", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 4096\n}\n" + }, + { + "name": "unset-cors", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 4096\n}\n" + }, + { + "name": "unset-env-last", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 4096\n}\n" + }, + { + "name": "unset-env-absent-name", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"env\": {\n \"B\": \"b\",\n \"A\": \"a\"\n }\n}\n" + }, + { + "name": "unset-env-remaining", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 4096,\n \"env\": {\n \"B\": \"b\",\n \"C\": \"c\"\n }\n}\n" + }, + { + "name": "absent-set-disabled-on", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"disabled\": true\n}\n" + }, + { + "name": "absent-set-disabled-off", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"disabled\": false\n}\n" + }, + { + "name": "absent-set-hostname", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"hostname\": \"localhost\"\n}\n" + }, + { + "name": "absent-set-port", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 4096\n}\n" + }, + { + "name": "absent-set-password", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"password\": \"saved\"\n}\n" + }, + { + "name": "absent-set-cors", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"cors\": [\n \"https://a.example\"\n ]\n}\n" + }, + { + "name": "absent-set-env", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"env\": {\n \"A\": \"a\"\n }\n}\n" + }, + { + "name": "absent-set-remote", + "outcome": "ok", + "message": null, + "output": null, + "file": "{}\n" + }, + { + "name": "absent-unset-disabled", + "outcome": "ok", + "message": null, + "output": null, + "file": "{}\n" + }, + { + "name": "absent-unset-hostname", + "outcome": "ok", + "message": null, + "output": null, + "file": "{}\n" + }, + { + "name": "absent-unset-port", + "outcome": "ok", + "message": null, + "output": null, + "file": "{}\n" + }, + { + "name": "absent-unset-password", + "outcome": "ok", + "message": null, + "output": null, + "file": "{}\n" + }, + { + "name": "absent-unset-cors", + "outcome": "ok", + "message": null, + "output": null, + "file": "{}\n" + }, + { + "name": "absent-unset-env", + "outcome": "ok", + "message": null, + "output": null, + "file": "{}\n" + }, + { + "name": "absent-unset-remote", + "outcome": "ok", + "message": null, + "output": null, + "file": "{}\n" + }, + { + "name": "legacy-set-hostname", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"remote\": {\n \"route\": \"@route\"\n },\n \"hostname\": \"after\",\n \"env\": {\n \"A\": \"a\"\n }\n}\n" + }, + { + "name": "legacy-set-disabled-off", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"hostname\": \"before\",\n \"env\": {\n \"A\": \"a\"\n },\n \"remote\": {\n \"route\": \"@route\"\n },\n \"disabled\": false\n}\n" + }, + { + "name": "empty-set-hostname", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 4096,\n \"hostname\": \"\"\n}\n" + }, + { + "name": "empty-set-password", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"password\": \"\"\n}\n" + }, + { + "name": "empty-name-set-env", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"env\": {\n \"\": \"v\"\n }\n}\n" + }, + { + "name": "empty-value-set-env", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"env\": {\n \"k\": \"\"\n }\n}\n" + }, + { + "name": "cors-duplicates", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"cors\": [\n \"https://b.example\",\n \"https://a.example\",\n \"https://b.example\"\n ]\n}\n" + }, + { + "name": "cors-nbsp", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"cors\": [\n \"https://a.example\"\n ]\n}\n" + }, + { + "name": "cors-bom", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"cors\": [\n \"https://a.example\"\n ]\n}\n" + }, + { + "name": "cors-ideographic", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"cors\": [\n \"https://a.example\"\n ]\n}\n" + }, + { + "name": "cors-line-separator", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"cors\": [\n \"https://a.example\"\n ]\n}\n" + }, + { + "name": "cors-next-line", + "outcome": "error", + "message": "CORS must be a comma-separated list of HTTP(S) origins without paths or trailing slashes", + "output": null, + "file": "{}" + }, + { + "name": "cors-zero-width", + "outcome": "error", + "message": "CORS must be a comma-separated list of HTTP(S) origins without paths or trailing slashes", + "output": null, + "file": "{}" + }, + { + "name": "cors-empty", + "outcome": "error", + "message": "CORS must be a comma-separated list of HTTP(S) origins without paths or trailing slashes", + "output": null, + "file": "{\"port\":4096}" + }, + { + "name": "cors-blank", + "outcome": "error", + "message": "CORS must be a comma-separated list of HTTP(S) origins without paths or trailing slashes", + "output": null, + "file": "{\"port\":4096}" + }, + { + "name": "cors-comma", + "outcome": "error", + "message": "CORS must be a comma-separated list of HTTP(S) origins without paths or trailing slashes", + "output": null, + "file": "{\"port\":4096}" + }, + { + "name": "cors-trailing-comma", + "outcome": "error", + "message": "CORS must be a comma-separated list of HTTP(S) origins without paths or trailing slashes", + "output": null, + "file": "{\"port\":4096}" + }, + { + "name": "cors-leading-comma", + "outcome": "error", + "message": "CORS must be a comma-separated list of HTTP(S) origins without paths or trailing slashes", + "output": null, + "file": "{\"port\":4096}" + }, + { + "name": "cors-double-comma", + "outcome": "error", + "message": "CORS must be a comma-separated list of HTTP(S) origins without paths or trailing slashes", + "output": null, + "file": "{\"port\":4096}" + }, + { + "name": "cors-default-port", + "outcome": "error", + "message": "CORS must be a comma-separated list of HTTP(S) origins without paths or trailing slashes", + "output": null, + "file": "{\"port\":4096}" + }, + { + "name": "cors-path", + "outcome": "error", + "message": "CORS must be a comma-separated list of HTTP(S) origins without paths or trailing slashes", + "output": null, + "file": "{\"port\":4096}" + }, + { + "name": "port-zero", + "outcome": "error", + "message": "Port must be between 1 and 65535", + "output": null, + "file": "{\"port\":4096}" + }, + { + "name": "port-negative", + "outcome": "error", + "message": "Port must be between 1 and 65535", + "output": null, + "file": "{\"port\":4096}" + }, + { + "name": "port-over", + "outcome": "error", + "message": "Port must be between 1 and 65535", + "output": null, + "file": "{\"port\":4096}" + }, + { + "name": "port-first", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 1\n}\n" + }, + { + "name": "port-last", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 65535\n}\n" + }, + { + "name": "same-set-port", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 4096\n}\n" + }, + { + "name": "same-unset-hostname", + "outcome": "ok", + "message": null, + "output": null, + "file": "{}\n" + }, + { + "name": "q2-set", + "outcome": "ok", + "message": null, + "output": null, + "file": "{\n \"port\": 4097,\n \"hostname\": \"after\"\n}\n" + }, + { + "name": "q2-unset", + "outcome": "ok", + "message": null, + "output": null, + "file": "{}\n" } ] diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigEditorCancellationTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigEditorCancellationTests.cs new file mode 100644 index 000000000..16eaf2678 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigEditorCancellationTests.cs @@ -0,0 +1,46 @@ +using System.Text; +using NSubstitute; +using OpenCode.Sdk.Tests.Hosting.BackgroundService.Support; +using TUnit.Assertions.Enums; + +namespace OpenCode.Sdk.Tests.Hosting.BackgroundService.Config; + +public sealed class ServiceConfigEditorCancellationTests +{ + [Test] + [Arguments("stop")] + [Arguments("read")] + public async Task SetHostnameAsync_Should_Preserve_Stop_And_Second_Read_Cancellation(string stage) + { + var scenario = new ServiceConfigScenario(); + var initial = scenario.Initial("all-members")!; + await scenario.SeedAsync(scenario.Paths.ConfigFile!, initial); + using var caller = new CancellationTokenSource(); + var cause = new OperationCanceledException(caller.Token); + if (stage == "stop") + { + scenario.Stop = (options, token) => Task.FromException(cause); + } + else + { + scenario.FileSystem.TryReadAllBytesAsync(scenario.Paths.ConfigFile!, Arg.Any()) + .Returns(Task.FromResult(Encoding.UTF8.GetBytes(initial)), Task.FromException(cause)); + } + scenario.ClearCalls(); + + var failure = await Assert.That(async () => await OpenCodeServiceConfiguration.SetHostnameWithSeamsAsync( + "requested", scenario.Options, scenario.Editor, caller.Token)).Throws(); + + await Assert.That(failure).IsSameReferenceAs(cause); + await Assert.That(scenario.StopTokens).IsEquivalentTo([caller.Token], CollectionOrdering.Matching); + string[] calls = stage == "stop" ? ["TryReadAllBytesAsync:" + scenario.Paths.ConfigFile] + : ["TryReadAllBytesAsync:" + scenario.Paths.ConfigFile, "TryReadAllBytesAsync:" + scenario.Paths.ConfigFile]; + await Assert.That(scenario.Calls).IsEquivalentTo(calls, CollectionOrdering.Matching); + foreach (var call in scenario.FileSystem.ReceivedCalls()) + { + await Assert.That(call.GetArguments()[^1]).IsEqualTo(caller.Token); + } + await Assert.That(await scenario.ReadTextAsync(scenario.Paths.ConfigFile!)).IsEqualTo(initial); + await Assert.That(scenario.Files.Directory.GetFiles(scenario.Root, "*.tmp", SearchOption.AllDirectories)).IsEmpty(); + } +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigEditorTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigEditorTests.cs index 7a7f1eae7..c078e0f51 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigEditorTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigEditorTests.cs @@ -1,3 +1,4 @@ +using System.Text.Json; using NSubstitute; using OpenCode.Sdk.Internal; using OpenCode.Sdk.Tests.Hosting.BackgroundService.Support; @@ -7,6 +8,111 @@ namespace OpenCode.Sdk.Tests.Hosting.BackgroundService.Config; public sealed class ServiceConfigEditorTests { + [Test] + [Arguments("all-members")] + [Arguments("legacy-on")] + public async Task SetHostnameAsync_Should_Leave_The_Requested_Change_Unmade_When_Stop_Fails(string name) + { + var scenario = new ServiceConfigScenario(); + var initial = scenario.Initial(name)!; + await scenario.SeedAsync(scenario.Paths.ConfigFile!, initial); + var inventory = scenario.Inventory(); + var cause = new OpenCodeServerException("scripted stop failure"); + scenario.Stop = (options, token) => Task.FromException(cause); + var failure = await ChangeHostnameFailureAsync(scenario); + + await Assert.That(failure).IsSameReferenceAs(cause); + await Assert.That(scenario.Stops.Count).IsEqualTo(1); + string[] events = name == "legacy-on" ? ["read", "rename", "stop"] : ["read", "stop"]; + await Assert.That(scenario.Events).IsEquivalentTo(events, CollectionOrdering.Matching); + if (name == "all-members") + { + await scenario.AssertUnchangedAsync(scenario.Paths.ConfigFile!, initial, inventory); + } + else + { + var bytes = await scenario.Adapter.TryReadAllBytesAsync(scenario.Paths.ConfigFile!, CancellationToken.None); + var repaired = ServiceConfigReader.TryReadDocument(bytes!)!; + await Assert.That(repaired.RemoteRoute).IsEqualTo("0011223344556677"); + await Assert.That(repaired.Hostname).IsEqualTo("legacy-on"); + using var written = JsonDocument.Parse(bytes); + await Assert.That(written.RootElement.EnumerateObject().Select(static member => member.Name)) + .IsEquivalentTo(["hostname", "env", "remote"], CollectionOrdering.Matching); + await Assert.That(scenario.Files.Directory.GetFiles(scenario.Root, "*.tmp", SearchOption.AllDirectories)).IsEmpty(); + } + } + + [Test] + [Arguments(false)] + [Arguments(true)] + public async Task SetHostnameAsync_Should_Refuse_The_Document_Or_Donor_Before_Stopping(bool donor) + { + var scenario = new ServiceConfigScenario(donor ? "beta" : "local"); + var path = donor ? scenario.Paths.LegacyConfigFile! : scenario.Paths.ConfigFile!; + var initial = scenario.Initial("repeated-member")!; + await scenario.SeedAsync(path, initial); + var inventory = scenario.Inventory(); + + var failure = await ChangeHostnameFailureAsync(scenario); + + await Assert.That(failure).IsNotNull(); + await Assert.That(failure.Message).Contains(path); + await Assert.That(scenario.Stops).IsEmpty(); + await scenario.AssertUnchangedAsync(path, initial, inventory); + } + + private static async Task ChangeHostnameFailureAsync(ServiceConfigScenario scenario) + { + scenario.ClearCalls(); + return await Assert.That(async () => await OpenCodeServiceConfiguration.SetHostnameWithSeamsAsync( + "requested", scenario.Options, scenario.Editor, CancellationToken.None)).Throws(); + } + + [Test] + [Arguments(0)] + [Arguments(1)] + [Arguments(2)] + [Arguments(3)] + [Arguments(4)] + [Arguments(5)] + [Arguments(6)] + [Arguments(7)] + [Arguments(8)] + [Arguments(9)] + [Arguments(10)] + [Arguments(11)] + [Arguments(12)] + [Arguments(13)] + public async Task ServiceConfigEditor_Should_Stop_Only_The_Operations_The_Cli_Stops(int index) + { + var row = ServiceConfigEditData.Cases[index]; + var scenario = new ServiceConfigScenario(); + scenario.Options.InstalledVersion = "0.0.0-local-42"; + await scenario.SeedAsync(scenario.Paths.ConfigFile!, scenario.Initial("all-members")!); + scenario.ClearCalls(); + scenario.Stop = (options, token) => + { + scenario.Options.Channel = "changed-after-snapshot"; + scenario.Options.InstalledVersion = "changed-after-snapshot"; + return Task.CompletedTask; + }; + + await ServiceConfigEditData.InvokeAsync(scenario, row.Command, CancellationToken.None); + + await Assert.That(scenario.Stops.Count).IsEqualTo(row.Stops); + foreach (var stop in scenario.Stops) + { + await Assert.That(stop.Channel).IsEqualTo("local"); + await Assert.That(stop.InstalledVersion).IsEqualTo("0.0.0-local-42"); + await Assert.That(stop.Pty).IsNull(); + } + string[] events = row.Stops == 0 ? ["read", "rename"] : ["read", "stop", "read", "rename"]; + await Assert.That(scenario.Events).IsEquivalentTo(events, CollectionOrdering.Matching); + string[] calls = row.Stops == 0 ? ["TryReadAllBytesAsync:" + scenario.Paths.ConfigFile, .. scenario.WriteCalls] + : ["TryReadAllBytesAsync:" + scenario.Paths.ConfigFile, "TryReadAllBytesAsync:" + scenario.Paths.ConfigFile, .. scenario.WriteCalls]; + await Assert.That(scenario.Calls).IsEquivalentTo(calls, CollectionOrdering.Matching); + } + [Test] [Arguments("empty-password")] [Arguments("absent-password")] @@ -19,7 +125,7 @@ public async Task GetOrCreatePasswordAsync_Should_Return_And_Store_Then_Reuse_Th await scenario.SeedAsync(scenario.Paths.ConfigFile!, initial); } scenario.ClearCalls(); - var editor = new ServiceConfigEditor(scenario.Store); + var editor = new ServiceConfigEditor(scenario.Store, scenario.StopAsync); var password = await editor.GetOrCreatePasswordAsync(scenario.Options, CancellationToken.None); @@ -39,7 +145,7 @@ await Assert.That(scenario.Calls.Count(call => call.StartsWith("Rename:", String public async Task GetOrCreatePasswordAsync_Should_Refuse_Blank_Options_Before_Any_Seam() { var scenario = new ServiceConfigScenario(); - var failure = await Assert.That(async () => await new ServiceConfigEditor(scenario.Store) + var failure = await Assert.That(async () => await new ServiceConfigEditor(scenario.Store, scenario.StopAsync) .GetOrCreatePasswordAsync(new OpenCodeServiceConfigOptions { Channel = " " }, CancellationToken.None)).Throws(); await Assert.That(failure).IsNotNull(); await Assert.That(failure.ParamName).IsEqualTo("options"); diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigJsonWriterTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigJsonWriterTests.cs index bdbfc9ce3..955ce16eb 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigJsonWriterTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigJsonWriterTests.cs @@ -8,7 +8,7 @@ public sealed class ServiceConfigJsonWriterTests [Test] public async Task Write_Should_Keep_Empty_Containers_Compact() { - var document = new ServiceConfigDocument { CorsOrigins = [], Environment = new Dictionary(StringComparer.Ordinal) }; + var document = new ServiceConfigDocument(corsOrigins: [], environment: new Dictionary(StringComparer.Ordinal)); await Assert.That(Encoding.UTF8.GetString(ServiceConfigJsonWriter.Write(document))) .IsEqualTo("{\n \"cors\": [],\n \"env\": {}\n}\n"); } @@ -16,16 +16,14 @@ await Assert.That(Encoding.UTF8.GetString(ServiceConfigJsonWriter.Write(document [Test] public async Task Write_Should_Order_Only_Canonical_Array_Index_Names_First() { - var document = new ServiceConfigDocument - { - Environment = new Dictionary(StringComparer.Ordinal) + var document = new ServiceConfigDocument( + environment: new Dictionary(StringComparer.Ordinal) { ["4294967295"] = "not-index", ["01"] = "not-canonical", ["4294967294"] = "last-index", ["0"] = "first-index", - }, - }; + }); await Assert.That(Encoding.UTF8.GetString(ServiceConfigJsonWriter.Write(document))).IsEqualTo( "{\n \"env\": {\n \"0\": \"first-index\",\n \"4294967294\": \"last-index\",\n" + " \"4294967295\": \"not-index\",\n \"01\": \"not-canonical\"\n }\n}\n"); @@ -34,7 +32,7 @@ await Assert.That(Encoding.UTF8.GetString(ServiceConfigJsonWriter.Write(document [Test] public async Task Write_Should_Use_Lowercase_Escapes_For_Controls_And_Lone_Surrogates() { - var document = new ServiceConfigDocument { Hostname = "\ud800\u001f\"\\/\b\f\n\r\té😀\u2028" }; + var document = new ServiceConfigDocument(hostname: "\ud800\u001f\"\\/\b\f\n\r\té😀\u2028"); var text = Encoding.UTF8.GetString(ServiceConfigJsonWriter.Write(document)); await Assert.That(text).IsEqualTo("{\n \"hostname\": \"\\ud800\\u001f\\\"\\\\/\\b\\f\\n\\r\\té😀\u2028\"\n}\n"); } @@ -42,16 +40,14 @@ public async Task Write_Should_Use_Lowercase_Escapes_For_Controls_And_Lone_Surro [Test] public async Task Write_Should_Order_Array_Index_Names_And_Keep_Other_Names_In_Order() { - var document = new ServiceConfigDocument - { - Environment = new Dictionary(StringComparer.Ordinal) + var document = new ServiceConfigDocument( + environment: new Dictionary(StringComparer.Ordinal) { ["B"] = "b", ["10"] = "ten", ["2"] = "two", ["01"] = "one", - }, - }; + }); await Assert.That(Encoding.UTF8.GetString(ServiceConfigJsonWriter.Write(document))).IsEqualTo( "{\n \"env\": {\n \"2\": \"two\",\n \"10\": \"ten\",\n \"B\": \"b\",\n \"01\": \"one\"\n }\n}\n"); } diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigStoreCancellationTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigStoreCancellationTests.cs index b68cfec2b..1a1962245 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigStoreCancellationTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigStoreCancellationTests.cs @@ -44,7 +44,7 @@ public async Task ReadForWriteAsync_Should_Propagate_The_Cancellation_Instance_W } else { - _ = await new ServiceConfigEditor(scenario.Store).GetOrCreatePasswordAsync(scenario.Options, caller.Token); + _ = await new ServiceConfigEditor(scenario.Store, scenario.StopAsync).GetOrCreatePasswordAsync(scenario.Options, caller.Token); } }).Throws(); diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigStoreTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigStoreTests.cs index 5ce9f4d0d..9931a7841 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigStoreTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigStoreTests.cs @@ -90,7 +90,7 @@ public async Task ReadForWriteAsync_Should_Copy_A_Current_Donor_As_Decoded_Text_ await scenario.SeedAsync(scenario.Paths.LegacyConfigFile!, bytes); scenario.ClearCalls(); - var password = await new ServiceConfigEditor(scenario.Store).GetOrCreatePasswordAsync(scenario.Options, CancellationToken.None); + var password = await new ServiceConfigEditor(scenario.Store, scenario.StopAsync).GetOrCreatePasswordAsync(scenario.Options, CancellationToken.None); await Assert.That(password).IsEqualTo("stored-password"); await Assert.That(await scenario.Adapter.TryReadAllBytesAsync(scenario.Paths.ConfigFile!, CancellationToken.None)) @@ -110,7 +110,7 @@ public async Task ReadForWriteAsync_Should_Refuse_A_Q2a_Donor_Before_Copying(str scenario.ClearCalls(); var inventory = scenario.Inventory(); var error = await Assert.That(async () => - await new ServiceConfigEditor(scenario.Store).GetOrCreatePasswordAsync(scenario.Options, CancellationToken.None)) + await new ServiceConfigEditor(scenario.Store, scenario.StopAsync).GetOrCreatePasswordAsync(scenario.Options, CancellationToken.None)) .Throws(); await Assert.That(error).IsNotNull(); await Assert.That(error.Message).Contains(scenario.Paths.LegacyConfigFile!); @@ -126,7 +126,7 @@ public async Task ReadForWriteAsync_Should_Not_Copy_A_Donor_Over_An_Unreadable_C var initial = await scenario.SeedDonorAsync("all-members"); scenario.FileSystem.TryReadAllBytesAsync(scenario.Paths.ConfigFile!, Arg.Any()).Returns((byte[]?)null); scenario.ClearCalls(); - var password = await new ServiceConfigEditor(scenario.Store).GetOrCreatePasswordAsync(scenario.Options, CancellationToken.None); + var password = await new ServiceConfigEditor(scenario.Store, scenario.StopAsync).GetOrCreatePasswordAsync(scenario.Options, CancellationToken.None); await Assert.That(password).IsEqualTo("ABEiM0RVZneImaq7zN3u_xAhMkNUZXaHmKm6y9zt_g8"); var bytes = await scenario.Adapter.TryReadAllBytesAsync(scenario.Paths.ConfigFile!, CancellationToken.None); var document = ServiceConfigReader.TryReadDocument(bytes!); diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigStoreWriteTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigStoreWriteTests.cs index 741bdbf95..2dc6fd3cd 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigStoreWriteTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Config/ServiceConfigStoreWriteTests.cs @@ -44,7 +44,7 @@ public async Task WriteAsync_Should_Create_Overwrite_And_Publish_The_Pid_Tempora } scenario.ClearCalls(); - await scenario.Store.WriteAsync(scenario.Paths, new ServiceConfigDocument { Port = 4096 }, CancellationToken.None); + await scenario.Store.WriteAsync(scenario.Paths, new ServiceConfigDocument(port: 4096), CancellationToken.None); await Assert.That(scenario.Calls).IsEquivalentTo([ "CreateDirectory:" + scenario.Files.Path.GetDirectoryName(scenario.Paths.ConfigFile), diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/OpenCodeServiceConfigurationLiveTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/OpenCodeServiceConfigurationLiveTests.cs index b6e7fc599..b43fbc048 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/OpenCodeServiceConfigurationLiveTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/OpenCodeServiceConfigurationLiveTests.cs @@ -2,6 +2,7 @@ using NSubstitute; using OpenCode.Sdk.Internal; using OpenCode.Sdk.Tests.Harness; +using OpenCode.Sdk.Tests.Hosting.BackgroundService.Support; using TUnit.Assertions.Enums; namespace OpenCode.Sdk.Tests.Hosting.BackgroundService; @@ -13,12 +14,10 @@ public sealed class OpenCodeServiceConfigurationLiveTests(PinnedManagedServiceFi [Test] public async Task GetOrCreatePasswordAsync_Should_Return_The_Managed_Service_Password_Without_Writing() { - var environment = Substitute.For(); - environment.GetEnvironmentVariable(Arg.Any()).Returns(call => - service.Environment.TryGetValue(call.Arg(), out var value) ? value : null); - environment.UserProfile.Returns(service.Environment.TryGetValue("HOME", out var home) ? home : service.Environment["USERPROFILE"]); + var scenario = new ServiceConfigLiveScenario(service); + var environment = scenario.Environment; using var random = RandomNumberGenerator.Create(); - var actual = new ServiceFileSystem(); + var actual = scenario.Files; var files = Substitute.For(); files.TryReadAllBytesAsync(Arg.Any(), Arg.Any()).Returns(call => actual.TryReadAllBytesAsync(call.ArgAt(0), call.ArgAt(1))); @@ -28,11 +27,14 @@ public async Task GetOrCreatePasswordAsync_Should_Return_The_Managed_Service_Pas await Assert.That(before).IsNotNull(); var registration = await ServiceRegistrationReader.TryReadAsync(actual, service.RegistrationFile, CancellationToken.None); await Assert.That(registration).IsNotNull(); - var editor = new ServiceConfigEditor(new ServiceConfigStore(environment, files, TimeProvider.System, new RandomCredential(random))); + var stops = 0; + var editor = new ServiceConfigEditor(new ServiceConfigStore(environment, files, TimeProvider.System, new RandomCredential(random)), + (options, token) => { stops++; return Task.CompletedTask; }); var password = await editor.GetOrCreatePasswordAsync(options, CancellationToken.None); await Assert.That(password).IsEqualTo(registration.Password); + await Assert.That(stops).IsEqualTo(0); await Assert.That(files.ReceivedCalls().Select(static call => call.GetMethodInfo().Name)) .IsEquivalentTo(["TryReadAllBytesAsync"], CollectionOrdering.Matching); var read = files.ReceivedCalls().Single(); diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/OpenCodeServiceConfigurationStopLiveTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/OpenCodeServiceConfigurationStopLiveTests.cs new file mode 100644 index 000000000..9683ab3cf --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/OpenCodeServiceConfigurationStopLiveTests.cs @@ -0,0 +1,61 @@ +using System.Security.Cryptography; +using System.Text.Json; +using NSubstitute; +using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Tests.Harness; +using OpenCode.Sdk.Tests.Hosting.BackgroundService.Support; +using OpenCode.Sdk.Tests.Support; +using Testably.Abstractions; +using TUnit.Assertions.Enums; + +namespace OpenCode.Sdk.Tests.Hosting.BackgroundService; + +[ClassDataSource] +[NotInParallel] +public sealed class OpenCodeServiceConfigurationStopLiveTests(PinnedManagedServiceFixture service) +{ + private const string Name = "SDK_CONFIG_STOP_WITNESS"; + private const string Value = "persisted-after-stop"; + private static readonly TimeSpan ExitBound = TimeSpan.FromSeconds(30); + + [Test] + [Timeout(180_000)] + public async Task SetEnvironmentVariableAsync_Should_Stop_The_Managed_Service_And_Preserve_Its_Config(CancellationToken cancellationToken) + { + var scenario = new ServiceConfigLiveScenario(service); + var environment = scenario.Environment; + environment.ProcessId.Returns(HostDescriptors.CurrentProcessId()); + var files = scenario.Files; + var time = TimeProvider.System; + using var random = RandomNumberGenerator.Create(); + var store = new ServiceConfigStore(environment, files, time, new RandomCredential(random)); + var options = new OpenCodeServiceConfigOptions { Channel = PinnedManagedServiceFixture.Channel }; + var paths = store.ResolvePaths(ServiceSelection.Snapshot(options)); + var before = await files.TryReadAllBytesAsync(paths.ConfigFile!, cancellationToken); + await Assert.That(before).IsNotNull(); + var editor = new ServiceConfigEditor(store, + (stopOptions, token) => OpenCodeServer.SystemStopper(environment, files, time).StopAsync(stopOptions, token)); + + await OpenCodeServiceConfiguration.SetEnvironmentVariableWithSeamsAsync(Name, Value, options, editor, cancellationToken); + + await Assert.That(await ProcessObservation.ObserveExitWithinAsync(service.ProcessId, ExitBound, cancellationToken)).IsTrue(); + var fileSystem = new RealFileSystem(); + await Assert.That(service.RegistrationFile).Satisfies(path => !fileSystem.File.Exists(path)); + var after = await files.TryReadAllBytesAsync(paths.ConfigFile!, cancellationToken); + await Assert.That(after).IsNotNull(); + using var original = JsonDocument.Parse(before); + using var written = JsonDocument.Parse(after); + await Assert.That(written.RootElement.EnumerateObject().Select(static member => member.Name)) + .IsEquivalentTo([.. original.RootElement.EnumerateObject().Select(static member => member.Name), "env"], CollectionOrdering.Matching); + foreach (var member in original.RootElement.EnumerateObject()) + { + await Assert.That(written.RootElement.GetProperty(member.Name).GetRawText()).IsEqualTo(member.Value.GetRawText()); + } + var entries = written.RootElement.GetProperty("env").EnumerateObject().ToArray(); + await Assert.That(entries.Select(static member => member.Name)).IsEquivalentTo([Name], CollectionOrdering.Matching); + await Assert.That(entries[0].Value.GetString()).IsEqualTo(Value); + var text = System.Text.Encoding.UTF8.GetString(after); + await Assert.That(text).StartsWith("{\n \""); + await Assert.That(text).EndsWith("}\n"); + } +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/OpenCodeServiceConfigurationTests.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/OpenCodeServiceConfigurationTests.cs index 89fccb4fd..ee12ada9c 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/OpenCodeServiceConfigurationTests.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/OpenCodeServiceConfigurationTests.cs @@ -10,6 +10,80 @@ namespace OpenCode.Sdk.Tests.Hosting.BackgroundService; public sealed class OpenCodeServiceConfigurationTests { + [Test] + [Arguments("hostname", "hostname", typeof(ArgumentNullException))] + [Arguments("password", "password", typeof(ArgumentNullException))] + [Arguments("name", "name", typeof(ArgumentNullException))] + [Arguments("value", "value", typeof(ArgumentNullException))] + [Arguments("unset-name", "name", typeof(ArgumentNullException))] + [Arguments("origins", "origins", typeof(ArgumentNullException))] + [Arguments("null-item", "origins", typeof(ArgumentNullException))] + [Arguments("empty", "origins", typeof(ArgumentException))] + [Arguments("comma", "origins", typeof(ArgumentException))] + [Arguments("invalid", "origins", typeof(ArgumentException))] + [Arguments("port-zero", "port", typeof(ArgumentOutOfRangeException))] + [Arguments("port-over", "port", typeof(ArgumentOutOfRangeException))] + [Arguments("setting-negative", "setting", typeof(ArgumentOutOfRangeException))] + [Arguments("setting-over", "setting", typeof(ArgumentOutOfRangeException))] + public async Task ServiceConfigEditor_Should_Refuse_Invalid_Arguments_Before_Using_Collaborators( + string guard, string parameter, Type exceptionType) + { + var scenario = new ServiceConfigScenario(); + var editor = scenario.Editor; + Func operation = guard switch + { + "hostname" => () => OpenCodeServiceConfiguration.SetHostnameWithSeamsAsync(null!, scenario.Options, editor, CancellationToken.None), + "password" => () => OpenCodeServiceConfiguration.SetPasswordWithSeamsAsync(null!, scenario.Options, editor, CancellationToken.None), + "name" => () => OpenCodeServiceConfiguration.SetEnvironmentVariableWithSeamsAsync(null!, "v", scenario.Options, editor, CancellationToken.None), + "value" => () => OpenCodeServiceConfiguration.SetEnvironmentVariableWithSeamsAsync("k", null!, scenario.Options, editor, CancellationToken.None), + "unset-name" => () => OpenCodeServiceConfiguration.UnsetEnvironmentVariableWithSeamsAsync(null!, scenario.Options, editor, CancellationToken.None), + "origins" => () => OpenCodeServiceConfiguration.SetCorsOriginsWithSeamsAsync(null!, scenario.Options, editor, CancellationToken.None), + "null-item" => () => OpenCodeServiceConfiguration.SetCorsOriginsWithSeamsAsync([null!], scenario.Options, editor, CancellationToken.None), + "empty" => () => OpenCodeServiceConfiguration.SetCorsOriginsWithSeamsAsync([], scenario.Options, editor, CancellationToken.None), + "comma" => () => OpenCodeServiceConfiguration.SetCorsOriginsWithSeamsAsync(["http://a,http://b"], scenario.Options, editor, CancellationToken.None), + "invalid" => () => OpenCodeServiceConfiguration.SetCorsOriginsWithSeamsAsync(["http://a/"], scenario.Options, editor, CancellationToken.None), + "port-zero" => () => OpenCodeServiceConfiguration.SetPortWithSeamsAsync(0, scenario.Options, editor, CancellationToken.None), + "port-over" => () => OpenCodeServiceConfiguration.SetPortWithSeamsAsync(65536, scenario.Options, editor, CancellationToken.None), + "setting-negative" => () => OpenCodeServiceConfiguration.UnsetWithSeamsAsync((OpenCodeServiceSetting)(-1), scenario.Options, editor, CancellationToken.None), + _ => () => OpenCodeServiceConfiguration.UnsetWithSeamsAsync((OpenCodeServiceSetting)5, scenario.Options, editor, CancellationToken.None), + }; + var failure = await Assert.That(operation).Throws(); + await Assert.That(failure).IsNotNull(); + await Assert.That(failure.GetType()).IsEqualTo(exceptionType); + await Assert.That(failure.ParamName).IsEqualTo(parameter); + await AssertUncalledAsync(scenario); + } + + [Test] + [Arguments(true)] + [Arguments(false)] + public async Task ServiceConfigEditor_Should_Refuse_Blank_Options_Before_Using_Collaborators(bool channel) + { + foreach (var row in ServiceConfigEditData.Cases) + { + var scenario = new ServiceConfigScenario(); + scenario.Options.Channel = channel ? " " : "local"; + scenario.Options.InstalledVersion = channel ? null : " "; + await AssertOptionRefusalAsync(() => ServiceConfigEditData.InvokeAsync(scenario, row.Command, CancellationToken.None), scenario); + } + } + + private static async Task AssertUncalledAsync(ServiceConfigScenario scenario) + { + await Assert.That(scenario.FileSystem.ReceivedCalls()).IsEmpty(); + await Assert.That(scenario.Environment.ReceivedCalls()).IsEmpty(); + await Assert.That(scenario.Stops).IsEmpty(); + } + + private static async Task AssertOptionRefusalAsync(Func operation, ServiceConfigScenario scenario) + { + var failure = await Assert.That(operation).Throws(); + await Assert.That(failure).IsNotNull(); + await Assert.That(failure.ParamName).IsEqualTo("options"); + await Assert.That(failure.Message).StartsWith("OpenCodeServiceConfigOptions."); + await AssertUncalledAsync(scenario); + } + [Test] public async Task GetOrCreatePasswordAsync_Should_Validate_Options_At_The_Public_Door() { @@ -212,7 +286,6 @@ public async Task ReadAsync_Should_Match_The_Upstream_Get_View() { var name = row.GetProperty("name").GetString()!; var verdict = verdicts.RootElement.EnumerateArray().Single(item => item.GetProperty("name").GetString() == name); - await Assert.That(verdict.GetProperty("outcome").GetString()).IsEqualTo("ok"); await AssertParityRowAsync(row, verdict); } } @@ -228,11 +301,22 @@ private static async Task AssertParityRowAsync(JsonElement row, JsonElement verd scenario.ClearCalls(); var inventory = scenario.Inventory(); var command = row.GetProperty("command").EnumerateArray().Select(static item => item.GetString()!).ToArray(); + if (verdict.GetProperty("outcome").GetString() == "error") + { + await Assert.That(async () => await InvokeParityAsync(scenario, command, verdict)).Throws(); + await Assert.That(scenario.Stops).IsEmpty(); + await Assert.That(scenario.Calls).IsEmpty(); + await Assert.That(scenario.Inventory()).IsEquivalentTo(inventory, CollectionOrdering.Matching); + await Assert.That(await scenario.Adapter.TryReadAllBytesAsync(scenario.Paths.ConfigFile!, CancellationToken.None)) + .IsEquivalentTo(Encoding.UTF8.GetBytes(initial!), CollectionOrdering.Matching); + return; + } if (row.TryGetProperty("divergence", out _)) { var failure = await Assert.That(async () => await InvokeParityAsync(scenario, command, verdict)).Throws(); await Assert.That(failure).IsNotNull(); await Assert.That(failure.Message).Contains(scenario.Paths.ConfigFile!); + await Assert.That(scenario.Stops).IsEmpty(); await scenario.AssertUnchangedAsync(scenario.Paths.ConfigFile!, initial!, inventory); await Assert.That(scenario.Calls).IsEquivalentTo(["TryReadAllBytesAsync:" + scenario.Paths.ConfigFile], CollectionOrdering.Matching); return; @@ -258,7 +342,13 @@ private static async Task AssertParityRowAsync(JsonElement row, JsonElement verd actual = MaskGenerated(actual!, "\n \"password\": ", password, "@password"); } await Assert.That(actual).IsEqualTo(expected).Because(row.GetProperty("name").GetString()!); - if (expected == initial) + if (command[0] is "set" or "unset") + { + var remote = Member(original.RootElement, "remote").ValueKind; + await Assert.That(scenario.Events.Count(static item => item == "rename")) + .IsEqualTo(remote is JsonValueKind.True or JsonValueKind.False ? 2 : 1); + } + else if (expected == initial) { await Assert.That(scenario.Inventory()).IsEquivalentTo(inventory, CollectionOrdering.Matching); string[] calls = initial is null @@ -278,14 +368,18 @@ private static string MaskGenerated(string text, string prefix, string secret, s private static async Task InvokeParityAsync(ServiceConfigScenario scenario, string[] command, JsonElement verdict) { - if (command[0] == "read") + if (command[0] is "set" or "unset") + { + await ServiceConfigEditData.InvokeAsync(scenario, command, CancellationToken.None); + } + else if (command[0] == "read") { _ = await scenario.Store.ReadForWriteAsync(ServiceSelection.Snapshot(scenario.Options), CancellationToken.None); } else if (command.Length == 2) { var password = await OpenCodeServiceConfiguration.GetOrCreatePasswordWithSeamsAsync( - scenario.Options, new ServiceConfigEditor(scenario.Store), CancellationToken.None); + scenario.Options, new ServiceConfigEditor(scenario.Store, scenario.StopAsync), CancellationToken.None); var expected = verdict.GetProperty("output").GetString(); if (expected == "@password") { @@ -316,16 +410,8 @@ public async Task ReadAsync_Should_Refuse_Blank_Options_Before_Using_Any_Seam(bo scenario.Options.Channel = channel ? " " : null; scenario.Options.InstalledVersion = channel ? null : "\t"; - var failure = await Assert.That(async () => - { - _ = await OpenCodeServiceConfiguration.ReadWithSeamsAsync(scenario.Options, scenario.Store, CancellationToken.None); - }).Throws(); - - await Assert.That(failure).IsNotNull(); - await Assert.That(failure.ParamName).IsEqualTo("options"); - await Assert.That(failure.Message).StartsWith("OpenCodeServiceConfigOptions."); - await Assert.That(scenario.FileSystem.ReceivedCalls()).IsEmpty(); - await Assert.That(scenario.Environment.ReceivedCalls()).IsEmpty(); + await AssertOptionRefusalAsync(() => OpenCodeServiceConfiguration.ReadWithSeamsAsync( + scenario.Options, scenario.Store, CancellationToken.None), scenario); } [Test] diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigEditCase.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigEditCase.cs new file mode 100644 index 000000000..76b04ffa9 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigEditCase.cs @@ -0,0 +1,3 @@ +namespace OpenCode.Sdk.Tests.Hosting.BackgroundService.Support; + +internal sealed record ServiceConfigEditCase(IReadOnlyList Command, int Stops); diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigEditData.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigEditData.cs new file mode 100644 index 000000000..a5500f627 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigEditData.cs @@ -0,0 +1,52 @@ +using System.Globalization; + +namespace OpenCode.Sdk.Tests.Hosting.BackgroundService.Support; + +internal static class ServiceConfigEditData +{ + public static IReadOnlyList Cases { get; } = + [ + new(["set", "disabled", "true"], 1), new(["set", "disabled", "false"], 0), + new(["set", "hostname", "changed"], 1), new(["set", "port", "4097"], 1), + new(["set", "password", "changed"], 1), new(["set", "cors", "https://a.example"], 1), + new(["set", "env", "A", "changed"], 1), new(["set", "remote", "false"], 1), + new(["unset", "disabled"], 0), new(["unset", "hostname"], 1), + new(["unset", "port"], 1), new(["unset", "password"], 1), + new(["unset", "cors"], 1), new(["unset", "env", "A"], 1), + ]; + + public static Task InvokeAsync(ServiceConfigScenario scenario, IReadOnlyList command, CancellationToken token) + { + var options = scenario.Options; + var editor = scenario.Editor; + if (command[0] == "set") + { + return command[1] switch + { + "disabled" => OpenCodeServiceConfiguration.SetDisabledWithSeamsAsync(bool.Parse(command[2]), options, editor, token), + "hostname" => OpenCodeServiceConfiguration.SetHostnameWithSeamsAsync(command[2], options, editor, token), + "port" => OpenCodeServiceConfiguration.SetPortWithSeamsAsync(int.Parse(command[2], CultureInfo.InvariantCulture), options, editor, token), + "password" => OpenCodeServiceConfiguration.SetPasswordWithSeamsAsync(command[2], options, editor, token), + "cors" => OpenCodeServiceConfiguration.SetCorsOriginsWithSeamsAsync(command[2].Split(','), options, editor, token), + "env" => OpenCodeServiceConfiguration.SetEnvironmentVariableWithSeamsAsync(command[2], command[3], options, editor, token), + "remote" => OpenCodeServiceConfiguration.DisableRemoteWithSeamsAsync(options, editor, token), + _ => throw new InvalidOperationException("Unknown config set command."), + }; + } + + return command[1] switch + { + "env" => OpenCodeServiceConfiguration.UnsetEnvironmentVariableWithSeamsAsync(command[2], options, editor, token), + "remote" => OpenCodeServiceConfiguration.DisableRemoteWithSeamsAsync(options, editor, token), + _ => OpenCodeServiceConfiguration.UnsetWithSeamsAsync(command[1] switch + { + "disabled" => OpenCodeServiceSetting.Disabled, + "hostname" => OpenCodeServiceSetting.Hostname, + "port" => OpenCodeServiceSetting.Port, + "password" => OpenCodeServiceSetting.Password, + "cors" => OpenCodeServiceSetting.CorsOrigins, + _ => throw new InvalidOperationException("Unknown config unset command."), + }, options, editor, token), + }; + } +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigLiveScenario.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigLiveScenario.cs new file mode 100644 index 000000000..f3086b762 --- /dev/null +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigLiveScenario.cs @@ -0,0 +1,19 @@ +using NSubstitute; +using OpenCode.Sdk.Internal; +using OpenCode.Sdk.Tests.Harness; + +namespace OpenCode.Sdk.Tests.Hosting.BackgroundService.Support; + +/// The real service-config file access under a managed fixture's isolated environment. +internal sealed class ServiceConfigLiveScenario +{ + public ServiceConfigLiveScenario(PinnedManagedServiceFixture service) + { + Environment.GetEnvironmentVariable(Arg.Any()).Returns(call => + service.Environment.TryGetValue(call.Arg(), out var value) ? value : null); + Environment.UserProfile.Returns(service.Environment.TryGetValue("HOME", out var home) ? home : service.Environment["USERPROFILE"]); + } + + public IServiceEnvironment Environment { get; } = Substitute.For(); + public ServiceFileSystem Files { get; } = new(); +} diff --git a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigScenario.cs b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigScenario.cs index d28284ba7..552344854 100644 --- a/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigScenario.cs +++ b/tests/OpenCode.Sdk.Tests/Hosting/BackgroundService/Support/ServiceConfigScenario.cs @@ -22,7 +22,11 @@ public ServiceConfigScenario(string? channel = "local") Environment.GetEnvironmentVariable("XDG_STATE_HOME").Returns(Files.Path.Combine(Root, "state")); Adapter = new TestablyServiceFileSystem(Files); FileSystem.TryReadAllBytesAsync(Arg.Any(), Arg.Any()) - .Returns(call => Adapter.TryReadAllBytesAsync(call.ArgAt(0), call.ArgAt(1))); + .Returns(call => + { + Events.Add("read"); + return Adapter.TryReadAllBytesAsync(call.ArgAt(0), call.ArgAt(1)); + }); FileSystem.Exists(Arg.Any()).Returns(call => Adapter.Exists(call.Arg())); FileSystem.When(files => files.CreateDirectory(Arg.Any())) .Do(call => Adapter.CreateDirectory(call.Arg())); @@ -33,7 +37,11 @@ public ServiceConfigScenario(string? channel = "local") .Returns(call => Adapter.TryCreateExclusiveAsync(call.ArgAt(0), call.ArgAt>(1), call.ArgAt(2))); FileSystem.TryDelete(Arg.Any()).Returns(call => Adapter.TryDelete(call.Arg())); FileSystem.When(files => files.Rename(Arg.Any(), Arg.Any())) - .Do(call => (Rename ?? Adapter.Rename)(call.ArgAt(0), call.ArgAt(1))); + .Do(call => + { + Events.Add("rename"); + (Rename ?? Adapter.Rename)(call.ArgAt(0), call.ArgAt(1)); + }); Options = new OpenCodeServiceConfigOptions { Channel = channel }; Paths = new ServicePathResolver(Environment).Resolve(ServiceSelection.Snapshot(Options)); ClearCalls(); @@ -50,6 +58,18 @@ public ServiceConfigScenario(string? channel = "local") public RandomCredential Credentials { get; set; } = new(new ScriptedRandomNumberGenerator()); public Action? Rename { get; set; } public ServiceConfigStore Store => new(Environment, FileSystem, Time, Credentials); + public ServiceConfigEditor Editor => new(Store, StopAsync); + public List Events { get; } = []; + public List Stops { get; } = []; + public List StopTokens { get; } = []; + public Func? Stop { get; set; } + public Task StopAsync(OpenCodeServerStopOptions options, CancellationToken cancellationToken) + { + Events.Add("stop"); + Stops.Add(options); + StopTokens.Add(cancellationToken); + return Stop?.Invoke(options, cancellationToken) ?? Task.CompletedTask; + } public IReadOnlyList WriteCalls => ["CreateDirectory:" + Files.Path.GetDirectoryName(Paths.ConfigFile), @@ -108,5 +128,8 @@ public void ClearCalls() { FileSystem.ClearReceivedCalls(); Environment.ClearReceivedCalls(); + Events.Clear(); + Stops.Clear(); + StopTokens.Clear(); } } diff --git a/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt b/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt index 6696f1f39..45d74e6fd 100644 --- a/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt +++ b/tests/OpenCode.Sdk.Tests/Snapshots/PublicApi.verified.txt @@ -1204,8 +1204,25 @@ namespace OpenCode.Sdk } public static class OpenCodeServiceConfiguration { + public static System.Threading.Tasks.Task DisableRemoteAsync(OpenCode.Sdk.OpenCodeServiceConfigOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } public static System.Threading.Tasks.Task GetOrCreatePasswordAsync(OpenCode.Sdk.OpenCodeServiceConfigOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } public static System.Threading.Tasks.Task ReadAsync(OpenCode.Sdk.OpenCodeServiceConfigOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } + public static System.Threading.Tasks.Task SetCorsOriginsAsync(System.Collections.Generic.IReadOnlyList origins, OpenCode.Sdk.OpenCodeServiceConfigOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } + public static System.Threading.Tasks.Task SetDisabledAsync(bool disabled, OpenCode.Sdk.OpenCodeServiceConfigOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } + public static System.Threading.Tasks.Task SetEnvironmentVariableAsync(string name, string value, OpenCode.Sdk.OpenCodeServiceConfigOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } + public static System.Threading.Tasks.Task SetHostnameAsync(string hostname, OpenCode.Sdk.OpenCodeServiceConfigOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } + public static System.Threading.Tasks.Task SetPasswordAsync(string password, OpenCode.Sdk.OpenCodeServiceConfigOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } + public static System.Threading.Tasks.Task SetPortAsync(int port, OpenCode.Sdk.OpenCodeServiceConfigOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } + public static System.Threading.Tasks.Task UnsetAsync(OpenCode.Sdk.OpenCodeServiceSetting setting, OpenCode.Sdk.OpenCodeServiceConfigOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } + public static System.Threading.Tasks.Task UnsetEnvironmentVariableAsync(string name, OpenCode.Sdk.OpenCodeServiceConfigOptions? options = null, System.Threading.CancellationToken cancellationToken = default) { } + } + public enum OpenCodeServiceSetting + { + Disabled = 0, + Hostname = 1, + Port = 2, + Password = 3, + CorsOrigins = 4, } public sealed class OpenCodeStreamFailureException : OpenCode.Sdk.OpenCodeTransportException { diff --git a/tests/OpenCode.Sdk.Tests/Support/ServiceCancellationDoors.cs b/tests/OpenCode.Sdk.Tests/Support/ServiceCancellationDoors.cs index 43e45dddf..3789c990e 100644 --- a/tests/OpenCode.Sdk.Tests/Support/ServiceCancellationDoors.cs +++ b/tests/OpenCode.Sdk.Tests/Support/ServiceCancellationDoors.cs @@ -41,6 +41,16 @@ internal async Task AtResolveConfigStoreReadAsync(Ca return failure; } + internal async Task AtConfigStopPreCancelledAsync(CancellationTokenSource caller) + { + var inventory = fileSystem.Directory.GetFiles(SessionIsolation.Root!, "*", SearchOption.AllDirectories); + await caller.CancelOnWorkerAsync(); + var failure = await observeCancellation(() => OpenCodeServiceConfiguration.SetHostnameAsync("localhost", cancellationToken: caller.Token)); + await Assert.That(fileSystem.Directory.GetFiles(SessionIsolation.Root!, "*", SearchOption.AllDirectories)) + .IsEquivalentTo(inventory, CollectionOrdering.Any); + return failure; + } + internal async Task AtConfigPreCancelledAsync(string row, CancellationTokenSource caller) { var options = new OpenCodeServiceConfigOptions(); diff --git a/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs b/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs index c95c6aea0..567ed7a2a 100644 --- a/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs +++ b/tests/OpenCode.Sdk.Tools.Tests/Support/GeneratedSourceCompiler.cs @@ -69,6 +69,7 @@ internal static readonly (string Consumer, string RequiredEmission)[] GeneratedS ("Hosting/BackgroundService/Internal/Handoff/ServicePtyShutdown.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), ("Hosting/BackgroundService/OpenCodeServer.BackgroundService.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), ("Hosting/BackgroundService/OpenCodeServerIncumbent.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), + ("Hosting/BackgroundService/OpenCodeServiceConfiguration.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), ("Hosting/Connection/OpenCodeServer.Connection.cs", "PersistentPtys/Internal/PersistentPtysRawClient.cs"), ("Hosting/Connection/OpenCodeServer.Connection.cs", "Server/ServerClient.cs"), ("Hosting/Connection/OpenCodeServer.Connection.cs", "Common/Errors/UnauthorizedError.cs"), diff --git a/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs b/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs index 21babe5c6..1656d6c19 100644 --- a/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs +++ b/tools/OpenCode.Sdk.Tools/Generator/Binding/ReservedNamePolicy.cs @@ -120,6 +120,7 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client) "OpenCodeServiceConfig", "OpenCodeServiceConfigOptions", "OpenCodeServiceConfiguration", + "OpenCodeServiceSetting", "OpenCodeStreamFailureException", "OpenCodeTransportException", "Optional", @@ -196,6 +197,7 @@ public static IEnumerable OptionalBodyTypeNames(ClientPlan client) "ConnectionResolver", "ConnectionSeams", "ConnectionSnapshot", + "CorsOriginPolicy", "CursorPaginator", "DeclaredHeader", "DefaultModelWait",