| 1 |
<?php |
| 2 |
/** |
| 3 |
* One-active-import-per-user guard (spec 042 FR-015, research.md §5). |
| 4 |
* |
| 5 |
* FSI is inherently single-session (`SessionData::get_session_id()` tracks one |
| 6 |
* import); the browser enforces one-at-a-time via its UI. Headless MCP callers |
| 7 |
* have no such UI, so this small registry makes the invariant hold: a second |
| 8 |
* `start` while one import is in flight returns the existing handle instead of |
| 9 |
* minting a parallel session. |
| 10 |
* |
| 11 |
* Stored in a NON-autoloaded per-user option so it never bloats the autoload |
| 12 |
* cache (matches the 026/034 storage convention). Scoped by user id the same |
| 13 |
* way `Templately\Utils\Options` scopes its rows. |
| 14 |
* |
| 15 |
* @package Templately\Modules\FullSiteImport\Abilities\Support |
| 16 |
*/ |
| 17 |
|
| 18 |
namespace Templately\Modules\FullSiteImport\Abilities\Support; |
| 19 |
|
| 20 |
class FsiActiveImportGuard { |
| 21 |
|
| 22 |
const OPTION_PREFIX = 'templately_mcp_fsi_active_'; |
| 23 |
|
| 24 |
/** |
| 25 |
* The active handle for a user, or null when there is none. |
| 26 |
* |
| 27 |
* @param int $user_id |
| 28 |
* @return array|null { session_id, started_at } or null. |
| 29 |
*/ |
| 30 |
public static function get_active( int $user_id ): ?array { |
| 31 |
$row = get_option( self::key( $user_id ) ); |
| 32 |
|
| 33 |
if ( empty( $row ) || ! is_array( $row ) || empty( $row['session_id'] ) ) { |
| 34 |
return null; |
| 35 |
} |
| 36 |
|
| 37 |
return $row; |
| 38 |
} |
| 39 |
|
| 40 |
/** |
| 41 |
* Record a user's active import handle. |
| 42 |
* |
| 43 |
* @param int $user_id |
| 44 |
* @param string $session_id |
| 45 |
* @return void |
| 46 |
*/ |
| 47 |
public static function set_active( int $user_id, string $session_id ): void { |
| 48 |
// add_option with autoload 'no' on first write; update_option keeps the |
| 49 |
// existing autoload flag on subsequent writes. |
| 50 |
$key = self::key( $user_id ); |
| 51 |
$row = [ 'session_id' => $session_id, 'started_at' => time() ]; |
| 52 |
|
| 53 |
if ( false === get_option( $key ) ) { |
| 54 |
add_option( $key, $row, '', 'no' ); |
| 55 |
} else { |
| 56 |
update_option( $key, $row ); |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* Clear a user's active import handle (on a terminal complete/failed/revert). |
| 62 |
* |
| 63 |
* @param int $user_id |
| 64 |
* @return void |
| 65 |
*/ |
| 66 |
public static function clear( int $user_id ): void { |
| 67 |
delete_option( self::key( $user_id ) ); |
| 68 |
} |
| 69 |
|
| 70 |
/** |
| 71 |
* @param int $user_id |
| 72 |
* @return string |
| 73 |
*/ |
| 74 |
private static function key( int $user_id ): string { |
| 75 |
return self::OPTION_PREFIX . $user_id; |
| 76 |
} |
| 77 |
} |
| 78 |
|