1+ import { Elysia } from "elysia" ;
2+ import { Logger } from "./logger" ;
3+ // import { SendTransactionDTO } from "./sendTransactionDTO";
4+ import { validateMatrixEvent } from "../../validation/EventValidationPipeline" ;
5+ import { Event as MatrixEvent } from "../../validation/validators/EventValidators" ;
6+ import { generateId } from "../../authentication" ;
7+ import { routerWithMutex } from "../../plugins/mutex" ;
8+
9+ const logger = new Logger ( "SendTransactionRoute" ) ;
10+
11+ async function processPDU ( pdu : MatrixEvent [ "event" ] , pduResults : Record < string , { error ?: string } > , txnId : string , context : any ) {
12+ const eventId = generateId ( pdu ) ;
13+
14+ try {
15+ const result = await validateMatrixEvent ( pdu , txnId , eventId , context ) ;
16+ if ( ! result . success && result . error ) {
17+ pduResults [ eventId ] = {
18+ error : `${ result . error . code } : ${ result . error . message } `
19+ } ;
20+ logger . error ( `Validation failed for PDU ${ eventId } : ${ result . error . message } ` ) ;
21+ } else {
22+ logger . debug ( `Successfully validated PDU ${ eventId } ` ) ;
23+ // TODO: Persist the event on LRU cache and database
24+ // TODO: Make this as part of the validation pipeline
25+ }
26+ } catch ( error ) {
27+ const errorMessage = error instanceof Error
28+ ? error . message
29+ : String ( error ) ;
30+ pduResults [ eventId ] = { error : errorMessage } ;
31+ logger . error ( `Error processing PDU: ${ errorMessage } ` ) ;
32+ }
33+
34+ return pduResults ;
35+ }
36+
37+ async function processPDUs ( pdus : MatrixEvent [ "event" ] [ ] , txnId : string , context : any ) : Promise < Record < string , { error ?: string } > > {
38+ if ( pdus . length === 0 ) {
39+ logger . debug ( "No PDUs to process" ) ;
40+ return { } ;
41+ }
42+
43+ const pduResults : Record < string , { error ?: string } > = { } ;
44+ await Promise . all ( pdus . map ( pdu => processPDU ( pdu , pduResults , txnId , context ) ) ) ;
45+
46+ return pduResults ;
47+ }
48+
49+ export const sendTransactionRoute = new Elysia ( )
50+ . use ( routerWithMutex )
51+ . put ( "/send/:txnId" , async ( { params, body, ...context } ) => {
52+ const { txnId } = params ;
53+ const { pdus = [ ] , edus = [ ] } = body as { pdus ?: MatrixEvent [ "event" ] [ ] , edus ?: MatrixEvent [ "event" ] [ ] } ;
54+
55+ const pduResults = await processPDUs ( pdus , txnId , context ) ;
56+ logger . debug ( `PDU results: ${ JSON . stringify ( pduResults ) } ` ) ;
57+
58+ context . set . status = 200 ;
59+ return {
60+ pdus : pduResults ,
61+ }
62+ // }, SendTransactionDTO);
63+ } ) ;
0 commit comments