|
| 1 | +// Copyright (c) Tetrate, Inc 2025 All Rights Reserved. |
| 2 | + |
| 3 | +package inprocess |
| 4 | + |
| 5 | +import ( |
| 6 | + "context" |
| 7 | + "errors" |
| 8 | + "fmt" |
| 9 | + "sync" |
| 10 | +) |
| 11 | + |
| 12 | +var ( |
| 13 | + ErrAlreadyRegistered = errors.New("already registered") |
| 14 | + ErrNotFound = errors.New("not found") |
| 15 | + |
| 16 | + // globalRegistry is the global registry of domain functions. |
| 17 | + globalRegistry = NewRegistry() |
| 18 | + |
| 19 | + _ Registry = (*registry)(nil) |
| 20 | +) |
| 21 | + |
| 22 | +// ResourcesFunction is a function used to return the domain resources. |
| 23 | +type ( |
| 24 | + ResourcesFunction func(context.Context) (any, error) |
| 25 | + |
| 26 | + // Registry is the interface for the global registry of domain functions. |
| 27 | + Registry interface { |
| 28 | + // Register the given domain function in the registry. |
| 29 | + Register(name string, f ResourcesFunction) error |
| 30 | + // Unregister the given domain function from the registry. |
| 31 | + Unregister(name string) |
| 32 | + // Run the domain function with the given name. |
| 33 | + Run(ctx context.Context, name string) (any, error) |
| 34 | + } |
| 35 | +) |
| 36 | + |
| 37 | +// GlobalRegistry returns the global registry of domain functions. |
| 38 | +func GlobalRegistry() Registry { return globalRegistry } |
| 39 | + |
| 40 | +// NewRegistry creates a new registry of domain functions. |
| 41 | +func NewRegistry() Registry { |
| 42 | + return ®istry{functions: make(map[string]ResourcesFunction)} |
| 43 | +} |
| 44 | + |
| 45 | +// registry is a thread-safe collection of domain functions. |
| 46 | +type registry struct { |
| 47 | + mu sync.RWMutex |
| 48 | + functions map[string]ResourcesFunction |
| 49 | +} |
| 50 | + |
| 51 | +// Register the given domain function in the registry. |
| 52 | +func (r *registry) Register(name string, f ResourcesFunction) error { |
| 53 | + r.mu.Lock() |
| 54 | + defer r.mu.Unlock() |
| 55 | + |
| 56 | + if _, ok := r.functions[name]; ok { |
| 57 | + return fmt.Errorf("%w: %s", ErrAlreadyRegistered, name) |
| 58 | + } |
| 59 | + r.functions[name] = f |
| 60 | + return nil |
| 61 | +} |
| 62 | + |
| 63 | +// Unregister the given domain function from the registry. |
| 64 | +func (r *registry) Unregister(name string) { |
| 65 | + r.mu.Lock() |
| 66 | + defer r.mu.Unlock() |
| 67 | + |
| 68 | + delete(r.functions, name) |
| 69 | +} |
| 70 | + |
| 71 | +// Run the domain function with the given name. |
| 72 | +func (r *registry) Run(ctx context.Context, name string) (any, error) { |
| 73 | + r.mu.RLock() |
| 74 | + defer r.mu.RUnlock() |
| 75 | + |
| 76 | + f, ok := r.functions[name] |
| 77 | + if !ok { |
| 78 | + return nil, fmt.Errorf("%w: %s", ErrNotFound, name) |
| 79 | + } |
| 80 | + return f(ctx) |
| 81 | +} |
0 commit comments