<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gabi Sual on Medium]]></title>
        <description><![CDATA[Stories by Gabi Sual on Medium]]></description>
        <link>https://medium.com/@liuqiang9596?source=rss-ee904f8161ee------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*1fuDRgGEMJ5FVQByik-D5w.jpeg</url>
            <title>Stories by Gabi Sual on Medium</title>
            <link>https://medium.com/@liuqiang9596?source=rss-ee904f8161ee------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:21:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@liuqiang9596/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[badgerdb的写操作(VI) 将block写到sst文件中,构建布隆过滤器]]></title>
            <link>https://medium.com/@liuqiang9596/badgerdb%E7%9A%84%E5%86%99%E6%93%8D%E4%BD%9C-vi-%E5%B0%86block%E5%86%99%E5%88%B0sst%E6%96%87%E4%BB%B6%E4%B8%AD-%E6%9E%84%E5%BB%BA%E5%B8%83%E9%9A%86%E8%BF%87%E6%BB%A4%E5%99%A8-dbbb8c89b932?source=rss-ee904f8161ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbbb8c89b932</guid>
            <category><![CDATA[badgerdb]]></category>
            <category><![CDATA[flatbuffers]]></category>
            <dc:creator><![CDATA[Gabi Sual]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 09:24:34 GMT</pubDate>
            <atom:updated>2025-07-03T09:24:34.507Z</atom:updated>
            <content:encoded><![CDATA[<p>之前讨论的是将memtable 跳表中的数据读取出来写到builder中的bblock中, 此时builder会有多个bblock.</p><p>现在要将这些bblock写到sst文件中.</p><p>写到sst文件之前，先将bblock中的值截断填充bblock的元数据信息.</p><p>此时的数据结构变成了buildData,如下,blockList包含了多个bblock.</p><pre>type buildData struct {<br>    blockList []*bblock<br>    index     []byte<br>    checksum  []byte<br>    Size      int<br>    alloc     *z.Allocator<br>}</pre><p>消息从bblock到table的sst要经历过如下几个阶段:</p><p>bblock-builder-buildData</p><p>第一步 完成所有 block、索引、bloom filter、checksum 的构建，返回 buildData 结构体，包含完整 Table 二进制内容和元数据</p><pre>type buildData struct {<br>    blockList []*bblock<br>    index     []byte<br>    checksum  []byte<br>    Size      int<br>    alloc     *z.Allocator<br>}</pre><p>根据builder中keyHash的数量以及误差率计算出需要的字节数，然后将所有的keyHash写到布隆过滤器中.接下来创建索引,</p><p>遍历builder中的bblock文件,将每一个bblock的baseKey机器及其对应在builder中的偏移量以及baseKey的长度写到fbs的UOffsetT中.粒度不是每一个key而是每一个bblock。</p><p>将这些bblock的索引写到fbs中，同时将布隆过滤器也写到fbs中，还包括最大版本，未压缩的尺寸，keyHashes的长度以及在Disk中的大小等.</p><p>第二步 将 buildData 的内容拷贝到 mmap 文件的内存区域</p><p>先将所有bblock写到mmap，再写索引以及索引长度，最后是校验和和校验和长度.</p><p>第三步 调用 msync，确保内存中的数据同步到磁盘</p><p>第四步 用 mmap 文件和构建参数打开 Table，返回可读的 Table 对象，打开table时,初始化 Table 的最小/最大 key 及索引(解析 Table 索引区，初始化最小 key、最大 key、block 索引、bloom filter 等元数据)</p><p>打开table后，首先要初始化该table的最大key，最小key以及索引</p><ul><li><strong>读取并解析 Table 索引区,</strong>调用 initIndex</li></ul><p>定位并读取 Table 文件尾部的索引区和校验和</p><p>校验索引区的 checksum</p><p>解析 FlatBuffers 格式的 TableIndex，填充 Table 的元数据（如 block 索引、bloom filter、最大版本号、key 数量等）</p><p>记录索引区在 mmap 文件中的起始位置和长度</p><p>返回第一个 block 的 BlockOffset</p><ul><li><strong>初始化 smallest key</strong></li></ul><p>用第一个 block 的 baseKey 作为 Table 的最小 key</p><ul><li><strong>初始化 biggest key</strong></li></ul><p>用反向迭代器遍历，获取最后一个 block 的 key 作为 Table 的最大 key。</p><p>FlatBuffers 是一种高效的跨语言二进制序列化库，适合高性能场景下的数据结构存储和解析</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbbb8c89b932" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[badgerdb的写操作(V) blockChan对数据进行加密和压缩]]></title>
            <link>https://medium.com/@liuqiang9596/badgerdb%E7%9A%84%E5%86%99%E6%93%8D%E4%BD%9C-v-blockchan%E5%AF%B9%E6%95%B0%E6%8D%AE%E8%BF%9B%E8%A1%8C%E5%8A%A0%E5%AF%86%E5%92%8C%E5%8E%8B%E7%BC%A9-6c9b254c06aa?source=rss-ee904f8161ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c9b254c06aa</guid>
            <category><![CDATA[badgerdb]]></category>
            <dc:creator><![CDATA[Gabi Sual]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 06:57:28 GMT</pubDate>
            <atom:updated>2025-07-03T06:57:28.112Z</atom:updated>
            <content:encoded><![CDATA[<p>badgerDB转门利用协程来需要压缩和加密的数据.</p><p>如果db设置了压缩则对数据进行压缩，将压缩完的数据设置成bblock的data字段</p><p>支持Snappy和ZSTD两种压缩方式</p><p>如果db设置了加密则对数据进行加密，将加密完的数据设置成bblock的data字段.</p><p>同时更新下bblock的end值(为压缩加密完后的数据长度)</p><p>最后设置下builder中的compressedSize属性( 为压缩加密后的长度)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c9b254c06aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[badgerdb的写操作(III) Memtable满了怎么办?]]></title>
            <link>https://medium.com/@liuqiang9596/badgerdb%E7%9A%84%E5%86%99%E6%93%8D%E4%BD%9C-iii-memtable%E6%BB%A1%E4%BA%86%E6%80%8E%E4%B9%88%E5%8A%9E-851cf32c7e70?source=rss-ee904f8161ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/851cf32c7e70</guid>
            <category><![CDATA[wisekey]]></category>
            <category><![CDATA[badgerdb]]></category>
            <category><![CDATA[key-value-database]]></category>
            <dc:creator><![CDATA[Gabi Sual]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 06:24:39 GMT</pubDate>
            <atom:updated>2025-07-03T06:24:39.032Z</atom:updated>
            <content:encoded><![CDATA[<p>每一次提交事务时,badgerDB会将事务包装成requests然后交给单独的协程处理,此时在将entry写入到memtable之前都会检查下当前memtable的尺寸是否超过了规定值.默认一个memtable大小是64MB.</p><p>memtable的大小指的就是Arena的大小.每插入一个key-value就要将其编码在Arena中，同时返回该key，该value在Arena的游标位置及其对应的尺寸大小. memtable的大小就是n的值即偏移量的大小.</p><pre>type Arena struct {<br> n   atomic.Uint32<br> buf []byte<br>}</pre><p>此处只讨论memtable尺寸超过规定值的情况.此时badgerDB进入到另一层面，之前讨论的只是key-value被包装成Entry,然后变成request，最终又根据value的大小值变成存储value本身还是存储value地址的方式，最终都是落到memtable+writeAheadLog中，</p><p>现在就是要对memtable作为一个单元进行处理，此时会将memtable发送到新的channel中(flushChan)，badger会有一个专门的协程来处理完整的memtable，这里面就涉及到各种压缩操作。</p><p>对于memtable用满了的情况，badgerDB会将该memtable 复制给immutable memtable，然后重新创建一个新的memtable。</p><blockquote>为了专注于讨论单一模块,我们假设这是第一次memtbale满了.</blockquote><h3>flushChan用来处理memtable</h3><p>memtable用满后会将该memtable传递给db的flushChan这个channel中</p><p>badgerDB会创建一个协程来处理flushChan中的memtable.</p><p>利用for range的语法特性实现不停从channel中去读memtable的值,如果channel没有输出就一直阻塞.</p><p>下面代码的 for mt := range db.flushChan 会保证不断从channel中取出memtable进行处理，直到channel关闭.for … range会阻塞等待新元素到来，每次取出一个元素赋值给mt,然后执行循环体.</p><pre> for mt := range db.flushChan {<br>  if mt == nil {<br>   continue<br>  }<br><br>  for {<br>   if err := db.handleMemTableFlush(mt, nil); err != nil {<br>    // Encountered error. Retry indefinitely.<br>    db.opt.Errorf(&quot;error flushing memtable to disk: %v, retrying&quot;, err)<br>    time.Sleep(time.Second)<br>    continue<br>   }<br>……<br>  }<br> }</pre><p>memtable满了后会将跳表转化成另一种存储形式,演变过程如下:</p><blockquote>step1: skipList的key-value</blockquote><p>跳表中会将key-value以node为单位存储在arena中，但是对外暴露时会返回真实的key和value.</p><blockquote>step2: 存储在Builder中</blockquote><p>builder 的结构如下:</p><p>key-value实际上会存储在bblock中, 但是一些元数据信息会存储在Builder一层.</p><p>其中跳表中的key会存储key与version(对应事务的版本).</p><p>此时只会读取出真正的key，此时对key进行布隆hash运算,采用的算法是MurmurHash，并将计算好后的hash存储到Builder的数组keyHashes中.</p><p>builder的MaxVersion表示的是当前builder的最大版本，version这个值来自于事务,db每一次运行时都会将事务加1，这里貌似有个问题，db关闭又重启后version该如何计算？</p><pre>type Builder struct {<br>    // Typically tens or hundreds of meg. This is for one single file.<br>    alloc            *z.Allocator<br>    curBlock         *bblock<br>    compressedSize   atomic.Uint32<br>    uncompressedSize atomic.Uint32<br><br>    lenOffsets    uint32<br>    keyHashes     []uint32 // Used for building the bloomfilter.<br>    opts          *Options<br>    maxVersion    uint64<br>    onDiskSize    uint32<br>    staleDataSize int<br><br>    // Used to concurrently compress/encrypt blocks.<br>    wg        sync.WaitGroup<br>    blockChan chan *bblock<br>    blockList []*bblock<br>}</pre><p>接下来会将key-value写到builder的curBlock中.bblock的结构如下:</p><pre>type bblock struct {<br>    data         []byte<br>    baseKey      []byte   // Base key for the current block.<br>    entryOffsets []uint32 // Offsets of entries present in current block.<br>    end          int      // Points to the end offset of the block.<br>}</pre><p>baseKey的设定是在builder的CurBlock初次使用时将跳表中的key设置成baseKey，</p><p>builder中还有一个结构体header用来表示该bblock中所有key和baseKey的区别，相同的长度是多少以及不同的长度是多少，结构如下:</p><pre>h := header{<br>    overlap: uint16(len(key) - len(diffKey)),<br>    diff:    uint16(len(diffKey)),<br>}</pre><p>每一次像bblock添加数据都要检查当前bblock剩余空间是否满足需要添加的字节数组.</p><p>默认的bblock大小是4KB,bblock的扩容原则是:4KB-&gt;8KB-&gt;16KB-&gt;32KB,按照原大小的2倍进行扩容,如果扩容完后的大小还是小于所需的大小，那么就申请当前尺寸+需要的字节数,最大大小是1GB.一般超过4KB就要创建一个新的bblock了.</p><p>encode的顺序分别是header+diffKey+ValueStruct.暨将header+diffKey+ValueStruct进行编码后存储到bblock中.</p><p>这里面使用了块内前缀压缩,一个bblock内，以第一个key作为参考，后续的的key都是在baseKey的基础上计算出实际的key,在bblock中以与baseKey不同的字节存储.value部分包含的内容是valueStruct的Meta,userMeta,ExpireAt以及实际的Value值.</p><blockquote>再将跳表的中key添加到bblock中，还有一点就是如何处理那些value存储地址的key-value</blockquote><p>如果value存储的是地址，那么此时就解析出该value的元信息，包括所在文件id，长度以及起始位置，用valuePointer表示.</p><pre>type valuePointer struct {<br>    Fid    uint32<br>    Len    uint32<br>    Offset uint32<br>}</pre><p>此时需要将valuePointer的长度传递给builder，builder的onDiskSize需要加上value的长度.</p><p>总结一下初次写入key-value的情况</p><p>第一会对key进行MurmurHash计算，存储到builder的keyHashes数组中,目的是为了使用布隆过滤器.</p><p>第二,更新builder的maxVersion，目的是可以得到该builder最新提交事务的版本.</p><p>第三,对于第一个插入的key-value，会将该key作为baseKey,采用前缀压缩, 后进来的key全部是baseKey的偏移值.使用header结构体存储该key与baseKey的区别(相同部分+相同部分).</p><p>第四,bblock会使用数组来存储每一个entry存储到bblock的游标位置.此时entryOffsets数据会存储在内存中而不是在指定位置.会在bblock写完后最后追加在bblock的后面.</p><p>第五,先将header进行编码存储到bblock中,占用4个字节</p><p>第六，对diffkey写到bblock中,</p><p>第七, 将valueStruct(meta,userMeta,expireAt,Value)存储到bblock中</p><p>第八，更新下builder的onDiskSize，添加的值为value本身的长度,比如value为test,那么长度为4.</p><p>另外每一次向bblock写入数据时，都会更新bblock的end属性，值为bblock最新的游标位置.</p><blockquote>如何检测bblock是否满了</blockquote><p>默认bblock的大小是4KB.</p><p>评估下新插入的key-value占用的空间是否超过4KB，bblock的大小由以下部分组成:</p><ol><li>entryOffsets数组,所占空间为N*4字节</li><li>entryOffsets 数组的长度</li><li>该bblock的checksum</li><li>checksum的长度</li><li>之前存储的key-value值</li></ol><p>上次5个部分在加上新key所占用的空间的长度如果超过4KB，则bblock会满，从而会新创建一个bblck.</p><h4>estimatedSize := uint32(b.curBlock.end) + uint32(6 /*header size for entry*/) +<br> uint32(len(key)) + value.EncodedSize() + entriesOffsetsSize<br> 我理解当前bblock的大小就是end，为什么在评估新插入key-value时，还要加上entriesOffsetsSize呢？</h4><p>b.curBlock.end 表示当前 block 已经写入的数据大小。但在评估新插入 key-value 后 block 的总大小时，<strong>必须加上 entriesOffsetsSize</strong>，原因如下：</p><p>entriesOffsetsSize 是 block 元数据的一部分，每个 block 结构如下（见注释）：</p><p>| Entry1 | Entry2 | … | EntryN | Block Meta (entryOffsets, etc) | Block Meta Size | Checksum | Checksum Size |</p><p>entryOffsets（entriesOffsetsSize）是 block 末尾的<strong>元数据</strong>，记录每个 entry 的起始偏移量，便于查找。这些元数据在 block 写满或 finish 时才会写入，但它们<strong>始终是 block 的一部分</strong>。</p><p>评估 block 是否“满”，要考虑所有最终会写入的数据，如果只考虑 end，忽略元数据，实际写入时 block 可能会超出设定的最大 block size，导致溢出或错误。所以，<strong>必须提前把元数据空间也算进去</strong>，确保 block 总大小不会超过限制。</p><p><strong>在 block 的所有 entry 数据写入后，</strong><strong>finishBlock 会把 </strong><strong>entryOffsets（即所有 entry 的起始偏移量数组）追加到 block 的末尾.</strong>紧接着写入 entryOffsets 的长度、checksum 及其长度。这决定了 entryOffsets 在 block 的物理布局：<strong>在 block 数据区的结尾，紧跟在 entry 数据之后，checksum 之前。</strong></p><blockquote>bblock满了的情况,怎么办?</blockquote><p>第一，之前每一次添加key-value时，就会将header-diffKey-value写到bblock的data字段,当检测到bblock满了后,会将bblock的entryOffsets 数组添加到bblock的后面,继续追加entryOffsets的长度,bblock数据(header-diffKey-value)的校验和,追加校验和的长度. 此时将该bblock添加到builder 的blockList中.</p><p>第二,更新builder属性uncompressedSize的值为bblock.end</p><p>第三,更新builder属性lenOffsets,类型uint32,计算方式如下: b.lenOffsets += uint32(int(math.Ceil(float64(len(b.curBlock.baseKey))/4))*4) + 40</p><p>如果添加bblock5次，添加后lenOffsets的值如下:</p><p>假设初始 b.lenOffsets = 0，每次添加后的值为：</p><p><strong>第一次添加后：</strong></p><p>lenOffsets1 = align4(len1) + 40</p><p><strong>第二次添加后：</strong></p><p>lenOffsets2 = align4(len1) + 40 + align4(len2) + 40</p><p><strong>第三次添加后：</strong></p><p>lenOffsets3 = align4(len1) + 40 + align4(len2) + 40 + align4(len3) + 40</p><p><strong>第四次添加后：</strong></p><p>lenOffsets4 = align4(len1) + 40 + align4(len2) + 40 + align4(len3) + 40 + align4(len4) + 40</p><p><strong>第五次添加后：</strong></p><p>lenOffsets5 = align4(len1) + 40 + align4(len2) + 40 + align4(len3) + 40 + align4(len4) + 40 + align4(len5) + 40</p><p>其中 align4(x) 表示 x 向上取整到 4 的倍数，即：align4(x) = ((x + 3) / 4) * 4</p><p>假设 5 个 baseKey 长度分别为 7, 12, 3, 8, 15：</p><ul><li>align4(7) = 8</li><li>align4(12) = 12</li><li>align4(3) = 4</li><li>align4(8) = 8</li><li>align4(15) = 16</li></ul><p>则每次添加后 lenOffsets 分别为：</p><ol><li>8 + 40 = <strong>48</strong></li><li>48 + 12 + 40 = <strong>100</strong></li><li>100 + 4 + 40 = <strong>144</strong></li><li>144 + 8 + 40 = <strong>192</strong></li><li>192 + 16 + 40 = <strong>248</strong></li></ol><p>目的是累计所有 block 的 baseKey 及其元数据在 table 索引区的总空间，用于后续 table 文件大小估算和分配.</p><ul><li><strong>table 索引区</strong>需要存储每个 block 的 baseKey 及其元数据，便于查找和定位 block。</li><li>由于 flatbuffers 及底层实现有对齐和元数据要求，必须提前准确预估空间。</li><li>这样可以保证 table 文件结构紧凑且高效，避免溢出和浪费。</li></ul><p>写完后向channel blockChan发送消息（下一篇来讨论如何消费blockChan中的数据）</p><h3>创建一个新的memtable</h3><blockquote>文件的ID从何而来？</blockquote><p>DB struct有一个字段nextMemFid用来继续下一个memtable的名字，在创建完memtable后会自动将nextMemFid+1.</p><pre>type DB struct {<br>    ……<br>    mt  *memTable   // Our latest (actively written) in-memory table<br>    imm []*memTable // Add here only AFTER pushing to flushChan.<br><br>    nextMemFid int<br>    opt       Options<br>    ……<br><br>}</pre><blockquote>memtable的尺寸是怎么来的？</blockquote><p>计算公式如下:opt.MemTableSize + opt.maxBatchSize + opt.maxBatchCount*int64(skl.MaxNodeSize)</p><p>默认的MemTableSize是64MB,maxBatchSize表示最大批处理的尺寸,默认值为15*64/100=9.6MB,最大Node尺寸是256KB,最大批处理数量是披处理尺寸除以最大node尺寸大概是<strong>35156.</strong></p><p>因此可以得到一个内存分配器的大小是81.1MB.</p><p>memtable是通过跳表的方式来存储数据的，跳表的结构如下:</p><pre>type Skiplist struct {<br>    height  atomic.Int32 // Current height. 1 &lt;= height &lt;= kMaxHeight. CAS.<br>    head    *node<br>    ref     atomic.Int32<br>    arena   *Arena<br>    OnClose func()<br>}</pre><p>跳表中包含内存分配器arena以及跳表的头</p><p>在新建skiplist时，需要通过arena的指针以及初始化的head来构建跳表.其中第一个node除了高度其余部分都是nil值.</p><p>memtable的结构体如下:</p><p>除了跳表外还包括writeAheadLog以及缓冲区buffer.</p><pre>type memTable struct {<br>    // TODO: Give skiplist z.Calloc&#39;d []byte.<br>    sl         *skl.Skiplist<br>    wal        *logFile<br>    maxVersion uint64<br>    opt        Options<br>    buf        *bytes.Buffer<br>}</pre><p>创建writeAheadLog ,write ahead log的结构体如下:</p><p>writeaheadlog先将消息写到mmapfile中.writeAt表示偏移量.</p><pre>type logFile struct {<br>    *z.MmapFile<br>    path string<br>    lock     sync.RWMutex<br>    fid      uint32<br>    size     atomic.Uint32<br>    dataKey  *pb.DataKey<br>    baseIV   []byte<br>    registry *KeyRegistry<br>    writeAt  uint32<br>    opt      Options<br>}</pre><p>Reference:</p><p><a href="https://en.wikipedia.org/wiki/MurmurHash">https://en.wikipedia.org/wiki/MurmurHash</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=851cf32c7e70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[badgerdb的写操作(IV) 向Memtable写入之前先写到valueLog中]]></title>
            <link>https://medium.com/@liuqiang9596/badgerdb%E7%9A%84%E5%86%99%E6%93%8D%E4%BD%9C-iv-%E5%90%91memtable%E5%86%99%E5%85%A5%E4%B9%8B%E5%89%8D%E5%85%88%E5%86%99%E5%88%B0valuelog%E4%B8%AD-475eef7d28a9?source=rss-ee904f8161ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/475eef7d28a9</guid>
            <category><![CDATA[badgerdb]]></category>
            <category><![CDATA[key-value-database]]></category>
            <dc:creator><![CDATA[Gabi Sual]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 07:30:18 GMT</pubDate>
            <atom:updated>2025-07-02T07:30:18.455Z</atom:updated>
            <content:encoded><![CDATA[<p>与其他NoSQL数据库不同，badgerdb再将数据写到memtable之前，会将entry写入到valuelog中，这也是badger的特殊之处，这样对于那些大尺寸的entry时，可以只把value的地址存储在内存中从而可以在同等内存大小下存储更多的key.</p><p>valueLog的格式如下:</p><pre>type valueLog struct {<br>    dirPath string<br><br>    // guards our view of which files exist, which to be deleted, how many active iterators<br>    filesLock        sync.RWMutex<br>    filesMap         map[uint32]*logFile<br>    maxFid           uint32<br>    filesToBeDeleted []uint32<br>    // A refcount of iterators -- when this hits zero, we can delete the filesToBeDeleted.<br>    numActiveIterators atomic.Int32<br><br>    db                *DB<br>    writableLogOffset atomic.Uint32 // read by read, written by write<br>    numEntriesWritten uint32<br>    opt               Options<br><br>    garbageCh    chan struct{}<br>    discardStats *discardStats<br>}</pre><p>badger从writeCh channel中读取request时，在将数据写入到memtable前会将这些key-value存储到vlog文件中,这些vlog文件中只会存储value尺寸大于阈值的key-value,对于小于阈值的key-value会直接存储在memtable和sst中.</p><p>和write-ahead-log一样的写入逻辑，采用header-key-value-crc32的格式，将entry写到buffer中，当大于阈值后再落盘。</p><p>阈值有两个条件，满足于一个就落盘，第一个条件是写入的entry数量，为100万，第二个valueLog的尺寸，为1GB。</p><p>request中会携带每一个value的地址，由于传入的request时引用传递因此在写入vlog时更新valuePointer可以保证在写到memtable时直接读取valuePointer就可以读到该key在vlog中的地址位置.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=475eef7d28a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[badgerdb的写操作(II) 存储数据到Memtable中]]></title>
            <link>https://medium.com/@liuqiang9596/badgerdb%E7%9A%84%E5%86%99%E6%93%8D%E4%BD%9C-ii-%E5%AD%98%E5%82%A8%E6%95%B0%E6%8D%AE%E5%88%B0memtable%E4%B8%AD-6c61f2080a14?source=rss-ee904f8161ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c61f2080a14</guid>
            <category><![CDATA[badgerdb]]></category>
            <category><![CDATA[skip-list]]></category>
            <category><![CDATA[write-ahead-logging]]></category>
            <category><![CDATA[memtable]]></category>
            <dc:creator><![CDATA[Gabi Sual]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 07:57:21 GMT</pubDate>
            <atom:updated>2025-07-01T07:57:21.608Z</atom:updated>
            <content:encoded><![CDATA[<p>所有写入到memtable的数据都要先将数据写到WriteAheadLog中，然后在写到memtable中，其中memtable的存储格式是skiplist.</p><p>memtable接收的数据的结构体如下:</p><p>Value有两种结果分别是真正的value或者是value的地址,meta用来表示该value的是哪种类型.</p><pre>Entry{<br>  Key:       key,<br>  Value:     value.Value,<br>  UserMeta:  value.UserMeta,<br>  meta:      value.Meta,<br>  ExpiresAt: value.ExpiresAt,<br>}</pre><h3>写入到WriteAheadLog</h3><p>writeAheadLog中的文件格式是有header-key-value-crc32组成</p><p>header中会存储key的长度，value的长度，entry的过期时间，entry的meta，userMeta等信息.</p><p>这些值都会写到mmapfile中最终落盘.</p><h3>写入到SkipList</h3><p>从skiplist的最高处开始排查,先查找当前skiplist中是否有该key如果有直接替换并返回，如果没有则需要在skiplist中添加该key.</p><p>skiplist 结构体如下:</p><p>height表明当前跳表的高度,head用来表示跳表的头每一次遍历都是从该head开始扫描，ref表示该跳表被谁引用，用来垃圾回收，arena是一个内存分配器里面存储着真正的key和value</p><pre>type Skiplist struct {<br>    height  atomic.Int32 // Current height. 1 &lt;= height &lt;= kMaxHeight. CAS.<br>    head    *node<br>    ref     atomic.Int32<br>    arena   *Arena<br>    OnClose func()<br>}</pre><p>跳表从上向下遍历的的过程中，key-value被包装成node，node存储在Arena中，通过unsafe将字节反序列化成node.只需要传入起始位置，使用unsfae就可以解析制定字节将这些字节数组反序列化成node.</p><p>node结构体如下:</p><pre>type node struct {<br>    value atomic.Uint64<br><br>    keyOffset uint32 // Immutable. No need to lock to access key.<br>    keySize   uint16 // Immutable. No need to lock to access key.<br><br>    height uint16<br>    tower [maxHeight]atomic.Uint32<br>}</pre><h4>更新key不是插入key</h4><blockquote>如何得到key?</blockquote><p>在node中会存储key的起始位置以及key的长度,在获取key时直接在Arena中获取对应的key而不是在node中得到key.</p><blockquote>如何更新key对应的value?</blockquote><p>新的value会追加到arena中并不会替换掉原来key对应value的地址，更新完后，arena的游标会向右移，存储在arean的value包含ValueStruct的Meta，UserMeta，ExpireAt以及实际的Value.即此时key和value在arena中是分离的不是连续的.Node中只会存储新value在Arena的起始位置及其长度.</p><h4>插入新的key</h4><p>随机生成一个高度,重新创建一个node,此时会将node写到arena中,arena会根据不同的高度得到新的偏移量，所有node的字段值会追加到arena中, 此时arena会存储key以及value(包含meta，UserMeta，ExpireAt，Value)，而node会存储key的起始位置，key的长度，node的高度以及value的偏移量与长度等元信息.</p><p>此时需要构建新节点在不同高度的前后节点关系.</p><p>Reference:</p><p><a href="https://pkg.go.dev/unsafe">https://pkg.go.dev/unsafe</a></p><p><a href="https://en.wikipedia.org/wiki/Compare-and-swap">https://en.wikipedia.org/wiki/Compare-and-swap</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c61f2080a14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[badgerdb的写操作(I) key-value在badgerdb传输过程中的数据格式]]></title>
            <link>https://medium.com/@liuqiang9596/badgerdb%E7%9A%84%E5%86%99%E6%93%8D%E4%BD%9C-i-key-value%E5%9C%A8badgerdb%E4%BC%A0%E8%BE%93%E8%BF%87%E7%A8%8B%E4%B8%AD%E7%9A%84%E6%95%B0%E6%8D%AE%E6%A0%BC%E5%BC%8F-4167e471ad68?source=rss-ee904f8161ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/4167e471ad68</guid>
            <category><![CDATA[key-value-database]]></category>
            <category><![CDATA[badgerdb]]></category>
            <dc:creator><![CDATA[Gabi Sual]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 06:04:23 GMT</pubDate>
            <atom:updated>2025-07-01T06:04:23.506Z</atom:updated>
            <content:encoded><![CDATA[<p>支持将多个key-value作为事务更新到badgerdb中.涉及到内存中如何存储以及以及背后的压缩操作.</p><p>需要了解存储的基本单元格式是什么以及sst文件的存储单元是什么.</p><p>写入时需要解决并发问题?需要表述下具体的并发问题是什么</p><p>set操作</p><p>commit操作</p><p>处理channel操作.</p><p>简单描述下key-value再经过层层转化后的载体的数据格式.</p><h3>step1: key-value</h3><p>用户只需要调用NewEntry函数并且传入key-value即可,此时对key,value要求是字节数组</p><h3>step2: Entry</h3><p>struct entry 除了包含key,value还包含其余的属性:</p><p>一对key-value对应一个Entry.</p><pre>type Entry struct {<br>    Key       []byte<br>    Value     []byte<br>    ExpiresAt uint64 // time.Unix<br>    version   uint64  // 事务提交的第i次,第一次是0后面会自动加1 <br>    offset    uint32 // offset is an internal field.<br>    UserMeta  byte<br>    meta      byte //用来表示改entry的状态,比如在事务中或者是事务的结尾符,还可以表示该entry是否被删除,<br><br>    // Fields maintained internally.<br>    hlen         int // Length of the header.<br>    valThreshold int64 <br>}</pre><p>在wiscdb中对单个entry的meta值有7中状态，用0表示这个entry已经被删除，1表示该value超过阈值，value仅存储value的地址而不是真正的值,2表示该entry的value是更早的版本可以被丢弃了,3表示该entry在压缩过程中是否可以被丢弃，6表示该entry正在事务中已被提交但是还没有被落盘，7表示该entry作为事务 的终止符.</p><h3>step3: request</h3><p>将Entry数组包装在requets 结构体中</p><pre>type request struct {<br>    // Input values<br>    Entries []*Entry //  存储事务中 的entry.<br>    // Output values and wait group stuff below<br>    Ptrs []valuePointer<br>    Wg   sync.WaitGroup //加锁<br>    Err  error<br>    ref  atomic.Int32 //  引用计数,便于后期垃圾回收.<br>}</pre><p>request有个加锁的操作， 除了加锁外requets还包含这次事务中多个entry的值,request的引用值加1为了后面的垃圾回收.</p><p>解析requests中的entries,在解析entries中的entry,根据entry中value的字节数是否超过阈值决定存储在value中的是value的地址还是value本身.</p><h3>step4 中间态 ValueStruct</h3><p>valueStruct作为一个中间态分别用来存储大于阈值的entry以及小于阈值的entry，如果小于阈值则entry存储的value就是其实际的value此时用meta来表示value是真实值还是地址</p><p>对于存储value的地址，会对request的valuePointer进行编码最终得到value对应的地址.</p><h3>step5 memtable</h3><pre><br>type memTable struct {<br>    // TODO: Give skiplist z.Calloc&#39;d []byte.<br>    sl         *skl.Skiplist<br>    wal        *logFile<br>    maxVersion uint64<br>    opt        Options<br>    buf        *bytes.Buffer<br>}</pre><p>此时entry就会被写到memtable中,但是目的地却有两个一个是write ahead log一个是skiplist.</p><p>在wrtie ahead log的结构体如下</p><pre>type logFile struct {<br>    *z.MmapFile<br>    path string<br>    lock     sync.RWMutex<br>    fid      uint32<br>    size     atomic.Uint32<br>    dataKey  *pb.DataKey<br>    baseIV   []byte<br>    registry *KeyRegistry<br>    writeAt  uint32<br>    opt      Options<br>}</pre><p>此时entry会扩充成header+key+value+crc32(校验和)并且存储在bytes.Buffer中. 最终这些buffer写到了memtable中</p><p>结构体header如下:</p><pre>type header struct {<br>    klen      uint32<br>    vlen      uint32<br>    expiresAt uint64<br>    meta      byte<br>    userMeta  byte<br>}</pre><p>header会存储key的长度，value的长度，entry的过期时间，entry的meta以及entry的userMeta.</p><p>先把header写到buffer中,然后在根据是否加密再将加密/不加密的key,value写到buffer中,再将校验和写到buffer中.</p><p>将buffer中的值符知道logFile的mmapfile中并更新logFile的游标writeAt.</p><p>skiplist的结构体如下</p><pre>type Skiplist struct {<br>    height  atomic.Int32 // Current height. 1 &lt;= height &lt;= kMaxHeight. CAS.<br>    head    *node<br>    ref     atomic.Int32<br>    arena   *Arena<br>    OnClose func()<br>}</pre><p>将key-value(有可能是真实value有可能是value的地址)存储到跳表中.</p><p>在skip list中使用node存储entry.node中会记录该entry在node中的偏移量,key的起始位置，key的长度，当前node的在跳表中的高度，并且对valuestruct编码</p><p>node的结构体如下:</p><pre><br>type node struct {<br>    value atomic.Uint64<br>    keyOffset uint32 // Immutable. No need to lock to access key.<br>    keySize   uint16 // Immutable. No need to lock to access key.<br>    height uint16<br>    tower [maxHeight]atomic.Uint32<br>}</pre><p>node存储的是key- value的索引包含key的起始位置，key的长度，该entry在所跳表的高度，node包含value在Arean中的地址起始位置以及value的长度，tower会存储每一层高度应用的下一个偏移量地址.</p><p>整个跳表都存储在arena中 ,结构如下:</p><pre>type Arena struct {<br>    n   atomic.Uint32<br>    buf []byte<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4167e471ad68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[各个编程语言提供的基础数据类型]]></title>
            <link>https://medium.com/@liuqiang9596/%E5%90%84%E4%B8%AA%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80%E6%8F%90%E4%BE%9B%E7%9A%84%E5%9F%BA%E7%A1%80%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B-df1053b7df6f?source=rss-ee904f8161ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/df1053b7df6f</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[built-in]]></category>
            <dc:creator><![CDATA[Gabi Sual]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 03:31:35 GMT</pubDate>
            <atom:updated>2024-10-27T03:31:35.831Z</atom:updated>
            <content:encoded><![CDATA[<p>各个编程语言提供的基础数据类型</p><h3>Inbuild Data Structures in Java</h3><p><a href="https://www.geeksforgeeks.org/inbuild-data-structures-in-java/">https://www.geeksforgeeks.org/inbuild-data-structures-in-java/</a></p><p><strong>ArrayList</strong></p><p><strong>LinkedList</strong></p><p><strong>Stack</strong></p><p><strong>Queue</strong></p><p><strong>PriorityQueue</strong></p><p><strong>HashSet</strong></p><p><strong>HashMap</strong></p><p><strong>TreeSet</strong></p><p><strong>TreeMap</strong></p><p><strong>HashTable</strong></p><p><strong>LinkedHashSet</strong></p><h3>Inbuild Data Structures in Go</h3><p><a href="https://blog.logrocket.com/comprehensive-guide-data-structures-go/">https://blog.logrocket.com/comprehensive-guide-data-structures-go/</a></p><p>Arrays</p><pre>var studentsAge [10]int</pre><p>Slices</p><pre>var sliceOfIntegers []int</pre><p>Maps</p><pre>var studentsAge map[string]int</pre><p>Structs</p><pre>type Rectangle struct {<br>  length  float64<br>  breadth float64<br>}</pre><h3>Inbuild Data Structures in Python</h3><p><a href="https://wesmckinney.com/book/python-builtin">https://wesmckinney.com/book/python-builtin</a></p><p>Tuple</p><pre>tup = (4, 5, 6)</pre><p>List</p><pre>a_list = [2, 3, 7, None]</pre><p>Dictionary</p><pre>d1 = {&quot;a&quot;: &quot;some value&quot;, &quot;b&quot;: [1, 2, 3, 4]}</pre><p>Set</p><pre>set([2, 2, 2, 1, 3, 3])<br>{1, 2, 3}</pre><h3>Inbuild Data Structures in C++</h3><p><a href="https://www.w3schools.com/cpp/cpp_data_structures.asp">W3Schools.com</a></p><p><a href="https://www.w3schools.com/cpp/cpp_list.asp">List</a></p><p><a href="https://www.w3schools.com/cpp/cpp_stacks.asp">Stack</a></p><p><a href="https://www.w3schools.com/cpp/cpp_queues.asp">Queue</a></p><p><a href="https://www.w3schools.com/cpp/cpp_deque.asp">Deque</a></p><p><a href="https://www.w3schools.com/cpp/cpp_sets.asp">Set</a></p><p><a href="https://www.w3schools.com/cpp/cpp_maps.asp">Map</a></p><p><a href="https://www.w3schools.com/cpp/cpp_vectors.asp">Vector</a></p><pre>// Include the vector library<br>#include &lt;vector&gt;<br><br>// Include the list library<br>#include &lt;list&gt;<br><br>// Include the set library<br>#include &lt;set&gt;<br><br>// Include the map library<br>#include &lt;map&gt;<br><br>// Include the stack library<br>#include &lt;stack&gt;<br><br>// Include the queue library<br>#include &lt;queue&gt;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df1053b7df6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[编程语言对Map的支持]]></title>
            <link>https://medium.com/@liuqiang9596/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80%E5%AF%B9map%E7%9A%84%E6%94%AF%E6%8C%81-6bf1a56d119f?source=rss-ee904f8161ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bf1a56d119f</guid>
            <category><![CDATA[mập]]></category>
            <dc:creator><![CDATA[Gabi Sual]]></dc:creator>
            <pubDate>Sun, 27 Oct 2024 02:58:27 GMT</pubDate>
            <atom:updated>2024-10-27T02:58:27.242Z</atom:updated>
            <content:encoded><![CDATA[<p>C语言，不支持Map，只能自己创建map</p><p><a href="https://www.geeksforgeeks.org/implementation-on-map-or-dictionary-data-structure-in-c/">https://www.geeksforgeeks.org/implementation-on-map-or-dictionary-data-structure-in-c/</a></p><pre>#include &lt;stdio.h&gt; <br>#include &lt;string.h&gt; <br><br>#define MAX_SIZE           \ <br> 100 // Maximum number of elements in the map <br><br>int size = 0; // Current number of elements in the map <br>char keys[MAX_SIZE][100]; // Array to store the keys <br>int values[MAX_SIZE]; // Array to store the values <br><br>// Function to get the index of a key in the keys array <br>int getIndex(char key[]) <br>{ <br> for (int i = 0; i &lt; size; i++) { <br>  if (strcmp(keys[i], key) == 0) { <br>   return i; <br>  } <br> } <br> return -1; // Key not found <br>} <br><br>// Function to insert a key-value pair into the map <br>void insert(char key[], int value) <br>{ <br> int index = getIndex(key); <br> if (index == -1) { // Key not found <br>  strcpy(keys[size], key); <br>  values[size] = value; <br>  size++; <br> } <br> else { // Key found <br>  values[index] = value; <br> } <br>} <br><br>// Function to get the value of a key in the map <br>int get(char key[]) <br>{ <br> int index = getIndex(key); <br> if (index == -1) { // Key not found <br>  return -1; <br> } <br> else { // Key found <br>  return values[index]; <br> } <br>} <br><br>// Function to print the map <br>void printMap() <br>{ <br> for (int i = 0; i &lt; size; i++) { <br>  printf(&quot;%s: %d\n&quot;, keys[i], values[i]); <br> } <br>} <br><br>int main() <br>{ <br> insert(&quot;Geeks&quot;, 5); <br> insert(&quot;GFG&quot;, 3); <br> insert(&quot;GeeksforGeeks&quot;, 7); <br><br> printf(&quot;Value of complete Map: \n&quot;); <br> printMap(); <br><br> printf(&quot;\nValue of apple: %d\n&quot;, get(&quot;GFG&quot;)); <br> printf(&quot;Index of GeeksforGeeks: %d\n&quot;, <br>  getIndex(&quot;GeeksforGeeks&quot;)); <br><br> return 0; <br>}</pre><p>Java，支持Map，创建方式</p><p><a href="https://www.baeldung.com/java-initialize-hashmap">Initialize a HashMap in Java | Baeldung</a></p><pre>Map&lt;String, String&gt; doubleBraceMap  = new HashMap&lt;String, String&gt;() {{<br>    put(&quot;key1&quot;, &quot;value1&quot;);<br>    put(&quot;key2&quot;, &quot;value2&quot;);<br>}};</pre><p>C++，支持Map，创建方式</p><pre>  map&lt;string, a&gt; myMap;<br>  ....<br>  myMap = new map&lt;string, a&gt;;</pre><p><a href="https://stackoverflow.com/questions/10918514/correct-way-to-initialize-a-map-and-delete-in-c">Correct way to initialize a map and delete in C++</a></p><p>Go 支持Map，创建方式</p><p><a href="https://gobyexample.com/maps">https://gobyexample.com/maps</a></p><pre>package main<br><br>import (<br>    &quot;fmt&quot;<br>    &quot;maps&quot;<br>)<br><br>func main() {<br><br>    m := make(map[string]int)<br><br>    m[&quot;k1&quot;] = 7<br>    m[&quot;k2&quot;] = 13<br><br>    fmt.Println(&quot;map:&quot;, m)<br><br>    v1 := m[&quot;k1&quot;]<br>    fmt.Println(&quot;v1:&quot;, v1)<br><br>    v3 := m[&quot;k3&quot;]<br>    fmt.Println(&quot;v3:&quot;, v3)<br><br>    fmt.Println(&quot;len:&quot;, len(m))<br><br>    delete(m, &quot;k2&quot;)<br>    fmt.Println(&quot;map:&quot;, m)<br><br>    clear(m)<br>    fmt.Println(&quot;map:&quot;, m)<br><br>    _, prs := m[&quot;k2&quot;]<br>    fmt.Println(&quot;prs:&quot;, prs)<br><br>    n := map[string]int{&quot;foo&quot;: 1, &quot;bar&quot;: 2}<br>    fmt.Println(&quot;map:&quot;, n)<br><br>    n2 := map[string]int{&quot;foo&quot;: 1, &quot;bar&quot;: 2}<br>    if maps.Equal(n, n2) {<br>        fmt.Println(&quot;n == n2&quot;)<br>    }<br>}</pre><p>Rush支持Map，创建方式</p><pre>let mut book_reviews = HashMap::new();</pre><p><a href="https://doc.rust-lang.org/std/collections/struct.HashMap.html">HashMap in std::collections - Rust</a></p><p>python 支持Map(使用<strong>dictionary 表示</strong>),创建方式：</p><p>5.5. Dictionaries<a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries">¶</a></p><p><a href="https://docs.python.org/3/tutorial/datastructures.html#dictionaries">https://docs.python.org/3/tutorial/datastructures.html#dictionaries</a></p><pre>tel = {&#39;jack&#39;: 4098, &#39;sape&#39;: 4139}<br>tel[&#39;guido&#39;] = 4127<br>tel<br>{&#39;jack&#39;: 4098, &#39;sape&#39;: 4139, &#39;guido&#39;: 4127}<br>tel[&#39;jack&#39;]<br>4098<br>del tel[&#39;sape&#39;]<br>tel[&#39;irv&#39;] = 4127<br>tel<br>{&#39;jack&#39;: 4098, &#39;guido&#39;: 4127, &#39;irv&#39;: 4127}<br>list(tel)<br>[&#39;jack&#39;, &#39;guido&#39;, &#39;irv&#39;]<br>sorted(tel)<br>[&#39;guido&#39;, &#39;irv&#39;, &#39;jack&#39;]<br>&#39;guido&#39; in tel<br>True<br>&#39;jack&#39; not in tel<br>False</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bf1a56d119f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[singleflight 源码阅读]]></title>
            <link>https://medium.com/@liuqiang9596/singleflight-%E6%BA%90%E7%A0%81%E9%98%85%E8%AF%BB-5cecdff4dc09?source=rss-ee904f8161ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cecdff4dc09</guid>
            <category><![CDATA[concurrent]]></category>
            <category><![CDATA[singleflight]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Gabi Sual]]></dc:creator>
            <pubDate>Thu, 28 Dec 2023 07:33:22 GMT</pubDate>
            <atom:updated>2023-12-28T07:38:47.352Z</atom:updated>
            <content:encoded><![CDATA[<p>官方介绍:Package singleflight provides a duplicate function call suppression mechanism.</p><p>扩展解释,signle flight的目的是减少短时间内多次相同的请求</p><p>实现原理，在处理请求上加一层拦截，用户可以根据HTTP 同一个header的key作为依据</p><p>在该unique request发送到response返回中，如果出现相同的请求，那么singlefligh可以满足仅调用一次请求.</p><p><a href="https://pkg.go.dev/golang.org/x/sync/singleflight">singleflight</a></p><p>由于窗口有效期为第一个request的时间，</p><p>所以singlefligt库适用的场景是: request耗时且短时间内多请求</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cecdff4dc09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[100 Go Mistakes and How to Avoid Them #3: Misusing init functions]]></title>
            <link>https://medium.com/@liuqiang9596/100-go-mistakes-and-how-to-avoid-them-3-misusing-init-functions-53d371d4500e?source=rss-ee904f8161ee------2</link>
            <guid isPermaLink="false">https://medium.com/p/53d371d4500e</guid>
            <category><![CDATA[100-go-mistakes]]></category>
            <category><![CDATA[itin]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Gabi Sual]]></dc:creator>
            <pubDate>Sat, 05 Aug 2023 13:27:12 GMT</pubDate>
            <atom:updated>2023-08-05T13:27:12.644Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is init() function</h3><p>The Go language reserve one function for a special purpose and the function is the <strong>init()</strong> function. <strong>init()</strong> function is present in every package and this function is called when the package is initialized.</p><p>Each source file can define its own niladic init function to set up whatever state is required. (Actually, each file can have multiple init functions.) This function is declared implicitly, so you cannot <strong>reference </strong>it from anywhere and you are allowed to create multiple <strong>init()</strong> functions in the same program and they execute in the order they are created.</p><h3>Limitations in the Built-in Features of the init() Function</h3><ul><li>Error management in an init function is limited. Indeed, as an init function doesn’t return an error, one of the only ways to signal an error is to panic, leading the application to be stopped.</li></ul><p>init database: init() VS general function</p><p>init() can’t return error.</p><pre>func init() {<br> dataSourceName :=<br>  os.Getenv(&quot;MYSQL_DATA_SOURCE_NAME&quot;)<br> d, err := sql.Open(&quot;mysql&quot;, dataSourceName)<br> if err != nil {<br>  log.Panic(err)<br> }<br> err = d.Ping()<br> if err != nil {<br>  log.Panic(err)<br> }<br> db = d<br>}</pre><p>opening the database within an init function prevents client packages from implementing their error-handling logic.</p><pre>func createClient(dsn string) (*sql.DB, error) {<br> db, err := sql.Open(&quot;mysql&quot;, dsn)<br> if err != nil {<br>  return nil, err<br> }<br> if err = db.Ping(); err != nil {<br>  return nil, err<br> }<br> return db, nil<br>}</pre><ul><li>Related to testing. If we add tests to this file, the init function will be executed before running the test cases, which isn’t necessarily what we want (for example, if we add unit tests on a utility function that doesn’t require this connection to be created). Therefore, the init function in this example complicates writing unit tests.</li><li>The last downside is that the variable will become a global variable. Global variables have some severe drawbacks; for example:</li></ul><ol><li>Any functions can alter global variables within the package. </li><li>Unit tests can be more complicated because a function that depends on a global variable won’t be isolated anymore.</li></ol><h3>Appropriate Usage of the init() Function</h3><p>uses an init function to set up the static HTTP configuration:</p><p><a href="https://cs.opensource.google/go/x/website/+/e0d934b4:blog/blog.go;l=32">https://cs.opensource.google/go/x/website/+/e0d934b4:blog/blog.go;l=32</a></p><pre>func init() {<br> // Redirect &quot;/blog/&quot; to &quot;/&quot;, because the menu bar link is to &quot;/blog/&quot;<br> // but we&#39;re serving from the root.<br> redirect := func(w http.ResponseWriter, r *http.Request) {<br>  http.Redirect(w, r, &quot;/&quot;, http.StatusFound)<br> }<br> http.HandleFunc(&quot;/blog&quot;, redirect)<br> http.HandleFunc(&quot;/blog/&quot;, redirect)<br><br> // Keep these static file handlers in sync with app.yaml.<br> static := http.FileServer(http.Dir(&quot;static&quot;))<br> http.Handle(&quot;/favicon.ico&quot;, static)<br> http.Handle(&quot;/fonts.css&quot;, static)<br> http.Handle(&quot;/fonts/&quot;, static)<br><br> http.Handle(&quot;/lib/godoc/&quot;, http.StripPrefix(&quot;/lib/godoc/&quot;, http.HandlerFunc(staticHandler)))<br>}</pre><h3>The Order of init() Loading</h3><p><strong>init() is called after all the variable declarations in the package have evaluated their initializers, and those are evaluated only after all the imported packages have been initialized.</strong>(<a href="https://go.dev/doc/effective_go#init">https://go.dev/doc/effective_go#init</a>)</p><ul><li><strong>after all the variable declarations in the package</strong>:</li></ul><p>Global variable WhatIsThe, the init() loaded after the AnswerToLife()</p><pre>var WhatIsThe = AnswerToLife()<br><br>func AnswerToLife() int {<br> return 43<br>}<br><br>func init() {<br> fmt.Printf(&quot;init() before: %d\n&quot;, WhatIsThe)<br> WhatIsThe = 0<br> fmt.Printf(&quot;init() after %d\n&quot;, WhatIsThe)<br><br>}<br><br>func main() {<br> if WhatIsThe == 0 {<br>  fmt.Printf(&quot;It&#39;s all a lie.&quot;)<br> }<br>}</pre><p>output:</p><p>init() before: 43<br>init() after 0 <br>It’s all a lie.</p><ul><li>have multiple init functions in a file, loaded by the order</li></ul><pre>func init() {<br> WhatIsThe := 0<br> fmt.Printf(&quot;init() 0 = %d\n&quot;, WhatIsThe)<br><br>}<br>func init() {<br> WhatIsThe := 1<br> fmt.Printf(&quot;init() 1 = %d\n&quot;, WhatIsThe)<br><br>}<br><br>func init() {<br> WhatIsThe := 2<br> fmt.Printf(&quot;init() 2 = %d\n&quot;, WhatIsThe)<br><br>}<br>func main() {<br><br>}</pre><p>output:</p><p>init() 0 = 0<br>init() 1 = 1<br>init() 2 = 2</p><ul><li>If there are multi-files in the same package, <strong>they are called in lexical file name order (Alphabetical Order)</strong></li></ul><p>create file a.go, ab.go, ba.go and main.go in same package:</p><p>a.go</p><pre>func init() {<br> fmt.Printf(&quot;file a.go\n&quot;)<br>}</pre><p>ab.go</p><pre>func init() {<br> fmt.Printf(&quot;file ab.go\n&quot;)<br>}</pre><p>ba.go</p><pre>func init() {<br> fmt.Printf(&quot;file ba.go\n&quot;)<br>}</pre><p>main.go</p><pre>func init() {<br> fmt.Printf(&quot;file main.go\n&quot;)<br><br>}<br><br>func main() {<br><br>}</pre><p>Output:</p><p>file a.go<br>file ab.go <br>file ba.go <br>file main.go</p><p>The order is by the Alphabetical, a-&gt;ab-&gt;ba-&gt;main</p><ul><li>multi packges</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/0*cCRJ3NBT-b0vB6g7" /></figure><ol><li>If a package imports other packages, the imported packages are initialized first.</li><li>Current package’s constant initialized then.</li><li>Current package’s variables are initialized then.</li><li>Finally, init() function of current package is called.</li></ol><h3>Resources:</h3><ul><li><a href="https://go.dev/doc/effective_go#init">Effective Go - The Go Programming Language</a></li><li><a href="https://www.geeksforgeeks.org/main-and-init-function-in-golang/">main and init function in Golang - GeeksforGeeks</a></li></ul><p><a href="https://cs.opensource.google/go/x/website/+/e0d934b4:blog/blog.go;l=32">https://cs.opensource.google/go/x/website/+/e0d934b4:blog/blog.go;l=32</a></p><p><a href="https://stackoverflow.com/questions/24790175/when-is-the-init-function-run">When is the init() function run?</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53d371d4500e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>