| 1 |
// Copyright 2019 The Hugo Authors. All rights reserved. |
| 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 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
// Package create contains functions for to create Resource objects. This will |
| 15 |
// typically non-files. |
| 16 |
package create |
| 17 |
|
| 18 |
import ( |
| 19 |
"errors" |
| 20 |
"net/http" |
| 21 |
"os" |
| 22 |
"path" |
| 23 |
"path/filepath" |
| 24 |
"strings" |
| 25 |
"time" |
| 26 |
|
| 27 |
"github.com/bep/helpers/contexthelpers" |
| 28 |
|
| 29 |
"github.com/bep/logg" |
| 30 |
"github.com/gohugoio/httpcache" |
| 31 |
hhttpcache "github.com/gohugoio/hugo/cache/httpcache" |
| 32 |
"github.com/gohugoio/hugo/hugofs/hglob" |
| 33 |
"github.com/gohugoio/hugo/identity" |
| 34 |
|
| 35 |
"github.com/gohugoio/hugo/hugofs" |
| 36 |
|
| 37 |
"github.com/gohugoio/hugo/cache/dynacache" |
| 38 |
"github.com/gohugoio/hugo/cache/filecache" |
| 39 |
"github.com/gohugoio/hugo/common/hashing" |
| 40 |
|
| 41 |
"github.com/gohugoio/hugo/common/hugio" |
| 42 |
"github.com/gohugoio/hugo/common/tasks" |
| 43 |
"github.com/gohugoio/hugo/resources" |
| 44 |
"github.com/gohugoio/hugo/resources/resource" |
| 45 |
) |
| 46 |
|
| 47 |
// Client contains methods to create Resource objects. |
| 48 |
// tasks to Resource objects. |
| 49 |
type Client struct { |
| 50 |
rs *resources.Spec |
| 51 |
httpClient *http.Client |
| 52 |
httpCacheConfig hhttpcache.ConfigCompiled |
| 53 |
cacheGetResource *filecache.Cache |
| 54 |
resourceIDDispatcher contexthelpers.ContextDispatcher[string] |
| 55 |
|
| 56 |
// Set when watching. |
| 57 |
remoteResourceChecker *tasks.RunEvery |
| 58 |
remoteResourceLogger logg.LevelLogger |
| 59 |
} |
| 60 |
|
| 61 |
type contextKey uint8 |
| 62 |
|
| 63 |
const ( |
| 64 |
contextKeyResourceID contextKey = iota |
| 65 |
) |
| 66 |
|
| 67 |
// New creates a new Client with the given specification. |
| 68 |
func New(rs *resources.Spec) *Client { |
| 69 |
fileCache := rs.FileCaches.GetResourceCache() |
| 70 |
resourceIDDispatcher := contexthelpers.NewContextDispatcher[string](contextKeyResourceID) |
| 71 |
httpCacheConfig := rs.Cfg.GetConfigSection("httpCacheCompiled").(hhttpcache.ConfigCompiled) |
| 72 |
var remoteResourceChecker *tasks.RunEvery |
| 73 |
if rs.Cfg.Watching() && !httpCacheConfig.IsPollingDisabled() { |
| 74 |
remoteResourceChecker = &tasks.RunEvery{ |
| 75 |
HandleError: func(name string, err error) { |
| 76 |
rs.Logger.Warnf("Failed to check remote resource: %s", err) |
| 77 |
}, |
| 78 |
RunImmediately: false, |
| 79 |
} |
| 80 |
|
| 81 |
if err := remoteResourceChecker.Start(); err != nil { |
| 82 |
panic(err) |
| 83 |
} |
| 84 |
|
| 85 |
rs.BuildClosers.Add(remoteResourceChecker) |
| 86 |
} |
| 87 |
|
| 88 |
httpTimeout := 2 * time.Minute // Need to cover retries. |
| 89 |
if httpTimeout < (rs.Cfg.Timeout() + 30*time.Second) { |
| 90 |
httpTimeout = rs.Cfg.Timeout() + 30*time.Second |
| 91 |
} |
| 92 |
|
| 93 |
return &Client{ |
| 94 |
rs: rs, |
| 95 |
httpCacheConfig: httpCacheConfig, |
| 96 |
resourceIDDispatcher: resourceIDDispatcher, |
| 97 |
remoteResourceChecker: remoteResourceChecker, |
| 98 |
remoteResourceLogger: rs.Logger.InfoCommand("remote"), |
| 99 |
httpClient: &http.Client{ |
| 100 |
Timeout: httpTimeout, |
| 101 |
CheckRedirect: func(req *http.Request, via []*http.Request) error { |
| 102 |
if err := rs.ExecHelper.Sec().CheckAllowedHTTPURL(req.URL.String()); err != nil { |
| 103 |
return err |
| 104 |
} |
| 105 |
if len(via) >= 10 { |
| 106 |
return errors.New("stopped after 10 redirects") |
| 107 |
} |
| 108 |
return nil |
| 109 |
}, |
| 110 |
Transport: &httpcache.Transport{ |
| 111 |
Cache: fileCache.AsHTTPCache(), |
| 112 |
CacheKey: func(req *http.Request) string { |
| 113 |
return resourceIDDispatcher.Get(req.Context()) |
| 114 |
}, |
| 115 |
Around: func(req *http.Request, key string) func() { |
| 116 |
return fileCache.NamedLock(key) |
| 117 |
}, |
| 118 |
AlwaysUseCachedResponse: func(req *http.Request, key string) bool { |
| 119 |
return !httpCacheConfig.For(req.URL.String()) |
| 120 |
}, |
| 121 |
ShouldCache: func(req *http.Request, resp *http.Response, key string) bool { |
| 122 |
return shouldCache(resp.StatusCode) |
| 123 |
}, |
| 124 |
CanStore: func(reqCacheControl, respCacheControl httpcache.CacheControl) (canStore bool) { |
| 125 |
if httpCacheConfig.Base.RespectCacheControlNoStoreInResponse { |
| 126 |
if _, ok := respCacheControl["no-store"]; ok { |
| 127 |
return false |
| 128 |
} |
| 129 |
} |
| 130 |
if httpCacheConfig.Base.RespectCacheControlNoStoreInRequest { |
| 131 |
if _, ok := reqCacheControl["no-store"]; ok { |
| 132 |
return false |
| 133 |
} |
| 134 |
} |
| 135 |
return true |
| 136 |
}, |
| 137 |
MarkCachedResponses: true, |
| 138 |
EnableETagPair: true, |
| 139 |
Transport: &transport{ |
| 140 |
Cfg: rs.Cfg, |
| 141 |
Logger: rs.Logger, |
| 142 |
}, |
| 143 |
}, |
| 144 |
}, |
| 145 |
cacheGetResource: fileCache, |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
// Copy copies r to the new targetPath. |
| 150 |
func (c *Client) Copy(r resource.Resource, targetPath string) (resource.Resource, error) { |
| 151 |
key := dynacache.CleanKey(targetPath) + "__copy" |
| 152 |
return c.rs.ResourceCache.GetOrCreate(key, func() (resource.Resource, error) { |
| 153 |
return resources.Copy(r, targetPath), nil |
| 154 |
}) |
| 155 |
} |
| 156 |
|
| 157 |
// Get creates a new Resource by opening the given pathname in the assets filesystem. |
| 158 |
func (c *Client) Get(pathname string) (resource.Resource, error) { |
| 159 |
pathname = path.Clean(pathname) |
| 160 |
key := dynacache.CleanKey(pathname) + "__get" |
| 161 |
|
| 162 |
return c.rs.ResourceCache.GetOrCreate(key, func() (resource.Resource, error) { |
| 163 |
// The resource file will not be read before it gets used (e.g. in .Content), |
| 164 |
// so we need to check that the file exists here. |
| 165 |
filename := filepath.FromSlash(pathname) |
| 166 |
fi, err := c.rs.BaseFs.Assets.Fs.Stat(filename) |
| 167 |
if err != nil { |
| 168 |
if os.IsNotExist(err) { |
| 169 |
return nil, nil |
| 170 |
} |
| 171 |
// A real error. |
| 172 |
return nil, err |
| 173 |
} |
| 174 |
|
| 175 |
return c.getOrCreateFileResource(fi.(hugofs.FileMetaInfo)) |
| 176 |
}) |
| 177 |
} |
| 178 |
|
| 179 |
// Match gets the resources matching the given pattern from the assets filesystem. |
| 180 |
func (c *Client) Match(pattern string) (resource.Resources, error) { |
| 181 |
return c.match("__match", pattern, nil, false) |
| 182 |
} |
| 183 |
|
| 184 |
func (c *Client) ByType(tp string) resource.Resources { |
| 185 |
res, err := c.match(path.Join("_byType", tp), "**", func(r resource.Resource) bool { return r.ResourceType() == tp }, false) |
| 186 |
if err != nil { |
| 187 |
panic(err) |
| 188 |
} |
| 189 |
return res |
| 190 |
} |
| 191 |
|
| 192 |
// GetMatch gets first resource matching the given pattern from the assets filesystem. |
| 193 |
func (c *Client) GetMatch(pattern string) (resource.Resource, error) { |
| 194 |
res, err := c.match("__get-match", pattern, nil, true) |
| 195 |
if err != nil || len(res) == 0 { |
| 196 |
return nil, err |
| 197 |
} |
| 198 |
return res[0], err |
| 199 |
} |
| 200 |
|
| 201 |
func (c *Client) getOrCreateFileResource(info hugofs.FileMetaInfo) (resource.Resource, error) { |
| 202 |
meta := info.Meta() |
| 203 |
return c.rs.ResourceCache.GetOrCreateFile(filepath.ToSlash(meta.Filename), func() (resource.Resource, error) { |
| 204 |
return c.rs.NewResource(resources.ResourceSourceDescriptor{ |
| 205 |
LazyPublish: true, |
| 206 |
OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { |
| 207 |
return meta.Open() |
| 208 |
}, |
| 209 |
NameNormalized: meta.PathInfo.Path(), |
| 210 |
NameOriginal: meta.PathInfo.Unnormalized().Path(), |
| 211 |
GroupIdentity: meta.PathInfo, |
| 212 |
TargetPath: meta.PathInfo.Unnormalized().Path(), |
| 213 |
SourceFilenameOrPath: meta.Filename, |
| 214 |
}) |
| 215 |
}) |
| 216 |
} |
| 217 |
|
| 218 |
func (c *Client) match(name, pattern string, matchFunc func(r resource.Resource) bool, firstOnly bool) (resource.Resources, error) { |
| 219 |
pattern = hglob.NormalizePath(pattern) |
| 220 |
partitions := hglob.FilterGlobParts(strings.Split(pattern, "/")) |
| 221 |
key := path.Join(name, path.Join(partitions...)) |
| 222 |
key = path.Join(key, pattern) |
| 223 |
|
| 224 |
return c.rs.ResourceCache.GetOrCreateResources(key, func() (resource.Resources, error) { |
| 225 |
var res resource.Resources |
| 226 |
|
| 227 |
handle := func(info hugofs.FileMetaInfo) (bool, error) { |
| 228 |
r, err := c.getOrCreateFileResource(info) |
| 229 |
if err != nil { |
| 230 |
return true, err |
| 231 |
} |
| 232 |
|
| 233 |
if matchFunc != nil && !matchFunc(r) { |
| 234 |
return false, nil |
| 235 |
} |
| 236 |
|
| 237 |
res = append(res, r) |
| 238 |
|
| 239 |
return firstOnly, nil |
| 240 |
} |
| 241 |
|
| 242 |
if err := hugofs.Glob(c.rs.BaseFs.Assets.Fs, pattern, handle); err != nil { |
| 243 |
return nil, err |
| 244 |
} |
| 245 |
|
| 246 |
return res, nil |
| 247 |
}) |
| 248 |
} |
| 249 |
|
| 250 |
type Options struct { |
| 251 |
// The target path relative to the publish directory. |
| 252 |
// Unix style path, i.e. "images/logo.png". |
| 253 |
TargetPath string |
| 254 |
|
| 255 |
// Whether the TargetPath has a hash in it which will change if the resource changes. |
| 256 |
// If not, we will calculate a hash from the content. |
| 257 |
TargetPathHasHash bool |
| 258 |
|
| 259 |
// The content to create the Resource from. |
| 260 |
CreateContent func() (func() (hugio.ReadSeekCloser, error), error) |
| 261 |
} |
| 262 |
|
| 263 |
// FromOpts creates a new Resource from the given Options. |
| 264 |
// Make sure to set optis.TargetPathHasHash if the TargetPath already contains a hash, |
| 265 |
// as this avoids the need to calculate it. |
| 266 |
// To create a new ReadSeekCloser from a string, use hugio.NewReadSeekerNoOpCloserFromString, |
| 267 |
// or hugio.NewReadSeekerNoOpCloserFromBytes for a byte slice. |
| 268 |
// See FromString. |
| 269 |
func (c *Client) FromOpts(opts Options) (resource.Resource, error) { |
| 270 |
opts.TargetPath = path.Clean(opts.TargetPath) |
| 271 |
var hash string |
| 272 |
var newReadSeeker func() (hugio.ReadSeekCloser, error) = nil |
| 273 |
if !opts.TargetPathHasHash { |
| 274 |
var err error |
| 275 |
newReadSeeker, err = opts.CreateContent() |
| 276 |
if err != nil { |
| 277 |
return nil, err |
| 278 |
} |
| 279 |
if err := func() error { |
| 280 |
r, err := newReadSeeker() |
| 281 |
if err != nil { |
| 282 |
return err |
| 283 |
} |
| 284 |
defer r.Close() |
| 285 |
|
| 286 |
hash, err = hashing.XxHashFromReaderHexEncoded(r) |
| 287 |
if err != nil { |
| 288 |
return err |
| 289 |
} |
| 290 |
return nil |
| 291 |
}(); err != nil { |
| 292 |
return nil, err |
| 293 |
} |
| 294 |
} |
| 295 |
|
| 296 |
key := dynacache.CleanKey(opts.TargetPath) + hash |
| 297 |
r, err := c.rs.ResourceCache.GetOrCreate(key, func() (resource.Resource, error) { |
| 298 |
if newReadSeeker == nil { |
| 299 |
var err error |
| 300 |
newReadSeeker, err = opts.CreateContent() |
| 301 |
if err != nil { |
| 302 |
return nil, err |
| 303 |
} |
| 304 |
} |
| 305 |
return c.rs.NewResource( |
| 306 |
resources.ResourceSourceDescriptor{ |
| 307 |
LazyPublish: true, |
| 308 |
IncludeHashInKey: !opts.TargetPathHasHash, |
| 309 |
GroupIdentity: identity.Anonymous, // All usage of this resource are tracked via its string content. |
| 310 |
OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { |
| 311 |
return newReadSeeker() |
| 312 |
}, |
| 313 |
TargetPath: opts.TargetPath, |
| 314 |
}) |
| 315 |
}) |
| 316 |
|
| 317 |
return r, err |
| 318 |
} |
| 319 |
|
| 320 |
// FromString creates a new Resource from a string with the given relative target path. |
| 321 |
func (c *Client) FromString(targetPath, content string) (resource.Resource, error) { |
| 322 |
return c.FromOpts(Options{ |
| 323 |
TargetPath: targetPath, |
| 324 |
CreateContent: func() (func() (hugio.ReadSeekCloser, error), error) { |
| 325 |
return func() (hugio.ReadSeekCloser, error) { |
| 326 |
return hugio.NewReadSeekerNoOpCloserFromString(content), nil |
| 327 |
}, nil |
| 328 |
}, |
| 329 |
}) |
| 330 |
} |