|
| 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 = &Registry{ |
| 18 | + functions: make(map[string]ResourcesFunction), |
| 19 | + } |
| 20 | + |
| 21 | + _ ResourceRegistry = (*Registry)(nil) |
| 22 | +) |
| 23 | + |
| 24 | +// ResourcesFunction is a function used to return the domain resources. |
| 25 | +type ( |
| 26 | + ResourcesFunction func(context.Context) (any, error) |
| 27 | + |
| 28 | + // ResourceRegistry is the interface for the global Registry of domain functions. |
| 29 | + ResourceRegistry interface { |
| 30 | + // Register the given domain function in the Registry. |
| 31 | + Register(name string, f ResourcesFunction) error |
| 32 | + // Unregister the given domain function from the Registry. |
| 33 | + Unregister(name string) |
| 34 | + // Run the domain function with the given name. |
| 35 | + Run(ctx context.Context, name string) (any, error) |
| 36 | + } |
| 37 | +) |
| 38 | + |
| 39 | +// GlobalRegistry returns the global Registry of domain functions. |
| 40 | +func GlobalRegistry() ResourceRegistry { return globalRegistry } |
| 41 | + |
| 42 | +// Registry is a thread-safe collection of domain functions. |
| 43 | +type Registry struct { |
| 44 | + mu sync.RWMutex |
| 45 | + functions map[string]ResourcesFunction |
| 46 | +} |
| 47 | + |
| 48 | +// Register the given domain function in the Registry. |
| 49 | +func (r *Registry) Register(name string, f ResourcesFunction) error { |
| 50 | + r.mu.Lock() |
| 51 | + defer r.mu.Unlock() |
| 52 | + |
| 53 | + if _, ok := r.functions[name]; ok { |
| 54 | + return fmt.Errorf("%w: %s", ErrAlreadyRegistered, name) |
| 55 | + } |
| 56 | + r.functions[name] = f |
| 57 | + return nil |
| 58 | +} |
| 59 | + |
| 60 | +// Unregister the given domain function from the Registry. |
| 61 | +func (r *Registry) Unregister(name string) { |
| 62 | + r.mu.Lock() |
| 63 | + defer r.mu.Unlock() |
| 64 | + |
| 65 | + delete(r.functions, name) |
| 66 | +} |
| 67 | + |
| 68 | +// Run the domain function with the given name. |
| 69 | +func (r *Registry) Run(ctx context.Context, name string) (any, error) { |
| 70 | + r.mu.RLock() |
| 71 | + defer r.mu.RUnlock() |
| 72 | + |
| 73 | + f, ok := r.functions[name] |
| 74 | + if !ok { |
| 75 | + return nil, fmt.Errorf("%w: %s", ErrNotFound, name) |
| 76 | + } |
| 77 | + return f(ctx) |
| 78 | +} |
0 commit comments