You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.go 2.2KB

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