File tree Expand file tree Collapse file tree 2 files changed +54
-1
lines changed Expand file tree Collapse file tree 2 files changed +54
-1
lines changed Original file line number Diff line number Diff line change 1+ const { conns } = require ( '../../../../helpers/bree-hooks' ) ;
2+
3+ let uuid = 0 ;
4+
15async function connect ( ctx ) {
26 if ( ctx . sse ) {
37 // likely not the best way to do this
@@ -21,18 +25,38 @@ async function connect(ctx) {
2125 data : isActive ( ctx )
2226 } ) ;
2327
28+ conns . push ( { id : uuid , sse : ctx . sse } ) ;
29+
2430 // send bree events over sse
2531 for ( const event of [ 'worker created' , 'worker deleted' ] ) {
2632 ctx . bree . on ( event , ( name ) => {
2733 ctx . sse . send ( { event, data : name } ) ;
2834 } ) ;
2935 }
3036
37+ ctx . bree . on ( 'worker message' , ( data ) => {
38+ ctx . sse . send ( { event : 'worker message' , data : JSON . stringify ( data ) } ) ;
39+ } ) ;
40+
41+ ctx . bree . on ( 'worker error' , ( data ) => {
42+ ctx . sse . send ( { event : 'worker error' , data : JSON . stringify ( data ) } ) ;
43+ } ) ;
44+
3145 ctx . sse . on ( 'close' , ( ) => {
3246 ctx . logger . error ( 'SSE closed' ) ;
3347
48+ // remove from conns array)
49+ const idx = conns . findIndex ( ( conn ) => conn . id === uuid ) ;
50+
51+ if ( idx > 0 ) {
52+ conns . splice ( idx , 1 ) ;
53+ }
54+
3455 clearInterval ( interval ) ;
3556 } ) ;
57+
58+ // bump uuid
59+ uuid ++ ;
3660 }
3761}
3862
Original file line number Diff line number Diff line change @@ -18,7 +18,36 @@ function plugin(opts, Bree) {
1818 const oldInit = Bree . prototype . init ;
1919
2020 Bree . prototype . init = async function ( ) {
21- await oldInit . bind ( this ) ( ) ;
21+ // hook error handler and message handler
22+ const oldErrorHandler = this . config . errorHandler ;
23+ const oldWorkerMessageHandler = this . config . workerMessageHandler ;
24+
25+ this . config . errorHandler = function ( error , data ) {
26+ if ( oldErrorHandler ) {
27+ oldErrorHandler . call ( this , error , data ) ;
28+ }
29+
30+ this . emit ( 'worker error' , {
31+ error,
32+ name : data ?. name ,
33+ data : data ? JSON . stringify ( data ) : undefined
34+ } ) ;
35+ } ;
36+
37+ this . config . errorHandler = this . config . errorHandler . bind ( this ) ;
38+
39+ this . config . workerMessageHandler = function ( data ) {
40+ if ( oldWorkerMessageHandler ) {
41+ oldWorkerMessageHandler . call ( this , data ) ;
42+ }
43+
44+ this . emit ( 'worker message' , data ) ;
45+ } ;
46+
47+ this . config . workerMessageHandler =
48+ this . config . workerMessageHandler . bind ( this ) ;
49+
50+ await oldInit . call ( this ) ;
2251
2352 // assign bree to the context
2453 api . app . context . bree = this ;
You can’t perform that action at this time.
0 commit comments