logifos 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.
data/HISTORY.txt ADDED
@@ -0,0 +1,33 @@
1
+ == Logifos 0.1.0
2
+
3
+ First release: Ruby connects to the bundled logifos engine.
4
+
5
+ * Platform gems carry the engine in two tiers: the MRI extension
6
+ (lib/logifos/<ruby version>/logifos_native), bound through magnus, and the
7
+ portable engine cdylib (lib/logifos/native/), which the ffi tier loads when
8
+ the extension is absent (TruffleRuby, an MRI whose extension did not build).
9
+ A source gem install compiles the extension.
10
+ * `Logifos::NativeRuntime.new` picks the extension when it loaded and the cdylib
11
+ otherwise, with no setup. `library_path:` still selects an external engine,
12
+ and `LOGIFOS_FFI_LIB` names a cdylib for the ffi tier.
13
+ * Each runtime binds its own library context and checks ABI 1, schema 1 and the
14
+ buffer/JSON feature bits before requests. Responses are copied by their exact
15
+ lengths and freed once through the library that allocated them.
16
+ * `negotiate` reports the implemented operations. A MathML `parse` request
17
+ returns the wire model and the Formula contract; `render` returns the SVG
18
+ document for a model rendered with the fonts of the call.
19
+ `render_mathml` parses a MathML document and renders it under the contract
20
+ the parse returned.
21
+ * Fonts are caller-side and belong to each call: `Logifos::NativeRuntime.font`
22
+ encodes caller-owned bytes for `options: { fallback_order:, fonts: }`. The
23
+ wrapper reads no host fonts and keeps no font state.
24
+ * Core refusals raise `Logifos::EngineError` with `code`, `path` and `stage`.
25
+ Loading, compatibility, transport and protocol failures raise
26
+ `LibraryError`, `CompatibilityError`, `TransportError` and `ProtocolError`.
27
+ * The MRI extension is declared Ractor-safe: a request is bytes in, bytes out
28
+ through per-call owned buffers, and the engine keeps no mutable global state.
29
+ * The release train builds every platform gem with both tiers, asserts that
30
+ they ride the gem, and installs and exercises the gem on six platforms before
31
+ publishing.
32
+
33
+ No migrations exist: no earlier version was released.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ribose Inc.
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, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,131 @@
1
+ # logifos-ruby
2
+
3
+ logifos-ruby connects Ruby to the bundled logifos Rust engine. Native
4
+ transport, negotiation, MathML parsing and SVG rendering with the fonts of
5
+ each call work through it; PNG output remains unavailable.
6
+
7
+ ## Bundled engine
8
+
9
+ The engine ships the way parsanol-ruby's does, in two tiers. Platform gems
10
+ carry the MRI extension (`lib/logifos/<ruby version>/logifos_native`), which
11
+ binds the engine through magnus and hands Ruby the response bytes directly,
12
+ and the portable engine cdylib (`lib/logifos/native/liblogifos`), which the
13
+ ffi-gem tier loads when the extension is absent (TruffleRuby, an MRI whose
14
+ extension did not build). The source gem compiles the extension on install.
15
+ `Logifos::NativeRuntime.new` picks the extension when it loaded and the cdylib
16
+ otherwise, so a plain install works with no setup:
17
+
18
+ ```ruby
19
+ require "logifos"
20
+
21
+ runtime = Logifos::NativeRuntime.new
22
+ capabilities = runtime.negotiate
23
+ puts capabilities.fetch("implemented_operations")
24
+ puts runtime.library.engine_version
25
+ ```
26
+
27
+ The extension is declared Ractor-safe: a request hands Ruby its response
28
+ bytes and retains nothing between calls.
29
+
30
+ Fonts stay caller-side: pass the OpenType MATH faces per call
31
+ (`options: { fallback_order:, fonts: }`). Building the source gem (the ruby
32
+ platform) requires Rust — rustc at least the engine's MSRV — and the `rb_sys`
33
+ gem, which the gem declares as a dependency; a prebuilt Rust toolchain is not
34
+ needed for platform gems. `LOGIFOS_FFI_LIB` names a cdylib for the ffi tier
35
+ explicitly.
36
+
37
+ `library_path:` still selects an external engine explicitly (absolute path to a
38
+ readable library). Each runtime binds its own library context and checks ABI 1,
39
+ schema 1, and the buffer/JSON feature bits before requests. Unknown feature
40
+ bits are ignored. The package version is independent of these wire versions.
41
+ Set `required_features:` to demand additional feature bits, such as
42
+ `Logifos::NativeRuntime::RENDER`.
43
+
44
+ `runtime.request(hash)` serializes an explicit wire request;
45
+ `runtime.request_bytes(string)` sends exactly the supplied JSON bytes, including
46
+ embedded NULs and invalid UTF-8, for core validation. Both return the response's
47
+ `result` hash on success. Responses are copied using their exact lengths and
48
+ freed once through the library that allocated them, before Ruby decodes JSON.
49
+ No native buffer escapes to the caller.
50
+
51
+ ## Rendering and per-call fonts
52
+
53
+ `runtime.render(formula, formula_contract:, format: :svg, options: {})` sends a
54
+ render request to the same core and returns the result hash, which holds the
55
+ `svg` document. The contract identity must come from a parse the caller made
56
+ or from the caller's pinned Formula schema; the wrapper does not invent one. A
57
+ render without fonts refuses typed with `MISSING_FONT` at `/options/fonts`, and
58
+ PNG refuses with `UNSUPPORTED_OUTPUT`.
59
+
60
+ `runtime.render_mathml(mathml, fonts:, format: :svg, options: {})` parses a
61
+ MathML document and renders the model under the contract the parse returned,
62
+ so the model and the contract always agree. Invalid MathML raises
63
+ `Logifos::EngineError` (`INVALID_SOURCE`; `TRANSFORM_FAILED` when the syntax
64
+ parses but does not transform):
65
+
66
+ ```ruby
67
+ fonts = [Logifos::NativeRuntime.font(id: "stix", bytes: File.binread(font_path))]
68
+ result = runtime.render_mathml("<math><mi>x</mi></math>", fonts: fonts)
69
+ puts result.fetch("svg")
70
+ ```
71
+
72
+ `Logifos.render` accepts the render arguments plus `library_path:` for an
73
+ external engine. Retain a `NativeRuntime` for repeated calls.
74
+
75
+ Fonts and options belong to each call. To encode caller-owned bytes:
76
+
77
+ ```ruby
78
+ font = Logifos::NativeRuntime.font(id: "Primary", bytes: supplied_bytes, face_index: 0)
79
+ options = { fonts: [font], fallback_order: ["Primary"], font_size_px: 18 }
80
+ ```
81
+
82
+ The helper computes SHA-256 and canonical base64 without validating font data;
83
+ the core reads each font when it renders and refuses typed when it cannot
84
+ (`INVALID_FONT`, `FONT_HASH_MISMATCH`) or when no font in the fallback order
85
+ carries a glyph the formula needs (`MISSING_GLYPH`). Pass the options to
86
+ `render(..., options: options)` or another wire request. No host fonts,
87
+ resource paths, global font mutation or implicit defaults are used by the
88
+ wrapper. Caller options are serialized without mutation and do not affect
89
+ later calls.
90
+
91
+ Core refusals raise `Logifos::EngineError`, preserving `code`, `path`, `stage`
92
+ and the diagnostic message. Library loading raises `LibraryError`; version or
93
+ feature mismatches raise `CompatibilityError`. Transport failures raise
94
+ `TransportError` with numeric `status` and symbolic `code`. Malformed response
95
+ envelopes raise `ProtocolError`. These all inherit from `Logifos::Error` and can
96
+ be rescued normally. Diagnostic messages are not stable API strings.
97
+
98
+ ## Development and focused checks
99
+
100
+ ```sh
101
+ bundle install
102
+ bundle exec rake compile
103
+ bundle exec rspec spec/render_spec.rb spec/logifos
104
+ bundle exec rubocop
105
+ ```
106
+
107
+ `bundle exec rake compile` builds the MRI extension for the running Ruby and
108
+ needs a Rust toolchain. Set `LOGIFOS_LIBRARY_PATH` to the absolute path of a
109
+ matching native library to run the native cases, and `LOGIFOS_FONT` to an
110
+ OpenType MATH face for the end-to-end MathML render. Without them, those cases
111
+ are explicitly skipped and the unit checks still run. The native cases cover
112
+ negotiation, UTF-8 byte limits, binary font transport, bad input, typed
113
+ refusals, independent contexts and repeated allocation/free.
114
+
115
+ `spec/package_smoke_spec.rb` builds the source gem, installs it into temporary
116
+ storage and compiles the extension there, so it needs a Rust toolchain and is
117
+ left to continuous integration.
118
+
119
+ Bundler creates a local `Gemfile.lock`; it is not committed.
120
+
121
+ ## Releases and migrations
122
+
123
+ 0.1.0 is the first release; its changes are recorded in [HISTORY.txt](HISTORY.txt).
124
+ Platform gems come only from the cross-gem train (`gem-build.yml` on push and
125
+ `release.yml` by dispatch), which asserts that both engine tiers ride every
126
+ platform gem and installs the gem on six platforms before publishing. There
127
+ are no migrations: no earlier version was released.
128
+
129
+ ## License
130
+
131
+ MIT; see [LICENSE.txt](LICENSE.txt).
data/Rakefile ADDED
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+
5
+ begin
6
+ require "rspec/core/rake_task"
7
+ rescue LoadError
8
+ # RSpec not available in this environment
9
+ end
10
+
11
+ require "rdoc/task"
12
+ require "rubygems/package_task"
13
+
14
+ begin
15
+ require "opal/rspec/rake_task"
16
+ rescue LoadError, NoMethodError
17
+ # Opal not available or incompatible with current Ruby version
18
+ end
19
+
20
+ GEMSPEC = Gem::Specification.load("logifos.gemspec")
21
+
22
+ # Load rake tasks from rakelib/
23
+ Dir.glob("rakelib/*.rake").each { |r| load r }
24
+
25
+ desc "Run all tests"
26
+ RSpec::Core::RakeTask.new(:spec)
27
+
28
+ namespace :spec do
29
+ desc "Run unit tests only"
30
+ RSpec::Core::RakeTask.new(:unit) do |task|
31
+ task.pattern = "spec/logifos/**/*_spec.rb"
32
+ end
33
+
34
+ if defined?(Opal::RSpec::RakeTask)
35
+ desc "Run Opal (JavaScript) tests"
36
+ Opal::RSpec::RakeTask.new(:opal) do |task|
37
+ task.append_path "lib"
38
+ end
39
+ end
40
+ end
41
+
42
+ RDoc::Task.new do |rdoc|
43
+ rdoc.rdoc_dir = "rdoc"
44
+ rdoc.title = "Logifos"
45
+ rdoc.options << "--line-numbers"
46
+ rdoc.rdoc_files.include("README.adoc")
47
+ rdoc.rdoc_files.include("lib/**/*.rb")
48
+ end
49
+
50
+ desc "Print LOC statistics"
51
+ task :stat do
52
+ %w[lib spec example].each do |dir|
53
+ next unless Dir.exist?(dir)
54
+
55
+ loc = `find #{dir} -name "*.rb" | xargs wc -l | grep 'total'`.split.first.to_i
56
+ printf("%<dir>20s %<loc>d\n", dir: dir, loc: loc)
57
+ end
58
+ end
59
+
60
+ # ===== Native Gem Building =====
61
+ namespace :gem do
62
+ desc "Build source gem (compile on install)"
63
+ task "native:any" do
64
+ sh "rake gem:platform:any gem"
65
+ end
66
+
67
+ # Vendor the pure-portable cdylib into PLATFORM gems (TODO.perf/9):
68
+ # the ruby (source) gem stays binary-free; each cross-gem carries its
69
+ # own triple's liblogifos next to the extension for the ffi tier
70
+ # (MRI resilience fallback, TruffleRuby native).
71
+ desc "Build ext/logifos_cdylib for the active cross target and vendor it"
72
+ task "vendor_cdylib" do
73
+ triplet = ENV["CARGO_BUILD_TARGET"] || ENV.fetch("RUST_TARGET", nil)
74
+ args = ["cargo", "build", "--release", "-p", "logifos_cdylib"]
75
+ args += ["--target", triplet] if triplet
76
+ sh(*args)
77
+ dir = triplet ? "target/#{triplet}/release" : "target/release"
78
+ name = %w[liblogifos.so liblogifos.dylib logifos.dll]
79
+ .map { |n| File.join(dir, n) }
80
+ .find { |f| File.file?(f) }
81
+ raise "cdylib not found under #{dir}" unless name
82
+
83
+ cp name, "lib/logifos/native/"
84
+ end
85
+
86
+ desc "Define the gem task to build on any platform (compile on install)"
87
+ task "platform:any" do
88
+ spec = Gem::Specification.load("logifos.gemspec").dup
89
+ task = Gem::PackageTask.new(spec)
90
+ task.define
91
+ end
92
+ end
93
+
94
+ task default: :spec
@@ -0,0 +1,20 @@
1
+ [package]
2
+ name = "logifos_cdylib"
3
+ version = "0.1.0"
4
+ edition = "2021"
5
+ description = "Vendored cdylib for logifos platform gems: the pure-portable C ABI (no magnus) for the ffi tier"
6
+ license = "MIT"
7
+ publish = false
8
+
9
+ [lib]
10
+ name = "logifos"
11
+ crate-type = ["cdylib"]
12
+ doc = false
13
+
14
+ [dependencies]
15
+ # Pinned to the engine revision the gem ships; bumped with the gem's
16
+ # release train so platform gems stay byte-reproducible.
17
+ logifos-ffi = { git = "https://github.com/logifos/logifos-rs", rev = "e24a601f548d5b40f00e80b679664e30487c168a" }
18
+
19
+ [profile.release]
20
+ strip = "symbols"
@@ -0,0 +1,12 @@
1
+ //! Vendored cdylib twin of logifos-rs's `logifos-ffi` crate, living in
2
+ //! the gem's ext workspace so the cross-gem build matrix can compile it
3
+ //! per platform triple. Mirrors logifos-ffi: linking the rlib publishes
4
+ //! the `#[no_mangle] logifos_*` exports; no wrappers.
5
+
6
+ // Force the dependency into the link even under aggressive stripping.
7
+ // Keep in sync with logifos-rs logifos-ffi/src/lib.rs.
8
+ #[allow(unused_imports)]
9
+ use logifos_ffi::{
10
+ logifos_abi_version, logifos_buffer_free_v1, logifos_engine_version, logifos_features,
11
+ logifos_request_json, logifos_request_v1, logifos_schema_version,
12
+ };
@@ -0,0 +1,29 @@
1
+ # Logifos Native Extension
2
+ #
3
+ # The MRI tier of logifos-ruby: a cdylib defining Logifos::Native through
4
+ # magnus, binding the engine's logifos-ffi transport directly.
5
+
6
+ [package]
7
+ name = "logifos_native"
8
+ version = "0.1.0"
9
+ edition = "2021"
10
+ rust-version = "1.75"
11
+ publish = false
12
+
13
+ [lib]
14
+ crate-type = ["cdylib"]
15
+
16
+ [dependencies]
17
+ # rb-sys for Ruby C API - WITHOUT link-ruby for dynamic extension
18
+ rb-sys = { version = "0.9.124", features = ["global-allocator"] }
19
+
20
+ # magnus for Ruby bindings
21
+ magnus = { version = "0.9" }
22
+
23
+ # The engine transport with its magnus bindings, pinned to the engine
24
+ # revision the gem ships; bumped with the release train so platform gems
25
+ # stay byte-reproducible.
26
+ logifos-ffi = { git = "https://github.com/logifos/logifos-rs", rev = "e24a601f548d5b40f00e80b679664e30487c168a", features = ["ruby"] }
27
+
28
+ [profile.release]
29
+ lto = "off"
@@ -0,0 +1,9 @@
1
+ fn main() {
2
+ // MRI loadables on macOS resolve ruby symbols from the host process
3
+ // at load time; cargo's cdylib link defaults to failing on undefined
4
+ // symbols, so the flag must come from the top-level package.
5
+ if cfg!(target_os = "macos") {
6
+ println!("cargo:rustc-link-arg=-Wl,-undefined,dynamic_lookup");
7
+ }
8
+ println!("cargo:rerun-if-changed=build.rs");
9
+ }
@@ -0,0 +1,55 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The Rust extension targets the CRuby C API through rb_sys/magnus. On
4
+ # engines whose C-extension story cannot build it (TruffleRuby compiles C
5
+ # extensions through Sulong and cannot load magnus-produced cdylibs; JRuby
6
+ # has no C-extension support), or when the pure-Ruby backend is requested
7
+ # explicitly, emit a no-op Makefile so the ruby-platform gem installs
8
+ # cleanly. Logifos::Native already falls back to the pure-Ruby parser at
9
+ # runtime (lib/logifos/native.rb rescues LoadError), so skipping the
10
+ # build here is sufficient — see
11
+ # https://github.com/logifos/logifos-ruby/issues/23
12
+ if ENV["LOGIFOS_PURE_RUBY"] == "1" || ENV["LOGIFOS_NATIVE"] == "0" ||
13
+ RUBY_ENGINE != "ruby"
14
+ # No mkmf yet (and not wanted on engines without a C toolchain): the
15
+ # hand-written no-op Makefile is the whole contract.
16
+ File.write("Makefile", <<~MAKEFILE)
17
+ all:
18
+ install:
19
+ clean:
20
+ MAKEFILE
21
+ warn "logifos: skipping the Rust extension on #{RUBY_ENGINE} " \
22
+ "(pure-Ruby backend will be used)"
23
+ exit 0
24
+ end
25
+
26
+ require "mkmf"
27
+ require "rb_sys/mkmf"
28
+
29
+ create_rust_makefile("logifos/logifos_native") do |r|
30
+ # Create debug builds in dev, release in production
31
+ r.profile = ENV.fetch("RB_SYS_CARGO_PROFILE", :dev).to_sym
32
+
33
+ # Persist RubyInstaller's headers into Make's later Cargo subprocess.
34
+ if RUBY_PLATFORM.include?("mingw") && ENV.key?("RI_DEVKIT") && ENV.key?("MSYSTEM_PREFIX")
35
+ sysroot = ENV.fetch("RI_DEVKIT").tr("\\", "/") + ENV.fetch("MSYSTEM_PREFIX")
36
+ r.env["BINDGEN_EXTRA_CLANG_ARGS"] = ENV.fetch("BINDGEN_EXTRA_CLANG_ARGS") do
37
+ "--target=x86_64-pc-windows-gnu --sysroot=#{sysroot} " \
38
+ "-D__AVX512VLFP16INTRIN_H -D__AVX512FP16INTRIN_H"
39
+ end
40
+ end
41
+
42
+ # cargo rustc builds dependency cdylibs verbatim, and logifos ships
43
+ # a cdylib crate-type (the ffi tier). On macOS every dylib in the
44
+ # build resolves ruby symbols from the host process at load time, so
45
+ # every link must tolerate undefined symbols. (extconf runs as a
46
+ # subprocess, so this must be baked into the Makefile — env changes
47
+ # here would not survive it.)
48
+ r.extra_rustflags = %w[-C link-arg=-Wl,-undefined,dynamic_lookup] if RbConfig::CONFIG["host_os"].include?("darwin")
49
+
50
+ # Enable stable API compiled fallback for ruby-head and older Ruby versions
51
+ r.use_stable_api_compiled_fallback = true
52
+
53
+ # Force install rust toolchain if needed (can also set RB_SYS_FORCE_INSTALL_RUST_TOOLCHAIN=true)
54
+ r.force_install_rust_toolchain = false
55
+ end
@@ -0,0 +1,21 @@
1
+ //! Logifos Native Extension
2
+ //!
3
+ //! The MRI tier of logifos-ruby: it compiles the engine's logifos-ffi
4
+ //! transport with its magnus bindings enabled.
5
+
6
+ use magnus::{Error, Ruby};
7
+
8
+ /// Initialize the Logifos native extension
9
+ ///
10
+ /// This sets up Logifos::Native with the transport queries and the v1
11
+ /// request from logifos-rs.
12
+ #[magnus::init]
13
+ fn init(ruby: &Ruby) -> Result<(), Error> {
14
+ // The native surface is Ractor-callable: a request is bytes in, bytes
15
+ // out, through per-call owned buffers. The engine keeps no mutable
16
+ // global state (its statics are immutable tables) and no Ruby object
17
+ // is retained across a call.
18
+ unsafe { rb_sys::rb_ext_ractor_safe(true) };
19
+
20
+ logifos_ffi::ruby::init(ruby)
21
+ }
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Logifos
4
+ # Base for recoverable runtime failures.
5
+ class Error < StandardError; end
6
+
7
+ # The explicitly requested library could not be loaded.
8
+ class LibraryError < Error; end
9
+
10
+ # The library does not support the required wire versions or features.
11
+ class CompatibilityError < LibraryError; end
12
+
13
+ # A library returned an invalid response envelope.
14
+ class ProtocolError < Error; end
15
+
16
+ # A native call failed before producing a JSON response.
17
+ class TransportError < Error
18
+ CODES = { 1 => "INVALID_REQUEST", 2 => "ALLOCATION_FAILED", 3 => "INTERNAL_ERROR" }.freeze
19
+
20
+ attr_reader :status, :code
21
+
22
+ def initialize(status)
23
+ @status = status
24
+ @code = CODES.fetch(status, "UNKNOWN_TRANSPORT_STATUS")
25
+ super("native transport failed: #{@code} (#{status})")
26
+ end
27
+ end
28
+
29
+ # A typed refusal returned by the core; diagnostic text is not a stable API.
30
+ class EngineError < Error
31
+ attr_reader :code, :path, :stage
32
+
33
+ def initialize(code:, message:, path:, stage:)
34
+ @code = code
35
+ @path = path
36
+ @stage = stage
37
+ super(message)
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Logifos
4
+ # The MRI tier: the platform gem's compiled extension defines the
5
+ # transport queries and `request_v1` below through magnus (logifos-rs's
6
+ # logifos-ffi `ruby` feature); this Ruby module only reports availability
7
+ # and triggers the lazy load. The ffi-gem cdylib tier (NativeLibrary)
8
+ # serves when the extension is absent.
9
+ module Native
10
+ @native_state = :pending
11
+
12
+ class << self
13
+ # First call performs the lazy bundle load: binding the statically
14
+ # linked engine costs on startup, and `require "logifos"` must stay
15
+ # cheap for consumers that only configure up front.
16
+ def available?
17
+ native_load!
18
+ extension_loaded?
19
+ end
20
+
21
+ def extension_loaded?
22
+ native_load! == :loaded
23
+ end
24
+
25
+ private
26
+
27
+ def native_load!
28
+ return @native_state unless @native_state == :pending
29
+
30
+ @native_state = load_extension
31
+ end
32
+
33
+ # rake-compiler installs the extension under the running Ruby's
34
+ # version directory; a source install puts it on the load path flat.
35
+ def load_extension
36
+ require "logifos/#{RUBY_VERSION.split(".").take(2).join(".")}/logifos_native"
37
+ :loaded
38
+ rescue LoadError
39
+ begin
40
+ require "logifos/logifos_native"
41
+ :loaded
42
+ rescue LoadError
43
+ :unavailable
44
+ end
45
+ end
46
+ end
47
+ end
48
+ end
@@ -0,0 +1,140 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ffi"
4
+ require_relative "errors"
5
+
6
+ module Logifos
7
+ # The ABI's owned, length-delimited response. Only its allocator may free it.
8
+ class NativeBuffer < FFI::Struct
9
+ layout :ptr, :pointer, :len, :size_t
10
+ end
11
+
12
+ # One loaded engine serves a runtime: the MRI extension's Logifos::Native
13
+ # when the platform gem or a source install compiled it (no library_path),
14
+ # else the ffi-gem cdylib tier bound by path. Each tier owns the allocation
15
+ # and free function for its calls.
16
+ class NativeLibrary
17
+ QUERY_TYPES = { abi_version: :uint32, schema_version: :uint32, features: :uint64, engine_version: :string }.freeze
18
+ # The transport's refusal of its arguments; the extension tier reports
19
+ # it as a nil response.
20
+ INVALID_REQUEST = 1
21
+ VENDORED = %w[liblogifos.dylib liblogifos.so logifos.dll].freeze
22
+
23
+ attr_reader :library_path, :abi_version, :schema_version, :engine_version, :features
24
+
25
+ # An explicit library_path must name a readable library by absolute path;
26
+ # a located one is this gem's own search result and is trusted.
27
+ def initialize(required_features:, library_path: nil, located: false)
28
+ @library_path = library_path&.dup&.freeze
29
+ validate_path(library_path) if library_path && !located
30
+ @api = bind_library if library_path
31
+ @abi_version, @schema_version, @engine_version, @features = queries
32
+ check_compatibility(required_features)
33
+ rescue LoadError, FFI::NotFoundError => e
34
+ raise LibraryError, "cannot load requested native library: #{e.message}"
35
+ end
36
+
37
+ # Search order: explicit override, gem-vendored cdylib next to the gem's
38
+ # lib (lib/logifos/native, where the cross-gem build puts it), then the
39
+ # system linker path — the parsanol-ruby ffi tier's order.
40
+ def self.locate_library(lib = File.expand_path("..", __dir__))
41
+ candidates(lib).find { |candidate| File.file?(candidate) || loadable?(candidate) }
42
+ end
43
+
44
+ def self.candidates(lib)
45
+ override = ENV.fetch("LOGIFOS_FFI_LIB", nil)
46
+ override = nil if override && override.empty?
47
+ vendored = VENDORED.filter_map do |name|
48
+ path = File.expand_path(name, File.join(lib, "logifos", "native"))
49
+ path if File.file?(path)
50
+ end
51
+ [override, *vendored, "logifos"].compact
52
+ end
53
+
54
+ def self.loadable?(candidate)
55
+ FFI::DynamicLibrary.open(candidate, FFI::DynamicLibrary::RTLD_NOW)
56
+ true
57
+ rescue LoadError, StandardError
58
+ false
59
+ end
60
+
61
+ def exchange(bytes)
62
+ raise ArgumentError, "request bytes must be a String" unless bytes.is_a?(String)
63
+
64
+ bytes = bytes.b
65
+ input = nil
66
+ return request_through_extension(bytes) unless @api
67
+
68
+ input = FFI::MemoryPointer.new(:uint8, [bytes.bytesize, 1].max)
69
+ input.put_bytes(0, bytes)
70
+ exchange_buffer(input, bytes.bytesize)
71
+ ensure
72
+ input&.free
73
+ end
74
+
75
+ private
76
+
77
+ def queries
78
+ if @api
79
+ [@api.logifos_abi_version, @api.logifos_schema_version, @api.logifos_engine_version.dup.freeze,
80
+ @api.logifos_features]
81
+ else
82
+ [Native.abi_version, Native.schema_version, Native.engine_version.dup.freeze, Native.features]
83
+ end
84
+ end
85
+
86
+ def request_through_extension(bytes)
87
+ response = Native.request_v1(bytes)
88
+ raise TransportError, INVALID_REQUEST unless response
89
+
90
+ response.dup.force_encoding(Encoding::UTF_8)
91
+ end
92
+
93
+ def validate_path(path)
94
+ return if path.is_a?(String) && File.absolute_path(path) == path && File.file?(path) && File.readable?(path)
95
+
96
+ raise LibraryError, "library_path must name a readable library by absolute path"
97
+ end
98
+
99
+ def bind_library
100
+ path = library_path
101
+ Module.new do
102
+ extend FFI::Library
103
+
104
+ ffi_lib path
105
+ QUERY_TYPES.each do |name, type|
106
+ attach_function :"logifos_#{name}", [], type
107
+ end
108
+ attach_function :logifos_request_v1, %i[pointer size_t pointer], :uint32
109
+ attach_function :logifos_buffer_free_v1, [NativeBuffer.by_value], :void
110
+ end
111
+ end
112
+
113
+ def check_compatibility(required)
114
+ raise CompatibilityError, "unsupported ABI version: #{abi_version}" unless abi_version == 1
115
+ raise CompatibilityError, "unsupported schema version: #{schema_version}" unless schema_version == 1
116
+ return if features & required == required
117
+
118
+ raise CompatibilityError, "native library lacks required features: #{required}"
119
+ end
120
+
121
+ def release(buffer)
122
+ @api.logifos_buffer_free_v1(buffer)
123
+ buffer[:ptr] = FFI::Pointer::NULL
124
+ buffer[:len] = 0
125
+ end
126
+
127
+ def exchange_buffer(input, length)
128
+ buffer = NativeBuffer.new
129
+ begin
130
+ status = @api.logifos_request_v1(input, length, buffer)
131
+ raise TransportError, status unless status.zero?
132
+ raise ProtocolError, "native library returned a null response" if buffer[:ptr].null?
133
+
134
+ buffer[:ptr].read_string(buffer[:len]).force_encoding(Encoding::UTF_8)
135
+ ensure
136
+ release(buffer)
137
+ end
138
+ end
139
+ end
140
+ end