cmvr-wms/scripts/projectdev/ScopedReplayCleanup.java

80 lines
12 KiB
Java
Raw Normal View History

import com.fasterxml.jackson.databind.*;
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
import java.sql.*;
import java.util.*;
/** Target-only cleanup. No source connection, restore, import, FK disabling, or DDL.
* Default is read-only plan. Execute requires a validated fresh target backup and
* exact fingerprints before deletion; any failure rolls back the whole cleanup. */
public class ScopedReplayCleanup {
private static final String TARGET="cmvr-project-dev";
private static final Set<String> FULL=Set.of(
"ai_command","bom_change_log","bom_line","bom_version",
"business_number_reservation","business_number_sequence","business_withdrawal",
"expense_category","in_record","initialization_record","inventory_cost_change",
"inventory_cost_event","inventory_cost_link","inventory_cost_revision","inventory_cutover",
"out_record","out_record_lot","product_info","production_action","production_product",
"production_settlement","production_task","project_budget","project_fund_ledger",
"project_item_cost","project_loan","project_loan_return","project_product","project_stock_balance",
"purchase_arrival","purchase_batch","purchase_operation_log","purchase_price_ledger",
"purchase_request","purchase_return","purchase_sheet_submission",
"real_data_replay_mapping","real_data_replay_run","real_data_replay_source","real_data_replay_stage",
"stock_check_record","stock_info","stock_lot","supplier_info","warehouse_area",
"warehouse_import_receipt","wms_batch_item","wms_batch_job","history_entry_receipt");
private static final ObjectMapper JSON=new ObjectMapper();
public static void main(String[] args)throws Exception{
if(args.length!=2||!Set.of("plan","execute").contains(args[0]))throw new IllegalArgumentException("plan|execute <validated target backup directory>");
boolean execute=args[0].equals("execute");Path directory=Path.of(args[1]).toRealPath();
if(!directory.startsWith(Path.of(".codex-tmp/database-backups").toRealPath()))throw new IllegalArgumentException("Backup outside target directory");
var manifest=JSON.readTree(directory.resolve("manifest.json").toFile());
if(!TARGET.equals(manifest.path("database").asText())||!manifest.path("complete").asBoolean()||!manifest.path("readOnly").asBoolean())throw new IllegalArgumentException("Unverified backup");
byte[] dump=Files.readAllBytes(directory.resolve(TARGET+".sql"));
if(!BackupReplayTarget.hash(dump).equals(manifest.path("sha256").asText())||!new String(dump,StandardCharsets.UTF_8).endsWith("-- BACKUP COMPLETE\n"))throw new IllegalArgumentException("Backup integrity check failed");
var preflight=JSON.readTree(directory.resolve("preservation-preflight.json").toFile());
if(!manifest.path("sha256").asText().equals(preflight.path("backupSha256").asText())||!preflight.path("unresolvedBeforeDeletion").isEmpty())throw new IllegalArgumentException("Preservation preflight invalid");
List<Long> projects=new ArrayList<>();for(var node:preflight.path("protectedProjectIds"))projects.add(node.asLong());
if(projects.isEmpty())throw new IllegalArgumentException("No confirmed protected projects");
Map<String,String> config=new HashMap<>();boolean master=false;
for(String line:Files.readAllLines(Path.of("ruoyi-admin/src/main/resources/application-druid.yml"))){if(line.trim().equals("master:")){master=true;continue;}if(line.trim().equals("slave:"))break;if(master&&line.indexOf(':')>0){int colon=line.indexOf(':');config.put(line.substring(0,colon).trim(),DatabaseTool.value(line.substring(colon+1).trim()));}}
String url=config.get("url");if(url==null||!url.matches("^jdbc:mysql://192\\.168\\.28\\.10:3306/cmvr-project-dev(?:\\?.*)?$"))throw new IllegalStateException("Refusing another database");
Properties props=new Properties();props.setProperty("user",config.get("username"));props.setProperty("password",config.get("password"));props.setProperty("tinyInt1isBit","false");props.setProperty("connectTimeout","5000");props.setProperty("socketTimeout","60000");
try(Connection db=DriverManager.getConnection(url,props)){
db.setReadOnly(!execute);db.setAutoCommit(false);
try{
if(!TARGET.equals(scalar(db,"select database()"))||!"1".equals(scalar(db,"select @@foreign_key_checks")))throw new IllegalStateException("Target/FK guard failed");
Set<String> existing=new TreeSet<>();try(var s=db.prepareStatement("select table_name from information_schema.tables where table_schema=? and table_type='BASE TABLE'")){s.setString(1,TARGET);try(var rs=s.executeQuery()){while(rs.next())existing.add(rs.getString(1));}}
Map<String,String> predicates=new LinkedHashMap<>();for(String table:new TreeSet<>(FULL))if(existing.contains(table))predicates.put(table,"1=1");
predicates.put("project_info","id not in ("+String.join(",",projects.stream().map(Object::toString).toList())+")");
// Only our dictionary values; never clear framework state/status dictionaries.
predicates.put("sys_dict_data","dict_type in ('wms_item_category','wms_item_category_group','wms_item_unit')");
// Preserve independently-owned collaboration audit trails and all shared login/notice history.
predicates.put("sys_oper_log","not (coalesce(oper_url,'') like '/project/manage%' or coalesce(oper_url,'') like '/project/collaboration%' or coalesce(method,'') like '%collab%' or coalesce(method,'') like '%Collab%' or coalesce(title,'') like '%协作%')");
List<String[]> foreignKeys=new ArrayList<>();try(var s=db.prepareStatement("select table_name,column_name,referenced_table_name,referenced_column_name from information_schema.key_column_usage where table_schema=? and referenced_table_name is not null")){s.setString(1,TARGET);try(var rs=s.executeQuery()){while(rs.next())foreignKeys.add(new String[]{rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4)});}}
for(var fk:foreignKeys)if(FULL.contains(fk[2])&&!predicates.containsKey(fk[0]))throw new IllegalStateException("Protected/unknown table references cleanup table: "+fk[0]+" -> "+fk[2]);
Map<String,String> before=new TreeMap<>();List<String> changed=new ArrayList<>();
// Lock and compare every preserved collaboration table plus every modified table.
Set<String> check=new TreeSet<>(predicates.keySet());for(String name:existing)if(name.startsWith("pm_")||name.equals("project_member"))check.add(name);
for(String table:check){var definition=manifest.path("tables").path(table);if(definition.isMissingNode())throw new IllegalStateException("Backup missing table "+table);String fingerprint=fingerprint(db,table,definition,execute);before.put(table,fingerprint);if(!fingerprint.equals(definition.path("rowFingerprint").asText()))changed.add(table);}
var report=new LinkedHashMap<String,Object>();report.put("target",TARGET);report.put("backupSha256",manifest.path("sha256").asText());report.put("protectedProjects",projects);report.put("sourceWrites",0);report.put("changedSinceBackup",changed);report.put("preservedSharedTables",List.of("pm_*","project_member","sys_user*","sys_role*","sys_menu","sys_logininfor","sys_notice*","sys_config","sys_dept","sys_post","sys_job*","QRTZ_*"));
Map<String,Long> counts=new LinkedHashMap<>();for(var p:predicates.entrySet())counts.put(p.getKey(),Long.parseLong(scalar(db,"select count(*) from "+BackupReplayTarget.id(p.getKey())+" where "+p.getValue())));report.put("rowsToClear",counts);
if(!execute){db.rollback();report.put("databaseWrites",0);Files.writeString(directory.resolve("cleanup-plan.json"),JSON.writerWithDefaultPrettyPrinter().writeValueAsString(report));System.out.println("PLAN ONLY tables="+counts.size()+" rows="+counts.values().stream().mapToLong(Long::longValue).sum()+" changedSinceBackup="+changed);return;}
if(!changed.isEmpty())throw new IllegalStateException("Database changed since backup; take a fresh backup: "+changed);
List<String> order=new ArrayList<>();Set<String> remaining=new LinkedHashSet<>(predicates.keySet());while(!remaining.isEmpty()){String next=remaining.stream().filter(parent -> foreignKeys.stream().noneMatch(fk -> !fk[0].equals(parent)&&fk[2].equals(parent)&&remaining.contains(fk[0]))).findFirst().orElseThrow(()->new IllegalStateException("Cross-table FK cycle; nothing deleted"));order.add(next);remaining.remove(next);}
Map<String,Long> deleted=new LinkedHashMap<>();for(String table:order){List<String[]> self=foreignKeys.stream().filter(fk -> fk[0].equals(table)&&fk[2].equals(table)).toList();long number=0;if(self.isEmpty()){try(var s=db.createStatement()){number=s.executeUpdate("delete from "+BackupReplayTarget.id(table)+" where "+predicates.get(table));}}else{if(!"1=1".equals(predicates.get(table)))throw new IllegalStateException("Partial self-reference cleanup requires manual review");number=deleteSelfReferenced(db,table,self);}if(number!=counts.get(table))throw new IllegalStateException("Unexpected deletion count: "+table);deleted.put(table,number);}
for(var entry:before.entrySet())if(!predicates.containsKey(entry.getKey())&&!entry.getValue().equals(fingerprint(db,entry.getKey(),manifest.path("tables").path(entry.getKey()),false)))throw new IllegalStateException("Protected table changed: "+entry.getKey());
db.commit();report.put("deletedRows",deleted);report.put("collaborationUnchanged",true);report.put("databaseWrites",deleted.values().stream().mapToLong(Long::longValue).sum());Files.writeString(directory.resolve("cleanup-result.json"),JSON.writerWithDefaultPrettyPrinter().writeValueAsString(report));System.out.println("CLEANUP COMMITTED target="+TARGET+" rows="+report.get("databaseWrites")+" collaborationUnchanged=true sourceWrites=0");
}catch(Exception error){db.rollback();throw error;}
}
}
private static long deleteSelfReferenced(Connection db,String table,List<String[]> refs)throws Exception{
// Remove leaves first without changing FK columns or turning off constraints.
Map<Long,Set<Long>> children=new LinkedHashMap<>();try(var s=db.createStatement();var rs=s.executeQuery("select * from "+BackupReplayTarget.id(table)+" for update")){while(rs.next()){long id=rs.getLong("id");children.computeIfAbsent(id,x->new HashSet<>());for(var ref:refs){Object parent=rs.getObject(ref[1]);if(parent!=null){long p=((Number)parent).longValue();if(p==id)throw new IllegalStateException("Self-cycle: "+table);children.computeIfAbsent(p,x->new HashSet<>()).add(id);}}}}
long count=0;try(var s=db.prepareStatement("delete from "+BackupReplayTarget.id(table)+" where id=?")){while(!children.isEmpty()){List<Long> leaves=children.entrySet().stream().filter(e->e.getValue().isEmpty()).map(Map.Entry::getKey).toList();if(leaves.isEmpty())throw new IllegalStateException("Self-FK cycle: "+table);for(long id:leaves){s.setLong(1,id);count+=s.executeUpdate();children.remove(id);}for(var set:children.values())set.removeAll(leaves);}}return count;
}
private static String fingerprint(Connection db,String table,JsonNode definition,boolean lock)throws Exception{
List<String> columns=new ArrayList<>();for(var node:definition.path("columns"))columns.add(node.asText());if(columns.isEmpty())throw new IllegalArgumentException("Missing backup columns");String list=String.join(",",columns.stream().map(BackupReplayTarget::id).toList());List<String> hashes=new ArrayList<>();try(var s=db.createStatement();var rs=s.executeQuery("select "+list+" from "+BackupReplayTarget.id(table)+(lock?" for update":""))){var meta=rs.getMetaData();while(rs.next()){StringJoiner values=new StringJoiner(",");for(int i=1;i<=meta.getColumnCount();i++)values.add(BackupReplayTarget.literal(rs,meta,i));String insert="INSERT INTO "+BackupReplayTarget.id(table)+" ("+list+") VALUES ("+values+");\n";hashes.add(BackupReplayTarget.hash(insert.getBytes(StandardCharsets.UTF_8)));}}Collections.sort(hashes);return BackupReplayTarget.hash(String.join("\n",hashes).getBytes(StandardCharsets.UTF_8));
}
private static String scalar(Connection db,String sql)throws Exception{try(var s=db.createStatement();var rs=s.executeQuery(sql)){if(!rs.next())throw new IllegalStateException("Missing scalar result");return rs.getString(1);}}
}