Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
77.56% covered (warning)
77.56%
121 / 156
33.33% covered (danger)
33.33%
3 / 9
CRAP
0.00% covered (danger)
0.00%
0 / 1
InitialContentSnapshot
77.56% covered (warning)
77.56%
121 / 156
33.33% covered (danger)
33.33%
3 / 9
45.30
0.00% covered (danger)
0.00%
0 / 1
 getFunctionSchemataSha
85.71% covered (warning)
85.71%
6 / 7
0.00% covered (danger)
0.00%
0 / 1
3.03
 dump
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
1
 restore
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
2
 validateBundle
51.28% covered (warning)
51.28%
20 / 39
0.00% covered (danger)
0.00%
0 / 1
24.99
 dumpPages
88.46% covered (warning)
88.46%
23 / 26
0.00% covered (danger)
0.00%
0 / 1
3.01
 dumpSecondaryTables
100.00% covered (success)
100.00%
21 / 21
100.00% covered (success)
100.00%
1 / 1
3
 writeManifest
71.43% covered (warning)
71.43%
10 / 14
0.00% covered (danger)
0.00%
0 / 1
2.09
 importPages
62.50% covered (warning)
62.50%
10 / 16
0.00% covered (danger)
0.00%
0 / 1
4.84
 restoreSecondaryTables
83.33% covered (warning)
83.33%
10 / 12
0.00% covered (danger)
0.00%
0 / 1
4.07
1<?php
2
3/**
4 * WikiLambda initial-content snapshot core.
5 *
6 * Single source of truth for the initial-content snapshot bundle: the built-in ZObject pages
7 * and their WikiLambda secondary tables, dumped so that install.php/update.php can restore them
8 * quickly instead of replaying the ~1,500 per-object edits that
9 * RepoHooks::createInitialContent() performs.
10 *
11 * The bundle is a pure performance cache: restore() validates it up front and returns false on
12 * any mismatch so the caller can fall back to the authoritative slow path, meaning a stale or
13 * corrupt bundle can only cost time, never correctness.
14 *
15 * This logic is shared by the dumpInitialContent.php / restoreInitialContent.php maintenance
16 * scripts and by RepoHooks::maybeRestoreInitialContent() (the automatic install/update path).
17 *
18 * @file
19 * @ingroup Extensions
20 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
21 * @license MIT
22 */
23
24namespace MediaWiki\Extension\WikiLambda;
25
26use MediaWiki\Export\DumpFileOutput;
27use MediaWiki\Export\WikiExporter;
28use MediaWiki\Import\ImportStreamSource;
29use MediaWiki\Json\FormatJson;
30use MediaWiki\MediaWikiServices;
31use MediaWiki\Permissions\UltimateAuthority;
32use MediaWiki\Shell\Shell;
33use MediaWiki\User\User;
34use RuntimeException;
35use Wikimedia\Rdbms\IDatabase;
36
37class InitialContentSnapshot {
38
39    /**
40     * Updatelog marker key set once the initial content has been restored from a snapshot bundle.
41     * When present, RepoHooks::createInitialContent() and initializeZObjectJoinTable() short-circuit
42     * so update.php doesn't replay the ~1,500 per-object edits (nor purge each page) over
43     * already-restored state.
44     */
45    public const MARKER = 'WikiLambda initial content restored from snapshot';
46
47    /**
48     * Bundle format version, stamped into the manifest and checked on restore. Bump whenever the
49     * on-disk bundle layout changes so stale bundles are rejected rather than mis-restored.
50     */
51    public const FORMAT_VERSION = 1;
52
53    /**
54     * The WikiLambda repo-mode secondary tables to snapshot, mapped to their auto-increment
55     * surrogate primary key. These are derived indexes over the ZObject pages; we dump them raw
56     * so restore can skip the (slow) secondary-data updates.
57     *
58     * The surrogate key is omitted from the dump (nothing references it) so restore lets the DB
59     * assign fresh values. Preserving explicit key values would work on MySQL/SQLite but leave a
60     * PostgreSQL identity sequence un-advanced, colliding on the first post-restore insert.
61     *
62     * wikilambda_ztester_results is deliberately excluded: its rows key on revision IDs, which
63     * importDump reassigns on the target wiki, so restored rows would dangle. It is a recomputable
64     * cache, so a restored wiki correctly starts with it empty.
65     */
66    public const SECONDARY_TABLES = [
67        'wikilambda_zobject_labels' => 'wlzl_id',
68        'wikilambda_zobject_join' => 'wlzo_id',
69        'wikilambda_zobject_function_join' => 'wlzf_id',
70        'wikilambda_zobject_label_conflicts' => 'wlzlc_id',
71        'wikilambda_zlanguages' => 'wlzlangs_id',
72    ];
73
74    public const PAGES_FILE = 'initial-content.xml';
75    public const SECONDARY_TABLES_FILE = 'secondary-tables.json';
76    public const MANIFEST_FILE = 'manifest.json';
77
78    /** Default bundle location, shared by the dump/restore scripts and the install/update hook. */
79    public const DEFAULT_DIR = __DIR__ . '/../maintenance/initial-content';
80
81    /** Number of secondary-table rows to insert per statement, within the single transaction. */
82    private const INSERT_BATCH_SIZE = 500;
83
84    /**
85     * Resolve the currently checked-out commit SHA of the function-schemata submodule. Used to
86     * stamp and validate initial-content snapshot bundles, so a bundle produced against a
87     * different set of built-in definitions is never restored.
88     *
89     * @return string|null The 40-character SHA, or null if it could not be determined
90     */
91    public static function getFunctionSchemataSha(): ?string {
92        $submodulePath = dirname( __DIR__ ) . '/function-schemata';
93        $result = Shell::command( 'git', '-C', $submodulePath, 'rev-parse', 'HEAD' )
94            ->execute();
95
96        if ( $result->getExitCode() !== 0 ) {
97            return null;
98        }
99
100        $sha = trim( $result->getStdout() );
101        return preg_match( '/^[0-9a-f]{40}$/', $sha ) ? $sha : null;
102    }
103
104    /**
105     * Produce a snapshot bundle (pages XML dump, secondary-tables sidecar and manifest) from the
106     * current wiki state into the given directory.
107     *
108     * @param string $dir Directory into which to write the bundle files (created by the caller)
109     * @param callable $output Progress sink, called as function( string $message ): void
110     * @return array The manifest that was written
111     * @throws RuntimeException On a silently-empty page export or an unresolvable submodule SHA
112     */
113    public static function dump( string $dir, callable $output ): array {
114        $dir = rtrim( $dir, '/' );
115
116        $pageCount = self::dumpPages( "$dir/" . self::PAGES_FILE );
117        $output( "Exported $pageCount page(s)." );
118
119        $tableRowCounts = self::dumpSecondaryTables( "$dir/" . self::SECONDARY_TABLES_FILE );
120        $output( "Dumped " . count( $tableRowCounts ) . ' secondary table(s).' );
121
122        $manifest = self::writeManifest( "$dir/" . self::MANIFEST_FILE, $pageCount, $tableRowCounts );
123        $output( 'Wrote manifest.' );
124
125        return $manifest;
126    }
127
128    /**
129     * Restore a snapshot bundle from the given directory: validate it, then import the built-in
130     * ZObject pages and bulk-load the WikiLambda secondary tables.
131     *
132     * The bundle is validated in full before any mutation happens, so a false return always means
133     * nothing was changed and the caller can safely fall back to the slow per-object load. This
134     * method deliberately does NOT write the updatelog marker: the correct mechanism differs by
135     * context (a raw insert for a standalone script run, DatabaseUpdater::insertUpdateRow() for the
136     * install/update hook), so the caller records it after a true return.
137     *
138     * @param IDatabase $dbw Primary database handle to bulk-insert the secondary tables into
139     * @param string $dir Directory containing the bundle files
140     * @param callable $output Progress/diagnostic sink, called as function( string $message ): void
141     * @return bool True if the bundle was valid and restored; false if it was missing, invalid or
142     *   mismatched (a reason is emitted via $output and nothing was mutated)
143     * @throws RuntimeException If a validated bundle then fails to import or insert
144     */
145    public static function restore( IDatabase $dbw, string $dir, callable $output ): bool {
146        $dir = rtrim( $dir, '/' );
147        $manifestFile = "$dir/" . self::MANIFEST_FILE;
148        $pagesFile = "$dir/" . self::PAGES_FILE;
149        $sidecarFile = "$dir/" . self::SECONDARY_TABLES_FILE;
150
151        $validated = self::validateBundle( $manifestFile, $pagesFile, $sidecarFile, $output );
152        if ( $validated === null ) {
153            return false;
154        }
155        [ $manifest, $dump ] = $validated;
156
157        self::importPages( $pagesFile );
158        self::restoreSecondaryTables( $dbw, $dump );
159        $pageCount = (int)( $manifest['pageCount'] ?? 0 );
160        $output( "Restored $pageCount ZObject page(s) from snapshot bundle." );
161
162        return true;
163    }
164
165    /**
166     * Validate the bundle's manifest, presence of all files and secondary-tables sidecar before any
167     * mutation. Returns the decoded, allowlist-checked secondary-tables dump on success.
168     *
169     * @param string $manifestFile
170     * @param string $pagesFile
171     * @param string $sidecarFile
172     * @param callable $output Reason sink for the fallback path
173     * @return array{0:array,1:array<string,array>}|null A [ manifest, secondary-tables dump ] pair,
174     *   or null if the bundle is missing, invalid or mismatched
175     */
176    private static function validateBundle(
177        string $manifestFile,
178        string $pagesFile,
179        string $sidecarFile,
180        callable $output
181    ): ?array {
182        if ( !is_file( $manifestFile ) ) {
183            $output( "No snapshot manifest at '$manifestFile'." );
184            return null;
185        }
186
187        $manifest = FormatJson::decode( file_get_contents( $manifestFile ), true );
188        if ( !is_array( $manifest ) ) {
189            $output( "Snapshot manifest at '$manifestFile' is not valid JSON." );
190            return null;
191        }
192
193        $bundleVersion = $manifest['formatVersion'] ?? null;
194        if ( $bundleVersion !== self::FORMAT_VERSION ) {
195            $output(
196                "Snapshot bundle format version '" . var_export( $bundleVersion, true ) . "' does not match "
197                . 'the current version ' . self::FORMAT_VERSION . '.'
198            );
199            return null;
200        }
201
202        $currentSha = self::getFunctionSchemataSha();
203        if ( $currentSha === null ) {
204            $output( 'Could not resolve the current function-schemata submodule commit SHA to validate against.' );
205            return null;
206        }
207        if ( ( $manifest['functionSchemataSha'] ?? null ) !== $currentSha ) {
208            $output(
209                'Snapshot bundle was produced against a different function-schemata revision '
210                . "(bundle: '" . ( $manifest['functionSchemataSha'] ?? 'none' ) . "', current: '$currentSha')."
211            );
212            return null;
213        }
214
215        if ( !is_file( $pagesFile ) ) {
216            $output( "Snapshot pages dump not found at '$pagesFile'." );
217            return null;
218        }
219        if ( !is_file( $sidecarFile ) ) {
220            $output( "Snapshot secondary-tables sidecar not found at '$sidecarFile'." );
221            return null;
222        }
223
224        $dump = FormatJson::decode( file_get_contents( $sidecarFile ), true );
225        if ( !is_array( $dump ) ) {
226            $output( "Snapshot secondary-tables sidecar at '$sidecarFile' is not valid JSON." );
227            return null;
228        }
229        foreach ( array_keys( $dump ) as $table ) {
230            if ( !array_key_exists( $table, self::SECONDARY_TABLES ) ) {
231                $output( "Snapshot sidecar names an unexpected table '$table'; refusing to restore." );
232                return null;
233            }
234        }
235
236        return [ $manifest, $dump ];
237    }
238
239    /**
240     * Export the current revision of every NS_MAIN ZObject page to an XML dump file, using core's
241     * WikiExporter so the output can be replayed by importPages() (equivalent to importDump.php).
242     *
243     * @param string $file Destination XML file path
244     * @return int Number of NS_MAIN pages exported
245     * @throws RuntimeException On a silently-empty export
246     */
247    private static function dumpPages( string $file ): int {
248        $services = MediaWikiServices::getInstance();
249        $dbr = $services->getConnectionProvider()->getReplicaDatabase();
250        $fname = __METHOD__;
251
252        $exporter = $services->getWikiExporterFactory()->getWikiExporter(
253            $dbr,
254            WikiExporter::CURRENT,
255            WikiExporter::TEXT,
256            [ NS_MAIN ]
257        );
258
259        $sink = new DumpFileOutput( $file );
260        $exporter->setOutputSink( $sink );
261        $exporter->openStream();
262        $exporter->allPages();
263        $exporter->closeStream();
264
265        $pageCount = (int)$dbr->newSelectQueryBuilder()
266            ->select( 'COUNT(*)' )
267            ->from( 'page' )
268            ->where( [ 'page_namespace' => NS_MAIN ] )
269            ->caller( $fname )
270            ->fetchField();
271
272        // Guard against a silently-empty export: a completed openStream()/closeStream() always
273        // writes the XML wrapper, so a zero-byte file means the sink captured nothing. Restoring
274        // from such a bundle would yield a wiki with no ZObject pages, so refuse to write it.
275        clearstatcache( true, $file );
276        if ( $pageCount > 0 && !filesize( $file ) ) {
277            throw new RuntimeException(
278                "Page export wrote an empty dump to '$file' despite $pageCount NS_MAIN pages existing; aborting."
279            );
280        }
281
282        return $pageCount;
283    }
284
285    /**
286     * Dump the WikiLambda secondary tables to a portable JSON sidecar, keyed by table name.
287     * Uses the DB abstraction (not raw SQL) so the bundle is backend-agnostic.
288     *
289     * @param string $file Destination JSON file path
290     * @return array<string,int> Map of table name to row count
291     */
292    private static function dumpSecondaryTables( string $file ): array {
293        $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
294        $fname = __METHOD__;
295
296        $dump = [];
297        $rowCounts = [];
298        foreach ( self::SECONDARY_TABLES as $table => $primaryKey ) {
299            $rows = [];
300            $res = $dbr->newSelectQueryBuilder()
301                ->select( '*' )
302                ->from( $table )
303                // Deterministic order so a regenerated bundle produces a minimal, reviewable diff.
304                ->orderBy( $primaryKey )
305                ->caller( $fname )
306                ->fetchResultSet();
307            foreach ( $res as $row ) {
308                $row = (array)$row;
309                // Drop the surrogate key so restore lets the DB reassign it (see SECONDARY_TABLES).
310                unset( $row[$primaryKey] );
311                $rows[] = $row;
312            }
313            $dump[$table] = $rows;
314            $rowCounts[$table] = count( $rows );
315        }
316
317        file_put_contents( $file, FormatJson::encode( $dump, true, FormatJson::UTF8_OK ) );
318
319        return $rowCounts;
320    }
321
322    /**
323     * Write the bundle manifest describing what was dumped, so restore() can validate the bundle
324     * before trusting it.
325     *
326     * @param string $file Destination manifest file path
327     * @param int $pageCount Number of NS_MAIN pages exported
328     * @param array<string,int> $tableRowCounts Map of table name to row count
329     * @return array The manifest that was written
330     * @throws RuntimeException If the function-schemata submodule SHA cannot be resolved
331     */
332    private static function writeManifest( string $file, int $pageCount, array $tableRowCounts ): array {
333        $sha = self::getFunctionSchemataSha();
334        if ( $sha === null ) {
335            throw new RuntimeException(
336                'Could not resolve the function-schemata submodule commit SHA; refusing to write an '
337                . 'unverifiable snapshot bundle. Ensure git is available and the submodule is checked out.'
338            );
339        }
340
341        $manifest = [
342            'formatVersion' => self::FORMAT_VERSION,
343            'functionSchemataSha' => $sha,
344            'pageCount' => $pageCount,
345            'tableRowCounts' => $tableRowCounts,
346        ];
347
348        file_put_contents( $file, FormatJson::encode( $manifest, true, FormatJson::UTF8_OK ) );
349
350        return $manifest;
351    }
352
353    /**
354     * Import the built-in ZObject pages from the bundle's XML dump, with secondary/link updates
355     * disabled since we restore those tables directly from the sidecar.
356     *
357     * NOTE: this is the profiling-sensitive step. It uses core's importer (equivalent to
358     * importDump.php --no-updates); if profiling shows XML import is the bottleneck, this method
359     * can be swapped for a raw page/revision/slots/content/text table restore without changing the
360     * rest of the flow.
361     *
362     * @param string $file XML dump file path
363     * @throws RuntimeException If the dump cannot be opened or the import fails
364     */
365    private static function importPages( string $file ): void {
366        $status = ImportStreamSource::newFromFile( $file );
367        if ( !$status->isGood() ) {
368            throw new RuntimeException(
369                "Could not open snapshot pages dump '$file': " . $status->getMessage()->text()
370            );
371        }
372
373        $user = User::newSystemUser( User::MAINTENANCE_SCRIPT_USER, [ 'steal' => true ] );
374        $importer = MediaWikiServices::getInstance()
375            ->getWikiImporterFactory()
376            ->getWikiImporter( $status->getValue(), new UltimateAuthority( $user ) );
377
378        // We restore the WikiLambda secondary tables raw, so skip the link/secondary-data updates.
379        $importer->setNoUpdates( true );
380        $importer->disableStatisticsUpdate();
381
382        try {
383            $imported = $importer->doImport();
384        } catch ( \Throwable $e ) {
385            throw new RuntimeException( "Import of snapshot pages dump '$file' failed: " . $e->getMessage(), 0, $e );
386        }
387        if ( !$imported ) {
388            throw new RuntimeException( "Import of snapshot pages dump '$file' reported failure." );
389        }
390    }
391
392    /**
393     * Bulk-insert the (already allowlist-checked) secondary-table rows into their assumed-empty
394     * tables, within a single atomic section so the restore is all-or-nothing.
395     *
396     * @param IDatabase $dbw Primary database handle
397     * @param array<string,array> $dump Map of table name to rows to insert
398     * @throws RuntimeException If the insert fails
399     */
400    private static function restoreSecondaryTables( IDatabase $dbw, array $dump ): void {
401        $fname = __METHOD__;
402        try {
403            $dbw->doAtomicSection( $fname, static function ( IDatabase $dbw ) use ( $dump, $fname ) {
404                foreach ( $dump as $table => $rows ) {
405                    foreach ( array_chunk( $rows, self::INSERT_BATCH_SIZE ) as $batch ) {
406                        $dbw->newInsertQueryBuilder()
407                            ->insertInto( $table )
408                            ->rows( $batch )
409                            ->caller( $fname )
410                            ->execute();
411                    }
412                }
413            } );
414        } catch ( \Throwable $e ) {
415            throw new RuntimeException( 'Failed to restore WikiLambda secondary tables: ' . $e->getMessage(), 0, $e );
416        }
417    }
418}