wails/v3/pkg/application/single_instance.go
Lea Anthony a06d55804c
perf(v3): optimize JSON processing and reduce allocations in hot paths (#4843)
* perf(v3): optimize JSON processing and reduce allocations in hot paths

- Switch to goccy/go-json for method binding, events, and HTTP transport
  (21-63% faster, 40-60% less memory for method calls)
- Optimize BoundMethod struct layout to reduce padding (144 -> 136 bytes)
- Cache isVariadic flag at registration to avoid reflect call per invocation
- Use stack-allocated buffer for method arguments (<=8 args)
- Optimize result collection to avoid slice allocation for single return values
- Use sync.Map for MIME cache to improve concurrent read performance
- Use buffer pool for HTTP transport request body reading
- Lazily allocate CloseNotify channel in content type sniffer
- Remove debug CSS logging from asset server
- Add comprehensive benchmark tests (build tag: bench)

Performance improvements for BoundMethod.Call:
- SimpleCall:   1290ns -> 930ns (28% faster), 240B -> 80B (67% less memory)
- ComplexCall:  10500ns -> 3900ns (63% faster), 1192B -> 1020B (14% less)
- VariadicCall: 3460ns -> 1600ns (54% faster), 512B -> 289B (44% less)

* perf(v3): add max size limit to buffer pool to prevent memory bloat

Buffers larger than 512KB are not returned to the pool, allowing GC
to reclaim memory after large requests (e.g., base64 encoded images).

* perf(v3): remove mimetype library dependency, saving ~208KB binary size

- Replace github.com/wailsapp/mimetype with expanded extension map + stdlib
- Expand MIME type map from 16 to 50+ common web formats (fonts, audio, video, etc.)
- Add comprehensive test suite validating MIME detection for all web formats
- Use http.DetectContentType as fallback for unknown extensions
- Actual binary size reduction: 1.2MB (11MB -> 9.8MB in test app)

* perf(v3): migrate all runtime code to goccy/go-json

Migrate remaining encoding/json usages to goccy/go-json in:
- pkg/application (android, darwin, ios, single_instance, webview_window)
- pkg/services (kvstore, notifications on all platforms)
- internal/assetserver/webview (request/response handling)
- internal/runtime and internal/capabilities

Note: encoding/json (110KB) remains in binary because:
1. goccy/go-json imports it for interface compatibility (json.Marshaler, etc.)
2. log/slog (stdlib) uses it for JSON output

The performance benefit is in the hot paths which now use the faster library.

* perf(v3): replace gopkg.in/ini.v1 with minimal .desktop file parser

Replace the gopkg.in/ini.v1 dependency with a purpose-built minimal parser
for Linux .desktop files.

The new parser:
- Only extracts the Exec key from [Desktop Entry] section (all we need)
- Follows the Desktop Entry Specification
- Has comprehensive test coverage (40 tests) including:
  - All major file managers (Nautilus, Dolphin, Thunar, PCManFM, Caja, Nemo)
  - Edge cases (UTF-8, special chars, comments, empty files, etc.)
  - Buffer limit handling

Binary size reduction: 45KB (10.22MB -> 10.18MB)

* perf(v3): remove samber/lo from runtime code, saving ~310KB binary size

Replace samber/lo with Go 1.21+ stdlib slices package and minimal internal
helpers in all runtime code paths. This removes 80 transitive dependencies
from the production binary.

Changes:
- Create internal/sliceutil package with Unique and FindMapKey helpers
- Replace lo.Without with slices.DeleteFunc in event handling
- Replace lo.Ternary with inline if/else in Windows code
- Replace lo.Uniq with sliceutil.Unique for feature flags
- Replace lo.FindKey with sliceutil.FindMapKey for method aliases
- Replace lo.Filter with slices.DeleteFunc in event listeners
- Replace lo.Must with inline panic in w32 package

Binary size: 10.18MB -> 9.87MB (~310KB / 3% reduction)

Note: CLI tools still use samber/lo since they don't affect
production binary size. The application_debug.go file also
retains lo usage as it has //go:build !production tag.

* fix: address CodeRabbit review comments

- Use application/x-typescript MIME type (not IANA-registered text/typescript)
- Fix potential panic in mimetype_stdlib_test.go for short MIME strings
- Use cached isVariadic flag in bindings_optimized_bench_test.go

* fix: initialize goccy/go-json decoder early to fix Windows test failure

On Windows, goccy/go-json's type address calculation can fail if the
decoder is first invoked during test execution rather than at init time.
Force early initialization by unmarshaling a []int during package init.

See: https://github.com/goccy/go-json/issues/474

* 📝 Add docstrings to `v3/performance-improvements` (#4844)

* fix: initialize goccy/go-json decoder early to fix Windows test failure

On Windows, goccy/go-json's type address calculation can fail if the
decoder is first invoked during test execution rather than at init time.
Force early initialization by unmarshaling a []int during package init.

See: https://github.com/goccy/go-json/issues/474

* 📝 Add docstrings to `v3/performance-improvements`

Docstrings generation was requested by @leaanthony.

* https://github.com/wailsapp/wails/pull/4843#issuecomment-3703472562

The following files were modified:

* `v3/internal/assetserver/common.go`
* `v3/internal/assetserver/content_type_sniffer.go`
* `v3/internal/assetserver/mimecache.go`
* `v3/internal/fileexplorer/desktopfile.go`
* `v3/internal/fileexplorer/fileexplorer_linux.go`
* `v3/internal/sliceutil/sliceutil.go`
* `v3/pkg/application/application_ios.go`
* `v3/pkg/application/bindings.go`
* `v3/pkg/application/ios_runtime_ios.go`
* `v3/pkg/w32/window.go`

---------

Co-authored-by: Lea Anthony <lea.anthony@gmail.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-01-02 07:03:36 +11:00

216 lines
5.2 KiB
Go

package application
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"os"
"path/filepath"
"sync"
json "github.com/goccy/go-json"
)
var alreadyRunningError = errors.New("application is already running")
var secondInstanceBuffer = make(chan string, 1)
var once sync.Once
// SecondInstanceData contains information about the second instance launch
type SecondInstanceData struct {
Args []string `json:"args"`
WorkingDir string `json:"workingDir"`
AdditionalData map[string]string `json:"additionalData,omitempty"`
}
// SingleInstanceOptions defines options for single instance functionality
type SingleInstanceOptions struct {
// UniqueID is used to identify the application instance
// This should be unique per application, e.g. "com.myapp.myapplication"
UniqueID string
// OnSecondInstanceLaunch is called when a second instance of the application is launched
// The callback receives data about the second instance launch
OnSecondInstanceLaunch func(data SecondInstanceData)
// AdditionalData allows passing custom data from second instance to first
AdditionalData map[string]string
// ExitCode is the exit code to use when the second instance exits
ExitCode int
// EncryptionKey is a 32-byte key used for encrypting instance communication
// If not provided (zero array), data will be sent unencrypted
EncryptionKey [32]byte
}
// platformLock is the interface that platform-specific lock implementations must implement
type platformLock interface {
// acquire attempts to acquire the lock
acquire(uniqueID string) error
// release releases the lock and cleans up resources
release()
// notify sends data to the first instance
notify(data string) error
}
// singleInstanceManager handles the single instance functionality
type singleInstanceManager struct {
options *SingleInstanceOptions
lock platformLock
app *App
}
func newSingleInstanceManager(app *App, options *SingleInstanceOptions) (*singleInstanceManager, error) {
if options == nil {
return nil, nil
}
manager := &singleInstanceManager{
options: options,
app: app,
}
// Launch second instance data listener
once.Do(func() {
go func() {
defer handlePanic()
for encryptedData := range secondInstanceBuffer {
var secondInstanceData SecondInstanceData
var jsonData []byte
var err error
// Check if encryption key is non-zero
var zeroKey [32]byte
if options.EncryptionKey != zeroKey {
// Try to decrypt the data
jsonData, err = decrypt(options.EncryptionKey, encryptedData)
if err != nil {
continue // Skip invalid data
}
} else {
jsonData = []byte(encryptedData)
}
if err := json.Unmarshal(jsonData, &secondInstanceData); err == nil && manager.options.OnSecondInstanceLaunch != nil {
manager.options.OnSecondInstanceLaunch(secondInstanceData)
}
}
}()
})
// Create platform-specific lock
lock, err := newPlatformLock(manager)
if err != nil {
return nil, err
}
manager.lock = lock
// Try to acquire the lock
err = lock.acquire(options.UniqueID)
if err != nil {
return manager, err
}
return manager, nil
}
func (m *singleInstanceManager) cleanup() {
if m == nil || m.lock == nil {
return
}
m.lock.release()
}
// encrypt encrypts data using AES-256-GCM
func encrypt(key [32]byte, plaintext []byte) (string, error) {
block, err := aes.NewCipher(key[:])
if err != nil {
return "", err
}
nonce := make([]byte, 12)
if _, err := rand.Read(nonce); err != nil {
return "", err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
encrypted := append(nonce, ciphertext...)
return base64.StdEncoding.EncodeToString(encrypted), nil
}
// decrypt decrypts data using AES-256-GCM
func decrypt(key [32]byte, encrypted string) ([]byte, error) {
data, err := base64.StdEncoding.DecodeString(encrypted)
if err != nil {
return nil, err
}
if len(data) < 12 {
return nil, errors.New("invalid encrypted data")
}
block, err := aes.NewCipher(key[:])
if err != nil {
return nil, err
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
nonce := data[:12]
ciphertext := data[12:]
return aesgcm.Open(nil, nonce, ciphertext, nil)
}
// notifyFirstInstance sends data to the first instance of the application
func (m *singleInstanceManager) notifyFirstInstance() error {
data := SecondInstanceData{
Args: os.Args,
WorkingDir: getCurrentWorkingDir(),
AdditionalData: m.options.AdditionalData,
}
serialized, err := json.Marshal(data)
if err != nil {
return err
}
// Check if encryption key is non-zero
var zeroKey [32]byte
if m.options.EncryptionKey != zeroKey {
encrypted, err := encrypt(m.options.EncryptionKey, serialized)
if err != nil {
return err
}
return m.lock.notify(encrypted)
}
return m.lock.notify(string(serialized))
}
func getCurrentWorkingDir() string {
dir, err := os.Getwd()
if err != nil {
return ""
}
return dir
}
// getLockPath returns the path to the lock file for Unix systems
func getLockPath(uniqueID string) string {
// Use system temp directory
tmpDir := os.TempDir()
lockFileName := uniqueID + ".lock"
return filepath.Join(tmpDir, lockFileName)
}