Files
SHiNE-server/SHiNE-server/shine-server-db/src/main/java/shine/db/dao/BlockchainResyncCleanupDAO.java
T

301 lines
23 KiB
Java

package shine.db.dao;
import shine.db.DbController;
import java.sql.*;
/**
* Atomic cleanup of one physical fork before deterministic replay.
* Physical fork identity is (login,fork_number). Incoming logical state is never rebound/deleted.
*/
public final class BlockchainResyncCleanupDAO {
private static volatile BlockchainResyncCleanupDAO instance;
private final DbController db=DbController.getInstance();
private BlockchainResyncCleanupDAO(){}
public static BlockchainResyncCleanupDAO getInstance(){ if(instance==null) synchronized(BlockchainResyncCleanupDAO.class){if(instance==null)instance=new BlockchainResyncCleanupDAO();} return instance; }
public CleanupResult cleanupBlockchainForFullResync(String blockchainName) throws SQLException {
ChainRef ref=chainRef(blockchainName);
try(Connection c=db.getConnection()){
boolean ac=c.getAutoCommit(); c.setAutoCommit(false);
try{
// Targets liked by this actor must survive long enough to recount after actor rows are removed.
try(Statement st=c.createStatement()){
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_targets(to_login TEXT,to_block_number INTEGER,to_block_hash BYTEA,PRIMARY KEY(to_login,to_block_number,to_block_hash)) ON COMMIT DROP");
st.execute("TRUNCATE shine_cleanup_targets");
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_channels(owner_bch_name TEXT,root_number INTEGER,root_hash BYTEA,PRIMARY KEY(owner_bch_name,root_number,root_hash)) ON COMMIT DROP");
st.execute("TRUNCATE shine_cleanup_channels");
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_users(login TEXT PRIMARY KEY) ON COMMIT DROP");
st.execute("TRUNCATE shine_cleanup_users");
}
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_targets(to_login,to_block_number,to_block_hash)
SELECT DISTINCT to_login,to_block_number,to_block_hash FROM reactions_state
WHERE LOWER(from_login)=LOWER(?) AND reaction_type=1 AND last_sub_type=1
ON CONFLICT DO NOTHING
""")){ ps.setString(1,ref.login()); ps.executeUpdate(); }
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_users(login)
SELECT DISTINCT to_login FROM connections_state
WHERE LOWER(login)=LOWER(?) AND to_login IS NOT NULL AND btrim(to_login)<>''
ON CONFLICT DO NOTHING
""")){ps.setString(1,ref.login());ps.executeUpdate();}
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_channels(owner_bch_name,root_number,root_hash)
SELECT DISTINCT cn.owner_bch_name,cn.channel_root_block_number,cn.channel_root_block_hash
FROM connections_state cs JOIN channel_names_state cn
ON LOWER(cn.owner_login)=LOWER(cs.to_login) AND cn.channel_root_block_number=cs.to_block_number AND cn.channel_root_block_hash=cs.to_block_hash
WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=30
ON CONFLICT DO NOTHING
""")){ps.setString(1,ref.login());ps.executeUpdate();}
// Followers of channels owned by this login must be refreshed after those channel projections are removed.
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_users(login)
SELECT DISTINCT cs.login
FROM connections_state cs
JOIN channel_names_state cn
ON LOWER(cn.owner_login)=LOWER(?)
AND LOWER(cs.to_login)=LOWER(cn.owner_login)
AND cs.to_block_number=cn.channel_root_block_number
AND cs.to_block_hash=cn.channel_root_block_hash
WHERE cs.rel_type=30
ON CONFLICT DO NOTHING
""")){ps.setString(1,ref.login());ps.executeUpdate();}
int deletedReactions=delete(c,"DELETE FROM reactions_state WHERE LOWER(from_login)=LOWER(?)",ref.login());
recountAffectedLikes(c);
int deletedConnections=delete(c,"DELETE FROM connections_state WHERE LOWER(login)=LOWER(?)",ref.login());
refreshAffectedChannelStats(c);
int deletedUsersParams=delete(c,"DELETE FROM users_params WHERE LOWER(login)=LOWER(?)",ref.login());
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_user_profile(?)")){ps.setString(1,ref.login());ps.execute();}
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_related_user_stats(?)")){ps.setString(1,ref.login());ps.execute();}
// Channel/chat projections are owned by login; replay recreates them. Incoming social stats are intentionally untouched.
delete(c,"DELETE FROM channel_stats_state WHERE LOWER(owner_login)=LOWER(?)",ref.login());
int deletedChannelNames=delete(c,"DELETE FROM channel_names_state WHERE LOWER(owner_login)=LOWER(?)",ref.login());
refreshAffectedUserStats(c);
int deletedChat200=delete(c,"DELETE FROM chat200_state WHERE LOWER(owner_login)=LOWER(?)",ref.login());
int deletedChatMembers=delete(c,"DELETE FROM chat200_members_state WHERE owner_bch_name LIKE ?",ref.login()+"-%");
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_user_stats(?)")){ps.setString(1,ref.login());ps.execute();}
int deletedBlocks;
try(PreparedStatement ps=c.prepareStatement("DELETE FROM blocks_store WHERE LOWER(login)=LOWER(?) AND fork_number=?")){
ps.setString(1,ref.login()); ps.setInt(2,ref.fork()); deletedBlocks=ps.executeUpdate();
}
int deletedState;
try(PreparedStatement ps=c.prepareStatement("DELETE FROM blockchain_state_store WHERE LOWER(login)=LOWER(?) AND fork_number=?")){
ps.setString(1,ref.login()); ps.setInt(2,ref.fork()); deletedState=ps.executeUpdate();
}
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_header_identity(?)")){ps.setString(1,ref.login());ps.execute();}
c.commit();
return new CleanupResult(ref.login(),deletedReactions,deletedConnections,deletedUsersParams,deletedChannelNames,deletedChat200,deletedChatMembers,deletedBlocks,deletedState);
}catch(Exception e){ try{c.rollback();}catch(Exception ignored){} if(e instanceof SQLException x)throw x; throw new SQLException("Stage2 fork cleanup failed: "+blockchainName,e); }
finally{try{c.setAutoCommit(ac);}catch(Exception ignored){}}
}
}
/** Clears all materialized state and raw local forks for one login before canonical replay.
* Raw canonical bytes must already be persisted in rebuild staging.
*
* This operation is deliberately idempotent. Before deleting the actor's projections we
* remember every foreign user/channel/message aggregate touched by them, then repair those
* aggregates after the rows/blocks have been removed. Canonical replay can therefore start
* from a clean baseline without double-counting replies, likes or subscriptions.
*/
public void cleanupLoginForCanonicalReplay(String login) throws SQLException {
if(login==null||login.isBlank())throw new IllegalArgumentException("login is blank");
try(Connection c=db.getConnection()){boolean ac=c.getAutoCommit();c.setAutoCommit(false);try{
try(Statement st=c.createStatement()){
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_targets(to_login TEXT,to_block_number INTEGER,to_block_hash BYTEA,PRIMARY KEY(to_login,to_block_number,to_block_hash)) ON COMMIT DROP");
st.execute("TRUNCATE shine_cleanup_targets");
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_reply_targets(to_login TEXT,to_block_number INTEGER,to_block_hash BYTEA,PRIMARY KEY(to_login,to_block_number,to_block_hash)) ON COMMIT DROP");
st.execute("TRUNCATE shine_cleanup_reply_targets");
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_channels(owner_bch_name TEXT,root_number INTEGER,root_hash BYTEA,PRIMARY KEY(owner_bch_name,root_number,root_hash)) ON COMMIT DROP");
st.execute("TRUNCATE shine_cleanup_channels");
st.execute("CREATE TEMP TABLE IF NOT EXISTS shine_cleanup_users(login TEXT PRIMARY KEY) ON COMMIT DROP");
st.execute("TRUNCATE shine_cleanup_users");
}
// Existing LIKE state produced by this actor.
try(PreparedStatement ps=c.prepareStatement("INSERT INTO shine_cleanup_targets SELECT DISTINCT to_login,to_block_number,to_block_hash FROM reactions_state WHERE LOWER(from_login)=LOWER(?) AND reaction_type=1 AND last_sub_type=1 ON CONFLICT DO NOTHING")){ps.setString(1,login);ps.executeUpdate();}
// Existing REPLY blocks produced by this actor. Their counters must be recomputed
// after deleting the old canonical blocks and before replay inserts the new canonical set.
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_reply_targets(to_login,to_block_number,to_block_hash)
SELECT DISTINCT to_login,to_block_number,to_block_hash
FROM blocks_store
WHERE LOWER(login)=LOWER(?) AND msg_type=1 AND msg_sub_type=20
AND to_login IS NOT NULL AND to_block_number IS NOT NULL AND to_block_hash IS NOT NULL
ON CONFLICT DO NOTHING
""")){ps.setString(1,login);ps.executeUpdate();}
// Users whose social counters may change when this actor's connection projection disappears.
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_users(login)
SELECT DISTINCT to_login FROM connections_state
WHERE LOWER(login)=LOWER(?) AND to_login IS NOT NULL AND btrim(to_login)<>''
ON CONFLICT DO NOTHING
""")){ps.setString(1,login);ps.executeUpdate();}
try(PreparedStatement ps=c.prepareStatement("INSERT INTO shine_cleanup_users(login) VALUES(?) ON CONFLICT DO NOTHING")){ps.setString(1,login);ps.executeUpdate();}
// Foreign channels followed/unfollowed by this actor.
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_channels(owner_bch_name,root_number,root_hash)
SELECT DISTINCT cn.owner_bch_name,cn.channel_root_block_number,cn.channel_root_block_hash
FROM connections_state cs JOIN channel_names_state cn
ON LOWER(cn.owner_login)=LOWER(cs.to_login)
AND cn.channel_root_block_number=cs.to_block_number
AND cn.channel_root_block_hash=cs.to_block_hash
WHERE LOWER(cs.login)=LOWER(?) AND cs.rel_type=30
ON CONFLICT DO NOTHING
""")){ps.setString(1,login);ps.executeUpdate();}
// Followers of channels owned by this login are also affected while channel projections
// disappear and are recreated by replay.
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO shine_cleanup_users(login)
SELECT DISTINCT cs.login
FROM connections_state cs
JOIN channel_names_state cn
ON LOWER(cn.owner_login)=LOWER(?)
AND LOWER(cs.to_login)=LOWER(cn.owner_login)
AND cs.to_block_number=cn.channel_root_block_number
AND cs.to_block_hash=cn.channel_root_block_hash
WHERE cs.rel_type=30
ON CONFLICT DO NOTHING
""")){ps.setString(1,login);ps.executeUpdate();}
delete(c,"DELETE FROM reactions_state WHERE LOWER(from_login)=LOWER(?)",login);
recountAffectedLikes(c);
delete(c,"DELETE FROM connections_state WHERE LOWER(login)=LOWER(?)",login);
refreshAffectedChannelStats(c);
delete(c,"DELETE FROM users_params WHERE LOWER(login)=LOWER(?)",login);
delete(c,"DELETE FROM channel_stats_state WHERE LOWER(owner_login)=LOWER(?)",login);
delete(c,"DELETE FROM channel_names_state WHERE LOWER(owner_login)=LOWER(?)",login);
// Notifications are projections of source blockchain blocks. Canonical replay recreates
// only the notifications that still exist on the selected branch.
delete(c,"DELETE FROM user_notifications_state WHERE LOWER(source_login)=LOWER(?)",login);
// Chat200 is legacy/unused and is intentionally not maintained by segmented-fork replay.
delete(c,"DELETE FROM chat200_state WHERE LOWER(owner_login)=LOWER(?)",login);
delete(c,"DELETE FROM chat200_members_state WHERE owner_bch_name LIKE ?",login+"-%");
delete(c,"DELETE FROM blocks_store WHERE LOWER(login)=LOWER(?)",login);
delete(c,"DELETE FROM blockchain_state_store WHERE LOWER(login)=LOWER(?)",login);
// With the old reply blocks gone, establish the exact baseline produced by all other
// actors. Replay will then add this actor's canonical replies exactly once.
recountAffectedReplies(c);
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_user_profile(?)")){ps.setString(1,login);ps.execute();}
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_related_user_stats(?)")){ps.setString(1,login);ps.execute();}
refreshAffectedUserStats(c);
c.commit();
}catch(Exception e){c.rollback();if(e instanceof SQLException x)throw x;throw new SQLException("canonical replay cleanup failed",e);}finally{c.setAutoCommit(ac);}}
}
/**
* Repairs server-owned projections after canonical replay. It is safe to call repeatedly.
* Signed channel read watermarks are preserved; only server-owned unread values are recomputed.
*/
public void finalizeCanonicalReplay(String login) throws SQLException {
if(login==null||login.isBlank())throw new IllegalArgumentException("login is blank");
try(Connection c=db.getConnection()){boolean ac=c.getAutoCommit();c.setAutoCommit(false);try{
// Remove view references to discarded messages of this user. Valid canonical targets survive.
try(PreparedStatement ps=c.prepareStatement("""
DELETE FROM message_views_state mv
WHERE LOWER(mv.to_login)=LOWER(?)
AND NOT EXISTS (
SELECT 1 FROM blocks_store b
WHERE LOWER(b.login)=LOWER(mv.to_login)
AND b.block_number=mv.to_block_number AND b.block_hash=mv.to_block_hash
)
""")){ps.setString(1,login);ps.executeUpdate();}
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_header_identity(?)")){ps.setString(1,login);ps.execute();}
// Recompute all message aggregates whose target belongs to this user. This also fixes
// external reactions/replies that intentionally survive this user's rebuild.
try(PreparedStatement ps=c.prepareStatement("""
INSERT INTO message_stats(to_login,to_block_number,to_block_hash,likes_count,primary_likes_count,shining_likes_count,replies_count)
SELECT t.login,t.block_number,t.block_hash,
(SELECT COUNT(*)::INTEGER FROM reactions_state r WHERE r.reaction_type=1 AND r.last_sub_type=1 AND LOWER(r.to_login)=LOWER(t.login) AND r.to_block_number=t.block_number AND r.to_block_hash=t.block_hash),
(SELECT COUNT(*)::INTEGER FROM reactions_state r WHERE r.reaction_type=1 AND r.last_sub_type=1 AND LOWER(r.to_login)=LOWER(t.login) AND r.to_block_number=t.block_number AND r.to_block_hash=t.block_hash AND shine_is_primary(r.from_login)),
(SELECT COUNT(*)::INTEGER FROM reactions_state r WHERE r.reaction_type=1 AND r.last_sub_type=1 AND LOWER(r.to_login)=LOWER(t.login) AND r.to_block_number=t.block_number AND r.to_block_hash=t.block_hash AND shine_is_primary(r.from_login) AND shine_is_shining(r.from_login)),
(SELECT COUNT(*)::INTEGER FROM blocks_store rb WHERE rb.msg_type=1 AND rb.msg_sub_type=20 AND LOWER(rb.to_login)=LOWER(t.login) AND rb.to_block_number=t.block_number AND rb.to_block_hash=t.block_hash)
FROM blocks_store t
WHERE LOWER(t.login)=LOWER(?)
AND (
EXISTS(SELECT 1 FROM message_stats oldms WHERE LOWER(oldms.to_login)=LOWER(t.login) AND oldms.to_block_number=t.block_number AND oldms.to_block_hash=t.block_hash)
OR EXISTS(SELECT 1 FROM reactions_state r WHERE LOWER(r.to_login)=LOWER(t.login) AND r.to_block_number=t.block_number AND r.to_block_hash=t.block_hash)
OR EXISTS(SELECT 1 FROM blocks_store rb WHERE rb.msg_type=1 AND rb.msg_sub_type=20 AND LOWER(rb.to_login)=LOWER(t.login) AND rb.to_block_number=t.block_number AND rb.to_block_hash=t.block_hash)
)
ON CONFLICT(to_login,to_block_number,to_block_hash) DO UPDATE SET
likes_count=EXCLUDED.likes_count,
primary_likes_count=EXCLUDED.primary_likes_count,
shining_likes_count=EXCLUDED.shining_likes_count,
replies_count=EXCLUDED.replies_count
""")){ps.setString(1,login);ps.executeUpdate();}
try(PreparedStatement ps=c.prepareStatement("""
DELETE FROM message_stats ms
WHERE LOWER(ms.to_login)=LOWER(?)
AND NOT EXISTS (SELECT 1 FROM blocks_store b WHERE LOWER(b.login)=LOWER(ms.to_login) AND b.block_number=ms.to_block_number AND b.block_hash=ms.to_block_hash)
""")){ps.setString(1,login);ps.executeUpdate();}
// Recalculate social/channel aggregates from the final canonical projections.
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_user_stats(?)")){ps.setString(1,login);ps.execute();}
try(PreparedStatement ps=c.prepareStatement("SELECT shine_refresh_related_user_stats(?)")){ps.setString(1,login);ps.execute();}
try(PreparedStatement ps=c.prepareStatement("""
SELECT shine_refresh_channel_follow_stats(owner_bch_name,channel_root_block_number,channel_root_block_hash)
FROM channel_names_state WHERE LOWER(owner_login)=LOWER(?) AND channel_type_code=1
""")){ps.setString(1,login);ps.execute();}
ChannelReadStateDAO.getInstance().recalculateUnreadForOwnedChannels(c,login,System.currentTimeMillis());
c.commit();
}catch(Exception e){c.rollback();if(e instanceof SQLException x)throw x;throw new SQLException("canonical replay finalize failed",e);}finally{c.setAutoCommit(ac);}}
}
private void recountAffectedLikes(Connection c)throws SQLException{
try(PreparedStatement ps=c.prepareStatement("""
UPDATE message_stats ms SET
likes_count=(SELECT COUNT(*)::INTEGER FROM reactions_state rs WHERE rs.reaction_type=1 AND rs.last_sub_type=1 AND rs.to_login=ms.to_login AND rs.to_block_number=ms.to_block_number AND rs.to_block_hash=ms.to_block_hash),
primary_likes_count=(SELECT COUNT(*)::INTEGER FROM reactions_state rs WHERE rs.reaction_type=1 AND rs.last_sub_type=1 AND rs.to_login=ms.to_login AND rs.to_block_number=ms.to_block_number AND rs.to_block_hash=ms.to_block_hash AND shine_is_primary(rs.from_login)),
shining_likes_count=(SELECT COUNT(*)::INTEGER FROM reactions_state rs WHERE rs.reaction_type=1 AND rs.last_sub_type=1 AND rs.to_login=ms.to_login AND rs.to_block_number=ms.to_block_number AND rs.to_block_hash=ms.to_block_hash AND shine_is_primary(rs.from_login) AND shine_is_shining(rs.from_login))
WHERE EXISTS(SELECT 1 FROM shine_cleanup_targets t WHERE t.to_login=ms.to_login AND t.to_block_number=ms.to_block_number AND t.to_block_hash=ms.to_block_hash)
""")){ps.executeUpdate();}
}
private void recountAffectedReplies(Connection c)throws SQLException{
try(PreparedStatement ps=c.prepareStatement("""
UPDATE message_stats ms SET replies_count=(
SELECT COUNT(*)::INTEGER FROM blocks_store b
WHERE b.msg_type=1 AND b.msg_sub_type=20
AND LOWER(b.to_login)=LOWER(ms.to_login)
AND b.to_block_number=ms.to_block_number AND b.to_block_hash=ms.to_block_hash
)
WHERE EXISTS(SELECT 1 FROM shine_cleanup_reply_targets t
WHERE LOWER(t.to_login)=LOWER(ms.to_login) AND t.to_block_number=ms.to_block_number AND t.to_block_hash=ms.to_block_hash)
""")){ps.executeUpdate();}
}
private void refreshAffectedChannelStats(Connection c)throws SQLException{
try(PreparedStatement q=c.prepareStatement("SELECT owner_bch_name,root_number,root_hash FROM shine_cleanup_channels"); ResultSet rs=q.executeQuery(); PreparedStatement p=c.prepareStatement("SELECT shine_refresh_channel_follow_stats(?,?,?)")){
while(rs.next()){p.setString(1,rs.getString(1));p.setInt(2,rs.getInt(2));p.setBytes(3,rs.getBytes(3));p.execute();}
}
}
private void refreshAffectedUserStats(Connection c)throws SQLException{
try(PreparedStatement q=c.prepareStatement("SELECT login FROM shine_cleanup_users"); ResultSet rs=q.executeQuery(); PreparedStatement p=c.prepareStatement("SELECT shine_refresh_user_stats(?)")){
while(rs.next()){p.setString(1,rs.getString(1));p.execute();}
}
}
private int delete(Connection c,String sql,String v)throws SQLException{try(PreparedStatement ps=c.prepareStatement(sql)){ps.setString(1,v);return ps.executeUpdate();}}
private record ChainRef(String login,int fork){}
private static ChainRef chainRef(String n){ if(n==null)throw new IllegalArgumentException("blockchainName is null"); String s=n.trim();int d=s.lastIndexOf('-');if(d<=0||s.length()-d-1!=3)throw new IllegalArgumentException("Bad blockchainName: "+n);try{int f=Integer.parseInt(s.substring(d+1));if(f<1||f>999)throw new IllegalArgumentException("fork out of range");return new ChainRef(s.substring(0,d),f);}catch(NumberFormatException e){throw new IllegalArgumentException("Bad blockchainName: "+n,e);} }
public record CleanupResult(String login,int deletedReactionsStateRows,int deletedConnectionsStateRows,int deletedUsersParamsRows,int deletedChannelNamesRows,int deletedChat200StateRows,int deletedChat200MembersRows,int deletedBlocksRows,int deletedBlockchainStateRows){}
}