|
| 1 | +/** |
| 2 | + * Copyright 2024 DWANGO Co., Ltd. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package cache |
| 17 | + |
| 18 | +import ( |
| 19 | + "context" |
| 20 | + "errors" |
| 21 | + "fmt" |
| 22 | + |
| 23 | + "github.com/dwango/yashiro/internal/values" |
| 24 | + "github.com/dwango/yashiro/pkg/config" |
| 25 | +) |
| 26 | + |
| 27 | +var ( |
| 28 | + ErrInvalidCacheType = errors.New("invalid cache type") |
| 29 | +) |
| 30 | + |
| 31 | +type Cache interface { |
| 32 | + // Load returns values from cache and whether or not cache is expired. If cache is empty, |
| 33 | + // returned values is empty and expired=true. |
| 34 | + Load(ctx context.Context) (values.Values, bool, error) |
| 35 | + |
| 36 | + // Save saves values to cache. |
| 37 | + Save(ctx context.Context, val values.Values) error |
| 38 | +} |
| 39 | + |
| 40 | +func New(cfg config.CacheConfig) (Cache, error) { |
| 41 | + switch cfg.Type { |
| 42 | + case config.CacheTypeUnspecified, config.CacheTypeMemory: |
| 43 | + return newMemoryCache() |
| 44 | + case config.CacheTypeFile: |
| 45 | + return newFileCache(cfg.File) |
| 46 | + default: |
| 47 | + return nil, fmt.Errorf("%w: %s", ErrInvalidCacheType, cfg.Type) |
| 48 | + } |
| 49 | +} |
0 commit comments