github.com/hasnat/dolt/go@v0.0.0-20210628190320-9eb5d843fbb7/utils/remotesrv/cscache.go (about)

     1  // Copyright 2019 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package main
    16  
    17  import (
    18  	"context"
    19  	"path/filepath"
    20  	"sync"
    21  
    22  	"github.com/dolthub/dolt/go/libraries/utils/filesys"
    23  	"github.com/dolthub/dolt/go/store/nbs"
    24  )
    25  
    26  const (
    27  	defaultMemTableSize = 128 * 1024 * 1024
    28  )
    29  
    30  type DBCache struct {
    31  	mu  *sync.Mutex
    32  	dbs map[string]*nbs.NomsBlockStore
    33  
    34  	fs filesys.Filesys
    35  }
    36  
    37  func NewLocalCSCache(filesys filesys.Filesys) *DBCache {
    38  	return &DBCache{
    39  		&sync.Mutex{},
    40  		make(map[string]*nbs.NomsBlockStore),
    41  		filesys,
    42  	}
    43  }
    44  
    45  func (cache *DBCache) Get(org, repo, nbfVerStr string) (*nbs.NomsBlockStore, error) {
    46  	cache.mu.Lock()
    47  	defer cache.mu.Unlock()
    48  
    49  	id := filepath.Join(org, repo)
    50  
    51  	if cs, ok := cache.dbs[id]; ok {
    52  		return cs, nil
    53  	}
    54  
    55  	var newCS *nbs.NomsBlockStore
    56  	if cache.fs != nil {
    57  		err := cache.fs.MkDirs(id)
    58  
    59  		if err != nil {
    60  			return nil, err
    61  		}
    62  
    63  		newCS, err = nbs.NewLocalStore(context.TODO(), nbfVerStr, id, defaultMemTableSize)
    64  
    65  		if err != nil {
    66  			return nil, err
    67  		}
    68  	}
    69  
    70  	cache.dbs[id] = newCS
    71  
    72  	return newCS, nil
    73  }