web/website/node/postbank-rate-publications.mjs

51 lines
4.8 KiB
JavaScript

import {spawn} from 'node:child_process';import {fileURLToPath} from 'node:url';import {randomUUID} from 'node:crypto';
import {queueRatesPublication} from './postbank-financial-policy.mjs';
export async function ensureRatesPublication(db,actorId,now=Date.now()){
return db.transaction(async tx=>{
await tx.query("INSERT INTO pb_financial_policies(policy_key,policy_json,version,updated_by,updated_at) VALUES('publication_guard','{}',0,?,?) ON DUPLICATE KEY UPDATE policy_key=VALUES(policy_key)",[actorId,now]);
await tx.first("SELECT policy_key FROM pb_financial_policies WHERE policy_key='publication_guard' FOR UPDATE");
const existing=await tx.first('SELECT id FROM pb_rate_publications ORDER BY created_at DESC,id DESC LIMIT 1 FOR UPDATE');
return existing?.id||await queueRatesPublication(tx,actorId,now);
});
}
export function renderRatesPDF(snapshot,{python='python3',logo=fileURLToPath(new URL('../web/assets/imperial-postbank-v2.png',import.meta.url))}={}){
return new Promise((resolve,reject)=>{
const child=spawn(python,[fileURLToPath(new URL('./postbank-rates-pdf.py',import.meta.url)),...(logo?[logo]:[])],{stdio:['pipe','pipe','pipe'],windowsHide:true}),chunks=[];let size=0,settled=false;
const finish=(error,value)=>{if(settled)return;settled=true;clearTimeout(timer);error?reject(error):resolve(value);};
const timer=setTimeout(()=>{child.kill();finish(Error('Tariff PDF rendering timed out.'));},30000);
child.stdout.on('data',chunk=>{size+=chunk.length;if(size>2000000){child.kill();finish(Error('Tariff PDF exceeds the size limit.'));}else chunks.push(chunk);});
child.stderr.resume();child.stdin.on('error',()=>{});child.on('error',()=>finish(Error('Tariff PDF renderer unavailable.')));
child.on('close',code=>{const pdf=Buffer.concat(chunks);if(code!==0||!pdf.subarray(0,5).equals(Buffer.from('%PDF-')))finish(Error('Tariff PDF could not be rendered.'));else finish(null,pdf);});
child.stdin.end(JSON.stringify(snapshot));
});
}
export class PostbankRatePublications{
constructor(db,{clock=Date.now,renderer=renderRatesPDF,...options}={}){this.db=db;this.clock=clock;this.renderer=snapshot=>renderer(snapshot,options);}
async process(){
const token=randomUUID(),now=this.clock(),row=await this.db.transaction(async tx=>{
const next=await tx.first("SELECT id,data_json FROM pb_rate_publications WHERE state<>'ready' AND lease_until<=? AND retry_at<=? ORDER BY created_at,id LIMIT 1 FOR UPDATE",[now,now]);
if(!next)return null;await tx.query("UPDATE pb_rate_publications SET lease_token=?,lease_until=?,state='rendering' WHERE id=?",[token,now+60000,next.id]);return next;
});
if(!row)return {generated:0,failed:0};
try{const pdf=await this.renderer(JSON.parse(row.data_json));
const result=await this.db.query("UPDATE pb_rate_publications SET pdf_blob=?,state='ready',lease_token='',lease_until=0,retry_at=0 WHERE id=? AND lease_token=?",[pdf,row.id,token]);return {generated:result.affectedRows?1:0,failed:0};
}catch{await this.db.query("UPDATE pb_rate_publications SET state='pending',lease_token='',lease_until=0,retry_at=? WHERE id=? AND lease_token=?",[this.clock()+300000,row.id,token]);return {generated:0,failed:1};}
}
async publicResponse(request){
const url=new URL(request.url),headers={'Access-Control-Allow-Origin':'*','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'};
const reply=(body,status=200)=>Response.json(body,{status,headers});
if(!['GET','HEAD'].includes(request.method))return reply({message:'Method not allowed.'},405);
if([...url.searchParams.keys()].some(k=>k!=='version')||url.searchParams.getAll('version').length>1)return reply({message:'Choose one publication version.'},400);
const version=url.searchParams.get('version');if(version&&!/^[a-f0-9-]{36}$/i.test(version))return reply({message:'Invalid publication version.'},400);
try{
const row=await this.db.first('SELECT id,data_json,state FROM pb_rate_publications '+(version?'WHERE id=? ':'')+'ORDER BY created_at DESC,id DESC LIMIT 1',version?[version]:[]);
if(!row)return reply({message:'The public tariff register is being prepared.'},503);
if(url.pathname.endsWith('.pdf')){
if(row.state!=='ready')return reply({message:'This publication PDF is being prepared.'},503);
const ready=await this.db.first("SELECT pdf_blob FROM pb_rate_publications WHERE id=? AND state='ready'",[row.id]);if(!ready?.pdf_blob)return reply({message:'The publication PDF is unavailable.'},503);
return new Response(request.method==='HEAD'?null:ready.pdf_blob,{headers:{...headers,'Content-Type':'application/pdf','Content-Disposition':'attachment; filename="imperial-postbank-rates-'+row.id+'.pdf"'}});
}
return reply({...JSON.parse(row.data_json),pdfReady:row.state==='ready',pdfUrl:'/api/bank/public/rates.pdf?version='+row.id});
}catch{return reply({message:'The tariff register could not be loaded.'},503);}
}
}