-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDataMachineJobCleanupRunEvidenceStore.php
More file actions
454 lines (406 loc) · 14.8 KB
/
Copy pathDataMachineJobCleanupRunEvidenceStore.php
File metadata and controls
454 lines (406 loc) · 14.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
<?php
/**
* Cleanup run evidence store backed by Data Machine job records.
*
* @package DataMachineCode\Cleanup
*/
namespace DataMachineCode\Cleanup;
defined( 'ABSPATH' ) || exit;
class DataMachineJobCleanupRunEvidenceStore implements CleanupRunEvidenceStoreInterface {
/**
* Read one cleanup run.
*
* @param string $run_id Stable cleanup run identifier.
* @param bool $include_evidence Whether to include raw evidence records.
* @return array<string,mixed>|\WP_Error
*/
public function read( string $run_id, bool $include_evidence = false ): array|\WP_Error {
$job_id = $this->cleanup_run_job_id( $run_id );
if ( $job_id <= 0 ) {
return new \WP_Error( 'invalid_cleanup_run_id', 'Cleanup run id must be a numeric job id or cleanup-run-<job_id>.', array( 'status' => 400 ) );
}
$job = $this->get_cleanup_run_job( $job_id );
if ( array() === $job ) {
return new \WP_Error( 'cleanup_run_not_found', sprintf( 'Cleanup run not found: %s', $this->cleanup_run_id( $job_id ) ), array( 'status' => 404 ) );
}
$engine_data = $this->normalize_engine_data( $job['engine_data'] ?? array() );
$child_jobs = $this->get_cleanup_run_descendant_jobs( $job_id );
$aggregate = $this->aggregate_cleanup_child_jobs( $child_jobs );
$children = $aggregate['children'];
$state = $this->cleanup_run_state( (string) ( $job['status'] ?? '' ), $children );
$output = array(
'success' => true,
'state' => $state,
'run_id' => $this->cleanup_run_id( $job_id ),
'job_id' => $job_id,
'status' => in_array( $state, array( 'children_processing', 'partial_failed' ), true ) ? $state : ( $job['status'] ?? '' ),
'created_at' => $job['created_at'] ?? '',
'completed_at' => $job['completed_at'] ?? '',
'artifact_cleanup' => $aggregate['artifact_cleanup'],
'cleanup_items' => $aggregate['cleanup_items'],
'children' => $children,
);
if ( isset( $engine_data['system_task_result'] ) && is_array( $engine_data['system_task_result'] ) ) {
$engine_data['system_task_result'] = $this->with_cleanup_aggregate_report( $engine_data['system_task_result'], $aggregate );
}
if ( $include_evidence ) {
$output['evidence'] = array(
'storage' => array(
'source' => 'datamachine_jobs',
'filesystem_plans' => false,
'schema_dependency' => 'datamachine_code_cleanup_runs and datamachine_code_cleanup_items from issue #244 become the canonical store when available.',
),
'artifact_cleanup' => $aggregate['artifact_cleanup'],
'cleanup_items' => $aggregate['cleanup_items'],
'children' => $children,
'engine_data' => $engine_data,
'job' => $job,
'child_jobs' => $child_jobs,
);
} else {
$output['mode'] = $engine_data['cleanup_run']['mode'] ?? '';
if ( isset( $engine_data['system_task_result'] ) ) {
$output['system_task_result'] = $engine_data['system_task_result'];
}
}
return $output;
}
/**
* Aggregate cleanup child job results for status/evidence output.
*
* @param array<int,array<string,mixed>> $child_jobs Descendant jobs.
* @return array{artifact_cleanup:array<string,mixed>,cleanup_items:array<string,mixed>,children:array<string,mixed>}
*/
private function aggregate_cleanup_child_jobs( array $child_jobs ): array {
$summary = array(
'artifact_cleanup' => array(
'planned_rows' => 0,
'applied_rows' => 0,
'skipped_rows' => 0,
'failed_rows' => 0,
'bytes_reclaimed' => 0,
'freed_human' => $this->format_bytes( 0 ),
'skipped_by_reason' => array(),
'failed_by_reason' => array(),
),
'cleanup_items' => array(
'planned_rows' => 0,
'applied_rows' => 0,
'skipped_rows' => 0,
'failed_rows' => 0,
'bytes_reclaimed' => 0,
'freed_human' => $this->format_bytes( 0 ),
'by_type' => array(),
'skipped_by_reason' => array(),
'failed_by_reason' => array(),
),
'children' => array(
'batch_job_ids' => array(),
'chunk_job_ids' => array(),
'processing' => 0,
'completed' => 0,
'failed' => 0,
'running' => 0,
'total' => 0,
'statuses' => array(),
'job_ids' => array(),
),
);
foreach ( $child_jobs as $child ) {
$child_job_id = (int) ( $child['job_id'] ?? 0 );
$status = (string) ( $child['status'] ?? '' );
$engine_data = $this->normalize_engine_data( $child['engine_data'] ?? array() );
$result = is_array( $engine_data['system_task_result'] ?? null ) ? $engine_data['system_task_result'] : array();
++$summary['children']['total'];
if ( $child_job_id > 0 ) {
$summary['children']['job_ids'][] = $child_job_id;
}
$this->count_cleanup_child_status( $summary['children'], $status );
if ( isset( $summary['children']['statuses'][ $status ] ) ) {
++$summary['children']['statuses'][ $status ];
} elseif ( '' !== $status ) {
$summary['children']['statuses'][ $status ] = 1;
}
if ( 'batch' === (string) ( $child['source'] ?? '' ) || isset( $engine_data['batch_id'] ) ) {
if ( $child_job_id > 0 ) {
$summary['children']['batch_job_ids'][] = $child_job_id;
}
continue;
}
if ( 'worktree_cleanup_chunk' !== (string) ( $engine_data['task_type'] ?? '' ) && ! isset( $result['chunk_type'] ) ) {
continue;
}
if ( $child_job_id > 0 ) {
$summary['children']['chunk_job_ids'][] = $child_job_id;
}
$this->merge_cleanup_item_result( $summary['cleanup_items'], $result );
if ( 'artifacts' === (string) ( $result['chunk_type'] ?? '' ) ) {
$this->merge_cleanup_item_result( $summary['artifact_cleanup'], $result );
}
}
$summary['artifact_cleanup']['freed_human'] = $this->format_bytes( $summary['artifact_cleanup']['bytes_reclaimed'] );
$summary['cleanup_items']['freed_human'] = $this->format_bytes( $summary['cleanup_items']['bytes_reclaimed'] );
$summary['children']['batch_job_ids'] = array_values( array_unique( $summary['children']['batch_job_ids'] ) );
$summary['children']['chunk_job_ids'] = array_values( array_unique( $summary['children']['chunk_job_ids'] ) );
$summary['children']['job_ids'] = array_values( array_unique( $summary['children']['job_ids'] ) );
$summary['children']['running'] = (int) $summary['children']['processing'];
return $summary;
}
/**
* Merge one chunk task result into aggregate cleanup item counters.
*
* @param array $summary Cleanup item summary.
* @param array $result Chunk task result.
* @return void
*/
private function merge_cleanup_item_result( array &$summary, array $result ): void {
$chunk_type = (string) ( $result['chunk_type'] ?? 'unknown' );
if ( ! isset( $summary['by_type'] ) ) {
$summary['by_type'] = array();
}
if ( ! isset( $summary['by_type'][ $chunk_type ] ) ) {
$summary['by_type'][ $chunk_type ] = array(
'planned_rows' => 0,
'applied_rows' => 0,
'skipped_rows' => 0,
'failed_rows' => 0,
'bytes_reclaimed' => 0,
);
}
$planned = max( 0, (int) ( $result['planned_count'] ?? 0 ) );
$applied = max( 0, (int) ( $result['applied_count'] ?? 0 ) );
$skipped = max( 0, (int) ( $result['skipped_count'] ?? 0 ) );
$failed = max( 0, (int) ( $result['failed_count'] ?? 0 ) );
$bytes_reclaimed = max( 0, (int) ( $result['bytes_reclaimed'] ?? 0 ) );
$summary['planned_rows'] += $planned;
$summary['applied_rows'] += $applied;
$summary['skipped_rows'] += $skipped;
$summary['failed_rows'] += $failed;
$summary['bytes_reclaimed'] += $bytes_reclaimed;
$summary['by_type'][ $chunk_type ]['planned_rows'] += $planned;
$summary['by_type'][ $chunk_type ]['applied_rows'] += $applied;
$summary['by_type'][ $chunk_type ]['skipped_rows'] += $skipped;
$summary['by_type'][ $chunk_type ]['failed_rows'] += $failed;
$summary['by_type'][ $chunk_type ]['bytes_reclaimed'] += $bytes_reclaimed;
$this->merge_cleanup_reason_counts( $summary['skipped_by_reason'], (array) ( $result['skipped'] ?? array() ) );
$this->merge_cleanup_reason_counts( $summary['failed_by_reason'], (array) ( $result['failed'] ?? array() ) );
}
/**
* Replace placeholder parent report fields with child aggregate totals.
*
* @param array $result Parent system task result.
* @param array $aggregate Child aggregate.
* @return array<string,mixed>
*/
private function with_cleanup_aggregate_report( array $result, array $aggregate ): array {
$cleanup_items = (array) ( $aggregate['cleanup_items'] ?? array() );
if ( ! empty( $result['job_backed'] ) && isset( $result['report'] ) && is_array( $result['report'] ) ) {
$result['report']['bytes_reclaimed'] = (int) ( $cleanup_items['bytes_reclaimed'] ?? 0 );
$result['report']['freed_human'] = (string) ( $cleanup_items['freed_human'] ?? $this->format_bytes( 0 ) );
}
$result['artifact_cleanup'] = (array) ( $aggregate['artifact_cleanup'] ?? array() );
$result['cleanup_items'] = $cleanup_items;
$result['children'] = (array) ( $aggregate['children'] ?? array() );
return $result;
}
/**
* Fetch the parent cleanup run job.
*
* @param int $job_id Job ID.
* @return array<string,mixed>
*/
private function get_cleanup_run_job( int $job_id ): array {
$ability = wp_get_ability( 'datamachine/get-jobs' );
if ( ! $ability ) {
return array();
}
$result = $ability->execute( array( 'job_id' => $job_id ) );
if ( ! ( $result['success'] ?? false ) ) {
return array();
}
$jobs = $result['jobs'] ?? array();
return is_array( $jobs ) && ! empty( $jobs[0] ) && is_array( $jobs[0] ) ? $jobs[0] : array();
}
/**
* Return every job linked below a cleanup run job.
*
* @param int $job_id Parent job ID.
* @param array<int,bool> $seen Seen job IDs.
* @return array<int,array<string,mixed>>
*/
private function get_cleanup_run_descendant_jobs( int $job_id, array &$seen = array() ): array {
$ability = wp_get_ability( 'datamachine/get-jobs' );
if ( ! $ability || isset( $seen[ $job_id ] ) ) {
return array();
}
$seen[ $job_id ] = true;
$children = array();
$offset = 0;
$per_page = 100;
do {
$result = $ability->execute(
array(
'parent_job_id' => $job_id,
'per_page' => $per_page,
'offset' => $offset,
'orderby' => 'j.job_id',
'order' => 'ASC',
)
);
if ( ! ( $result['success'] ?? false ) ) {
break;
}
$page = is_array( $result['jobs'] ?? null ) ? $result['jobs'] : array();
foreach ( $page as $child ) {
if ( ! is_array( $child ) ) {
continue;
}
$child_id = (int) ( $child['job_id'] ?? 0 );
if ( $child_id <= 0 || isset( $seen[ $child_id ] ) ) {
continue;
}
$children[] = $child;
$children = array_merge( $children, $this->get_cleanup_run_descendant_jobs( $child_id, $seen ) );
}
$offset += $per_page;
$total = (int) ( $result['total'] ?? count( $page ) );
} while ( $offset < $total && ! empty( $page ) );
return $children;
}
/**
* Normalize engine_data stored as either decoded array or JSON string.
*
* @param mixed $engine_data Engine data.
* @return array<string,mixed>
*/
private function normalize_engine_data( mixed $engine_data ): array {
if ( is_array( $engine_data ) ) {
return $engine_data;
}
if ( is_string( $engine_data ) && '' !== trim( $engine_data ) ) {
$decoded = json_decode( $engine_data, true );
return is_array( $decoded ) ? $decoded : array();
}
return array();
}
/**
* Count a child job status into stable status buckets.
*
* @param array $children Child aggregate.
* @param string $status Job status.
* @return void
*/
private function count_cleanup_child_status( array &$children, string $status ): void {
if ( in_array( $status, array( 'pending', 'processing' ), true ) ) {
++$children['processing'];
return;
}
if ( str_starts_with( $status, 'failed' ) ) {
++$children['failed'];
return;
}
if ( str_starts_with( $status, 'completed' ) ) {
++$children['completed'];
}
}
/**
* Merge skipped/failed reason counts from chunk rows.
*
* @param array $counts Reason counts.
* @param array $rows Rows with reason_code/reason.
* @return void
*/
private function merge_cleanup_reason_counts( array &$counts, array $rows ): void {
foreach ( $rows as $row ) {
$reason = is_array( $row ) ? (string) ( $row['reason_code'] ?? $row['reason'] ?? 'unknown' ) : 'unknown';
if ( '' === $reason ) {
$reason = 'unknown';
}
$counts[ $reason ] = (int) ( $counts[ $reason ] ?? 0 ) + 1;
}
}
/**
* Compute aggregate cleanup run state from parent and child jobs.
*
* @param string $status Parent job status.
* @param array $children Child summary.
* @return string
*/
private function cleanup_run_state( string $status, array $children ): string {
$parent_state = $this->cleanup_job_state( $status );
if ( in_array( $parent_state, array( 'cancelled', 'partial_failure' ), true ) ) {
return $parent_state;
}
if ( (int) ( $children['running'] ?? 0 ) > 0 ) {
return 'children_processing';
}
if ( (int) ( $children['failed'] ?? 0 ) > 0 ) {
return 'partial_failed';
}
return $parent_state;
}
/**
* Convert job status into cleanup run state.
*
* @param string $status Job status.
* @return string
*/
private function cleanup_job_state( string $status ): string {
if ( in_array( $status, array( 'pending', 'processing' ), true ) ) {
return 'running';
}
if ( str_starts_with( $status, 'failed - cleanup_cancelled' ) ) {
return 'cancelled';
}
if ( str_starts_with( $status, 'failed' ) ) {
return 'partial_failure';
}
if ( str_starts_with( $status, 'completed' ) ) {
return 'complete';
}
return 'unknown';
}
/**
* Build stable run id from a Data Machine job id.
*
* @param int $job_id Job ID.
* @return string
*/
private function cleanup_run_id( int $job_id ): string {
return 'cleanup-run-' . $job_id;
}
/**
* Parse stable run id into a Data Machine job id.
*
* @param string $run_id Run ID.
* @return int
*/
private function cleanup_run_job_id( string $run_id ): int {
$run_id = trim( $run_id );
if ( is_numeric( $run_id ) ) {
return (int) $run_id;
}
if ( preg_match( '/cleanup-run-(\d+)/', $run_id, $matches ) ) {
return (int) $matches[1];
}
return 0;
}
/**
* Format bytes using binary units.
*
* @param int $bytes Bytes.
* @return string
*/
private function format_bytes( int $bytes ): string {
$bytes = max( 0, $bytes );
$units = array( 'B', 'KiB', 'MiB', 'GiB', 'TiB' );
$max_unit = count( $units ) - 1;
$value = (float) $bytes;
$unit = 0;
while ( $value >= 1024 && $unit < $max_unit ) {
$value /= 1024;
++$unit;
}
return 0 === $unit ? sprintf( '%d B', (int) $value ) : sprintf( '%.1f %s', $value, $units[ $unit ] );
}
}