Artifact 9eb062209d93771c8e20ec61e420219f4b0e8ef3f46c83212fd6ffa68903dcc7:
- File
backend/src/sync_lock.gleam
— part of check-in
[5bb18ed4d4]
at
2026-10-23 03:34:10
on branch trunk
— 把来肯对接和本地库落到可切换的后端。
账号从环境读取,商品由人工增量同步,订单按五分钟轮询并缓存登录会话。开发期用 SQLite,同一套结构可切到 PostgreSQL。 (user: pluto size: 1174)
import exception import gleam/erlang/process.{type Subject} import gleam/list import gleam/otp/actor pub type Message { TryBegin(entity: String, reply: Subject(Bool)) Finish(entity: String) } pub fn start() -> Result(Subject(Message), actor.StartError) { case actor.new([]) |> actor.on_message(handle) |> actor.start() { Ok(started) -> Ok(started.data) Error(err) -> Error(err) } } pub fn with_lock(lock: Subject(Message), entity: String, f: fn() -> a) -> Result(a, Nil) { case actor.call(lock, 5000, TryBegin(entity, _)) { False -> Error(Nil) True -> { use <- exception.defer(fn() { process.send(lock, Finish(entity)) }) Ok(f()) } } } fn handle(state: List(String), message: Message) -> actor.Next(List(String), Message) { case message { TryBegin(entity, reply) -> case list.contains(state, entity) { True -> { process.send(reply, False) actor.continue(state) } False -> { process.send(reply, True) actor.continue([entity, ..state]) } } Finish(entity) -> actor.continue(list.filter(state, fn(held) { held != entity })) } }