Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 36 additions & 3 deletions internal/attention/notifications_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,10 @@ type macNotificationCenter struct {
dispatchAsync func(uintptr, objc.Block)
}

// NSApplicationActivationPolicyProhibited: process-local LSBackgroundOnly behavior.
// UserNotifications uses the bundle identity and system UI, not app windows.
const serviceActivationPolicy int64 = 2

func startMacNotifications(exe string) (objc.ID, *macNotificationCenter, error) {
for _, framework := range []string{"AppKit", "UserNotifications"} {
if _, err := purego.Dlopen("/System/Library/Frameworks/"+framework+".framework/"+framework, purego.RTLD_GLOBAL|purego.RTLD_NOW); err != nil {
Expand All @@ -152,16 +156,26 @@ func startMacNotifications(exe string) (objc.ID, *macNotificationCenter, error)
if err := macBundleIdentity(); err != nil {
return 0, nil, err
}
app := nsClass("NSApplication").Send(objc.RegisterName("sharedApplication"))
// Accessory app: no Dock icon or window, while retaining Driga's bundle identity.
app.Send(objc.RegisterName("setActivationPolicy:"), int64(1))
c := &macNotificationCenter{center: nsClass("UNUserNotificationCenter").Send(objc.RegisterName("currentNotificationCenter"))}
var err error
c.queue, err = purego.Dlsym(purego.RTLD_DEFAULT, "_dispatch_main_q")
if err != nil {
return 0, nil, err
}
purego.RegisterLibFunc(&c.dispatchAsync, purego.RTLD_DEFAULT, "dispatch_async")
var app objc.ID
c.onMainSync(func() {
app = nsClass("NSApplication").Send(objc.RegisterName("sharedApplication"))
// Accessory still permits activation and can swallow open -a Driga.
// Do not set LSBackgroundOnly in the shared bundle: the GUI needs windows.
if !objc.Send[bool](app, objc.RegisterName("setActivationPolicy:"), serviceActivationPolicy) {
err = fmt.Errorf("cannot make notification service background-only")
}
})
if err != nil {
return 0, nil, err
}

delegate, err := objc.RegisterClass("DrigaNotificationDelegate", objc.GetClass("NSObject"),
[]*objc.Protocol{objc.GetProtocol("UNUserNotificationCenterDelegate")}, nil, []objc.MethodDef{
{Cmd: objc.RegisterName("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:"),
Expand Down Expand Up @@ -205,6 +219,25 @@ func (c *macNotificationCenter) onMain(fn func()) {
block.Release()
}

// onMainSync runs inline during locked-main startup, before the run loop exists.
// A worker caller requires the main run loop to be running and waits for it.
func (c *macNotificationCenter) onMainSync(fn func()) {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
main := objc.Send[bool](nsClass("NSThread"), objc.RegisterName("isMainThread"))
dispatchMainAndWait(main, c.onMain, fn)
}

func dispatchMainAndWait(main bool, enqueue func(func()), fn func()) {
if main {
fn()
return
}
done := make(chan struct{})
enqueue(func() { defer close(done); fn() })
<-done
}

func nativeNotificationError(err objc.ID) error {
if err == 0 {
return nil
Expand Down
46 changes: 46 additions & 0 deletions internal/attention/notifications_darwin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package attention

import (
"testing"
"time"

"github.com/ebitengine/purego/objc"
)
Expand All @@ -26,3 +27,48 @@ func TestNativeCompletionBlockABI(t *testing.T) {
t.Fatal(options)
}
}

func TestServiceActivationPolicy(t *testing.T) {
if serviceActivationPolicy != 2 {
t.Fatal("service must be background-only (Prohibited)")
}
}

func TestDispatchMainAndWait(t *testing.T) {
t.Run("main thread runs inline", func(t *testing.T) {
ran := false
dispatchMainAndWait(true, func(func()) { t.Fatal("dispatching on main would deadlock before run loop starts") }, func() { ran = true })
if !ran {
t.Fatal("not run synchronously")
}
})
t.Run("worker waits for main queue", func(t *testing.T) {
queued := make(chan func(), 1)
done := make(chan struct{})
ran := false
go func() {
dispatchMainAndWait(false, func(fn func()) { queued <- fn }, func() { ran = true })
close(done)
}()
var fn func()
select {
case fn = <-queued:
case <-time.After(time.Second):
t.Fatal("not queued")
}
select {
case <-done:
t.Fatal("returned before main queue executed")
default:
}
fn()
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("did not return")
}
if !ran {
t.Fatal("callback not run")
}
})
}
1 change: 1 addition & 0 deletions internal/cleanup/cleanup.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ type Candidate struct {
Evidence []string `json:"evidence"`
Status string `json:"status"`
Size int64 `json:"size_bytes"`
SizeKnown bool `json:"size_known"`
SizeCapped bool `json:"size_capped"`
Ignored []IgnoredPath `json:"ignored"`
head, defaultHead, upstream, upstreamHead string
Expand Down
1 change: 1 addition & 0 deletions internal/cleanup/size.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ func Measure(ctx context.Context, c Candidate, now time.Time) (Candidate, error)
} else {
c.Size, c.SizeCapped, err = WalkSize(ctx, c.Path)
}
c.SizeKnown = err == nil
for i := range c.Ignored {
var capped bool
var ignoredErr error
Expand Down
120 changes: 120 additions & 0 deletions internal/cleanup/size_cache.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
package cleanup

import (
"context"
"os"
"sync"
"time"
)

const sizeRefreshInterval = 10 * time.Minute

type sizeKey struct {
id, path string
mtime int64
}
type sizeEntry struct {
size int64
known, capped, pending, running bool
at time.Time
cancel context.CancelFunc
}

// SizeCache lazily measures ready candidates, with at most two directory walks.
// Snapshot only stats roots and copies cached values; recursive IO runs outside
// the caller's context. The zero value is ready to use. Do not copy after use.
type SizeCache struct {
mu sync.Mutex
entries map[sizeKey]*sizeEntry
workers int
// walk is overridden by tests to control completion without sleeps.
walk func(context.Context, string) (int64, bool, error)
}

func (c *SizeCache) Snapshot(rows []Candidate) []Candidate {
out := append([]Candidate(nil), rows...)
c.mu.Lock()
defer c.mu.Unlock()
if c.entries == nil {
c.entries = make(map[sizeKey]*sizeEntry)
}
live := make(map[sizeKey]bool)
now := time.Now()
for i := range out {
row := &out[i]
if row.Status != "ready" {
continue
}
row.Size, row.SizeKnown, row.SizeCapped = 0, false, false
info, err := os.Lstat(row.Path)
if err != nil {
continue
}
key := sizeKey{row.ID, row.Path, info.ModTime().UnixNano()}
live[key] = true
entry := c.entries[key]
if entry == nil {
entry = &sizeEntry{pending: true}
c.entries[key] = entry
} else if !entry.pending && !entry.running && now.Sub(entry.at) >= sizeRefreshInterval {
entry.pending, entry.known = true, false
}
row.Size, row.SizeKnown, row.SizeCapped = entry.size, entry.known, entry.capped
}
// Removal also cancels in-flight work. Its completion cannot resurrect a row.
for key, entry := range c.entries {
if !live[key] {
if entry.cancel != nil {
entry.cancel()
}
delete(c.entries, key)
}
}
pending := 0
for _, entry := range c.entries {
if entry.pending {
pending++
}
}
for c.workers < 2 && pending > 0 {
c.workers++
pending--
go c.work()
}
return out
}

func (c *SizeCache) work() {
for {
c.mu.Lock()
var key sizeKey
var entry *sizeEntry
for k, e := range c.entries {
if e.pending {
key, entry = k, e
break
}
}
if entry == nil {
c.workers--
c.mu.Unlock()
return
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
entry.pending, entry.running, entry.cancel = false, true, cancel
walk := c.walk
if walk == nil {
walk = WalkSize
}
c.mu.Unlock()

size, capped, err := walk(ctx, key.path)
cancel()
c.mu.Lock()
if c.entries[key] == entry {
entry.size, entry.capped, entry.known = size, capped, err == nil
entry.at, entry.running, entry.cancel = time.Now(), false, nil
}
c.mu.Unlock()
}
}
74 changes: 74 additions & 0 deletions internal/cleanup/size_cache_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package cleanup

import (
"context"
"testing"
"time"
)

func filled(t *testing.T, cache *SizeCache, rows []Candidate) []Candidate {
t.Helper()
deadline := time.Now().Add(3 * time.Second)
for time.Now().Before(deadline) {
out := cache.Snapshot(rows)
ready := true
for _, c := range out {
if c.Status == "ready" && !c.SizeKnown {
ready = false
}
}
if ready {
return out
}
time.Sleep(time.Millisecond)
}
t.Fatal("size cache did not fill")
return nil
}

func TestSizeCacheBoundedAndCancelled(t *testing.T) {
started := make(chan struct{}, 10)
cache := SizeCache{walk: func(ctx context.Context, _ string) (int64, bool, error) {
started <- struct{}{}
<-ctx.Done()
return 12, true, nil
}}
rows := make([]Candidate, 6)
for i := range rows {
rows[i] = Candidate{ID: string(rune('a' + i)), Path: t.TempDir(), Status: "ready"}
}
cache.Snapshot(rows)
for range 2 {
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("walk not started")
}
}
cache.mu.Lock()
if cache.workers != 2 {
t.Fatalf("workers: %d", cache.workers)
}
cache.mu.Unlock()
cache.Snapshot(nil)
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) {
cache.mu.Lock()
done := cache.workers == 0 && len(cache.entries) == 0
cache.mu.Unlock()
if done {
return
}
time.Sleep(time.Millisecond)
}
t.Fatal("removed work was not cancelled")
}

func TestSizeCacheCapped(t *testing.T) {
cache := SizeCache{walk: func(context.Context, string) (int64, bool, error) { return 42, true, nil }}
rows := []Candidate{{ID: "cap", Path: t.TempDir(), Status: "ready"}}
out := filled(t, &cache, rows)
if out[0].Size != 42 || !out[0].SizeCapped {
t.Fatalf("lost lower bound: %+v", out)
}
}
Loading
Loading