forked from longtao.wu/droboticflow
🛠️ Centralize service endpoint defaults
This commit is contained in:
parent
08ea0219b1
commit
9ed7f8c736
@ -21,6 +21,8 @@ OPERATOR_ALLOW_SHELL_COMMANDS=false
|
||||
OPERATOR_COMMAND_ALLOWLIST_REGEX=
|
||||
OPERATOR_COMMAND_DENYLIST_REGEX=
|
||||
VITE_API_BASE_URL=
|
||||
VITE_DEV_API_BASE_URL=http://127.0.0.1:3001
|
||||
VITE_DEV_WORKER_BASE_URL=http://127.0.0.1:3002
|
||||
AI_API_BASE_URL=https://coding.dashscope.aliyuncs.com/v1
|
||||
AI_MODEL=glm-5
|
||||
AI_API_KEY=
|
||||
|
||||
@ -110,9 +110,13 @@ Key environment variables:
|
||||
- `AI_MODEL`: server-side model name, default `glm-5`
|
||||
- `AI_API_KEY`: server-side DashScope-compatible API key used for workflow/operator generation
|
||||
- `VITE_API_BASE_URL`: optional frontend API base URL override
|
||||
- `VITE_DEV_API_BASE_URL`: optional Vite dev proxy target for `/api`, default `http://127.0.0.1:3001`
|
||||
- `VITE_DEV_WORKER_BASE_URL`: optional Vite dev proxy target for `/worker-api`, default `http://127.0.0.1:3002`
|
||||
|
||||
Explicit numeric startup values are validated before API/worker startup, before Kubernetes manifest rendering, and before `scripts/deploy-k8s.sh` performs cluster writes. `PORT`/`WORKER_PORT` must be valid TCP ports, Mongo retry count and retry delay must be positive, worker poll interval must be positive, replica counts must be non-negative in manifests, NodePort must be in the Kubernetes `30000..32767` range, and `OPERATOR_JOB_TTL_SECONDS` must be non-negative (`0` disables TTL injection). Explicit boolean env values accept `true/false`, `1/0`, `yes/no`, or `on/off`; other spellings fail fast instead of silently falling back, and accepted true aliases drive deploy-time branches such as public LoadBalancer creation.
|
||||
|
||||
Development and acceptance entrypoints resolve API endpoints through shared helpers instead of each script carrying its own localhost default. Node/Vite entrypoints use `scripts/lib/service-endpoints.mjs`, Python operational scripts use `scripts/lib/droboticflow_env.py`, and shell wrappers use `scripts/lib/service-endpoints.sh`. `BASE_URL` is accepted by browser-oriented acceptance scripts, while deployment/reconcile wrappers preserve `API_BASE_URL` as their primary environment variable.
|
||||
|
||||
The frontend never reads the AI key directly. Workflow generation and operator generation are proxied through the Go API so secrets stay on the server side.
|
||||
The settings page can update K8s access details, the worker defaults, the global `timezone`, `provider`, `baseURL`, `model`, and the server-side AI key. `GET /api/settings` only returns whether secrets exist via `k8s.hasKubeconfig` / `ai.hasAPIKey`; it does not echo plaintext kubeconfig or API keys back to the browser. Timestamps in the UI are rendered in the configured IANA timezone with compact minute-level formatting for cards, lists, and summaries, while logs keep finer granularity when needed. OSS-related bucket and path settings belong on OSS operators in workflows, not in the global system settings page. Scan workflows can now reference reusable BOS storage connections via `scanConfig.connectionId`, so endpoint and AK/SK are stored once in `/api/storage/connections` and resolved by the API/worker at preview and execution time instead of being duplicated into each workflow.
|
||||
|
||||
|
||||
@ -240,7 +240,7 @@ export DROBOTICFLOW_API_TOKEN=<shared-api-token>
|
||||
# Required for session-authenticated public APIs; use an organization admin:
|
||||
export DROBOTICFLOW_SMOKE_EMAIL=<admin-email>
|
||||
export DROBOTICFLOW_SMOKE_PASSWORD=<admin-password>
|
||||
./scripts/reconcile-system-data.sh http://127.0.0.1:3001
|
||||
API_BASE_URL=http://<node-ip>:30080 ./scripts/reconcile-system-data.sh
|
||||
```
|
||||
|
||||
`scripts/reconcile-system-data.sh` is only the environment wrapper. The Python implementation reads the current builtin operator catalog from `/api/operators` and updates those live records to the requested `OPERATOR_RUNNER_IMAGE`; it does not carry a second static builtin-operator list. The cleanup step skips builtin operators even when their image tag is `:latest`, so old custom/demo operators can be removed without tombstoning platform-provided builtins.
|
||||
|
||||
@ -9,6 +9,7 @@ This note tracks the production-facing safeguards that must stay true for Drobod
|
||||
- Worker proxy health, stats, metrics, and retry calls use short upstream timeouts. Manual `process-once` uses a long timeout because it can execute real queued work.
|
||||
- Explicit shell operators are disabled by default through `OPERATOR_ALLOW_SHELL_COMMANDS=false`; allowlist and denylist regexes are platform-controlled and cannot be overridden by workflow hyperparams.
|
||||
- Environment-specific values such as `K8S_ENDPOINT`, registry username, and workspace BOS bucket have no private repository defaults; provide them from local deploy secrets or CI secrets.
|
||||
- Local development and acceptance endpoints are resolved through shared helpers instead of per-script localhost literals. Vite dev proxy targets can be overridden with `VITE_DEV_API_BASE_URL` and `VITE_DEV_WORKER_BASE_URL`; browser-oriented acceptance scripts accept `BASE_URL` or `API_BASE_URL`, while reconcile/deploy wrappers keep `API_BASE_URL` as the primary operational variable.
|
||||
- Data reconciliation uses real API calls and supports protected deployments through `DROBOTICFLOW_API_TOKEN` or session login credentials plus CSRF headers. Public session-auth environments must use an organization admin account for reconcile because it updates settings and management resources.
|
||||
- Python live-acceptance and WJZH regression scripts use the shared `DroboticflowClient` helper for API token headers, session-login cookies, CSRF propagation, JSON calls, and binary object-storage calls. WJZH quality thresholds are caller-supplied through `QUALITY_MIN_CLARITY`, `QUALITY_MAX_SHAKE`, and `QUALITY_MAX_HAND_OCCLUSION`; window, slicing, and annotation timing are caller-supplied through the documented `*_SECONDS` values; sampling thresholds are caller-supplied through `SAMPLING_RULES_JSON`. The scripts do not carry built-in audit rules. New Python acceptance scripts should reuse that helper instead of carrying their own auth/request stack.
|
||||
- Python WJZH and X-platform acceptance scripts validate quality thresholds through the shared normalized-threshold gate. `QUALITY_MIN_CLARITY`, `QUALITY_MAX_SHAKE`, `QUALITY_MAX_HAND_OCCLUSION`, `XPLATFORM_MIN_CLARITY`, `XPLATFORM_MAX_SHAKE`, and `XPLATFORM_MAX_HAND_OCCLUSION` must be finite values in `[0, 1]`; invalid values fail before live workflows are created.
|
||||
|
||||
40
scripts/lib/droboticflow_env.py
Normal file
40
scripts/lib/droboticflow_env.py
Normal file
@ -0,0 +1,40 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections.abc import Mapping, Sequence
|
||||
|
||||
|
||||
DEFAULT_API_BASE_URL = "http://127.0.0.1:3001"
|
||||
DEFAULT_WORKER_BASE_URL = "http://127.0.0.1:3002"
|
||||
|
||||
|
||||
def trim_trailing_slash(value: str | None) -> str:
|
||||
return str(value or "").strip().rstrip("/")
|
||||
|
||||
|
||||
def first_non_empty(*values: str | None) -> str:
|
||||
for value in values:
|
||||
normalized = trim_trailing_slash(value)
|
||||
if normalized:
|
||||
return normalized
|
||||
return ""
|
||||
|
||||
|
||||
def service_url_from_env(
|
||||
names: Sequence[str],
|
||||
*,
|
||||
environ: Mapping[str, str] | None = None,
|
||||
fallback: str = "",
|
||||
) -> str:
|
||||
source = environ if environ is not None else os.environ
|
||||
return first_non_empty(*(source.get(name, "") for name in names), fallback)
|
||||
|
||||
|
||||
def api_base_url_from_env(
|
||||
*,
|
||||
environ: Mapping[str, str] | None = None,
|
||||
include_base_url: bool = True,
|
||||
fallback: str = DEFAULT_API_BASE_URL,
|
||||
) -> str:
|
||||
names = ("BASE_URL", "API_BASE_URL") if include_base_url else ("API_BASE_URL",)
|
||||
return service_url_from_env(names, environ=environ, fallback=fallback)
|
||||
72
scripts/lib/service-endpoints.mjs
Normal file
72
scripts/lib/service-endpoints.mjs
Normal file
@ -0,0 +1,72 @@
|
||||
export const DEFAULT_API_BASE_URL = "http://127.0.0.1:3001";
|
||||
export const DEFAULT_WORKER_BASE_URL = "http://127.0.0.1:3002";
|
||||
|
||||
export function trimTrailingSlash(value = "") {
|
||||
return String(value || "").trim().replace(/\/+$/, "");
|
||||
}
|
||||
|
||||
export function firstNonEmpty(...values) {
|
||||
for (const value of values) {
|
||||
const normalized = trimTrailingSlash(value);
|
||||
if (normalized) {
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export function serviceURLFromEnv({
|
||||
env = process.env,
|
||||
names = [],
|
||||
cliArgs = [],
|
||||
cliIndex = null,
|
||||
fallback = "",
|
||||
} = {}) {
|
||||
const candidates = names.map((name) => env?.[name]);
|
||||
if (Number.isInteger(cliIndex)) {
|
||||
candidates.push(cliArgs?.[cliIndex]);
|
||||
}
|
||||
candidates.push(fallback);
|
||||
return firstNonEmpty(...candidates);
|
||||
}
|
||||
|
||||
export function apiBaseURLFromEnv({
|
||||
env = process.env,
|
||||
cliArgs = process.argv,
|
||||
cliIndex = 2,
|
||||
includeBaseURL = true,
|
||||
fallback = DEFAULT_API_BASE_URL,
|
||||
} = {}) {
|
||||
const names = includeBaseURL ? ["BASE_URL", "API_BASE_URL"] : ["API_BASE_URL"];
|
||||
return serviceURLFromEnv({ env, names, cliArgs, cliIndex, fallback });
|
||||
}
|
||||
|
||||
export function workerBaseURLFromEnv({
|
||||
env = process.env,
|
||||
cliArgs = process.argv,
|
||||
cliIndex = null,
|
||||
fallback = DEFAULT_WORKER_BASE_URL,
|
||||
} = {}) {
|
||||
return serviceURLFromEnv({
|
||||
env,
|
||||
names: ["WORKER_BASE_URL", "WORKER_API_BASE_URL"],
|
||||
cliArgs,
|
||||
cliIndex,
|
||||
fallback,
|
||||
});
|
||||
}
|
||||
|
||||
export function viteProxyTargets(env = process.env) {
|
||||
return {
|
||||
api: serviceURLFromEnv({
|
||||
env,
|
||||
names: ["VITE_DEV_API_BASE_URL", "VITE_API_PROXY_TARGET"],
|
||||
fallback: DEFAULT_API_BASE_URL,
|
||||
}),
|
||||
worker: serviceURLFromEnv({
|
||||
env,
|
||||
names: ["VITE_DEV_WORKER_BASE_URL", "VITE_WORKER_API_PROXY_TARGET"],
|
||||
fallback: DEFAULT_WORKER_BASE_URL,
|
||||
}),
|
||||
};
|
||||
}
|
||||
27
scripts/lib/service-endpoints.sh
Normal file
27
scripts/lib/service-endpoints.sh
Normal file
@ -0,0 +1,27 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
droboticflow_trim_trailing_slash() {
|
||||
local value="${1:-}"
|
||||
while [[ "$value" == */ ]]; do
|
||||
value="${value%/}"
|
||||
done
|
||||
printf '%s\n' "$value"
|
||||
}
|
||||
|
||||
droboticflow_first_service_url() {
|
||||
local candidate
|
||||
for candidate in "$@"; do
|
||||
if [[ -n "$candidate" ]]; then
|
||||
droboticflow_trim_trailing_slash "$candidate"
|
||||
return
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
droboticflow_default_api_base_url() {
|
||||
printf '%s\n' "http://127.0.0.1:3001"
|
||||
}
|
||||
|
||||
droboticflow_default_worker_base_url() {
|
||||
printf '%s\n' "http://127.0.0.1:3002"
|
||||
}
|
||||
@ -9,9 +9,10 @@ import {
|
||||
loginIfConfigured,
|
||||
validateSessionCredentials,
|
||||
} from "./lib/acceptance-client.mjs";
|
||||
import { apiBaseURLFromEnv } from "./lib/service-endpoints.mjs";
|
||||
|
||||
const MAX_EDITOR_PAYLOAD_BYTES = 4 * 1024 * 1024;
|
||||
const BASE_URL = (process.env.BASE_URL || process.env.API_BASE_URL || "http://127.0.0.1:3001").replace(/\/+$/, "");
|
||||
const BASE_URL = apiBaseURLFromEnv({ env: process.env, cliIndex: null });
|
||||
const API_TOKEN = (process.env.DROBOTICFLOW_API_TOKEN || "").trim();
|
||||
const SMOKE_EMAIL = (process.env.DROBOTICFLOW_SMOKE_EMAIL || "").trim();
|
||||
const SMOKE_PASSWORD = process.env.DROBOTICFLOW_SMOKE_PASSWORD || "";
|
||||
|
||||
@ -2,9 +2,10 @@ import { chromium } from "playwright";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { authenticationHeaders, createAcceptanceAPIClient } from "./lib/acceptance-client.mjs";
|
||||
import { apiBaseURLFromEnv } from "./lib/service-endpoints.mjs";
|
||||
import { inferSourceDataSource } from "./lib/source-data-source.mjs";
|
||||
|
||||
const baseURL = (process.env.BASE_URL || process.argv[2] || "http://127.0.0.1:3001").replace(/\/+$/, "");
|
||||
const baseURL = apiBaseURLFromEnv({ env: process.env, cliArgs: process.argv });
|
||||
const apiToken = (process.env.DROBOTICFLOW_API_TOKEN || "").trim();
|
||||
const apiClient = createAcceptanceAPIClient({ baseURL, apiToken });
|
||||
const artifactDir = path.resolve("output/playwright");
|
||||
|
||||
@ -3,8 +3,9 @@ import path from "node:path";
|
||||
|
||||
import { chromium } from "playwright";
|
||||
import { authenticationHeaders, createAcceptanceAPIClient } from "./lib/acceptance-client.mjs";
|
||||
import { apiBaseURLFromEnv } from "./lib/service-endpoints.mjs";
|
||||
|
||||
const baseURL = (process.env.BASE_URL || process.argv[2] || "http://127.0.0.1:3001").replace(/\/+$/, "");
|
||||
const baseURL = apiBaseURLFromEnv({ env: process.env, cliArgs: process.argv });
|
||||
const apiToken = (process.env.DROBOTICFLOW_API_TOKEN || "").trim();
|
||||
const apiClient = createAcceptanceAPIClient({ baseURL, apiToken });
|
||||
const suffix = Date.now().toString(36);
|
||||
|
||||
@ -2,7 +2,9 @@
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
API_BASE_URL="${1:-${API_BASE_URL:-http://127.0.0.1:3001}}"
|
||||
# shellcheck disable=SC1091
|
||||
source "$ROOT_DIR/scripts/lib/service-endpoints.sh"
|
||||
API_BASE_URL="$(droboticflow_first_service_url "${1:-}" "${API_BASE_URL:-}" "${BASE_URL:-}" "$(droboticflow_default_api_base_url)")"
|
||||
K8S_ENDPOINT="${K8S_ENDPOINT:-}"
|
||||
K8S_NAMESPACE="${K8S_NAMESPACE:-droboticflow}"
|
||||
OPERATOR_RUNNER_IMAGE="${OPERATOR_RUNNER_IMAGE:-}"
|
||||
|
||||
@ -12,6 +12,7 @@ ROOT = pathlib.Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
|
||||
from lib.droboticflow_acceptance import DroboticflowClient
|
||||
from lib.droboticflow_env import api_base_url_from_env
|
||||
|
||||
|
||||
JSON = dict[str, Any]
|
||||
@ -166,7 +167,7 @@ def reconcile(client: DroboticflowClient, *, k8s_endpoint: str, k8s_namespace: s
|
||||
|
||||
def parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(description="Reconcile droboticflow system data through the protected API")
|
||||
parser.add_argument("--api-base-url", default=os.getenv("API_BASE_URL", "http://127.0.0.1:3001"))
|
||||
parser.add_argument("--api-base-url", default=api_base_url_from_env(include_base_url=False))
|
||||
parser.add_argument("--k8s-endpoint", default=os.getenv("K8S_ENDPOINT", ""))
|
||||
parser.add_argument("--k8s-namespace", default=os.getenv("K8S_NAMESPACE", "droboticflow"))
|
||||
parser.add_argument("--operator-runner-image", default=os.getenv("OPERATOR_RUNNER_IMAGE", ""))
|
||||
|
||||
@ -1,12 +1,16 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
# shellcheck disable=SC1091
|
||||
source "$SCRIPT_DIR/lib/service-endpoints.sh"
|
||||
|
||||
if [[ $# -gt 0 ]]; then
|
||||
API_BASE_URL="$1"
|
||||
WORKER_BASE_URL="${2:-${WORKER_BASE_URL:-}}"
|
||||
API_BASE_URL="$(droboticflow_first_service_url "$1")"
|
||||
WORKER_BASE_URL="$(droboticflow_first_service_url "${2:-}" "${WORKER_BASE_URL:-}")"
|
||||
else
|
||||
API_BASE_URL="${API_BASE_URL:-http://127.0.0.1:3001}"
|
||||
WORKER_BASE_URL="${WORKER_BASE_URL:-http://127.0.0.1:3002}"
|
||||
API_BASE_URL="$(droboticflow_first_service_url "${API_BASE_URL:-}" "${BASE_URL:-}" "$(droboticflow_default_api_base_url)")"
|
||||
WORKER_BASE_URL="$(droboticflow_first_service_url "${WORKER_BASE_URL:-}" "${WORKER_API_BASE_URL:-}" "$(droboticflow_default_worker_base_url)")"
|
||||
fi
|
||||
SMOKE_SOURCE_PATH="${SMOKE_SOURCE_PATH:-}"
|
||||
SMOKE_RUN_TIMEOUT_SECONDS="${SMOKE_RUN_TIMEOUT_SECONDS:-180}"
|
||||
|
||||
@ -20,11 +20,11 @@ if str(SCRIPT_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(SCRIPT_DIR))
|
||||
|
||||
from lib.droboticflow_acceptance import DroboticflowClient
|
||||
from lib.droboticflow_env import api_base_url_from_env
|
||||
from lib.quality_thresholds import positive_float_issues, positive_int_issues, unit_interval_threshold_issues
|
||||
from lib.sampling_rules import normalize_sampling_rules_json as normalize_rules_json
|
||||
|
||||
|
||||
DEFAULT_API_BASE_URL = "http://127.0.0.1:3001"
|
||||
DEFAULT_PROJECT_PREFIX = "真实数据算子回归"
|
||||
CLIENT: DroboticflowClient | None = None
|
||||
|
||||
@ -236,7 +236,7 @@ def login_if_configured(config: Config) -> None:
|
||||
|
||||
def parse_args() -> Config:
|
||||
parser = argparse.ArgumentParser(description="Run production-style WJZH operator regression workflows")
|
||||
parser.add_argument("--api-base-url", default=env_default("API_BASE_URL", DEFAULT_API_BASE_URL))
|
||||
parser.add_argument("--api-base-url", default=api_base_url_from_env(include_base_url=False))
|
||||
parser.add_argument("--api-token", default=env_default("DROBOTICFLOW_API_TOKEN"))
|
||||
parser.add_argument("--smoke-email", default=env_default("DROBOTICFLOW_SMOKE_EMAIL"))
|
||||
parser.add_argument("--smoke-password", default=os.getenv("DROBOTICFLOW_SMOKE_PASSWORD", ""))
|
||||
|
||||
@ -16,11 +16,11 @@ if str(SCRIPT_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(SCRIPT_DIR))
|
||||
|
||||
from lib.droboticflow_acceptance import DroboticflowClient
|
||||
from lib.droboticflow_env import api_base_url_from_env
|
||||
from lib.quality_thresholds import positive_float_issues, positive_int_issues, unit_interval_threshold_issues
|
||||
from lib.sampling_rules import normalize_sampling_rules_json as normalize_rules_json
|
||||
|
||||
|
||||
DEFAULT_API_BASE_URL = "http://127.0.0.1:3001"
|
||||
DEFAULT_PROJECT_PREFIX = "XPlatform Real Acceptance"
|
||||
CLIENT: DroboticflowClient | None = None
|
||||
|
||||
@ -90,7 +90,7 @@ def optional_int_env_default(name: str) -> int | None:
|
||||
|
||||
def parse_args() -> Config:
|
||||
parser = argparse.ArgumentParser(description="Run X-platform operator acceptance against an explicit real dataset")
|
||||
parser.add_argument("--api-base-url", default=env_default("BASE_URL", env_default("API_BASE_URL", DEFAULT_API_BASE_URL)))
|
||||
parser.add_argument("--api-base-url", default=api_base_url_from_env())
|
||||
parser.add_argument("--api-token", default=env_default("DROBOTICFLOW_API_TOKEN"))
|
||||
parser.add_argument("--smoke-email", default=env_default("DROBOTICFLOW_SMOKE_EMAIL"))
|
||||
parser.add_argument("--smoke-password", default=os.getenv("DROBOTICFLOW_SMOKE_PASSWORD", ""))
|
||||
|
||||
54
tests/backend/droboticflow_env_test.py
Normal file
54
tests/backend/droboticflow_env_test.py
Normal file
@ -0,0 +1,54 @@
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
|
||||
from lib.droboticflow_env import DEFAULT_API_BASE_URL, api_base_url_from_env, first_non_empty, service_url_from_env
|
||||
|
||||
|
||||
class DroboticflowEnvTest(unittest.TestCase):
|
||||
def test_first_non_empty_normalizes_url(self):
|
||||
self.assertEqual(first_non_empty("", " ", "https://api.example.test///"), "https://api.example.test")
|
||||
|
||||
def test_api_base_url_uses_shared_default(self):
|
||||
self.assertEqual(api_base_url_from_env(environ={}), DEFAULT_API_BASE_URL)
|
||||
|
||||
def test_api_base_url_prefers_base_url_when_enabled(self):
|
||||
self.assertEqual(
|
||||
api_base_url_from_env(
|
||||
environ={
|
||||
"BASE_URL": "https://base.example.test/",
|
||||
"API_BASE_URL": "https://api.example.test/",
|
||||
},
|
||||
),
|
||||
"https://base.example.test",
|
||||
)
|
||||
|
||||
def test_api_base_url_can_preserve_api_env_only_behavior(self):
|
||||
self.assertEqual(
|
||||
api_base_url_from_env(
|
||||
environ={
|
||||
"BASE_URL": "https://ignored.example.test/",
|
||||
"API_BASE_URL": "https://api.example.test/",
|
||||
},
|
||||
include_base_url=False,
|
||||
),
|
||||
"https://api.example.test",
|
||||
)
|
||||
|
||||
def test_service_url_from_env_uses_first_configured_name(self):
|
||||
self.assertEqual(
|
||||
service_url_from_env(
|
||||
("PRIMARY_URL", "SECONDARY_URL"),
|
||||
environ={"SECONDARY_URL": "https://secondary.example.test/"},
|
||||
fallback="https://fallback.example.test",
|
||||
),
|
||||
"https://secondary.example.test",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
32
tests/backend/service_endpoints_shell_test.py
Normal file
32
tests/backend/service_endpoints_shell_test.py
Normal file
@ -0,0 +1,32 @@
|
||||
import pathlib
|
||||
import subprocess
|
||||
|
||||
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
|
||||
|
||||
def run_shell(script: str) -> str:
|
||||
result = subprocess.run(
|
||||
["bash", "-c", script],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
text=True,
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
)
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def test_shell_service_endpoint_helper_defaults_and_normalizes_urls():
|
||||
output = run_shell(
|
||||
"source scripts/lib/service-endpoints.sh; "
|
||||
"droboticflow_default_api_base_url; "
|
||||
"droboticflow_default_worker_base_url; "
|
||||
"droboticflow_first_service_url '' 'https://api.example.test///'"
|
||||
)
|
||||
|
||||
assert output.splitlines() == [
|
||||
"http://127.0.0.1:3001",
|
||||
"http://127.0.0.1:3002",
|
||||
"https://api.example.test",
|
||||
]
|
||||
94
tests/frontend/service-endpoints.test.mjs
Normal file
94
tests/frontend/service-endpoints.test.mjs
Normal file
@ -0,0 +1,94 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import {
|
||||
DEFAULT_API_BASE_URL,
|
||||
DEFAULT_WORKER_BASE_URL,
|
||||
apiBaseURLFromEnv,
|
||||
firstNonEmpty,
|
||||
serviceURLFromEnv,
|
||||
trimTrailingSlash,
|
||||
viteProxyTargets,
|
||||
workerBaseURLFromEnv,
|
||||
} from "../../scripts/lib/service-endpoints.mjs";
|
||||
|
||||
test("normalizes service endpoint strings", () => {
|
||||
assert.equal(trimTrailingSlash(" https://api.example.test/// "), "https://api.example.test");
|
||||
assert.equal(firstNonEmpty("", " ", "http://127.0.0.1:3001/"), "http://127.0.0.1:3001");
|
||||
});
|
||||
|
||||
test("resolves API base URL with explicit precedence", () => {
|
||||
assert.equal(apiBaseURLFromEnv({ env: {}, cliArgs: ["node", "script"] }), DEFAULT_API_BASE_URL);
|
||||
assert.equal(
|
||||
apiBaseURLFromEnv({
|
||||
env: { API_BASE_URL: "https://api-env.example.test/" },
|
||||
cliArgs: ["node", "script", "https://api-cli.example.test"],
|
||||
}),
|
||||
"https://api-env.example.test",
|
||||
);
|
||||
assert.equal(
|
||||
apiBaseURLFromEnv({
|
||||
env: {},
|
||||
cliArgs: ["node", "script", "https://api-cli.example.test///"],
|
||||
}),
|
||||
"https://api-cli.example.test",
|
||||
);
|
||||
});
|
||||
|
||||
test("resolves worker base URL from worker-specific env", () => {
|
||||
assert.equal(workerBaseURLFromEnv({ env: {}, cliArgs: [] }), DEFAULT_WORKER_BASE_URL);
|
||||
assert.equal(
|
||||
workerBaseURLFromEnv({
|
||||
env: { WORKER_API_BASE_URL: "https://worker-api.example.test/" },
|
||||
cliArgs: [],
|
||||
}),
|
||||
"https://worker-api.example.test",
|
||||
);
|
||||
assert.equal(
|
||||
workerBaseURLFromEnv({
|
||||
env: { WORKER_BASE_URL: "https://worker.example.test/", WORKER_API_BASE_URL: "https://ignored.example.test" },
|
||||
cliArgs: [],
|
||||
}),
|
||||
"https://worker.example.test",
|
||||
);
|
||||
});
|
||||
|
||||
test("resolves Vite proxy targets from dedicated dev env", () => {
|
||||
assert.deepEqual(viteProxyTargets({}), {
|
||||
api: DEFAULT_API_BASE_URL,
|
||||
worker: DEFAULT_WORKER_BASE_URL,
|
||||
});
|
||||
assert.deepEqual(
|
||||
viteProxyTargets({
|
||||
BASE_URL: "https://runtime.example.test",
|
||||
API_BASE_URL: "https://api-runtime.example.test",
|
||||
WORKER_API_BASE_URL: "https://worker-runtime.example.test",
|
||||
}),
|
||||
{
|
||||
api: DEFAULT_API_BASE_URL,
|
||||
worker: DEFAULT_WORKER_BASE_URL,
|
||||
},
|
||||
);
|
||||
assert.deepEqual(
|
||||
viteProxyTargets({
|
||||
BASE_URL: "https://runtime.example.test",
|
||||
VITE_DEV_API_BASE_URL: "https://vite-api.example.test/",
|
||||
VITE_DEV_WORKER_BASE_URL: "https://vite-worker.example.test/",
|
||||
}),
|
||||
{
|
||||
api: "https://vite-api.example.test",
|
||||
worker: "https://vite-worker.example.test",
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("allows direct custom service endpoint candidate lists", () => {
|
||||
assert.equal(
|
||||
serviceURLFromEnv({
|
||||
env: { SECONDARY_URL: "https://secondary.example.test/" },
|
||||
names: ["PRIMARY_URL", "SECONDARY_URL"],
|
||||
fallback: "https://fallback.example.test",
|
||||
}),
|
||||
"https://secondary.example.test",
|
||||
);
|
||||
});
|
||||
@ -2,8 +2,11 @@ import tailwindcss from "@tailwindcss/vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import path from "path";
|
||||
import { defineConfig } from "vite";
|
||||
import { viteProxyTargets } from "./scripts/lib/service-endpoints.mjs";
|
||||
|
||||
export default defineConfig(() => {
|
||||
const proxyTargets = viteProxyTargets(process.env);
|
||||
|
||||
return {
|
||||
plugins: [react(), tailwindcss()],
|
||||
build: {
|
||||
@ -44,11 +47,11 @@ export default defineConfig(() => {
|
||||
},
|
||||
server: {
|
||||
// HMR is disabled in AI Studio via DISABLE_HMR env var.
|
||||
// Do not modifyâfile watching is disabled to prevent flickering during agent edits.
|
||||
// Do not modify: file watching is disabled to prevent flickering during agent edits.
|
||||
hmr: process.env.DISABLE_HMR !== "true",
|
||||
proxy: {
|
||||
"/api": "http://127.0.0.1:3001",
|
||||
"/worker-api": "http://127.0.0.1:3002",
|
||||
"/api": proxyTargets.api,
|
||||
"/worker-api": proxyTargets.worker,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user