tina4ruby 3.13.157 → 3.13.159
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 +4 -4
- data/CHANGELOG.md +39 -0
- data/lib/tina4/cli.rb +73 -18
- data/lib/tina4/database.rb +14 -2
- data/lib/tina4/database_url.rb +7 -3
- data/lib/tina4/dev_admin.rb +15 -5
- data/lib/tina4/dispatch_pipeline.rb +5 -0
- data/lib/tina4/frond.rb +80 -10
- data/lib/tina4/migration.rb +35 -0
- data/lib/tina4/public/bundled-component-provenance.json +2 -2
- data/lib/tina4/public/js/frond.js +26 -7
- data/lib/tina4/public/js/frond.min.js +1 -1
- data/lib/tina4/query_builder.rb +32 -0
- data/lib/tina4/queue_backends/kafka_backend.rb +39 -7
- data/lib/tina4/shutdown.rb +13 -0
- data/lib/tina4/tcp.rb +573 -0
- data/lib/tina4/version.rb +1 -1
- data/lib/tina4/webserver.rb +5 -0
- data/lib/tina4.rb +1 -0
- metadata +3 -2
data/lib/tina4/query_builder.rb
CHANGED
|
@@ -186,6 +186,38 @@ module Tina4
|
|
|
186
186
|
self
|
|
187
187
|
end
|
|
188
188
|
|
|
189
|
+
# Set OFFSET (rows to skip) as its own chainable verb.
|
|
190
|
+
#
|
|
191
|
+
# `limit(n, offset)` buries the offset as a second positional arg; this
|
|
192
|
+
# exposes it on its own, so `.offset(20).limit(10)` reads naturally and
|
|
193
|
+
# matches the SQL keyword.
|
|
194
|
+
#
|
|
195
|
+
# @param count [Integer] Number of rows to skip.
|
|
196
|
+
# @return [self]
|
|
197
|
+
def offset(count)
|
|
198
|
+
@offset_val = count
|
|
199
|
+
self
|
|
200
|
+
end
|
|
201
|
+
|
|
202
|
+
# Alias for {#offset} — the Mongo/Eloquent name for the same thing.
|
|
203
|
+
#
|
|
204
|
+
# Mirrors the DocStore cursor's `skip` and the `:skip` key that {#to_mongo}
|
|
205
|
+
# already emits, so a query reads the same whether it targets SQL or MongoDB.
|
|
206
|
+
#
|
|
207
|
+
# @param count [Integer] Number of rows to skip.
|
|
208
|
+
# @return [self]
|
|
209
|
+
def skip(count)
|
|
210
|
+
offset(count)
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
# Alias for {#limit} — the Eloquent name; pairs with {#skip}.
|
|
214
|
+
#
|
|
215
|
+
# @param count [Integer] Maximum rows to return.
|
|
216
|
+
# @return [self]
|
|
217
|
+
def take(count)
|
|
218
|
+
limit(count)
|
|
219
|
+
end
|
|
220
|
+
|
|
189
221
|
# Build and return the SQL string without executing.
|
|
190
222
|
#
|
|
191
223
|
# @return [String] The constructed SQL query.
|
|
@@ -42,6 +42,11 @@ module Tina4
|
|
|
42
42
|
}.merge(security)
|
|
43
43
|
@consumer = Rdkafka::Config.new(consumer_config).consumer
|
|
44
44
|
@subscribed_topics = []
|
|
45
|
+
# Records polled but not yet acknowledged, keyed by the id the Queue
|
|
46
|
+
# hands back to acknowledge(), valued by the rdkafka message (its
|
|
47
|
+
# topic/partition/offset). acknowledge() commits exactly THAT record's
|
|
48
|
+
# offset, never a single "last message" slot (ADR-0022 decision 3).
|
|
49
|
+
@in_flight = {}
|
|
45
50
|
rescue LoadError
|
|
46
51
|
raise "Kafka backend requires the 'rdkafka' gem. Install with: gem install rdkafka"
|
|
47
52
|
end
|
|
@@ -157,12 +162,28 @@ module Tina4
|
|
|
157
162
|
return nil unless msg
|
|
158
163
|
|
|
159
164
|
data = Tina4.parse_json(msg.payload)
|
|
160
|
-
|
|
165
|
+
coordinate = "#{topic}:#{msg.partition}:#{msg.offset}"
|
|
166
|
+
|
|
167
|
+
# A record carrying a "payload" key is a Tina4 envelope: keep its own id
|
|
168
|
+
# (falling back to the coordinate) and carry attempts/error back so a
|
|
169
|
+
# redelivery does not reset the count and re-produce a poison record
|
|
170
|
+
# forever. A record WITHOUT one is externally produced (Debezium/CDC and
|
|
171
|
+
# friends, no envelope, no id -- tina4#274): its whole value IS the
|
|
172
|
+
# payload, and the coordinate becomes its id. Either way the job gets the
|
|
173
|
+
# id acknowledge() maps back to this record's offset.
|
|
174
|
+
job =
|
|
175
|
+
if data.is_a?(Hash) && data.key?("payload")
|
|
176
|
+
id = data["id"].to_s.empty? ? coordinate : data["id"]
|
|
177
|
+
Tina4::Job.new(
|
|
178
|
+
topic: topic, payload: data["payload"], id: id,
|
|
179
|
+
attempts: data["attempts"] || 0, error: data["error"]
|
|
180
|
+
)
|
|
181
|
+
else
|
|
182
|
+
Tina4::Job.new(topic: topic, payload: data, id: coordinate, attempts: 0)
|
|
183
|
+
end
|
|
161
184
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
# redelivery, so a poison record would be re-produced forever.
|
|
165
|
-
Tina4::Job.from_payload(data)
|
|
185
|
+
@in_flight[job.id.to_s] = msg
|
|
186
|
+
job
|
|
166
187
|
rescue Rdkafka::RdkafkaError
|
|
167
188
|
nil
|
|
168
189
|
end
|
|
@@ -177,8 +198,19 @@ module Tina4
|
|
|
177
198
|
0
|
|
178
199
|
end
|
|
179
200
|
|
|
180
|
-
|
|
181
|
-
|
|
201
|
+
# Commit the offset JUST PAST the acknowledged record so the group never
|
|
202
|
+
# re-reads it, even across a restart (ADR-0022 decisions 2 + 4). The offset
|
|
203
|
+
# is committed for the specific record dequeue() tracked against this job's
|
|
204
|
+
# id -- NOT a bare @consumer.commit of the whole polled position, which
|
|
205
|
+
# would commit past records still in flight when jobs are completed out of
|
|
206
|
+
# order (decision 3). A job never dequeued (or already acked) is a no-op.
|
|
207
|
+
def acknowledge(message)
|
|
208
|
+
msg = @in_flight.delete(message.id.to_s)
|
|
209
|
+
return unless msg
|
|
210
|
+
|
|
211
|
+
tpl = Rdkafka::Consumer::TopicPartitionList.new
|
|
212
|
+
tpl.add_topic_and_partitions_with_offsets(msg.topic, msg.partition => msg.offset + 1)
|
|
213
|
+
@consumer.commit(tpl, false)
|
|
182
214
|
end
|
|
183
215
|
|
|
184
216
|
def requeue(message)
|
data/lib/tina4/shutdown.rb
CHANGED
|
@@ -106,10 +106,21 @@ module Tina4
|
|
|
106
106
|
# otherwise leak on every single shutdown.
|
|
107
107
|
def release_resources
|
|
108
108
|
close_websockets
|
|
109
|
+
stop_tcp_services
|
|
109
110
|
stop_background_tasks
|
|
110
111
|
close_database
|
|
111
112
|
end
|
|
112
113
|
|
|
114
|
+
# Drain live raw TCP service connections (feature 142) within the deadline,
|
|
115
|
+
# firing their on_close handlers, alongside the HTTP/WebSocket drain.
|
|
116
|
+
def stop_tcp_services
|
|
117
|
+
return unless defined?(Tina4::Tcp)
|
|
118
|
+
|
|
119
|
+
Tina4::Tcp.drain_all(timeout: @timeout.to_f)
|
|
120
|
+
rescue StandardError => e
|
|
121
|
+
Tina4::Log.error("Error draining TCP services: #{e.message}")
|
|
122
|
+
end
|
|
123
|
+
|
|
113
124
|
# Block until initiate_shutdown has finished every teardown step.
|
|
114
125
|
#
|
|
115
126
|
# stop_accepting unblocks the built-in server's accept loop immediately, so
|
|
@@ -158,6 +169,8 @@ module Tina4
|
|
|
158
169
|
return unless @server.respond_to?(:shutdown)
|
|
159
170
|
|
|
160
171
|
@server.shutdown
|
|
172
|
+
# Raw TCP listeners stop accepting at the same moment as HTTP.
|
|
173
|
+
Tina4::Tcp.stop_accepting_all if defined?(Tina4::Tcp)
|
|
161
174
|
Tina4::Log.info("Stopped accepting new connections")
|
|
162
175
|
rescue StandardError => e
|
|
163
176
|
Tina4::Log.error("Error closing the listening socket: #{e.message}")
|
data/lib/tina4/tcp.rb
ADDED
|
@@ -0,0 +1,573 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Copyright (c) 2026 Code Infinity
|
|
4
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
5
|
+
# This Source Code Form is subject to the terms of the Mozilla Public
|
|
6
|
+
# License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
7
|
+
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
8
|
+
|
|
9
|
+
require "socket"
|
|
10
|
+
|
|
11
|
+
module Tina4
|
|
12
|
+
# Raw TCP service — a user-facing, non-HTTP, long-lived binary TCP listener.
|
|
13
|
+
#
|
|
14
|
+
# Governed by ADR-0102 (feature 142), and the Python reference
|
|
15
|
+
# tina4_python/tcp. A Tina4 app exposes its own protocol — a GPS/GPRS
|
|
16
|
+
# car-tracker gateway (GT06/TK103/Concox/Teltonika) is the driving case — in
|
|
17
|
+
# the SAME process as its HTTP dashboard, reusing config, logging, ORM and
|
|
18
|
+
# queue.
|
|
19
|
+
#
|
|
20
|
+
# svc = Tina4::Tcp.service(5023, idle_timeout: 0, max_connections: 5000)
|
|
21
|
+
# svc.on_data do |conn, data|
|
|
22
|
+
# frame = parse(data) # the APP frames the stream
|
|
23
|
+
# conn.identify(frame.imei) if frame.login?
|
|
24
|
+
# conn.send(ack_for(frame)) # ACK on the same socket
|
|
25
|
+
# end
|
|
26
|
+
#
|
|
27
|
+
# # server -> device push from an HTTP route:
|
|
28
|
+
# Tina4::Tcp.get.send_to(imei, build_command("set_interval", 30))
|
|
29
|
+
#
|
|
30
|
+
# Ruby's thread-per-connection model satisfies D1 (in-process): the acceptor
|
|
31
|
+
# thread runs in the SAME VM as the HTTP server, so the device gateway and its
|
|
32
|
+
# dashboard share one process. The framework owns the socket hard-parts:
|
|
33
|
+
# lifecycle, max_connections refusal, an idle reaper (default OFF for
|
|
34
|
+
# long-lived device sockets), graceful-shutdown drain, bounded write
|
|
35
|
+
# backpressure, and single-owner bind under N workers.
|
|
36
|
+
#
|
|
37
|
+
# Non-goals in v1 (ADR-0102): no CRC/length framing helper beyond on_line, no
|
|
38
|
+
# TLS termination, no UDP, no replacement for the WebSocket surface.
|
|
39
|
+
|
|
40
|
+
# One live TCP connection — the uniform connection object (ADR-0102 D5). The
|
|
41
|
+
# SAME surface exists in all four frameworks so the primitive ports.
|
|
42
|
+
class TcpConnection
|
|
43
|
+
# The raw TCP peer address ("127.0.0.1:54321"), never a forwarded header.
|
|
44
|
+
attr_reader :remote_addr
|
|
45
|
+
# Per-connection mutable state bag — the app's parse buffer, auth flag.
|
|
46
|
+
attr_accessor :context
|
|
47
|
+
attr_reader :socket
|
|
48
|
+
# Stable registry key: the fd number captured at construction (see below).
|
|
49
|
+
attr_reader :fileno
|
|
50
|
+
|
|
51
|
+
def initialize(socket, service, remote_addr)
|
|
52
|
+
@socket = socket
|
|
53
|
+
# Cache the fd number now: once the socket is closed, #fileno raises
|
|
54
|
+
# IOError, and the registry still needs a stable key to remove by.
|
|
55
|
+
@fileno = begin
|
|
56
|
+
socket.fileno
|
|
57
|
+
rescue IOError, SystemCallError
|
|
58
|
+
nil
|
|
59
|
+
end
|
|
60
|
+
@service = service
|
|
61
|
+
@remote_addr = remote_addr
|
|
62
|
+
@id = nil # the registry id (IMEI), nil until identify
|
|
63
|
+
@context = {}
|
|
64
|
+
@closed = false
|
|
65
|
+
@close_fired = false
|
|
66
|
+
@last_activity = monotonic
|
|
67
|
+
@pending = +"".b
|
|
68
|
+
@line_buffer = +"".b
|
|
69
|
+
@write_lock = Mutex.new
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# The registry id (the IMEI), or nil until identify is called.
|
|
73
|
+
def id
|
|
74
|
+
@id
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def closed?
|
|
78
|
+
@closed
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def last_activity
|
|
82
|
+
@last_activity
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def touch
|
|
86
|
+
@last_activity = monotonic
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
# Accessors the service's reader loop uses for on_line buffering.
|
|
90
|
+
def line_buffer
|
|
91
|
+
@line_buffer
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def line_buffer=(value)
|
|
95
|
+
@line_buffer = value
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
# Register this live connection under an app-chosen id (the IMEI). A second
|
|
99
|
+
# connection identifying with the same id SUPERSEDES the first in the
|
|
100
|
+
# registry — exactly a device that dropped and reconnected.
|
|
101
|
+
def identify(app_id)
|
|
102
|
+
@id = app_id.to_s
|
|
103
|
+
@service.register_id(@id, self)
|
|
104
|
+
self
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# Write raw bytes to THIS socket. Returns true when queued/sent, false when
|
|
108
|
+
# the connection is closed or dropped for backpressure. A stalled reader
|
|
109
|
+
# (never draining) is bounded: once more than the service's max_backlog
|
|
110
|
+
# bytes are outstanding, the connection is dropped rather than buffered
|
|
111
|
+
# without end (mirrors the WebSocket TINA4_WS_MAX_BACKLOG posture).
|
|
112
|
+
def send(data)
|
|
113
|
+
return false if @closed
|
|
114
|
+
|
|
115
|
+
bytes = data.to_s.dup.force_encoding(Encoding::BINARY)
|
|
116
|
+
overflow = false
|
|
117
|
+
@write_lock.synchronize do
|
|
118
|
+
@pending << bytes
|
|
119
|
+
flush_pending
|
|
120
|
+
limit = @service.max_backlog
|
|
121
|
+
overflow = (limit.positive? && @pending.bytesize > limit)
|
|
122
|
+
end
|
|
123
|
+
return false if @closed
|
|
124
|
+
|
|
125
|
+
if overflow
|
|
126
|
+
Tina4::Log.warning(
|
|
127
|
+
"tcp_service '#{@service.name}': dropping a stalled reader — " \
|
|
128
|
+
"#{@pending.bytesize} bytes queued exceeds the #{@service.max_backlog}-byte backlog limit"
|
|
129
|
+
)
|
|
130
|
+
close
|
|
131
|
+
return false
|
|
132
|
+
end
|
|
133
|
+
true
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
# Flush the per-connection queue without blocking. Caller holds @write_lock.
|
|
137
|
+
def flush_pending
|
|
138
|
+
return if @socket.nil? || @pending.empty?
|
|
139
|
+
|
|
140
|
+
until @pending.empty?
|
|
141
|
+
written = @socket.write_nonblock(@pending, exception: false)
|
|
142
|
+
break if written == :wait_writable
|
|
143
|
+
|
|
144
|
+
@pending = @pending.byteslice(written..) || +"".b
|
|
145
|
+
end
|
|
146
|
+
rescue IOError, SystemCallError
|
|
147
|
+
@closed = true
|
|
148
|
+
close_socket
|
|
149
|
+
end
|
|
150
|
+
|
|
151
|
+
# Opportunistic flush from the reader loop (acquires the lock).
|
|
152
|
+
def try_flush
|
|
153
|
+
return if @closed
|
|
154
|
+
|
|
155
|
+
@write_lock.synchronize { flush_pending }
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
# Close this connection. on_close fires exactly once (from the service's
|
|
159
|
+
# removal path) and the registry entry is removed.
|
|
160
|
+
def close
|
|
161
|
+
return if @closed
|
|
162
|
+
|
|
163
|
+
@closed = true
|
|
164
|
+
close_socket
|
|
165
|
+
@service.remove(self)
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
# Fire on_close exactly once. Called by the service when the connection
|
|
169
|
+
# leaves (peer close, server close, reap, or drain).
|
|
170
|
+
def fire_close
|
|
171
|
+
return if @close_fired
|
|
172
|
+
|
|
173
|
+
@close_fired = true
|
|
174
|
+
@closed = true
|
|
175
|
+
handler = @service.callback(:on_close)
|
|
176
|
+
return if handler.nil?
|
|
177
|
+
|
|
178
|
+
begin
|
|
179
|
+
handler.call(self)
|
|
180
|
+
rescue StandardError => e
|
|
181
|
+
Tina4::Log.error("tcp_service '#{@service.name}' on_close error: #{e.message}")
|
|
182
|
+
end
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
private
|
|
186
|
+
|
|
187
|
+
def close_socket
|
|
188
|
+
# Shut the socket down before closing so the peer sees EOF immediately.
|
|
189
|
+
# A plain close is enough on macOS, but on Linux the FIN can be deferred
|
|
190
|
+
# while the reader thread still holds the fd in IO.select, so the client
|
|
191
|
+
# never observes end-of-stream. shutdown(SHUT_RDWR) forces it.
|
|
192
|
+
@socket&.shutdown(Socket::SHUT_RDWR)
|
|
193
|
+
rescue IOError, SystemCallError
|
|
194
|
+
nil
|
|
195
|
+
ensure
|
|
196
|
+
begin
|
|
197
|
+
@socket&.close
|
|
198
|
+
rescue IOError, SystemCallError
|
|
199
|
+
nil
|
|
200
|
+
end
|
|
201
|
+
end
|
|
202
|
+
|
|
203
|
+
def monotonic
|
|
204
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
205
|
+
end
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
# A named raw TCP listener and its connection registry (ADR-0102).
|
|
209
|
+
class TcpService
|
|
210
|
+
READ_CHUNK = 65_536
|
|
211
|
+
|
|
212
|
+
attr_reader :name, :port
|
|
213
|
+
|
|
214
|
+
def initialize(port, name: "default", on_connect: nil, on_data: nil,
|
|
215
|
+
on_close: nil, on_line: nil, idle_timeout: 0,
|
|
216
|
+
max_connections: nil, max_backlog: nil, &block)
|
|
217
|
+
@port = Integer(port)
|
|
218
|
+
@name = name.to_s
|
|
219
|
+
@callbacks = {
|
|
220
|
+
on_connect: on_connect,
|
|
221
|
+
on_data: on_data || block, # a bare block is the on_data handler
|
|
222
|
+
on_close: on_close,
|
|
223
|
+
on_line: on_line
|
|
224
|
+
}
|
|
225
|
+
# Default OFF: tracker sockets are deliberately long-lived and mostly idle
|
|
226
|
+
# between location packets, so a default reaper would kill healthy devices.
|
|
227
|
+
@idle_timeout = idle_timeout.to_f
|
|
228
|
+
@max_connections = max_connections.nil? ? nil : Integer(max_connections)
|
|
229
|
+
@max_backlog = self.class.resolve_max_backlog(max_backlog)
|
|
230
|
+
|
|
231
|
+
@connections = {} # socket.fileno => TcpConnection
|
|
232
|
+
@by_id = {} # app_id => TcpConnection
|
|
233
|
+
@mutex = Mutex.new
|
|
234
|
+
@server = nil
|
|
235
|
+
@owner = false
|
|
236
|
+
@bound_port = nil
|
|
237
|
+
@acceptor = nil
|
|
238
|
+
@readers = {} # object_id => Thread
|
|
239
|
+
@running = false
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
def self.resolve_max_backlog(explicit)
|
|
243
|
+
default = 1 << 20 # 1 MiB
|
|
244
|
+
return (explicit.to_i.positive? ? explicit.to_i : default) unless explicit.nil?
|
|
245
|
+
|
|
246
|
+
raw = (ENV["TINA4_TCP_MAX_BACKLOG"] || "").strip
|
|
247
|
+
return default if raw.empty?
|
|
248
|
+
|
|
249
|
+
value = raw.to_i
|
|
250
|
+
value.positive? ? value : default
|
|
251
|
+
end
|
|
252
|
+
|
|
253
|
+
def max_backlog
|
|
254
|
+
@max_backlog
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
def callback(event)
|
|
258
|
+
@callbacks[event]
|
|
259
|
+
end
|
|
260
|
+
|
|
261
|
+
def owner?
|
|
262
|
+
@owner
|
|
263
|
+
end
|
|
264
|
+
|
|
265
|
+
def bound_port
|
|
266
|
+
@bound_port || @port
|
|
267
|
+
end
|
|
268
|
+
|
|
269
|
+
def count
|
|
270
|
+
@mutex.synchronize { @connections.size }
|
|
271
|
+
end
|
|
272
|
+
|
|
273
|
+
# ── Decorator-style setters (parity with the Python @svc.on_* handlers) ──
|
|
274
|
+
|
|
275
|
+
def on_connect(&block) = set_callback(:on_connect, block)
|
|
276
|
+
def on_data(&block) = set_callback(:on_data, block)
|
|
277
|
+
def on_close(&block) = set_callback(:on_close, block)
|
|
278
|
+
def on_line(&block) = set_callback(:on_line, block)
|
|
279
|
+
|
|
280
|
+
# ── Registry (D4 — server -> device push) ──────────────────────────────
|
|
281
|
+
|
|
282
|
+
def register_id(app_id, conn)
|
|
283
|
+
@mutex.synchronize { @by_id[app_id] = conn } # supersede: the live one wins
|
|
284
|
+
end
|
|
285
|
+
|
|
286
|
+
# The live connection for an app id, or nil if unknown or closed.
|
|
287
|
+
def connection(app_id)
|
|
288
|
+
conn = @mutex.synchronize { @by_id[app_id.to_s] }
|
|
289
|
+
return nil if conn.nil? || conn.closed?
|
|
290
|
+
|
|
291
|
+
conn
|
|
292
|
+
end
|
|
293
|
+
|
|
294
|
+
# Write bytes to exactly the connection identified by app_id. A send to an
|
|
295
|
+
# unknown or closed id is a NO-OP that returns false — never a raise.
|
|
296
|
+
def send_to(app_id, data)
|
|
297
|
+
conn = connection(app_id)
|
|
298
|
+
return false if conn.nil?
|
|
299
|
+
|
|
300
|
+
conn.send(data)
|
|
301
|
+
end
|
|
302
|
+
|
|
303
|
+
# Write bytes to every live connection. Returns how many received it.
|
|
304
|
+
def broadcast(data)
|
|
305
|
+
conns = @mutex.synchronize { @connections.values.dup }
|
|
306
|
+
conns.count { |conn| conn.send(data) }
|
|
307
|
+
end
|
|
308
|
+
|
|
309
|
+
# ── Lifecycle ────────────────────────────────────────────────────────────
|
|
310
|
+
|
|
311
|
+
# Bind the listener on host:port and start accepting on a dedicated thread.
|
|
312
|
+
# SO_REUSEPORT is OFF, so under a multi-worker deployment exactly ONE worker
|
|
313
|
+
# wins the bind; a worker that finds the port already bound skips silently
|
|
314
|
+
# (single-owner, D1). Returns true when THIS call bound the port.
|
|
315
|
+
def start(host = "0.0.0.0")
|
|
316
|
+
return @owner unless @server.nil?
|
|
317
|
+
|
|
318
|
+
begin
|
|
319
|
+
@server = TCPServer.new(host, @port)
|
|
320
|
+
rescue Errno::EADDRINUSE, Errno::EADDRNOTAVAIL => e
|
|
321
|
+
@owner = false
|
|
322
|
+
Tina4::Log.info(
|
|
323
|
+
"tcp_service '#{@name}' port #{@port} is already bound by another worker — " \
|
|
324
|
+
"single-owner, this worker will not bind (#{e.class})"
|
|
325
|
+
)
|
|
326
|
+
return false
|
|
327
|
+
end
|
|
328
|
+
@owner = true
|
|
329
|
+
@running = true
|
|
330
|
+
@bound_port = @server.addr[1]
|
|
331
|
+
Tina4::Log.info("tcp_service '#{@name}' listening on #{host}:#{@bound_port}")
|
|
332
|
+
@acceptor = Thread.new { accept_loop }
|
|
333
|
+
true
|
|
334
|
+
end
|
|
335
|
+
|
|
336
|
+
# Stop accepting new connections (close the listener). Live connections stay.
|
|
337
|
+
def stop_accepting
|
|
338
|
+
@running = false
|
|
339
|
+
srv = @server
|
|
340
|
+
@server = nil
|
|
341
|
+
srv&.close
|
|
342
|
+
rescue IOError, SystemCallError
|
|
343
|
+
nil
|
|
344
|
+
end
|
|
345
|
+
|
|
346
|
+
# Close every live connection (firing on_close) and release the listener.
|
|
347
|
+
def drain(timeout: 5.0)
|
|
348
|
+
stop_accepting
|
|
349
|
+
@acceptor&.join(timeout)
|
|
350
|
+
conns = @mutex.synchronize { @connections.values.dup }
|
|
351
|
+
conns.each(&:close)
|
|
352
|
+
readers = @mutex.synchronize { @readers.values.dup }
|
|
353
|
+
deadline = monotonic + timeout
|
|
354
|
+
readers.each do |thread|
|
|
355
|
+
remaining = deadline - monotonic
|
|
356
|
+
thread.join(remaining.positive? ? remaining : 0)
|
|
357
|
+
end
|
|
358
|
+
end
|
|
359
|
+
|
|
360
|
+
alias stop drain
|
|
361
|
+
|
|
362
|
+
# Remove a connection from the registry and fire on_close exactly once.
|
|
363
|
+
# Called by TcpConnection#close and by the reader loop on EOF.
|
|
364
|
+
def remove(conn)
|
|
365
|
+
tracked = false
|
|
366
|
+
@mutex.synchronize do
|
|
367
|
+
key = conn.fileno
|
|
368
|
+
if key && @connections[key].equal?(conn)
|
|
369
|
+
@connections.delete(key)
|
|
370
|
+
tracked = true
|
|
371
|
+
else
|
|
372
|
+
found = @connections.key(conn)
|
|
373
|
+
unless found.nil?
|
|
374
|
+
@connections.delete(found)
|
|
375
|
+
tracked = true
|
|
376
|
+
end
|
|
377
|
+
end
|
|
378
|
+
# Only drop the id when THIS connection still owns it; a newer
|
|
379
|
+
# connection that superseded it keeps the id.
|
|
380
|
+
@by_id.delete(conn.id) if conn.id && @by_id[conn.id].equal?(conn)
|
|
381
|
+
end
|
|
382
|
+
conn.fire_close if tracked
|
|
383
|
+
end
|
|
384
|
+
|
|
385
|
+
private
|
|
386
|
+
|
|
387
|
+
def set_callback(event, block)
|
|
388
|
+
@callbacks[event] = block if block
|
|
389
|
+
self
|
|
390
|
+
end
|
|
391
|
+
|
|
392
|
+
def accept_loop
|
|
393
|
+
while @running
|
|
394
|
+
begin
|
|
395
|
+
socket = @server&.accept
|
|
396
|
+
rescue IOError, Errno::EBADF, Errno::ECONNABORTED
|
|
397
|
+
break # listener closed by stop_accepting
|
|
398
|
+
end
|
|
399
|
+
break if socket.nil?
|
|
400
|
+
|
|
401
|
+
handle_accept(socket)
|
|
402
|
+
end
|
|
403
|
+
rescue StandardError => e
|
|
404
|
+
Tina4::Log.error("tcp_service '#{@name}' accept loop error: #{e.message}")
|
|
405
|
+
end
|
|
406
|
+
|
|
407
|
+
def handle_accept(socket)
|
|
408
|
+
# Refuse past the limit BEFORE the connection joins the registry.
|
|
409
|
+
over_limit = @mutex.synchronize do
|
|
410
|
+
!@max_connections.nil? && @connections.size >= @max_connections
|
|
411
|
+
end
|
|
412
|
+
if over_limit
|
|
413
|
+
socket.close rescue nil
|
|
414
|
+
return
|
|
415
|
+
end
|
|
416
|
+
|
|
417
|
+
conn = TcpConnection.new(socket, self, peer_address(socket))
|
|
418
|
+
@mutex.synchronize { @connections[conn.fileno] = conn }
|
|
419
|
+
|
|
420
|
+
fire(:on_connect, conn)
|
|
421
|
+
|
|
422
|
+
reader = Thread.new { reader_loop(conn) }
|
|
423
|
+
@mutex.synchronize { @readers[conn.object_id] = reader }
|
|
424
|
+
end
|
|
425
|
+
|
|
426
|
+
def reader_loop(conn)
|
|
427
|
+
socket = conn.socket
|
|
428
|
+
line_handler = @callbacks[:on_line]
|
|
429
|
+
sweep = @idle_timeout.positive? ? [@idle_timeout / 2.0, 1.0].min.clamp(0.05, 1.0) : nil
|
|
430
|
+
loop do
|
|
431
|
+
break if conn.closed?
|
|
432
|
+
|
|
433
|
+
ready = IO.select([socket], nil, nil, sweep)
|
|
434
|
+
if ready.nil?
|
|
435
|
+
# Idle sweep: close a connection silent past the timeout.
|
|
436
|
+
if @idle_timeout.positive? && (monotonic - conn.last_activity) >= @idle_timeout
|
|
437
|
+
conn.close
|
|
438
|
+
break
|
|
439
|
+
end
|
|
440
|
+
next
|
|
441
|
+
end
|
|
442
|
+
|
|
443
|
+
data = socket.read_nonblock(READ_CHUNK, exception: false)
|
|
444
|
+
next if data == :wait_readable
|
|
445
|
+
break if data.nil? # EOF — peer closed
|
|
446
|
+
|
|
447
|
+
conn.touch
|
|
448
|
+
dispatch_data(conn, data, line_handler)
|
|
449
|
+
conn.try_flush
|
|
450
|
+
end
|
|
451
|
+
rescue IOError, EOFError, Errno::ECONNRESET, Errno::EBADF
|
|
452
|
+
nil
|
|
453
|
+
rescue StandardError => e
|
|
454
|
+
Tina4::Log.error("tcp_service '#{@name}' handler error: #{e.message}")
|
|
455
|
+
ensure
|
|
456
|
+
@mutex.synchronize { @readers.delete(conn.object_id) }
|
|
457
|
+
remove(conn)
|
|
458
|
+
end
|
|
459
|
+
|
|
460
|
+
def dispatch_data(conn, data, line_handler)
|
|
461
|
+
on_data = @callbacks[:on_data]
|
|
462
|
+
# Raw bytes, exactly as received — never newline-split, never decoded.
|
|
463
|
+
if on_data
|
|
464
|
+
begin
|
|
465
|
+
on_data.call(conn, data)
|
|
466
|
+
rescue StandardError => e
|
|
467
|
+
Tina4::Log.error("tcp_service '#{@name}' on_data error: #{e.message}")
|
|
468
|
+
end
|
|
469
|
+
end
|
|
470
|
+
|
|
471
|
+
return unless line_handler
|
|
472
|
+
|
|
473
|
+
buffer = conn.line_buffer
|
|
474
|
+
buffer << data
|
|
475
|
+
while (index = buffer.index("\n"))
|
|
476
|
+
line = buffer.byteslice(0, index)
|
|
477
|
+
buffer = buffer.byteslice(index + 1..) || +"".b
|
|
478
|
+
line = line.chomp("\r")
|
|
479
|
+
begin
|
|
480
|
+
line_handler.call(conn, line)
|
|
481
|
+
rescue StandardError => e
|
|
482
|
+
Tina4::Log.error("tcp_service '#{@name}' on_line error: #{e.message}")
|
|
483
|
+
end
|
|
484
|
+
end
|
|
485
|
+
conn.line_buffer = buffer
|
|
486
|
+
end
|
|
487
|
+
|
|
488
|
+
def fire(event, conn)
|
|
489
|
+
handler = @callbacks[event]
|
|
490
|
+
return if handler.nil?
|
|
491
|
+
|
|
492
|
+
begin
|
|
493
|
+
handler.call(conn)
|
|
494
|
+
rescue StandardError => e
|
|
495
|
+
Tina4::Log.error("tcp_service '#{@name}' #{event} error: #{e.message}")
|
|
496
|
+
end
|
|
497
|
+
end
|
|
498
|
+
|
|
499
|
+
def peer_address(socket)
|
|
500
|
+
addr = socket.peeraddr(false)
|
|
501
|
+
"#{addr[3]}:#{addr[1]}"
|
|
502
|
+
rescue StandardError
|
|
503
|
+
""
|
|
504
|
+
end
|
|
505
|
+
|
|
506
|
+
def monotonic
|
|
507
|
+
Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
508
|
+
end
|
|
509
|
+
end
|
|
510
|
+
|
|
511
|
+
# Registry facade and the server-driven lifecycle hooks.
|
|
512
|
+
module Tcp
|
|
513
|
+
@services = {}
|
|
514
|
+
@mutex = Mutex.new
|
|
515
|
+
|
|
516
|
+
class << self
|
|
517
|
+
# Register a named raw TCP service; the server binds it on boot (D1).
|
|
518
|
+
def service(port, **options, &block)
|
|
519
|
+
name = (options[:name] || "default").to_s
|
|
520
|
+
svc = TcpService.new(port, **options, &block)
|
|
521
|
+
@mutex.synchronize { @services[name] = svc }
|
|
522
|
+
svc
|
|
523
|
+
end
|
|
524
|
+
|
|
525
|
+
# The registry for a named service, for server -> device push. Raises for
|
|
526
|
+
# an unknown service name — a programming error, unlike a send to an
|
|
527
|
+
# unknown device id, which is a runtime no-op.
|
|
528
|
+
def get(name = "default")
|
|
529
|
+
svc = @mutex.synchronize { @services[name.to_s] }
|
|
530
|
+
return svc unless svc.nil?
|
|
531
|
+
|
|
532
|
+
known = @services.keys.empty? ? "(none registered)" : @services.keys.join(", ")
|
|
533
|
+
raise KeyError, "no tcp_service named '#{name}' is registered; known services: #{known}"
|
|
534
|
+
end
|
|
535
|
+
|
|
536
|
+
def registered
|
|
537
|
+
@mutex.synchronize { @services.values.dup }
|
|
538
|
+
end
|
|
539
|
+
|
|
540
|
+
# Drop every registered service (test isolation; not used in production).
|
|
541
|
+
def clear_registry
|
|
542
|
+
@mutex.synchronize { @services = {} }
|
|
543
|
+
end
|
|
544
|
+
|
|
545
|
+
# Start every registered service on boot (called by the web server).
|
|
546
|
+
def start_all(host = "0.0.0.0")
|
|
547
|
+
registered.each do |svc|
|
|
548
|
+
svc.start(host)
|
|
549
|
+
rescue StandardError => e
|
|
550
|
+
Tina4::Log.error("tcp_service '#{svc.name}' failed to start: #{e.message}")
|
|
551
|
+
end
|
|
552
|
+
end
|
|
553
|
+
|
|
554
|
+
# Stop every service accepting (shutdown step 1).
|
|
555
|
+
def stop_accepting_all
|
|
556
|
+
registered.each do |svc|
|
|
557
|
+
svc.stop_accepting
|
|
558
|
+
rescue StandardError => e
|
|
559
|
+
Tina4::Log.error("tcp_service '#{svc.name}' stop-accepting failed: #{e.message}")
|
|
560
|
+
end
|
|
561
|
+
end
|
|
562
|
+
|
|
563
|
+
# Drain and release every service's connections (shutdown drain step).
|
|
564
|
+
def drain_all(timeout: 5.0)
|
|
565
|
+
registered.each do |svc|
|
|
566
|
+
svc.drain(timeout: timeout)
|
|
567
|
+
rescue StandardError => e
|
|
568
|
+
Tina4::Log.error("tcp_service '#{svc.name}' drain failed: #{e.message}")
|
|
569
|
+
end
|
|
570
|
+
end
|
|
571
|
+
end
|
|
572
|
+
end
|
|
573
|
+
end
|