在go中使用Semaphoregroup

在netbird 中看到一个semaphore-group 函数 package semaphoregroup import ( "context" "sync" ) // SemaphoreGroup is a custom type that combines sync.WaitGroup and a semaphore. type SemaphoreGroup struct { waitGroup sync.WaitGroup semaphore chan struct{} } // NewSemaphoreGroup creates a new SemaphoreGroup with the specified semaphore limit. func NewSemaphoreGroup(limit int) *SemaphoreGroup { return &SemaphoreGroup{ semaphore: make(chan struct{}, limit), } } // Add increments the internal WaitGroup counter and acquires a semaphore slot. func (sg *SemaphoreGroup) Add(ctx context.Context) { sg.waitGroup.Add(1) // Acquire semaphore slot select { case <-ctx.Done(): return case sg.semaphore <- struct{}{}: } } // Done decrements the internal WaitGroup counter and releases a semaphore slot. func (sg *SemaphoreGroup) Done(ctx context.Context) { sg.waitGroup.Done() // Release semaphore slot select { case <-ctx.Done(): return case <-sg.semaphore: } } // Wait waits until the internal WaitGroup counter is zero. func (sg *SemaphoreGroup) Wait() { sg.waitGroup.Wait() } 官方测试用例 ...

2025-06-05 · 3 分钟 · czyt

在 Go 中构建可扩展的多租户应用程序【译】

原文链接 https://atlasgo.io/blog/2025/05/26/gophercon-scalable-multi-tenant-apps-in-go 为 GopherCon Israel 2025 准备并呈现。 引言 在本篇博客中,我们将基于我们在构建 Atlas Cloud 后端(作为我们商业产品的一部分)的经验,探讨在 Go 中构建可扩展多租户应用程序的不同策略。 但首先,让我们明确一下我们所说的多租户应用是什么。 多租户是一个系统的特性,即单个实例为多个客户(租户)提供服务。 作为一家商业企业,你的目标当然是有很多客户!但你想要服务许多客户,他们期望有一个流畅无缝的体验,就好像只有他们在使用你的服务一样。 你向客户隐含做出的两个重要承诺是: 数据隔离:每个租户的数据都是隔离和安全的,确保一个租户无法访问另一个租户的数据。 性能:无论租户数量如何,应用程序都应表现良好,确保一个租户的使用不会降低其他租户的体验。 让我们探讨一些可能实现这些承诺的方法。 物理隔离 确保数据和性能隔离最直接的方法是为每个租户运行一个独立的应用实例。这种方法通常被称为“物理隔离”或“专用实例”。 为每个租户运行独立实例,可以确保: 每个租户的数据存储在独立的数据库中,从而保证完全隔离。如有需要,租户可以在不同的 VPC 中运行,甚至可以在不同的云账户中运行。 租户独立消费资源,因此一个租户的使用不会影响其他租户,从而消除了“吵闹邻居”问题。 然而,大多数公司不会选择这条路,原因有几点: 运营开销:将应用程序部署到数百或数千个生产环境,每个环境都有自己的数据库和配置,管理起来可能非常复杂。 成本:如果您的公司需要为每个租户的资源支付云服务提供商的费用,成本可能会迅速变得难以承受。 可扩展性:如果添加新租户需要部署新实例,那么扩展应用程序以支持许多租户可能会成为瓶颈。 可见性:跨多个实例监控和调试问题可能具有挑战性,因为您需要从所有实例中聚合日志和指标。 逻辑隔离 另一种方法是运行单个应用程序实例来服务多个租户,通常称为“逻辑隔离”。在此模型中,租户共享相同的应用程序代码和数据库,但它们的数据在逻辑上是隔离的。逻辑隔离可以总结为: 共享基础设施,作用域请求 让我们看看在 Go 应用程序中实际如何使用这个示例,从一个简单的 GORM 示例开始: package main type Tenant struct { ID uint `gorm:"primaryKey" json:"id"` Name string `json:"name"` } type Customer struct { ID uint `gorm:"primaryKey" json:"id"` Name string `json:"name"` TenantID uint `json:"tenant_id"` } 在这个示例中,我们有两个模型: Tenant 和 Customer 。每个 Customer 属于一个 Tenant , Customer 模型中的 TenantID 字段用于将每个客户与特定的租户关联起来。 ...

2025-05-30 · 6 分钟 · czyt

TIL:Bash 脚本中的超时【译】

原文链接 https://heitorpb.github.io/bla/timeout/ 前几天在工作中,我们有一个 Bash 脚本,用于设置一个 Web 服务器,并等待它启动后再继续执行后续操作。这个脚本运行正常,我们也没有遇到任何问题,直到出现了一个无限循环。 我们使用 Bash 内置的 until 来检查 Web 服务器是否正常: until curl --silent --fail-with-body 10.0.0.1:8080/health; do sleep 1 done 这很好用。除非我们的 Web 服务器在启动过程中崩溃,并且我们 sleep 1 永远等待。 这里有一个实用的工具:timeout。顾名思义,这个命令可以为其他命令添加超时功能。您指定想要等待命令的时间限制,如果该时间已过,timeout 会发送一个信号来终止它,并以非零状态退出。默认情况下,timeout 发送的是 SIGTERM 信号,但您可以通过 --signal 标志来更改它,例如 timeout --signal=SIGKILL 1s foo 。 例如,timeout 1s sleep 5 将向 sleep 发送 SIGTERM 信号 1秒后: $ time timeout 1s sleep 4 real 0m1,004s user 0m0,000s sys 0m0,005s $ echo $? 124 那么接下来应该将 timeout 和 until 结合起来: timeout 1m until curl --silent --fail-with-body 10.0.0.1:8080/health; do sleep 1 done 唯一的问题是这行不通。timeout 需要一个可终止的命令,而 until 是一个 shell 关键字:你不能 SIGTERMuntil``。我们无法使用 timeout 与任何 shell 内建命令一起使用。 ...

2025-05-30 · 1 分钟 · czyt

Sherpa Go语言实战

简介 sherpa 是 Next-gen Kaldi 项目的部署框架。 使用 VAD 语音活动检测(Voice Activity Detection,简称VAD)是一种技术,用于检测音频信号中是否存在语音或其他声音活动。它在语音处理、语音识别、音频压缩等领域有广泛的应用。 VAD的主要功能 语音识别系统:通过VAD,系统可以在检测到语音时启动识别过程,提高效率。 音频压缩:在语音通信中,VAD可以帮助压缩算法仅对有效语音信号进行压缩,减少传输数据量。 噪声抑制系统:通过检测语音活动,系统可以在静默时段增强噪声抑制效果。 在GO中使用 todo KWS 关键词唤醒(Keyword Spotting,简称KWS)是一种技术,用于检测音频信号中特定的关键词或短语。它广泛应用于语音助手、智能家居设备、车载系统等领域,通过识别特定关键词来激活设备或执行特定命令。 主要功能 关键词检测:识别音频信号中是否包含预定义的关键词或短语。 唤醒设备:当检测到关键词时,激活设备或应用程序。 提高用户体验:通过语音命令简化操作流程,增强用户体验。 自定义keywords 通过官方的工具sherpa-onnx-cli,可以实现自定义关键字,下面是简单的介绍 原文 # Note: You need to run pip install sherpa-onnx to get the commandline tool: sherpa-onnx-cli sherpa-onnx-cli text2token --help Usage: sherpa-onnx-cli text2token [OPTIONS] INPUT OUTPUT Options: --text TEXT Path to the input texts. Each line in the texts contains the original phrase, it might also contain some extra items, for example, the boosting score (startting with :), the triggering threshold (startting with #, only used in keyword spotting task) and the original phrase (startting with @). Note: extra items will be kept in the output. example input 1 (tokens_type = ppinyin): 小爱同学 :2.0 #0.6 @小爱同学 你好问问 :3.5 @你好问问 小艺小艺 #0.6 @小艺小艺 example output 1: x iǎo ài tóng x ué :2.0 #0.6 @小爱同学 n ǐ h ǎo w èn w èn :3.5 @你好问问 x iǎo y ì x iǎo y ì #0.6 @小艺小艺 example input 2 (tokens_type = bpe): HELLO WORLD :1.5 #0.4 HI GOOGLE :2.0 #0.8 HEY SIRI #0.35 example output 2: ▁HE LL O ▁WORLD :1.5 #0.4 ▁HI ▁GO O G LE :2.0 #0.8 ▁HE Y ▁S I RI #0.35 --tokens TEXT The path to tokens.txt. --tokens-type TEXT The type of modeling units, should be cjkchar, bpe, cjkchar+bpe, fpinyin or ppinyin. fpinyin means full pinyin, each cjkchar has a pinyin(with tone). ppinyin means partial pinyin, it splits pinyin into initial and final, --bpe-model TEXT The path to bpe.model. Only required when tokens-type is bpe or cjkchar+bpe. --help Show this message and exit. 我这里只是记录下小爱同学 :2.0 #0.6 @小爱同学 这部分。在这个例子里面:数字 是增强得分(boosting score),#数字 是触发阈值(triggering threshold)。 ...

2025-03-20 · 6 分钟 · czyt

在Go程序中使用Vosk进行语音识别STT

Vosk 介绍 Vosk是一款基于深度学习 的开源语音识别工具,能够在没有云连接的情况下进行高效的离线语音识别。它通过对语音信号进行预处理、特征提取和模型推断,将语音转换成文本。Vosk不仅支持多种主流编程语言,还覆盖了20多种语言和方言,包括英语、中文、法语、德语等,为跨语言应用提供了强大的支持。 工作原理 Vosk的语音识别过程可以分为以下几个关键步骤: 语音信号预处理:对输入的语音信号进行去噪、增强等处理,以提高识别准确性。 特征提取:从处理后的语音信号中提取出能够表征语音特性的关键特征。 模型推断:利用预训练的深度学习模型对提取的特征进行识别,输出对应的文本。 优势解析 隐私保护:Vosk的离线特性意味着用户的语音数据不会离开设备,有效保护了用户的隐私。 实时性:在设备端进行语音识别,减少了网络传输时间和延迟,使得识别过程更加实时。 跨平台:支持Windows、Linux、macOS以及嵌入式设备等多种平台,便于在不同场景下的应用。 可扩展性:作为开源项目,Vosk允许开发者根据自己的需求进行定制和优化,以适应不同的应用场景。 多语言支持:提供对多种语言和方言的识别能力,为跨国应用提供了便利。 官方 https://alphacephei.com/vosk/ 模型下载 https://alphacephei.com/vosk/models GO项目搭建 本文基于Linux,Windows请参考官方仓库的说明 创建go程序 创建go程序内容如下: package main import ( "encoding/json" "flag" "fmt" "io" "log" "os" vosk "github.com/alphacep/vosk-api/go" ) func main() { var filename string flag.StringVar(&filename, "f", "", "file to transcribe") flag.Parse() model, err := vosk.NewModel("model") if err != nil { log.Fatal(err) } // we can check if word is in the vocabulary // fmt.Println(model.FindWord("air")) sampleRate := 16000.0 rec, err := vosk.NewRecognizer(model, sampleRate) if err != nil { log.Fatal(err) } rec.SetWords(1) file, err := os.Open(filename) if err != nil { panic(err) } defer file.Close() buf := make([]byte, 4096) for { _, err := file.Read(buf) if err != nil { if err != io.EOF { log.Fatal(err) } break } if rec.AcceptWaveform(buf) != 0 { fmt.Println(rec.Result()) } } // Unmarshal example for final result var jres map[string]interface{} json.Unmarshal([]byte(rec.FinalResult()), &jres) fmt.Println(jres["text"]) } 下载模型 同时需要下载对应的模型,我这里使用中文的模型 https://alphacephei.com/vosk/models/vosk-model-small-cn-0.22.zip ...

2025-03-17 · 2 分钟 · czyt

AUFS简要笔记

文章内容为Claude生成,留作备忘 什么是 AUFS? AUFS 是一种联合文件系统(Union File System),最初是为 Linux 系统开发的。它的主要功能是将多个目录(称为分支或层)的内容虚拟地合并成一个统一的视图。这种技术在容器化技术(如早期的 Docker)中得到了广泛应用。 AUFS 的基本原理 联合挂载机制 AUFS 核心原理是联合挂载(Union Mount)技术,其工作原理如下: 多层结构:AUFS 允许将多个目录层叠在一起,形成一个统一的视图 读写分离:通常配置为一个可写层和多个只读层 写时复制(Copy-on-Write,CoW):当需要修改只读层中的文件时,AUFS 会将文件复制到可写层进行修改,保持底层文件不变 分支优先级 在 AUFS 中,每个分支都有优先级设置: 较高优先级的分支中的文件会覆盖低优先级分支中的同名文件 当访问一个文件时,AUFS 会从最高优先级的分支开始查找 AUFS 的主要特性 1. 写时复制(CoW) 当用户试图修改只读层中的文件时: ┌─────────────┐ │ 可写层 │ ← 修改后的文件被存储在这里 ├─────────────┤ │ 只读层 1 │ ← 原始文件位置 ├─────────────┤ │ 只读层 2 │ └─────────────┘ 2. 删除处理 当删除一个文件时,AUFS 会在可写层创建一个特殊的删除标记(whiteout 文件),以表示该文件已被删除。 3. 分支管理 AUFS 提供了动态添加、删除和重新排序分支的能力,使文件系统结构可以灵活调整。 AUFS 在容器技术中的应用 在容器技术早期发展中,AUFS 扮演了重要角色: 镜像分层:容器镜像由多个只读层组成,每层代表构建过程中的一步 容器实例:运行容器时,会在镜像上添加一个可写层 资源共享:多个容器可以共享基础镜像层,节省存储空间 AUFS 的优缺点 优点 高效的存储利用率(通过共享基础层) 快速的容器启动时间 成熟稳定的实现 缺点 较复杂的实现导致维护挑战 性能开销(尤其是在深层目录结构中) 在现代 Linux 内核中已被其他联合文件系统(如 OverlayFS)逐渐替代 实际应用场景 1. 软件测试而不污染原始环境 场景描述 假设你有一个稳定的应用程序环境,需要测试新版本软件但不想影响现有环境。 ...

2025-02-25 · 2 分钟 · czyt

iter.Seq实践【译】

原文链接 https://blog.vertigrated.com/iterseq-in-practice FirstN 返回序列中的前 N 个项。 // FirstN takes an iter.Seq[int] and returns a new iter.Seq[int] that // yields only the first 'limit' items without creating intermediate slices. func FirstN[T any](original iter.Seq[T], limit int) iter.Seq[T] { return iter.Seq[T](func(yield func(T) bool) { count := 0 for item := range original { if count < limit { if !yield(item) { return } count++ } else { return } } }) } SkipFirstN 跳过前 N 个元素并返回剩余的序列。 ...

2025-02-19 · 4 分钟 · czyt

懒猫微服开发简明教程

最近入手了懒猫微服,简单记录下开发相关的内容。 环境配置 先决条件 你必须有一台懒猫微服,购买地址 安装基本环境lzc-cli,请参考官方说明地址 如果你要发布程序,必须要申请成为懒猫微服开发者,申请地址 设备上必须安装懒猫开发者工具 应用。这个应用主要用来通过lzc-cli进入devshell容器的开发以及将本地的测试镜像推送到盒子进行测试。 开发机器上安装懒猫微服客户端,这和懒猫微服的网络机制有关,参考官方文档 。开启客户端并且设备需要联网开机。 如果上面的条件都已经满足,那么我们进入下一步。 不同类型应用的注意事项 Docker应用 对于公网的docker应用如果要使用,需要先进行copy-image来利用懒猫官方提供的镜像源,参考官方说明 。下面是我的一个执行例子: 我在没copy操作之前lzc-cli project devshell cmd: install --uid czyt --pkgId cloud.lazycat.app.gokapi Error: rpc error: code = Unknown desc = "time=\"2025-02-08T00:18:51+08:00\" level=warning msg=\"The \\\"LAZYCAT_APP_ID\\\" variable is not set. Defaulting to a blank string.\"\ntime=\"2025-02-08T00:18:51+08:00\" level=warning msg=\"The \\\"LAZYCAT_APP_DEPLOY_UID\\\" variable is not set. Defaulting to a blank string.\"\ntime=\"2025-02-08T00:18:51+08:00\" level=warning msg=\"The \\\"LAZYCAT_APP_DEPLOY_UID\\\" variable is not set. Defaulting to a blank string.\"\ntime=\"2025-02-08T00:18:51+08:00\" level=warning msg=\"The \\\"LAZYCAT_APP_DOMAIN\\\" variable is not set. Defaulting to a blank string.\"\ntime=\"2025-02-08T00:18:51+08:00\" level=warning msg=\"The \\\"LAZYCAT_APP_DEPLOY_UID\\\" variable is not set. Defaulting to a blank string.\"\ntime=\"2025-02-08T00:18:51+08:00\" level=warning msg=\"The \\\"LAZYCAT_APP_DEPLOY_UID\\\" variable is not set. Defaulting to a blank string.\"\ntime=\"2025-02-08T00:18:51+08:00\" level=warning msg=\"The \\\"LAZYCAT_APP_DOMAIN\\\" variable is not set. Defaulting to a blank string.\"\ntime=\"2025-02-08T00:18:51+08:00\" level=warning msg=\"The \\\"LAZYCAT_APP_ID\\\" variable is not set. Defaulting to a blank string.\"\n app Pulling \n gokapi Pulling \n a0bed814693a Already exists \n b4e16c7102ef Already exists \n b23adc163656 Pulling fs layer \n 99db376b5073 Pulling fs layer \n 5ed8719dcb50 Pulling fs layer \n 99db376b5073 Downloading [==================================================>] 251B/251B\n 99db376b5073 Verifying Checksum \n 99db376b5073 Download complete \n b23adc163656 Downloading [> ] 134.7kB/11.46MB\n 5ed8719dcb50 Downloading [> ] 265.8kB/23.48MB\n b23adc163656 Verifying Checksum \n b23adc163656 Download complete \n 5ed8719dcb50 Verifying Checksum \n 5ed8719dcb50 Download complete \n b23adc163656 Extracting [> ] 131.1kB/11.46MB\n b23adc163656 Extracting [======================> ] 5.243MB/11.46MB\n b23adc163656 Extracting [==================================================>] 11.46MB/11.46MB\n gokapi Error unknown: {\"errors\":[{\"code\":\"MANIFEST_UNKNOWN\",\"message\":\"manifest unknown\",\"detail\":{\"name\":\"f0rc3/gokapi\",\"revision\":\"v1.9.6\"}}]}\nError response from daemon: unknown: {\"errors\":[{\"code\":\"MANIFEST_UNKNOWN\",\"message\":\"manifest unknown\",\"detail\":{\"name\":\"f0rc3/gokapi\",\"revision\":\"v1.9.6\"}}]}\n" with exit status 18 Copy ...

2025-02-07 · 12 分钟 · czyt

Slint相关资源

视频 SurrealismUI Slint Easy Slint Advanced Slint With Rust 在线教程 Slint Learn 官方教程 UI 库 SurrealismUI JUI

2025-01-16 · 1 分钟 · czyt

Go程序自动升级的方案探究

前导 2024年的最后一天看见v站的这个 帖子,故整理下,备忘。 常用的库 cloudflare tableflip 仓库为 https://github.com/cloudflare/tableflip 官方示例 package tableflip_test import ( "context" "flag" "fmt" "log" "net/http" "os" "os/signal" "syscall" "time" "github.com/cloudflare/tableflip" ) // This shows how to use the upgrader // with the graceful shutdown facilities of net/http. func Example_httpShutdown() { var ( listenAddr = flag.String("listen", "localhost:8080", "`Address` to listen on") pidFile = flag.String("pid-file", "", "`Path` to pid file") ) flag.Parse() log.SetPrefix(fmt.Sprintf("%d ", os.Getpid())) upg, err := tableflip.New(tableflip.Options{ PIDFile: *pidFile, }) if err != nil { panic(err) } defer upg.Stop() // Do an upgrade on SIGHUP go func() { sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGHUP) for range sig { err := upg.Upgrade() if err != nil { log.Println("Upgrade failed:", err) } } }() // Listen must be called before Ready ln, err := upg.Listen("tcp", *listenAddr) if err != nil { log.Fatalln("Can't listen:", err) } server := http.Server{ // Set timeouts, etc. } go func() { err := server.Serve(ln) if err != http.ErrServerClosed { log.Println("HTTP server:", err) } }() log.Printf("ready") if err := upg.Ready(); err != nil { panic(err) } <-upg.Exit() // Make sure to set a deadline on exiting the process // after upg.Exit() is closed. No new upgrades can be // performed if the parent doesn't exit. time.AfterFunc(30*time.Second, func() { log.Println("Graceful shutdown timed out") os.Exit(1) }) // Wait for connections to drain. server.Shutdown(context.Background()) } 这个示例实现了以下功能: ...

2024-12-31 · 2 分钟 · czyt