Skip to content

Commit 1d31005

Browse files
authored
Merge pull request #139 from nitrocloudofficial/develop
Release 0.5.0
2 parents feb2bae + 20fe2c1 commit 1d31005

296 files changed

Lines changed: 28853 additions & 13581 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.env.example‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
# NitroStack Python SDK / CLI — analytics (see docs/analytics-events.md)
2+
# Optional: override the built-in public PostHog project key (never commit non-public values).
3+
NITROSTACK_POSTHOG_KEY=
4+
# Optional: PostHog ingest host (default US Cloud).
5+
NITROSTACK_POSTHOG_HOST=https://us.i.posthog.com
6+
# production | staging | development (default: inferred from NODE_ENV / CI).
7+
NITROSTACK_ENVIRONMENT=
8+
# Set to 0/false/off to disable CLI telemetry (DO_NOT_TRACK=1 also disables).
9+
NITROSTACK_TELEMETRY=

‎.file_length_baseline.json‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
{
2+
"examples/flight_booking_server.py": 582,
3+
"nitrostack/auth/oauth.py": 516,
4+
"nitrostack/core/app.py": 2273,
5+
"nitrostack/transports/http.py": 797,
6+
"nitrostack/widgets/route_templates.py": 870,
7+
"nitrostack/widgets/views.py": 569,
8+
"tests/test_cli.py": 1589,
9+
"tests/test_oauth.py": 1011,
10+
"tests/test_secret_value.py": 515,
11+
"tests/test_tasks.py": 574,
12+
"tests/test_transports.py": 732,
13+
"tests/test_widgets.py": 629
14+
}

‎.github/workflows/test.yml‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,17 @@ jobs:
2121
with:
2222
python-version: ${{ matrix.python-version }}
2323

24+
- name: Secure pip bootstrap (eMudhra/emSign advisory)
25+
run: |
26+
python -m pip install "pip @ https://files.pythonhosted.org/packages/3f/06/3e4420302363fbb71be3c7f35ce042f54bfca330e3e66b3a2e3c4cca579f/pip-26.2.2-py3-none-any.whl#sha256=fd7f4dfa8190e014013b9f08f3e973f4e4c26ffd179a204895533a7254813a70"
27+
python -m pip install --upgrade "certifi>=2026.10.19"
28+
2429
- name: Install dependencies
2530
run: |
26-
python -m pip install --upgrade pip
27-
pip install -e ".[dev]"
31+
python -m pip install -e ".[dev]"
32+
33+
- name: Check Python file length policy
34+
run: python scripts/check_file_lengths.py
2835

2936
- name: Run pytest with coverage
3037
run: pytest tests --cov=nitrostack --cov-report=term-missing --timeout=60

‎CONTRIBUTING.md‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# Contributing to Nitrostack Python SDK
2+
3+
Welcome! This guide explains our development workflow and coding policies to help you contribute smoothly.
4+
5+
---
6+
7+
## Quick Start for Developers
8+
9+
```bash
10+
# 1. Set up virtual environment and install dev dependencies
11+
python -m venv .venv
12+
source .venv/bin/activate
13+
pip install -e ".[dev]"
14+
15+
# 2. Run tests
16+
pytest tests
17+
18+
# 3. Check Python file-length policy
19+
python scripts/check_file_lengths.py
20+
```
21+
22+
---
23+
24+
## Python File-Length Policy
25+
26+
To keep modules focused and reviewable, we enforce a **500 physical-line limit** on Python files.
27+
28+
### The Rule
29+
* **New files & standard files:** Must be **500 lines or fewer**.
30+
* **Lines counted:** Total physical lines (including blanks, comments, docstrings, and multiline strings).
31+
* **Scope:** Tracked `*.py` files in `nitrostack/`, `tests/`, `examples/`, and `scripts/`. Embedded templates in Python files count toward this limit.
32+
* **Exempt:** Documentation (`.md`), static assets (HTML/CSS/JS), lockfiles, vendored packages, and generated build output.
33+
34+
---
35+
36+
## Working with Existing Oversized Files (The Ratchet)
37+
38+
A set of pre-existing legacy files exceed 500 lines. Instead of forcing immediate file splits, we use a **ratchet** tracked in [`.file_length_baseline.json`](.file_length_baseline.json):
39+
40+
1. **They cannot grow:** CI fails if any legacy file exceeds its current baseline number.
41+
2. **They can shrink:** When you refactor or shrink an oversized file, lower its baseline automatically with:
42+
```bash
43+
python scripts/check_file_lengths.py --update-baseline
44+
```
45+
Then commit the updated `.file_length_baseline.json` with your PR.
46+
3. **Graduation:** Once a legacy file reaches 500 lines or fewer, `--update-baseline` automatically removes it from the baseline. From that point on, it is capped at 500 lines forever.
47+
48+
> **Need an exception?** Any baseline increase is exceptional and must be explicitly justified and approved during code review.
49+
50+
---
51+
52+
## Continuous Integration (CI)
53+
54+
Our GitHub Actions workflow automatically checks every PR across Python 3.10, 3.11, and 3.12:
55+
1. **File-length check:** Runs `python scripts/check_file_lengths.py`.
56+
2. **Test suite:** Runs `pytest tests --cov=nitrostack --cov-report=term-missing --timeout=60`.

‎README.md‎

Lines changed: 456 additions & 210 deletions
Large diffs are not rendered by default.

‎docs/analytics-events.md‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# NitroStack Python SDK CLI — analytics events
2+
3+
Telemetry uses a **built-in public PostHog project key** (same ingest as the TypeScript CLI). Set `NITROSTACK_POSTHOG_KEY` only if you need to override that key. Telemetry is **off** when `DO_NOT_TRACK=1`, when `NITROSTACK_TELEMETRY=0` (or `false`/`off`/`no`), during pytest (`PYTEST_CURRENT_TEST`), and in CI when `NITROSTACK_TELEMETRY` is unset (set it to a truthy value to allow capture in CI).
4+
5+
On process exit the CLI runs a **best-effort flush** (PostHog `shutdown` on a background thread, joined for up to **2 seconds**). Events still in the queue after that window may not be delivered; command completion is never blocked longer than that timeout.
6+
7+
`pack --dry-run` lists files that would be packed but does **not** emit `cli_deploy_completed` or `cli_deploy_failed`.
8+
9+
## Super properties
10+
11+
Sent on every captured event:
12+
13+
| Property | Description |
14+
|----------|-------------|
15+
| `product` | `python_sdk` |
16+
| `surface` | `terminal` |
17+
| `environment` | `production`, `staging`, or `development` (from `NITROSTACK_ENVIRONMENT` or heuristics) |
18+
| `app_version` | Installed `nitrostack` package version |
19+
| `python_version` | Interpreter version |
20+
| `sdk_version` | Same as `app_version` |
21+
| `os_platform` | `sys.platform` |
22+
| `os_arch` | `platform.machine()` |
23+
24+
## Events
25+
26+
| Event | When | Properties |
27+
|-------|------|------------|
28+
| `cli_command_invoked` | Every subcommand after parse | `command`: subcommand name (`init`, `pack`, …) |
29+
| `cli_init_completed` | `init` finishes successfully | `template`, `skip_install`, `duration_ms`, `has_custom_description` |
30+
| `cli_login_completed` | After `nitrostack-py login` succeeds (identity helper) | `user_email`, `cloud_user_id` (+ super properties) |
31+
| `cli_deploy_completed` | `pack` writes a valid wheel | none beyond super properties |
32+
| `cli_deploy_failed` | `pack` raises before success | `error_code`: exception type name (truncated) |
33+
34+
## Identity
35+
36+
- **Anonymous:** distinct id = first 16 hex chars of SHA-256(`hostname`:`username`), same scheme as the TypeScript CLI.
37+
- **Login:** `login` runs `alias(anonymous, user_id)`, `identify(user_id, { email })`, optional `group_identify('organization', org_id)`, then `cli_login_completed`. Subsequent events use the Cloud user id as distinct id.
38+
39+
## Code locations
40+
41+
- Module: `nitrostack/cli/telemetry.py`
42+
- CLI wiring: `nitrostack/cli/main.py` (`track_command_invoked`, `login`, `shutdown_telemetry`)
43+
- Init: `nitrostack/cli/_project_init.py` (`cli_init_completed`)
44+
- Deploy: `nitrostack/cli/pack.py` (`cli_deploy_*`)
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# Investigation: TypeScript `DiscoveryHttpServer` vs the Python SDK (#77)
2+
3+
Checked against: Python `nitrostack-python-sdk` `develop` at `fb0faf8`;
4+
TypeScript `nitrocloudofficial/nitrostack` at `10859bef`. Date: 2026-11-03.
5+
6+
## 1. What the TypeScript server does
7+
File: `typescript/packages/core/src/core/transports/discovery-http-server.ts`
8+
9+
- Options (`:11-18`): `port`, `autoRetry`, `maxRetries`.
10+
- Defaults (`:53-67`): with an options object, `port` 3005, `autoRetry` true,
11+
`maxRetries` 10. With the legacy numeric constructor, `autoRetry` false.
12+
- Retry (`:23-45`, `:97-109`): when `autoRetry` is on, `findAvailablePort` probes
13+
`port`, `port+1`, ... up to `maxRetries` using a throwaway `net` server, then
14+
listens on the first free port. It throws if none is free.
15+
- Without `autoRetry`, an `EADDRINUSE` error is logged with a hint to set
16+
`OAUTH_DISCOVERY_PORT` and the start promise rejects (`:117-127`).
17+
- Reporting (`:93-95`): `getPort()` returns the port actually used.
18+
- Routing (`:72-87`): exact-match path handlers registered with `on(path, handler)`;
19+
unknown paths return 404. Bind address is not passed to `listen`, so Node's default applies.
20+
21+
## 2. Consumers in the TypeScript stack
22+
| Consumer | File:line | Use |
23+
|---|---|---|
24+
| `OAuthModule.start()` | `core/oauth-module.ts:560-569` | In stdio mode, creates the server with `autoRetry` (env `OAUTH_DISCOVERY_AUTO_RETRY`, default on, `:549`) and `maxRetries: 50` (`:554`), reads `getPort()`, then emits the port to the client. |
25+
| `OAuthModule.start()` fallback | `core/oauth-module.ts:610-617` | Starts the same server if the HTTP transport is missing in http/dual mode. |
26+
| `registerDiscoveryHandlers` | `core/oauth-module.ts:667-673` | Registers `/.well-known/oauth-authorization-server`, `/.well-known/oauth-protected-resource`, and `/oauth/v2/register` when client registration is enabled. |
27+
| `notifyClientAboutOAuth` | `core/oauth-module.ts:639-657` | Writes `[NITROSTACK_OAUTH]{...}[/NITROSTACK_OAUTH]` to stderr with the actual port and well-known URLs. |
28+
| CLI template docs | `packages/cli/templates/typescript-oauth/OAUTH_SETUP.md:97,210,350` | Documents port 3005 and the startup log line. |
29+
| Tests | `transport.http.test.ts:111-172`, `transports.test.ts:244-288`, `oauth.extended.test.ts:39-41` | Cover the retry and no-retry options (ports 34508/34509). |
30+
31+
Within `typescript/packages`, outside tests and templates, the only consumer is
32+
`OAuthModule`. No other code in that tree (including the CLI sources) references it.
33+
**Not checked:** NitroStudio's source is not in this repository, so whether Studio
34+
parses the `[NITROSTACK_OAUTH]` marker could not be verified.
35+
36+
## 3. Current Python behaviour
37+
| Concern | Location | Behaviour |
38+
|---|---|---|
39+
| Startup | `nitrostack/core/app.py:1958-1966` | `McpApplication.start()` calls `OAuthService.start_discovery_server()` only when an `OAuthService` is registered in the container. |
40+
| Bind | `nitrostack/auth/oauth.py:259-274` | A daemon thread builds `HTTPServer(("localhost", port), DiscoveryHandler)` once. No probing and no retry. |
41+
| Port setting | `nitrostack/auth/oauth.py:261` | `int(os.environ.get("OAUTH_DISCOVERY_PORT", self.discovery_port))`: the **environment variable wins** over the `for_root(discovery_port=...)` value. `oauth_module.py` contains no port logic. |
42+
| Failure | `nitrostack/auth/oauth.py:275-277` | Any exception is written to stderr and swallowed. The thread ends, `_server` stays `None`, and the app keeps running with no discovery server. |
43+
| Reporting | `nitrostack/auth/oauth.py:264-273` | Writes `[NITROSTACK_OAUTH]{port, resource_uri, authorization_servers}[/NITROSTACK_OAUTH]` to stderr. The TypeScript marker carries more fields: `type`, `scopesSupported` and `wellKnownEndpoints`. |
44+
| CLI ports | `nitrostack/cli/main.py` `_resolve_runtime_ports`, `_normalize_port` | Resolve the MCP and widget ports (`--port`, `--widget`, env, defaults 3000/3001). Unrelated to OAuth discovery; no retry. |
45+
46+
### Probe: preferred port already in use
47+
`scripts/probe_discovery_port.py` reserves a port, then starts the Python discovery server on it.
48+
Output on Windows (Python 3.12):
49+
busy port: 58380
50+
Failed to start OAuth Discovery Server on port 58380: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions
51+
server object: None
52+
bound to: None
53+
GET failed: TimeoutError timed out
54+
55+
The server does not start, no port is reported, and the application is not told.
56+
Note: Windows returned `WinError 10013` rather than the usual address-in-use error,
57+
which is how it reports binding to a port held by another socket here.
58+
59+
## 4. Comparison
60+
| Capability | TypeScript | Python | Gap? |
61+
|---|---|---|---|
62+
| Separate discovery server | yes, stdio mode and as fallback | yes, always a background thread when OAuth is registered | no |
63+
| Preferred port | option, default 3005, env `OAUTH_DISCOVERY_PORT` | env or `discovery_port` | no |
64+
| Retry on busy port | `autoRetry`, `maxRetries` (50 in OAuthModule) | none | **yes** |
65+
| Actual port available to code | `getPort()` and `OAuthModule.discoveryInfo` | no | yes |
66+
| Port reported to the host tool | stderr marker with port and well-known URLs | stderr marker with port only | partial |
67+
| Behaviour on bind failure | start promise rejects | logged and swallowed; no server | yes |
68+
| Only started when OAuth is configured | yes | yes | no |
69+
70+
## 5. Conclusion
71+
**Open an implementation issue; do not close this one.** The two servers match in
72+
purpose, endpoints and stderr marker. They differ in port conflicts: TypeScript tries
73+
up to 50 ports and reports the one it used, while Python makes one attempt and silently
74+
runs without discovery when the port is taken, as the probe shows. A client that reads
75+
the marker will then never receive a port.
76+
77+
Proposed scope for the follow-up (link here once opened):
78+
- Retry on a busy port, controlled by `OAUTH_DISCOVERY_AUTO_RETRY` and a max-retries
79+
limit, with the same defaults as TypeScript (on, 50).
80+
- Store the actual port on `OAuthService` and put it in the stderr marker.
81+
- Surface bind failures instead of swallowing them.
82+
- Tests: busy port with retry, retries exhausted, port reported.
83+
84+
Out of scope: matching the TypeScript marker's extra fields, until it is known
85+
whether NitroStudio consumes them.

0 commit comments

Comments
 (0)