~james/core

core/spindle/engine/cache_controller.go -rw-r--r-- 18.2 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 14 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
package engine

import (
	"context"
	"crypto/sha256"
	"database/sql"
	"encoding/hex"
	"errors"
	"fmt"
	"hash"
	"io"
	"log/slog"
	"net/url"
	"os/exec"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"github.com/google/uuid"
	"tangled.org/core/spindle/db"
	"tangled.org/core/spindle/models"
	"tangled.org/core/spindle/quota"
	"tangled.org/core/spindle/storage"
	"tangled.org/core/workflow"
)

type CacheUpdateAction int

const (
	CacheUsed CacheUpdateAction = iota + 1
	CacheStored
	CacheDiscarded
	CacheMissing
)

type CacheUpdate struct {
	Action    CacheUpdateAction
	ID        string
	Ref       string
	SizeBytes int64
	Checksum  string
}

type CacheController interface {
	Plan(ctx context.Context, pipeline *models.Pipeline, workflow *models.Workflow) ([]models.CacheBinding, error)
	Apply(ctx context.Context, update CacheUpdate) error
}

type localCacheController struct {
	index              *db.DB
	quota              *db.QuotaStore
	store              storage.Storage
	repoDir            string
	maxEntriesPerOwner int64
	maxBytes           int64
	logger             *slog.Logger
}

// a nil qs leaves cache entries uncharged
func NewLocalCacheController(index *db.DB, qs *db.QuotaStore, store storage.Storage, repoDir string, maxEntriesPerOwner, maxBytes int64, logger *slog.Logger) CacheController {
	return &localCacheController{
		index:              index,
		quota:              qs,
		store:              store,
		repoDir:            repoDir,
		maxEntriesPerOwner: maxEntriesPerOwner,
		maxBytes:           maxBytes,
		logger:             logger,
	}
}

// on a hash miss, the newest older generation still warms the build
// unusable entries degrade to a plain miss
func resolveCaches(ctx context.Context, l *slog.Logger, index *db.DB, repoDID, engine, repoPath, rev string, entries []models.CacheEntry) []models.CacheBinding {
	resolved := make([]models.CacheBinding, 0, len(entries))
	for entryIndex, entry := range entries {
		hash := ""
		if len(entry.Hash) > 0 && repoPath != "" {
			sum, missing := hashKeyFilesLegacy(ctx, repoPath, rev, entry.Hash)
			for _, m := range missing {
				l.Warn("cache hash file not in repo", "key", entry.Key, "path", m)
			}
			hash = sum
		}
		binding := models.CacheBinding{
			EntryIndex:       entryIndex,
			Paths:            entry.Paths,
			Key:              entry.Key,
			Hash:             hash,
			CompressionLevel: entry.CompressionLevel,
			When:             entry.When,
		}

		found, err := index.FindCacheEntry(ctx, repoDID, engine, entry.Key, hash)
		if errors.Is(err, sql.ErrNoRows) && hash != "" {
			found, err = index.FindFallbackCacheEntry(ctx, repoDID, engine, entry.Key, hash)
			if err == nil {
				binding.RestoreName = entry.Key + "-" + found.CacheHash
			}
		}
		if err != nil && !errors.Is(err, sql.ErrNoRows) {
			l.Warn("cache lookup failed; entry will save but not restore", "key", entry.Key, "err", err)
		} else if err == nil {
			binding.RestoreID = found.ID
			binding.RestoreKey = found.StorageKey
		}
		resolved = append(resolved, binding)
	}
	return resolved
}

func hashKeyFilesLegacy(ctx context.Context, repoPath, rev string, paths []string) (string, []string) {
	h := sha256.New()
	var missing []string
	hashed := 0
	for _, p := range paths {
		blob, err := gitBlobId(ctx, repoPath, rev, p)
		if err != nil {
			missing = append(missing, p)
			continue
		}
		fmt.Fprintf(h, "%s=%s\n", p, blob)
		hashed++
	}
	if hashed == 0 {
		return "", missing
	}
	return hex.EncodeToString(h.Sum(nil))[:12], missing
}

func hashKeyFiles(ctx context.Context, repoPath, rev string, paths []string) (string, []string) {
	h := sha256.New()
	var missing []string
	hashed := 0
	for _, p := range paths {
		blob, err := gitBlobId(ctx, repoPath, rev, p)
		if err != nil {
			missing = append(missing, p)
			continue
		}
		fmt.Fprintf(h, "%s=%s\n", p, blob)
		hashed++
	}
	if hashed == 0 {
		return "", missing
	}
	return hex.EncodeToString(h.Sum(nil)), missing
}

// sparse checkouts might not have the file, but the object database does
func gitBlobId(ctx context.Context, repoPath, rev, path string) (string, error) {
	out, err := exec.CommandContext(ctx, "git", "-C", repoPath, "rev-parse", rev+":"+path).Output()
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(out)), nil
}
func cacheIdentityKey(workflowName, ref, key string) string {
	return url.PathEscape(workflowName) + ":" + url.PathEscape(ref) + ":" + key
}

func pipelineRef(metadata *workflow.TriggerMetadata) string {
	if metadata == nil {
		return ""
	}
	if metadata.Push != nil {
		return metadata.Push.Ref
	}
	if pr := metadata.PullRequest; pr != nil {
		// "refs/heads/" alone would pool the caches of every pull without a source branch
		if pr.SourceBranch == "" && pr.Pull != nil {
			return *pr.Pull
		}
		return "refs/heads/" + pr.SourceBranch
	}
	if metadata.Manual != nil && metadata.Manual.Ref != nil {
		return *metadata.Manual.Ref
	}
	if metadata.Schedule != nil {
		return metadata.Schedule.Ref
	}
	return ""
}

func defaultBranchRef(metadata *workflow.TriggerMetadata) string {
	if metadata == nil || metadata.Repo == nil || metadata.Repo.DefaultBranch == "" {
		return ""
	}
	return "refs/heads/" + metadata.Repo.DefaultBranch
}

func findCache(ctx context.Context, index *db.DB, repoDID, engine, key, hash string, fallback bool) (*db.CacheEntry, error) {
	found, err := index.FindCacheEntry(ctx, repoDID, engine, key, hash)
	if errors.Is(err, sql.ErrNoRows) && fallback && hash != "" {
		return index.FindFallbackCacheEntry(ctx, repoDID, engine, key, hash)
	}
	return found, err
}

// a ref with no cache of its own restores the default branch's, but only ever saves under itself
func resolveCachesIdentity(ctx context.Context, l *slog.Logger, index *db.DB, repoDID, engine, repoPath, rev, workflowName, ref, defaultRef string, entries []models.CacheEntry) []models.CacheBinding {
	resolved := make([]models.CacheBinding, 0, len(entries))
	for i, entry := range entries {
		hash := ""
		if len(entry.Hash) > 0 && repoPath != "" {
			hash, _ = hashKeyFiles(ctx, repoPath, rev, entry.Hash)
		}
		b := models.CacheBinding{EntryIndex: i, Paths: entry.Paths, Key: entry.Key, Hash: hash, CompressionLevel: entry.CompressionLevel, When: entry.When}
		found, err := findCache(ctx, index, repoDID, engine, cacheIdentityKey(workflowName, ref, entry.Key), hash, entry.Fallback)
		if errors.Is(err, sql.ErrNoRows) && defaultRef != "" && defaultRef != ref {
			found, err = findCache(ctx, index, repoDID, engine, cacheIdentityKey(workflowName, defaultRef, entry.Key), hash, entry.Fallback)
		}
		if err == nil {
			b.RestoreID, b.RestoreKey, b.Checksum, b.SizeBytes = found.ID, found.StorageKey, found.Checksum, found.SizeBytes
			if found.CacheHash != hash {
				b.RestoreName = entry.Key + "-" + found.CacheHash
			}
		}
		if err != nil && !errors.Is(err, sql.ErrNoRows) {
			l.Warn("cache lookup failed; entry will save but not restore", "key", entry.Key, "err", err)
		}
		resolved = append(resolved, b)
	}
	return resolved
}

func (c *localCacheController) Plan(ctx context.Context, pipeline *models.Pipeline, workflow *models.Workflow) ([]models.CacheBinding, error) {
	repo, err := c.index.GetRepoByDid(pipeline.RepoDid)
	if err != nil {
		return nil, fmt.Errorf("cache owner lookup: %w", err)
	}

	repoPath, rev := "", ""
	if metadata := pipeline.TriggerMetadata; metadata != nil {
		if resolvedRev, err := models.ExtractCommitSHA(*metadata); err != nil {
			c.logger.Warn("cannot resolve pipeline commit; cache hashing disabled", "err", err)
		} else {
			did := pipeline.RepoDid.String()
			if metadata.SourceRepo != nil && *metadata.SourceRepo != "" {
				did = *metadata.SourceRepo
			}
			repoPath, rev = filepath.Join(c.repoDir, did), resolvedRev
		}
	}

	cacheNamespace := workflow.CacheNamespace
	if cacheNamespace == "" {
		cacheNamespace = models.CacheNamespace()
	}
	cacheEngine := workflow.Engine + "/" + cacheNamespace
	var bindings []models.CacheBinding
	if workflow.Name == "" && pipeline.TriggerMetadata == nil {
		bindings = resolveCaches(ctx, c.logger, c.index, pipeline.RepoDid.String(), cacheEngine, repoPath, rev, workflow.Caches)
	} else {
		bindings = resolveCachesIdentity(ctx, c.logger, c.index, pipeline.RepoDid.String(), cacheEngine, repoPath, rev, workflow.Name, pipelineRef(pipeline.TriggerMetadata), defaultBranchRef(pipeline.TriggerMetadata), workflow.Caches)
	}
	now := time.Now()
	pendingUntil := now
	// pending rows stay live through the workflow deadline
	if deadline, ok := ctx.Deadline(); ok {
		pendingUntil = deadline
	}
	for i := range bindings {
		id := uuid.NewString()
		cacheKey := bindings[i].Key
		if workflow.Name != "" || pipeline.TriggerMetadata != nil {
			cacheKey = cacheIdentityKey(workflow.Name, pipelineRef(pipeline.TriggerMetadata), cacheKey)
		}
		saveKey, err := models.CacheObjectKey(pipeline.RepoDid.String(), id)
		if err != nil {
			return nil, err
		}
		bindings[i].SaveID = id
		bindings[i].SaveKey = saveKey
		inserted, err := c.index.InsertCacheEntryWithinQuota(ctx, db.CacheEntry{
			ID:         id,
			StorageKey: bindings[i].SaveKey,
			OwnerDID:   repo.Owner.String(),
			RepoDID:    pipeline.RepoDid.String(),
			Engine:     cacheEngine,
			CacheKey:   cacheKey,
			CacheHash:  bindings[i].Hash,
			State:      "pending",
			CreatedAt:  now,
			LastUsedAt: pendingUntil,
		}, c.maxEntriesPerOwner)
		if err != nil {
			for _, planned := range bindings[:i] {
				_ = c.Apply(context.WithoutCancel(ctx), CacheUpdate{
					Action: CacheDiscarded,
					ID:     planned.SaveID,
					Ref:    planned.SaveKey,
				})
			}
			for j := range bindings {
				bindings[j].SaveID = ""
				bindings[j].SaveKey = ""
			}
			c.logger.Warn("cache save reservations failed; restoring only", "err", err)
			return bindings, nil
		}
		if !inserted {
			bindings[i].SaveID = ""
			bindings[i].SaveKey = ""
		}
	}
	return bindings, nil
}

type cacheByteReserver interface {
	reserveBytes(context.Context, models.CacheBinding) (int64, error)
}

// an archive bigger than the whole cache or one of its owner's limits could never be kept
func (c *localCacheController) reserveBytes(ctx context.Context, binding models.CacheBinding) (int64, error) {
	entry, err := c.index.GetCacheEntry(ctx, binding.SaveID)
	if err != nil {
		return 0, err
	}
	if entry.State != "pending" {
		return 0, sql.ErrNoRows
	}
	limit := c.maxBytes
	if c.quota == nil {
		return limit, nil
	}
	for _, subject := range []struct {
		scope quota.Scope
		did   string
	}{{quota.ScopeRepo, entry.RepoDID}, {quota.ScopeUser, entry.OwnerDID}} {
		l, err := c.quota.LimitFor(ctx, subject.scope, subject.did, quota.ResourceCacheStorageBytes)
		if err != nil {
			return 0, err
		}
		if l != nil && (limit == 0 || *l < limit) {
			limit = *l
		}
	}
	return limit, nil
}

func (c *localCacheController) Apply(ctx context.Context, update CacheUpdate) error {
	now := time.Now()
	switch update.Action {
	case CacheUsed:
		return c.index.TouchCacheEntry(ctx, update.ID, now)
	case CacheStored:
		superseded, err := c.index.MarkCacheEntryReadyWithChecksum(ctx, update.ID, update.SizeBytes, update.Checksum, c.quota, c.maxBytes, now)
		if err != nil {
			_ = c.store.Delete(context.WithoutCancel(ctx), update.Ref)
			return err
		}
		for _, old := range superseded {
			if err := c.deleteEntry(context.WithoutCancel(ctx), old.StorageKey, old.ID); err != nil {
				c.logger.Warn("delete replaced cache failed", "id", old.ID, "err", err)
			}
		}
	case CacheDiscarded, CacheMissing:
		if update.Action == CacheDiscarded {
			claimed, err := c.index.ClaimPendingCacheEntry(ctx, update.ID)
			if err != nil || !claimed {
				return err
			}
		}
		return c.deleteEntry(ctx, update.Ref, update.ID)
	default:
		return fmt.Errorf("unknown cache update action %d", update.Action)
	}
	return nil
}

func (c *localCacheController) deleteEntry(ctx context.Context, ref, id string) error {
	pinned, err := c.index.CacheEntryPinned(ctx, id)
	if err != nil {
		return err
	}
	if pinned {
		return c.index.ApplyEventBatch(nil, func(tx *db.EventBatchTx) error { return tx.QueueCacheObjectDeletion(ctx, ref, time.Now()) })
	}
	if err := c.store.Delete(ctx, ref); err != nil {
		return err
	}
	return c.index.DeleteCacheEntry(ctx, id)
}

type preplannedCacheController struct {
	apply func(context.Context, CacheUpdate) error
}

func NewPreplannedCacheController(apply func(context.Context, CacheUpdate) error) CacheController {
	return &preplannedCacheController{apply: apply}
}

func (c *preplannedCacheController) Plan(_ context.Context, _ *models.Pipeline, workflow *models.Workflow) ([]models.CacheBinding, error) {
	return workflow.CacheBindings, nil
}

func (c *preplannedCacheController) Apply(ctx context.Context, update CacheUpdate) error {
	return c.apply(ctx, update)
}

type trackedCacheStore struct {
	storage.Storage
	controller CacheController
	logger     *slog.Logger
	mu         sync.Mutex
	restores   map[string]models.CacheBinding
	saves      map[string]models.CacheBinding
}

func newTrackedCacheStore(base storage.Storage, controller CacheController, logger *slog.Logger, bindings []models.CacheBinding) *trackedCacheStore {
	store := &trackedCacheStore{
		Storage:    base,
		controller: controller,
		logger:     logger,
		restores:   make(map[string]models.CacheBinding, len(bindings)),
		saves:      make(map[string]models.CacheBinding, len(bindings)),
	}
	for _, binding := range bindings {
		if binding.RestoreKey != "" {
			store.restores[binding.RestoreKey] = binding
		}
		if binding.SaveKey != "" {
			store.saves[binding.SaveKey] = binding
		}
	}
	return store
}

func (s *trackedCacheStore) beginRestore(ctx context.Context, id string) (bool, *db.DB, error) {
	if c, ok := s.controller.(*localCacheController); ok {
		pinned, err := c.index.BeginCacheRestore(ctx, id)
		return pinned, c.index, err
	}
	return true, nil, nil
}
func (s *trackedCacheStore) endRestore(ctx context.Context, id string) error {
	if c, ok := s.controller.(*localCacheController); ok {
		return c.index.EndCacheRestore(ctx, id)
	}
	return nil
}

func (s *trackedCacheStore) Get(ctx context.Context, key string) (io.ReadCloser, error) {
	s.mu.Lock()
	binding, tracked := s.restores[key]
	s.mu.Unlock()
	if !tracked {
		return nil, fmt.Errorf("cache metadata missing for %q", key)
	}

	pinned, index, err := s.beginRestore(ctx, binding.RestoreID)
	if err != nil {
		return nil, err
	}
	if !pinned {
		return nil, storage.ErrNotExist
	}
	reader, err := s.Storage.Get(ctx, key)
	if err != nil {
		_ = s.endRestore(context.WithoutCancel(ctx), binding.RestoreID)
		if errors.Is(err, storage.ErrNotExist) {
			_ = s.controller.Apply(context.WithoutCancel(ctx), CacheUpdate{Action: CacheMissing, ID: binding.RestoreID, Ref: binding.RestoreKey})
		}
		return nil, err
	}
	if err := s.controller.Apply(ctx, CacheUpdate{
		Action: CacheUsed,
		ID:     binding.RestoreID,
		Ref:    binding.RestoreKey,
	}); err != nil {
		s.logger.Warn("cache usage update failed", "id", binding.RestoreID, "err", err)
	}
	return &verifiedCacheReader{ReadCloser: reader, expected: binding.Checksum, expectedSize: binding.SizeBytes, id: binding.RestoreID, index: index}, nil
}

type verifiedCacheReader struct {
	io.ReadCloser
	expected     string
	expectedSize int64
	id           string
	index        *db.DB
	h            hash.Hash
	n            int64
	checked      bool
}

func (r *verifiedCacheReader) verify() error {
	if r.expectedSize > 0 && r.n != r.expectedSize {
		return fmt.Errorf("cache object size mismatch: got %d, want %d", r.n, r.expectedSize)
	}
	if r.expected != "" && hex.EncodeToString(r.h.Sum(nil)) != r.expected {
		return fmt.Errorf("cache object checksum mismatch")
	}
	return nil
}

func (r *verifiedCacheReader) Read(p []byte) (int, error) {
	if r.h == nil {
		r.h = sha256.New()
	}
	n, err := r.ReadCloser.Read(p)
	if n > 0 {
		_, _ = r.h.Write(p[:n])
		r.n += int64(n)
	}
	if err == io.EOF {
		r.checked = true
		if verifyErr := r.verify(); verifyErr != nil {
			return n, verifyErr
		}
	}
	return n, err
}

func (r *verifiedCacheReader) Close() error {
	var err error
	if !r.checked {
		if r.h == nil {
			r.h = sha256.New()
		}
		_, err = io.Copy(io.Discard, r)
		if err == nil {
			r.checked = true
			err = r.verify()
		}
	}
	if closeErr := r.ReadCloser.Close(); err == nil {
		err = closeErr
	}
	if r.index != nil {
		if endErr := r.index.EndCacheRestore(context.Background(), r.id); err == nil {
			err = endErr
		}
	}
	return err
}

func (s *trackedCacheStore) Put(ctx context.Context, key string, reader io.Reader) error {
	s.mu.Lock()
	binding, tracked := s.saves[key]
	s.mu.Unlock()
	if !tracked {
		return fmt.Errorf("cache metadata missing for %q", key)
	}

	limit := int64(0)
	if reserver, ok := s.controller.(cacheByteReserver); ok {
		var err error
		limit, err = reserver.reserveBytes(ctx, binding)
		if err != nil {
			return err
		}
	}
	counted := &countingReader{r: reader, limit: limit, h: sha256.New()}
	put := s.Storage.Put
	if conditional, ok := s.Storage.(storage.ConditionalStorage); ok {
		put = func(ctx context.Context, key string, r io.Reader) error { return conditional.PutIfAbsent(ctx, key, r) }
	}
	if err := put(ctx, key, counted); err != nil {
		_ = s.Storage.Delete(context.WithoutCancel(ctx), key)
		return err
	}
	if err := s.controller.Apply(ctx, CacheUpdate{
		Action:    CacheStored,
		ID:        binding.SaveID,
		Ref:       binding.SaveKey,
		SizeBytes: counted.n,
		Checksum:  hex.EncodeToString(counted.h.Sum(nil)),
	}); err != nil {
		_ = s.Storage.Delete(context.WithoutCancel(ctx), key)
		return fmt.Errorf("record cache upload: %w", err)
	}

	s.mu.Lock()
	delete(s.saves, key)
	s.mu.Unlock()
	return nil
}

func (s *trackedCacheStore) cleanup(ctx context.Context) {
	s.mu.Lock()
	pending := make([]models.CacheBinding, 0, len(s.saves))
	for _, binding := range s.saves {
		pending = append(pending, binding)
	}
	clear(s.saves)
	s.mu.Unlock()

	for _, binding := range pending {
		if err := s.controller.Apply(ctx, CacheUpdate{
			Action: CacheDiscarded,
			ID:     binding.SaveID,
			Ref:    binding.SaveKey,
		}); err != nil {
			s.logger.Warn("discard incomplete cache failed", "id", binding.SaveID, "err", err)
		}
	}
}

var ErrCacheObjectTooLarge = errors.New("cache object exceeds a cache byte limit")

type countingReader struct {
	r     io.Reader
	n     int64
	limit int64
	h     hash.Hash
}

func (r *countingReader) Read(p []byte) (int, error) {
	if r.limit > 0 {
		remaining := r.limit - r.n
		if remaining <= 0 {
			return 0, ErrCacheObjectTooLarge
		}
		if int64(len(p)) > remaining {
			p = p[:remaining]
		}
	}
	n, err := r.r.Read(p)
	r.n += int64(n)
	if n > 0 && r.h != nil {
		_, _ = r.h.Write(p[:n])
	}
	return n, err
}