y.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. /*
  2. * SPDX-FileCopyrightText: © 2017-2025 Istari Digital, Inc.
  3. * SPDX-License-Identifier: Apache-2.0
  4. */
  5. package y
  6. import (
  7. "bytes"
  8. "encoding/binary"
  9. stderrors "errors"
  10. "fmt"
  11. "hash/crc32"
  12. "io"
  13. "math"
  14. "os"
  15. "reflect"
  16. "strconv"
  17. "sync"
  18. "time"
  19. "unsafe"
  20. "github.com/dgraph-io/badger/v4/pb"
  21. "github.com/dgraph-io/ristretto/v2/z"
  22. )
  23. var (
  24. // ErrEOF indicates an end of file when trying to read from a memory mapped file
  25. // and encountering the end of slice.
  26. ErrEOF = stderrors.New("ErrEOF: End of file")
  27. // ErrCommitAfterFinish indicates that write batch commit was called after
  28. // finish
  29. ErrCommitAfterFinish = stderrors.New("Batch commit not permitted after finish")
  30. )
  31. type Flags int
  32. const (
  33. // Sync indicates that O_DSYNC should be set on the underlying file,
  34. // ensuring that data writes do not return until the data is flushed
  35. // to disk.
  36. Sync Flags = 1 << iota
  37. // ReadOnly opens the underlying file on a read-only basis.
  38. ReadOnly
  39. )
  40. var (
  41. // This is O_DSYNC (datasync) on platforms that support it -- see file_unix.go
  42. datasyncFileFlag = 0x0
  43. // CastagnoliCrcTable is a CRC32 polynomial table
  44. CastagnoliCrcTable = crc32.MakeTable(crc32.Castagnoli)
  45. )
  46. // OpenExistingFile opens an existing file, errors if it doesn't exist.
  47. func OpenExistingFile(filename string, flags Flags) (*os.File, error) {
  48. openFlags := os.O_RDWR
  49. if flags&ReadOnly != 0 {
  50. openFlags = os.O_RDONLY
  51. }
  52. if flags&Sync != 0 {
  53. openFlags |= datasyncFileFlag
  54. }
  55. return os.OpenFile(filename, openFlags, 0)
  56. }
  57. // CreateSyncedFile creates a new file (using O_EXCL), errors if it already existed.
  58. func CreateSyncedFile(filename string, sync bool) (*os.File, error) {
  59. flags := os.O_RDWR | os.O_CREATE | os.O_EXCL
  60. if sync {
  61. flags |= datasyncFileFlag
  62. }
  63. return os.OpenFile(filename, flags, 0600)
  64. }
  65. // OpenSyncedFile creates the file if one doesn't exist.
  66. func OpenSyncedFile(filename string, sync bool) (*os.File, error) {
  67. flags := os.O_RDWR | os.O_CREATE
  68. if sync {
  69. flags |= datasyncFileFlag
  70. }
  71. return os.OpenFile(filename, flags, 0600)
  72. }
  73. // OpenTruncFile opens the file with O_RDWR | O_CREATE | O_TRUNC
  74. func OpenTruncFile(filename string, sync bool) (*os.File, error) {
  75. flags := os.O_RDWR | os.O_CREATE | os.O_TRUNC
  76. if sync {
  77. flags |= datasyncFileFlag
  78. }
  79. return os.OpenFile(filename, flags, 0600)
  80. }
  81. // SafeCopy does append(a[:0], src...).
  82. func SafeCopy(a, src []byte) []byte {
  83. b := append(a[:0], src...)
  84. if b == nil {
  85. return []byte{}
  86. }
  87. return b
  88. }
  89. // Copy copies a byte slice and returns the copied slice.
  90. func Copy(a []byte) []byte {
  91. b := make([]byte, len(a))
  92. copy(b, a)
  93. return b
  94. }
  95. // KeyWithTs generates a new key by appending ts to key.
  96. func KeyWithTs(key []byte, ts uint64) []byte {
  97. out := make([]byte, len(key)+8)
  98. copy(out, key)
  99. binary.BigEndian.PutUint64(out[len(key):], math.MaxUint64-ts)
  100. return out
  101. }
  102. // ParseTs parses the timestamp from the key bytes.
  103. func ParseTs(key []byte) uint64 {
  104. if len(key) <= 8 {
  105. return 0
  106. }
  107. return math.MaxUint64 - binary.BigEndian.Uint64(key[len(key)-8:])
  108. }
  109. // CompareKeys checks the key without timestamp and checks the timestamp if keyNoTs
  110. // is same.
  111. // a<timestamp> would be sorted higher than aa<timestamp> if we use bytes.compare
  112. // All keys should have timestamp.
  113. func CompareKeys(key1, key2 []byte) int {
  114. if cmp := bytes.Compare(key1[:len(key1)-8], key2[:len(key2)-8]); cmp != 0 {
  115. return cmp
  116. }
  117. return bytes.Compare(key1[len(key1)-8:], key2[len(key2)-8:])
  118. }
  119. // ParseKey parses the actual key from the key bytes.
  120. func ParseKey(key []byte) []byte {
  121. if len(key) < 8 {
  122. return nil
  123. }
  124. return key[:len(key)-8]
  125. }
  126. // SameKey checks for key equality ignoring the version timestamp suffix.
  127. func SameKey(src, dst []byte) bool {
  128. if len(src) != len(dst) {
  129. return false
  130. }
  131. return bytes.Equal(ParseKey(src), ParseKey(dst))
  132. }
  133. // Slice holds a reusable buf, will reallocate if you request a larger size than ever before.
  134. // One problem is with n distinct sizes in random order it'll reallocate log(n) times.
  135. type Slice struct {
  136. buf []byte
  137. }
  138. // Resize reuses the Slice's buffer (or makes a new one) and returns a slice in that buffer of
  139. // length sz.
  140. func (s *Slice) Resize(sz int) []byte {
  141. if cap(s.buf) < sz {
  142. s.buf = make([]byte, sz)
  143. }
  144. return s.buf[0:sz]
  145. }
  146. // FixedDuration returns a string representation of the given duration with the
  147. // hours, minutes, and seconds.
  148. func FixedDuration(d time.Duration) string {
  149. str := fmt.Sprintf("%02ds", int(d.Seconds())%60)
  150. if d >= time.Minute {
  151. str = fmt.Sprintf("%02dm", int(d.Minutes())%60) + str
  152. }
  153. if d >= time.Hour {
  154. str = fmt.Sprintf("%02dh", int(d.Hours())) + str
  155. }
  156. return str
  157. }
  158. // Throttle allows a limited number of workers to run at a time. It also
  159. // provides a mechanism to check for errors encountered by workers and wait for
  160. // them to finish.
  161. type Throttle struct {
  162. once sync.Once
  163. wg sync.WaitGroup
  164. ch chan struct{}
  165. errCh chan error
  166. finishErr error
  167. }
  168. // NewThrottle creates a new throttle with a max number of workers.
  169. func NewThrottle(max int) *Throttle {
  170. return &Throttle{
  171. ch: make(chan struct{}, max),
  172. errCh: make(chan error, max),
  173. }
  174. }
  175. // Do should be called by workers before they start working. It blocks if there
  176. // are already maximum number of workers working. If it detects an error from
  177. // previously Done workers, it would return it.
  178. func (t *Throttle) Do() error {
  179. for {
  180. select {
  181. case t.ch <- struct{}{}:
  182. t.wg.Add(1)
  183. return nil
  184. case err := <-t.errCh:
  185. if err != nil {
  186. return err
  187. }
  188. }
  189. }
  190. }
  191. // Done should be called by workers when they finish working. They can also
  192. // pass the error status of work done.
  193. func (t *Throttle) Done(err error) {
  194. if err != nil {
  195. t.errCh <- err
  196. }
  197. select {
  198. case <-t.ch:
  199. default:
  200. panic("Throttle Do Done mismatch")
  201. }
  202. t.wg.Done()
  203. }
  204. // Finish waits until all workers have finished working. It would return any error passed by Done.
  205. // If Finish is called multiple time, it will wait for workers to finish only once(first time).
  206. // From next calls, it will return same error as found on first call.
  207. func (t *Throttle) Finish() error {
  208. t.once.Do(func() {
  209. t.wg.Wait()
  210. close(t.ch)
  211. close(t.errCh)
  212. for err := range t.errCh {
  213. if err != nil {
  214. t.finishErr = err
  215. return
  216. }
  217. }
  218. })
  219. return t.finishErr
  220. }
  221. // U16ToBytes converts the given Uint16 to bytes
  222. func U16ToBytes(v uint16) []byte {
  223. var uBuf [2]byte
  224. binary.BigEndian.PutUint16(uBuf[:], v)
  225. return uBuf[:]
  226. }
  227. // BytesToU16 converts the given byte slice to uint16
  228. func BytesToU16(b []byte) uint16 {
  229. return binary.BigEndian.Uint16(b)
  230. }
  231. // U32ToBytes converts the given Uint32 to bytes
  232. func U32ToBytes(v uint32) []byte {
  233. var uBuf [4]byte
  234. binary.BigEndian.PutUint32(uBuf[:], v)
  235. return uBuf[:]
  236. }
  237. // BytesToU32 converts the given byte slice to uint32
  238. func BytesToU32(b []byte) uint32 {
  239. return binary.BigEndian.Uint32(b)
  240. }
  241. // U32SliceToBytes converts the given Uint32 slice to byte slice
  242. func U32SliceToBytes(u32s []uint32) []byte {
  243. if len(u32s) == 0 {
  244. return nil
  245. }
  246. var b []byte
  247. hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  248. hdr.Len = len(u32s) * 4
  249. hdr.Cap = hdr.Len
  250. hdr.Data = uintptr(unsafe.Pointer(&u32s[0]))
  251. return b
  252. }
  253. // BytesToU32Slice converts the given byte slice to uint32 slice
  254. func BytesToU32Slice(b []byte) []uint32 {
  255. if len(b) == 0 {
  256. return nil
  257. }
  258. var u32s []uint32
  259. hdr := (*reflect.SliceHeader)(unsafe.Pointer(&u32s))
  260. hdr.Len = len(b) / 4
  261. hdr.Cap = hdr.Len
  262. hdr.Data = uintptr(unsafe.Pointer(&b[0]))
  263. return u32s
  264. }
  265. // U64ToBytes converts the given Uint64 to bytes
  266. func U64ToBytes(v uint64) []byte {
  267. var uBuf [8]byte
  268. binary.BigEndian.PutUint64(uBuf[:], v)
  269. return uBuf[:]
  270. }
  271. // BytesToU64 converts the given byte slice to uint64
  272. func BytesToU64(b []byte) uint64 {
  273. return binary.BigEndian.Uint64(b)
  274. }
  275. // U64SliceToBytes converts the given Uint64 slice to byte slice
  276. func U64SliceToBytes(u64s []uint64) []byte {
  277. if len(u64s) == 0 {
  278. return nil
  279. }
  280. var b []byte
  281. hdr := (*reflect.SliceHeader)(unsafe.Pointer(&b))
  282. hdr.Len = len(u64s) * 8
  283. hdr.Cap = hdr.Len
  284. hdr.Data = uintptr(unsafe.Pointer(&u64s[0]))
  285. return b
  286. }
  287. // BytesToU64Slice converts the given byte slice to uint64 slice
  288. func BytesToU64Slice(b []byte) []uint64 {
  289. if len(b) == 0 {
  290. return nil
  291. }
  292. var u64s []uint64
  293. hdr := (*reflect.SliceHeader)(unsafe.Pointer(&u64s))
  294. hdr.Len = len(b) / 8
  295. hdr.Cap = hdr.Len
  296. hdr.Data = uintptr(unsafe.Pointer(&b[0]))
  297. return u64s
  298. }
  299. // page struct contains one underlying buffer.
  300. type page struct {
  301. buf []byte
  302. }
  303. // PageBuffer consists of many pages. A page is a wrapper over []byte. PageBuffer can act as a
  304. // replacement of bytes.Buffer. Instead of having single underlying buffer, it has multiple
  305. // underlying buffers. Hence it avoids any copy during relocation(as happens in bytes.Buffer).
  306. // PageBuffer allocates memory in pages. Once a page is full, it will allocate page with double the
  307. // size of previous page. Its function are not thread safe.
  308. type PageBuffer struct {
  309. pages []*page
  310. length int // Length of PageBuffer.
  311. nextPageSize int // Size of next page to be allocated.
  312. }
  313. // NewPageBuffer returns a new PageBuffer with first page having size pageSize.
  314. func NewPageBuffer(pageSize int) *PageBuffer {
  315. b := &PageBuffer{}
  316. b.pages = append(b.pages, &page{buf: make([]byte, 0, pageSize)})
  317. b.nextPageSize = pageSize * 2
  318. return b
  319. }
  320. // Write writes data to PageBuffer b. It returns number of bytes written and any error encountered.
  321. func (b *PageBuffer) Write(data []byte) (int, error) {
  322. dataLen := len(data)
  323. for {
  324. cp := b.pages[len(b.pages)-1] // Current page.
  325. n := copy(cp.buf[len(cp.buf):cap(cp.buf)], data)
  326. cp.buf = cp.buf[:len(cp.buf)+n]
  327. b.length += n
  328. if len(data) == n {
  329. break
  330. }
  331. data = data[n:]
  332. b.pages = append(b.pages, &page{buf: make([]byte, 0, b.nextPageSize)})
  333. b.nextPageSize *= 2
  334. }
  335. return dataLen, nil
  336. }
  337. // WriteByte writes data byte to PageBuffer and returns any encountered error.
  338. func (b *PageBuffer) WriteByte(data byte) error {
  339. _, err := b.Write([]byte{data})
  340. return err
  341. }
  342. // Len returns length of PageBuffer.
  343. func (b *PageBuffer) Len() int {
  344. return b.length
  345. }
  346. // pageForOffset returns pageIdx and startIdx for the offset.
  347. func (b *PageBuffer) pageForOffset(offset int) (int, int) {
  348. AssertTrue(offset < b.length)
  349. var pageIdx, startIdx, sizeNow int
  350. for i := 0; i < len(b.pages); i++ {
  351. cp := b.pages[i]
  352. if sizeNow+len(cp.buf)-1 < offset {
  353. sizeNow += len(cp.buf)
  354. } else {
  355. pageIdx = i
  356. startIdx = offset - sizeNow
  357. break
  358. }
  359. }
  360. return pageIdx, startIdx
  361. }
  362. // Truncate truncates PageBuffer to length n.
  363. func (b *PageBuffer) Truncate(n int) {
  364. pageIdx, startIdx := b.pageForOffset(n)
  365. // For simplicity of the code reject extra pages. These pages can be kept.
  366. b.pages = b.pages[:pageIdx+1]
  367. cp := b.pages[len(b.pages)-1]
  368. cp.buf = cp.buf[:startIdx]
  369. b.length = n
  370. }
  371. // Bytes returns whole Buffer data as single []byte.
  372. func (b *PageBuffer) Bytes() []byte {
  373. buf := make([]byte, b.length)
  374. written := 0
  375. for i := 0; i < len(b.pages); i++ {
  376. written += copy(buf[written:], b.pages[i].buf)
  377. }
  378. return buf
  379. }
  380. // WriteTo writes whole buffer to w. It returns number of bytes written and any error encountered.
  381. func (b *PageBuffer) WriteTo(w io.Writer) (int64, error) {
  382. written := int64(0)
  383. for i := 0; i < len(b.pages); i++ {
  384. n, err := w.Write(b.pages[i].buf)
  385. written += int64(n)
  386. if err != nil {
  387. return written, err
  388. }
  389. }
  390. return written, nil
  391. }
  392. // NewReaderAt returns a reader which starts reading from offset in page buffer.
  393. func (b *PageBuffer) NewReaderAt(offset int) *PageBufferReader {
  394. pageIdx, startIdx := b.pageForOffset(offset)
  395. return &PageBufferReader{
  396. buf: b,
  397. pageIdx: pageIdx,
  398. startIdx: startIdx,
  399. }
  400. }
  401. // PageBufferReader is a reader for PageBuffer.
  402. type PageBufferReader struct {
  403. buf *PageBuffer // Underlying page buffer.
  404. pageIdx int // Idx of page from where it will start reading.
  405. startIdx int // Idx inside page - buf.pages[pageIdx] from where it will start reading.
  406. }
  407. // Read reads upto len(p) bytes. It returns number of bytes read and any error encountered.
  408. func (r *PageBufferReader) Read(p []byte) (int, error) {
  409. // Check if there is enough to Read.
  410. pc := len(r.buf.pages)
  411. read := 0
  412. for r.pageIdx < pc && read < len(p) {
  413. cp := r.buf.pages[r.pageIdx] // Current Page.
  414. endIdx := len(cp.buf) // Last Idx up to which we can read from this page.
  415. n := copy(p[read:], cp.buf[r.startIdx:endIdx])
  416. read += n
  417. r.startIdx += n
  418. // Instead of len(cp.buf), we comparing with cap(cp.buf). This ensures that we move to next
  419. // page only when we have read all data. Reading from last page is an edge case. We don't
  420. // want to move to next page until last page is full to its capacity.
  421. if r.startIdx >= cap(cp.buf) {
  422. // We should move to next page.
  423. r.pageIdx++
  424. r.startIdx = 0
  425. continue
  426. }
  427. // When last page in not full to its capacity and we have read all data up to its
  428. // length, just break out of the loop.
  429. if r.pageIdx == pc-1 {
  430. break
  431. }
  432. }
  433. if read == 0 && len(p) > 0 {
  434. return read, io.EOF
  435. }
  436. return read, nil
  437. }
  438. const kvsz = int(unsafe.Sizeof(pb.KV{}))
  439. func NewKV(alloc *z.Allocator) *pb.KV {
  440. if alloc == nil {
  441. return &pb.KV{}
  442. }
  443. b := alloc.AllocateAligned(kvsz)
  444. return (*pb.KV)(unsafe.Pointer(&b[0]))
  445. }
  446. // IBytesToString converts size in bytes to human readable format.
  447. // The code is taken from humanize library and changed to provide
  448. // value upto custom decimal precision.
  449. // IBytesToString(12312412, 1) -> 11.7 MiB
  450. func IBytesToString(size uint64, precision int) string {
  451. sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
  452. base := float64(1024)
  453. if size < 10 {
  454. return fmt.Sprintf("%d B", size)
  455. }
  456. e := math.Floor(math.Log(float64(size)) / math.Log(base))
  457. suffix := sizes[int(e)]
  458. val := float64(size) / math.Pow(base, e)
  459. f := "%." + strconv.Itoa(precision) + "f %s"
  460. return fmt.Sprintf(f, val, suffix)
  461. }
  462. type RateMonitor struct {
  463. start time.Time
  464. lastSent uint64
  465. lastCapture time.Time
  466. rates []float64
  467. idx int
  468. }
  469. func NewRateMonitor(numSamples int) *RateMonitor {
  470. return &RateMonitor{
  471. start: time.Now(),
  472. rates: make([]float64, numSamples),
  473. }
  474. }
  475. const minRate = 0.0001
  476. // Capture captures the current number of sent bytes. This number should be monotonically
  477. // increasing.
  478. func (rm *RateMonitor) Capture(sent uint64) {
  479. diff := sent - rm.lastSent
  480. dur := time.Since(rm.lastCapture)
  481. rm.lastCapture, rm.lastSent = time.Now(), sent
  482. rate := float64(diff) / dur.Seconds()
  483. if rate < minRate {
  484. rate = minRate
  485. }
  486. rm.rates[rm.idx] = rate
  487. rm.idx = (rm.idx + 1) % len(rm.rates)
  488. }
  489. // Rate returns the average rate of transmission smoothed out by the number of samples.
  490. func (rm *RateMonitor) Rate() uint64 {
  491. var total float64
  492. var den float64
  493. for _, r := range rm.rates {
  494. if r < minRate {
  495. // Ignore this. We always set minRate, so this is a zero.
  496. // Typically at the start of the rate monitor, we'd have zeros.
  497. continue
  498. }
  499. total += r
  500. den += 1.0
  501. }
  502. if den < minRate {
  503. return 0
  504. }
  505. return uint64(total / den)
  506. }