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
@@ -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.
|
||||
*
|
||||
|
||||
Reference in new issue
Block a user