|
| 1 | +-- Compatibility layer for bee.lua API changes |
| 2 | +local thread = require 'bee.thread' |
| 3 | +local channel_mod = require 'bee.channel' |
| 4 | +local select_mod = require 'bee.select' |
| 5 | + |
| 6 | +-- Store original thread.create |
| 7 | +local original_create = thread.create |
| 8 | + |
| 9 | +-- Add thread.thread as alias for backward compatibility |
| 10 | +thread.thread = original_create |
| 11 | + |
| 12 | +-- Store channels globally |
| 13 | +local channels = {} |
| 14 | +local selector = select_mod.create() |
| 15 | + |
| 16 | +-- Create a wrapper for errlog to make it compatible with channel interface |
| 17 | +local errlog_channel = setmetatable({}, { |
| 18 | + __index = { |
| 19 | + pop = function() |
| 20 | + local err = thread.errlog() |
| 21 | + if err then |
| 22 | + return true, err |
| 23 | + else |
| 24 | + return false |
| 25 | + end |
| 26 | + end, |
| 27 | + bpop = function() |
| 28 | + while true do |
| 29 | + local err = thread.errlog() |
| 30 | + if err then |
| 31 | + return err |
| 32 | + end |
| 33 | + thread.sleep(10) |
| 34 | + end |
| 35 | + end, |
| 36 | + } |
| 37 | +}) |
| 38 | + |
| 39 | +-- Create a new channel |
| 40 | +function thread.newchannel(name) |
| 41 | + if name == 'errlog' then |
| 42 | + return errlog_channel |
| 43 | + end |
| 44 | + if channels[name] then |
| 45 | + error("Channel already exists: " .. name) |
| 46 | + end |
| 47 | + local ch = channel_mod.create(name) |
| 48 | + channels[name] = ch |
| 49 | + -- Add to selector for blocking operations |
| 50 | + selector:event_add(ch:fd(), select_mod.SELECT_READ) |
| 51 | + return ch |
| 52 | +end |
| 53 | + |
| 54 | +-- Get an existing channel |
| 55 | +function thread.channel(name) |
| 56 | + if name == 'errlog' then |
| 57 | + return errlog_channel |
| 58 | + end |
| 59 | + local ch = channels[name] |
| 60 | + if not ch then |
| 61 | + ch = channel_mod.query(name) |
| 62 | + if ch then |
| 63 | + channels[name] = ch |
| 64 | + selector:event_add(ch:fd(), select_mod.SELECT_READ) |
| 65 | + end |
| 66 | + end |
| 67 | + return ch |
| 68 | +end |
| 69 | + |
| 70 | +-- Add blocking pop support to channels |
| 71 | +local channel_mt = debug.getregistry()['bee::channel'] |
| 72 | +if channel_mt and not channel_mt.bpop then |
| 73 | + function channel_mt:bpop() |
| 74 | + while true do |
| 75 | + local results = table.pack(self:pop()) |
| 76 | + if results[1] then |
| 77 | + return table.unpack(results, 2, results.n) |
| 78 | + end |
| 79 | + -- Wait for data with a timeout |
| 80 | + selector:wait(100) |
| 81 | + end |
| 82 | + end |
| 83 | +end |
| 84 | + |
| 85 | +return thread |
0 commit comments