feat(ui): mark unhealthy environment toggles (#82)
## Use case Environment toggle buttons get a red border when the environment pipeline contains a failed or unfinished step. The state updates with WebSocket environment updates and does not disable the toggle. ## Verification - `node --check frontend/app.js` - `git diff --check` - `27 passed, 1 skipped`; 4 Playwright tests blocked by unavailable `/var/run/docker.sock` --------- Co-authored-by: rudolf <rudolfss13@gmail.com> Reviewed-on: #82 Co-authored-by: hermes <rudolfss13+hermes@gmail.com>
This commit was merged in pull request #82.
This commit is contained in:
+11
-2
@@ -51,11 +51,20 @@ class App:
|
||||
"is_running": False,
|
||||
})
|
||||
else:
|
||||
pipeline_state.append({
|
||||
step_state = {
|
||||
"name": r.name,
|
||||
"status": result,
|
||||
"is_running": False,
|
||||
})
|
||||
}
|
||||
step_errors = getattr(r, "errors", [])
|
||||
if step_errors:
|
||||
step_state["status"] = {"result": result, "errors": step_errors}
|
||||
step_state["error"] = True
|
||||
step_warnings = getattr(r, "warnings", [])
|
||||
if step_warnings and not step_errors:
|
||||
step_state["status"] = {"result": result, "warnings": step_warnings}
|
||||
step_state["warning"] = True
|
||||
pipeline_state.append(step_state)
|
||||
except BaseException as e:
|
||||
stack = traceback.format_exception(type(e), e, e.__traceback__)
|
||||
pipeline_state.append({
|
||||
|
||||
+36
-20
@@ -71,6 +71,7 @@ class GitClone(AbstractStep[str]):
|
||||
self.repo_path = repo_path
|
||||
self.branchNamePrefix = branchNamePrefix
|
||||
self.credEnvPrefix = credEnvPrefix
|
||||
self.errors: List[str] = []
|
||||
|
||||
def _get_auth_git_url(self, url: str) -> str:
|
||||
username = os.getenv(f'{self.credEnvPrefix}_USERNAME')
|
||||
@@ -83,6 +84,7 @@ class GitClone(AbstractStep[str]):
|
||||
return url
|
||||
|
||||
def progress(self) -> str:
|
||||
self.errors = []
|
||||
self.repo_path = self.repo_path or os.path.join(tempfile.gettempdir(),
|
||||
f"{self.env.id}_{hashlib.sha1('|'.join(self.urls).encode()).hexdigest()[:5]}")
|
||||
logger.info(f"Cloning repositories {self.remotes} to {self.repo_path}")
|
||||
@@ -94,29 +96,39 @@ class GitClone(AbstractStep[str]):
|
||||
else:
|
||||
repo = git.Repo.init(self.repo_path)
|
||||
|
||||
fetched_remotes = 0
|
||||
for entry in self.remotes:
|
||||
remote_name = entry["name"]
|
||||
repository_url = entry["url"]
|
||||
auth_url = self._get_auth_git_url(repository_url)
|
||||
if remote_name in repo.remotes:
|
||||
remote = repo.remotes[remote_name]
|
||||
if remote.url != auth_url:
|
||||
remote.set_url(auth_url)
|
||||
else:
|
||||
remote = repo.create_remote(remote_name, auth_url)
|
||||
with repo.config_writer() as config:
|
||||
config.set_value(
|
||||
f'remote "{remote_name}"',
|
||||
'fetch',
|
||||
f'+refs/heads/*:refs/remotes/{remote_name}/*',
|
||||
)
|
||||
if remote_name == "origin" and self.branchNamePrefix != "":
|
||||
try:
|
||||
auth_url = self._get_auth_git_url(repository_url)
|
||||
if remote_name in repo.remotes:
|
||||
remote = repo.remotes[remote_name]
|
||||
if remote.url != auth_url:
|
||||
remote.set_url(auth_url)
|
||||
else:
|
||||
remote = repo.create_remote(remote_name, auth_url)
|
||||
with repo.config_writer() as config:
|
||||
config.set_value('remote "origin"', "fetch",
|
||||
f"+refs/heads/{self.branchNamePrefix}/*:refs/remotes/origin/{self.branchNamePrefix}/*")
|
||||
result = remote.fetch(prune=True)
|
||||
if not result or any(fetch_info.flags & fetch_info.ERROR for fetch_info in result):
|
||||
raise BaseException(f"Failed to fetch updates for {remote_name}")
|
||||
config.set_value(
|
||||
f'remote "{remote_name}"',
|
||||
'fetch',
|
||||
f'+refs/heads/*:refs/remotes/{remote_name}/*',
|
||||
)
|
||||
if remote_name == "origin" and self.branchNamePrefix != "":
|
||||
with repo.config_writer() as config:
|
||||
config.set_value('remote "origin"', "fetch",
|
||||
f"+refs/heads/{self.branchNamePrefix}/*:refs/remotes/origin/{self.branchNamePrefix}/*")
|
||||
result = remote.fetch(prune=True)
|
||||
if not result or any(fetch_info.flags & fetch_info.ERROR for fetch_info in result):
|
||||
raise BaseException(f"Failed to fetch updates for {remote_name}")
|
||||
fetched_remotes += 1
|
||||
except BaseException as remote_error:
|
||||
if "File contains no section headers" in str(remote_error):
|
||||
raise
|
||||
self.errors.append(f"Unable to fetch remote {remote_name} ({repository_url}): {remote_error}")
|
||||
logger.warning("Unable to fetch remote %s (%s): %s", remote_name, repository_url, remote_error)
|
||||
if fetched_remotes == 0:
|
||||
logger.warning("No configured git remotes are available; keeping the local repository state")
|
||||
if not os.path.exists(os.path.join(self.repo_path, ".git")):
|
||||
raise BaseException(f"Failed to clone repositories {self.remotes} to {self.repo_path}")
|
||||
except BaseException as e:
|
||||
@@ -353,9 +365,12 @@ class GitUnmerge(AbstractStep[GitUnmergeResult]):
|
||||
super().__init__(**kwargs)
|
||||
self.wd = wd
|
||||
self.check = check
|
||||
self.warnings: List[str] = []
|
||||
|
||||
def progress(self) -> GitUnmergeResult:
|
||||
self.warnings = []
|
||||
wd = self.wd.progress()
|
||||
repo = git.Repo(wd)
|
||||
deployState: Mapping[str, HasVersion] = self.check.progress()
|
||||
|
||||
versions = set([it.version for it in deployState.values()])
|
||||
@@ -363,9 +378,10 @@ class GitUnmerge(AbstractStep[GitUnmergeResult]):
|
||||
raise BaseException(f"Expected exactly one version, got: {versions}")
|
||||
|
||||
version = list(versions)[0]
|
||||
if not version:
|
||||
return GitUnmergeResult(branches=[], columns={"Deployed": {}})
|
||||
if version is None:
|
||||
raise BaseException(f"Expected exactly one version, got: {versions}")
|
||||
repo = git.Repo(wd)
|
||||
childs: Dict[Commit, List[Commit]] | None = None
|
||||
if version.startswith(AUTO_BRANCH_PREFIX):
|
||||
version_parts = version[len(AUTO_BRANCH_PREFIX):].split('-')
|
||||
|
||||
@@ -26,6 +26,20 @@
|
||||
|
||||
Эти тесты не покрывают весь пользовательский сценарий целиком: например, проверка `GET /state` на HTTP 200 не проверяет все поля ответа, а локальный container test не является тестом Docker Swarm rollout.
|
||||
|
||||
## Непокрытые UI-сценарии
|
||||
|
||||
### NU-09. Красная рамка toggle-кнопки при проблемном pipeline
|
||||
|
||||
**Требование:** [U-06](USE_CASES_UI.md#u-06-отфильтровать-окружения-toggle-кнопками).
|
||||
|
||||
Нет автоматического UI-теста, который проверяет:
|
||||
|
||||
- красную рамку для окружения с `error`-шагом;
|
||||
- красную рамку для окружения с `is_running`-шагом;
|
||||
- отсутствие красной рамки у окружения, где все шаги завершены успешно;
|
||||
- обновление рамки после WebSocket-сообщения с новым pipeline state;
|
||||
- сохранение возможности включать и выключать проблемную toggle-кнопку.
|
||||
|
||||
## Непокрытые backend-сценарии
|
||||
|
||||
### NB-01. Получение главной страницы и static resource
|
||||
|
||||
@@ -60,6 +60,8 @@ Brencher показывает оператору состояние Git-исто
|
||||
6. Если все toggle-кнопки выключены, UI показывает все окружения.
|
||||
7. Фильтр меняет только отображение и не изменяет серверное состояние.
|
||||
8. Обновление состояния не должно сбрасывать активный выбор toggle-кнопок, если выбранные окружения всё ещё существуют.
|
||||
9. Если pipeline окружения содержит хотя бы один неуспешный (`error`) или незаконченный (`is_running`) шаг, соответствующая toggle-кнопка получает красную рамку.
|
||||
10. Красная рамка обновляется вместе с состоянием pipeline и не изменяет доступность или поведение toggle-кнопки.
|
||||
|
||||
### U-06a. Отфильтровать окружения текстом
|
||||
|
||||
|
||||
+32
-11
@@ -89,6 +89,12 @@ function filterBranches() {
|
||||
renderBranches();
|
||||
}
|
||||
|
||||
function environmentHasPipelineProblem(envObj) {
|
||||
return Array.isArray(envObj.pipeline) && envObj.pipeline.some(job =>
|
||||
job && (job.error || job.is_running)
|
||||
);
|
||||
}
|
||||
|
||||
function renderEnvironmentFilters() {
|
||||
const environments = environmentsRaw
|
||||
.filter(envObj => envObj && (envObj.id || envObj.name))
|
||||
@@ -98,9 +104,14 @@ function renderEnvironmentFilters() {
|
||||
[...activeEnvFilters].forEach(envId => {
|
||||
if (!environmentIds.has(envId)) activeEnvFilters.delete(envId);
|
||||
});
|
||||
envFilterToggles.innerHTML = environments.map(({id, name}) => `
|
||||
<button type="button" class="env-filter-toggle${activeEnvFilters.has(id) ? ' active' : ''}" data-env="${escapeHtml(id)}" aria-pressed="${activeEnvFilters.has(id)}">${escapeHtml(name)}</button>
|
||||
`).join('');
|
||||
envFilterToggles.innerHTML = environments.map(({id, name}) => {
|
||||
const hasPipelineProblem = environmentHasPipelineProblem(
|
||||
environmentsRaw.find(envObj => (envObj.id || envObj.name) === id) || {}
|
||||
);
|
||||
return `
|
||||
<button type="button" class="env-filter-toggle${activeEnvFilters.has(id) ? ' active' : ''}${hasPipelineProblem ? ' has-pipeline-problem' : ''}" data-env="${escapeHtml(id)}" aria-pressed="${activeEnvFilters.has(id)}"${hasPipelineProblem ? ' title="Pipeline has failed or unfinished steps"' : ''}>${escapeHtml(name)}</button>
|
||||
`;
|
||||
}).join('');
|
||||
envFilterToggles.querySelectorAll('.env-filter-toggle').forEach(button => {
|
||||
button.onclick = () => {
|
||||
const envId = button.dataset.env;
|
||||
@@ -184,11 +195,6 @@ function renderBranches() {
|
||||
checkForPendingChanges();
|
||||
|
||||
const branchesToShow = filteredBranches.length > 0 || branchFilter.value.trim() || activeEnvFilters.size > 0 ? filteredBranches : branches;
|
||||
if (!branchesToShow.length) {
|
||||
branchesList.innerHTML = '<p class="loading">No branches found.</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
// Group by envId for clearer separation
|
||||
const groups = branchesToShow.reduce((acc, b) => {
|
||||
acc[b.envId] = acc[b.envId] || {envName: b.envName, rows: []};
|
||||
@@ -196,18 +202,30 @@ function renderBranches() {
|
||||
return acc;
|
||||
}, {});
|
||||
|
||||
environmentsRaw
|
||||
.filter(envObj => envObj && (activeEnvFilters.size === 0 || activeEnvFilters.has(envObj.id || envObj.name)))
|
||||
.forEach(envObj => {
|
||||
const envId = envObj.id || envObj.name;
|
||||
if (!groups[envId]) groups[envId] = {envName: envObj.name || envId, rows: []};
|
||||
});
|
||||
|
||||
if (!Object.keys(groups).length) {
|
||||
branchesList.innerHTML = '<p class="loading">No branches found.</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
branchesList.innerHTML = Object.entries(groups).map(([envId, {envName, rows}]) => {
|
||||
const envCols = columnsByEnv[envId] || {};
|
||||
const colNames = Object.keys(envCols);
|
||||
return `
|
||||
<div class="env-block">
|
||||
<h3 class="env-title">
|
||||
Environment: ${envName || envId}
|
||||
Environment: ${escapeHtml(envName || envId)}
|
||||
<button class="dry-run-btn ${dryRunByEnv[envId] ? 'dry-run-active' : ''}" data-env="${envId}" title="${dryRunByEnv[envId] ? 'Dry run on — click to resume' : 'Running — click to pause (dry run)'}">
|
||||
${dryRunByEnv[envId] ? '▶' : '⏸'}
|
||||
</button>
|
||||
</h3>
|
||||
<table class="branches-table">
|
||||
${rows.length ? `<table class="branches-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Deploy</th>
|
||||
@@ -238,7 +256,7 @@ function renderBranches() {
|
||||
</tr>`;
|
||||
}).join('')}
|
||||
</tbody>
|
||||
</table>
|
||||
</table>` : '<p class="loading">No branches found.</p>'}
|
||||
</div>`;
|
||||
}).join('');
|
||||
// Event wiring
|
||||
@@ -358,6 +376,7 @@ function renderJobs() {
|
||||
const storageKey = 'jobSpoiler:' + key;
|
||||
const safeId = 'spoiler-' + encodeURIComponent(key).replace(/[^a-zA-Z0-9_-]/g, '_');
|
||||
const isError = job.error;
|
||||
const isWarning = job.warning;
|
||||
const isRunning = !!job.is_running;
|
||||
const openByDefault = isError || (window._jobSpoilerState && window._jobSpoilerState[storageKey] === 'open');
|
||||
|
||||
@@ -369,6 +388,8 @@ function renderJobs() {
|
||||
? `<span class="step-spinner" title="Running"></span>`
|
||||
: isError
|
||||
? `<span style="color:#dc3545;font-weight:bold;margin-right:6px;" title="Error">!</span>`
|
||||
: isWarning
|
||||
? `<span style="color:#d99700;font-weight:bold;margin-right:6px;" title="Warning">⚠</span>`
|
||||
: `<span style="color:#28a745;font-weight:bold;margin-right:6px;" title="OK">✔</span>`}
|
||||
${envObj.id} - ${job.name}
|
||||
</div>
|
||||
|
||||
@@ -161,6 +161,10 @@ body {
|
||||
border-color: #007bff;
|
||||
}
|
||||
|
||||
.env-filter-toggle.has-pipeline-problem {
|
||||
border: 2px solid #dc3545;
|
||||
}
|
||||
|
||||
/* Branches table styling */
|
||||
.branches-table {
|
||||
width: 100%;
|
||||
|
||||
@@ -82,6 +82,29 @@ class TestGitIntegration:
|
||||
shutil.rmtree(github_dir, ignore_errors=True)
|
||||
shutil.rmtree(gitea_dir, ignore_errors=True)
|
||||
|
||||
def test_git_clone_keeps_available_remote_when_another_is_unreachable(self, repo_helper: RemoteRepoHelper) -> None:
|
||||
repo_helper.create_commit(repo_helper.repo, "master", "master", "README.md", "content", "Initial commit")
|
||||
clone = GitClone(remotes=[
|
||||
{"name": "available", "url": repo_helper.remote_dir},
|
||||
{"name": "unreachable", "url": "/does/not/exist"},
|
||||
])
|
||||
clone.env = repo_helper.env
|
||||
|
||||
clone.progress()
|
||||
|
||||
assert "available/master" in clone.get_branches()
|
||||
assert len(clone.errors) == 1
|
||||
assert "unreachable" in clone.errors[0]
|
||||
|
||||
def test_git_clone_keeps_empty_repository_when_all_remotes_are_unreachable(self, repo_helper: RemoteRepoHelper) -> None:
|
||||
clone = GitClone(url="/does/not/exist")
|
||||
clone.env = repo_helper.env
|
||||
|
||||
repo_path = clone.progress()
|
||||
|
||||
assert os.path.isdir(os.path.join(repo_path, ".git"))
|
||||
assert clone.get_branches() == {}
|
||||
|
||||
def test_git_clone_remotes_validation(self) -> None:
|
||||
# Empty list: rejected (would produce an unusable clone).
|
||||
with pytest.raises(ValueError, match="At least one repository URL is required"):
|
||||
@@ -347,6 +370,15 @@ class TestGitIntegration:
|
||||
with pytest.raises(BaseException, match="Version format not recognized"):
|
||||
repo_helper.git_unmerge.progress()
|
||||
|
||||
def test_git_unmerge_empty_version_uses_default_branch(self, repo_helper: RemoteRepoHelper) -> None:
|
||||
repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content", "Initial commit")
|
||||
repo_helper.set_desired_branches([])
|
||||
repo_helper.mock_check.version = lambda: "" # type: ignore[attr-defined]
|
||||
|
||||
result = repo_helper.git_unmerge.progress()
|
||||
|
||||
assert result.branches == [()]
|
||||
|
||||
def test_git_unmerge_nonhead_commit(self, repo_helper: RemoteRepoHelper) -> None:
|
||||
# Create initial commit
|
||||
commit1 = repo_helper.create_commit(repo_helper.repo, "master", "master", "file1.txt", "content1",
|
||||
|
||||
Reference in New Issue
Block a user