Skip to content

Commit e359b8f

Browse files
committed
fix(connection): retry bootstrap cleanup after save failure
Keep gateway registry memory aligned with persisted state when bootstrap credential cleanup cannot be saved, so later connection lifecycle events can retry safely. Co-authored-by: Copilot App <[email protected]> Copilot-Session: 73908040-d4b7-493b-b024-b0c9ebcfc98d
1 parent 23654f2 commit e359b8f

3 files changed

Lines changed: 128 additions & 19 deletions

File tree

‎src/OpenClaw.Connection/GatewayConnectionManager.cs‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1886,13 +1886,14 @@ private void TryClearBootstrapTokenAfterDurablePairing(string gatewayRecordId, s
18861886
return;
18871887
}
18881888

1889-
var updated = _registry.Update(gatewayRecordId, r => r with { BootstrapToken = null });
1890-
if (updated == null)
1891-
return;
1892-
18931889
try
18941890
{
1895-
_registry.Save();
1891+
var updated = _registry.UpdateAndSave(
1892+
gatewayRecordId,
1893+
r => r with { BootstrapToken = null });
1894+
if (updated == null)
1895+
return;
1896+
18961897
_diagnostics.Record("credential", "Cleared bootstrap token — operator and node tokens are durable");
18971898
}
18981899
catch (Exception ex)

‎src/OpenClaw.Connection/GatewayRegistry.cs‎

Lines changed: 54 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -139,32 +139,72 @@ public void SetActive(string? gatewayId)
139139
return updated;
140140
}
141141

142-
// ─── Persistence ───
143-
144-
public void Save()
142+
/// <summary>
143+
/// Atomically update and persist a record. If persistence fails, the in-memory
144+
/// record is restored so a later lifecycle event can safely retry the update.
145+
/// </summary>
146+
public GatewayRecord? UpdateAndSave(string id, Func<GatewayRecord, GatewayRecord> updater)
145147
{
148+
GatewayRecord? updated;
149+
List<GatewayRecord> snapshot;
150+
string? activeId;
146151
lock (_lock)
147152
{
148-
var data = new RegistryData { Gateways = _records.ToList(), ActiveId = _activeId };
149-
var json = JsonSerializer.Serialize(data, s_jsonOptions);
153+
var idx = _records.FindIndex(r => r.Id == id);
154+
if (idx < 0) return null;
150155

151-
var dir = Path.GetDirectoryName(_filePath);
152-
if (dir != null && !_fs.DirectoryExists(dir))
153-
_fs.CreateDirectory(dir);
156+
var original = _records[idx];
157+
updated = updater(original);
158+
ArgumentNullException.ThrowIfNull(updated, nameof(updater));
159+
_records[idx] = updated;
154160

155-
// Atomic write: unique temp file then rename. Keep the registry lock
156-
// through the move so concurrent saves cannot publish stale snapshots.
157-
var tempPath = $"{_filePath}.{Guid.NewGuid():N}.tmp";
158161
try
159162
{
160-
_fs.WriteAllText(tempPath, json);
161-
File.Move(tempPath, _filePath, overwrite: true);
163+
SaveLocked();
162164
}
163165
catch
164166
{
165-
TryDeleteTempFile(tempPath);
167+
_records[idx] = original;
166168
throw;
167169
}
170+
171+
snapshot = _records.ToList();
172+
activeId = _activeId;
173+
}
174+
175+
Changed?.Invoke(this, new GatewayRegistryChangedEventArgs(snapshot, activeId));
176+
return updated;
177+
}
178+
179+
// ─── Persistence ───
180+
181+
public void Save()
182+
{
183+
lock (_lock)
184+
SaveLocked();
185+
}
186+
187+
private void SaveLocked()
188+
{
189+
var data = new RegistryData { Gateways = _records.ToList(), ActiveId = _activeId };
190+
var json = JsonSerializer.Serialize(data, s_jsonOptions);
191+
192+
var dir = Path.GetDirectoryName(_filePath);
193+
if (dir != null && !_fs.DirectoryExists(dir))
194+
_fs.CreateDirectory(dir);
195+
196+
// Atomic write: unique temp file then rename. Keep the registry lock
197+
// through the move so concurrent saves cannot publish stale snapshots.
198+
var tempPath = $"{_filePath}.{Guid.NewGuid():N}.tmp";
199+
try
200+
{
201+
_fs.WriteAllText(tempPath, json);
202+
File.Move(tempPath, _filePath, overwrite: true);
203+
}
204+
catch
205+
{
206+
TryDeleteTempFile(tempPath);
207+
throw;
168208
}
169209
}
170210

‎tests/OpenClaw.Connection.Tests/GatewayConnectionManagerTests.cs‎

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3337,6 +3337,29 @@ public void CopyFile(string source, string destination, bool overwrite) =>
33373337
public void DeleteFile(string path) => File.Delete(path);
33383338
}
33393339

3340+
private sealed class FailOnceWriteFileSystem : IFileSystem
3341+
{
3342+
private int _writeAttempts;
3343+
3344+
public int WriteAttempts => Volatile.Read(ref _writeAttempts);
3345+
public bool FileExists(string path) => File.Exists(path);
3346+
public string ReadAllText(string path) => File.ReadAllText(path);
3347+
3348+
public void WriteAllText(string path, string content)
3349+
{
3350+
if (Interlocked.Increment(ref _writeAttempts) == 1)
3351+
throw new UnauthorizedAccessException("simulated transient access denial");
3352+
3353+
File.WriteAllText(path, content);
3354+
}
3355+
3356+
public void CreateDirectory(string path) => Directory.CreateDirectory(path);
3357+
public bool DirectoryExists(string path) => Directory.Exists(path);
3358+
public void CopyFile(string source, string destination, bool overwrite) =>
3359+
File.Copy(source, destination, overwrite);
3360+
public void DeleteFile(string path) => File.Delete(path);
3361+
}
3362+
33403363
internal sealed class MockLifecycle : IGatewayClientLifecycle
33413364
{
33423365
private readonly MockGatewayClient _client;
@@ -3603,6 +3626,51 @@ public async Task NodeDeviceTokenReceived_ClearsBootstrapWhenNodeTokenBecomesDur
36033626
await WaitUntilAsync(() => _registry.GetById("gw-1")?.BootstrapToken == null);
36043627
}
36053628

3629+
[Fact]
3630+
public async Task DeviceTokenReceived_BootstrapClearSaveFailure_RemainsRetryable()
3631+
{
3632+
var dataDir = Path.Combine(_tempDir, "bootstrap-clear-retry");
3633+
var fs = new FailOnceWriteFileSystem();
3634+
var registry = new GatewayRegistry(dataDir, fs);
3635+
registry.AddOrUpdate(new GatewayRecord
3636+
{
3637+
Id = "gw-1",
3638+
Url = "wss://test",
3639+
BootstrapToken = "bs-secret"
3640+
});
3641+
registry.SetActive("gw-1");
3642+
3643+
var identityDir = registry.GetIdentityDirectory("gw-1");
3644+
var identity = new DeviceIdentity(identityDir, NullLogger.Instance);
3645+
identity.Initialize();
3646+
identity.StoreDeviceTokenForRole("operator", "op-device-token", ["operator.read"]);
3647+
identity.StoreDeviceTokenForRole("node", "node-device-token");
3648+
3649+
var resolver = new MockCredentialResolver
3650+
{
3651+
OperatorCredential = new GatewayCredential("tok", false, "test")
3652+
};
3653+
var factory = new MockClientFactory();
3654+
using var manager = new GatewayConnectionManager(
3655+
resolver,
3656+
factory,
3657+
registry,
3658+
NullLogger.Instance);
3659+
3660+
await manager.ConnectAsync("gw-1");
3661+
var lifecycle = factory.CreatedClients[0];
3662+
3663+
lifecycle.SimulateDeviceTokenReceived("op-device-token", "operator", ["operator.read"]);
3664+
await WaitUntilAsync(() => fs.WriteAttempts >= 1);
3665+
3666+
Assert.Equal("bs-secret", registry.GetById("gw-1")?.BootstrapToken);
3667+
3668+
lifecycle.SimulateDeviceTokenReceived("op-device-token", "operator", ["operator.read"]);
3669+
await WaitUntilAsync(() => registry.GetById("gw-1")?.BootstrapToken == null);
3670+
3671+
Assert.Equal(2, fs.WriteAttempts);
3672+
}
3673+
36063674
[Fact]
36073675
public async Task DeviceTokenReceived_NodeRole_WhenBootstrapAlreadyNull_Succeeds()
36083676
{

0 commit comments

Comments
 (0)