| 1 | package boot |
| 2 | |
| 3 | import ( |
| 4 | "io" |
| 5 | "os" |
| 6 | "strings" |
| 7 | |
| 8 | "reasonix/internal/skill" |
| 9 | "reasonix/internal/skill/skillwatch" |
| 10 | ) |
| 11 | |
| 12 | // watchSkillsEnabled reports whether production controllers own physical |
| 13 | // watchers. Package fixtures opt out so they cannot exhaust descriptors, while |
| 14 | // store watcher tests opt in explicitly. |
| 15 | func watchSkillsEnabled() bool { |
| 16 | return !strings.HasSuffix(strings.TrimSuffix(os.Args[0], ".exe"), ".test") |
| 17 | } |
| 18 | |
| 19 | func newSkillWatchService(enabled bool, stderr io.Writer) *skillwatch.Service { |
| 20 | if !enabled { |
| 21 | return nil |
| 22 | } |
| 23 | return skillwatch.NewService(skillwatch.Options{Stderr: stderr}) |
| 24 | } |
| 25 | |
| 26 | // buildSkillWatchService picks the one watch service a build's enabled and |
| 27 | // all-skill stores share: the caller's host-lifetime service when supplied |
| 28 | // (hostOwned), otherwise one this build owns and closes. |
| 29 | func buildSkillWatchService(shared *skillwatch.Service, enabled bool, stderr io.Writer) (svc *skillwatch.Service, hostOwned bool) { |
| 30 | if shared != nil { |
| 31 | return shared, true |
| 32 | } |
| 33 | return newSkillWatchService(enabled, stderr), false |
| 34 | } |
| 35 | |
| 36 | // NewHostSkillWatchService returns a caller-owned watcher that every controller |
| 37 | // on one host can share, or nil when watching is disabled. Pass it as |
| 38 | // Options.SharedSkillWatchService and close it once the host's controllers are |
| 39 | // gone: Build then subscribes each controller to it instead of creating one |
| 40 | // service — and one helper process — per build. |
| 41 | func NewHostSkillWatchService(stderr io.Writer) *skillwatch.Service { |
| 42 | return newSkillWatchService(watchSkillsEnabled(), stderr) |
| 43 | } |
| 44 | |
| 45 | // closeSkillsWithWatcher closes this build's skill stores, and the watch service |
| 46 | // only when this build owns it. A caller-supplied service outlives the build: |
| 47 | // the caller closes it, and closing it here would tear down the helper process |
| 48 | // other controllers on the same host are still watching through. |
| 49 | func closeSkillsWithWatcher(primary, all *skill.Store, watchService **skillwatch.Service, hostOwned bool) { |
| 50 | closeSkillStores(primary, all) |
| 51 | if *watchService != nil && !hostOwned { |
| 52 | _ = (*watchService).Close() |
| 53 | } |
| 54 | *watchService = nil |
| 55 | } |
| 56 |