Serialize Android registration transfer with diagnostics

This commit is contained in:
Andrei Smaliak 2026-11-11 16:14:10 +01:00
parent 8b9afef36d
commit af32f6ed75
4 changed files with 48 additions and 4 deletions

View File

@ -21,6 +21,7 @@ final class AndroidClient implements AutoCloseable {
private volatile String problem = "Loading client registration";
private volatile boolean closed;
private final java.util.concurrent.locks.ReentrantLock operation = new java.util.concurrent.locks.ReentrantLock();
private final java.util.concurrent.atomic.AtomicBoolean transferInProgress = new java.util.concurrent.atomic.AtomicBoolean();
AndroidClient(Context context) { this.context = context; }
void start() { sampler.scheduleWithFixedDelay(() -> { if(operation.tryLock())try{sample();}finally{operation.unlock();} },0,15,TimeUnit.SECONDS); }
String version() { try { return context.getPackageManager().getPackageInfo(PACKAGE,0).versionName; } catch(Exception e) { return ""; } }
@ -52,15 +53,27 @@ final class AndroidClient implements AutoCloseable {
.put("capability_reason","Android supports transfer of an enrolled device. Initial registration and reset are performed in EVAx10 locally.");
registration=next; problem="";
} else problem="";
} catch(Exception e) { android.util.Log.w("EvaxClient", e.getClass().getSimpleName()+" "+java.util.Arrays.toString(e.getStackTrace())); problem="Client settings channel is unavailable ("+e.getClass().getSimpleName()+")"; }
} catch(Exception e) {
android.util.Log.w("EvaxClient", e.getClass().getSimpleName()+" "+java.util.Arrays.toString(e.getStackTrace()));
problem=connectionProblem(e);
}
sampledAt=System.currentTimeMillis();
}
private static String connectionProblem(Exception error) {
if(error instanceof TimeoutException)
return "EVAx10 Client did not answer on its MQTT settings channel. Its saved registration and active MQTT identity may differ; complete registration in EVAx10 Settings > Connection, then refresh status.";
String message=error.getMessage()==null?"":error.getMessage();
if(message.contains("Cached broker configuration does not match current registration"))
return "EVAx10 Client registration does not match its active MQTT identity. Complete registration in EVAx10 Settings > Connection, then refresh status.";
return "EVAx10 Client settings channel is unavailable. Start the client and refresh status.";
}
JSONObject registration() throws Exception {
JSONObject result = new JSONObject(registration.toString());
if(!problem.isEmpty() || System.currentTimeMillis()-sampledAt>60000) {
result.put("registered",false).put("logged",false).put("status","error")
.put("warning",problem.isEmpty()?"Client diagnostics expired":problem)
.put("capabilities",obj("can_register",false,"can_reset",false));
.put("capabilities",obj("can_register",false,"can_reset",false))
.put("capability_reason",problem.isEmpty()?"Refresh client diagnostics before registration.":problem);
}
result.put("ok",true); return result;
}
@ -77,8 +90,12 @@ final class AndroidClient implements AutoCloseable {
JSONObject status() throws Exception { return obj("ok",true,"service",service(),"registration",registration()); }
JSONObject runtime() throws Exception { return obj("ok",true,"current_time",AndroidPlatform.timestamp(System.currentTimeMillis()),"service_state",service().optString("state")); }
JSONObject transfer(JSONObject input) throws Exception {
if(!operation.tryLock())throw new IllegalStateException("Client operation already in progress");
if(!transferInProgress.compareAndSet(false,true))throw new IllegalStateException("Registration transfer already in progress");
boolean locked=false;
try {
// A periodic status sample uses the same MQTT channel. Wait for that
// short read to finish instead of reporting a false transfer conflict.
operation.lockInterruptibly();locked=true;
String target=input.optString("host","").trim(); if(!target.contains("://"))target="https://"+target;
URI uri=new URI(target);
if(!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost()==null || uri.getUserInfo()!=null || uri.getQuery()!=null || uri.getFragment()!=null || !(uri.getPath().isEmpty()||"/".equals(uri.getPath())))
@ -105,7 +122,7 @@ final class AndroidClient implements AutoCloseable {
}
throw new IllegalStateException("Registration transfer was not confirmed; check the client. The old registration is not overwritten by Console.");
}
} finally { operation.unlock(); }
} finally { if(locked)operation.unlock();transferInProgress.set(false); }
}
static boolean sameServer(String a,String b) { return a.replaceAll("/+$","").equalsIgnoreCase(b.replaceAll("/+$","")); }
static boolean same(ClientRegistration a,ClientRegistration b) { return a.registered==b.registered && a.user.equals(b.user) && a.server.equals(b.server) && a.password.equals(b.password); }

View File

@ -30,4 +30,15 @@ class EmbeddedContract(unittest.TestCase):
self.assertIn('android:process=":console"',source)
self.assertIn('assets/evaxconsole/',source)
self.assertIn('sha256',source)
def test_registration_waits_for_diagnostics_but_rejects_a_second_transfer(self):
source=(SRC/'AndroidClient.java').read_text()
self.assertIn('transferInProgress.compareAndSet(false,true)',source)
self.assertIn('operation.lockInterruptibly()',source)
self.assertIn('if(locked)operation.unlock();transferInProgress.set(false)',source)
self.assertNotIn('if(!operation.tryLock())throw new IllegalStateException("Client operation already in progress")',source)
def test_mqtt_timeout_reports_identity_recovery_without_enabling_register(self):
source=(SRC/'AndroidClient.java').read_text()
self.assertIn('error instanceof TimeoutException',source)
self.assertIn('saved registration and active MQTT identity may differ',source)
self.assertIn('.put("capability_reason",problem.isEmpty()',source)
if __name__=='__main__':unittest.main()

View File

@ -18,6 +18,9 @@ class SharedConsoleContract(unittest.TestCase):
self.assertIn('card.capabilities.desktop_mode !== false',ui)
self.assertIn('card.capabilities.pulse_audio !== false',ui)
self.assertIn('registration.capabilities.can_register === false',ui)
self.assertIn('registration.status === "error"',ui)
self.assertIn('if (!itscreenCanRegister(registration))',ui)
self.assertIn('current.capability_reason || state.itscreen.error',ui)
self.assertIn('capabilities.logs === false ? "" : renderItscreenLogsCard()',ui)
def test_registration_stays_client_owned(self):
adapter=(ROOT/'android_console/src/com/iomatex/console/AndroidClient.java').read_text()

View File

@ -1798,6 +1798,7 @@
function itscreenCanRegister(registration) {
if (state.itscreen.busyAction || state.itscreen.loading) return false;
if (state.itscreen.error || (registration && registration.status === "error")) return false;
if (registration && registration.capabilities && registration.capabilities.can_register === false) return false;
if (itscreenHostValidationError()) return false;
if (!(registration && registration.registered)) return true;
@ -5858,6 +5859,18 @@
window.__itscreenRegister = async function () {
if (state.itscreen.busyAction) return;
const registration = itscreenRegistration();
if (!itscreenCanRegister(registration)) {
await loadItscreenInitialData({ force: true, maxAgeMs: 0 });
await loadItscreenRegistration({ force: true, maxAgeMs: 0 });
const current = itscreenRegistration();
if (!itscreenCanRegister(current)) {
await showRegistrationWarning(
t("Registration is unavailable"),
current.capability_reason || state.itscreen.error || t("Refresh client status and try again.")
);
return;
}
}
const targetAddress = itscreenResolvedHost();
const currentAddress = textValue(registration && (registration.server || registration.host), "");
const changingServer = !!(registration && registration.registered && comparableServerAddress(targetAddress) !== comparableServerAddress(currentAddress));