Ticket contract for automated reporters: dedup_key, source, links, reopen window (#123)
Lint / JS (eslint) (push) Successful in 14s
Lint / PHP (phpcs PSR-12) (push) Successful in 44s
Lint / PHP requirements (version + extensions) (push) Successful in 42s
Lint / Deploy (push) Skipped
Lint / Notify on failure (push) Skipped
Lint / PHP (phpcs PSR-12) (pull_request) Successful in 1m15s
Lint / JS (eslint) (pull_request) Successful in 34s
Lint / PHP requirements (version + extensions) (pull_request) Successful in 42s
Lint / Deploy (pull_request) Skipped
Lint / Notify on failure (pull_request) Skipped
Security / PHP Security (semgrep) (push) Successful in 4m13s
Security / PHP Security (semgrep) (pull_request) Successful in 3m25s
Lint / JS (eslint) (push) Successful in 14s
Lint / PHP (phpcs PSR-12) (push) Successful in 44s
Lint / PHP requirements (version + extensions) (push) Successful in 42s
Lint / Deploy (push) Skipped
Lint / Notify on failure (push) Skipped
Lint / PHP (phpcs PSR-12) (pull_request) Successful in 1m15s
Lint / JS (eslint) (pull_request) Successful in 34s
Lint / PHP requirements (version + extensions) (pull_request) Successful in 42s
Lint / Deploy (pull_request) Skipped
Lint / Notify on failure (pull_request) Skipped
Security / PHP Security (semgrep) (push) Successful in 4m13s
Security / PHP Security (semgrep) (pull_request) Successful in 3m25s
From the thor#1 plan: each reporter (gandalf, hwmonDaemon, thor) decides
what "the same problem" is, and Tinker enforces it.
- dedup_key on create_ticket_api.php (scope:subject:kind, A-Za-z0-9_.:-,
case-sensitive). The hash becomes sha256("key:" + key) and the title is
not looked at; an invalid key is a 400. Keyless callers hash exactly as
before (checked over every prod title).
- Recurrence window for every reporter, keyed or not: a match on a ticket
closed under AUTO_REOPEN_WINDOW_DAYS (7) ago reopens it as before
(subject to the Workflow Designer); an older one gets a new ticket that
takes over the dedup slot (tickets.hash stays UNIQUE, the old ticket
gives it up), carries the key, records recurrence_of, is linked
relates_to, and gets a history comment. action: new_recurrence.
- GET api/tickets_api.php?dedup_key= returns the newest ticket with that
key plus its recurrence chain; ?source= filters the list.
- New api/ticket_link_api.php (link/unlink, read_write) through
DependencyService::link()/unlink(), now shared with MCP
link_tickets/unlink_tickets; audit rows record the key name.
- tickets.source records the API key name. Shown as the creator instead of
"System" on the dashboard and ticket page, a Source filter in the
sidebar, source in MCP results and a search_tickets filter. Comments the
create API writes name the reporter instead of a hard-coded
"hwmonDaemon", and system-linked comments display that name.
- Migration 008 (dedup_key, source, recurrence_of). Scripts:
backfill_ticket_source.php (pre-#123 tickets, where certain) and
backfill_dedup_keys.php (mapping file supplied by the app).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
13ffc51cb7
commit
7061c40d4d
20 files changed
+1025
-206
No files matched your search
@@ -94,3 +94,8 @@ AVATAR_CACHE_TTL=3600
|
||||
; Bearer-key API traffic is rate-limited separately, per API key.
|
||||
RATE_LIMIT_DEFAULT=100
|
||||
RATE_LIMIT_API=60
|
||||
|
||||
; Automated reporters (gandalf, hwmonDaemon, thor): a report matching a ticket
|
||||
; closed less than this many days ago reopens it; an older one opens a new
|
||||
; ticket linked to the old one.
|
||||
AUTO_REOPEN_WINDOW_DAYS=7
|
||||
@@ -108,8 +108,9 @@ All Bearer-authenticated, rate-limited, and (like `create_ticket_api.php`) exemp
|
||||
|
||||
| Endpoint | Method | Scope | Purpose |
|
||||
|----------|--------|-------|---------|
|
||||
| `/create_ticket_api.php` | POST | read_write | Create a ticket (hwmonDaemon, external tools) |
|
||||
| `/api/tickets_api.php` | GET | read | List/triage the queue (`?status=`, `?priority=`, `?host=` [title match], `?page=`, `?limit=`) **or** read one (`?ticket_id=NNN`) with its comments |
|
||||
| `/create_ticket_api.php` | POST | read_write | Create a ticket (gandalf, hwmonDaemon, thor, external tools). Optional `dedup_key`; see [Automated Ticket Creation](#automated-ticket-creation-hwmondaemon) |
|
||||
| `/api/tickets_api.php` | GET | read | List/triage the queue (`?status=`, `?priority=`, `?host=` [title match], `?source=` [reporter, comma-separated], `?page=`, `?limit=`) **or** read one (`?ticket_id=NNN`) with its comments **or** look one up by key (`?dedup_key=K`: the newest ticket with that key in any status, plus `recurrences`, the earlier tickets of its chain) |
|
||||
| `/api/ticket_link_api.php` | POST | read_write | Link two tickets: `{ticket_id, other_ticket_id, relation}`, read as "ticket_id relation other_ticket_id" (`blocks`, `blocked_by`, `relates_to`, `duplicates`); add `"action": "unlink"` to remove one (found from either side). Same checks and audit entries as the Dependencies tab and MCP. 404 for a missing or hidden ticket, 409 if already linked or circular |
|
||||
| `/api/ticket_comment_api.php` | POST | read_write | Add a comment: `{ticket_id, comment_text, markdown_enabled?}` |
|
||||
| `/api/ticket_status_api.php` | POST | read_write | Change/close status (workflow-validated): `{ticket_id, status, comment?}` — `comment` is required for transitions that require one (e.g. → Closed); it is posted as the close reason in the same call |
|
||||
|
||||
@@ -127,7 +128,7 @@ claude mcp login tinker # add --no-browser on a headless machine, the
|
||||
|
||||
| Tool | Scope | What it does |
|
||||
|------|-------|--------------|
|
||||
| `search_tickets` | `tickets:read` | Search/list tickets you can see (text, status, priority, category, assignee `me`/`unassigned`/username), paginated |
|
||||
| `search_tickets` | `tickets:read` | Search/list tickets you can see (text, status, priority, category, assignee `me`/`unassigned`/username, `source` reporter), paginated; results include `source` |
|
||||
| `get_ticket` | `tickets:read` | One ticket's details + comments, its links (Dependencies tab, phrased from this ticket's side incl. `duplicated_by`) and a `blocked` flag (any open `blocked_by`) |
|
||||
| `find_similar_tickets` | `tickets:read` | Open tickets with similar titles, by title text or an existing ticket (same finder as the ticket page's possible-duplicates list) |
|
||||
| `create_ticket` | `tickets:write` | Create a ticket (title, description, priority, category, type, visibility, assignee) |
|
||||
@@ -225,7 +226,10 @@ Content-Type: application/json
|
||||
|
||||
**Key behaviours:**
|
||||
- Authenticated via `Authorization: Bearer` header — API key stored in `/etc/hwmonDaemon/.env`
|
||||
- **Deduplication**: Generates a SHA-256 hash from the issue category, hostname, and device (no time window). A repeat alert matching an existing **open** ticket updates its title/description and escalates the priority if the condition worsened; if the matching ticket was already **closed**, it is reopened instead of creating a new one
|
||||
- **Source**: the API key's name (`gandalf`, `hwmonDaemon`, `thor`) is stored in `tickets.source` and shown as the creator instead of "System"; the dashboard has a Source filter. Comments this endpoint writes (escalation, recurrence) are authored by the key name too. Tickets from before #123: `php scripts/backfill_ticket_source.php --dry-run`, then without
|
||||
- **`dedup_key` (preferred, #123)**: the reporter decides what "the same problem" is by sending `dedup_key` (`scope:subject:kind`, 1-128 of `A-Za-z0-9_.:-`, case-sensitive, e.g. `host:compute-storage-01:oom`, `cluster:ceph:BLUESTORE_SLOW_OP_ALERT`). The hash is then `sha256("key:" + dedup_key)` and the title is not looked at; an invalid key is a 400. When an app starts sending keys, give its existing tickets theirs with `php scripts/backfill_dedup_keys.php --map=file.json [--dry-run]` (the app supplies `{ticket_id: dedup_key}`), or its next reports open duplicates
|
||||
- **Deduplication without a key**: Generates a SHA-256 hash from the issue category, hostname, and device (no time window). A repeat alert matching an existing **open** ticket updates its title/description and escalates the priority if the condition worsened
|
||||
- **Recurrence (every reporter, keyed or not)**: a report matching a **Closed** ticket that closed less than `AUTO_REOPEN_WINDOW_DAYS` (default 7) ago reopens it, if the Workflow Designer allows an unattended reopen (no admin, no comment); otherwise the recurrence is noted on it and it stays Closed (`recurrence_noted`). A ticket closed longer ago is left alone: a **new ticket** takes over the dedup slot, carries the same `dedup_key`, records the old one in `recurrence_of`, is linked `relates_to` it, and gets a history comment (times seen in the last 7 and 30 days, when it last cleared). Response `action`: `created`, `updated`, `deduplicated`, `reopened`, `recurrence_noted` or `new_recurrence` (with `previous_ticket_id`)
|
||||
- Cluster-wide issues (Ceph health, etc.) deduplicate across all nodes (hostname excluded from hash)
|
||||
- Automated network tickets are keyed per problem, not just per host: on the optional `check_code` payload field when sent (it must name the instance, e.g. `iface_down:enp3s0`), otherwise on the title text outside the `[tags]`. After deploying this change (#116), run `php scripts/rehash_network_tickets.php --dry-run`, then without `--dry-run`, so open network tickets keep matching their alerts. The hash logic lives in `helpers/TicketHash.php`
|
||||
- `description` is rendered as markdown on the ticket page, the same as markdown comments (#114). Reporters should send markdown: `##` sections, tables for key/value data and fenced code blocks for raw command output. Fixed-width box layouts lose their alignment.
|
||||
@@ -302,6 +306,7 @@ Content-Type: application/json
|
||||
| `/api/tickets_api.php` | GET | Bearer: list/triage queue or read one ticket + comments |
|
||||
| `/api/ticket_comment_api.php` | POST | Bearer: add a comment (read_write scope) |
|
||||
| `/api/ticket_status_api.php` | POST | Bearer: change/close status, workflow-validated (read_write scope) |
|
||||
| `/api/ticket_link_api.php` | POST | Bearer: link or unlink two tickets (read_write scope) |
|
||||
| `/api/update_ticket.php` | POST | Update ticket with workflow validation |
|
||||
| `/api/assign_ticket.php` | POST | Assign ticket to user |
|
||||
| `/api/add_comment.php` | POST | Add comment to ticket |
|
||||
@@ -438,6 +443,7 @@ tinker_tickets/
|
||||
│ ├── 005_attachment_thumbnails.sql # ticket_attachments.thumbnail_filename
|
||||
│ ├── 006_api_key_visibility_scope.sql # api_keys.see_all_visibility (public-only by default)
|
||||
│ ├── 007_notification_retry_queue.sql # Queue for failed Matrix webhook retries
|
||||
│ ├── 008_dedup_key_source.sql # tickets.dedup_key, source, recurrence_of (#123)
|
||||
│ └── migrate.php # CLI migration runner (tracks applied migrations)
|
||||
├── mcp/
|
||||
│ ├── server.php # MCP endpoint (/mcp): OAuth resource server; only file that loads vendor/
|
||||
@@ -446,12 +452,16 @@ tinker_tickets/
|
||||
│ ├── Tools/ # TicketReadTools, TicketWriteTools
|
||||
│ └── ToolCatalog.php # Tool registry + which tools need tickets:write
|
||||
├── scripts/
|
||||
│ ├── backfill_dedup_keys.php # Give existing tickets a reporter's dedup_keys from its mapping file (#123)
|
||||
│ ├── backfill_ticket_source.php # Set tickets.source on pre-#123 API tickets where the reporter is certain
|
||||
│ ├── check_requirements.php # Verify PHP extensions/config prerequisites
|
||||
│ └── cleanup_orphan_uploads.php # Delete orphaned upload files past grace period (cron)
|
||||
│ ├── cleanup_orphan_uploads.php # Delete orphaned upload files past grace period (cron)
|
||||
│ └── rehash_network_tickets.php # One-off re-key of open network tickets (#116)
|
||||
├── services/
|
||||
│ ├── AssignmentService.php # Assign/unassign (shared by assign_ticket.php + MCP)
|
||||
│ ├── AutoTicketService.php # Automated tickets: insert, reopen window, recurrence chains (create_ticket_api.php)
|
||||
│ ├── CommentService.php # Add/edit/delete comments (shared by the comment endpoints + MCP)
|
||||
│ ├── DependencyService.php # List/add/remove ticket links (shared by ticket_dependencies.php + MCP)
|
||||
│ ├── DependencyService.php # List/add/remove ticket links (shared by ticket_dependencies.php, ticket_link_api.php + MCP)
|
||||
│ ├── SimilarTicketService.php # Similar-title finder (shared by check_duplicates.php + MCP)
|
||||
│ └── TicketCreationService.php # Create ticket (shared by TicketController + MCP)
|
||||
├── uploads/ # File attachment storage (served only via PHP; nginx: internal)
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* ticket_link_api.php — Bearer-key endpoint to link or unlink two tickets (#123).
|
||||
*
|
||||
* POST only. Requires 'read_write' scope. Runs through
|
||||
* DependencyService::link()/unlink(), the same code as the ticket page's
|
||||
* Dependencies tab and the MCP link_tickets / unlink_tickets tools, so the
|
||||
* checks (duplicates from either side, circular blocking chains) and audit
|
||||
* entries match. Audit entries also record the API key's name.
|
||||
*
|
||||
* Body (JSON): {
|
||||
* "ticket_id": "NNN" (required),
|
||||
* "other_ticket_id": "NNN" (required),
|
||||
* "relation": "blocks" | "blocked_by" | "relates_to" | "duplicates",
|
||||
* "action": "link" (default) | "unlink"
|
||||
* }
|
||||
* Read it as "ticket_id <relation> other_ticket_id". Unlink also finds a link
|
||||
* recorded from the other ticket's side.
|
||||
*
|
||||
* Responses: 200 {success, ticket_id, relation, other_ticket_id[, removed]};
|
||||
* 400 bad input; 404 a ticket missing or not visible to this key, or no such
|
||||
* link to remove; 409 already linked or a circular blocking chain.
|
||||
*/
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
require_once dirname(__DIR__) . '/helpers/ErrorHandler.php';
|
||||
ErrorHandler::init();
|
||||
|
||||
require_once dirname(__DIR__) . '/middleware/RateLimitMiddleware.php';
|
||||
RateLimitMiddleware::apply('api');
|
||||
|
||||
require_once dirname(__DIR__) . '/config/config.php';
|
||||
require_once dirname(__DIR__) . '/helpers/Database.php';
|
||||
require_once dirname(__DIR__) . '/middleware/ApiKeyAuth.php';
|
||||
require_once dirname(__DIR__) . '/models/TicketModel.php';
|
||||
require_once dirname(__DIR__) . '/services/DependencyService.php';
|
||||
|
||||
try {
|
||||
$conn = Database::getConnection();
|
||||
} catch (Throwable $e) {
|
||||
error_log('ticket_link_api: DB connection failed: ' . $e->getMessage());
|
||||
http_response_code(500);
|
||||
echo json_encode(['success' => false, 'error' => 'Internal server error']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$apiKeyAuth = new ApiKeyAuth($conn);
|
||||
|
||||
try {
|
||||
$systemUser = $apiKeyAuth->authenticate();
|
||||
} catch (Exception $e) {
|
||||
// ApiKeyAuth already sent the 401 response.
|
||||
exit;
|
||||
}
|
||||
|
||||
// Linking is a write: reject 'read' keys with 403 before any mutation.
|
||||
$apiKeyAuth->requireScope('read_write');
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
http_response_code(405);
|
||||
echo json_encode(['success' => false, 'error' => 'Method not allowed. Use POST.']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$data = json_decode(file_get_contents('php://input'), true);
|
||||
if (!is_array($data)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['success' => false, 'error' => 'Invalid JSON body']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$ticketId = trim((string)($data['ticket_id'] ?? ''));
|
||||
$otherId = trim((string)($data['other_ticket_id'] ?? ''));
|
||||
$relation = (string)($data['relation'] ?? '');
|
||||
$action = strtolower(trim((string)($data['action'] ?? 'link')));
|
||||
if ($ticketId === '' || $otherId === '' || $relation === '') {
|
||||
http_response_code(400);
|
||||
echo json_encode(['success' => false, 'error' => 'ticket_id, other_ticket_id and relation are required']);
|
||||
exit;
|
||||
}
|
||||
if (!in_array($action, ['link', 'unlink'], true)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['success' => false, 'error' => 'action must be "link" or "unlink"']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$context = $apiKeyAuth->getKeyContext();
|
||||
$keyName = (string)($context['key_name'] ?? 'API');
|
||||
|
||||
// Keys see public tickets only unless marked see_all_visibility (#70), the
|
||||
// same rule as tickets_api.php. Check that first with the same synthetic
|
||||
// no-access user (user_id -1, so it can never match a creator or assignee),
|
||||
// answering a hidden ticket exactly like a missing one.
|
||||
if (empty($context['see_all_visibility'])) {
|
||||
$ticketModel = new TicketModel($conn);
|
||||
$visibilityUser = ['user_id' => -1, 'is_admin' => false, 'groups' => ''];
|
||||
foreach ([$ticketId, $otherId] as $id) {
|
||||
$ticket = ctype_digit($id) ? $ticketModel->getTicketById($id) : null;
|
||||
if (!$ticket || !$ticketModel->canUserAccessTicket($ticket, $visibilityUser)) {
|
||||
http_response_code(404);
|
||||
echo json_encode(['success' => false, 'error' => "Ticket {$id} not found"]);
|
||||
exit;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The link is created and audited as the system user, like other API writes;
|
||||
// past the check above the key may act on both tickets.
|
||||
$actor = array_merge($systemUser, ['is_admin' => true]);
|
||||
$auditExtra = ['api_key' => $keyName];
|
||||
$result = $action === 'unlink'
|
||||
? DependencyService::unlink($conn, $actor, $ticketId, $relation, $otherId, $auditExtra)
|
||||
: DependencyService::link($conn, $actor, $ticketId, $relation, $otherId, $auditExtra);
|
||||
|
||||
if (empty($result['success'])) {
|
||||
http_response_code((int)($result['http_status'] ?? 400));
|
||||
echo json_encode(['success' => false, 'error' => $result['error'] ?? 'Request failed']);
|
||||
exit;
|
||||
}
|
||||
|
||||
echo json_encode($result);
|
||||
exit;
|
||||
+51
-3
@@ -10,8 +10,11 @@
|
||||
* (API Key Management) when it genuinely needs the full queue.
|
||||
*
|
||||
* GET ?ticket_id=NNN -> {success, ticket, comments}
|
||||
* GET ?dedup_key=K -> {success, ticket, comments, recurrences}
|
||||
* the newest ticket carrying that key, in any status (#123);
|
||||
* recurrences lists the earlier tickets of its recurrence chain
|
||||
* GET ?status=&priority=&host= -> {success, tickets, page, total, pages}
|
||||
* &page=&limit=
|
||||
* &source=&page=&limit=
|
||||
*/
|
||||
|
||||
header('Content-Type: application/json');
|
||||
@@ -28,6 +31,8 @@ require_once dirname(__DIR__) . '/helpers/Database.php';
|
||||
require_once dirname(__DIR__) . '/middleware/ApiKeyAuth.php';
|
||||
require_once dirname(__DIR__) . '/models/TicketModel.php';
|
||||
require_once dirname(__DIR__) . '/models/CommentModel.php';
|
||||
require_once dirname(__DIR__) . '/helpers/TicketHash.php';
|
||||
require_once dirname(__DIR__) . '/services/AutoTicketService.php';
|
||||
|
||||
try {
|
||||
$conn = Database::getConnection();
|
||||
@@ -72,6 +77,33 @@ if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
|
||||
|
||||
$ticketModel = new TicketModel($conn);
|
||||
|
||||
// ── LOOKUP BY DEDUP KEY (#123) ────────────────────────────────────────────
|
||||
// Resolved to a ticket_id here, then answered by the read-one code below, so
|
||||
// visibility and the response shape are the same.
|
||||
$recurrences = null;
|
||||
if (isset($_GET['dedup_key']) && trim((string)$_GET['dedup_key']) !== '') {
|
||||
$dedupKey = trim((string)$_GET['dedup_key']);
|
||||
if (!TicketHash::isValidKey($dedupKey)) {
|
||||
http_response_code(400);
|
||||
echo json_encode(['success' => false, 'error' => 'Invalid dedup_key']);
|
||||
exit;
|
||||
}
|
||||
$keyStmt = $conn->prepare(
|
||||
"SELECT ticket_id FROM tickets WHERE dedup_key = ? ORDER BY created_at DESC, ticket_id DESC LIMIT 1"
|
||||
);
|
||||
$keyStmt->bind_param('s', $dedupKey);
|
||||
$keyStmt->execute();
|
||||
$keyRow = $keyStmt->get_result()->fetch_assoc();
|
||||
$keyStmt->close();
|
||||
if (!$keyRow) {
|
||||
http_response_code(404);
|
||||
echo json_encode(['success' => false, 'error' => 'No ticket with that dedup_key']);
|
||||
exit;
|
||||
}
|
||||
$_GET['ticket_id'] = $keyRow['ticket_id'];
|
||||
$recurrences = array_slice(AutoTicketService::chain($conn, $keyRow['ticket_id']), 1);
|
||||
}
|
||||
|
||||
// ── READ ONE ──────────────────────────────────────────────────────────────
|
||||
if (isset($_GET['ticket_id']) && trim((string)$_GET['ticket_id']) !== '') {
|
||||
$ticketId = trim((string)$_GET['ticket_id']);
|
||||
@@ -96,11 +128,22 @@ if (isset($_GET['ticket_id']) && trim((string)$_GET['ticket_id']) !== '') {
|
||||
$commentModel = new CommentModel($conn);
|
||||
$comments = $commentModel->getCommentsByTicketId($ticketId, false);
|
||||
|
||||
echo json_encode([
|
||||
$response = [
|
||||
'success' => true,
|
||||
'ticket' => $ticket,
|
||||
'comments' => $comments,
|
||||
]);
|
||||
];
|
||||
if ($recurrences !== null) {
|
||||
// A public-only key only learns the ids of earlier occurrences it may see.
|
||||
$response['recurrences'] = array_values(array_filter($recurrences, function ($id) use ($ticketModel, $visibilityUser) {
|
||||
if ($visibilityUser === null) {
|
||||
return true;
|
||||
}
|
||||
$t = $ticketModel->getTicketById($id);
|
||||
return $t && $ticketModel->canUserAccessTicket($t, $visibilityUser);
|
||||
}));
|
||||
}
|
||||
echo json_encode($response);
|
||||
exit;
|
||||
}
|
||||
|
||||
@@ -132,6 +175,11 @@ if (isset($_GET['priority']) && trim((string)$_GET['priority']) !== '') {
|
||||
}
|
||||
}
|
||||
|
||||
// Reporter (API key name) that created the ticket, comma-separated (#123).
|
||||
if (isset($_GET['source']) && trim((string)$_GET['source']) !== '') {
|
||||
$filters['source'] = explode(',', (string)$_GET['source']);
|
||||
}
|
||||
|
||||
// hwmon puts the host in the title (e.g. "[hostname] ..."), so a host filter is a
|
||||
// title substring match — served by getAllTickets's `search` param (title search).
|
||||
$search = null;
|
||||
|
||||
@@ -295,6 +295,7 @@ function clearAllFilters() {
|
||||
params.delete('priority');
|
||||
params.delete('category');
|
||||
params.delete('type');
|
||||
params.delete('source');
|
||||
params.delete('assigned_to');
|
||||
params.delete('search');
|
||||
params.delete('created_from');
|
||||
@@ -339,6 +340,9 @@ function initSidebarFilters() {
|
||||
const selectedTypes = Array.from(
|
||||
document.querySelectorAll('.lt-filter-group input[name="type"]:checked')
|
||||
).map(cb => cb.value);
|
||||
const selectedSources = Array.from(
|
||||
document.querySelectorAll('.lt-filter-group input[name="source"]:checked')
|
||||
).map(cb => cb.value);
|
||||
|
||||
if (selectedStatuses.length > 0) params.set('status', selectedStatuses.join(','));
|
||||
else params.delete('status');
|
||||
@@ -346,6 +350,8 @@ function initSidebarFilters() {
|
||||
else params.delete('category');
|
||||
if (selectedTypes.length > 0) params.set('type', selectedTypes.join(','));
|
||||
else params.delete('type');
|
||||
if (selectedSources.length > 0) params.set('source', selectedSources.join(','));
|
||||
else params.delete('source');
|
||||
|
||||
// Date inputs
|
||||
const dateFields = ['created_from','created_to','updated_from','updated_to','closed_from','closed_to'];
|
||||
|
||||
@@ -153,6 +153,11 @@ $GLOBALS['config'] = [
|
||||
'RATE_LIMIT_DEFAULT' => (int)($envVars['RATE_LIMIT_DEFAULT'] ?? 100), // Session-based, general endpoints
|
||||
'RATE_LIMIT_API' => (int)($envVars['RATE_LIMIT_API'] ?? 60), // Session-based, API endpoints
|
||||
|
||||
// Automated reporters (create_ticket_api.php): a report matching a ticket
|
||||
// closed less than this many days ago reopens it; an older one gets a new
|
||||
// ticket linked to the old one (#123).
|
||||
'AUTO_REOPEN_WINDOW_DAYS' => (int)($envVars['AUTO_REOPEN_WINDOW_DAYS'] ?? 7),
|
||||
|
||||
// Audit log settings
|
||||
'AUDIT_LOG_RETENTION_DAYS' => 90,
|
||||
|
||||
|
||||
@@ -162,6 +162,11 @@ class DashboardController
|
||||
$filters['priority_max'] = $priorityMax;
|
||||
}
|
||||
|
||||
// Source: the API key (reporter) that created the ticket (#123)
|
||||
if (!empty($_GET['source'])) {
|
||||
$filters['source'] = array_slice(array_map(fn($s) => substr(trim($s), 0, 100), explode(',', (string)$_GET['source'])), 0, 20);
|
||||
}
|
||||
|
||||
// Validate user ID filters
|
||||
$createdBy = $this->validateUserId($_GET['created_by'] ?? null);
|
||||
if ($createdBy !== null) {
|
||||
@@ -188,6 +193,7 @@ class DashboardController
|
||||
$filterOptions = $this->getCategoriesAndTypes();
|
||||
$categories = $filterOptions['categories'];
|
||||
$types = $filterOptions['types'];
|
||||
$sources = $filterOptions['sources'];
|
||||
|
||||
// Extract data for the view
|
||||
$tickets = $result['tickets'];
|
||||
@@ -202,23 +208,26 @@ class DashboardController
|
||||
}
|
||||
|
||||
/**
|
||||
* Get categories and types in a single query
|
||||
* Get categories, types and sources in a single query
|
||||
*
|
||||
* @return array ['categories' => [...], 'types' => [...]]
|
||||
* @return array ['categories' => [...], 'types' => [...], 'sources' => [...]]
|
||||
*/
|
||||
private function getCategoriesAndTypes(): array
|
||||
{
|
||||
$sql = "SELECT 'category' as field, category as value FROM tickets WHERE category IS NOT NULL
|
||||
UNION
|
||||
SELECT 'type' as field, type as value FROM tickets WHERE type IS NOT NULL
|
||||
UNION
|
||||
SELECT 'source' as field, source as value FROM tickets WHERE source IS NOT NULL
|
||||
ORDER BY field, value";
|
||||
|
||||
$result = $this->conn->query($sql);
|
||||
$categories = [];
|
||||
$types = [];
|
||||
$sources = [];
|
||||
|
||||
if (!$result) {
|
||||
return ['categories' => $categories, 'types' => $types];
|
||||
return ['categories' => $categories, 'types' => $types, 'sources' => $sources];
|
||||
}
|
||||
|
||||
while ($row = $result->fetch_assoc()) {
|
||||
@@ -226,9 +235,11 @@ class DashboardController
|
||||
$categories[] = $row['value'];
|
||||
} elseif ($row['field'] === 'type' && !in_array($row['value'], $types, true)) {
|
||||
$types[] = $row['value'];
|
||||
} elseif ($row['field'] === 'source' && !in_array($row['value'], $sources, true)) {
|
||||
$sources[] = $row['value'];
|
||||
}
|
||||
}
|
||||
|
||||
return ['categories' => $categories, 'types' => $types];
|
||||
return ['categories' => $categories, 'types' => $types, 'sources' => $sources];
|
||||
}
|
||||
}
|
||||
+123
-114
@@ -46,6 +46,7 @@ require_once __DIR__ . '/models/TicketModel.php';
|
||||
require_once __DIR__ . '/models/WorkflowModel.php';
|
||||
require_once __DIR__ . '/helpers/UrlHelper.php';
|
||||
require_once __DIR__ . '/helpers/TicketHash.php';
|
||||
require_once __DIR__ . '/services/AutoTicketService.php';
|
||||
|
||||
$apiKeyAuth = new ApiKeyAuth($conn);
|
||||
|
||||
@@ -105,6 +106,24 @@ if (!is_numeric($priority) || (int)$priority < 1 || (int)$priority > 5) {
|
||||
}
|
||||
$priority = (int)$priority;
|
||||
|
||||
// An explicit dedup_key (#123) decides what "the same problem" is. A
|
||||
// malformed one is an error, never a silent fall back to title hashing.
|
||||
if (isset($data['dedup_key']) && $data['dedup_key'] !== '' && !TicketHash::isValidKey($data['dedup_key'])) {
|
||||
http_response_code(400);
|
||||
echo json_encode([
|
||||
'success' => false,
|
||||
'error' => 'Invalid dedup_key: use 1-128 of A-Z a-z 0-9 _ . : - (e.g. host:compute-storage-01:oom)',
|
||||
]);
|
||||
exit;
|
||||
}
|
||||
$dedupKey = TicketHash::key($data);
|
||||
|
||||
// Which reporter this is (gandalf, hwmonDaemon, thor): the API key's name.
|
||||
// Recorded as the ticket's source and used as the author of the comments
|
||||
// this endpoint writes.
|
||||
$source = (string)($apiKeyAuth->getKeyContext()['key_name'] ?? 'API');
|
||||
$commentAuthor = mb_substr($source, 0, 50);
|
||||
|
||||
$ticketHash = TicketHash::generate($data);
|
||||
$auditLog = new AuditLogModel($conn);
|
||||
|
||||
@@ -129,14 +148,10 @@ $maxDedupAttempts = 2;
|
||||
for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) {
|
||||
$conn->begin_transaction();
|
||||
|
||||
// Look up any existing ticket with this hash (open OR closed)
|
||||
$checkStmt = $conn->prepare("SELECT ticket_id, status, title, priority FROM tickets WHERE hash = ? ORDER BY created_at DESC LIMIT 1 FOR UPDATE");
|
||||
$checkStmt->bind_param("s", $ticketHash);
|
||||
$checkStmt->execute();
|
||||
$existing = $checkStmt->get_result()->fetch_assoc();
|
||||
$checkStmt->close();
|
||||
// Look up the ticket holding this hash (open OR closed)
|
||||
$existing = AutoTicketService::lockByHash($conn, $ticketHash);
|
||||
|
||||
if ($existing) {
|
||||
if ($existing && ($existing['status'] !== 'Closed' || $existing['closed_recently'])) {
|
||||
$existingId = $existing['ticket_id'];
|
||||
$existingStatus = $existing['status'];
|
||||
$existingTitle = $existing['title'];
|
||||
@@ -193,13 +208,13 @@ for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) {
|
||||
$toP = (int)$changes['priority']['to'];
|
||||
$fromL = $pLabels[$fromP] ?? "P{$fromP}";
|
||||
$toL = $pLabels[$toP] ?? "P{$toP}";
|
||||
$commentText = "**hwmonDaemon raised priority {$fromL} → {$toL}.**\n\n"
|
||||
. "The latest monitoring scan reported a more severe condition for this issue, "
|
||||
. "so it now needs faster attention. Current sensor data is in the ticket description above.";
|
||||
$commentText = "**{$source} raised priority {$fromL} → {$toL}.**\n\n"
|
||||
. "The latest report described a more severe condition for this issue, "
|
||||
. "so it now needs faster attention. Current details are in the ticket description above.";
|
||||
$commentStmt = $conn->prepare(
|
||||
"INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, 'hwmonDaemon', ?, 1)"
|
||||
"INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, ?, ?, 1)"
|
||||
);
|
||||
$commentStmt->bind_param("sis", $existingId, $userId, $commentText);
|
||||
$commentStmt->bind_param("siss", $existingId, $userId, $commentAuthor, $commentText);
|
||||
$commentStmt->execute();
|
||||
$commentStmt->close();
|
||||
}
|
||||
@@ -212,7 +227,7 @@ for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) {
|
||||
if (!empty($auditedChanges)) {
|
||||
$auditLog->log($userId, 'update', 'ticket', $existingId, array_merge(
|
||||
$auditedChanges,
|
||||
['reason' => 'auto-updated by hwmonDaemon (condition worsened)']
|
||||
['reason' => "auto-updated by {$source} (condition worsened)"]
|
||||
));
|
||||
}
|
||||
|
||||
@@ -245,7 +260,7 @@ for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) {
|
||||
exit;
|
||||
}
|
||||
|
||||
// Ticket was closed — reopen it and add a recurrence comment. Route
|
||||
// Ticket closed inside the reopen window: reopen it and add a recurrence comment. Route
|
||||
// through the Workflow Designer like every other status-write path in
|
||||
// the app, rather than forcing status='Open' via raw SQL regardless of
|
||||
// configured transition rules.
|
||||
@@ -278,37 +293,37 @@ for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) {
|
||||
'priority' => $priority,
|
||||
], $userId);
|
||||
} else {
|
||||
error_log("create_ticket_api: hwmonDaemon recurrence for ticket $existingId — "
|
||||
error_log("create_ticket_api: {$source} recurrence for ticket $existingId: "
|
||||
. "no admin-free, comment-free transition from Closed is configured; leaving ticket Closed");
|
||||
}
|
||||
|
||||
$commentText = "**Issue recurred — ticket reopened automatically.**\n\n" .
|
||||
"hwmonDaemon detected this condition again. The ticket description reflects the "
|
||||
. "original report; see this comment's timestamp for when the issue recurred.";
|
||||
$commentText = "**Issue recurred, ticket reopened automatically.**\n\n"
|
||||
. "{$source} detected this condition again. The ticket description reflects the "
|
||||
. "latest report; see this comment's timestamp for when the issue recurred.";
|
||||
if ($reopenStatus === null) {
|
||||
$commentText = "**Issue recurred, but the ticket could not be reopened automatically.**\n\n"
|
||||
. "hwmonDaemon detected this condition again. No Workflow Designer transition from "
|
||||
. "{$source} detected this condition again. No Workflow Designer transition from "
|
||||
. "Closed is configured that this automation can perform unattended (no comment/admin "
|
||||
. "requirement); the ticket remains Closed. Please review and reopen manually if appropriate.";
|
||||
}
|
||||
$commentStmt = $conn->prepare(
|
||||
"INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, 'hwmonDaemon', ?, 1)"
|
||||
"INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, ?, ?, 1)"
|
||||
);
|
||||
$commentStmt->bind_param("sis", $existingId, $userId, $commentText);
|
||||
$commentStmt->bind_param("siss", $existingId, $userId, $commentAuthor, $commentText);
|
||||
$commentStmt->execute();
|
||||
$commentStmt->close();
|
||||
|
||||
if ($reopenStatus !== null) {
|
||||
$auditLog->log($userId, 'update', 'ticket', $existingId, [
|
||||
'status' => ['from' => 'Closed', 'to' => $reopenStatus],
|
||||
'reason' => 'auto-reopened by hwmonDaemon (issue recurred)',
|
||||
'reason' => "auto-reopened by {$source} (issue recurred)",
|
||||
]);
|
||||
|
||||
// Ticket reopened — refresh dashboard stats.
|
||||
(new StatsModel($conn))->invalidateCache();
|
||||
} else {
|
||||
$auditLog->log($userId, 'update', 'ticket', $existingId, [
|
||||
'reason' => 'hwmonDaemon recurrence detected but no valid reopen transition configured; ticket left Closed',
|
||||
'reason' => "{$source} recurrence detected but no valid reopen transition configured; ticket left Closed",
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -337,89 +352,69 @@ for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) {
|
||||
exit;
|
||||
}
|
||||
|
||||
// No existing ticket — create a new one. Still inside the transaction opened
|
||||
// above, so a concurrent request for the same hash is blocked on its own
|
||||
// SELECT ... FOR UPDATE until this one commits or rolls back (see comment
|
||||
// there) rather than racing this INSERT.
|
||||
// No ticket holds this hash, or the one that does closed longer ago than
|
||||
// the reopen window (#123): create a new one. In the second case the new
|
||||
// ticket is a recurrence: it takes over the hash (unique, so the old
|
||||
// ticket gives it up), records the old ticket in recurrence_of, and is
|
||||
// linked relates_to it with a history comment.
|
||||
//
|
||||
// Still inside the transaction opened above, so a concurrent request for
|
||||
// the same hash is blocked on its own SELECT ... FOR UPDATE until this one
|
||||
// commits or rolls back rather than racing this INSERT.
|
||||
//
|
||||
// Note on FOR UPDATE over a not-yet-existing key: InnoDB's gap lock in that
|
||||
// case is a shared lock, not exclusive — two concurrent transactions can
|
||||
// case is a shared lock, not exclusive, so two concurrent transactions can
|
||||
// both acquire it and both reach this INSERT. The conflict only surfaces
|
||||
// when they each request the insert-intention lock for the same gap,
|
||||
// which InnoDB resolves as a deadlock (error 1213), not by blocking one
|
||||
// of the SELECTs. The outer loop above retries that case: the loser rolls
|
||||
// back and re-runs its own SELECT ... FOR UPDATE, which by then finds the
|
||||
// winner's committed row and takes the update/escalate branch instead.
|
||||
//
|
||||
// Generate a collision-safe unique ticket_id with a pre-check + retry loop (same
|
||||
// approach as TicketModel::createTicket) so a ticket_id clash cannot happen. That
|
||||
// way a 1062 on INSERT below can only be the unique_hash (dedup) key — and with
|
||||
// the FOR UPDATE lock above, only in the unlikely case of a hash collision from
|
||||
// two genuinely different reports, not the same-hash race this used to be.
|
||||
$ticket_id = null;
|
||||
$maxAttempts = 50;
|
||||
$attempts = 0;
|
||||
do {
|
||||
try {
|
||||
$candidateId = sprintf('%09d', random_int(100000000, 999999999));
|
||||
} catch (Exception $e) {
|
||||
$candidateId = sprintf('%09d', mt_rand(100000000, 999999999));
|
||||
}
|
||||
|
||||
$idCheckStmt = $conn->prepare("SELECT ticket_id FROM tickets WHERE ticket_id = ? LIMIT 1");
|
||||
$idCheckStmt->bind_param("s", $candidateId);
|
||||
$idCheckStmt->execute();
|
||||
$idExists = $idCheckStmt->get_result()->num_rows > 0;
|
||||
$idCheckStmt->close();
|
||||
|
||||
if (!$idExists) {
|
||||
$ticket_id = $candidateId;
|
||||
}
|
||||
$attempts++;
|
||||
} while ($ticket_id === null && $attempts < $maxAttempts);
|
||||
$previous = $existing; // a Closed ticket outside the window, or null
|
||||
$previousId = $previous['ticket_id'] ?? null;
|
||||
|
||||
// A ticket_id that is free, so a 1062 on INSERT below can only be the
|
||||
// unique hash, and with the FOR UPDATE lock above only in the unlikely
|
||||
// case of a hash collision between two genuinely different reports.
|
||||
$ticket_id = AutoTicketService::newTicketId($conn);
|
||||
if ($ticket_id === null) {
|
||||
$conn->rollback();
|
||||
error_log('create_ticket_api: failed to generate a unique ticket_id after ' . $maxAttempts . ' attempts');
|
||||
error_log('create_ticket_api: failed to generate a unique ticket_id');
|
||||
http_response_code(500);
|
||||
echo json_encode(['success' => false, 'error' => 'Internal server error']);
|
||||
exit;
|
||||
}
|
||||
|
||||
$insertStmt = $conn->prepare(
|
||||
"INSERT INTO tickets (ticket_id, title, description, status, priority, category, type, hash, created_by)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
||||
);
|
||||
$insertStmt->bind_param(
|
||||
"ssssssssi",
|
||||
$ticket_id,
|
||||
$title,
|
||||
$description,
|
||||
$status,
|
||||
$priority,
|
||||
$category,
|
||||
$type,
|
||||
$ticketHash,
|
||||
$userId
|
||||
);
|
||||
|
||||
try {
|
||||
$inserted = $insertStmt->execute();
|
||||
if ($previousId !== null) {
|
||||
AutoTicketService::releaseHash($conn, $previousId);
|
||||
}
|
||||
AutoTicketService::insert($conn, [
|
||||
'ticket_id' => $ticket_id,
|
||||
'title' => $title,
|
||||
'description' => $description,
|
||||
'status' => $status,
|
||||
'priority' => $priority,
|
||||
'category' => $category,
|
||||
'type' => $type,
|
||||
'hash' => $ticketHash,
|
||||
'created_by' => $userId,
|
||||
'source' => $source,
|
||||
'dedup_key' => $dedupKey ?? ($previous['dedup_key'] ?? null),
|
||||
'recurrence_of' => $previousId,
|
||||
]);
|
||||
} catch (mysqli_sql_exception $e) {
|
||||
$insertStmt->close();
|
||||
$conn->rollback();
|
||||
if (in_array($e->getCode(), [1213, 1205], true) && $dedupAttempt < $maxDedupAttempts) {
|
||||
// Deadlock (1213) or lock wait timeout (1205) from a concurrent
|
||||
// insert into the same not-yet-existing hash gap — see the note
|
||||
// insert into the same not-yet-existing hash gap: see the note
|
||||
// above. Retry: the next iteration's own SELECT ... FOR UPDATE
|
||||
// will find whichever side won and take the update/escalate path.
|
||||
continue;
|
||||
}
|
||||
if ($e->getCode() === 1062) {
|
||||
// Should be unreachable in the same-hash race this issue was filed
|
||||
// for now that the SELECT above takes FOR UPDATE — kept as a
|
||||
// defensive fallback in case of a genuine hash collision between two
|
||||
// different reports.
|
||||
// Defensive: only a genuine hash collision between two different
|
||||
// reports can get here now that the SELECT above takes FOR UPDATE.
|
||||
echo json_encode(['success' => false, 'error' => 'Duplicate ticket']);
|
||||
} else {
|
||||
error_log('create_ticket_api: insert failed: ' . $e->getMessage());
|
||||
@@ -428,43 +423,57 @@ for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) {
|
||||
}
|
||||
exit;
|
||||
}
|
||||
$insertStmt->close();
|
||||
|
||||
if ($inserted) {
|
||||
$auditLog->logTicketCreate($userId, $ticket_id, [
|
||||
'title' => $title,
|
||||
'priority' => $priority,
|
||||
'category' => $category,
|
||||
'type' => $type,
|
||||
$auditLog->logTicketCreate($userId, $ticket_id, [
|
||||
'title' => $title,
|
||||
'priority' => $priority,
|
||||
'category' => $category,
|
||||
'type' => $type,
|
||||
]);
|
||||
|
||||
if ($previousId !== null) {
|
||||
AutoTicketService::linkRecurrence($conn, $ticket_id, $previousId, (int)$userId);
|
||||
$historyText = AutoTicketService::historyComment($conn, $ticket_id, $previousId, $previous['closed_at'] ?? null);
|
||||
$commentStmt = $conn->prepare(
|
||||
"INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, ?, ?, 1)"
|
||||
);
|
||||
$commentStmt->bind_param("siss", $ticket_id, $userId, $commentAuthor, $historyText);
|
||||
$commentStmt->execute();
|
||||
$commentStmt->close();
|
||||
$auditLog->log($userId, 'update', 'ticket', $previousId, [
|
||||
'reason' => "{$source} reported this problem again after the "
|
||||
. AutoTicketService::reopenWindowDays() . "-day reopen window; continued in {$ticket_id}",
|
||||
]);
|
||||
|
||||
// New ticket created — refresh dashboard stats.
|
||||
(new StatsModel($conn))->invalidateCache();
|
||||
|
||||
$conn->commit();
|
||||
Database::close();
|
||||
|
||||
require_once __DIR__ . '/helpers/NotificationHelper.php';
|
||||
NotificationHelper::sendTicketNotification($ticket_id, [
|
||||
'title' => $title,
|
||||
'priority' => $priority,
|
||||
'category' => $category,
|
||||
'type' => $type,
|
||||
'status' => $status,
|
||||
], 'automated');
|
||||
|
||||
echo json_encode([
|
||||
'success' => true,
|
||||
'ticket_id' => $ticket_id,
|
||||
'message' => 'Ticket created successfully',
|
||||
]);
|
||||
} else {
|
||||
$conn->rollback();
|
||||
error_log('create_ticket_api: ticket insert reported failure: ' . $conn->error);
|
||||
http_response_code(500);
|
||||
echo json_encode(['success' => false, 'error' => 'Internal server error']);
|
||||
}
|
||||
// Done — only the deadlock `continue` above may run the loop again.
|
||||
|
||||
// New ticket created: refresh dashboard stats.
|
||||
(new StatsModel($conn))->invalidateCache();
|
||||
|
||||
$conn->commit();
|
||||
Database::close();
|
||||
|
||||
require_once __DIR__ . '/helpers/NotificationHelper.php';
|
||||
NotificationHelper::sendTicketNotification($ticket_id, [
|
||||
'title' => $title,
|
||||
'priority' => $priority,
|
||||
'category' => $category,
|
||||
'type' => $type,
|
||||
'status' => $status,
|
||||
], 'automated');
|
||||
|
||||
$response = [
|
||||
'success' => true,
|
||||
'ticket_id' => $ticket_id,
|
||||
'message' => $previousId !== null
|
||||
? "New ticket for a recurrence of {$previousId}"
|
||||
: 'Ticket created successfully',
|
||||
'action' => $previousId !== null ? 'new_recurrence' : 'created',
|
||||
];
|
||||
if ($previousId !== null) {
|
||||
$response['previous_ticket_id'] = $previousId;
|
||||
}
|
||||
echo json_encode($response);
|
||||
// Done: only the deadlock `continue` above may run the loop again.
|
||||
// Falling through re-entered it on a closed connection, appending a
|
||||
// 500 error body after the success response for every new ticket.
|
||||
exit;
|
||||
|
||||
+37
-3
@@ -4,8 +4,9 @@
|
||||
* Dedup hash for tickets created through create_ticket_api.php.
|
||||
*
|
||||
* Two reports with the same hash land on the same ticket (updated while open,
|
||||
* reopened when closed), so the components below decide what counts as "the
|
||||
* same problem". Changing them re-keys existing tickets: see
|
||||
* reopened or followed by a linked new ticket when closed). A reporter can
|
||||
* send an explicit dedup_key and decide that itself (#123); otherwise the
|
||||
* components below decide what counts as "the same problem". Changing them re-keys existing tickets: see
|
||||
* scripts/rehash_network_tickets.php for how #116 handled that.
|
||||
*/
|
||||
class TicketHash
|
||||
@@ -178,9 +179,42 @@ class TicketHash
|
||||
return $stableComponents;
|
||||
}
|
||||
|
||||
/** SHA-256 dedup hash of the payload's stable components. */
|
||||
/**
|
||||
* Format of a reporter-supplied dedup_key: scope:subject:kind, e.g.
|
||||
* host:compute-storage-01:oom or cluster:ceph:BLUESTORE_SLOW_OP_ALERT.
|
||||
* Upper case is allowed for codes like Ceph's; keys are case-sensitive.
|
||||
*/
|
||||
public const KEY_PATTERN = '/^[A-Za-z0-9_.:-]{1,128}$/';
|
||||
|
||||
public static function isValidKey($key): bool
|
||||
{
|
||||
return is_string($key) && preg_match(self::KEY_PATTERN, $key) === 1;
|
||||
}
|
||||
|
||||
/** The request's dedup_key, or null when it sent none. Validate with isValidKey() first. */
|
||||
public static function key(array $data): ?string
|
||||
{
|
||||
$key = $data['dedup_key'] ?? null;
|
||||
return ($key === null || $key === '') ? null : (string)$key;
|
||||
}
|
||||
|
||||
/** Dedup hash for an explicit key. The "key:" prefix keeps it apart from every legacy hash. */
|
||||
public static function forKey(string $key): string
|
||||
{
|
||||
return hash('sha256', 'key:' . $key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Dedup hash for a create request. With a dedup_key the reporter decides
|
||||
* what "the same problem" is and the title is not looked at (#123);
|
||||
* without one, the stable components of the title decide, as before.
|
||||
*/
|
||||
public static function generate(array $data): string
|
||||
{
|
||||
$key = self::key($data);
|
||||
if ($key !== null) {
|
||||
return self::forKey($key);
|
||||
}
|
||||
return hash('sha256', json_encode(self::components($data), JSON_UNESCAPED_SLASHES));
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ final class TicketReadTools
|
||||
* @param int|null $priority Exact priority: 1 (critical) to 5 (minimal).
|
||||
* @param string|null $category Exact category name.
|
||||
* @param string|null $assignee "me", "unassigned", or a username.
|
||||
* @param string|null $source Reporter that created the ticket through the API, e.g. "gandalf", "hwmonDaemon", "thor". Comma-separated for several.
|
||||
* @param int $page Page number, starting at 1.
|
||||
* @param int $limit Tickets per page, 1-50.
|
||||
*
|
||||
@@ -37,6 +38,7 @@ final class TicketReadTools
|
||||
?int $priority = null,
|
||||
?string $category = null,
|
||||
?string $assignee = null,
|
||||
?string $source = null,
|
||||
int $page = 1,
|
||||
int $limit = 20,
|
||||
): array {
|
||||
@@ -68,6 +70,9 @@ final class TicketReadTools
|
||||
if ($assignee !== null && trim($assignee) !== '') {
|
||||
$filters['assigned_to'] = $this->resolveAssigneeFilter(trim($assignee), $user);
|
||||
}
|
||||
if ($source !== null && trim($source) !== '') {
|
||||
$filters['source'] = explode(',', $source);
|
||||
}
|
||||
|
||||
$page = max(1, $page);
|
||||
$limit = min(50, max(1, $limit));
|
||||
@@ -140,7 +145,7 @@ final class TicketReadTools
|
||||
$details['comment_count'] = count($comments);
|
||||
$details['comments'] = array_map(fn(array $c) => [
|
||||
'comment_id' => (int)$c['comment_id'],
|
||||
'author' => $c['display_name'] ?? $c['username'] ?? $c['user_name'] ?? null,
|
||||
'author' => $c['display_name_formatted'] ?? $c['display_name'] ?? $c['username'] ?? $c['user_name'] ?? null,
|
||||
'created_at' => $c['created_at'] ?? null,
|
||||
'reply_to' => isset($c['parent_comment_id']) ? (int)$c['parent_comment_id'] : null,
|
||||
'text' => $c['comment_text'] ?? '',
|
||||
@@ -275,6 +280,7 @@ final class TicketReadTools
|
||||
'visibility' => $t['visibility'] ?? 'public',
|
||||
'assigned_to' => $t['assigned_display_name'] ?? $t['assigned_username'] ?? null,
|
||||
'created_by' => $t['creator_display_name'] ?? $t['creator_username'] ?? null,
|
||||
'source' => $t['source'] ?? null,
|
||||
'created_at' => $t['created_at'] ?? null,
|
||||
'updated_at' => $t['updated_at'] ?? null,
|
||||
'url' => \UrlHelper::ticketUrl((string)$t['ticket_id']),
|
||||
|
||||
@@ -252,22 +252,12 @@ final class TicketWriteTools
|
||||
*/
|
||||
public function linkTickets(string $ticket_id, string $relation, string $other_ticket_id): array
|
||||
{
|
||||
$user = McpIdentity::user();
|
||||
[$ticketId, $otherId, $relation] = $this->linkArgs($ticket_id, $relation, $other_ticket_id);
|
||||
|
||||
$result = \DependencyService::add($this->conn, $user, [
|
||||
'ticket_id' => $ticketId,
|
||||
'depends_on_id' => $otherId,
|
||||
'dependency_type' => $relation,
|
||||
]);
|
||||
$result = \DependencyService::link($this->conn, McpIdentity::user(), $ticket_id, $relation, $other_ticket_id);
|
||||
if (empty($result['success'])) {
|
||||
if (($result['error'] ?? '') === 'Target ticket not found') {
|
||||
throw new ToolCallException("Ticket {$otherId} not found");
|
||||
}
|
||||
throw new ToolCallException($this->errorMessage($result, $ticketId));
|
||||
throw new ToolCallException((string)$result['error']);
|
||||
}
|
||||
|
||||
return ['ticket_id' => $ticketId, 'relation' => $relation, 'other_ticket_id' => $otherId];
|
||||
return ['ticket_id' => $result['ticket_id'], 'relation' => $result['relation'], 'other_ticket_id' => $result['other_ticket_id']];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -283,56 +273,17 @@ final class TicketWriteTools
|
||||
*/
|
||||
public function unlinkTickets(string $ticket_id, string $relation, string $other_ticket_id): array
|
||||
{
|
||||
$user = McpIdentity::user();
|
||||
[$ticketId, $otherId, $relation] = $this->linkArgs($ticket_id, $relation, $other_ticket_id);
|
||||
|
||||
// The same relationship can be stored from either ticket. duplicates
|
||||
// has no inverse type, so it is only ever stored one way.
|
||||
$inverse = ['blocks' => 'blocked_by', 'blocked_by' => 'blocks', 'relates_to' => 'relates_to'];
|
||||
$attempts = [[$ticketId, $otherId, $relation]];
|
||||
if (isset($inverse[$relation])) {
|
||||
$attempts[] = [$otherId, $ticketId, $inverse[$relation]];
|
||||
$result = \DependencyService::unlink($this->conn, McpIdentity::user(), $ticket_id, $relation, $other_ticket_id);
|
||||
if (empty($result['success'])) {
|
||||
throw new ToolCallException((string)$result['error']);
|
||||
}
|
||||
|
||||
$removed = 0;
|
||||
foreach ($attempts as [$from, $to, $type]) {
|
||||
$result = \DependencyService::remove($this->conn, $user, [
|
||||
'ticket_id' => $from,
|
||||
'depends_on_id' => $to,
|
||||
'dependency_type' => $type,
|
||||
]);
|
||||
if (empty($result['success'])) {
|
||||
throw new ToolCallException($this->errorMessage($result, $from));
|
||||
}
|
||||
$removed += (int)$result['removed'];
|
||||
}
|
||||
if ($removed === 0) {
|
||||
throw new ToolCallException("No {$relation} link between {$ticketId} and {$otherId}");
|
||||
}
|
||||
|
||||
return ['ticket_id' => $ticketId, 'relation' => $relation, 'other_ticket_id' => $otherId, 'removed' => true];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{0:string,1:string,2:string}
|
||||
*/
|
||||
private function linkArgs(string $ticketId, string $relation, string $otherId): array
|
||||
{
|
||||
$ticketId = trim($ticketId);
|
||||
$otherId = trim($otherId);
|
||||
$relation = strtolower(trim($relation));
|
||||
if (!in_array($relation, \DependencyService::TYPES, true)) {
|
||||
throw new ToolCallException('relation must be one of: ' . implode(', ', \DependencyService::TYPES));
|
||||
}
|
||||
foreach ([$ticketId, $otherId] as $id) {
|
||||
if (!ctype_digit($id)) {
|
||||
throw new ToolCallException("Ticket {$id} not found");
|
||||
}
|
||||
}
|
||||
if ($ticketId === $otherId) {
|
||||
throw new ToolCallException('A ticket cannot be linked to itself');
|
||||
}
|
||||
return [$ticketId, $otherId, $relation];
|
||||
return [
|
||||
'ticket_id' => $result['ticket_id'],
|
||||
'relation' => $result['relation'],
|
||||
'other_ticket_id' => $result['other_ticket_id'],
|
||||
'removed' => true,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
-- Explicit dedup keys, ticket source and recurrence chains (#123)
|
||||
--
|
||||
-- dedup_key: the key an automated reporter sends (scope:subject:kind). Not
|
||||
-- unique: every ticket in a recurrence chain carries it. tickets.hash stays
|
||||
-- UNIQUE and marks the one ticket that currently holds the dedup slot.
|
||||
-- Case-sensitive (ascii_bin), like the hash built from it.
|
||||
-- source: the API key name that created the ticket (gandalf, hwmonDaemon, thor),
|
||||
-- shown in place of "System". NULL for tickets made in the web UI or MCP.
|
||||
-- recurrence_of: for a ticket opened because a problem came back after the
|
||||
-- reopen window, the ticket_id of the previous occurrence.
|
||||
--
|
||||
-- All three are nullable, so code from before this migration keeps working.
|
||||
|
||||
ALTER TABLE `tickets`
|
||||
ADD COLUMN `dedup_key` varchar(128) CHARACTER SET ascii COLLATE ascii_bin DEFAULT NULL,
|
||||
ADD COLUMN `source` varchar(100) DEFAULT NULL,
|
||||
ADD COLUMN `recurrence_of` varchar(9) DEFAULT NULL,
|
||||
ADD KEY `idx_tickets_dedup_key` (`dedup_key`),
|
||||
ADD KEY `idx_tickets_source` (`source`),
|
||||
ADD KEY `idx_tickets_recurrence_of` (`recurrence_of`);
|
||||
+17
-7
@@ -117,11 +117,7 @@ class CommentModel
|
||||
|
||||
$commentMap = [];
|
||||
while ($row = $result->fetch_assoc()) {
|
||||
if (!empty($row['display_name'])) {
|
||||
$row['display_name_formatted'] = $row['display_name'];
|
||||
} else {
|
||||
$row['display_name_formatted'] = $row['user_name'] ?? 'Unknown User';
|
||||
}
|
||||
$row['display_name_formatted'] = self::authorName($row);
|
||||
$row['replies'] = [];
|
||||
$row['parent_comment_id'] = $row['parent_comment_id'] ?? null;
|
||||
$row['thread_depth'] = $row['thread_depth'] ?? 0;
|
||||
@@ -164,7 +160,7 @@ class CommentModel
|
||||
$commentMap = [];
|
||||
$rootIds = [];
|
||||
while ($row = $rootResult->fetch_assoc()) {
|
||||
$row['display_name_formatted'] = $row['display_name'] ?: ($row['user_name'] ?? 'Unknown User');
|
||||
$row['display_name_formatted'] = self::authorName($row);
|
||||
$row['replies'] = [];
|
||||
$row['parent_comment_id'] = null;
|
||||
$row['thread_depth'] = 0;
|
||||
@@ -203,7 +199,7 @@ class CommentModel
|
||||
if (isset($commentMap[$row['comment_id']])) {
|
||||
continue; // guard against cycles / duplicates
|
||||
}
|
||||
$row['display_name_formatted'] = $row['display_name'] ?: ($row['user_name'] ?? 'Unknown User');
|
||||
$row['display_name_formatted'] = self::authorName($row);
|
||||
$row['replies'] = [];
|
||||
$row['thread_depth'] = $depth + 1;
|
||||
$commentMap[$row['comment_id']] = $row;
|
||||
@@ -433,4 +429,18 @@ class CommentModel
|
||||
return ['success' => false, 'error' => 'Failed to delete comment'];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Name shown for a comment's author. Comments written by an API reporter
|
||||
* through create_ticket_api.php are linked to the shared "system" user but
|
||||
* store the reporter (gandalf, hwmonDaemon, thor) in user_name (#123), so
|
||||
* show that rather than "System".
|
||||
*/
|
||||
private static function authorName(array $row): string
|
||||
{
|
||||
if (($row['username'] ?? null) === 'system' && !empty($row['user_name'])) {
|
||||
return (string)$row['user_name'];
|
||||
}
|
||||
return (string)($row['display_name'] ?: ($row['user_name'] ?? 'Unknown User'));
|
||||
}
|
||||
}
|
||||
@@ -154,6 +154,18 @@ class TicketModel
|
||||
$paramTypes .= 'i';
|
||||
}
|
||||
|
||||
// Source: the API key (reporter) that created the ticket (#123)
|
||||
if (!empty($filters['source'])) {
|
||||
$sources = array_values(array_filter(array_map('trim', (array)$filters['source']), 'strlen'));
|
||||
if ($sources) {
|
||||
$whereConditions[] = 't.source IN (' . implode(',', array_fill(0, count($sources), '?')) . ')';
|
||||
foreach ($sources as $src) {
|
||||
$params[] = $src;
|
||||
$paramTypes .= 's';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Created by user
|
||||
if (!empty($filters['created_by'])) {
|
||||
$whereConditions[] = "t.created_by = ?";
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Give existing tickets the dedup_key a reporter now sends (#123).
|
||||
*
|
||||
* When an app starts sending dedup_key, its next report hashes on the key
|
||||
* instead of the title, so without this its open tickets would get
|
||||
* duplicates. The app owns its key scheme, so it supplies the mapping as a
|
||||
* JSON object of ticket_id => dedup_key:
|
||||
*
|
||||
* {"673679581": "cluster:ceph:OSDMAP_FLAGS", "629475198": "cluster:ceph:RECENT_CRASH"}
|
||||
*
|
||||
* php scripts/backfill_dedup_keys.php --map=thor-ceph.json --dry-run
|
||||
* php scripts/backfill_dedup_keys.php --map=thor-ceph.json
|
||||
*
|
||||
* Each listed ticket gets dedup_key set and its hash moved to the key's hash.
|
||||
* A ticket whose key hash already belongs to another ticket is skipped and
|
||||
* reported, as is an invalid key or a missing ticket. Closed tickets are
|
||||
* re-keyed too, with a warning (a report inside the reopen window will
|
||||
* reopen them). Each change writes an audit_log row. Safe to re-run.
|
||||
*/
|
||||
|
||||
if (php_sapi_name() !== 'cli') {
|
||||
http_response_code(403);
|
||||
exit('CLI access only');
|
||||
}
|
||||
|
||||
require_once dirname(__DIR__) . '/config/config.php';
|
||||
require_once dirname(__DIR__) . '/helpers/Database.php';
|
||||
require_once dirname(__DIR__) . '/helpers/TicketHash.php';
|
||||
require_once dirname(__DIR__) . '/models/UserModel.php';
|
||||
require_once dirname(__DIR__) . '/models/AuditLogModel.php';
|
||||
|
||||
$dryRun = in_array('--dry-run', $argv, true);
|
||||
$mapFile = null;
|
||||
foreach ($argv as $arg) {
|
||||
if (str_starts_with($arg, '--map=')) {
|
||||
$mapFile = substr($arg, 6);
|
||||
}
|
||||
}
|
||||
if ($mapFile === null || !is_readable($mapFile)) {
|
||||
fwrite(STDERR, "usage: php scripts/backfill_dedup_keys.php --map=file.json [--dry-run]\n");
|
||||
exit(2);
|
||||
}
|
||||
$map = json_decode((string)file_get_contents($mapFile), true);
|
||||
if (!is_array($map) || array_is_list($map)) {
|
||||
fwrite(STDERR, "$mapFile must be a JSON object of ticket_id => dedup_key\n");
|
||||
exit(2);
|
||||
}
|
||||
|
||||
$conn = Database::getConnection();
|
||||
$system = (new UserModel($conn))->getSystemUser();
|
||||
$actorId = $system ? (int)$system['user_id'] : null;
|
||||
$audit = new AuditLogModel($conn);
|
||||
|
||||
$get = $conn->prepare("SELECT ticket_id, title, status, hash, dedup_key FROM tickets WHERE ticket_id = ?");
|
||||
$holder = $conn->prepare("SELECT ticket_id FROM tickets WHERE hash = ? AND ticket_id <> ? LIMIT 1");
|
||||
$update = $conn->prepare("UPDATE tickets SET dedup_key = ?, hash = ? WHERE ticket_id = ?");
|
||||
$counts = ['updated' => 0, 'unchanged' => 0, 'skipped' => 0];
|
||||
|
||||
foreach ($map as $ticketId => $key) {
|
||||
$ticketId = (string)$ticketId;
|
||||
if (!TicketHash::isValidKey($key)) {
|
||||
$counts['skipped']++;
|
||||
echo "INVALID KEY $ticketId " . json_encode($key) . "\n";
|
||||
continue;
|
||||
}
|
||||
$get->bind_param('s', $ticketId);
|
||||
$get->execute();
|
||||
$ticket = $get->get_result()->fetch_assoc();
|
||||
if (!$ticket) {
|
||||
$counts['skipped']++;
|
||||
echo "NOT FOUND $ticketId\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
$newHash = TicketHash::forKey($key);
|
||||
if ($ticket['dedup_key'] === $key && $ticket['hash'] === $newHash) {
|
||||
$counts['unchanged']++;
|
||||
echo "unchanged $ticketId $key\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
$holder->bind_param('ss', $newHash, $ticketId);
|
||||
$holder->execute();
|
||||
$other = $holder->get_result()->fetch_assoc();
|
||||
if ($other) {
|
||||
$counts['skipped']++;
|
||||
echo "CONFLICT $ticketId $key (already the live ticket for that key: {$other['ticket_id']})\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
$warn = $ticket['status'] === 'Closed' ? ' [Closed]' : '';
|
||||
if (!$dryRun) {
|
||||
$update->bind_param('sss', $key, $newHash, $ticketId);
|
||||
$update->execute();
|
||||
$audit->log($actorId, 'update', 'ticket', $ticketId, [
|
||||
'dedup_key' => ['from' => $ticket['dedup_key'], 'to' => $key],
|
||||
'reason' => 'dedup_key backfilled from ' . basename($mapFile) . ' (tinker_tickets#123)',
|
||||
]);
|
||||
}
|
||||
$counts['updated']++;
|
||||
echo ($dryRun ? 'would update' : 'updated ') . " $ticketId $key$warn " . mb_substr((string)$ticket['title'], 0, 80) . "\n";
|
||||
}
|
||||
|
||||
printf(
|
||||
"%s%d updated, %d already current, %d skipped\n",
|
||||
$dryRun ? '[dry run] ' : '',
|
||||
$counts['updated'],
|
||||
$counts['unchanged'],
|
||||
$counts['skipped']
|
||||
);
|
||||
exit($counts['skipped'] > 0 ? 1 : 0);
|
||||
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Fill in tickets.source for tickets the API created before #123.
|
||||
*
|
||||
* Since #123, create_ticket_api.php records the API key name (gandalf,
|
||||
* hwmonDaemon, thor) as the ticket's source. Older API tickets only show the
|
||||
* "system" user. This script sets source where the reporter is certain and
|
||||
* leaves the rest NULL:
|
||||
*
|
||||
* - hwmonDaemon: description uses its box-drawing layout
|
||||
* - gandalf: [auto] title and Gandalf's own footer
|
||||
* ("automatically by Gandalf" / "from the Gandalf monitor")
|
||||
*
|
||||
* Only tickets created by the system user with no source yet are touched.
|
||||
* Each change writes an audit_log row. Safe to re-run.
|
||||
*
|
||||
* php scripts/backfill_ticket_source.php --dry-run # report only
|
||||
* php scripts/backfill_ticket_source.php
|
||||
*/
|
||||
|
||||
if (php_sapi_name() !== 'cli') {
|
||||
http_response_code(403);
|
||||
exit('CLI access only');
|
||||
}
|
||||
|
||||
require_once dirname(__DIR__) . '/config/config.php';
|
||||
require_once dirname(__DIR__) . '/helpers/Database.php';
|
||||
require_once dirname(__DIR__) . '/models/UserModel.php';
|
||||
require_once dirname(__DIR__) . '/models/AuditLogModel.php';
|
||||
|
||||
$dryRun = in_array('--dry-run', $argv, true);
|
||||
$conn = Database::getConnection();
|
||||
|
||||
$system = (new UserModel($conn))->getSystemUser();
|
||||
if (!$system) {
|
||||
fwrite(STDERR, "No system user found\n");
|
||||
exit(1);
|
||||
}
|
||||
$systemId = (int)$system['user_id'];
|
||||
|
||||
/** The reporter a ticket certainly came from, or null. */
|
||||
function detectSource(array $t): ?string
|
||||
{
|
||||
$title = (string)$t['title'];
|
||||
$description = (string)$t['description'];
|
||||
if (preg_match('/[┏┃┗━┣]/u', $description)) {
|
||||
return 'hwmonDaemon';
|
||||
}
|
||||
if (
|
||||
stripos($title, '[auto]') !== false
|
||||
&& preg_match('/automatically by Gandalf|from the Gandalf monitor/i', $description)
|
||||
) {
|
||||
return 'gandalf';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
$stmt = $conn->prepare(
|
||||
"SELECT ticket_id, title, description FROM tickets WHERE created_by = ? AND source IS NULL ORDER BY ticket_id"
|
||||
);
|
||||
$stmt->bind_param('i', $systemId);
|
||||
$stmt->execute();
|
||||
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
|
||||
$stmt->close();
|
||||
|
||||
$update = $conn->prepare("UPDATE tickets SET source = ? WHERE ticket_id = ? AND source IS NULL");
|
||||
$audit = new AuditLogModel($conn);
|
||||
$counts = [];
|
||||
$unknown = [];
|
||||
|
||||
foreach ($rows as $row) {
|
||||
$source = detectSource($row);
|
||||
if ($source === null) {
|
||||
$unknown[] = $row;
|
||||
continue;
|
||||
}
|
||||
$counts[$source] = ($counts[$source] ?? 0) + 1;
|
||||
if ($dryRun) {
|
||||
continue;
|
||||
}
|
||||
$update->bind_param('ss', $source, $row['ticket_id']);
|
||||
$update->execute();
|
||||
if ($update->affected_rows > 0) {
|
||||
$audit->log($systemId, 'update', 'ticket', $row['ticket_id'], [
|
||||
'source' => ['from' => null, 'to' => $source],
|
||||
'reason' => 'source backfilled from the description (tinker_tickets#123)',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($unknown as $row) {
|
||||
echo 'left unset ' . $row['ticket_id'] . ' ' . mb_substr((string)$row['title'], 0, 100) . "\n";
|
||||
}
|
||||
ksort($counts);
|
||||
$summary = [];
|
||||
foreach ($counts as $source => $n) {
|
||||
$summary[] = "$n $source";
|
||||
}
|
||||
printf(
|
||||
"%s%s %s, %d left unset\n",
|
||||
$dryRun ? '[dry run] ' : '',
|
||||
$dryRun ? 'would set' : 'set',
|
||||
$summary ? implode(', ', $summary) : 'none',
|
||||
count($unknown)
|
||||
);
|
||||
@@ -0,0 +1,216 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Helpers for tickets created by automated reporters through
|
||||
* create_ticket_api.php (gandalf, hwmonDaemon, thor): inserting a ticket,
|
||||
* the reopen window, and recurrence chains (#123).
|
||||
*
|
||||
* Every method runs on the caller's connection and inside the caller's
|
||||
* transaction; nothing here commits or rolls back.
|
||||
*
|
||||
* Recurrence rule, the same for every reporter: a report whose dedup hash
|
||||
* matches a Closed ticket reopens it when it closed less than
|
||||
* AUTO_REOPEN_WINDOW_DAYS ago. Otherwise a new ticket takes over the hash, is
|
||||
* linked relates_to the old one, records it in recurrence_of, and gets a
|
||||
* history comment. tickets.hash is UNIQUE, so the old ticket gives up its hash
|
||||
* (set to NULL) and keeps its dedup_key.
|
||||
*/
|
||||
|
||||
require_once dirname(__DIR__) . '/models/DependencyModel.php';
|
||||
|
||||
class AutoTicketService
|
||||
{
|
||||
/** Longest recurrence chain walked for the history line. */
|
||||
private const MAX_CHAIN = 50;
|
||||
|
||||
public static function reopenWindowDays(): int
|
||||
{
|
||||
$days = (int)($GLOBALS['config']['AUTO_REOPEN_WINDOW_DAYS'] ?? 7);
|
||||
return $days > 0 ? $days : 7;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ticket holding this dedup hash, locked FOR UPDATE, with
|
||||
* closed_recently = whether it closed inside the reopen window. A Closed
|
||||
* ticket without closed_at (closed before that column was kept) uses
|
||||
* updated_at instead.
|
||||
*/
|
||||
public static function lockByHash(mysqli $conn, string $hash): ?array
|
||||
{
|
||||
$days = self::reopenWindowDays();
|
||||
$stmt = $conn->prepare(
|
||||
"SELECT ticket_id, status, title, priority, closed_at, dedup_key,
|
||||
COALESCE(closed_at, updated_at) >= NOW() - INTERVAL ? DAY AS closed_recently
|
||||
FROM tickets WHERE hash = ? ORDER BY created_at DESC LIMIT 1 FOR UPDATE"
|
||||
);
|
||||
$stmt->bind_param('is', $days, $hash);
|
||||
$stmt->execute();
|
||||
$row = $stmt->get_result()->fetch_assoc();
|
||||
$stmt->close();
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A ticket_id not in use yet (same approach as TicketModel::createTicket),
|
||||
* so a 1062 on insert can only come from the unique hash.
|
||||
*/
|
||||
public static function newTicketId(mysqli $conn): ?string
|
||||
{
|
||||
$check = $conn->prepare("SELECT 1 FROM tickets WHERE ticket_id = ? LIMIT 1");
|
||||
for ($attempt = 0; $attempt < 50; $attempt++) {
|
||||
try {
|
||||
$candidate = sprintf('%09d', random_int(100000000, 999999999));
|
||||
} catch (Exception $e) {
|
||||
$candidate = sprintf('%09d', mt_rand(100000000, 999999999));
|
||||
}
|
||||
$check->bind_param('s', $candidate);
|
||||
$check->execute();
|
||||
if ($check->get_result()->num_rows === 0) {
|
||||
$check->close();
|
||||
return $candidate;
|
||||
}
|
||||
}
|
||||
$check->close();
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert an automated ticket. Throws mysqli_sql_exception (deadlock,
|
||||
* duplicate hash) for the caller's retry handling.
|
||||
*
|
||||
* @param array $t ticket_id, title, description, status, priority, category,
|
||||
* type, hash, created_by, source, dedup_key, recurrence_of
|
||||
*/
|
||||
public static function insert(mysqli $conn, array $t): void
|
||||
{
|
||||
$stmt = $conn->prepare(
|
||||
"INSERT INTO tickets (ticket_id, title, description, status, priority, category, type, hash,
|
||||
created_by, source, dedup_key, recurrence_of)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
|
||||
);
|
||||
$stmt->bind_param(
|
||||
'ssssisssisss',
|
||||
$t['ticket_id'],
|
||||
$t['title'],
|
||||
$t['description'],
|
||||
$t['status'],
|
||||
$t['priority'],
|
||||
$t['category'],
|
||||
$t['type'],
|
||||
$t['hash'],
|
||||
$t['created_by'],
|
||||
$t['source'],
|
||||
$t['dedup_key'],
|
||||
$t['recurrence_of']
|
||||
);
|
||||
try {
|
||||
$stmt->execute();
|
||||
} finally {
|
||||
$stmt->close();
|
||||
}
|
||||
}
|
||||
|
||||
/** Free the dedup slot held by a closed ticket so a new occurrence can take it. */
|
||||
public static function releaseHash(mysqli $conn, string $ticketId): void
|
||||
{
|
||||
$stmt = $conn->prepare("UPDATE tickets SET hash = NULL WHERE ticket_id = ?");
|
||||
$stmt->bind_param('s', $ticketId);
|
||||
$stmt->execute();
|
||||
$stmt->close();
|
||||
}
|
||||
|
||||
/** Link the new occurrence to the previous one, as the Dependencies tab shows it. */
|
||||
public static function linkRecurrence(mysqli $conn, string $newId, string $previousId, int $userId): void
|
||||
{
|
||||
$result = (new DependencyModel($conn))->addDependency($newId, $previousId, 'relates_to', $userId);
|
||||
if (empty($result['success'])) {
|
||||
error_log("AutoTicketService: could not link recurrence $newId -> $previousId: " . ($result['error'] ?? ''));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ticket IDs of a recurrence chain, newest first, starting at $ticketId
|
||||
* and following recurrence_of back.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function chain(mysqli $conn, string $ticketId): array
|
||||
{
|
||||
$ids = [];
|
||||
$stmt = $conn->prepare("SELECT recurrence_of FROM tickets WHERE ticket_id = ?");
|
||||
$current = $ticketId;
|
||||
while ($current !== null && $current !== '' && count($ids) < self::MAX_CHAIN && !in_array($current, $ids, true)) {
|
||||
$ids[] = $current;
|
||||
$stmt->bind_param('s', $current);
|
||||
$stmt->execute();
|
||||
$row = $stmt->get_result()->fetch_assoc();
|
||||
$current = $row['recurrence_of'] ?? null;
|
||||
}
|
||||
$stmt->close();
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* How many times this problem came up in the last $days: tickets in the
|
||||
* chain opened in that time, plus reports that reopened one of them (or
|
||||
* were noted on it while it stayed Closed because the Workflow Designer
|
||||
* allows no unattended reopen).
|
||||
*
|
||||
* @param list<string> $chain
|
||||
*/
|
||||
public static function occurrences(mysqli $conn, array $chain, int $days): int
|
||||
{
|
||||
if (!$chain) {
|
||||
return 0;
|
||||
}
|
||||
$in = implode(',', array_fill(0, count($chain), '?'));
|
||||
$types = 'i' . str_repeat('s', count($chain));
|
||||
|
||||
$stmt = $conn->prepare(
|
||||
"SELECT COUNT(*) FROM tickets WHERE created_at >= NOW() - INTERVAL ? DAY AND ticket_id IN ($in)"
|
||||
);
|
||||
$stmt->bind_param($types, $days, ...$chain);
|
||||
$stmt->execute();
|
||||
$opened = (int)$stmt->get_result()->fetch_row()[0];
|
||||
$stmt->close();
|
||||
|
||||
$stmt = $conn->prepare(
|
||||
"SELECT COUNT(*) FROM audit_log
|
||||
WHERE created_at >= NOW() - INTERVAL ? DAY AND entity_type = 'ticket' AND action_type = 'update'
|
||||
AND (details LIKE '%auto-reopened by%' OR details LIKE '%recurrence detected but%')
|
||||
AND entity_id IN ($in)"
|
||||
);
|
||||
$stmt->bind_param($types, $days, ...$chain);
|
||||
$stmt->execute();
|
||||
$reopened = (int)$stmt->get_result()->fetch_row()[0];
|
||||
$stmt->close();
|
||||
|
||||
return $opened + $reopened;
|
||||
}
|
||||
|
||||
/**
|
||||
* Comment for the first post on a new occurrence: which ticket it follows,
|
||||
* when that one cleared, and how often the problem has come up lately.
|
||||
*/
|
||||
public static function historyComment(mysqli $conn, string $newId, string $previousId, ?string $previousClosedAt): string
|
||||
{
|
||||
$window = self::reopenWindowDays();
|
||||
$chain = self::chain($conn, $newId);
|
||||
$week = self::occurrences($conn, $chain, 7);
|
||||
$month = self::occurrences($conn, $chain, 30);
|
||||
|
||||
$cleared = 'at an unknown time';
|
||||
if ($previousClosedAt) {
|
||||
$ts = strtotime($previousClosedAt);
|
||||
$tz = $GLOBALS['config']['TIMEZONE_ABBREV'] ?? '';
|
||||
$cleared = 'on ' . date('Y-m-d H:i', $ts !== false ? $ts : time()) . ($tz !== '' ? " $tz" : '');
|
||||
}
|
||||
$times = fn(int $n) => $n === 1 ? '1 time' : "$n times";
|
||||
|
||||
return "**Recurrence of #{$previousId}.**\n\n"
|
||||
. "That ticket was closed {$cleared}, more than {$window} days ago, so this occurrence gets "
|
||||
. "a new ticket instead of reopening it. The two are linked under Dependencies.\n\n"
|
||||
. 'Seen ' . $times($week) . ' in the last 7 days and ' . $times($month) . ' in the last 30 days '
|
||||
. "(" . count($chain) . " " . (count($chain) === 1 ? 'ticket' : 'tickets') . " in this chain).";
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,9 @@
|
||||
* relates_to / duplicates): access checks on the tickets involved,
|
||||
* DependencyModel's duplicate/inverse/cycle checks, and audit logging.
|
||||
*
|
||||
* Shared by the web UI (api/ticket_dependencies.php) and the MCP
|
||||
* link_tickets / unlink_tickets / get_ticket tools so both run one code path.
|
||||
* Shared by the web UI (api/ticket_dependencies.php), the MCP
|
||||
* link_tickets / unlink_tickets / get_ticket tools and the Bearer
|
||||
* api/ticket_link_api.php (#123) so they all run one code path.
|
||||
* Extracted from ticket_dependencies.php with the same checks, order and
|
||||
* error messages. Returns result arrays; failures carry 'http_status' for
|
||||
* HTTP callers. Callers own sessions/CSRF/responses.
|
||||
@@ -86,7 +87,7 @@ class DependencyService
|
||||
'ticket_id' => $ticketId,
|
||||
'depends_on_id' => $dependsOnId,
|
||||
'type' => $type
|
||||
]);
|
||||
] + ($data['audit_extra'] ?? []));
|
||||
|
||||
return $result;
|
||||
}
|
||||
@@ -131,7 +132,7 @@ class DependencyService
|
||||
'ticket_id' => $ticketId,
|
||||
'depends_on_id' => $dependsOnId,
|
||||
'type' => $type
|
||||
]);
|
||||
] + ($data['audit_extra'] ?? []));
|
||||
}
|
||||
return ['success' => true, 'removed' => $removed];
|
||||
}
|
||||
@@ -164,6 +165,113 @@ class DependencyService
|
||||
return ['success' => true, 'removed' => $removed];
|
||||
}
|
||||
|
||||
/**
|
||||
* Link two tickets, read as "ticket_id <relation> other_ticket_id". Used
|
||||
* by MCP link_tickets and the Bearer link API, so both validate and word
|
||||
* errors the same way. A missing or hidden ticket is "Ticket N not found".
|
||||
*
|
||||
* @param array $auditExtra Extra audit details, e.g. ['api_key' => 'thor']
|
||||
* @return array success: ticket_id, relation, other_ticket_id; failure: error, http_status
|
||||
*/
|
||||
public static function link(mysqli $conn, array $currentUser, $ticketId, $relation, $otherId, array $auditExtra = []): array
|
||||
{
|
||||
$args = self::linkArgs($ticketId, $relation, $otherId);
|
||||
if (isset($args['error'])) {
|
||||
return $args;
|
||||
}
|
||||
[$ticketId, $otherId, $relation] = $args;
|
||||
|
||||
$result = self::add($conn, $currentUser, [
|
||||
'ticket_id' => $ticketId,
|
||||
'depends_on_id' => $otherId,
|
||||
'dependency_type' => $relation,
|
||||
'audit_extra' => $auditExtra,
|
||||
]);
|
||||
if (empty($result['success'])) {
|
||||
$error = (string)($result['error'] ?? 'Request failed');
|
||||
if ($error === 'Ticket not found') {
|
||||
return ['success' => false, 'error' => "Ticket {$ticketId} not found", 'http_status' => 404];
|
||||
}
|
||||
if ($error === 'Target ticket not found') {
|
||||
return ['success' => false, 'error' => "Ticket {$otherId} not found", 'http_status' => 404];
|
||||
}
|
||||
// Already linked (either side) or a circular blocking chain.
|
||||
return ['success' => false, 'error' => $error, 'http_status' => 409];
|
||||
}
|
||||
|
||||
return ['success' => true, 'ticket_id' => $ticketId, 'relation' => $relation, 'other_ticket_id' => $otherId];
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a link stated as in link(). The same relationship can be stored
|
||||
* from either ticket ("B blocked_by A" for "A blocks B"); both are tried.
|
||||
* duplicates has no inverse type, so it is only ever stored one way.
|
||||
*
|
||||
* @param array $auditExtra Extra audit details, e.g. ['api_key' => 'thor']
|
||||
* @return array success: ticket_id, relation, other_ticket_id, removed; failure: error, http_status
|
||||
*/
|
||||
public static function unlink(mysqli $conn, array $currentUser, $ticketId, $relation, $otherId, array $auditExtra = []): array
|
||||
{
|
||||
$args = self::linkArgs($ticketId, $relation, $otherId);
|
||||
if (isset($args['error'])) {
|
||||
return $args;
|
||||
}
|
||||
[$ticketId, $otherId, $relation] = $args;
|
||||
|
||||
$inverse = ['blocks' => 'blocked_by', 'blocked_by' => 'blocks', 'relates_to' => 'relates_to'];
|
||||
$attempts = [[$ticketId, $otherId, $relation]];
|
||||
if (isset($inverse[$relation])) {
|
||||
$attempts[] = [$otherId, $ticketId, $inverse[$relation]];
|
||||
}
|
||||
|
||||
$removed = 0;
|
||||
foreach ($attempts as [$from, $to, $type]) {
|
||||
$result = self::remove($conn, $currentUser, [
|
||||
'ticket_id' => $from,
|
||||
'depends_on_id' => $to,
|
||||
'dependency_type' => $type,
|
||||
'audit_extra' => $auditExtra,
|
||||
]);
|
||||
if (empty($result['success'])) {
|
||||
$error = (string)($result['error'] ?? 'Request failed');
|
||||
if ($error === 'Ticket not found') {
|
||||
return ['success' => false, 'error' => "Ticket {$from} not found", 'http_status' => 404];
|
||||
}
|
||||
return ['success' => false, 'error' => $error, 'http_status' => $result['http_status'] ?? 400];
|
||||
}
|
||||
$removed += (int)$result['removed'];
|
||||
}
|
||||
if ($removed === 0) {
|
||||
return ['success' => false, 'error' => "No {$relation} link between {$ticketId} and {$otherId}", 'http_status' => 404];
|
||||
}
|
||||
|
||||
return ['success' => true, 'ticket_id' => $ticketId, 'relation' => $relation, 'other_ticket_id' => $otherId, 'removed' => true];
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise and check link arguments.
|
||||
*
|
||||
* @return array [ticketId, otherId, relation], or an error result
|
||||
*/
|
||||
private static function linkArgs($ticketId, $relation, $otherId): array
|
||||
{
|
||||
$ticketId = trim((string)$ticketId);
|
||||
$otherId = trim((string)$otherId);
|
||||
$relation = strtolower(trim((string)$relation));
|
||||
if (!in_array($relation, self::TYPES, true)) {
|
||||
return ['success' => false, 'error' => 'relation must be one of: ' . implode(', ', self::TYPES), 'http_status' => 400];
|
||||
}
|
||||
foreach ([$ticketId, $otherId] as $id) {
|
||||
if (!ctype_digit($id)) {
|
||||
return ['success' => false, 'error' => "Ticket {$id} not found", 'http_status' => 404];
|
||||
}
|
||||
}
|
||||
if ($ticketId === $otherId) {
|
||||
return ['success' => false, 'error' => 'A ticket cannot be linked to itself', 'http_status' => 400];
|
||||
}
|
||||
return [$ticketId, $otherId, $relation];
|
||||
}
|
||||
|
||||
/**
|
||||
* users.groups is a comma-separated string; the dependency model expects an array.
|
||||
*
|
||||
|
||||
+22
-2
@@ -53,6 +53,9 @@ if (!empty($_GET['category'])) {
|
||||
if (!empty($_GET['type'])) {
|
||||
$activeFilters[] = ['type' => 'type', 'value' => $_GET['type'], 'label' => 'Type: ' . $_GET['type']];
|
||||
}
|
||||
if (!empty($_GET['source'])) {
|
||||
$activeFilters[] = ['type' => 'source', 'value' => $_GET['source'], 'label' => 'Source: ' . $_GET['source']];
|
||||
}
|
||||
if (!empty($_GET['assigned_to'])) {
|
||||
$label = match ($_GET['assigned_to']) {
|
||||
'unassigned' => 'Unassigned', 'me' => 'Me', default => 'User #' . $_GET['assigned_to']
|
||||
@@ -82,6 +85,7 @@ $_lt_statuses = $GLOBALS['config']['TICKET_STATUSES'];
|
||||
$currentStatus = isset($_GET['status']) ? explode(',', $_GET['status']) : ['Open', 'Pending', 'In Progress'];
|
||||
$currentCategories = isset($_GET['category']) ? explode(',', $_GET['category']) : [];
|
||||
$currentTypes = isset($_GET['type']) ? explode(',', $_GET['type']) : [];
|
||||
$currentSources = isset($_GET['source']) ? explode(',', $_GET['source']) : [];
|
||||
$isAdmin = $GLOBALS['currentUser']['is_admin'] ?? false;
|
||||
$colCount = $isAdmin ? 12 : 11;
|
||||
|
||||
@@ -543,6 +547,21 @@ include __DIR__ . '/layout_header.php';
|
||||
</fieldset>
|
||||
<?php endif ?>
|
||||
|
||||
<!-- Source Filter: which reporter (API key) created the ticket (#123) -->
|
||||
<?php if (!empty($sources)) : ?>
|
||||
<fieldset class="lt-filter-group">
|
||||
<legend class="lt-filter-label">Source</legend>
|
||||
<?php foreach ($sources as $src) : ?>
|
||||
<label class="lt-filter-option">
|
||||
<input type="checkbox" class="lt-checkbox sidebar-filter"
|
||||
name="source" value="<?= htmlspecialchars($src) ?>"
|
||||
<?= in_array($src, $currentSources) ? 'checked' : '' ?>>
|
||||
<?= htmlspecialchars($src) ?>
|
||||
</label>
|
||||
<?php endforeach ?>
|
||||
</fieldset>
|
||||
<?php endif ?>
|
||||
|
||||
<!-- Date Filters -->
|
||||
<fieldset class="lt-filter-group">
|
||||
<legend class="lt-filter-label">Created</legend>
|
||||
@@ -591,7 +610,7 @@ include __DIR__ . '/layout_header.php';
|
||||
<button type="button" id="lt-sidebar-toggle-btn" class="lt-btn lt-btn-ghost lt-btn-sm"
|
||||
aria-label="Toggle filter sidebar" title="Toggle filters">⋮⋮ Filters</button>
|
||||
<form method="GET" action="" class="lt-search-form" role="search">
|
||||
<?php foreach (['status','category','type','sort','dir'] as $p) : ?>
|
||||
<?php foreach (['status','category','type','source','sort','dir'] as $p) : ?>
|
||||
<?php if (isset($_GET[$p])) : ?>
|
||||
<input type="hidden" name="<?= $p ?>" value="<?= htmlspecialchars($_GET[$p]) ?>">
|
||||
<?php endif ?>
|
||||
@@ -785,7 +804,8 @@ include __DIR__ . '/layout_header.php';
|
||||
</tr>
|
||||
<?php else : ?>
|
||||
<?php foreach ($tickets as $row) :
|
||||
$creator = htmlspecialchars($row['creator_display_name'] ?? $row['creator_username'] ?? 'System');
|
||||
// API-created tickets show the reporter (key name) instead of "System" (#123)
|
||||
$creator = htmlspecialchars(!empty($row['source']) ? $row['source'] : ($row['creator_display_name'] ?? $row['creator_username'] ?? 'System'));
|
||||
$assignedTo = htmlspecialchars($row['assigned_display_name'] ?? $row['assigned_username'] ?? 'Unassigned');
|
||||
$pNum = (int)$row['priority'];
|
||||
$rowStatusSlug = strtolower(str_replace(' ', '-', $row['status']));
|
||||
|
||||
@@ -103,7 +103,10 @@ $statusSlug = strtolower(str_replace(' ', '-', $ticket['status']));
|
||||
$priorityNum = (int)($ticket['priority'] ?? 3);
|
||||
$currentUserId = $GLOBALS['currentUser']['user_id'] ?? null;
|
||||
$isAdmin = $GLOBALS['currentUser']['is_admin'] ?? false;
|
||||
$creator = $ticket['creator_display_name'] ?? $ticket['creator_username'] ?? 'System';
|
||||
// API-created tickets name the reporter (the API key) instead of "System" (#123)
|
||||
$creator = !empty($ticket['source'])
|
||||
? $ticket['source'] . ' (API)'
|
||||
: ($ticket['creator_display_name'] ?? $ticket['creator_username'] ?? 'System');
|
||||
|
||||
// Visibility
|
||||
$currentVisibility = $ticket['visibility'] ?? 'public';
|
||||
|
||||
Reference in new issue
Block a user