github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/nosql/manager.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  package nosql
     7  
     8  import (
     9  	"context"
    10  	"strconv"
    11  	"sync"
    12  	"time"
    13  
    14  	"github.com/gitbundle/modules/process"
    15  
    16  	"github.com/redis/go-redis/v9"
    17  	"github.com/syndtr/goleveldb/leveldb"
    18  )
    19  
    20  var manager *Manager
    21  
    22  // Manager is the nosql connection manager
    23  type Manager struct {
    24  	ctx      context.Context
    25  	finished context.CancelFunc
    26  	mutex    sync.Mutex
    27  
    28  	RedisConnections   map[string]*redisClientHolder
    29  	LevelDBConnections map[string]*levelDBHolder
    30  }
    31  
    32  type redisClientHolder struct {
    33  	redis.UniversalClient
    34  	name  []string
    35  	count int64
    36  }
    37  
    38  func (r *redisClientHolder) Close() error {
    39  	return manager.CloseRedisClient(r.name[0])
    40  }
    41  
    42  type levelDBHolder struct {
    43  	name  []string
    44  	count int64
    45  	db    *leveldb.DB
    46  }
    47  
    48  func init() {
    49  	_ = GetManager()
    50  }
    51  
    52  // GetManager returns a Manager and initializes one as singleton is there's none yet
    53  func GetManager() *Manager {
    54  	if manager == nil {
    55  		ctx, _, finished := process.GetManager().AddTypedContext(context.Background(), "Service: NoSQL", process.SystemProcessType, false)
    56  		manager = &Manager{
    57  			ctx:                ctx,
    58  			finished:           finished,
    59  			RedisConnections:   make(map[string]*redisClientHolder),
    60  			LevelDBConnections: make(map[string]*levelDBHolder),
    61  		}
    62  	}
    63  	return manager
    64  }
    65  
    66  func valToTimeDuration(vs []string) (result time.Duration) {
    67  	var err error
    68  	for _, v := range vs {
    69  		result, err = time.ParseDuration(v)
    70  		if err != nil {
    71  			var val int
    72  			val, err = strconv.Atoi(v)
    73  			result = time.Duration(val)
    74  		}
    75  		if err == nil {
    76  			return
    77  		}
    78  	}
    79  	return
    80  }