| 1 | package cage |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "regexp" |
| 9 | "sync" |
| 10 | "time" |
| 11 | ) |
| 12 | |
| 13 | const JobEnv = "CLAUDE_CAGE_JOB_ID" |
| 14 | |
| 15 | var jobIDPattern = regexp.MustCompile(`^[a-f0-9]{12,64}$`) |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | func RequestJobStop(profile, id string) error { |
| 21 | if !jobIDPattern.MatchString(id) { |
| 22 | return errors.New("invalid Cage job identifier") |
| 23 | } |
| 24 | dir := filepath.Join(profile, "stopped-jobs") |
| 25 | if err := os.MkdirAll(dir, 0700); err != nil { |
| 26 | return err |
| 27 | } |
| 28 | f, err := os.OpenFile(filepath.Join(dir, id), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) |
| 29 | if os.IsExist(err) { |
| 30 | return nil |
| 31 | } |
| 32 | if err != nil { |
| 33 | return err |
| 34 | } |
| 35 | return f.Close() |
| 36 | } |
| 37 | |
| 38 | func InstanceJobID(state, name string) string { |
| 39 | if filepath.Base(name) != name { |
| 40 | return "" |
| 41 | } |
| 42 | data, err := os.ReadFile(filepath.Join(state, "lima", name, "cage-running.json")) |
| 43 | if err != nil || len(data) > 4096 { |
| 44 | return "" |
| 45 | } |
| 46 | var record runningProfile |
| 47 | if json.Unmarshal(data, &record) != nil || !jobIDPattern.MatchString(record.JobID) { |
| 48 | return "" |
| 49 | } |
| 50 | return record.JobID |
| 51 | } |
| 52 | |
| 53 | |
| 54 | |
| 55 | func WatchJobStop(profile, id string, onStop func()) (func(), error) { |
| 56 | if id == "" { |
| 57 | return func() {}, nil |
| 58 | } |
| 59 | if !jobIDPattern.MatchString(id) { |
| 60 | return nil, errors.New("invalid Cage job identifier") |
| 61 | } |
| 62 | path := filepath.Join(profile, "stopped-jobs", id) |
| 63 | stopped := func() bool { _, err := os.Lstat(path); return err == nil || !os.IsNotExist(err) } |
| 64 | if stopped() { |
| 65 | return nil, errors.New("Cage startup was cancelled") |
| 66 | } |
| 67 | done := make(chan struct{}) |
| 68 | var once sync.Once |
| 69 | stop := func() { once.Do(func() { close(done) }) } |
| 70 | go func() { |
| 71 | ticker := time.NewTicker(100 * time.Millisecond) |
| 72 | defer ticker.Stop() |
| 73 | for { |
| 74 | select { |
| 75 | case <-done: |
| 76 | return |
| 77 | case <-ticker.C: |
| 78 | if stopped() { |
| 79 | onStop() |
| 80 | return |
| 81 | } |
| 82 | } |
| 83 | } |
| 84 | }() |
| 85 | return stop, nil |
| 86 | } |