podman
98 строк · 2.5 Кб
1// Copyright 2015 go-swagger maintainers
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
15package spec
16
17import (
18"sync"
19)
20
21// ResolutionCache a cache for resolving urls
22type ResolutionCache interface {
23Get(string) (interface{}, bool)
24Set(string, interface{})
25}
26
27type simpleCache struct {
28lock sync.RWMutex
29store map[string]interface{}
30}
31
32func (s *simpleCache) ShallowClone() ResolutionCache {
33store := make(map[string]interface{}, len(s.store))
34s.lock.RLock()
35for k, v := range s.store {
36store[k] = v
37}
38s.lock.RUnlock()
39
40return &simpleCache{
41store: store,
42}
43}
44
45// Get retrieves a cached URI
46func (s *simpleCache) Get(uri string) (interface{}, bool) {
47s.lock.RLock()
48v, ok := s.store[uri]
49
50s.lock.RUnlock()
51return v, ok
52}
53
54// Set caches a URI
55func (s *simpleCache) Set(uri string, data interface{}) {
56s.lock.Lock()
57s.store[uri] = data
58s.lock.Unlock()
59}
60
61var (
62// resCache is a package level cache for $ref resolution and expansion.
63// It is initialized lazily by methods that have the need for it: no
64// memory is allocated unless some expander methods are called.
65//
66// It is initialized with JSON schema and swagger schema,
67// which do not mutate during normal operations.
68//
69// All subsequent utilizations of this cache are produced from a shallow
70// clone of this initial version.
71resCache *simpleCache
72onceCache sync.Once
73
74_ ResolutionCache = &simpleCache{}
75)
76
77// initResolutionCache initializes the URI resolution cache. To be wrapped in a sync.Once.Do call.
78func initResolutionCache() {
79resCache = defaultResolutionCache()
80}
81
82func defaultResolutionCache() *simpleCache {
83return &simpleCache{store: map[string]interface{}{
84"http://swagger.io/v2/schema.json": MustLoadSwagger20Schema(),
85"http://json-schema.org/draft-04/schema": MustLoadJSONSchemaDraft04(),
86}}
87}
88
89func cacheOrDefault(cache ResolutionCache) ResolutionCache {
90onceCache.Do(initResolutionCache)
91
92if cache != nil {
93return cache
94}
95
96// get a shallow clone of the base cache with swagger and json schema
97return resCache.ShallowClone()
98}
99