Module: FinchAPI::Util Private

Defined in:
lib/finch-api/util.rb

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Defined Under Namespace

Classes: ReadIOAdapter

Constant Summary collapse

OMIT =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Use this to indicate that a value should be explicitly removed from a data

structure when using `FinchAPI::Util.deep_merge`.

e.g. merging `{a: 1}` and `{a: OMIT}` should produce `{}`, where merging
`{a: 1}` and `{}` would produce `{a: 1}`.
Object.new.freeze

Class Method Summary collapse

Class Method Details

.archString

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (String)


17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/finch-api/util.rb', line 17

def arch
  case (arch = RbConfig::CONFIG["arch"])&.downcase
  in nil
    "unknown"
  in /aarch64|arm64/
    "arm64"
  in /x86_64/
    "x64"
  in /arm/
    "arm"
  else
    "other:#{arch}"
  end
end

.chain_fused(enum, &blk) {|| ... } ⇒ Enumerable

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • enum (Enumerable, nil)
  • blk (Proc)

Yield Parameters:

  • (Enumerator::Yielder)

Returns:

  • (Enumerable)


639
640
641
642
# File 'lib/finch-api/util.rb', line 639

def chain_fused(enum, &blk)
  iter = Enumerator.new { blk.call(_1) }
  fused_enum(iter) { close_fused!(enum) }
end

.close_fused!(enum) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • enum (Enumerable, nil)


624
625
626
627
628
629
630
# File 'lib/finch-api/util.rb', line 624

def close_fused!(enum)
  return unless enum.is_a?(Enumerator)

  # rubocop:disable Lint/UnreachableLoop
  enum.rewind.each { break }
  # rubocop:enable Lint/UnreachableLoop
end

.coerce_boolean(input) ⇒ Boolean, Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • input (Object)

Returns:

  • (Boolean, Object)


75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/finch-api/util.rb', line 75

def coerce_boolean(input)
  case input.is_a?(String) ? input.downcase : input
  in Numeric
    input.nonzero?
  in "true"
    true
  in "false"
    false
  else
    input
  end
end

.coerce_boolean!(input) ⇒ Boolean?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • input (Object)

Returns:

  • (Boolean, nil)

Raises:

  • (ArgumentError)


94
95
96
97
98
99
100
101
# File 'lib/finch-api/util.rb', line 94

def coerce_boolean!(input)
  case coerce_boolean(input)
  in true | false | nil => coerced
    coerced
  else
    raise ArgumentError.new("Unable to coerce #{input.inspect} into boolean value")
  end
end

.coerce_float(input) ⇒ Float, Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • input (Object)

Returns:

  • (Float, Object)


124
125
126
127
128
129
130
131
132
133
# File 'lib/finch-api/util.rb', line 124

def coerce_float(input)
  case input
  in true
    1.0
  in false
    0.0
  else
    Float(input, exception: false) || input
  end
end

.coerce_hash(input) ⇒ Hash{Object=>Object}, Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • input (Object)

Returns:

  • (Hash{Object=>Object}, Object)


140
141
142
143
144
145
146
147
# File 'lib/finch-api/util.rb', line 140

def coerce_hash(input)
  case input
  in NilClass | Array | Set | Enumerator
    input
  else
    input.respond_to?(:to_h) ? input.to_h : input
  end
end

.coerce_integer(input) ⇒ Integer, Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • input (Object)

Returns:

  • (Integer, Object)


108
109
110
111
112
113
114
115
116
117
# File 'lib/finch-api/util.rb', line 108

def coerce_integer(input)
  case input
  in true
    1
  in false
    0
  else
    Integer(input, exception: false) || input
  end
end

.decode_content(headers, stream:, suppress_error: false) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • headers (Hash{String=>String}, Net::HTTPHeader)
  • stream (Enumerable)
  • suppress_error (Boolean) (defaults to: false)

Returns:

  • (Object)

Raises:

  • (JSON::ParserError)


561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
# File 'lib/finch-api/util.rb', line 561

def decode_content(headers, stream:, suppress_error: false)
  case headers["content-type"]
  in %r{^application/(?:vnd\.api\+)?json}
    json = stream.to_a.join
    begin
      JSON.parse(json, symbolize_names: true)
    rescue JSON::ParserError => e
      raise e unless suppress_error
      json
    end
  in %r{^application/(?:x-)?jsonl}
    lines = decode_lines(stream)
    chain_fused(lines) do |y|
      lines.each { y << JSON.parse(_1, symbolize_names: true) }
    end
  in %r{^text/event-stream}
    lines = decode_lines(stream)
    decode_sse(lines)
  in %r{^text/}
    stream.to_a.join
  else
    # TODO: parsing other response types
    StringIO.new(stream.to_a.join)
  end
end

.decode_lines(enum) ⇒ Enumerable

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • enum (Enumerable)

Returns:

  • (Enumerable)


651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
# File 'lib/finch-api/util.rb', line 651

def decode_lines(enum)
  re = /(\r\n|\r|\n)/
  buffer = String.new.b
  cr_seen = nil

  chain_fused(enum) do |y|
    enum.each do |row|
      offset = buffer.bytesize
      buffer << row
      while (match = re.match(buffer, cr_seen&.to_i || offset))
        case [match.captures.first, cr_seen]
        in ["\r", nil]
          cr_seen = match.end(1)
          next
        in ["\r" | "\r\n", Integer]
          y << buffer.slice!(..(cr_seen.pred))
        else
          y << buffer.slice!(..(match.end(1).pred))
        end
        offset = 0
        cr_seen = nil
      end
    end

    y << buffer.slice!(..(cr_seen.pred)) unless cr_seen.nil?
    y << buffer unless buffer.empty?
  end
end

.decode_query(query) ⇒ Hash{String=>Array<String>}

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • query (String, nil)

Returns:

  • (Hash{String=>Array<String>})


269
270
271
# File 'lib/finch-api/util.rb', line 269

def decode_query(query)
  CGI.parse(query.to_s)
end

.decode_sse(lines) ⇒ Hash{Symbol=>Object}

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

html.spec.whatwg.org/multipage/server-sent-events.html#parsing-an-event-stream

Parameters:

  • lines (Enumerable)

Returns:

  • (Hash{Symbol=>Object})


687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
# File 'lib/finch-api/util.rb', line 687

def decode_sse(lines)
  # rubocop:disable Metrics/BlockLength
  chain_fused(lines) do |y|
    blank = {event: nil, data: nil, id: nil, retry: nil}
    current = {}

    lines.each do |line|
      case line.sub(/\R$/, "")
      in ""
        next if current.empty?
        y << {**blank, **current}
        current = {}
      in /^:/
        next
      in /^([^:]+):\s?(.*)$/
        field, value = Regexp.last_match.captures
        case field
        in "event"
          current.merge!(event: value)
        in "data"
          (current[:data] ||= String.new.b) << (value << "\n")
        in "id" unless value.include?("\0")
          current.merge!(id: value)
        in "retry" if /^\d+$/ =~ value
          current.merge!(retry: Integer(value))
        else
        end
      else
      end
    end
    # rubocop:enable Metrics/BlockLength

    y << {**blank, **current} unless current.empty?
  end
end

.deep_merge(*values, sentinel: nil, concat: false) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Recursively merge one hash with another. If the values at a given key are not

both hashes, just take the new value.

Parameters:

  • values (Array<Object>)
  • sentinel (Object, nil) (defaults to: nil)

    the value to return if no values are provided.

  • concat (Boolean) (defaults to: false)

    whether to merge sequences by concatenation.

Returns:

  • (Object)


193
194
195
196
197
198
199
200
201
202
# File 'lib/finch-api/util.rb', line 193

def deep_merge(*values, sentinel: nil, concat: false)
  case values
  in [value, *values]
    values.reduce(value) do |acc, val|
      deep_merge_lr(acc, val, concat: concat)
    end
  else
    sentinel
  end
end

.dig(data, pick, sentinel = nil, &blk) ⇒ Object?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • data (Hash{Symbol=>Object}, Array<Object>, Object)
  • pick (Symbol, Integer, Array<Symbol, Integer>, nil)
  • sentinel (Object, nil) (defaults to: nil)
  • blk (Proc, nil)

Returns:

  • (Object, nil)


212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/finch-api/util.rb', line 212

def dig(data, pick, sentinel = nil, &blk)
  case [data, pick, blk]
  in [_, nil, nil]
    data
  in [Hash, Symbol, _] | [Array, Integer, _]
    blk.nil? ? data.fetch(pick, sentinel) : data.fetch(pick, &blk)
  in [Hash | Array, Array, _]
    pick.reduce(data) do |acc, key|
      case acc
      in Hash if acc.key?(key)
        acc.fetch(key)
      in Array if key.is_a?(Integer) && key < acc.length
        acc[key]
      else
        return blk.nil? ? sentinel : blk.call
      end
    end
  in _
    blk.nil? ? sentinel : blk.call
  end
end

.encode_content(headers, body) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • headers (Hash{String=>String})
  • body (Object)

Returns:

  • (Object)


535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
# File 'lib/finch-api/util.rb', line 535

def encode_content(headers, body)
  content_type = headers["content-type"]
  case [content_type, body]
  in [%r{^application/(?:vnd\.api\+)?json}, Hash | Array]
    [headers, JSON.fast_generate(body)]
  in [%r{^application/(?:x-)?jsonl}, Enumerable]
    [headers, body.lazy.map { JSON.fast_generate(_1) }]
  in [%r{^multipart/form-data}, Hash | IO | StringIO]
    boundary, strio = encode_multipart_streaming(body)
    headers = {**headers, "content-type" => "#{content_type}; boundary=#{boundary}"}
    [headers, strio]
  in [_, StringIO]
    [headers, body.string]
  else
    [headers, body]
  end
end

.encode_query(query) ⇒ String?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • query (Hash{String=>Array<String>, String, nil}, nil)

Returns:

  • (String, nil)


278
279
280
# File 'lib/finch-api/util.rb', line 278

def encode_query(query)
  query.to_h.empty? ? nil : URI.encode_www_form(query)
end

.fused_enum(enum, external: false, &close) ⇒ Enumerable

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

doc.rust-lang.org/std/iter/trait.FusedIterator.html

Parameters:

  • enum (Enumerable)
  • external (Boolean) (defaults to: false)
  • close (Proc)

Returns:

  • (Enumerable)


598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# File 'lib/finch-api/util.rb', line 598

def fused_enum(enum, external: false, &close)
  fused = false
  iter = Enumerator.new do |y|
    next if fused

    fused = true
    if external
      loop { y << enum.next }
    else
      enum.each(&y)
    end
  ensure
    close&.call
    close = nil
  end

  iter.define_singleton_method(:rewind) do
    fused = true
    self
  end
  iter
end

.interpolate_path(path) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • path (String, Array<String>)

Returns:

  • (String)


250
251
252
253
254
255
256
257
258
259
260
# File 'lib/finch-api/util.rb', line 250

def interpolate_path(path)
  case path
  in String
    path
  in []
    ""
  in [String, *interpolations]
    encoded = interpolations.map { ERB::Util.url_encode(_1) }
    path.first % encoded
  end
end

.join_parsed_uri(lhs, rhs) ⇒ URI::Generic

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • lhs (Hash{Symbol=>String, Integer, nil})

    .

    @option lhs [String, nil] :scheme

    @option lhs [String, nil] :host

    @option lhs [Integer, nil] :port

    @option lhs [String, nil] :path

    @option lhs [HashString=>Array<String>] :query

  • rhs (Hash{Symbol=>String, Integer, nil})

    .

    @option rhs [String, nil] :scheme

    @option rhs [String, nil] :host

    @option rhs [Integer, nil] :port

    @option rhs [String, nil] :path

    @option rhs [HashString=>Array<String>] :query

Returns:

  • (URI::Generic)


340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
# File 'lib/finch-api/util.rb', line 340

def join_parsed_uri(lhs, rhs)
  base_path, base_query = lhs.fetch_values(:path, :query)
  slashed = base_path.end_with?("/") ? base_path : "#{base_path}/"

  parsed_path, parsed_query = parse_uri(rhs.fetch(:path)).fetch_values(:path, :query)
  override = URI::Generic.build(**rhs.slice(:scheme, :host, :port), path: parsed_path)

  joined = URI.join(URI::Generic.build(lhs.except(:path, :query)), slashed, override)
  query = deep_merge(
    joined.path == base_path ? base_query : {},
    parsed_query,
    rhs[:query].to_h,
    concat: true
  )

  joined.query = encode_query(query)
  joined
end

.monotonic_secsFloat

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (Float)


11
# File 'lib/finch-api/util.rb', line 11

def self.monotonic_secs = Process.clock_gettime(Process::CLOCK_MONOTONIC)

.normalized_headers(*headers) ⇒ Hash{String=>String}

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • headers (Hash{String=>String, Integer, Array<String, Integer, nil>, nil})

Returns:

  • (Hash{String=>String})


366
367
368
369
370
371
372
373
374
375
376
377
# File 'lib/finch-api/util.rb', line 366

def normalized_headers(*headers)
  {}.merge(*headers.compact).to_h do |key, val|
    value =
      case val
      in Array
        val.map { _1.to_s.strip }.join(", ")
      else
        val&.to_s&.strip
      end
    [key.downcase, value]
  end
end

.osString

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns:

  • (String)


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/finch-api/util.rb', line 35

def os
  case (host = RbConfig::CONFIG["host_os"])&.downcase
  in nil
    "Unknown"
  in /linux/
    "Linux"
  in /darwin/
    "MacOS"
  in /freebsd/
    "FreeBSD"
  in /openbsd/
    "OpenBSD"
  in /mswin|mingw|cygwin|ucrt/
    "Windows"
  else
    "Other:#{host}"
  end
end

.parse_uri(url) ⇒ Hash{Symbol=>String, Integer, nil}

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • url (URI::Generic, String)

Returns:

  • (Hash{Symbol=>String, Integer, nil})


289
290
291
292
# File 'lib/finch-api/util.rb', line 289

def parse_uri(url)
  parsed = URI::Generic.component.zip(URI.split(url)).to_h
  {**parsed, query: decode_query(parsed.fetch(:query))}
end

.primitive?(input) ⇒ Boolean

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • input (Object)

Returns:

  • (Boolean)


61
62
63
64
65
66
67
68
# File 'lib/finch-api/util.rb', line 61

def primitive?(input)
  case input
  in true | false | Integer | Float | Symbol | String
    true
  else
    false
  end
end

.string_io(&blk) {|| ... } ⇒ Enumerable

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • blk (Proc)

Yield Parameters:

  • (Enumerator::Yielder)

Returns:

  • (Enumerable)


444
445
446
447
448
449
450
451
452
453
# File 'lib/finch-api/util.rb', line 444

def string_io(&blk)
  Enumerator.new do |y|
    y.define_singleton_method(:write) do
      self << _1.clone
      _1.bytesize
    end

    blk.call(y)
  end
end

.unparse_uri(parsed) ⇒ URI::Generic

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • parsed (Hash{Symbol=>String, Integer, nil})

    .

    @option parsed [String, nil] :scheme

    @option parsed [String, nil] :host

    @option parsed [Integer, nil] :port

    @option parsed [String, nil] :path

    @option parsed [HashString=>Array<String>] :query

Returns:

  • (URI::Generic)


309
310
311
# File 'lib/finch-api/util.rb', line 309

def unparse_uri(parsed)
  URI::Generic.build(**parsed, query: encode_query(parsed.fetch(:query)))
end

.uri_origin(uri) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Parameters:

  • uri (URI::Generic)

Returns:

  • (String)


241
242
243
# File 'lib/finch-api/util.rb', line 241

def uri_origin(uri)
  "#{uri.scheme}://#{uri.host}#{uri.port == uri.default_port ? '' : ":#{uri.port}"}"
end