2026-07-25 20:35:13 +02:00
|
|
|
"""Subprocess wrapper around garminconnect, spoken to over newline-delimited
|
|
|
|
|
JSON on stdin/stdout by geniusrund's internal/garmin package. See
|
|
|
|
|
docs/superpowers/specs/2026-07-25-garmin-direct-wrapper-design.md."""
|
|
|
|
|
|
|
|
|
|
import json
|
|
|
|
|
import os
|
|
|
|
|
import queue
|
|
|
|
|
import sys
|
|
|
|
|
import threading
|
|
|
|
|
import traceback
|
|
|
|
|
|
2026-07-27 18:50:43 +02:00
|
|
|
from garminconnect import Garmin, GarminConnectNotFoundError
|
2026-07-25 20:35:13 +02:00
|
|
|
|
2026-07-26 21:25:53 +02:00
|
|
|
TOKENSTORE = os.path.expanduser(os.environ.get("GARMIN_TOKENSTORE", "~/.garmin"))
|
2026-07-25 20:35:13 +02:00
|
|
|
|
|
|
|
|
_client = None
|
|
|
|
|
_auth_state = "unauthenticated"
|
|
|
|
|
_mfa_input_queue = queue.Queue()
|
|
|
|
|
_login_result_queue = queue.Queue()
|
2026-07-26 21:25:53 +02:00
|
|
|
# Set the first time this subprocess attempts any login, whichever path
|
|
|
|
|
# gets there first (see _handle_call's lazy call and _handle_authenticate) --
|
|
|
|
|
# guarantees _startup_login runs at most once per subprocess lifetime, and
|
|
|
|
|
# never at all once an explicit authenticate has been attempted.
|
|
|
|
|
_startup_login_attempted = False
|
2026-07-25 20:35:13 +02:00
|
|
|
|
|
|
|
|
|
2026-08-04 16:42:25 +02:00
|
|
|
def _log(level, msg, **attrs):
|
|
|
|
|
"""Emit one JSON log line on stderr. internal/garmin/client.go reads
|
|
|
|
|
stderr line by line and re-emits these through the Go application
|
|
|
|
|
logger, so the backend's combined output stays a single JSON stream --
|
|
|
|
|
never print free text to stderr or stdout from this process (stdout is
|
|
|
|
|
reserved for the request/response protocol)."""
|
|
|
|
|
entry = {"level": level, "msg": msg}
|
|
|
|
|
entry.update(attrs)
|
|
|
|
|
print(json.dumps(entry), file=sys.stderr, flush=True)
|
2026-07-25 20:35:13 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def _prompt_mfa():
|
2026-08-04 16:42:25 +02:00
|
|
|
_log("info", "garminconnect invoked prompt_mfa() -- this is a REAL MFA challenge from Garmin")
|
2026-07-25 20:35:13 +02:00
|
|
|
code = _mfa_input_queue.get(timeout=300)
|
2026-08-04 16:42:25 +02:00
|
|
|
_log("debug", "prompt_mfa() handing code back to garminconnect", code_length=len(code))
|
2026-07-25 20:35:13 +02:00
|
|
|
return code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _startup_login():
|
2026-07-26 21:25:53 +02:00
|
|
|
"""Silently resume a cached tokenstore session, so a freshly
|
|
|
|
|
(re)spawned subprocess can already be authenticated for a data 'call'
|
|
|
|
|
that never goes through the explicit authenticate command -- e.g.
|
|
|
|
|
"Sync now" reaching an already-connected user's client right after a
|
|
|
|
|
backend restart cleared the in-memory cache.
|
|
|
|
|
|
|
|
|
|
Called lazily (see _handle_call), at most once per subprocess lifetime,
|
|
|
|
|
and only if nothing has explicitly called authenticate first. Running
|
|
|
|
|
it unconditionally at process start used to be actively counterproductive
|
|
|
|
|
whenever the very first command actually was authenticate: on success it
|
|
|
|
|
just duplicated a login _handle_authenticate was about to redo anyway
|
|
|
|
|
(it always rebuilds _client from scratch), and on failure it was a
|
|
|
|
|
wasted, unauthenticated hit against Garmin's servers moments before the
|
|
|
|
|
real attempt -- extra load that only makes rate-limiting worse.
|
2026-07-25 21:43:52 +02:00
|
|
|
|
|
|
|
|
Bounded to the same 10s timeout as _handle_authenticate: the actual
|
|
|
|
|
login runs on a background daemon thread, and this function waits up
|
2026-07-26 21:25:53 +02:00
|
|
|
to 10s for it before returning either way, so a slow/rate-limited
|
|
|
|
|
Garmin login can never block the caller indefinitely -- if it times
|
|
|
|
|
out, the thread keeps running and will update _auth_state whenever it
|
|
|
|
|
eventually finishes (success or failure), just without wedging the
|
|
|
|
|
whole subprocess unresponsive in the meantime.
|
2026-07-25 21:52:48 +02:00
|
|
|
|
|
|
|
|
Deliberately uses its own private, function-local result queue rather
|
|
|
|
|
than the module-level _login_result_queue that _handle_authenticate and
|
|
|
|
|
_handle_complete_mfa share -- those two are legitimately two halves of
|
|
|
|
|
one explicit, MFA-capable login flow and must share a queue for the MFA
|
|
|
|
|
handoff to work, but this is a plain background tokenstore resume with
|
|
|
|
|
no MFA involved. Sharing the queue here would let this thread's stale
|
|
|
|
|
result (arriving after the 10s timeout below) be dequeued by an
|
|
|
|
|
unrelated, later authenticate/complete_mfa call instead of that call's
|
|
|
|
|
own fresh result."""
|
2026-07-25 20:35:13 +02:00
|
|
|
global _client, _auth_state
|
|
|
|
|
email = os.environ.get("GARMIN_EMAIL")
|
|
|
|
|
password = os.environ.get("GARMIN_PASSWORD")
|
|
|
|
|
if not email or not password:
|
|
|
|
|
return
|
2026-07-25 21:43:52 +02:00
|
|
|
|
|
|
|
|
_client = Garmin(email, password)
|
2026-07-25 21:52:48 +02:00
|
|
|
result_queue = queue.Queue() # private to this call, never shared with authenticate/complete_mfa
|
2026-07-25 21:43:52 +02:00
|
|
|
|
|
|
|
|
def _do_login():
|
|
|
|
|
try:
|
|
|
|
|
_client.login(tokenstore=TOKENSTORE)
|
2026-07-25 21:52:48 +02:00
|
|
|
result_queue.put(("success", None))
|
2026-07-25 21:43:52 +02:00
|
|
|
except Exception as exc:
|
2026-07-25 21:52:48 +02:00
|
|
|
result_queue.put(("error", str(exc)))
|
2026-07-25 21:43:52 +02:00
|
|
|
|
|
|
|
|
threading.Thread(target=_do_login, daemon=True).start()
|
|
|
|
|
|
2026-07-25 20:35:13 +02:00
|
|
|
try:
|
2026-07-25 21:52:48 +02:00
|
|
|
status, err = result_queue.get(timeout=10)
|
2026-07-25 21:43:52 +02:00
|
|
|
if status == "success":
|
|
|
|
|
_auth_state = "authenticated"
|
|
|
|
|
else:
|
2026-08-04 16:42:25 +02:00
|
|
|
_log("warn", "startup tokenstore login failed", error=err)
|
2026-07-25 21:43:52 +02:00
|
|
|
_auth_state = "unauthenticated"
|
|
|
|
|
except queue.Empty:
|
2026-08-04 16:42:25 +02:00
|
|
|
_log(
|
|
|
|
|
"warn",
|
2026-07-25 21:43:52 +02:00
|
|
|
"startup tokenstore login hit the 10s timeout -- still running in the "
|
2026-08-04 16:42:25 +02:00
|
|
|
"background and will update auth state whenever it finishes",
|
2026-07-25 21:43:52 +02:00
|
|
|
)
|
2026-07-25 20:35:13 +02:00
|
|
|
_auth_state = "unauthenticated"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _handle_authenticate(_params):
|
2026-07-26 21:25:53 +02:00
|
|
|
global _client, _auth_state, _startup_login_attempted
|
|
|
|
|
# An explicit authenticate is happening (successful or not) -- the lazy
|
|
|
|
|
# startup-login fallback in _handle_call must never fire after this, it
|
|
|
|
|
# would be redundant at best and a wasted extra hit against Garmin at
|
|
|
|
|
# worst.
|
|
|
|
|
_startup_login_attempted = True
|
2026-07-25 20:35:13 +02:00
|
|
|
|
|
|
|
|
email = os.environ.get("GARMIN_EMAIL", "")
|
|
|
|
|
password = os.environ.get("GARMIN_PASSWORD", "")
|
|
|
|
|
if not email or not password:
|
|
|
|
|
return {
|
|
|
|
|
"status": "failed",
|
|
|
|
|
"message": "GARMIN_EMAIL and GARMIN_PASSWORD environment variables are required.",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
def _do_login():
|
2026-08-04 16:42:25 +02:00
|
|
|
_log("debug", "background login thread starting _client.login()", tokenstore=TOKENSTORE)
|
2026-07-25 20:35:13 +02:00
|
|
|
try:
|
|
|
|
|
_client.login(tokenstore=TOKENSTORE)
|
2026-08-04 16:42:25 +02:00
|
|
|
_log("debug", "_client.login() returned successfully")
|
2026-07-25 20:35:13 +02:00
|
|
|
_login_result_queue.put(("success", None))
|
|
|
|
|
except Exception as exc:
|
2026-08-04 16:42:25 +02:00
|
|
|
_log(
|
|
|
|
|
"error",
|
|
|
|
|
"_client.login() raised",
|
|
|
|
|
error=str(exc),
|
|
|
|
|
error_type=type(exc).__name__,
|
|
|
|
|
traceback=traceback.format_exc(),
|
|
|
|
|
)
|
2026-07-25 20:35:13 +02:00
|
|
|
_login_result_queue.put(("error", str(exc)))
|
|
|
|
|
|
|
|
|
|
_client = Garmin(email, password)
|
|
|
|
|
_client.prompt_mfa = _prompt_mfa
|
|
|
|
|
threading.Thread(target=_do_login, daemon=True).start()
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
status, err = _login_result_queue.get(timeout=10)
|
2026-08-04 16:42:25 +02:00
|
|
|
_log("debug", "authenticate got result within 10s timeout", status=status)
|
2026-07-25 20:35:13 +02:00
|
|
|
if status == "success":
|
|
|
|
|
_auth_state = "authenticated"
|
|
|
|
|
return {"status": "success", "message": "Authenticated successfully."}
|
|
|
|
|
return {"status": "failed", "message": f"Authentication failed: {err}"}
|
|
|
|
|
except queue.Empty:
|
2026-08-04 16:42:25 +02:00
|
|
|
_log(
|
|
|
|
|
"warn",
|
2026-07-25 20:35:13 +02:00
|
|
|
"authenticate hit the 10s timeout with no result yet -- reporting mfa_required, "
|
|
|
|
|
"but this does NOT necessarily mean prompt_mfa() was actually invoked; check "
|
2026-08-04 16:42:25 +02:00
|
|
|
"whether the 'REAL MFA challenge' log line above appears to tell real MFA "
|
|
|
|
|
"apart from a merely slow login.",
|
2026-07-25 20:35:13 +02:00
|
|
|
)
|
|
|
|
|
_auth_state = "mfa_pending"
|
|
|
|
|
return {
|
|
|
|
|
"status": "mfa_required",
|
|
|
|
|
"message": "MFA required. Garmin has sent a verification code to your registered email or phone.",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _handle_complete_mfa(params):
|
|
|
|
|
global _auth_state
|
|
|
|
|
|
|
|
|
|
if _auth_state != "mfa_pending":
|
|
|
|
|
return {"status": "failed", "message": "No MFA in progress. Call authenticate first."}
|
|
|
|
|
|
|
|
|
|
code = params["code"]
|
2026-08-04 16:42:25 +02:00
|
|
|
_log("debug", "complete_mfa received a code, pushing to mfa queue", code_length=len(code))
|
2026-07-25 20:35:13 +02:00
|
|
|
_mfa_input_queue.put(code)
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
status, err = _login_result_queue.get(timeout=30)
|
2026-08-04 16:42:25 +02:00
|
|
|
_log("debug", "complete_mfa got result", status=status, error=err)
|
2026-07-25 20:35:13 +02:00
|
|
|
if status == "success":
|
|
|
|
|
_auth_state = "authenticated"
|
|
|
|
|
return {"status": "success", "message": "MFA accepted. Authenticated successfully."}
|
|
|
|
|
return {"status": "failed", "message": f"Authentication failed after MFA: {err}"}
|
|
|
|
|
except queue.Empty:
|
|
|
|
|
_auth_state = "unauthenticated"
|
|
|
|
|
return {
|
|
|
|
|
"status": "failed",
|
|
|
|
|
"message": "Timed out waiting for authentication to complete. Call authenticate again.",
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _handle_call(params):
|
2026-07-26 21:25:53 +02:00
|
|
|
global _startup_login_attempted
|
|
|
|
|
if _auth_state != "authenticated" and not _startup_login_attempted:
|
|
|
|
|
_startup_login_attempted = True
|
|
|
|
|
_startup_login()
|
2026-07-25 20:35:13 +02:00
|
|
|
if _auth_state != "authenticated":
|
|
|
|
|
raise RuntimeError("Not authenticated. Call authenticate first.")
|
|
|
|
|
method = params["method"]
|
|
|
|
|
args = params.get("args") or {}
|
|
|
|
|
fn = getattr(_client, method)
|
|
|
|
|
return fn(**args)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_HANDLERS = {
|
|
|
|
|
"authenticate": _handle_authenticate,
|
|
|
|
|
"complete_mfa": _handle_complete_mfa,
|
|
|
|
|
"call": _handle_call,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def dispatch(req):
|
|
|
|
|
handler = _HANDLERS.get(req.get("cmd"))
|
|
|
|
|
if handler is None:
|
|
|
|
|
return {"id": req.get("id"), "error": f"unknown cmd {req.get('cmd')!r}"}
|
|
|
|
|
try:
|
|
|
|
|
result = handler(req.get("params") or {})
|
|
|
|
|
return {"id": req["id"], "result": result}
|
|
|
|
|
except Exception as exc:
|
2026-08-04 16:42:25 +02:00
|
|
|
# The full failure detail travels IN the response -- error text,
|
|
|
|
|
# exception class, and traceback -- so the Go side can log one
|
|
|
|
|
# complete structured record instead of correlating stderr noise.
|
|
|
|
|
resp = {
|
|
|
|
|
"id": req.get("id"),
|
|
|
|
|
"error": str(exc),
|
|
|
|
|
"error_type": type(exc).__name__,
|
|
|
|
|
"traceback": traceback.format_exc(),
|
|
|
|
|
}
|
2026-07-27 18:50:43 +02:00
|
|
|
# A 404 (e.g. get_workout_by_id for a workout deleted on Garmin's
|
|
|
|
|
# side after being linked to an activity) is definitive, not a
|
|
|
|
|
# transient failure worth retrying forever -- marked specifically so
|
|
|
|
|
# internal/garmin/client.go can tell the two apart (see
|
|
|
|
|
# docs/superpowers/specs/2026-07-27-workout-not-found-design.md).
|
|
|
|
|
if isinstance(exc, GarminConnectNotFoundError):
|
|
|
|
|
resp["not_found"] = True
|
|
|
|
|
return resp
|
2026-07-25 20:35:13 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
|
for line in sys.stdin:
|
|
|
|
|
line = line.strip()
|
|
|
|
|
if not line:
|
|
|
|
|
continue
|
2026-08-04 16:42:25 +02:00
|
|
|
try:
|
|
|
|
|
req = json.loads(line)
|
|
|
|
|
except json.JSONDecodeError as exc:
|
|
|
|
|
# A malformed request has no id to answer to -- log and keep
|
|
|
|
|
# serving rather than crashing the subprocess.
|
|
|
|
|
_log("error", "malformed request line", error=str(exc))
|
|
|
|
|
continue
|
2026-07-25 20:35:13 +02:00
|
|
|
resp = dispatch(req)
|
2026-08-04 16:42:25 +02:00
|
|
|
try:
|
|
|
|
|
print(json.dumps(resp), flush=True)
|
|
|
|
|
except (TypeError, ValueError) as exc:
|
|
|
|
|
# A non-JSON-serializable handler result must still produce a
|
|
|
|
|
# protocol response, or the Go side would block on a reply.
|
|
|
|
|
print(
|
|
|
|
|
json.dumps(
|
|
|
|
|
{
|
|
|
|
|
"id": req.get("id"),
|
|
|
|
|
"error": f"unserializable result: {exc}",
|
|
|
|
|
"error_type": type(exc).__name__,
|
|
|
|
|
}
|
|
|
|
|
),
|
|
|
|
|
flush=True,
|
|
|
|
|
)
|
2026-07-25 20:35:13 +02:00
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2026-08-04 16:42:25 +02:00
|
|
|
try:
|
|
|
|
|
main()
|
|
|
|
|
except Exception as exc: # last resort: die loudly, but still in JSON
|
|
|
|
|
_log(
|
|
|
|
|
"error",
|
|
|
|
|
"wrapper crashed",
|
|
|
|
|
error=str(exc),
|
|
|
|
|
error_type=type(exc).__name__,
|
|
|
|
|
traceback=traceback.format_exc(),
|
|
|
|
|
)
|
|
|
|
|
raise SystemExit(1)
|