mirror of
https://github.com/bitechdev/ResolveSpec.git
synced 2026-08-05 09:07:39 +00:00
Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 16cc7d350e | |||
| a172c73ab0 | |||
| ef28959c4d |
@@ -26,6 +26,18 @@ func TestResolveSortColumns(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestResolveSortColumnsDesc(t *testing.T) {
|
||||||
|
sort := []SortOption{
|
||||||
|
{Column: PrimaryKeySortColumn, Direction: "desc"},
|
||||||
|
}
|
||||||
|
|
||||||
|
got := ResolveSortColumns(sort, "id")
|
||||||
|
want := []SortOption{{Column: "id", Direction: "desc"}}
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Errorf("ResolveSortColumns() = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestResolveSortColumnsEmptyPK(t *testing.T) {
|
func TestResolveSortColumnsEmptyPK(t *testing.T) {
|
||||||
sort := []SortOption{
|
sort := []SortOption{
|
||||||
{Column: PrimaryKeySortColumn, Direction: "asc"},
|
{Column: PrimaryKeySortColumn, Direction: "asc"},
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
"sync"
|
"sync"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ModelRules defines the permissions and security settings for a model
|
// ModelRules defines the permissions and security settings for a model
|
||||||
@@ -59,12 +60,44 @@ func NewModelRegistry() *DefaultModelRegistry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// lockRetryAttempts/lockRetryDelay bound how long the try-lock helpers below
|
||||||
|
// will spin before giving up, so a contended registriesMutex can never hang
|
||||||
|
// a caller of GetDefaultRegistry/SetDefaultRegistry.
|
||||||
|
const (
|
||||||
|
lockRetryAttempts = 20
|
||||||
|
lockRetryDelay = 1 * time.Millisecond
|
||||||
|
)
|
||||||
|
|
||||||
|
// GetDefaultRegistry returns the current default registry. It uses a
|
||||||
|
// bounded TryRLock instead of a blocking RLock so it can never hang;
|
||||||
|
// if the lock can't be acquired in time it falls back to the last known
|
||||||
|
// value without synchronization.
|
||||||
func GetDefaultRegistry() *DefaultModelRegistry {
|
func GetDefaultRegistry() *DefaultModelRegistry {
|
||||||
|
for i := 0; i < lockRetryAttempts; i++ {
|
||||||
|
if registriesMutex.TryRLock() {
|
||||||
|
defer registriesMutex.RUnlock()
|
||||||
|
return defaultRegistry
|
||||||
|
}
|
||||||
|
time.Sleep(lockRetryDelay)
|
||||||
|
}
|
||||||
return defaultRegistry
|
return defaultRegistry
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetDefaultRegistry replaces the default registry. It uses a bounded
|
||||||
|
// TryLock instead of a blocking Lock so it can never hang; if the lock
|
||||||
|
// can't be acquired in time the call is a no-op.
|
||||||
func SetDefaultRegistry(registry *DefaultModelRegistry) {
|
func SetDefaultRegistry(registry *DefaultModelRegistry) {
|
||||||
registriesMutex.Lock()
|
acquired := false
|
||||||
|
for i := 0; i < lockRetryAttempts; i++ {
|
||||||
|
if registriesMutex.TryLock() {
|
||||||
|
acquired = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
time.Sleep(lockRetryDelay)
|
||||||
|
}
|
||||||
|
if !acquired {
|
||||||
|
return
|
||||||
|
}
|
||||||
defer registriesMutex.Unlock()
|
defer registriesMutex.Unlock()
|
||||||
|
|
||||||
foundAt := -1
|
foundAt := -1
|
||||||
@@ -90,8 +123,34 @@ func AddRegistry(registry *DefaultModelRegistry) {
|
|||||||
registries = append(registries, registry)
|
registries = append(registries, registry)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// tryLock attempts to acquire the registry's write lock, retrying briefly.
|
||||||
|
// Returns false if it could not be acquired within the bound.
|
||||||
|
func (r *DefaultModelRegistry) tryLock() bool {
|
||||||
|
for i := 0; i < lockRetryAttempts; i++ {
|
||||||
|
if r.mutex.TryLock() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
time.Sleep(lockRetryDelay)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// tryRLock attempts to acquire the registry's read lock, retrying briefly.
|
||||||
|
// Returns false if it could not be acquired within the bound.
|
||||||
|
func (r *DefaultModelRegistry) tryRLock() bool {
|
||||||
|
for i := 0; i < lockRetryAttempts; i++ {
|
||||||
|
if r.mutex.TryRLock() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
time.Sleep(lockRetryDelay)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func (r *DefaultModelRegistry) RegisterModel(name string, model interface{}) error {
|
func (r *DefaultModelRegistry) RegisterModel(name string, model interface{}) error {
|
||||||
r.mutex.Lock()
|
if !r.tryLock() {
|
||||||
|
return fmt.Errorf("failed to register model %s: registry locked", name)
|
||||||
|
}
|
||||||
defer r.mutex.Unlock()
|
defer r.mutex.Unlock()
|
||||||
|
|
||||||
if _, exists := r.models[name]; exists {
|
if _, exists := r.models[name]; exists {
|
||||||
@@ -137,7 +196,9 @@ func (r *DefaultModelRegistry) RegisterModel(name string, model interface{}) err
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *DefaultModelRegistry) GetModel(name string) (interface{}, error) {
|
func (r *DefaultModelRegistry) GetModel(name string) (interface{}, error) {
|
||||||
r.mutex.RLock()
|
if !r.tryRLock() {
|
||||||
|
return nil, fmt.Errorf("failed to get model %s: registry locked", name)
|
||||||
|
}
|
||||||
defer r.mutex.RUnlock()
|
defer r.mutex.RUnlock()
|
||||||
|
|
||||||
model, exists := r.models[name]
|
model, exists := r.models[name]
|
||||||
@@ -149,7 +210,9 @@ func (r *DefaultModelRegistry) GetModel(name string) (interface{}, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (r *DefaultModelRegistry) GetAllModels() map[string]interface{} {
|
func (r *DefaultModelRegistry) GetAllModels() map[string]interface{} {
|
||||||
r.mutex.RLock()
|
if !r.tryRLock() {
|
||||||
|
return make(map[string]interface{})
|
||||||
|
}
|
||||||
defer r.mutex.RUnlock()
|
defer r.mutex.RUnlock()
|
||||||
|
|
||||||
result := make(map[string]interface{})
|
result := make(map[string]interface{})
|
||||||
@@ -253,14 +316,26 @@ func IterateModels(fn func(name string, model interface{})) {
|
|||||||
// GetModels returns a list of all models from all registries
|
// GetModels returns a list of all models from all registries
|
||||||
// Models are collected in registry order, with duplicates included
|
// Models are collected in registry order, with duplicates included
|
||||||
func GetModels() []interface{} {
|
func GetModels() []interface{} {
|
||||||
registriesMutex.RLock()
|
acquired := false
|
||||||
|
for i := 0; i < lockRetryAttempts; i++ {
|
||||||
|
if registriesMutex.TryRLock() {
|
||||||
|
acquired = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
time.Sleep(lockRetryDelay)
|
||||||
|
}
|
||||||
|
if !acquired {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
defer registriesMutex.RUnlock()
|
defer registriesMutex.RUnlock()
|
||||||
|
|
||||||
var models []interface{}
|
var models []interface{}
|
||||||
seen := make(map[string]bool)
|
seen := make(map[string]bool)
|
||||||
|
|
||||||
for _, registry := range registries {
|
for _, registry := range registries {
|
||||||
registry.mutex.RLock()
|
if !registry.tryRLock() {
|
||||||
|
continue
|
||||||
|
}
|
||||||
for name, model := range registry.models {
|
for name, model := range registry.models {
|
||||||
// Only add the first occurrence of each model name
|
// Only add the first occurrence of each model name
|
||||||
if !seen[name] {
|
if !seen[name] {
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ package resolvemcp
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"runtime/debug"
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
"github.com/uptrace/bun"
|
"github.com/uptrace/bun"
|
||||||
@@ -25,6 +26,7 @@ import (
|
|||||||
|
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/common"
|
"github.com/bitechdev/ResolveSpec/pkg/common"
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/common/adapters/database"
|
"github.com/bitechdev/ResolveSpec/pkg/common/adapters/database"
|
||||||
|
"github.com/bitechdev/ResolveSpec/pkg/logger"
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/modelregistry"
|
"github.com/bitechdev/ResolveSpec/pkg/modelregistry"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -82,11 +84,20 @@ func SetupMuxRoutes(muxRouter *mux.Router, handler *Handler) {
|
|||||||
// - GET {basePath}/sse — SSE connection endpoint
|
// - GET {basePath}/sse — SSE connection endpoint
|
||||||
// - POST {basePath}/message — JSON-RPC message endpoint
|
// - POST {basePath}/message — JSON-RPC message endpoint
|
||||||
func SetupBunRouterRoutes(router *bunrouter.Router, handler *Handler) {
|
func SetupBunRouterRoutes(router *bunrouter.Router, handler *Handler) {
|
||||||
|
defer func() {
|
||||||
|
if rec := recover(); rec != nil {
|
||||||
|
logger.Error("panic in resolvemcp.SetupBunRouterRoutes: %v\n%s", rec, debug.Stack())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
basePath := handler.config.BasePath
|
basePath := handler.config.BasePath
|
||||||
h := handler.SSEServer()
|
h := handler.SSEServer()
|
||||||
|
|
||||||
router.GET(basePath+"/sse", bunrouter.HTTPHandler(h))
|
router.GET(basePath+"/sse", bunrouter.HTTPHandler(h))
|
||||||
|
logger.Info("Registered resolvemcp bunrouter route GET %s/sse", basePath)
|
||||||
|
|
||||||
router.POST(basePath+"/message", bunrouter.HTTPHandler(h))
|
router.POST(basePath+"/message", bunrouter.HTTPHandler(h))
|
||||||
|
logger.Info("Registered resolvemcp bunrouter route POST %s/message", basePath)
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewSSEServer returns an http.Handler that serves MCP over SSE.
|
// NewSSEServer returns an http.Handler that serves MCP over SSE.
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ func (h *Handler) getDefaultSort(schema, name string) []common.SortOption {
|
|||||||
if h.defaultSort == nil {
|
if h.defaultSort == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if sort, ok := h.defaultSort[defaultSortKey(schema, name)]; ok {
|
if sort := h.defaultSort[defaultSortKey(schema, name)]; len(sort) > 0 {
|
||||||
return sort
|
return sort
|
||||||
}
|
}
|
||||||
return h.defaultSort[defaultSortKey("", "")]
|
return h.defaultSort[defaultSortKey("", "")]
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package resolvespec
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/common"
|
"github.com/bitechdev/ResolveSpec/pkg/common"
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/logger"
|
"github.com/bitechdev/ResolveSpec/pkg/logger"
|
||||||
@@ -82,6 +84,7 @@ type HookFunc func(*HookContext) error
|
|||||||
// HookRegistry manages all registered hooks
|
// HookRegistry manages all registered hooks
|
||||||
type HookRegistry struct {
|
type HookRegistry struct {
|
||||||
hooks map[HookType][]HookFunc
|
hooks map[HookType][]HookFunc
|
||||||
|
mutex sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewHookRegistry creates a new hook registry
|
// NewHookRegistry creates a new hook registry
|
||||||
@@ -91,8 +94,46 @@ func NewHookRegistry() *HookRegistry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// hookLockRetryAttempts/hookLockRetryDelay bound how long the try-lock
|
||||||
|
// helpers below will spin before giving up, so a contended mutex can
|
||||||
|
// never hang a caller.
|
||||||
|
const (
|
||||||
|
hookLockRetryAttempts = 20
|
||||||
|
hookLockRetryDelay = 1 * time.Millisecond
|
||||||
|
)
|
||||||
|
|
||||||
|
// tryLock attempts to acquire the write lock, retrying briefly. Returns
|
||||||
|
// false if it could not be acquired within the bound.
|
||||||
|
func (r *HookRegistry) tryLock() bool {
|
||||||
|
for i := 0; i < hookLockRetryAttempts; i++ {
|
||||||
|
if r.mutex.TryLock() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
time.Sleep(hookLockRetryDelay)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// tryRLock attempts to acquire the read lock, retrying briefly. Returns
|
||||||
|
// false if it could not be acquired within the bound.
|
||||||
|
func (r *HookRegistry) tryRLock() bool {
|
||||||
|
for i := 0; i < hookLockRetryAttempts; i++ {
|
||||||
|
if r.mutex.TryRLock() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
time.Sleep(hookLockRetryDelay)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// Register adds a new hook for the specified hook type
|
// Register adds a new hook for the specified hook type
|
||||||
func (r *HookRegistry) Register(hookType HookType, hook HookFunc) {
|
func (r *HookRegistry) Register(hookType HookType, hook HookFunc) {
|
||||||
|
if !r.tryLock() {
|
||||||
|
logger.Error("Failed to register resolvespec hook for %s: registry locked", hookType)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.mutex.Unlock()
|
||||||
|
|
||||||
if r.hooks == nil {
|
if r.hooks == nil {
|
||||||
r.hooks = make(map[HookType][]HookFunc)
|
r.hooks = make(map[HookType][]HookFunc)
|
||||||
}
|
}
|
||||||
@@ -110,8 +151,13 @@ func (r *HookRegistry) RegisterMultiple(hookTypes []HookType, hook HookFunc) {
|
|||||||
// Execute runs all hooks for the specified type in order
|
// Execute runs all hooks for the specified type in order
|
||||||
// If any hook returns an error, execution stops and the error is returned
|
// If any hook returns an error, execution stops and the error is returned
|
||||||
func (r *HookRegistry) Execute(hookType HookType, ctx *HookContext) error {
|
func (r *HookRegistry) Execute(hookType HookType, ctx *HookContext) error {
|
||||||
hooks, exists := r.hooks[hookType]
|
if !r.tryRLock() {
|
||||||
if !exists || len(hooks) == 0 {
|
return fmt.Errorf("hook execution failed: registry locked")
|
||||||
|
}
|
||||||
|
hooks := append([]HookFunc(nil), r.hooks[hookType]...)
|
||||||
|
r.mutex.RUnlock()
|
||||||
|
|
||||||
|
if len(hooks) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -145,18 +191,35 @@ func (r *HookRegistry) ExecuteBeforeOp(hookType HookType, ctx *HookContext) erro
|
|||||||
|
|
||||||
// Clear removes all hooks for the specified type
|
// Clear removes all hooks for the specified type
|
||||||
func (r *HookRegistry) Clear(hookType HookType) {
|
func (r *HookRegistry) Clear(hookType HookType) {
|
||||||
|
if !r.tryLock() {
|
||||||
|
logger.Error("Failed to clear resolvespec hooks for %s: registry locked", hookType)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.mutex.Unlock()
|
||||||
|
|
||||||
delete(r.hooks, hookType)
|
delete(r.hooks, hookType)
|
||||||
logger.Info("Cleared all resolvespec hooks for %s", hookType)
|
logger.Info("Cleared all resolvespec hooks for %s", hookType)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ClearAll removes all registered hooks
|
// ClearAll removes all registered hooks
|
||||||
func (r *HookRegistry) ClearAll() {
|
func (r *HookRegistry) ClearAll() {
|
||||||
|
if !r.tryLock() {
|
||||||
|
logger.Error("Failed to clear all resolvespec hooks: registry locked")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.mutex.Unlock()
|
||||||
|
|
||||||
r.hooks = make(map[HookType][]HookFunc)
|
r.hooks = make(map[HookType][]HookFunc)
|
||||||
logger.Info("Cleared all resolvespec hooks")
|
logger.Info("Cleared all resolvespec hooks")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Count returns the number of hooks registered for a specific type
|
// Count returns the number of hooks registered for a specific type
|
||||||
func (r *HookRegistry) Count(hookType HookType) int {
|
func (r *HookRegistry) Count(hookType HookType) int {
|
||||||
|
if !r.tryRLock() {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
defer r.mutex.RUnlock()
|
||||||
|
|
||||||
if hooks, exists := r.hooks[hookType]; exists {
|
if hooks, exists := r.hooks[hookType]; exists {
|
||||||
return len(hooks)
|
return len(hooks)
|
||||||
}
|
}
|
||||||
@@ -170,6 +233,11 @@ func (r *HookRegistry) HasHooks(hookType HookType) bool {
|
|||||||
|
|
||||||
// GetAllHookTypes returns all hook types that have registered hooks
|
// GetAllHookTypes returns all hook types that have registered hooks
|
||||||
func (r *HookRegistry) GetAllHookTypes() []HookType {
|
func (r *HookRegistry) GetAllHookTypes() []HookType {
|
||||||
|
if !r.tryRLock() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
defer r.mutex.RUnlock()
|
||||||
|
|
||||||
types := make([]HookType, 0, len(r.hooks))
|
types := make([]HookType, 0, len(r.hooks))
|
||||||
for hookType := range r.hooks {
|
for hookType := range r.hooks {
|
||||||
types = append(types, hookType)
|
types = append(types, hookType)
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package resolvespec
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"runtime/debug"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
@@ -12,6 +13,7 @@ import (
|
|||||||
"github.com/bitechdev/ResolveSpec/pkg/common"
|
"github.com/bitechdev/ResolveSpec/pkg/common"
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/common/adapters/database"
|
"github.com/bitechdev/ResolveSpec/pkg/common/adapters/database"
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/common/adapters/router"
|
"github.com/bitechdev/ResolveSpec/pkg/common/adapters/router"
|
||||||
|
"github.com/bitechdev/ResolveSpec/pkg/logger"
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/modelregistry"
|
"github.com/bitechdev/ResolveSpec/pkg/modelregistry"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -244,6 +246,11 @@ func wrapBunRouterHandler(handler bunrouter.HandlerFunc, authMiddleware Middlewa
|
|||||||
// Accepts bunrouter.Router or bunrouter.Group
|
// Accepts bunrouter.Router or bunrouter.Group
|
||||||
// authMiddleware is optional - if provided, routes will be protected with the middleware
|
// authMiddleware is optional - if provided, routes will be protected with the middleware
|
||||||
func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler, authMiddleware MiddlewareFunc) {
|
func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler, authMiddleware MiddlewareFunc) {
|
||||||
|
defer func() {
|
||||||
|
if rec := recover(); rec != nil {
|
||||||
|
logger.Error("panic in resolvespec.SetupBunRouterRoutes: %v\n%s", rec, debug.Stack())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
// CORS config
|
// CORS config
|
||||||
corsConfig := common.DefaultCORSConfig()
|
corsConfig := common.DefaultCORSConfig()
|
||||||
@@ -269,6 +276,13 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler, authMiddleware M
|
|||||||
|
|
||||||
// Loop through each registered model and create explicit routes
|
// Loop through each registered model and create explicit routes
|
||||||
for fullName := range allModels {
|
for fullName := range allModels {
|
||||||
|
func() {
|
||||||
|
defer func() {
|
||||||
|
if rec := recover(); rec != nil {
|
||||||
|
logger.Error("panic registering resolvespec routes for model %s: %v\n%s", fullName, rec, debug.Stack())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
// Parse the full name (e.g., "public.users" or just "users")
|
// Parse the full name (e.g., "public.users" or just "users")
|
||||||
schema, entity := parseModelName(fullName)
|
schema, entity := parseModelName(fullName)
|
||||||
|
|
||||||
@@ -375,6 +389,9 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler, authMiddleware M
|
|||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
|
logger.Info("Registered resolvespec bunrouter routes for model %s at %s", fullName, entityPath)
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -82,7 +82,7 @@ func (h *Handler) getDefaultSort(schema, name string) []common.SortOption {
|
|||||||
if h.defaultSort == nil {
|
if h.defaultSort == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if sort, ok := h.defaultSort[defaultSortKey(schema, name)]; ok {
|
if sort := h.defaultSort[defaultSortKey(schema, name)]; len(sort) > 0 {
|
||||||
return sort
|
return sort
|
||||||
}
|
}
|
||||||
return h.defaultSort[defaultSortKey("", "")]
|
return h.defaultSort[defaultSortKey("", "")]
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ package restheadspec
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/common"
|
"github.com/bitechdev/ResolveSpec/pkg/common"
|
||||||
"github.com/bitechdev/ResolveSpec/pkg/logger"
|
"github.com/bitechdev/ResolveSpec/pkg/logger"
|
||||||
@@ -89,6 +91,7 @@ type HookFunc func(*HookContext) error
|
|||||||
// HookRegistry manages all registered hooks
|
// HookRegistry manages all registered hooks
|
||||||
type HookRegistry struct {
|
type HookRegistry struct {
|
||||||
hooks map[HookType][]HookFunc
|
hooks map[HookType][]HookFunc
|
||||||
|
mutex sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewHookRegistry creates a new hook registry
|
// NewHookRegistry creates a new hook registry
|
||||||
@@ -98,8 +101,46 @@ func NewHookRegistry() *HookRegistry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// hookLockRetryAttempts/hookLockRetryDelay bound how long the try-lock
|
||||||
|
// helpers below will spin before giving up, so a contended mutex can
|
||||||
|
// never hang a caller.
|
||||||
|
const (
|
||||||
|
hookLockRetryAttempts = 20
|
||||||
|
hookLockRetryDelay = 1 * time.Millisecond
|
||||||
|
)
|
||||||
|
|
||||||
|
// tryLock attempts to acquire the write lock, retrying briefly. Returns
|
||||||
|
// false if it could not be acquired within the bound.
|
||||||
|
func (r *HookRegistry) tryLock() bool {
|
||||||
|
for i := 0; i < hookLockRetryAttempts; i++ {
|
||||||
|
if r.mutex.TryLock() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
time.Sleep(hookLockRetryDelay)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// tryRLock attempts to acquire the read lock, retrying briefly. Returns
|
||||||
|
// false if it could not be acquired within the bound.
|
||||||
|
func (r *HookRegistry) tryRLock() bool {
|
||||||
|
for i := 0; i < hookLockRetryAttempts; i++ {
|
||||||
|
if r.mutex.TryRLock() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
time.Sleep(hookLockRetryDelay)
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
// Register adds a new hook for the specified hook type
|
// Register adds a new hook for the specified hook type
|
||||||
func (r *HookRegistry) Register(hookType HookType, hook HookFunc) {
|
func (r *HookRegistry) Register(hookType HookType, hook HookFunc) {
|
||||||
|
if !r.tryLock() {
|
||||||
|
logger.Error("Failed to register hook for %s: registry locked", hookType)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.mutex.Unlock()
|
||||||
|
|
||||||
if r.hooks == nil {
|
if r.hooks == nil {
|
||||||
r.hooks = make(map[HookType][]HookFunc)
|
r.hooks = make(map[HookType][]HookFunc)
|
||||||
}
|
}
|
||||||
@@ -117,8 +158,13 @@ func (r *HookRegistry) RegisterMultiple(hookTypes []HookType, hook HookFunc) {
|
|||||||
// Execute runs all hooks for the specified type in order
|
// Execute runs all hooks for the specified type in order
|
||||||
// If any hook returns an error, execution stops and the error is returned
|
// If any hook returns an error, execution stops and the error is returned
|
||||||
func (r *HookRegistry) Execute(hookType HookType, ctx *HookContext) error {
|
func (r *HookRegistry) Execute(hookType HookType, ctx *HookContext) error {
|
||||||
hooks, exists := r.hooks[hookType]
|
if !r.tryRLock() {
|
||||||
if !exists || len(hooks) == 0 {
|
return fmt.Errorf("hook execution failed: registry locked")
|
||||||
|
}
|
||||||
|
hooks := append([]HookFunc(nil), r.hooks[hookType]...)
|
||||||
|
r.mutex.RUnlock()
|
||||||
|
|
||||||
|
if len(hooks) == 0 {
|
||||||
// logger.Debug("No hooks registered for %s", hookType)
|
// logger.Debug("No hooks registered for %s", hookType)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -154,18 +200,35 @@ func (r *HookRegistry) ExecuteBeforeOp(hookType HookType, ctx *HookContext) erro
|
|||||||
|
|
||||||
// Clear removes all hooks for the specified type
|
// Clear removes all hooks for the specified type
|
||||||
func (r *HookRegistry) Clear(hookType HookType) {
|
func (r *HookRegistry) Clear(hookType HookType) {
|
||||||
|
if !r.tryLock() {
|
||||||
|
logger.Error("Failed to clear hooks for %s: registry locked", hookType)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.mutex.Unlock()
|
||||||
|
|
||||||
delete(r.hooks, hookType)
|
delete(r.hooks, hookType)
|
||||||
logger.Info("Cleared all hooks for %s", hookType)
|
logger.Info("Cleared all hooks for %s", hookType)
|
||||||
}
|
}
|
||||||
|
|
||||||
// ClearAll removes all registered hooks
|
// ClearAll removes all registered hooks
|
||||||
func (r *HookRegistry) ClearAll() {
|
func (r *HookRegistry) ClearAll() {
|
||||||
|
if !r.tryLock() {
|
||||||
|
logger.Error("Failed to clear all hooks: registry locked")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer r.mutex.Unlock()
|
||||||
|
|
||||||
r.hooks = make(map[HookType][]HookFunc)
|
r.hooks = make(map[HookType][]HookFunc)
|
||||||
logger.Info("Cleared all hooks")
|
logger.Info("Cleared all hooks")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Count returns the number of hooks registered for a specific type
|
// Count returns the number of hooks registered for a specific type
|
||||||
func (r *HookRegistry) Count(hookType HookType) int {
|
func (r *HookRegistry) Count(hookType HookType) int {
|
||||||
|
if !r.tryRLock() {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
defer r.mutex.RUnlock()
|
||||||
|
|
||||||
if hooks, exists := r.hooks[hookType]; exists {
|
if hooks, exists := r.hooks[hookType]; exists {
|
||||||
return len(hooks)
|
return len(hooks)
|
||||||
}
|
}
|
||||||
@@ -179,6 +242,11 @@ func (r *HookRegistry) HasHooks(hookType HookType) bool {
|
|||||||
|
|
||||||
// GetAllHookTypes returns all hook types that have registered hooks
|
// GetAllHookTypes returns all hook types that have registered hooks
|
||||||
func (r *HookRegistry) GetAllHookTypes() []HookType {
|
func (r *HookRegistry) GetAllHookTypes() []HookType {
|
||||||
|
if !r.tryRLock() {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
defer r.mutex.RUnlock()
|
||||||
|
|
||||||
types := make([]HookType, 0, len(r.hooks))
|
types := make([]HookType, 0, len(r.hooks))
|
||||||
for hookType := range r.hooks {
|
for hookType := range r.hooks {
|
||||||
types = append(types, hookType)
|
types = append(types, hookType)
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ package restheadspec
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"runtime/debug"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
@@ -308,6 +309,11 @@ func wrapBunRouterHandler(handler bunrouter.HandlerFunc, authMiddleware Middlewa
|
|||||||
// Accepts bunrouter.Router or bunrouter.Group
|
// Accepts bunrouter.Router or bunrouter.Group
|
||||||
// authMiddleware is optional - if provided, routes will be protected with the middleware
|
// authMiddleware is optional - if provided, routes will be protected with the middleware
|
||||||
func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler, authMiddleware MiddlewareFunc) {
|
func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler, authMiddleware MiddlewareFunc) {
|
||||||
|
defer func() {
|
||||||
|
if rec := recover(); rec != nil {
|
||||||
|
logger.Error("panic in restheadspec.SetupBunRouterRoutes: %v\n%s", rec, debug.Stack())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
// CORS config
|
// CORS config
|
||||||
corsConfig := common.DefaultCORSConfig()
|
corsConfig := common.DefaultCORSConfig()
|
||||||
@@ -333,6 +339,13 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler, authMiddleware M
|
|||||||
|
|
||||||
// Loop through each registered model and create explicit routes
|
// Loop through each registered model and create explicit routes
|
||||||
for fullName := range allModels {
|
for fullName := range allModels {
|
||||||
|
func() {
|
||||||
|
defer func() {
|
||||||
|
if rec := recover(); rec != nil {
|
||||||
|
logger.Error("panic registering restheadspec routes for model %s: %v\n%s", fullName, rec, debug.Stack())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
// Parse the full name (e.g., "public.users" or just "users")
|
// Parse the full name (e.g., "public.users" or just "users")
|
||||||
schema, entity := parseModelName(fullName)
|
schema, entity := parseModelName(fullName)
|
||||||
|
|
||||||
@@ -498,6 +511,9 @@ func SetupBunRouterRoutes(r BunRouterHandler, handler *Handler, authMiddleware M
|
|||||||
handler.HandleGet(respAdapter, reqAdapter, params)
|
handler.HandleGet(respAdapter, reqAdapter, params)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
|
|
||||||
|
logger.Info("Registered restheadspec bunrouter routes for model %s at %s", fullName, entityPath)
|
||||||
|
}()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user