Merge pull request 'Update managed forum announcements when website news changes (372)' (#35) from dev/MC:dev/ticket-372-news-revisions into checkpoint/alpha-1.0.0.3

Reviewed-on: unimatrix/MC#35
This commit is contained in:
Unimatrix 2026-11-06 08:54:06 +01:00
commit 524d5dbb64
8 changed files with 235 additions and 26 deletions

View file

@ -0,0 +1,21 @@
# Forum news revisions — native task372
The existing source-ID delivery queue now detects published title, body, category and public-author changes and updates the same managed announcement topic. A successful response must confirm the exact content revision and topic ID before delivery is recorded. Publication changes during a send are picked up on the next tick. Unknown outcomes remain uncertain for reconciliation, rather than blindly creating duplicates.
Withdrawals (archive, draft, deleted, future publication or missing source) send only source ID and archive status. The existing first post becomes an explicit archived notice, and its subject is marked [Archived]. No unpublished fields travel to MyBB. Republishing restores the same topic and first-post identity. No reply is deleted, moved or rewritten. The original first-post date and author remain unchanged. Only previously managed topics can be archived; an unpublished new article never creates a forum topic.
The private CLI adapter uses MyBB PostDataHandler validation and update_post/insert_thread. It checks current forum14 public visibility and author permissions, exact DuneRealms uid2 ownership, first-post identity, visibility and immutable source marker. Moved, hidden or reassigned topics require review. A native advisory lock and persisted source mapping guard creation; per-source revision tracking makes successful edits/replays idempotent. Native MyISAM post/thread writes are not claimed to be a cross-service transaction. The website records confirmed revision/state atomically in its own database.
The website category label is reconciled to NEWS, matching the visible forum and Discord label. Other established labels, artwork and destination permissions are retained. The Discord worker remains independent; historical messages are not replayed, and editing a website article does not create another Discord announcement. X remains manual, as requested.
## Validation at this staged checkpoint
21 focused Node checks pass across forum revisions, Discord failure/deduplication, public pagination/author links, safe article formatting and manual X draft generation. Actual MySQL syntax/claim/revision transitions were exercised with connection-local temporary tables: publish, edit, withdraw, republish and no repeat delivery passed.
The actual installed MyBB PostDataHandler was exercised with every native table shadowed by a connection-local temporary table before cache/session initialization. Only bootstrap paths and CREATE TABLE statements were redirected for isolation; native adapter and PostDataHandler logic were unchanged. Create/edit/archive/replay/republish retained the same topic, first-post ID and original date. A sentinel reply remained byte-for-byte unchanged. Wrong topic author, forum, visibility and first-post identity all rejected changes. The synthetic source ID had zero permanent delivery mappings after the test. Existing production forum remained12threads/21posts and9managed news mappings.
Reproduce native checks by uploading tests/native-forum-news-shadow.php as /tmp/forum372-shadow.php, tests/native-forum-news-qa.py as /tmp/forum372-native-qa.py and the candidate integrations/forum-news.php as /tmp/forum-news372-candidate.php on the existing integration host, then run the Python script. It refuses an existing /tmp/forum372-native-qa/state.json; preserve/rename previous fixture evidence first. The configured MyBB database cache is required. All synthetic rows exist only in temporary tables; the saved fixture JSON contains only synthetic posts/threads/mapping/revision data. No production account/session/topic is created by the harness.
For the actual MySQL worker test, upload node/forum-news.mjs as /tmp/forum-news372-candidate.mjs and tests/native-forum-news-mysql.mjs to /tmp, then execute with the deployed Node22 runtime. It uses the existing private connection file without printing credentials, shadows queue/source tables, and injects a send stub so no public announcement is made.
This checkpoint is staged only. Merge/deployment, backup paths, live existing-topic reconciliation and a genuine fresh Discord delivery must be recorded in native task372 before closure. Do not fabricate a live test news article or enable paid/automatic X posting.

View file

@ -1,24 +1,62 @@
<?php
// Private CLI adapter. Existing native forum permissions and PostDataHandler remain authoritative.
// Private CLI adapter: native forum validation and exact source ownership remain authoritative.
if(PHP_SAPI!=='cli')exit(1);
$input=json_decode(stream_get_contents(STDIN),true);if(!is_array($input)||!preg_match('/^[0-9a-f-]{36}$/i',$input['id']??'')||!is_numeric($input['published_at']??null)||(int)$input['published_at']>(int)(microtime(true)*1000)||!is_string($input['title']??null)||!is_string($input['body']??null))exit(2);
$input=json_decode(stream_get_contents(STDIN),true);
if(!is_array($input)||!preg_match('/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i',$input['id']??''))exit(2);
$status=$input['status']??'published';$modern=isset($input['revision']);
if(!in_array($status,['published','archived'],true)||($modern&&!preg_match('/^[0-9a-f]{64}$/',$input['revision'])))exit(2);
if($status==='published'&&(!is_numeric($input['published_at']??null)||(int)$input['published_at']>(int)(microtime(true)*1000)||!is_string($input['title']??null)||!is_string($input['body']??null)))exit(2);
$_SERVER['SCRIPT_NAME']='/dune-sso.php';$_SERVER['REQUEST_METHOD']='GET';$_SERVER['REMOTE_ADDR']='127.0.0.1';$_SERVER['HTTP_HOST']='forums.dunerealms.com';define('IN_MYBB',1);chdir('/home/dunerealms/apps/integrations/mybb');ob_start();require 'global.php';ob_end_clean();
$fid=14;$uid=2;$author=get_user($uid);if(strtolower($author['username']??'')!=='dunerealms')exit(3);$mybb->user=$author;$permissions=forum_permissions($fid,$uid);if(empty($permissions['canpostthreads'])||empty($permissions['canview']))exit(3);
$current=$fid;$seen=[];while($current){if(isset($seen[$current]))exit(3);$seen[$current]=true;$forum=get_forum($current);$guest=forum_permissions($current,0,1);if(empty($forum['active'])||!empty($forum['password'])||empty($guest['canview'])||empty($guest['canviewthreads'])||!empty($guest['canonlyviewownthreads']))exit(3);$current=(int)$forum['pid'];}
$id=$db->escape_string($input['id']);$lock='dune-news-'.$id;$locked=$db->fetch_field($db->query("SELECT GET_LOCK('{$lock}',5) AS acquired"),'acquired');if(!$locked)exit(4);
try{
$db->write_query('CREATE TABLE IF NOT EXISTS '.TABLE_PREFIX.'dune_news_delivery(post_id CHAR(36) PRIMARY KEY,state VARCHAR(16) NOT NULL,tid INT NOT NULL DEFAULT 0,pid INT NOT NULL DEFAULT 0) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
$db->write_query('CREATE TABLE IF NOT EXISTS '.TABLE_PREFIX.'dune_news_revision(post_id CHAR(36) PRIMARY KEY,revision VARCHAR(64) NOT NULL,state VARCHAR(16) NOT NULL,updated_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
$mapping=$db->fetch_array($db->simple_select('dune_news_delivery','*',"post_id='{$id}'"));
if($mapping&&$mapping['state']==='sent'){$thread=get_thread((int)$mapping['tid']);if(!$thread||(int)$thread['fid']!==14||(int)$thread['visible']!==1)throw new Exception('Existing topic unavailable');echo json_encode(['state'=>'sent','thread_id'=>(int)$mapping['tid']]);exit;}
// Reconcile a timeout/crash by the immutable source marker; never blindly create twice.
$marker='DuneRealms source: '.$input['id'];$query=$db->query('SELECT t.tid,p.pid FROM '.TABLE_PREFIX.'threads t JOIN '.TABLE_PREFIX.'posts p ON p.pid=t.firstpost WHERE t.fid=14 AND t.uid=2 AND p.message LIKE \'%'.$db->escape_string($marker).'%\' LIMIT 2');$matches=[];while($row=$db->fetch_array($query))$matches[]=$row;
if(count($matches)===1){$db->replace_query('dune_news_delivery',['post_id'=>$input['id'],'state'=>'sent','tid'=>(int)$matches[0]['tid'],'pid'=>(int)$matches[0]['pid']],'post_id');echo json_encode(['state'=>'sent','thread_id'=>(int)$matches[0]['tid']]);exit;}
if($mapping||count($matches)>1)throw new Exception('Interrupted native creation requires review');
$labels=['world'=>'World','news'=>'NEWS','maintenance'=>'Maintenance','changelogs'=>'Changelogs','events'=>'Events','community'=>'Community','unis_blog'=>"Uni’s Blog"];$label=$labels[$input['category']]??'NEWS';$prefix=$db->fetch_array($db->simple_select('threadprefixes','pid',"prefix='".$db->escape_string($label)."' AND forums='14'"));
if(!$prefix){$pid=$db->insert_query('threadprefixes',['prefix'=>$label,'displaystyle'=>'<span class="dune-news-tag">'.htmlspecialchars_uni($label).'</span>','forums'=>'14','groups'=>'-1']);$cache->update_threadprefixes();$prefix=['pid'=>$pid];}
$marker='DuneRealms source: '.$input['id'];
if(!$mapping||!in_array($mapping['state'],['sent','archived'],true)){
// Reconcile a timeout/crash by immutable marker; never blindly create twice.
$query=$db->query('SELECT t.tid,p.pid FROM '.TABLE_PREFIX.'threads t JOIN '.TABLE_PREFIX.'posts p ON p.pid=t.firstpost WHERE t.fid=14 AND t.uid=2 AND p.message LIKE \'%'.$db->escape_string($marker).'%\' LIMIT 2');$matches=[];while($row=$db->fetch_array($query))$matches[]=$row;
if(count($matches)===1){$mapping=['post_id'=>$input['id'],'state'=>'sent','tid'=>(int)$matches[0]['tid'],'pid'=>(int)$matches[0]['pid']];$db->replace_query('dune_news_delivery',$mapping,'post_id');}
elseif($mapping||count($matches)>1)throw new Exception('Interrupted native creation requires review');
}
$thread=null;$first=null;
if($mapping){
$thread=get_thread((int)$mapping['tid']);$first=get_post((int)$mapping['pid']);
if(!$thread||!$first||(int)$thread['fid']!==14||(int)$thread['visible']!==1||(int)$thread['uid']!==2||(int)$thread['firstpost']!==(int)$first['pid']||(int)$first['uid']!==2||(int)$first['tid']!==(int)$thread['tid']||(int)$first['visible']!==1||strpos($first['message'],$marker)===false)throw new Exception('Managed topic ownership or visibility changed');
}
if($status==='archived'&&!$mapping)throw new Exception('Withdrawal cannot create a new topic');
$revision=$modern?$input['revision']:hash('sha256',json_encode($input));
$saved=$db->fetch_array($db->simple_select('dune_news_revision','*',"post_id='{$id}'"));
$state=$status==='published'?'sent':'archived';
$reply=function($tid)use($state,$revision,$modern){$out=['state'=>$state,'thread_id'=>(int)$tid];if($modern)$out['revision']=$revision;echo json_encode($out);};
if($saved&&!$mapping)throw new Exception('Revision mapping requires reconciliation');
if($saved&&$saved['revision']===$revision&&$saved['state']===$state){$reply($mapping['tid']);exit;}
$safe=fn($s)=>str_replace(['[',']'],['&#91;','&#93;'],(string)$s);$url='https://www.dunerealms.com/news-archive.html?post='.$input['id'];
$message='[b]'.$safe($label).'[/b]' . "\n" . 'Written by '.$safe($input['author_name']??'DuneRealms')."\n".'Originally published '.gmdate('j F Y, H:i',(int)($input['published_at']/1000))." UTC\n\n".$safe($input['body'])."\n\n[url=".$url."]Read the original article[/url]\n\n[size=x-small]".$marker.'[/size]';
require_once MYBB_ROOT.'inc/datahandlers/post.php';$handler=new PostDataHandler('insert');$handler->action='thread';$handler->set_data(['fid'=>14,'uid'=>2,'username'=>$author['username'],'subject'=>$input['title'],'prefix'=>(int)$prefix['pid'],'message'=>$message,'dateline'=>(int)($input['published_at']/1000),'ipaddress'=>'127.0.0.1','savedraft'=>0,'options'=>['signature'=>0,'disablesmilies'=>1,'subscriptionmethod'=>0]]);
if(!$handler->validate_thread())throw new Exception('Native post validation failed');
$db->insert_query('dune_news_delivery',['post_id'=>$input['id'],'state'=>'creating','tid'=>0,'pid'=>0]);$result=$handler->insert_thread();$tid=(int)($result['tid']??0);$pid=(int)($result['pid']??0);$thread=get_thread($tid);if(!$tid||!$pid||!$thread||(int)$thread['visible']!==1)throw new Exception('Native topic visibility requires review');$db->update_query('dune_news_delivery',['state'=>'sent','tid'=>$tid,'pid'=>$pid],"post_id='{$id}'");echo json_encode(['state'=>'sent','thread_id'=>$tid]);
if($status==='published'){
$labels=['world'=>'World','news'=>'NEWS','maintenance'=>'Maintenance','changelogs'=>'Changelogs','events'=>'Events','community'=>'Community','unis_blog'=>"Uni’s Blog"];$label=$labels[$input['category']??'news']??'NEWS';$prefix=$db->fetch_array($db->simple_select('threadprefixes','pid',"prefix='".$db->escape_string($label)."' AND forums='14'"));
if(!$prefix){$prefix=['pid'=>$db->insert_query('threadprefixes',['prefix'=>$label,'displaystyle'=>'<span class="dune-news-tag">'.htmlspecialchars_uni($label).'</span>','forums'=>'14','groups'=>'-1'])];$cache->update_threadprefixes();}
$subject=$input['title'];$prefix_id=(int)$prefix['pid'];
$message='[b]'.$safe($label).'[/b]'."\n".'Written by '.$safe($input['author_name']??'DuneRealms')."\n".'Originally published '.gmdate('j F Y, H:i',(int)($input['published_at']/1000))." UTC\n\n".$safe($input['body'])."\n\n[url=".$url."]Read the original article[/url]\n\n[size=x-small]".$marker.'[/size]';
}else{
$subject=my_substr('[Archived] '.preg_replace('/^\[Archived\] /','',$thread['subject']),0,120);$prefix_id=(int)$thread['prefix'];
$message="[b]Archived announcement[/b]\n\nThis article has been withdrawn from the DuneRealms website. Earlier replies are retained for context.\n\n[size=x-small]".$marker.'[/size]';
}
require_once MYBB_ROOT.'inc/datahandlers/post.php';
if($mapping){
if(empty($permissions['caneditposts'])&&!is_moderator($fid,'caneditposts',$uid))throw new Exception('Native edit permission denied');
$earliest=$db->fetch_array($db->simple_select('posts','pid',"tid='".(int)$thread['tid']."'",['order_by'=>'dateline,pid','limit'=>1]));if((int)($earliest['pid']??0)!==(int)$first['pid'])throw new Exception('Native first post requires review');
if($first['subject']!==$subject||$first['message']!==$message||(int)$thread['prefix']!==$prefix_id){
$handler=new PostDataHandler('update');$handler->set_data(['pid'=>(int)$first['pid'],'tid'=>(int)$thread['tid'],'fid'=>$fid,'uid'=>$uid,'edit_uid'=>$uid,'subject'=>$subject,'prefix'=>$prefix_id,'message'=>$message,'editreason'=>$status==='published'?'Synchronized website article revision':'Website article withdrawn; replies retained','options'=>['signature'=>0,'disablesmilies'=>1]]);
if(!$handler->validate_post())throw new Exception('Native edit validation failed');$handler->update_post();
$check=$db->fetch_array($db->simple_select('posts','message,subject,visible',"pid='".(int)$first['pid']."'"));$checkThread=$db->fetch_array($db->simple_select('threads','subject,prefix',"tid='".(int)$thread['tid']."'"));if(!$check||!$checkThread||$check['message']!==$message||$check['subject']!==$subject||(int)$check['visible']!==1||$checkThread['subject']!==$subject||(int)$checkThread['prefix']!==$prefix_id)throw new Exception('Native edit requires review');
}
$tid=(int)$thread['tid'];$pid=(int)$first['pid'];
}else{
$handler=new PostDataHandler('insert');$handler->action='thread';$handler->set_data(['fid'=>$fid,'uid'=>$uid,'username'=>$author['username'],'subject'=>$subject,'prefix'=>$prefix_id,'message'=>$message,'dateline'=>(int)($input['published_at']/1000),'ipaddress'=>'127.0.0.1','savedraft'=>0,'options'=>['signature'=>0,'disablesmilies'=>1,'subscriptionmethod'=>0]]);
if(!$handler->validate_thread())throw new Exception('Native post validation failed');$db->insert_query('dune_news_delivery',['post_id'=>$input['id'],'state'=>'creating','tid'=>0,'pid'=>0]);$result=$handler->insert_thread();$tid=(int)($result['tid']??0);$pid=(int)($result['pid']??0);$thread=get_thread($tid);if(!$tid||!$pid||!$thread||(int)$thread['visible']!==1)throw new Exception('Native topic visibility requires review');
}
$db->update_query('dune_news_delivery',['state'=>$state,'tid'=>$tid,'pid'=>$pid],"post_id='{$id}'");
$db->replace_query('dune_news_revision',['post_id'=>$input['id'],'revision'=>$revision,'state'=>$state,'updated_at'=>(int)(microtime(true)*1000)],'post_id');$reply($tid);
}catch(Throwable $e){fwrite(STDERR,'Forum news delivery requires review'.PHP_EOL);exit(5);}finally{$db->query("SELECT RELEASE_LOCK('{$lock}')");}

View file

@ -1,14 +1,47 @@
import{execFile}from'node:child_process';import{existsSync}from'node:fs';import{randomUUID}from'node:crypto';
export async function initializeForumNews(db){await db.prepare("CREATE TABLE IF NOT EXISTS forum_news_delivery(post_id CHAR(36) PRIMARY KEY,state VARCHAR(16) NOT NULL,thread_id BIGINT NOT NULL DEFAULT 0,claim_token CHAR(36) NOT NULL DEFAULT '',claimed_at BIGINT NOT NULL DEFAULT 0,last_error VARCHAR(120) NOT NULL DEFAULT '')").run();}
import {execFile} from 'node:child_process';
import {existsSync} from 'node:fs';
import {createHash,randomUUID} from 'node:crypto';
export async function initializeForumNews(db){
await db.prepare("CREATE TABLE IF NOT EXISTS forum_news_delivery(post_id CHAR(36) PRIMARY KEY,state VARCHAR(16) NOT NULL,thread_id BIGINT NOT NULL DEFAULT 0,claim_token CHAR(36) NOT NULL DEFAULT '',claimed_at BIGINT NOT NULL DEFAULT 0,last_error VARCHAR(120) NOT NULL DEFAULT '')").run();
await db.prepare("CREATE TABLE IF NOT EXISTS forum_news_revision(post_id CHAR(36) PRIMARY KEY,delivered_hash VARCHAR(64) NOT NULL DEFAULT '')").run();
}
const nativeSend=post=>new Promise((resolve,reject)=>{const child=execFile('/usr/bin/php',['/home/dunerealms/apps/integrations/forum-news.php'],{timeout:30000,maxBuffer:262144},(error,stdout)=>{if(error)return reject(error);try{resolve(JSON.parse(stdout));}catch(e){reject(e);}});child.stdin.end(JSON.stringify(post));});
export function forumNewsRevision(row,time){
// Withdrawal payloads deliberately contain no current draft/private/future content.
const post=row.status==='published'&&row.published_at!=null&&Number.isFinite(Number(row.published_at))&&Number(row.published_at)<=time
?{id:row.id,status:'published',title:row.title,body:row.body,category:row.category,published_at:Number(row.published_at),author_name:row.author_name||'DuneRealms'}
:{id:row.id,status:'archived'};
return {...post,revision:createHash('sha256').update(JSON.stringify(post)).digest('hex')};
}
const sourceSQL="SELECT d.post_id AS id,d.thread_id,d.state,p.title,p.body,p.category,p.published_at,p.status,COALESCE(a.display_name,a.username,'DuneRealms') author_name,r.delivered_hash FROM forum_news_delivery d LEFT JOIN website_posts p ON p.id=d.post_id LEFT JOIN site_accounts a ON a.id=p.author_id LEFT JOIN forum_news_revision r ON r.post_id=d.post_id";
export async function drainForumNews(db,{send=nativeSend,now=Date.now}={}){
const time=now();await db.prepare("UPDATE forum_news_delivery SET state='queued',claim_token='' WHERE state='sending' AND claimed_at<?").bind(time-120000).run();
const time=now();
// Native source-marker reconciliation makes an interrupted claim safe to inspect again.
await db.prepare("UPDATE forum_news_delivery SET state='queued',claim_token='' WHERE state='sending' AND claimed_at<?").bind(time-120000).run();
await db.prepare("INSERT INTO forum_news_delivery(post_id,state) SELECT id,'queued' FROM website_posts WHERE status='published' AND published_at<=? ON CONFLICT(post_id) DO UPDATE SET post_id=excluded.post_id").bind(time).run();
const {results:known}=await db.prepare(sourceSQL).all();
for(const row of known){
const post=forumNewsRevision(row,time);
if(post.status==='archived'&&!Number(row.thread_id))continue;
if(row.delivered_hash===post.revision)continue;
// The revision guard prevents a stale concurrent scan from requeueing an already delivered update.
await db.prepare("UPDATE forum_news_delivery SET state='queued' WHERE post_id=? AND state IN ('sent','archived','withdrawn') AND NOT EXISTS(SELECT 1 FROM forum_news_revision WHERE post_id=? AND delivered_hash=?)").bind(row.id,row.id,post.revision).run();
}
const{results}=await db.prepare("SELECT post_id FROM forum_news_delivery WHERE state='queued' ORDER BY post_id LIMIT 5").all();const states=[];
for(const job of results){const token=randomUUID();const claim=await db.prepare("UPDATE forum_news_delivery SET state='sending',claim_token=?,claimed_at=? WHERE post_id=? AND state='queued'").bind(token,time,job.post_id).run();if(!claim.meta.changes)continue;
const post=await db.prepare("SELECT p.id,p.title,p.body,p.category,p.published_at,COALESCE(a.display_name,a.username,'DuneRealms') author_name FROM website_posts p LEFT JOIN site_accounts a ON a.id=p.author_id WHERE p.id=? AND p.status='published' AND p.published_at<=?").bind(job.post_id,time).first();
if(!post){await db.prepare("UPDATE forum_news_delivery SET state='withdrawn' WHERE post_id=? AND claim_token=?").bind(job.post_id,token).run();continue;}
try{const result=await send(post);if(result.state!=='sent'||!Number.isSafeInteger(result.thread_id)||result.thread_id<1)throw Error('Native reconciliation required');await db.prepare("UPDATE forum_news_delivery SET state='sent',thread_id=?,last_error='' WHERE post_id=? AND claim_token=?").bind(result.thread_id,job.post_id,token).run();states.push('sent');}catch{await db.prepare("UPDATE forum_news_delivery SET state='uncertain',last_error='Native delivery requires reconciliation' WHERE post_id=? AND claim_token=?").bind(job.post_id,token).run();states.push('uncertain');}
for(const job of results){
const token=randomUUID();const claim=await db.prepare("UPDATE forum_news_delivery SET state='sending',claim_token=?,claimed_at=? WHERE post_id=? AND state='queued'").bind(token,time,job.post_id).run();if(!claim.meta.changes)continue;
const row=await db.prepare(sourceSQL+' WHERE d.post_id=?').bind(job.post_id).first();const post=forumNewsRevision(row,time);
if(post.status==='archived'&&!Number(row.thread_id)){await db.prepare("UPDATE forum_news_delivery SET state='withdrawn',claim_token='' WHERE post_id=? AND claim_token=?").bind(job.post_id,token).run();continue;}
try{
const result=await send(post),state=post.status==='archived'?'archived':'sent';
if(result.state!==state||result.revision!==post.revision||!Number.isSafeInteger(result.thread_id)||result.thread_id<1)throw Error('Native reconciliation required');
await db.batch([
db.prepare("INSERT INTO forum_news_revision(post_id,delivered_hash) SELECT ?,? WHERE EXISTS(SELECT 1 FROM forum_news_delivery WHERE post_id=? AND claim_token=? AND state='sending') ON CONFLICT(post_id) DO UPDATE SET delivered_hash=excluded.delivered_hash").bind(job.post_id,post.revision,job.post_id,token),
db.prepare("UPDATE forum_news_delivery SET state=?,thread_id=?,claim_token='',last_error='' WHERE post_id=? AND claim_token=?").bind(state,result.thread_id,job.post_id,token)
]);states.push(state);
}catch{
await db.prepare("UPDATE forum_news_delivery SET state='uncertain',last_error='Native delivery requires reconciliation' WHERE post_id=? AND claim_token=?").bind(job.post_id,token).run();states.push('uncertain');
}
}return states;
}
export async function startForumNewsWorker(db,{logger=console}={}){if(!existsSync('/home/dunerealms/apps/integrations/forum-news.php'))return()=>{};await initializeForumNews(db);let busy=false;const tick=async()=>{if(busy)return;busy=true;try{await drainForumNews(db);}catch{logger.warn('Forum news delivery check failed');}finally{busy=false;}};const timer=setInterval(tick,10000);timer.unref?.();void tick();return()=>clearInterval(timer);}
export async function startForumNewsWorker(db,{logger=console}={}){if(!existsSync('/home/dunerealms/apps/integrations/forum-news.php'))return()=>{};await initializeForumNews(db);let stopped=false,busy=false;const tick=async()=>{if(stopped||busy)return;busy=true;try{await drainForumNews(db);}catch{logger.warn('Forum news delivery check failed');}finally{busy=false;}};const timer=setInterval(tick,10000);timer.unref?.();void tick();return()=>{stopped=true;clearInterval(timer);};}

View file

@ -2,9 +2,9 @@ import {nativeForumFeed} from './native-forum-feed.mjs';
import {randomUUID} from 'node:crypto';
import {readFile} from 'node:fs/promises';
import {json} from './game-link.mjs';
export const NEWS_CATEGORIES={world:'World',news:'News',maintenance:'Maintenance',changelogs:'Changelogs',events:'Events',community:'Community',unis_blog:"Uni’s Blog"};
export const NEWS_CATEGORIES={world:'World',news:'NEWS',maintenance:'Maintenance',changelogs:'Changelogs',events:'Events',community:'Community',unis_blog:"Uni’s Blog"};
export async function initializeNews(db){
for(const [key,label] of Object.entries(NEWS_CATEGORIES))await db.prepare('INSERT INTO website_post_categories(category_key,label,artwork) VALUES(?,?,?) ON CONFLICT(category_key) DO UPDATE SET category_key=excluded.category_key').bind(key,label,'assets/news-'+(key==='unis_blog'?'news':key)+'.png').run();
for(const [key,label] of Object.entries(NEWS_CATEGORIES))await db.prepare('INSERT INTO website_post_categories(category_key,label,artwork) VALUES(?,?,?) ON CONFLICT(category_key) DO UPDATE SET label=excluded.label').bind(key,label,'assets/news-'+(key==='unis_blog'?'news':key)+'.png').run();
// Only published release records become posts. Pending work never becomes a release announcement.
let releases=[];try{const file=JSON.parse(await readFile(new URL('../scripts/changelog.json',import.meta.url),'utf8'));releases=Array.isArray(file)?file:file.releases||[];}catch{}
for(const release of releases){

View file

@ -1,4 +1,37 @@
import test from'node:test';import assert from'node:assert/strict';import{LocalD1}from'./d1-adapter.mjs';import{initializeForumNews,drainForumNews}from'../node/forum-news.mjs';
import test from 'node:test';import assert from 'node:assert/strict';
import {LocalD1} from './d1-adapter.mjs';
import {initializeForumNews,drainForumNews,forumNewsRevision} from '../node/forum-news.mjs';
const fixture=()=>new LocalD1('CREATE TABLE website_posts(id TEXT PRIMARY KEY,title TEXT,body TEXT,category TEXT,published_at INT,status TEXT,author_id TEXT);CREATE TABLE site_accounts(id TEXT,display_name TEXT,username TEXT);');
test('published news backfills once with original author/date; drafts and future news never send',async()=>{const db=fixture();try{await initializeForumNews(db);await db.prepare("INSERT INTO site_accounts VALUES('a','Writer','writer')").run();for(const[id,status,time]of[['one','published',100],['draft','draft',100],['future','published',5000]])await db.prepare('INSERT INTO website_posts VALUES(?,?,?,?,?,?,?)').bind(id,'Title','Full body','news',time,status,'a').run();const sent=[];const send=async post=>{sent.push(post);return{state:'sent',thread_id:42};};await Promise.all([drainForumNews(db,{send,now:()=>1000}),drainForumNews(db,{send,now:()=>1000})]);await drainForumNews(db,{send,now:()=>1000});assert.equal(sent.length,1);assert.equal(sent[0].author_name,'Writer');assert.equal(sent[0].published_at,100);assert.equal(sent[0].body,'Full body');assert.equal((await db.prepare("SELECT thread_id FROM forum_news_delivery WHERE post_id='one'").first()).thread_id,42);}finally{db.close();}});
test('unknown native outcome waits for reconciliation and does not blindly retry',async()=>{const db=fixture();try{await initializeForumNews(db);await db.prepare("INSERT INTO website_posts VALUES('one','Title','Body','news',100,'published','a')").run();let calls=0;const send=async()=>{calls++;throw Error('Timeout');};await drainForumNews(db,{send,now:()=>1000});await drainForumNews(db,{send,now:()=>1000000});assert.equal(calls,1);assert.equal((await db.prepare("SELECT state FROM forum_news_delivery WHERE post_id='one'").first()).state,'uncertain');}finally{db.close();}});
const success=post=>({state:post.status==='archived'?'archived':'sent',thread_id:42,revision:post.revision});
async function seed(db){await initializeForumNews(db);await db.prepare("INSERT INTO website_posts VALUES('one','Title','Body','news',100,'published','a')").run();}
test('published news backfills once with original author/date; drafts and future news never send',async()=>{
const db=fixture();try{await initializeForumNews(db);await db.prepare("INSERT INTO site_accounts VALUES('a','Writer','writer')").run();for(const[id,status,time]of[['one','published',100],['draft','draft',100],['future','published',5000]])await db.prepare('INSERT INTO website_posts VALUES(?,?,?,?,?,?,?)').bind(id,'Title','Full body','news',time,status,'a').run();const sent=[];const send=async post=>{sent.push(post);return success(post);};await Promise.all([drainForumNews(db,{send,now:()=>1000}),drainForumNews(db,{send,now:()=>1000})]);await drainForumNews(db,{send,now:()=>1000});assert.equal(sent.length,1);assert.equal(sent[0].author_name,'Writer');assert.equal(sent[0].published_at,100);assert.equal(sent[0].body,'Full body');assert.equal((await db.prepare("SELECT thread_id FROM forum_news_delivery WHERE post_id='one'").first()).thread_id,42);}finally{db.close();}
});
test('unknown native outcome waits for reconciliation and does not blindly retry',async()=>{
const db=fixture();try{await seed(db);let calls=0;const send=async()=>{calls++;throw Error('Timeout');};await drainForumNews(db,{send,now:()=>1000});await drainForumNews(db,{send,now:()=>1000000});assert.equal(calls,1);assert.equal((await db.prepare("SELECT state FROM forum_news_delivery WHERE post_id='one'").first()).state,'uncertain');}finally{db.close();}
});
test('published edits update the existing mapped topic once, retaining source identity and author',async()=>{
const db=fixture();try{await seed(db);const sent=[];const send=async post=>{sent.push(post);return success(post);};await drainForumNews(db,{send,now:()=>1000});await db.prepare("UPDATE website_posts SET title='Corrected title',body='Corrected body',category='maintenance' WHERE id='one'").run();await drainForumNews(db,{send,now:()=>1000});await drainForumNews(db,{send,now:()=>1000});assert.equal(sent.length,2);assert.equal(sent[1].id,sent[0].id);assert.equal(sent[1].category,'maintenance');assert.notEqual(sent[1].revision,sent[0].revision);assert.equal((await db.prepare("SELECT thread_id FROM forum_news_delivery WHERE post_id='one'").first()).thread_id,42);}finally{db.close();}
});
test('withdrawal, draft, deletion and rescheduling send no unpublished article content; republish reuses topic',async()=>{
for(const status of ['archived','draft','deleted','future','missing']){const db=fixture();try{
await seed(db);const sent=[];const send=async post=>{sent.push(post);return success(post);};await drainForumNews(db,{send,now:()=>1000});
if(status==='missing')await db.prepare("DELETE FROM website_posts WHERE id='one'").run();else await db.prepare("UPDATE website_posts SET status=?,published_at=?,body='PRIVATE DRAFT',title='SECRET TITLE' WHERE id='one'").bind(status==='future'?'published':status,status==='future'?5000:100).run();
await drainForumNews(db,{send,now:()=>1000});await drainForumNews(db,{send,now:()=>1000});assert.equal(sent.length,2);assert.equal(sent[1].status,'archived');assert.deepEqual(Object.keys(sent[1]).sort(),['id','revision','status']);assert.equal((await db.prepare("SELECT state FROM forum_news_delivery WHERE post_id='one'").first()).state,'archived');
if(status==='missing')continue;
await db.prepare("UPDATE website_posts SET status='published',published_at=100,body='Republished body' WHERE id='one'").run();await drainForumNews(db,{send,now:()=>1000});assert.equal(sent.length,3);assert.equal(sent[2].status,'published');assert.equal((await db.prepare("SELECT thread_id FROM forum_news_delivery WHERE post_id='one'").first()).thread_id,42);
}finally{db.close();}}
});
test('editing during native delivery is picked up next tick rather than marking the new content delivered',async()=>{
const db=fixture();try{await seed(db);const sent=[];const send=async post=>{sent.push(post);if(sent.length===1)await db.prepare("UPDATE website_posts SET body='New revision' WHERE id='one'").run();return success(post);};await drainForumNews(db,{send,now:()=>1000});await drainForumNews(db,{send,now:()=>1000});assert.deepEqual(sent.map(p=>p.body),['Body','New revision']);assert.equal((await db.prepare("SELECT delivered_hash FROM forum_news_revision WHERE post_id='one'").first()).delivered_hash,sent[1].revision);}finally{db.close();}
});
test('wrong native revision never confirms the website link or delivery',async()=>{
const db=fixture();try{await seed(db);await drainForumNews(db,{send:async p=>({...success(p),revision:'wrong'}),now:()=>1000});assert.equal((await db.prepare("SELECT state,thread_id FROM forum_news_delivery WHERE post_id='one'").first()).state,'uncertain');assert.equal(await db.prepare("SELECT * FROM forum_news_revision WHERE post_id='one'").first(),null);}finally{db.close();}
});
test('archiving while the first job is queued never creates a new withdrawn topic',async()=>{
const db=fixture();try{await seed(db);await db.prepare("INSERT INTO forum_news_delivery(post_id,state) VALUES('one','queued')").run();await db.prepare("UPDATE website_posts SET status='draft',body='SECRET' WHERE id='one'").run();let calls=0;await drainForumNews(db,{send:async p=>{calls++;return success(p);},now:()=>1000});assert.equal(calls,0);assert.equal((await db.prepare("SELECT state FROM forum_news_delivery WHERE post_id='one'").first()).state,'withdrawn');await db.prepare("UPDATE website_posts SET status='published' WHERE id='one'").run();await drainForumNews(db,{send:async p=>{calls++;return success(p);},now:()=>1000});assert.equal(calls,1);}finally{db.close();}
});
test('category and author changes revise publication, while draft fields do not revise the withdrawal payload',()=>{
const base={id:'one',status:'published',title:'A',body:'B',category:'news',published_at:100,author_name:'Writer'};assert.notEqual(forumNewsRevision(base,1000).revision,forumNewsRevision({...base,author_name:'Other'},1000).revision);assert.deepEqual(forumNewsRevision({...base,status:'draft'},1000),forumNewsRevision({...base,status:'draft',body:'PRIVATE'},1000));
for(const published_at of [null,undefined,NaN,Infinity,'bad'])assert.equal(forumNewsRevision({...base,published_at},1000).status,'archived');
});

View file

@ -0,0 +1,18 @@
import{readFile}from'node:fs/promises';import{createRequire}from'node:module';import assert from'node:assert/strict';
import{mysqlSql}from'/home/dunerealms/apps/dunerealms/current/node/mysql.mjs';
import{initializeForumNews,drainForumNews}from'/tmp/forum-news372-candidate.mjs';
const require=createRequire('/home/dunerealms/apps/dunerealms/current/node/mysql.mjs'),mysql=require('mysql2/promise');
const config=JSON.parse(await readFile('/home/dunerealms/.config/integrations.json','utf8'));
const connection=await mysql.createConnection({host:config.host,user:config.username,password:config.password,database:config.database});
const db={prepare(sql){let values=[];return{bind(...v){values=v;return this},async first(){return(await connection.execute(mysqlSql(sql),values))[0][0]||null},async all(){return{results:(await connection.execute(mysqlSql(sql),values))[0]}},async run(){const[r]=await connection.execute(mysqlSql(sql).replace(/^CREATE TABLE /,'CREATE TEMPORARY TABLE '),values);return{meta:{changes:r.affectedRows}}}}},async batch(items){await connection.beginTransaction();try{let out=[];for(const item of items)out.push(await item.run());await connection.commit();return out;}catch(error){await connection.rollback();throw error;}}};
try{
await connection.query('CREATE TEMPORARY TABLE website_posts(id CHAR(36) PRIMARY KEY,title TEXT,body TEXT,category VARCHAR(40),published_at BIGINT,status VARCHAR(16),author_id VARCHAR(40))');
await connection.query('CREATE TEMPORARY TABLE site_accounts(id VARCHAR(40),display_name VARCHAR(80),username VARCHAR(80))');
await initializeForumNews(db);await db.prepare("INSERT INTO website_posts VALUES('one','Title','Body','news',100,'published','a')").run();
const sent=[],send=async post=>{sent.push(post);return{state:post.status==='archived'?'archived':'sent',thread_id:42,revision:post.revision}};
await drainForumNews(db,{send,now:()=>1000});await drainForumNews(db,{send,now:()=>1000});assert.equal(sent.length,1);
await db.prepare("UPDATE website_posts SET body='Correction',category='maintenance' WHERE id='one'").run();await drainForumNews(db,{send,now:()=>1000});assert.equal(sent.length,2);
await db.prepare("UPDATE website_posts SET status='draft',body='PRIVATE' WHERE id='one'").run();await drainForumNews(db,{send,now:()=>1000});assert.deepEqual(Object.keys(sent[2]).sort(),['id','revision','status']);assert.equal(sent[2].status,'archived');
await db.prepare("UPDATE website_posts SET status='published' WHERE id='one'").run();await drainForumNews(db,{send,now:()=>1000});assert.equal(sent.length,4);assert.equal((await db.prepare("SELECT thread_id FROM forum_news_delivery WHERE post_id='one'").first()).thread_id,42);
console.log(JSON.stringify({actualMysqlStatements:true,temporaryTablesOnly:true,publishEditArchiveRepublish:true,noRepeatedDelivery:true,privatePayloadExcluded:true}));
}finally{await connection.end();}

View file

@ -0,0 +1,38 @@
import pathlib,subprocess,json,os,hashlib
root=pathlib.Path('/home/dunerealms/apps/integrations/mybb');qa=pathlib.Path('/tmp/forum372-native-qa');qa.mkdir(mode=0o700,exist_ok=True)
assert not (qa/'state.json').exists(),'Use a fresh isolated fixture directory'
init=(root/'inc/init.php').read_text();needle="$db->type = $config['database']['type'];";assert init.count(needle)==1
(qa/'init.php').write_text(init.replace(needle,needle+"\nrequire '/tmp/forum372-shadow.php';"))
glob=(root/'global.php').read_text();needle="require_once $working_dir.'/inc/init.php';";assert glob.count(needle)==1
(qa/'global.php').write_text(glob.replace(needle,"define('MYBB_ROOT','"+str(root)+"/');require_once '/tmp/forum372-native-qa/init.php';"))
source=pathlib.Path('/tmp/forum-news372-candidate.php').read_text();assert source.count("require 'global.php';")==1
# Only bootstrap/DDL are redirected. Adapter logic and native PostDataHandler are unchanged.
(qa/'adapter.php').write_text(source.replace("require 'global.php';","require '/tmp/forum372-native-qa/global.php';").replace('CREATE TABLE IF NOT EXISTS','CREATE TEMPORARY TABLE IF NOT EXISTS'))
id='8b10b073-96d8-4827-a372-111111111111';post={'id':id,'status':'published','title':'Isolated native QA announcement','body':'Original isolated article body','category':'news','published_at':1793900000000,'author_name':'QA Author'}
def run(payload,reply=False):
payload=dict(payload);payload['revision']=hashlib.sha256(json.dumps(payload,ensure_ascii=False,separators=(',',':')).encode()).hexdigest()
result=subprocess.run(['php',str(qa/'adapter.php')],input=json.dumps(payload),text=True,capture_output=True,env={**os.environ,'ADD_REPLY':'1' if reply else '0'})
if result.returncode:raise RuntimeError('Native fixture failed: '+str(result.returncode)+' '+result.stdout[:300]+' '+result.stderr[:600])
output=json.loads(result.stdout);assert output['revision']==payload['revision'];state=json.loads((qa/'state.json').read_text());return output,state
initial,state=run(post);tid=initial['thread_id'];pid=state['threads'][0]['firstpost'];date=state['posts'][0]['dateline'];assert len(state['threads'])==len(state['posts'])==1
post.update(title='Corrected isolated announcement',body='Corrected article body',category='maintenance')
edited,state=run(post,True);assert edited['thread_id']==tid and len(state['posts'])==2 and len(state['threads'])==1
assert state['posts'][0]['pid']==pid and state['posts'][0]['dateline']==date and 'Corrected article body' in state['posts'][0]['message']
reply=next(p for p in state['posts'] if str(p['pid'])=='100');reply_bytes=json.dumps(reply,sort_keys=True)
archived,state=run({'id':id,'status':'archived'});assert archived['state']=='archived' and archived['thread_id']==tid and len(state['posts'])==2
assert state['threads'][0]['subject'].startswith('[Archived] ') and 'Archived announcement' in state['posts'][0]['message']
assert json.dumps(next(p for p in state['posts'] if str(p['pid'])=='100'),sort_keys=True)==reply_bytes
again,state=run({'id':id,'status':'archived'});assert len(state['threads'])==1 and len(state['posts'])==2 and again==archived
restored,state=run(post);assert restored['state']=='sent' and restored['thread_id']==tid and not state['threads'][0]['subject'].startswith('[Archived] ')
assert json.dumps(next(p for p in state['posts'] if str(p['pid'])=='100'),sort_keys=True)==reply_bytes
assert state['posts'][0]['dateline']==date and state['posts'][0]['pid']==pid
baseline=json.loads(json.dumps(state));denials=[]
for field,value in [('uid','7'),('fid','99'),('visible','0'),('firstpost','100')]:
changed=json.loads(json.dumps(baseline));changed['threads'][0][field]=value;(qa/'state.json').write_text(json.dumps(changed))
payload={**post,'body':'Must not be applied'};payload['revision']=hashlib.sha256(json.dumps(payload,separators=(',',':')).encode()).hexdigest()
result=subprocess.run(['php',str(qa/'adapter.php')],input=json.dumps(payload),text=True,capture_output=True,env={**os.environ,'ADD_REPLY':'0'})
assert result.returncode==5,(field,result.returncode)
final=json.loads((qa/'state.json').read_text());assert final['posts']==changed['posts'],field
denials.append(field)
(qa/'state.json').write_text(json.dumps(baseline))
print(json.dumps({'nativePostDataHandler':True,'temporaryTablesOnly':True,'createEditArchiveReplayRepublish':True,'topicIdentityPreserved':True,'replyByteForBytePreserved':True,'originalPostDatePreserved':True,'ownershipForumVisibilityFirstPostDenials':denials}))

View file

@ -0,0 +1,28 @@
<?php
// Test only: invoked immediately after MyBB DB connection, before cache/session init.
if(PHP_SAPI!=='cli'||($config['cache_store']??'db')!=='db')throw new Exception('DB-cache CLI isolation required');
$stateFile='/tmp/forum372-native-qa/state.json';$saved=is_file($stateFile)?json_decode(file_get_contents($stateFile),true):[];
$seed=['users','settings','usergroups','forums','forumpermissions','threadprefixes','moderators','datacache','settinggroups'];
$result=$db->query("SHOW TABLES LIKE '".$db->escape_string(TABLE_PREFIX)."%'");$names=[];while($row=$db->fetch_array($result))$names[]=array_values($row)[0];
foreach($names as$name){
if(!preg_match('/^[A-Za-z0-9_]+$/',$name)||strpos($name,TABLE_PREFIX)!==0)throw new Exception('Unexpected table name');
$short=substr($name,strlen(TABLE_PREFIX));$rows=[];
if(in_array($short,$seed,true)){$q=$db->query('SELECT * FROM `'.$name.'`'.($short==='users'?' WHERE uid=2':''));while($r=$db->fetch_array($q))$rows[]=$r;}
if(isset($saved[$short]))$rows=$saved[$short];
$binary=[];$q=$db->query('SHOW COLUMNS FROM `'.$name.'`');while($column=$db->fetch_array($q))$binary[$column['Field']]=(bool)preg_match('/binary|blob/i',$column['Type']);
$ddl=$db->fetch_array($db->query('SHOW CREATE TABLE `'.$name.'`'));
$create=preg_replace('/^CREATE TABLE /','CREATE TEMPORARY TABLE ',array_values($ddl)[1],1,$count);if($count!==1)throw new Exception('Unexpected table DDL');$db->write_query($create);
foreach($rows as$row){$columns=[];$values=[];foreach($row as$k=>$v){if(!preg_match('/^[A-Za-z0-9_]+$/',$k))throw new Exception('Unexpected column');$columns[]='`'.$k.'`';$values[]=$v===null?'NULL':($binary[$k]?"X'".bin2hex((string)$v)."'":"'".$db->escape_string($v)."'");}$db->write_query('INSERT INTO `'.$name.'` ('.implode(',',$columns).') VALUES ('.implode(',',$values).')');}
}
// New adapter table is also temporary, including on the first migration run.
if(!in_array(TABLE_PREFIX.'dune_news_revision',$names,true))$db->write_query('CREATE TEMPORARY TABLE '.TABLE_PREFIX.'dune_news_revision(post_id CHAR(36) PRIMARY KEY,revision VARCHAR(64) NOT NULL,state VARCHAR(16) NOT NULL,updated_at BIGINT NOT NULL) ENGINE=InnoDB');
if(isset($saved['dune_news_revision'])&&!in_array(TABLE_PREFIX.'dune_news_revision',$names,true))foreach($saved['dune_news_revision']as$row)$db->insert_query('dune_news_revision',array_map(fn($v)=>$db->escape_string($v),$row));
if(getenv('ADD_REPLY')==='1'){
$thread=$db->fetch_array($db->simple_select('threads','*'));
$db->insert_query('posts',['pid'=>100,'tid'=>(int)$thread['tid'],'fid'=>14,'subject'=>'Re: QA announcement','uid'=>2,'username'=>'dunerealms','dateline'=>(int)$thread['dateline']+1,'message'=>'REPLY SENTINEL KEEP','ipaddress'=>'','visible'=>1]);
$db->update_query('threads',['replies'=>1,'lastpost'=>(int)$thread['dateline']+1,'lastposter'=>'dunerealms','lastposteruid'=>2],"tid='".(int)$thread['tid']."'");
}
register_shutdown_function(function()use($db,$stateFile){
$state=[];foreach(['threads','posts','dune_news_delivery','dune_news_revision']as$table){$q=$db->simple_select($table,'*');$state[$table]=[];while($row=$db->fetch_array($q))$state[$table][]=$row;}
file_put_contents($stateFile,json_encode($state,JSON_THROW_ON_ERROR));
});