7
7
"strconv"
8
8
"strings"
9
9
"sync"
10
+ "sync/atomic"
10
11
"time"
11
12
12
13
"github.com/gptscript-ai/gptscript/pkg/runner"
@@ -22,7 +23,8 @@ type Event struct {
22
23
}
23
24
24
25
type fileFactory struct {
25
- file * os.File
26
+ file * os.File
27
+ runningCount atomic.Int32
26
28
}
27
29
28
30
// NewFileFactory creates a new monitor factory that writes events to the location specified.
@@ -44,23 +46,26 @@ func NewFileFactory(loc string) (runner.MonitorFactory, error) {
44
46
45
47
file = os .NewFile (uintptr (fd ), "events" )
46
48
} else {
47
- file , err = os .OpenFile (loc , os .O_WRONLY | os .O_CREATE , 0 )
49
+ file , err = os .OpenFile (loc , os .O_WRONLY | os .O_CREATE , 0644 )
48
50
if err != nil {
49
51
return nil , err
50
52
}
51
53
}
52
54
53
55
return & fileFactory {
54
- file : file ,
56
+ file : file ,
57
+ runningCount : atomic.Int32 {},
55
58
}, nil
56
59
}
57
60
58
- func (s fileFactory ) Start (_ context.Context , prg * types.Program , env []string , input string ) (runner.Monitor , error ) {
61
+ func (s * fileFactory ) Start (_ context.Context , prg * types.Program , env []string , input string ) (runner.Monitor , error ) {
62
+ s .runningCount .Add (1 )
59
63
fd := & fd {
60
- prj : prg ,
61
- env : env ,
62
- input : input ,
63
- file : s .file ,
64
+ prj : prg ,
65
+ env : env ,
66
+ input : input ,
67
+ file : s .file ,
68
+ factory : s ,
64
69
}
65
70
66
71
fd .event (Event {
@@ -74,12 +79,21 @@ func (s fileFactory) Start(_ context.Context, prg *types.Program, env []string,
74
79
return fd , nil
75
80
}
76
81
82
+ func (s * fileFactory ) close () {
83
+ if count := s .runningCount .Add (- 1 ); count == 0 {
84
+ if err := s .file .Close (); err != nil {
85
+ log .Errorf ("error closing monitor file: %v" , err )
86
+ }
87
+ }
88
+ }
89
+
77
90
type fd struct {
78
91
prj * types.Program
79
92
env []string
80
93
input string
81
94
file * os.File
82
95
runLock sync.Mutex
96
+ factory * fileFactory
83
97
}
84
98
85
99
func (f * fd ) Event (event runner.Event ) {
@@ -117,9 +131,7 @@ func (f *fd) Stop(output string, err error) {
117
131
}
118
132
119
133
f .event (e )
120
- if err = f .file .Close (); err != nil {
121
- log .Errorf ("Failed to close file: %v" , err )
122
- }
134
+ f .factory .close ()
123
135
}
124
136
125
137
func (f * fd ) Pause () func () {
0 commit comments