code.gitea.io/gitea@v1.21.7/models/actions/utils.go (about) 1 // Copyright 2022 The Gitea Authors. All rights reserved. 2 // SPDX-License-Identifier: MIT 3 4 package actions 5 6 import ( 7 "bytes" 8 "encoding/binary" 9 "encoding/hex" 10 "errors" 11 "fmt" 12 "io" 13 "time" 14 15 auth_model "code.gitea.io/gitea/models/auth" 16 "code.gitea.io/gitea/modules/timeutil" 17 "code.gitea.io/gitea/modules/util" 18 ) 19 20 func generateSaltedToken() (string, string, string, string, error) { 21 salt, err := util.CryptoRandomString(10) 22 if err != nil { 23 return "", "", "", "", err 24 } 25 buf, err := util.CryptoRandomBytes(20) 26 if err != nil { 27 return "", "", "", "", err 28 } 29 token := hex.EncodeToString(buf) 30 hash := auth_model.HashToken(token, salt) 31 return token, salt, hash, token[len(token)-8:], nil 32 } 33 34 /* 35 LogIndexes is the index for mapping log line number to buffer offset. 36 Because it uses varint encoding, it is impossible to predict its size. 37 But we can make a simple estimate with an assumption that each log line has 200 byte, then: 38 | lines | file size | index size | 39 |-----------|---------------------|--------------------| 40 | 100 | 20 KiB(20000) | 258 B(258) | 41 | 1000 | 195 KiB(200000) | 2.9 KiB(2958) | 42 | 10000 | 1.9 MiB(2000000) | 34 KiB(34715) | 43 | 100000 | 19 MiB(20000000) | 386 KiB(394715) | 44 | 1000000 | 191 MiB(200000000) | 4.1 MiB(4323626) | 45 | 10000000 | 1.9 GiB(2000000000) | 47 MiB(49323626) | 46 | 100000000 | 19 GiB(20000000000) | 490 MiB(513424280) | 47 */ 48 type LogIndexes []int64 49 50 func (indexes *LogIndexes) FromDB(b []byte) error { 51 reader := bytes.NewReader(b) 52 for { 53 v, err := binary.ReadVarint(reader) 54 if err != nil { 55 if errors.Is(err, io.EOF) { 56 return nil 57 } 58 return fmt.Errorf("binary ReadVarint: %w", err) 59 } 60 *indexes = append(*indexes, v) 61 } 62 } 63 64 func (indexes *LogIndexes) ToDB() ([]byte, error) { 65 buf, i := make([]byte, binary.MaxVarintLen64*len(*indexes)), 0 66 for _, v := range *indexes { 67 n := binary.PutVarint(buf[i:], v) 68 i += n 69 } 70 return buf[:i], nil 71 } 72 73 var timeSince = time.Since 74 75 func calculateDuration(started, stopped timeutil.TimeStamp, status Status) time.Duration { 76 if started == 0 { 77 return 0 78 } 79 s := started.AsTime() 80 if status.IsDone() { 81 return stopped.AsTime().Sub(s) 82 } 83 return timeSince(s).Truncate(time.Second) 84 }