@@ -24,7 +24,9 @@ func baseSSEService[R any](
2424 generator func () (* stream.Stream [R ], error ),
2525 ctx * gin.Context ,
2626 max_timeout_seconds int ,
27+ onCompletion func (status string , duration float64 ),
2728) {
29+ startTime := time .Now ()
2830 writer := ctx .Writer
2931 writer .WriteHeader (200 )
3032 writer .Header ().Set ("Content-Type" , "text/event-stream" )
@@ -47,6 +49,10 @@ func baseSSEService[R any](
4749
4850 if err != nil {
4951 writeData (exception .InternalServerError (err ).ToResponse ())
52+ duration := time .Since (startTime ).Seconds ()
53+ if onCompletion != nil {
54+ onCompletion ("error" , duration )
55+ }
5056 close (done )
5157 return
5258 }
@@ -55,15 +61,22 @@ func baseSSEService[R any](
5561 routinepkg .RoutineLabelKeyModule : "service" ,
5662 routinepkg .RoutineLabelKeyMethod : "baseSSEService" ,
5763 }, func () {
64+ status := "success"
5865 for pluginDaemonResponse .Next () {
5966 chunk , err := pluginDaemonResponse .Read ()
6067 if err != nil {
6168 writeData (exception .InvokePluginError (err ).ToResponse ())
69+ status = "error"
6270 break
6371 }
6472 writeData (entities .NewSuccessResponse (chunk ))
6573 }
6674
75+ duration := time .Since (startTime ).Seconds ()
76+ if onCompletion != nil {
77+ onCompletion (status , duration )
78+ }
79+
6780 if atomic .CompareAndSwapInt32 (doneClosed , 0 , 1 ) {
6881 close (done )
6982 }
@@ -79,11 +92,19 @@ func baseSSEService[R any](
7992 select {
8093 case <- writer .CloseNotify ():
8194 pluginDaemonResponse .Close ()
95+ duration := time .Since (startTime ).Seconds ()
96+ if onCompletion != nil {
97+ onCompletion ("client_disconnect" , duration )
98+ }
8299 return
83100 case <- done :
84101 return
85102 case <- timer .C :
86103 writeData (exception .InternalServerError (errors .New ("killed by timeout" )).ToResponse ())
104+ duration := time .Since (startTime ).Seconds ()
105+ if onCompletion != nil {
106+ onCompletion ("timeout" , duration )
107+ }
87108 if atomic .CompareAndSwapInt32 (doneClosed , 0 , 1 ) {
88109 close (done )
89110 }
@@ -128,13 +149,12 @@ func baseSSEWithSession[T any, R any](
128149 runtimeType ,
129150 ).Inc ()
130151
131- stream , err := generator (session )
132-
133- duration := time .Since (startTime ).Seconds ()
134- status := "success"
135- if err != nil {
136- status = "error"
137- }
152+ return generator (session )
153+ },
154+ ctx ,
155+ max_timeout_seconds ,
156+ func (status string , duration float64 ) {
157+ pluginID , runtimeType := getPluginMetricLabels (session )
138158
139159 metrics .PluginInvocationsTotal .WithLabelValues (
140160 pluginID ,
@@ -155,11 +175,7 @@ func baseSSEWithSession[T any, R any](
155175 string (access_type ),
156176 runtimeType ,
157177 ).Dec ()
158-
159- return stream , err
160178 },
161- ctx ,
162- max_timeout_seconds ,
163179 )
164180}
165181
0 commit comments