feature: handle delete operation for IPs

This commit is contained in:
ayurishchev committed 2026-08-23 22:24:55 +03:00
1 parent 4f597505cc
commit f8336740ad
20 files changed
+1083 -5

No files matched your search

+21
View File
@@ -115,6 +115,27 @@ func (c *client) CancelIP(ctx context.Context, ip string) error {
return c.do(ctx, http.MethodPost, "/api/v1/admin/ips/"+url.PathEscape(ip)+"/cancel", nil, nil)
}
// DeleteIP permanently removes one address and its full history — unlike
// CancelIP, there's nothing left to look up afterward.
func (c *client) DeleteIP(ctx context.Context, ip string) error {
return c.do(ctx, http.MethodDelete, "/api/v1/admin/ips/"+url.PathEscape(ip), nil, nil)
}
// DeleteIPs permanently removes a specific list of addresses in one call.
func (c *client) DeleteIPs(ctx context.Context, addresses []string) (deleteIPsResponse, error) {
var out deleteIPsResponse
err := c.do(ctx, http.MethodPost, "/api/v1/admin/ips/delete", map[string][]string{"addresses": addresses}, &out)
return out, err
}
// ClearQueue permanently removes every address currently in the queue,
// including those actively being checked.
func (c *client) ClearQueue(ctx context.Context) (clearQueueResponse, error) {
var out clearQueueResponse
err := c.do(ctx, http.MethodPost, "/api/v1/admin/ips/clear", nil, &out)
return out, err
}
func (c *client) ListValidators(ctx context.Context) ([]validatorDTO, error) {
var out []validatorDTO
err := c.do(ctx, http.MethodGet, "/api/v1/admin/config/validators", nil, &out)
+48
View File
@@ -139,6 +139,54 @@ func (f *fakeControlAPI) handler() http.Handler {
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
})
mux.HandleFunc("DELETE /api/v1/admin/ips/{ip}", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
addr := r.PathValue("ip")
idx := f.findIP(addr)
if idx < 0 {
writeAPIErr(w, http.StatusNotFound, "unknown ip: "+addr)
return
}
f.ips = append(f.ips[:idx], f.ips[idx+1:]...)
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
})
mux.HandleFunc("POST /api/v1/admin/ips/delete", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
var req struct {
Addresses []string `json:"addresses"`
}
_ = json.NewDecoder(r.Body).Decode(&req)
if len(req.Addresses) == 0 {
writeAPIErr(w, http.StatusBadRequest, "addresses must not be empty")
return
}
resp := deleteIPsResponse{}
for _, addr := range req.Addresses {
idx := f.findIP(addr)
if idx < 0 {
resp.NotFound = append(resp.NotFound, addr)
continue
}
f.ips = append(f.ips[:idx], f.ips[idx+1:]...)
resp.Deleted = append(resp.Deleted, addr)
}
writeJSON(w, http.StatusOK, resp)
})
mux.HandleFunc("POST /api/v1/admin/ips/clear", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
resp := clearQueueResponse{}
for _, ip := range f.ips {
resp.Deleted = append(resp.Deleted, ip.IPAddress)
}
f.ips = nil
writeJSON(w, http.StatusOK, resp)
})
mux.HandleFunc("GET /api/v1/admin/config/validators", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
+9
View File
@@ -89,6 +89,15 @@ type submitIPsResponse struct {
SkippedInProgress []string `json:"skipped_in_progress"`
}
type deleteIPsResponse struct {
Deleted []string `json:"deleted"`
NotFound []string `json:"not_found"`
}
type clearQueueResponse struct {
Deleted []string `json:"deleted"`
}
type validatorDTO struct {
ValidatorID string `json:"validator_id"`
OSPortID string `json:"os_port_id"`
+25
View File
@@ -69,3 +69,28 @@ func (s *Server) handleIPCancel(w http.ResponseWriter, r *http.Request) {
err := s.CA.CancelIP(r.Context(), ip)
s.renderIPsTable(w, r, err)
}
func (s *Server) handleIPDelete(w http.ResponseWriter, r *http.Request) {
ip := r.PathValue("ip")
err := s.CA.DeleteIP(r.Context(), ip)
s.renderIPsTable(w, r, err)
}
func (s *Server) handleIPsDeleteSelected(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
s.renderIPsTable(w, r, fmt.Errorf("invalid form: %w", err))
return
}
addresses := r.Form["addresses"]
if len(addresses) == 0 {
s.renderIPsTable(w, r, &apiErr{Status: http.StatusBadRequest, Message: "ничего не выбрано"})
return
}
_, err := s.CA.DeleteIPs(r.Context(), addresses)
s.renderIPsTable(w, r, err)
}
func (s *Server) handleIPsClear(w http.ResponseWriter, r *http.Request) {
_, err := s.CA.ClearQueue(r.Context())
s.renderIPsTable(w, r, err)
}
+70
View File
@@ -105,6 +105,76 @@ func TestIPCancel(t *testing.T) {
}
}
func TestIPDelete(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
now := time.Now()
fake.ips = []ipQueueItem{{IPAddress: "7.7.7.7", State: "checking", UpdatedAt: now, CreatedAt: now}}
ts := newTestServer(t, caURL)
body := postForm(t, ts, "DELETE", "/ips/7.7.7.7", nil)
if strings.Contains(body, "7.7.7.7") {
t.Fatalf("expected 7.7.7.7 removed from table, got:\n%s", body)
}
if len(fake.ips) != 0 {
t.Fatalf("expected fake control-api queue empty, got %+v", fake.ips)
}
// Deleting an already-gone address is a 404, surfaced via banner.
body = postForm(t, ts, "DELETE", "/ips/7.7.7.7", nil)
if !strings.Contains(body, "error-banner") {
t.Fatalf("expected error banner deleting unknown ip, got:\n%s", body)
}
}
func TestIPsDeleteSelected(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
now := time.Now()
fake.ips = []ipQueueItem{
{IPAddress: "1.1.1.1", State: "queued", UpdatedAt: now, CreatedAt: now},
{IPAddress: "2.2.2.2", State: "queued", UpdatedAt: now, CreatedAt: now},
{IPAddress: "3.3.3.3", State: "queued", UpdatedAt: now, CreatedAt: now},
}
ts := newTestServer(t, caURL)
body := postForm(t, ts, "POST", "/ips/delete", map[string][]string{"addresses": {"1.1.1.1", "2.2.2.2"}})
if strings.Contains(body, "1.1.1.1") || strings.Contains(body, "2.2.2.2") {
t.Fatalf("expected selected addresses removed, got:\n%s", body)
}
if !strings.Contains(body, "3.3.3.3") {
t.Fatalf("expected untouched address still listed, got:\n%s", body)
}
if len(fake.ips) != 1 || fake.ips[0].IPAddress != "3.3.3.3" {
t.Fatalf("expected only 3.3.3.3 left in fake control-api, got %+v", fake.ips)
}
// Empty selection is a client error banner, not a 500.
body = postForm(t, ts, "POST", "/ips/delete", nil)
if !strings.Contains(body, "alert-warning") {
t.Fatalf("expected client error banner for empty selection, got:\n%s", body)
}
}
func TestIPsClear(t *testing.T) {
fake, caURL := newFakeControlAPI(t)
now := time.Now()
fake.ips = []ipQueueItem{
{IPAddress: "1.1.1.1", State: "checking", UpdatedAt: now, CreatedAt: now},
{IPAddress: "2.2.2.2", State: "queued", UpdatedAt: now, CreatedAt: now},
}
ts := newTestServer(t, caURL)
body := postForm(t, ts, "POST", "/ips/clear", nil)
if strings.Contains(body, "1.1.1.1") || strings.Contains(body, "2.2.2.2") {
t.Fatalf("expected all addresses removed, got:\n%s", body)
}
if !strings.Contains(body, "Очередь пуста") {
t.Fatalf("expected empty-queue message, got:\n%s", body)
}
if len(fake.ips) != 0 {
t.Fatalf("expected fake control-api queue empty, got %+v", fake.ips)
}
}
func TestValidatorsCRUD(t *testing.T) {
_, caURL := newFakeControlAPI(t)
ts := newTestServer(t, caURL)
+3
View File
@@ -13,6 +13,9 @@ func (s *Server) routes(mux *http.ServeMux) {
mux.HandleFunc("POST /ips", s.handleIPsSubmit)
mux.HandleFunc("POST /ips/{ip}/recheck", s.handleIPRecheck)
mux.HandleFunc("POST /ips/{ip}/cancel", s.handleIPCancel)
mux.HandleFunc("DELETE /ips/{ip}", s.handleIPDelete)
mux.HandleFunc("POST /ips/delete", s.handleIPsDeleteSelected)
mux.HandleFunc("POST /ips/clear", s.handleIPsClear)
mux.HandleFunc("GET /validators", s.handleValidatorsPage)
mux.HandleFunc("POST /validators", s.handleValidatorCreate)
+9 -1
View File
@@ -43,15 +43,21 @@
{{end}}
{{define "ips_table"}}
<form id="ips-form">
<div class="panel">
<div class="panel-body" style="display:flex; gap:8px; align-items:center;">
<button type="button" class="btn btn-danger-ghost btn-sm" hx-post="/ips/delete" hx-target="#ips-table-wrap" hx-swap="innerHTML" hx-confirm="Удалить выбранные адреса без возможности восстановления?">Удалить выбранные</button>
<button type="button" class="btn btn-danger-ghost btn-sm" hx-post="/ips/clear" hx-target="#ips-table-wrap" hx-swap="innerHTML" hx-confirm="Удалить ВСЕ адреса из очереди, включая те, что сейчас проверяются? Действие необратимо.">Очистить всё</button>
</div>
<div class="table-scroll">
<table>
<thead><tr><th>Адрес</th><th>Состояние</th><th>Валидатор</th><th>Попытка</th><th>Обновлено</th><th></th></tr></thead>
<thead><tr><th><input type="checkbox" onclick="this.closest('table').querySelectorAll('input[name=addresses]').forEach(cb => cb.checked = this.checked)"></th><th>Адрес</th><th>Состояние</th><th>Валидатор</th><th>Попытка</th><th>Обновлено</th><th></th></tr></thead>
<tbody>
{{range .Items}}
{{$b := ipBadge .State .OverallResult}}
{{$terminal := or (eq .State "done") (eq .State "failed")}}
<tr>
<td data-label=""><input type="checkbox" name="addresses" value="{{.IPAddress}}"></td>
<td class="addr" data-label="Адрес"><a href="/ips/{{.IPAddress}}">{{.IPAddress}}</a></td>
<td data-label="Состояние"><span class="pill {{$b.Class}}">{{$b.Label}}</span></td>
<td data-label="Валидатор">{{deref .OwnerValidatorID}}</td>
@@ -64,6 +70,7 @@
{{else}}
<button class="btn btn-danger-ghost btn-sm" hx-post="/ips/{{.IPAddress}}/cancel" hx-target="#ips-table-wrap" hx-swap="innerHTML" hx-confirm="Остановить проверку {{.IPAddress}}?">Отменить</button>
{{end}}
<button class="btn btn-danger-ghost btn-sm" hx-delete="/ips/{{.IPAddress}}" hx-target="#ips-table-wrap" hx-swap="innerHTML" hx-confirm="Удалить {{.IPAddress}} без возможности восстановления?">Удалить</button>
</div>
</td>
</tr>
@@ -72,5 +79,6 @@
</table>
</div>
</div>
</form>
{{if not .Items}}<p class="muted">Очередь пуста.</p>{{end}}
{{end}}