ll-rb 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 76c7d4f0f085278537c164d5777cc4f7fd6542c56065fa402d7c70623426c7eb
4
+ data.tar.gz: e969e6f98b49c087e18764865aa20a3a042d8f7ef12da74decec489799711e8f
5
+ SHA512:
6
+ metadata.gz: 312200ee03331150d9e4fb7a8f5744895d16857f1bcc4e9bcabd06d5ec17ec9092de02b368e5da38dc6c4e5d75bacf7cbc275da8c7e7044af817761800204c57
7
+ data.tar.gz: a6832f7ed624ee9e87dbed97e326c68c1a4c458efe3bfd461ab759da155c94f9cd14211915ae2c759dd4102d95542dde8a122007084c426ab9cced45161f37bd
data/.gitignore ADDED
@@ -0,0 +1,14 @@
1
+ /.bundle/
2
+ /vendor/bundle/
3
+ /.ruby-version
4
+ /.yardoc/
5
+ /_yardoc/
6
+ /doc/
7
+ /pkg/
8
+ *.gem
9
+ *.log
10
+ *.pid
11
+ /tmp/
12
+ var/
13
+ config/*.toml
14
+ !config/config.toml.example
data/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ll-tg
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
data/README.md ADDED
@@ -0,0 +1,52 @@
1
+ # ll-rb
2
+
3
+ `ll-rb` is an independent Ruby-only Telegram Bot API runtime. Bot source is ordinary Ruby (`.rb`); there is no DSL, dispatcher, plugin marketplace, application database, or checked-in Telegram schema.
4
+
5
+ ## Installation
6
+
7
+ Ruby 3.1+ is required. The runtime uses only the Ruby standard library (`json`, `net/http`, `openssl`, `webrick`, and `minitest` for tests). Install the gem from a local checkout with:
8
+
9
+ ```sh
10
+ gem build ll-rb.gemspec
11
+ gem install ./ll-rb-0.1.0.gem
12
+ ```
13
+
14
+ The repository intentionally does not publish to RubyGems or GitHub. For development, `ruby -Ilib examples/echo_bot.rb` is sufficient after setting `TELEGRAM_BOT_TOKEN`.
15
+
16
+ ## Quick start
17
+
18
+ ```sh
19
+ export TELEGRAM_BOT_TOKEN='...'
20
+ ruby -Ilib examples/echo_bot.rb
21
+ ```
22
+
23
+ `Bot` exposes the explicit `on_command`, `on_text`, and `on_update` callbacks plus Ruby-native aliases: `command`, `text`, `event`, `callback_query`, and `inline_query`. `Context#reply` uses Telegram's `sendMessage`; snake_case and camelCase API calls such as `send_message` and `sendMessage` both map to the canonical Telegram method. `start`, `stop`, and `reload` provide lifecycle shorthand while the explicit `run`, `reload!`, and hook APIs remain available. See the [Ruby API and native shorthand reference](docs/api.md) for exact `.rb` examples. Application state should be kept behind your own storage service, not in this runtime.
24
+
25
+ ## Runtime operations
26
+
27
+ The client fetches `https://raw.githubusercontent.com/ll-api/tg/main/api.min.json` over HTTPS at startup, parses it in memory, and validates API method names. No schema JSON or generated API source is committed. `--fetch-schema` performs this check without starting a bot.
28
+
29
+ Webhook mode has a bounded 1 MiB body, Telegram secret-header verification, `/healthz`, `/readyz`, and `/metrics`. TLS and optional client certificate verification are supported by passing certificate paths in the `tls` hash to `Bot#run`. Long polling uses `getUpdates` and advances the offset only after enqueueing.
30
+
31
+ Every bot has exactly nine worker threads. The durable queue fsyncs newline-delimited records before accepting updates, replays unacknowledged records after restart, applies exponential retry, and writes a dead-letter queue after the configured attempt limit. The spool is an operational delivery buffer, not a database.
32
+
33
+ ```ruby
34
+ bot.run(mode: "webhook", listen: "127.0.0.1:8443", webhook_secret: ENV.fetch("WEBHOOK_SECRET"), tls: {"cert"=>"server.crt", "key"=>"server.key", "ca"=>"ca.crt", "verify_client"=>true})
35
+ ```
36
+
37
+ A complete configuration example is in [`config/config.toml.example`](config/config.toml.example). The CLI reads this intentionally small TOML subset with `ll-rb --config config.toml`; environment variables are preferred for secrets.
38
+
39
+ ## Security and deployment
40
+
41
+ Terminate TLS at the process or a hardened reverse proxy. Use a high-entropy webhook secret, restrict `/healthz` and `/metrics`, run as an unprivileged account, make `var/` writable only by that account, and rotate bot tokens through the environment. mTLS requires a CA file and client certificates; it is not enabled unless `verify_client` is true. The library does not sandbox arbitrary Ruby callbacks, so only trusted application code belongs in a bot process.
42
+
43
+ For systemd, run `bundle exec ruby -Ilib bin/ll-rb --config /etc/ll-rb/config.toml` with `NoNewPrivileges=true`, `PrivateTmp=true`, `Restart=on-failure`, and a dedicated `StateDirectory=ll-rb`. A reverse proxy can provide public HTTPS while the bot listens on loopback.
44
+
45
+ ## Tests and limits
46
+
47
+ ```sh
48
+ ruby -Ilib -Itest test/test_ll_rb.rb
49
+ ruby -c lib/ll/rb.rb
50
+ ```
51
+
52
+ This project implements the Ruby-native subset of the requested lifecycle: remote schema validation, webhook and long polling, nine workers, durable spool/replay/retry/DLQ, lifecycle hooks, health/readiness/metrics, graceful shutdown, webhook secret, TLS/mTLS helper, and external-storage boundary by convention. It does not implement the reference's Rust VM, Go/gRPC bridge, `.lz` compiler, cluster lease protocol, or native-language sandboxing; those are intentionally absent from this language-only distribution.
data/bin/ll-rb ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env ruby
2
+ require "ll/rb"
3
+ exit(LL::RB::CLI.run(ARGV))
@@ -0,0 +1,22 @@
1
+ name = "ruby-bot"
2
+ listen = "127.0.0.1:8080"
3
+ mode = "webhook"
4
+ workers = 9
5
+ queue_capacity = 1024
6
+ spool_path = "var/updates.spool"
7
+ dlq_path = "var/updates.dlq"
8
+ webhook_path = "/telegram/webhook"
9
+ webhook_secret = "change-me"
10
+ api_schema_url = "https://raw.githubusercontent.com/ll-api/tg/main/api.min.json"
11
+ [telegram]
12
+ token = ""
13
+ polling_timeout = 25
14
+ polling_limit = 100
15
+ [security]
16
+ cert = ""
17
+ key = ""
18
+ ca = ""
19
+ verify_client = false
20
+ [retry]
21
+ max_attempts = 8
22
+ base_delay = 1.0
data/docs/api.md ADDED
@@ -0,0 +1,59 @@
1
+ # Ruby API and native shorthand
2
+
3
+ All bot source remains ordinary `.rb` code. The shorthand is executable Ruby behavior; it does not introduce another language, a compiler, a plugin marketplace, or an application database.
4
+
5
+ ## Routes
6
+
7
+ The explicit callbacks remain supported. Their native aliases are:
8
+
9
+ ```ruby
10
+ require "ll/rb"
11
+
12
+ bot = LL::RB::Bot.new(token: ENV.fetch("TELEGRAM_BOT_TOKEN"))
13
+
14
+ bot.command("/start") { |ctx| ctx.reply("Hello") }
15
+ bot.text { |ctx| ctx.reply("Echo: #{ctx.text}") }
16
+ bot.on_update { |ctx| warn "update: #{ctx.update.keys.join(",")}" }
17
+ ```
18
+
19
+ `command` is an alias for `on_command`; command names are matched without the leading slash, so both `"start"` and `"/start"` work. `text` is an alias for `on_text`. `on_update` continues to receive every update before specialized routes.
20
+
21
+ Named Telegram update events can be registered directly. The callback receives the same `LL::RB::Context` as other routes:
22
+
23
+ ```ruby
24
+ bot.callback_query { |ctx| ctx.answer_callback_query("callback_query_id" => ctx.update["callback_query"]["id"]) }
25
+ bot.inline_query { |ctx| puts ctx.update["inline_query"]["query"] }
26
+ bot.event(:message) { |ctx| puts ctx.text }
27
+ ```
28
+
29
+ `event(name)` is the general named-update form. It matches the update's top-level Telegram key, including `callback_query`, `inline_query`, `message`, `edited_message`, `channel_post`, and other update keys present in the received payload.
30
+
31
+ ## Context and direct API shorthand
32
+
33
+ `Context#reply` is the concise `sendMessage` form and automatically supplies the current chat ID. Context API calls and bot API calls accept either Telegram's canonical camelCase name or Ruby's snake_case spelling:
34
+
35
+ ```ruby
36
+ bot.text do |ctx|
37
+ ctx.reply("Welcome") # sendMessage
38
+ ctx.send_message("text" => "Another reply") # sendMessage, chat_id inferred
39
+ ctx.answerCallbackQuery("callback_query_id" => "abc")
40
+ end
41
+
42
+ bot.send_message("chat_id" => 123, "text" => "Hello")
43
+ bot.sendMessage("chat_id" => 123, "text" => "Same canonical method")
44
+ bot.get_updates("offset" => 10)
45
+ ```
46
+
47
+ The API remains schema-validated against the remote schema fetched at startup. Unknown methods are rejected when a schema is present; no schema file is bundled or generated locally.
48
+
49
+ ## Lifecycle
50
+
51
+ `start(**options)` is an alias for `run(**options)`. `stop` requests shutdown and closes the durable queue; `reload` is an alias for `reload!` and invokes registered reload hooks. Existing `run`, `reload!`, `on_shutdown`, and `on_reload` APIs remain available:
52
+
53
+ ```ruby
54
+ bot.on_reload { puts "reloaded" }
55
+ bot.reload
56
+ bot.start(mode: ENV.fetch("LL_RB_MODE", "polling"))
57
+ ```
58
+
59
+ A complete bot using only `.rb` source is available in [`examples/echo_bot.rb`](../examples/echo_bot.rb). Queue durability, retry/DLQ behavior, webhook checks, TLS/mTLS, nine workers, and lifecycle cleanup are unchanged.
data/docs/security.md ADDED
@@ -0,0 +1,8 @@
1
+ # Security and deployment notes
2
+
3
+ - Keep `TELEGRAM_BOT_TOKEN` and webhook secrets in an environment manager; never commit them.
4
+ - Use HTTPS for Telegram webhooks. `Bot#run` accepts `cert`, `key`, `ca`, and `verify_client` for Ruby WEBrick TLS/mTLS.
5
+ - Put health and metrics endpoints behind an internal firewall or authenticated reverse proxy.
6
+ - Run under a dedicated unprivileged user with a private, writable spool directory.
7
+ - Ruby callbacks are trusted code and are not sandboxed.
8
+ - The spool and DLQ can contain update payloads; protect them as operational sensitive data and rotate them according to retention policy.
data/docs/storage.md ADDED
@@ -0,0 +1,3 @@
1
+ # External storage boundary
2
+
3
+ `ll-rb` does not ship an application database or persist sessions. A bot may call an external developer-owned service from its callbacks, or you may wrap that service in your own Ruby object. The durable queue is only for delivery recovery and must not be treated as business storage.
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env ruby
2
+ # A complete bot definition. The framework stays agnostic to application state.
3
+ require "ll/rb"
4
+
5
+ bot = LL::RB::Bot.new(token: ENV.fetch("TELEGRAM_BOT_TOKEN"))
6
+ bot.command("/start") { |ctx| ctx.reply("Hello from Ruby") }
7
+ bot.text { |ctx| ctx.reply("Echo: #{ctx.text}") }
8
+ bot.start(mode: ENV.fetch("LL_RB_MODE", "polling"))
data/lib/ll/rb.rb ADDED
@@ -0,0 +1,275 @@
1
+ # frozen_string_literal: true
2
+ require "json"
3
+ require "net/http"
4
+ require "uri"
5
+ require "openssl"
6
+ require "socket"
7
+ require "webrick"
8
+ require "securerandom"
9
+ require "time"
10
+ require "fileutils"
11
+
12
+ module LL
13
+ module RB
14
+ API_SCHEMA_URL = "https://raw.githubusercontent.com/ll-api/tg/main/api.min.json"
15
+ WORKER_COUNT = 9
16
+
17
+ class Error < StandardError; end
18
+
19
+ class Config
20
+ attr_reader :data
21
+ def initialize(data = {}) = @data = data
22
+ def [](key) = @data[key.to_s]
23
+ def fetch(key, default=nil) = @data.fetch(key.to_s, default)
24
+ def self.load(path)
25
+ current = {}
26
+ section = nil
27
+ File.foreach(path) do |line|
28
+ line=line.strip
29
+ next if line.empty? || line.start_with?("#")
30
+ if (m=line.match(/^\[([^\]]+)\]$/)); section=m[1]; current[section] ||= {}; next end
31
+ k,v=line.split("=",2); next unless v
32
+ v=v.strip
33
+ val = if v.start_with?(34.chr) then v[1..-2].gsub('\\"', '"') elsif v == "true" then true elsif v == "false" then false elsif v.include?(".") then v.to_f else v.to_i end
34
+ (section ? current[section] : current)[k.strip]=val
35
+ end
36
+ new(current)
37
+ end
38
+ end
39
+
40
+ class Schema
41
+ attr_reader :methods, :types
42
+ def initialize(payload)
43
+ @payload=payload
44
+ @methods = payload.is_a?(Hash) ? (payload["methods"] || payload.dig("api","methods") || {}) : {}
45
+ @types = payload.is_a?(Hash) ? (payload["types"] || payload.dig("api","types") || {}) : {}
46
+ end
47
+ def method?(name) = @methods.key?(name.to_s)
48
+ def parameters(name)
49
+ item=@methods[name.to_s]; item.is_a?(Hash) ? (item["parameters"] || item["params"] || []) : []
50
+ end
51
+ def self.fetch(url=API_SCHEMA_URL, timeout: 15)
52
+ uri=URI(url); http=Net::HTTP.new(uri.host, uri.port); http.use_ssl=(uri.scheme=="https"); http.open_timeout=timeout; http.read_timeout=timeout
53
+ response=http.get(uri.request_uri); raise Error, "schema fetch failed: HTTP #{response.code}" unless response.is_a?(Net::HTTPSuccess)
54
+ new(JSON.parse(response.body))
55
+ end
56
+ end
57
+
58
+ class Telegram
59
+ attr_reader :token
60
+ def initialize(token, schema: nil, timeout: 30)
61
+ raise ArgumentError, "token is required" if token.to_s.empty?
62
+ @token,@schema,@timeout=token,schema,timeout
63
+ end
64
+ def call(method, params={})
65
+ validate_method!(method)
66
+ uri=URI("https://api.telegram.org/bot#{@token}/#{method}")
67
+ req=Net::HTTP::Post.new(uri); req.set_form_data(params.transform_keys(&:to_s).transform_values(&:to_s))
68
+ http=Net::HTTP.new(uri.host,uri.port); http.use_ssl=true; http.open_timeout=@timeout; http.read_timeout=@timeout
69
+ response=http.request(req); body=JSON.parse(response.body); raise Error, body["description"] || "Telegram API error" unless body["ok"]
70
+ body["result"]
71
+ end
72
+ def updates(offset: nil, limit: 100, timeout: 25)
73
+ params={"limit"=>limit,"timeout"=>timeout}; params["offset"]=offset if offset
74
+ call("getUpdates", params)
75
+ end
76
+ # Ruby-native API spelling: send_message/sendMessage both invoke
77
+ # Telegram's canonical sendMessage endpoint without changing validation.
78
+ def method_missing(name, *args, **kwargs, &block)
79
+ return super unless block.nil?
80
+ canonical = LL::RB.canonical_api_name(name)
81
+ return super if canonical == name.to_s && !respond_to_api?(canonical)
82
+ params = args.length == 1 && args.first.is_a?(Hash) ? args.first : {}
83
+ params = params.merge(kwargs.transform_keys(&:to_s)) unless kwargs.empty?
84
+ raise ArgumentError, "API methods accept a parameter hash" unless args.empty? || (args.length == 1 && args.first.is_a?(Hash))
85
+ call(canonical, params)
86
+ end
87
+
88
+ def respond_to_missing?(name, _include_private=false)
89
+ respond_to_api?(LL::RB.canonical_api_name(name)) || super
90
+ end
91
+
92
+ private
93
+ def respond_to_api?(name)
94
+ @schema.nil? || @schema.method?(name) || name.to_s == "getUpdates"
95
+ end
96
+ def validate_method!(method)
97
+ return unless @schema && !@schema.method?(method)
98
+ raise Error, "method #{method} is not present in fetched Telegram schema"
99
+ end
100
+ end
101
+
102
+ class Context
103
+ attr_reader :update, :bot
104
+ def initialize(update, bot) = (@update,@bot=update,bot)
105
+ def text = @update.dig("message","text").to_s
106
+ def chat_id = @update.dig("message","chat","id") || @update.dig("callback_query","message","chat","id")
107
+ def command = text[/\A\/([^\s]+)/,1]
108
+ def reply(text, **params) = @bot.api.call("sendMessage", {"chat_id"=>chat_id,"text"=>text}.merge(params.transform_keys(&:to_s)))
109
+
110
+ # Context API shorthand defaults sendMessage to this update's chat.
111
+ def method_missing(name, *args, **kwargs, &block)
112
+ return super unless block.nil?
113
+ canonical = LL::RB.canonical_api_name(name)
114
+ return super unless @bot.api.respond_to?(canonical)
115
+ params = args.length == 1 && args.first.is_a?(Hash) ? args.first.dup : {}
116
+ params.merge!(kwargs.transform_keys(&:to_s))
117
+ raise ArgumentError, "API methods accept a parameter hash" unless args.empty? || (args.length == 1 && args.first.is_a?(Hash))
118
+ params["chat_id"] ||= chat_id if canonical == "sendMessage"
119
+ @bot.api.call(canonical, params)
120
+ end
121
+
122
+ def respond_to_missing?(name, include_private=false)
123
+ @bot.api.respond_to?(LL::RB.canonical_api_name(name)) || super
124
+ end
125
+ end
126
+
127
+ class DurableQueue
128
+ def size = @mutex.synchronize { @items.length + @inflight }
129
+ def initialize(capacity:, spool_path:, dlq_path:, max_attempts: 8, base_delay: 1.0)
130
+ @capacity,@spool,@dlq,@max,@delay=capacity,spool_path,dlq_path,max_attempts,base_delay; @mutex=Mutex.new; @cv=ConditionVariable.new; @items=[]; @inflight=0; @closed=false
131
+ FileUtils.mkdir_p(File.dirname(@spool)) unless File.dirname(@spool)=="."; FileUtils.mkdir_p(File.dirname(@dlq)) unless File.dirname(@dlq)=="."; replay
132
+ end
133
+ def push(update)
134
+ @mutex.synchronize do
135
+ raise Error,"queue is full" if (@items.length+@inflight)>=@capacity
136
+ record={"id"=>update["update_id"] || SecureRandom.uuid,"attempts"=>0,"update"=>update}; append(@spool,record); @items << record; @cv.signal
137
+ end
138
+ end
139
+ def pop
140
+ @mutex.synchronize do
141
+ @cv.wait(@mutex) while @items.empty? && !@closed
142
+ return nil if @items.empty? && @closed
143
+ record=@items.shift; @inflight+=1; record
144
+ end
145
+ end
146
+ def ack(record)
147
+ @mutex.synchronize { @inflight-=1; rewrite_spool; @cv.broadcast }
148
+ end
149
+ def fail(record, error)
150
+ record["attempts"]+=1
151
+ if record["attempts"] >= @max
152
+ append(@dlq, record.merge("error"=>error.to_s,"failed_at"=>Time.now.utc.iso8601)); ack(record)
153
+ else
154
+ sleep(@delay * (2 ** [record["attempts"]-1, 6].min))
155
+ @mutex.synchronize { @items << record; @inflight-=1; @cv.signal }
156
+ end
157
+ end
158
+ def close = @mutex.synchronize { @closed=true; @cv.broadcast }
159
+ private
160
+ def append(path, record); File.open(path,"a") { |f| f.puts(JSON.generate(record)); f.flush; f.fsync }; end
161
+ def replay
162
+ return unless File.file?(@spool)
163
+ File.foreach(@spool) { |line| @items << JSON.parse(line) rescue nil }
164
+ end
165
+ def rewrite_spool
166
+ File.open(@spool,"w") { |f| @items.each { |x| f.puts(JSON.generate(x)) }; f.flush; f.fsync }
167
+ end
168
+ end
169
+
170
+ def self.canonical_api_name(name)
171
+ value=name.to_s
172
+ return value if value.match?(/[A-Z]/) && !value.include?("_")
173
+ value.split("_").each_with_index.map { |part, i| i.zero? ? part : part[0].upcase + part[1..] }.join
174
+ end
175
+
176
+ class Bot
177
+ attr_reader :telegram, :queue
178
+ def initialize(token:, schema_url: API_SCHEMA_URL, schema: nil, queue_capacity: 1024, spool_path: "var/updates.spool", dlq_path: "var/updates.dlq", max_attempts: 8, base_delay: 1.0)
179
+ schema ||= Schema.fetch(schema_url)
180
+ @telegram=Telegram.new(token, schema: schema); @routes=[]; @commands={}; @text_handler=nil; @event_handlers={}; @shutdown_hooks=[]; @reload_hooks=[]; @stop=false
181
+ @queue=DurableQueue.new(capacity: queue_capacity, spool_path: spool_path, dlq_path: dlq_path, max_attempts: max_attempts, base_delay: base_delay)
182
+ end
183
+ def on_command(name,&block) = (@commands[name.to_s.sub(/\A\//, "")]=block)
184
+ alias command on_command
185
+ def on_text(&block) = (@text_handler=block)
186
+ alias text on_text
187
+ def on_update(&block) = (@routes << block)
188
+ def on_event(name, &block) = (@event_handlers[name.to_s] = block)
189
+ alias event on_event
190
+ def callback_query(&block) = on_event(:callback_query, &block)
191
+ def inline_query(&block) = on_event(:inline_query, &block)
192
+ def on_shutdown(&block) = (@shutdown_hooks << block)
193
+ def on_reload(&block) = (@reload_hooks << block)
194
+ def reload! = (@reload_hooks.each(&:call); true)
195
+ alias reload reload!
196
+ def api = @telegram
197
+ def method_missing(name, *args, **kwargs, &block)
198
+ return super unless block.nil?
199
+ canonical = LL::RB.canonical_api_name(name)
200
+ return super unless @telegram.respond_to?(canonical)
201
+ params = args.length == 1 && args.first.is_a?(Hash) ? args.first : {}
202
+ params = params.merge(kwargs.transform_keys(&:to_s)) unless kwargs.empty?
203
+ raise ArgumentError, "API methods accept a parameter hash" unless args.empty? || (args.length == 1 && args.first.is_a?(Hash))
204
+ @telegram.call(canonical, params)
205
+ end
206
+ def respond_to_missing?(name, include_private=false) = (@telegram.respond_to?(LL::RB.canonical_api_name(name)) || super)
207
+ def enqueue(update) = @queue.push(update)
208
+ def handle(update)
209
+ ctx=Context.new(update,self); @routes.each { |r| r.call(ctx) }
210
+ update.each_key { |key| @event_handlers[key].call(ctx) if @event_handlers[key] }
211
+ if ctx.command && @commands[ctx.command]; @commands[ctx.command].call(ctx)
212
+ elsif @text_handler && !ctx.text.empty?; @text_handler.call(ctx); end
213
+ end
214
+ def start(**options) = run(**options)
215
+ def stop
216
+ @stop=true
217
+ @queue.close
218
+ true
219
+ end
220
+ def run(mode: "polling", listen: "127.0.0.1:8080", webhook_path: "/telegram/webhook", webhook_secret: nil, tls: {})
221
+ workers=Array.new(WORKER_COUNT) { Thread.new { worker_loop } }; trap_signals
222
+ mode.to_s=="webhook" ? serve_webhook(listen, webhook_path, webhook_secret, tls) : poll_loop
223
+ ensure
224
+ stop; workers&.each(&:join); @shutdown_hooks.each(&:call)
225
+ end
226
+ def health = {"status"=>"ok","queue"=>@queue.size,"workers"=>WORKER_COUNT}
227
+ private
228
+ def worker_loop
229
+ until @stop
230
+ record=@queue.pop; break unless record
231
+ begin; handle(record["update"]); @queue.ack(record); rescue => e; @queue.fail(record,e); end
232
+ end
233
+ end
234
+ def poll_loop
235
+ offset=nil
236
+ until @stop
237
+ @telegram.updates(offset: offset).each { |u| offset=u["update_id"].to_i+1; enqueue(u) }
238
+ end
239
+ end
240
+ def serve_webhook(listen,path,secret,tls)
241
+ host,port=listen.split(":"); server=WEBrick::HTTPServer.new(BindAddress:host,Port:port.to_i,AccessLog:[],Logger:WEBrick::Log.new($stderr,WEBrick::Log::WARN), **tls_options(tls))
242
+ server.mount_proc(path) do |req,res|
243
+ raise WEBrick::HTTPStatus::Forbidden if secret && req.header["x-telegram-bot-api-secret-token"].to_s != secret
244
+ raise WEBrick::HTTPStatus::BadRequest unless req.body.to_s.bytesize <= 1_048_576
245
+ enqueue(JSON.parse(req.body)); res.status=202; res.body="accepted\n"
246
+ rescue JSON::ParserError; res.status=400; res.body="invalid JSON\n"
247
+ rescue WEBrick::HTTPStatus::Status => e; res.status=e.code; res.body="rejected\n"
248
+ end
249
+ server.mount_proc("/healthz") { |_q,r| r["Content-Type"]="application/json"; r.body=JSON.generate(health) }
250
+ server.mount_proc("/readyz") { |_q,r| r.status=(@stop ? 503 : 200); r.body=JSON.generate(health) }
251
+ server.mount_proc("/metrics") { |_q,r| r["Content-Type"]="text/plain"; r.body="ll_rb_queue_size #{@queue.size}\nll_rb_workers #{WORKER_COUNT}\n" }
252
+ trap("TERM") { server.shutdown }; trap("INT") { server.shutdown }; server.start
253
+ end
254
+ def tls_options(tls)
255
+ return {} unless tls && tls["cert"] && tls["key"]
256
+ {SSLEnable:true, SSLCertificate:OpenSSL::X509::Certificate.new(File.read(tls["cert"])), SSLPrivateKey:OpenSSL::PKey.read(File.read(tls["key"])), SSLVerifyClient:(tls["verify_client"] ? OpenSSL::SSL::VERIFY_PEER : OpenSSL::SSL::VERIFY_NONE), SSLCAFile:tls["ca"]}
257
+ end
258
+ def trap_signals; trap("TERM"){@stop=true}; trap("INT"){@stop=true}; end
259
+ end
260
+
261
+ module CLI
262
+ def self.run(args)
263
+ if args.include?("--fetch-schema"); Schema.fetch; puts "schema fetched and parsed in memory"; return 0 end
264
+ config=Config.load(args[args.index("--config") + 1]) if args.include?("--config")
265
+ token=ENV["TELEGRAM_BOT_TOKEN"] || config&.dig("telegram","token")
266
+ abort "TELEGRAM_BOT_TOKEN or telegram.token is required" if token.to_s.empty?
267
+ bot=Bot.new(token: token, queue_capacity: config&.fetch("queue_capacity",1024) || 1024, spool_path: config&.fetch("spool_path","var/updates.spool") || "var/updates.spool", dlq_path: config&.fetch("dlq_path","var/updates.dlq") || "var/updates.dlq")
268
+ bot.run(mode: config&.fetch("mode","polling") || "polling", listen: config&.fetch("listen","127.0.0.1:8080") || "127.0.0.1:8080", webhook_path: config&.fetch("webhook_path","/telegram/webhook") || "/telegram/webhook", webhook_secret: config&.dig("webhook_secret"))
269
+ 0
270
+ rescue Interrupt; 0
271
+ rescue => e; warn "ll-rb: #{e.message}"; 1
272
+ end
273
+ end
274
+ end
275
+ end
metadata ADDED
@@ -0,0 +1,54 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ll-rb
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - ll-tg
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-11-28 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Standard-library Telegram bot framework for webhook and long-polling
14
+ deployments.
15
+ email:
16
+ executables:
17
+ - ll-rb
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - ".gitignore"
22
+ - LICENSE
23
+ - README.md
24
+ - bin/ll-rb
25
+ - config/config.toml.example
26
+ - docs/api.md
27
+ - docs/security.md
28
+ - docs/storage.md
29
+ - examples/echo_bot.rb
30
+ - lib/ll/rb.rb
31
+ homepage: https://github.com/ll-tg/ll-rb
32
+ licenses:
33
+ - MIT
34
+ metadata: {}
35
+ post_install_message:
36
+ rdoc_options: []
37
+ require_paths:
38
+ - lib
39
+ required_ruby_version: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - ">="
42
+ - !ruby/object:Gem::Version
43
+ version: '3.1'
44
+ required_rubygems_version: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: '0'
49
+ requirements: []
50
+ rubygems_version: 3.4.20
51
+ signing_key:
52
+ specification_version: 4
53
+ summary: A Ruby-only Telegram bot runtime with bounded delivery and lifecycle controls
54
+ test_files: []