reflex-hosting-cli 0.2.0a1__tar.gz → 0.2.1a1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/CHANGELOG.md +26 -3
  2. reflex_hosting_cli-0.2.1a1/PKG-INFO +44 -0
  3. reflex_hosting_cli-0.2.1a1/README.md +22 -0
  4. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/pyproject.toml +4 -5
  5. reflex_hosting_cli-0.2.1a1/src/reflex_cli/utils/deploy.py +196 -0
  6. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/utils/exceptions.py +17 -2
  7. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/utils/hosting.py +174 -29
  8. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/v2/apps.py +42 -3
  9. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/v2/auth.py +5 -2
  10. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/v2/cli.py +6 -12
  11. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/v2/project.py +6 -1
  12. reflex_hosting_cli-0.2.0a1/PKG-INFO +0 -24
  13. reflex_hosting_cli-0.2.0a1/README.md +0 -2
  14. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/.gitignore +0 -0
  15. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/news/.gitkeep +0 -0
  16. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/__init__.py +0 -0
  17. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/cli.py +0 -0
  18. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/constants/__init__.py +0 -0
  19. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/constants/base.py +0 -0
  20. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/constants/compiler.py +0 -0
  21. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/constants/hosting.py +0 -0
  22. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/constants/log_level.py +0 -0
  23. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/core/__init__.py +0 -0
  24. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/core/config.py +0 -0
  25. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/deployments.py +0 -0
  26. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/utils/__init__.py +0 -0
  27. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/utils/cli_options.py +0 -0
  28. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/utils/console.py +0 -0
  29. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/utils/dependency.py +0 -0
  30. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/utils/log.py +0 -0
  31. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/utils/output.py +0 -0
  32. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/v2/__init__.py +0 -0
  33. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/v2/deploy.py +0 -0
  34. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/v2/deployments.py +0 -0
  35. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/v2/gcp.py +0 -0
  36. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/v2/providers.py +0 -0
  37. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/v2/scan.py +0 -0
  38. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/v2/secrets.py +0 -0
  39. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/v2/utils.py +0 -0
  40. {reflex_hosting_cli-0.2.0a1 → reflex_hosting_cli-0.2.1a1}/src/reflex_cli/v2/vmtypes_regions.py +0 -0
@@ -1,8 +1,31 @@
1
- ## v0.2.0a1 (2026-10-06)
1
+ ## v0.2.1a1 (2026-10-23)
2
+
3
+ ### Bug Fixes
4
+
5
+ - The `reflex cloud project list` table shows the project tier name instead of the full tier object. Use `--json` to get the full tier. ([#7340](https://github.com/reflex-dev/reflex/issues/7340))
6
+ - Print `reflex cloud apps logs` lines as readable `timestamp [LEVEL] message` text instead of Python dicts. `--json` still prints the structured records, and `--loglevel` no longer hides the log lines. ([#7390](https://github.com/reflex-dev/reflex/issues/7390))
7
+ - Show `reflex login` guidance when initial authentication rejects an access token, including instructions to replace or remove an explicit `REFLEX_ACCESS_TOKEN` or `--token` override.
8
+ When `reflex cloud whoami` or a noninteractive cloud command cannot validate a token due to a temporary service or connection failure, suggest retrying instead of replacing credentials. ([#7434](https://github.com/reflex-dev/reflex/issues/7434))
9
+ - `reflex deploy` now waits and retries confirmed scaling conflicts with progress messages, reusing the uploaded build and preserving support for custom backend URL prefixes. It stops on unrelated failures and uncertain writes, and warns when bounds may remain changed after a failed deployment, including server errors and unreadable success responses. ([#7463](https://github.com/reflex-dev/reflex/issues/7463))
10
+ - Authentication validation now reports the HTTP status when the control plane refuses the request, and only suggests trying again later for failures that may succeed on retry (timeouts, HTTP 429 and server errors). ([#7546](https://github.com/reflex-dev/reflex/issues/7546))
11
+
12
+ ### Performance
13
+
14
+ - Speed up non-interactive deploys by skipping the provider availability request used only for the interactive provider prompt. ([#7452](https://github.com/reflex-dev/reflex/issues/7452))
15
+
16
+
17
+ ## v0.2.0 (2026-10-08)
2
18
 
3
19
  ### Breaking Changes
4
20
 
5
- - Some `reflex cloud` commands changed what they report. A refused request now exits non-zero rather than printing a `"... failed: ..."` line and exiting 0, and `--json` writes no document on that path; `apps stop`, `apps start` and `apps delete` are the ones most likely to be scripted against, and they now report their own outcome rather than echoing the server's sentence. `vmtypes` and `regions` answered a failed request with an empty listing and exit 0, which a script could not tell from a control plane that offers neither; they exit non-zero now. `apps history --json` replaces `hostname` with the deployment's `url`, reports `vm type` as the machine's name rather than an object, and reports `timestamp` as an ISO 8601 string with an offset; `apps inspect --json` drops `hostname` from `latest_deployment` the same way, the URL carrying it already. `create-token --json` replaces `expires_in_days` with `expires_at`, an ISO 8601 string or `null`, carrying the expiry the server applied rather than the duration that was asked for. `apps logs` drops its inert `--cursor` option and its `--json` document returns every line in the window rather than one page. `project role-permissions` lists permission names rather than objects. `reflex deploy` now requires a control plane that signs upload URLs; the multipart fallback for older ones is gone, and with it the "payload is too large (over 100MB)" hint, which only that path could produce. And `apps status --watch --json` reports `"success": null` when the watch stopped before the deployment ended -- it is still running, and the command did not see how it finished -- rather than answering `true` or `false` for something it does not know. ([#7207](https://github.com/reflex-dev/reflex/issues/7207))
21
+ - Some `reflex cloud` commands changed what they report: ([#7207](https://github.com/reflex-dev/reflex/issues/7207))
22
+ - A refused request exits non-zero instead of printing a `"... failed: ..."` line and exiting 0, and `--json` writes no document. This includes `vmtypes` and `regions`, which answered a failed request with an empty listing, and `apps stop`, `apps start` and `apps delete`, which now report their own outcome rather than echoing the server's message.
23
+ - `apps history --json` replaces `hostname` with the deployment's `url`, reports `vm type` as the machine's name rather than an object, and reports `timestamp` as an ISO 8601 string with an offset. `apps inspect --json` drops `hostname` from `latest_deployment`.
24
+ - `create-token --json` replaces `expires_in_days` with `expires_at`, an ISO 8601 string or `null`, carrying the expiry the server applied.
25
+ - `apps logs` drops its unused `--cursor` option, and its `--json` document returns every line in the window rather than one page.
26
+ - `apps status --watch --json` reports `"success": null` when the watch stopped before the deployment finished.
27
+ - `project role-permissions` lists permission names rather than objects.
28
+ - `reflex deploy` requires a control plane that signs upload URLs; the multipart upload fallback for older ones, and its "payload is too large (over 100MB)" hint, are gone.
6
29
  - Require Python 3.11 or newer; Python 3.10 is no longer supported. ([#7449](https://github.com/reflex-dev/reflex/issues/7449))
7
30
 
8
31
  ### Bug Fixes
@@ -18,7 +41,7 @@
18
41
 
19
42
  ### Miscellaneous
20
43
 
21
- - `reflex-hosting-cli` now talks to Reflex Build through `reflex-build-sdk` rather than its own HTTP layer, so every command shares the SDK's retries, timeouts and typed errors. While the SDK is pre-1.0, where any release may change its API, the requirement is capped to the single patch line the CLI was built against, so upgrade `reflex-hosting-cli` to move to a newer SDK rather than upgrading the SDK on its own. ([#7207](https://github.com/reflex-dev/reflex/issues/7207))
44
+ - `reflex-hosting-cli` now talks to Reflex Build through `reflex-build-sdk`, so every command shares the SDK's retries, timeouts and typed errors. While the SDK is pre-1.0, the CLI pins it to a single patch line, so upgrade `reflex-hosting-cli` to move to a newer SDK rather than upgrading the SDK on its own. ([#7207](https://github.com/reflex-dev/reflex/issues/7207))
22
45
 
23
46
 
24
47
  ## v0.1.72 (2026-09-11)
@@ -0,0 +1,44 @@
1
+ Metadata-Version: 2.5
2
+ Name: reflex-hosting-cli
3
+ Version: 0.2.1a1
4
+ Summary: Reflex Hosting CLI
5
+ Author-email: Nikhil Rao <nikhil@reflex.dev>, Alek Petuskey <alek@reflex.dev>
6
+ Maintainer-email: Simon Young <simon@reflex.dev>, Khaleel Al-Adhami <khaleel@reflex.dev>
7
+ License: Apache-2.0
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Classifier: Programming Language :: Python :: 3.13
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Classifier: Programming Language :: Python :: 3.15
14
+ Requires-Python: >=3.11
15
+ Requires-Dist: click>=8.2
16
+ Requires-Dist: httpx<1.0,>=0.25.1
17
+ Requires-Dist: packaging>=24.2
18
+ Requires-Dist: platformdirs<5.0,>=3.10.0
19
+ Requires-Dist: reflex-build-sdk[httpx]!=0.1.2,<0.1.2.post,>=0.1.1a1
20
+ Requires-Dist: rich<16,>=13
21
+ Description-Content-Type: text/markdown
22
+
23
+ # reflex-hosting-cli
24
+ Hosting CLI for Reflex.
25
+
26
+ When an app is still scaling, `reflex deploy` waits 15 seconds between confirmed
27
+ scaling refusals, for up to 7 retries to update instance bounds and 11 retries
28
+ to submit the deployment. The CLI reports each wait, and you can cancel
29
+ with Ctrl-C. Submission retries reuse the uploaded build. The SDK's usual safe
30
+ retries can add two more submission attempts, for up to 14 attempts in total;
31
+ they do not restart the scaling wait budget. The scaling sleeps total at most
32
+ 165 seconds for submission; requests and SDK backoff add to elapsed time.
33
+ Other failures, including a lost submission response, are reported without
34
+ replaying an uncertain write.
35
+ If an instance-bounds write has an uncertain outcome, including a server error,
36
+ the CLI warns that the bounds may have changed.
37
+ A success response that cannot be decoded also stops deployment with a separate
38
+ warning about bounds left changed.
39
+
40
+ If an access token is expired or rejected, run `reflex login` to authenticate
41
+ again. If you supply a token explicitly, replace it with a valid token or remove
42
+ the override before using the saved login: unset `REFLEX_ACCESS_TOKEN` or omit
43
+ `--token`. Logging in does not replace an environment variable or command-line
44
+ token. Noninteractive commands exit on rejection without opening a browser.
@@ -0,0 +1,22 @@
1
+ # reflex-hosting-cli
2
+ Hosting CLI for Reflex.
3
+
4
+ When an app is still scaling, `reflex deploy` waits 15 seconds between confirmed
5
+ scaling refusals, for up to 7 retries to update instance bounds and 11 retries
6
+ to submit the deployment. The CLI reports each wait, and you can cancel
7
+ with Ctrl-C. Submission retries reuse the uploaded build. The SDK's usual safe
8
+ retries can add two more submission attempts, for up to 14 attempts in total;
9
+ they do not restart the scaling wait budget. The scaling sleeps total at most
10
+ 165 seconds for submission; requests and SDK backoff add to elapsed time.
11
+ Other failures, including a lost submission response, are reported without
12
+ replaying an uncertain write.
13
+ If an instance-bounds write has an uncertain outcome, including a server error,
14
+ the CLI warns that the bounds may have changed.
15
+ A success response that cannot be decoded also stops deployment with a separate
16
+ warning about bounds left changed.
17
+
18
+ If an access token is expired or rejected, run `reflex login` to authenticate
19
+ again. If you supply a token explicitly, replace it with a valid token or remove
20
+ the override before using the saved login: unset `REFLEX_ACCESS_TOKEN` or omit
21
+ `--token`. Logging in does not replace an environment variable or command-line
22
+ token. Noninteractive commands exit on rejection without opening a browser.
@@ -31,11 +31,10 @@ dependencies = [
31
31
  # The SDK ships no HTTP library of its own; [httpx] points it at the one
32
32
  # `check_version` already pulls in, so the extra costs nothing to install.
33
33
  # The SDK is pre-1.0, so every release may break its API: cap at the patch
34
- # and raise all three bounds when adopting a new one. The floor admits the
35
- # workspace's dev build until the 0.1.0 alpha publishes and materialization
36
- # lifts it; the cap admits 0.1.0 and the ``0.1.1.devN`` builds that follow
37
- # its tag, but not 0.1.1 itself.
38
- "reflex-build-sdk[httpx] >=0.1.0a1,<0.1.1.post,!=0.1.1",
34
+ # and raise all three bounds when adopting a new one. The default transport
35
+ # factory requires the next SDK release; materialization lifts this dev
36
+ # floor when it publishes. The cap also admits the following dev builds.
37
+ "reflex-build-sdk[httpx] >=0.1.1a1,<0.1.2.post,!=0.1.2",
39
38
  "rich >=13,<16",
40
39
  ]
41
40
 
@@ -0,0 +1,196 @@
1
+ """Wait for confirmed scaling refusals without repeating build uploads."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import time
7
+ from collections.abc import Callable
8
+ from http import HTTPStatus
9
+ from typing import TypeVar
10
+
11
+ from reflex_build_sdk import APIStatusError, ConflictError
12
+ from reflex_build_sdk.transports import Request, Response, Transport
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ _T = TypeVar("_T")
17
+ _SCALING_RETRY_DELAY = 15
18
+ _DEPLOYMENT_SCALING_CODE = "app_scaling"
19
+ _LEGACY_DEPLOYMENT_SCALING_DETAIL = (
20
+ "the app is currently being scaled; wait for the scale to finish, then deploy again"
21
+ )
22
+
23
+
24
+ def _is_scaling_conflict(error: APIStatusError, *, url: str, code: str) -> bool:
25
+ """Identify a refusal that guarantees a write was blocked by scaling.
26
+
27
+ Args:
28
+ error: The SDK's typed refusal.
29
+ url: The endpoint's full URL on the configured backend.
30
+ code: The expected scaling refusal code.
31
+
32
+ Returns:
33
+ Whether this request was explicitly refused before applying its write.
34
+ """
35
+ if (
36
+ error.status_code != HTTPStatus.CONFLICT
37
+ or error.request.method != "POST"
38
+ or error.request.url != url
39
+ ):
40
+ return False
41
+ # Older servers use app_busy for scaling, stopping, and another deployment.
42
+ # Only the exact scaling detail guarantees the submission can be retried.
43
+ return error.code == code or (
44
+ code == _DEPLOYMENT_SCALING_CODE
45
+ and error.code == "app_busy"
46
+ and error.detail == _LEGACY_DEPLOYMENT_SCALING_DETAIL
47
+ )
48
+
49
+
50
+ def _retry_scaling_conflicts(
51
+ operation: Callable[[], _T], *, url: str, code: str, action: str, attempts: int
52
+ ) -> _T:
53
+ """Retry only writes the server explicitly refused because of scaling.
54
+
55
+ Args:
56
+ operation: The SDK operation to attempt.
57
+ url: The endpoint's full URL on the configured backend.
58
+ code: The expected scaling refusal code.
59
+ action: The action described in progress messages.
60
+ attempts: The maximum number of calls, including the initial attempt.
61
+
62
+ Returns:
63
+ The successful operation's result.
64
+
65
+ Raises:
66
+ APIStatusError: If scaling persists or the refusal is unrelated.
67
+ """
68
+ return _ScalingRetryBudget(attempts=attempts).run(
69
+ operation, url=url, code=code, action=action
70
+ )
71
+
72
+
73
+ class _ScalingRetryBudget:
74
+ """Keep scaling waits bounded across the SDK's own safe request retries."""
75
+
76
+ def __init__(self, *, attempts: int) -> None:
77
+ """Create the scaling retry budget.
78
+
79
+ Args:
80
+ attempts: The initial attempt plus the permitted scaling retries.
81
+ """
82
+ self._retries = attempts - 1
83
+ self._used = 0
84
+
85
+ def run(
86
+ self, operation: Callable[[], _T], *, url: str, code: str, action: str
87
+ ) -> _T:
88
+ """Retry a refused operation within the remaining scaling wait budget.
89
+
90
+ Args:
91
+ operation: The operation to attempt.
92
+ url: The endpoint's full URL on the configured backend.
93
+ code: The expected scaling refusal code.
94
+ action: The action described in progress messages.
95
+
96
+ Returns:
97
+ The successful operation's result.
98
+
99
+ Raises:
100
+ APIStatusError: If scaling persists or the refusal is unrelated.
101
+ """
102
+ while True:
103
+ try:
104
+ return operation()
105
+ except APIStatusError as ex:
106
+ if self._used >= self._retries or not _is_scaling_conflict(
107
+ ex, url=url, code=code
108
+ ):
109
+ raise
110
+ self._used += 1
111
+ logger.info(
112
+ f"App is being scaled; waiting {_SCALING_RETRY_DELAY} seconds before "
113
+ f"retrying {action} (scaling retry {self._used}/{self._retries})."
114
+ )
115
+ time.sleep(_SCALING_RETRY_DELAY)
116
+
117
+
118
+ class _DeploymentRetryTransport:
119
+ """Retry one deployment's refused submission using its uploaded archives.
120
+
121
+ The CLI creates a fresh upload client and transport for each deployment.
122
+ Its scaling budget is shared across the SDK's safe retries of that submission.
123
+ """
124
+
125
+ def __init__(self, transport: Transport, *, url: str) -> None:
126
+ """Wrap the transport used by a deployment's upload client.
127
+
128
+ Args:
129
+ transport: The underlying transport, closed by ``close``.
130
+ url: The exact control-plane deployment submission URL.
131
+ """
132
+ self._transport = transport
133
+ self._url = url
134
+ self._budget = _ScalingRetryBudget(attempts=12)
135
+
136
+ def send(self, request: Request) -> Response:
137
+ """Send a request, waiting only when a deployment is refused for scaling.
138
+
139
+ Args:
140
+ request: The SDK's request, including its serialized body.
141
+
142
+ Returns:
143
+ The response for the SDK to decode.
144
+
145
+ Raises:
146
+ ConflictError: If scaling persists after eleven scaling waits.
147
+ """
148
+ if (
149
+ request.method != "POST"
150
+ or request.url != self._url
151
+ or not isinstance(request.content, bytes)
152
+ ):
153
+ return self._transport.send(request)
154
+ # Submit bodies are immutable bytes. Replaying this request keeps the
155
+ # stored_build_id and avoids reserving and uploading the archives again.
156
+ return self._budget.run(
157
+ lambda: self._send_submission(request),
158
+ url=self._url,
159
+ code=_DEPLOYMENT_SCALING_CODE,
160
+ action="deployment",
161
+ )
162
+
163
+ def _send_submission(self, request: Request) -> Response:
164
+ """Turn only a confirmed scaling response into a retryable SDK error.
165
+
166
+ Args:
167
+ request: The replayable submission request.
168
+
169
+ Returns:
170
+ Any response other than a confirmed scaling refusal.
171
+
172
+ Raises:
173
+ ConflictError: If the server refused this submission for scaling.
174
+ """
175
+ response = self._transport.send(request)
176
+ if response.status_code != HTTPStatus.CONFLICT:
177
+ return response
178
+ try:
179
+ body = response.json()
180
+ except ValueError:
181
+ return response
182
+ if not isinstance(body, dict):
183
+ return response
184
+ detail = body.get("detail")
185
+ error = ConflictError(
186
+ f"409 {response.reason_phrase}: {detail}",
187
+ response=response,
188
+ detail=detail,
189
+ )
190
+ if _is_scaling_conflict(error, url=self._url, code=_DEPLOYMENT_SCALING_CODE):
191
+ raise error
192
+ return response
193
+
194
+ def close(self) -> None:
195
+ """Release the wrapped transport's connections."""
196
+ self._transport.close()
@@ -16,19 +16,34 @@ class TokenValidationError(ReflexHostingCliError):
16
16
  surface it for correlation with server-side logs.
17
17
  """
18
18
 
19
- def __init__(self, message: str, request_id: str = ""):
19
+ def __init__(self, message: str, request_id: str = "", retryable: bool = True):
20
20
  """Initialize the error.
21
21
 
22
22
  Args:
23
23
  message: The error message.
24
24
  request_id: The X-Request-ID header sent with the failed request.
25
+ retryable: Whether trying again later may succeed. False when the
26
+ control plane refused the request itself.
25
27
  """
26
28
  super().__init__(message)
27
29
  self.request_id = request_id
30
+ self.retryable = retryable
28
31
 
29
32
 
30
33
  class TokenAccessDeniedError(TokenValidationError, ValueError):
31
- """Raised when the control plane rejects the access token."""
34
+ """Raised when the control plane rejects the access token.
35
+
36
+ Trying again with the same token cannot succeed, so it is never retryable.
37
+ """
38
+
39
+ def __init__(self, message: str, request_id: str = ""):
40
+ """Initialize the error.
41
+
42
+ Args:
43
+ message: The error message.
44
+ request_id: The X-Request-ID header sent with the failed request.
45
+ """
46
+ super().__init__(message, request_id, retryable=False)
32
47
 
33
48
 
34
49
  class GetAppError(ReflexHostingCliError):
@@ -32,6 +32,7 @@ import click
32
32
  from reflex_build_sdk import (
33
33
  APIConnectionError,
34
34
  APIError,
35
+ APIResponseValidationError,
35
36
  APIStatusError,
36
37
  AuthenticationError,
37
38
  DeploymentFailedError,
@@ -44,12 +45,18 @@ from reflex_build_sdk import (
44
45
  )
45
46
  from reflex_build_sdk._decode import json_key
46
47
  from reflex_build_sdk._deploy import status_message_outcome
48
+ from reflex_build_sdk.transports import default_transport
47
49
  from reflex_build_sdk.types import DeploymentReport, LoginRequest, Me
48
50
 
49
51
  import reflex_cli.constants as constants
50
52
  from reflex_cli.core.config import Config, RegionOption
51
53
  from reflex_cli.utils import console, log
52
54
  from reflex_cli.utils.dependency import is_valid_url
55
+ from reflex_cli.utils.deploy import (
56
+ _DeploymentRetryTransport,
57
+ _is_scaling_conflict,
58
+ _retry_scaling_conflicts,
59
+ )
53
60
  from reflex_cli.utils.exceptions import (
54
61
  ResponseError,
55
62
  ScaleAppError,
@@ -465,8 +472,8 @@ def get_existing_access_token_with_source() -> tuple[str, TokenSource]:
465
472
  return "", TokenSource.NONE
466
473
 
467
474
 
468
- def rejected_token_message(source: TokenSource, err: TokenValidationError) -> str:
469
- """Describe a token the control plane would not validate.
475
+ def rejected_token_message(source: TokenSource, err: TokenAccessDeniedError) -> str:
476
+ """Describe a rejected token and how to replace it for its source.
470
477
 
471
478
  Args:
472
479
  source: Where the token was loaded from.
@@ -475,9 +482,44 @@ def rejected_token_message(source: TokenSource, err: TokenValidationError) -> st
475
482
  Returns:
476
483
  The message to report.
477
484
  """
485
+ if source is TokenSource.ENVIRONMENT:
486
+ recovery = (
487
+ "Replace REFLEX_ACCESS_TOKEN with a valid token, or unset it and run "
488
+ "`reflex login` to authenticate."
489
+ )
490
+ elif source is TokenSource.OPTION:
491
+ recovery = (
492
+ "Replace the --token value with a valid token, or omit --token and run "
493
+ "`reflex login` to authenticate."
494
+ )
495
+ else:
496
+ recovery = "Run `reflex login` to authenticate."
478
497
  return (
479
498
  f"The access token from the {source.value} was rejected: {err} "
480
- f"(auth request id: {err.request_id})"
499
+ f"(auth request id: {err.request_id}). {recovery}"
500
+ )
501
+
502
+
503
+ def _token_validation_failure_message(
504
+ source: TokenSource, err: TokenValidationError
505
+ ) -> str:
506
+ """Describe a validation failure, suggesting a retry only if one may help.
507
+
508
+ Args:
509
+ source: Where the token was loaded from.
510
+ err: The validation error.
511
+
512
+ Returns:
513
+ The message to report.
514
+ """
515
+ if not err.retryable:
516
+ return (
517
+ f"Unable to validate the access token from the {source.value}: "
518
+ f"{err} (auth request id: {err.request_id})."
519
+ )
520
+ return (
521
+ f"Unable to validate the access token from the {source.value}: "
522
+ f"{err} (auth request id: {err.request_id}). Please try again later."
481
523
  )
482
524
 
483
525
 
@@ -720,6 +762,26 @@ def new_client(token: str | None = None) -> ReflexBuild:
720
762
  )
721
763
 
722
764
 
765
+ def _is_retryable_status(status_code: int) -> bool:
766
+ """Tell whether a refused request may succeed if sent again later.
767
+
768
+ Args:
769
+ status_code: The status the control plane answered with.
770
+
771
+ Returns:
772
+ True for a timeout, a throttled request or a server error.
773
+ """
774
+ return (
775
+ status_code
776
+ in (
777
+ HTTPStatus.REQUEST_TIMEOUT,
778
+ HTTPStatus.TOO_EARLY,
779
+ HTTPStatus.TOO_MANY_REQUESTS,
780
+ )
781
+ or status_code >= HTTPStatus.INTERNAL_SERVER_ERROR
782
+ )
783
+
784
+
723
785
  def _validate(token: str, api: ReflexBuild | None = None) -> Me:
724
786
  """Ask the control plane who an access token authenticates as.
725
787
 
@@ -733,7 +795,9 @@ def _validate(token: str, api: ReflexBuild | None = None) -> Me:
733
795
  Raises:
734
796
  TokenAccessDeniedError: If the token was refused.
735
797
  TokenValidationError: If the answer could not be had -- a timeout, a
736
- failed request, a server error. These are worth trying again.
798
+ failed request, a server error, or a request the control plane
799
+ refused. Only the first kinds are worth trying again, as
800
+ ``retryable`` says.
737
801
 
738
802
  """
739
803
  global _last_auth_request_id
@@ -749,10 +813,16 @@ def _validate(token: str, api: ReflexBuild | None = None) -> Me:
749
813
  raise TokenAccessDeniedError(
750
814
  "access denied", request_id=ex.request_id
751
815
  ) from ex
816
+ retryable = _is_retryable_status(ex.status_code)
817
+ # The API's explanation is not shown or logged: it may echo the
818
+ # request, including the token.
819
+ message = f"HTTP {ex.status_code}"
752
820
  logger.debug(
753
- f"Unable to validate the token due to: {ex} (request id: {ex.request_id})"
821
+ f"Unable to validate the token due to: {message} (request id: {ex.request_id})"
754
822
  )
755
- raise TokenValidationError("server error", request_id=ex.request_id) from ex
823
+ raise TokenValidationError(
824
+ message, request_id=ex.request_id, retryable=retryable
825
+ ) from ex
756
826
  except APIError as ex:
757
827
  _last_auth_request_id = ex.request_id
758
828
  logger.debug(
@@ -784,7 +854,8 @@ def identity_as_dict(me: Me) -> dict[str, Any]:
784
854
  }
785
855
 
786
856
 
787
- def upload_client(client: AuthenticatedClient) -> ReflexBuild:
857
+ @contextlib.contextmanager
858
+ def upload_client(client: AuthenticatedClient) -> Iterator[ReflexBuild]:
788
859
  """Build a client whose timeouts suit pushing a build's archives.
789
860
 
790
861
  The SDK's defaults are sized for API calls. An archive is not one: it is
@@ -794,15 +865,25 @@ def upload_client(client: AuthenticatedClient) -> ReflexBuild:
794
865
  Args:
795
866
  client: The authenticated client the deploy is running under.
796
867
 
797
- Returns:
798
- A client to submit the deployment with. The caller closes it.
868
+ Yields:
869
+ A client that retries confirmed scaling refusals without reuploading.
799
870
 
800
871
  """
801
- return ReflexBuild(
802
- token=client.token,
803
- base_url=constants.Hosting.HOSTING_SERVICE,
804
- timeout=UPLOAD_IO_TIMEOUT.total_seconds(),
805
- )
872
+ base_url = constants.Hosting.HOSTING_SERVICE.rstrip("/")
873
+ with (
874
+ contextlib.closing(
875
+ _DeploymentRetryTransport(
876
+ default_transport(), url=f"{base_url}/api/v1/deployments"
877
+ )
878
+ ) as transport,
879
+ ReflexBuild(
880
+ token=client.token,
881
+ base_url=base_url,
882
+ timeout=UPLOAD_IO_TIMEOUT.total_seconds(),
883
+ transport=transport,
884
+ ) as uploader,
885
+ ):
886
+ yield uploader
806
887
 
807
888
 
808
889
  def validate_token(token: str) -> dict[str, Any]:
@@ -920,10 +1001,7 @@ def get_authenticated_client(
920
1001
  raise click.exceptions.Exit(1) from err
921
1002
  except TokenValidationError as err:
922
1003
  api.close()
923
- logger.error(
924
- f"Unable to validate the access token from the {source.value}: "
925
- f"{err} (auth request id: {err.request_id})"
926
- )
1004
+ logger.error(_token_validation_failure_message(source, err))
927
1005
  raise click.exceptions.Exit(1) from err
928
1006
  return AuthenticatedClient(api, me)
929
1007
 
@@ -1209,11 +1287,27 @@ def find_gcp_connection(
1209
1287
  return None
1210
1288
 
1211
1289
 
1290
+ def _warn_unconfirmed_instance_bounds(app_name: str) -> None:
1291
+ """Warn when a bounds write may have committed without acknowledgement.
1292
+
1293
+ Args:
1294
+ app_name: The app whose instance bounds were being updated.
1295
+ """
1296
+ logger.warning(
1297
+ f"Could not confirm the instance bounds of "
1298
+ f"'{app_name}'; they may or may not have been applied. "
1299
+ "Check the app in the Reflex Cloud dashboard before relying "
1300
+ "on its scaling."
1301
+ )
1302
+
1303
+
1212
1304
  def set_instance_bounds(
1213
1305
  app_id: str,
1214
1306
  client: AuthenticatedClient,
1215
1307
  min_instances: int | None = None,
1216
1308
  max_instances: int | None = None,
1309
+ *,
1310
+ retry_scaling: bool = False,
1217
1311
  ) -> str | None:
1218
1312
  """Set the autoscaling instance bounds on an app.
1219
1313
 
@@ -1227,23 +1321,74 @@ def set_instance_bounds(
1227
1321
  client: The authenticated client.
1228
1322
  min_instances: The minimum number of instances to keep running.
1229
1323
  max_instances: The maximum number of instances to scale out to.
1324
+ retry_scaling: Whether to retry confirmed scaling refusals, up to eight
1325
+ attempts with a 15-second wait between attempts.
1230
1326
 
1231
1327
  Returns:
1232
1328
  None on success, or a ``"set instance bounds failed: ..."`` string on
1233
- error (validation, unsupported platform, or a scale already running).
1329
+ a non-retryable refusal (validation or unsupported platform).
1330
+
1331
+ Raises:
1332
+ APIStatusError: If scaling refused the write or a server error left its
1333
+ outcome unknown.
1334
+ APIConnectionError: If contact is lost while reading or updating bounds.
1335
+ APIResponseValidationError: If the response could not be decoded.
1234
1336
 
1235
1337
  """
1236
- try:
1338
+ bounds_url = f"{client.api.base_url}/api/v1/apps/{app_id}/instance_bounds"
1339
+ scaling_code = "instance_bounds_scale_conflict"
1340
+
1341
+ def update_bounds() -> None:
1342
+ """Update the requested bounds, preserving the latest unspecified bound."""
1237
1343
  current = client.api.apps.get(app_id)
1238
- client.api.apps.set_instance_bounds(
1239
- app_id,
1240
- min_instances=current.min_instances
1241
- if min_instances is None
1242
- else min_instances,
1243
- max_instances=current.max_instances
1244
- if max_instances is None
1245
- else max_instances,
1246
- )
1344
+ try:
1345
+ client.api.apps.set_instance_bounds(
1346
+ app_id,
1347
+ min_instances=current.min_instances
1348
+ if min_instances is None
1349
+ else min_instances,
1350
+ max_instances=current.max_instances
1351
+ if max_instances is None
1352
+ else max_instances,
1353
+ )
1354
+ except MissingTokenError:
1355
+ raise
1356
+ except APIResponseValidationError:
1357
+ logger.warning(
1358
+ f"The server reported success setting the instance bounds of "
1359
+ f"'{current.name}', but its response could not be decoded. "
1360
+ "The bounds may have changed even though this deploy stopped. "
1361
+ "Check the app in the Reflex Cloud dashboard before relying "
1362
+ "on its scaling."
1363
+ )
1364
+ raise
1365
+ except APIStatusError as ex:
1366
+ if ex.status_code >= 500:
1367
+ _warn_unconfirmed_instance_bounds(current.name)
1368
+ raise
1369
+ except BaseException:
1370
+ _warn_unconfirmed_instance_bounds(current.name)
1371
+ raise
1372
+
1373
+ try:
1374
+ if retry_scaling:
1375
+ _retry_scaling_conflicts(
1376
+ update_bounds,
1377
+ url=bounds_url,
1378
+ code=scaling_code,
1379
+ action="the instance bounds update",
1380
+ attempts=8,
1381
+ )
1382
+ else:
1383
+ update_bounds()
1384
+ except (APIConnectionError, APIResponseValidationError):
1385
+ raise
1386
+ except APIStatusError as ex:
1387
+ if ex.status_code >= 500 or _is_scaling_conflict(
1388
+ ex, url=bounds_url, code=scaling_code
1389
+ ):
1390
+ raise
1391
+ return f"set instance bounds failed: {error_message(ex)}"
1247
1392
  except ReflexBuildError as ex:
1248
1393
  return f"set instance bounds failed: {error_message(ex)}"
1249
1394
  return None
@@ -3,9 +3,10 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import datetime
6
+ import json
6
7
  import logging
7
8
  from collections.abc import Sequence
8
- from typing import Any
9
+ from typing import TYPE_CHECKING, Any
9
10
 
10
11
  import click
11
12
 
@@ -21,6 +22,9 @@ from reflex_cli.utils.exceptions import (
21
22
  )
22
23
  from reflex_cli.utils.output import interactive_option, json_option, print_json
23
24
 
25
+ if TYPE_CHECKING:
26
+ from reflex_build_sdk.types import LogRecord
27
+
24
28
  logger = logging.getLogger(__name__)
25
29
 
26
30
  # How many log lines `apps logs --follow` prints before prompting for more.
@@ -30,6 +34,14 @@ _LOGS_PAGE_SIZE = 100
30
34
  _LIST_COLUMNS = ("id", "name", "description", "provider")
31
35
  _HISTORY_COLUMNS = ("id", "status", "timestamp", "can rollback", "description")
32
36
 
37
+ # Terminal control characters print as escapes, so a log line cannot move the
38
+ # cursor or rewrite the lines above it. Tabs stay.
39
+ _CONTROL_ESCAPES = {
40
+ code: f"\\x{code:02x}"
41
+ for code in (*range(0x20), *range(0x7F, 0xA0))
42
+ if code != 0x09
43
+ }
44
+
33
45
 
34
46
  def _print_records(records: list[dict[str, Any]], columns: Sequence[str]) -> None:
35
47
  """Print records as a table whose ids and names stay whole on one line.
@@ -46,6 +58,29 @@ def _print_records(records: list[dict[str, Any]], columns: Sequence[str]) -> Non
46
58
  )
47
59
 
48
60
 
61
+ def _format_log_record(record: LogRecord) -> str:
62
+ """Render a log record as a ``timestamp [LEVEL] message`` line.
63
+
64
+ The message's further lines and the details follow indented, so no line
65
+ of a record can pass for the start of another.
66
+
67
+ Args:
68
+ record: The record to render.
69
+
70
+ Returns:
71
+ The record as terminal text.
72
+ """
73
+ message = record.message
74
+ if not isinstance(message, str):
75
+ message = json.dumps(message, ensure_ascii=False)
76
+ lines = message.splitlines() or [""]
77
+ if record.details:
78
+ lines.extend(record.details.splitlines())
79
+ level = (record.log_level or "info").upper()
80
+ lines[0] = f"{record.timestamp} [{level}] {lines[0]}"
81
+ return "\n ".join(line.translate(_CONTROL_ESCAPES) for line in lines)
82
+
83
+
49
84
  @click.group()
50
85
  def apps_cli():
51
86
  """Commands for managing apps."""
@@ -746,8 +781,12 @@ def app_logs(
746
781
 
747
782
  printed = 0
748
783
  for record in records:
749
- entry = hosting.as_json_document(record)
750
- logger.info(pprint.pformat(entry, indent=2) if pretty else entry)
784
+ message = (
785
+ pprint.pformat(hosting.as_json_document(record), indent=2)
786
+ if pretty
787
+ else _format_log_record(record)
788
+ )
789
+ console.print(message, markup=False, emoji=False, soft_wrap=True)
751
790
  printed += 1
752
791
  if printed % _LOGS_PAGE_SIZE:
753
792
  continue
@@ -11,7 +11,7 @@ import click
11
11
 
12
12
  from reflex_cli import constants
13
13
  from reflex_cli.utils import console, log
14
- from reflex_cli.utils.exceptions import TokenValidationError
14
+ from reflex_cli.utils.exceptions import TokenAccessDeniedError, TokenValidationError
15
15
  from reflex_cli.utils.output import json_option, print_json
16
16
 
17
17
  logger = logging.getLogger(__name__)
@@ -106,9 +106,12 @@ def whoami_command(token: str | None, loglevel: str, as_json: bool):
106
106
 
107
107
  try:
108
108
  validated_info = hosting.validate_token(access_token)
109
- except TokenValidationError as err:
109
+ except TokenAccessDeniedError as err:
110
110
  logger.error(hosting.rejected_token_message(source, err))
111
111
  raise click.exceptions.Exit(1) from err
112
+ except TokenValidationError as err:
113
+ logger.error(hosting._token_validation_failure_message(source, err))
114
+ raise click.exceptions.Exit(1) from err
112
115
 
113
116
  identity = {
114
117
  field: validated_info[field]
@@ -322,8 +322,8 @@ def _resolve_deploy_provider(
322
322
  # Explicit --provider always wins; validated by the caller already.
323
323
  target = hosting.normalize_provider(provider_arg)
324
324
  else:
325
- gcp_status = hosting.gcp_deploy_available(client)
326
- if not gcp_status or not interactive:
325
+ gcp_status = hosting.gcp_deploy_available(client) if interactive else None
326
+ if not gcp_status:
327
327
  # No GCP connected, or non-interactive with no explicit choice: keep
328
328
  # whatever the app already targets.
329
329
  target = current
@@ -1109,18 +1109,12 @@ def deploy(
1109
1109
  min_instances=min_instances,
1110
1110
  max_instances=max_instances,
1111
1111
  client=authenticated_client,
1112
+ retry_scaling=True,
1112
1113
  )
1113
- except BaseException:
1114
- # A dropped connection says nothing about whether the server
1115
- # applied the write, and the bounds are billable state, so hedge
1116
- # rather than report either outcome as fact.
1117
- logger.warning(
1118
- f"Lost contact while setting the instance bounds of "
1119
- f"'{app.name}'; they may or may not have been applied. "
1120
- "Check the app in the Reflex Cloud dashboard before relying "
1121
- "on its scaling."
1114
+ except ReflexBuildError as ex:
1115
+ hosting.exit_reporting(
1116
+ ex, f"set instance bounds failed: {hosting.error_message(ex)}"
1122
1117
  )
1123
- raise
1124
1118
  if bounds_error:
1125
1119
  logger.error(bounds_error)
1126
1120
  raise click.exceptions.Exit(1)
@@ -336,7 +336,12 @@ def get_projects(
336
336
  )
337
337
  projects = authenticated_client.api.projects.list()
338
338
 
339
- _print_rows([hosting.as_json_document(project) for project in projects], as_json)
339
+ rows = [hosting.as_json_document(project) for project in projects]
340
+ if not as_json:
341
+ for row, project in zip(rows, projects, strict=True):
342
+ row["tier"] = project.tier.name
343
+
344
+ _print_rows(rows, as_json)
340
345
 
341
346
 
342
347
  @project_cli.command(name="roles")
@@ -1,24 +0,0 @@
1
- Metadata-Version: 2.5
2
- Name: reflex-hosting-cli
3
- Version: 0.2.0a1
4
- Summary: Reflex Hosting CLI
5
- Author-email: Nikhil Rao <nikhil@reflex.dev>, Alek Petuskey <alek@reflex.dev>
6
- Maintainer-email: Simon Young <simon@reflex.dev>, Khaleel Al-Adhami <khaleel@reflex.dev>
7
- License: Apache-2.0
8
- Classifier: Programming Language :: Python :: 3
9
- Classifier: Programming Language :: Python :: 3.11
10
- Classifier: Programming Language :: Python :: 3.12
11
- Classifier: Programming Language :: Python :: 3.13
12
- Classifier: Programming Language :: Python :: 3.14
13
- Classifier: Programming Language :: Python :: 3.15
14
- Requires-Python: >=3.11
15
- Requires-Dist: click>=8.2
16
- Requires-Dist: httpx<1.0,>=0.25.1
17
- Requires-Dist: packaging>=24.2
18
- Requires-Dist: platformdirs<5.0,>=3.10.0
19
- Requires-Dist: reflex-build-sdk[httpx]!=0.1.1,<0.1.1.post,>=0.1.0a1
20
- Requires-Dist: rich<16,>=13
21
- Description-Content-Type: text/markdown
22
-
23
- # reflex-hosting-cli
24
- Hosting CLI for Reflex.
@@ -1,2 +0,0 @@
1
- # reflex-hosting-cli
2
- Hosting CLI for Reflex.