Module: Persist

Defined in:
lib/rbbt/persist.rb,
lib/rbbt/persist/tsv.rb

Constant Summary collapse

MEMORY =
{}
MAX_FILE_LENGTH =
150
TRUE_STRINGS =
Set.new ["true", "True", "TRUE", "t", "T", "1", "yes", "Yes", "YES", "y", "Y", "ON", "on"]
TC_CONNECTIONS =
{}

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.cachedirObject

Returns the value of attribute cachedir.



10
11
12
# File 'lib/rbbt/persist.rb', line 10

def cachedir
  @cachedir
end

Class Method Details

.is_persisted?(path, persist_options = {}) ⇒ Boolean

Returns:

  • (Boolean)


28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/rbbt/persist.rb', line 28

def self.is_persisted?(path, persist_options = {})
  return false if not Open.exists? path
  return false if TrueClass === persist_options[:update]

  check = persist_options[:check]
  if not check.nil?
    if Array === check
      return false if check.select{|file| newer? path, file}.any?
   else
      return false if newer? path, check
   end
  end

  return true
end

.load_file(path, type) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/rbbt/persist.rb', line 79

def self.load_file(path, type)
  case (type || "nil").to_sym
  when :nil
    nil
  when :boolean
    TRUE_STRINGS.include? Open.read(path).chomp.strip
  when :annotations
    Annotated.load_tsv TSV.open(path)
  when :tsv
    TSV.open(path)
  when :marshal_tsv
    TSV.setup(Marshal.load(Open.open(path)))
  when :fwt
    FixWidthTable.get(path) 
  when :string, :text
    Open.read(path)
  when :binary
    f = File.open(path, 'rb')
    res = f.read
    f.close
    res.force_encoding("ASCII-8BIT") if res.respond_to? :force_encoding
    res
  when :array
    res = Open.read(path).split("\n", -1)
    res.pop
    res
  when :marshal
    Marshal.load(Open.open(path))
  when :yaml
    YAML.load(Open.open(path))
  when :float
    Open.read(path).to_f
  when :integer
    Open.read(path).to_i
  else
    raise "Unknown persistence: #{ type }"
  end
end

.newer?(path, file) ⇒ Boolean

Returns:

  • (Boolean)


22
23
24
25
26
# File 'lib/rbbt/persist.rb', line 22

def self.newer?(path, file)
  return true if not Open.exists? file
  return true if File.mtime(path) < File.mtime(file)
  return false
end

.open_tokyocabinet(path, write, serializer = nil, tokyocabinet_class = TokyoCabinet::HDB) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/rbbt/persist/tsv.rb', line 10

def self.open_tokyocabinet(path, write, serializer = nil, tokyocabinet_class = TokyoCabinet::HDB)
  write = true if not File.exists?(path)

  tokyocabinet_class = TokyoCabinet::HDB if tokyocabinet_class == "HDB"
  tokyocabinet_class = TokyoCabinet::BDB if tokyocabinet_class == "BDB"

  flags = (write ? tokyocabinet_class::OWRITER | tokyocabinet_class::OCREAT : tokyocabinet_class::OREADER)

  FileUtils.mkdir_p File.dirname(path) unless File.exists?(File.dirname(path))

  database = TC_CONNECTIONS[path] ||= tokyocabinet_class.new
  database.close

  if !database.open(path, flags)
    ecode = database.ecode
    raise "Open error: #{database.errmsg(ecode)}. Trying to open file #{path}"
  end

  if not database.respond_to? :old_close
    class << database
      attr_accessor :writable, :closed, :persistence_path, :tokyocabinet_class

      def prefix(key)
        range(key, 1, key + 255.chr, 1)
      end

      def closed?
        @closed
      end

      alias old_close close
      def close
        @closed = true
        old_close
      end

      def read(force = false)
        return if not write? and not closed and not force
        self.close
        if !self.open(@persistence_path, tokyocabinet_class::OREADER)
          ecode = self.ecode
          raise "Open error: #{self.errmsg(ecode)}. Trying to open file #{@persistence_path}"
        end
        @writable = false
        @closed = false
        self
      end

      def write(force = true)
        return if write? and not closed and not force
        self.close

        if !self.open(@persistence_path, tokyocabinet_class::OWRITER)
          ecode = self.ecode
          raise "Open error: #{self.errmsg(ecode)}. Trying to open file #{@persistence_path}"
        end

        @writable = true
        @closed = false
        self
      end

      def write?
        @writable
      end

      def collect
        res = []
        each do |key, value|
          res << if block_given?
                   yield key, value
          else
            [key, value]
          end
        end
        res
      end

      def delete(key)
        out(key)
      end

      def write_and_read
        lock_filename = Persist.persistence_path(persistence_path, {:dir => TSV.lock_dir})
        Misc.lock(lock_filename) do
          write if @closed or not write?
          res = begin
                  yield
                ensure
                  read
                end
          res
        end
      end


      def write_and_close
        lock_filename = Persist.persistence_path(persistence_path, {:dir => TSV.lock_dir})
        Misc.lock(lock_filename) do
          write if @closed or not write?
          res = begin
                  yield
                ensure
                  close
                end
          res
        end
      end

      def read_and_close
        read if @closed or write?
        res = begin
                yield
              ensure
                close
              end
        res
      end

      def merge!(hash)
        hash.each do |key,values|
          self[key] = values
        end
      end

      if instance_methods.include? "range"
        alias old_range range

        def range(*args)
          keys = old_range(*args)
          keys - TSV::ENTRY_KEYS
        end
      end
    end
  end

  database.persistence_path ||= path
  database.tokyocabinet_class = tokyocabinet_class

  unless serializer == :clean
    TSV.setup database
    database.serializer = serializer || database.serializer
    database.fields
  end

  database
end

.persist(name, type = nil, persist_options = {}) ⇒ Object



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/rbbt/persist.rb', line 161

def self.persist(name, type = nil, persist_options = {})
  type ||= :marshal
  persist_options = Misc.add_defaults persist_options, :persist => true
  other_options = Misc.process_options persist_options, :other

  if persist_options[:persist]
    path = persistence_path(name, persist_options, other_options || {})

    case 
    when type.to_sym === :memory
      Persist::MEMORY[path] ||= yield

    when (type.to_sym == :annotations and persist_options.include? :annotation_repo)

      repo = persist_options[:annotation_repo]

      keys = nil
      subkey = name + ":"

      if String === repo
        repo = Persist.open_tokyocabinet(repo, false, :list, "BDB")
        repo.read_and_close do
          keys = repo.range subkey + 0.chr, true, subkey + 254.chr, true
        end
        repo.close
      else
        repo.read_and_close do
          keys = repo.range subkey + 0.chr, true, subkey + 254.chr, true
        end
      end

      case
      when (keys.length == 1 and keys.first == subkey + 'NIL')
        nil
      when (keys.length == 1 and keys.first == subkey + 'EMPTY')
        []
      when (keys.length == 1 and keys.first =~ /:SINGLE$/)
        key = keys.first
        values = repo.read_and_close do
          repo[key]
        end
        Annotated.load_tsv_values(key, values, "literal", "annotation_types", "JSON")
      when (keys.any? and not keys.first =~ /ANNOTATED_DOUBLE_ARRAY/)
        repo.read_and_close do
          keys.sort_by{|k| k.split(":").last.to_i}.collect{|key|
            v = repo[key]
            Annotated.load_tsv_values(key, v, "literal", "annotation_types", "JSON")
          }
        end
      when (keys.any? and keys.first =~ /ANNOTATED_DOUBLE_ARRAY/)
        repo.read_and_close do

          res = keys.sort_by{|k| k.split(":").last.to_i}.collect{|key|
            v = repo[key]
            Annotated.load_tsv_values(key, v, "literal", "annotation_types", "JSON")
          }

          res.first.annotate res
          res.extend AnnotatedArray

          res
        end
      else
        entities = yield

        repo.write_and_close do 
          case
          when entities.nil?
            repo[subkey + "NIL"] = nil
          when entities.empty?
            repo[subkey + "EMPTY"] = nil
          when (not Array === entities or (AnnotatedArray === entities and not Array === entities.first))
            tsv_values = entities.tsv_values("literal", "annotation_types", "JSON") 
            repo[subkey + entities.id << ":" << "SINGLE"] = tsv_values
          when (not Array === entities or (AnnotatedArray === entities and AnnotatedArray === entities.first))
            entities.each_with_index do |e,i|
              next if e.nil?
              tsv_values = e.tsv_values("literal", "annotation_types", "JSON") 
              repo[subkey + e.id << ":ANNOTATED_DOUBLE_ARRAY:" << i.to_s] = tsv_values
            end
          else
            entities.each_with_index do |e,i|
              next if e.nil?
              tsv_values = e.tsv_values("literal", "annotation_types", "JSON") 
              repo[subkey + e.id << ":" << i.to_s] = tsv_values
            end
          end
        end

        entities
      end

    else

      if is_persisted?(path, persist_options)
        Log.low "Persist up-to-date: #{ path } - #{persist_options.inspect[0..100]}"
        return nil if persist_options[:no_load]
        return load_file(path, type) 
      else
        Log.medium "Persist create: #{ path } - #{persist_options.inspect[0..100]}"
      end

      begin
        res = yield
        Misc.lock(path) do
          save_file(path, type, res)
        end
        res
      rescue
        Log.high "Error in persist. #{Open.exists?(path) ? "Erasing '#{ path }'" : ""}"
        FileUtils.rm path if Open.exists? path 
        raise $!
      end
    end

  else
    yield
  end
end

.persist_tsv(source, filename, options = {}, persist_options = {}) ⇒ Object



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/rbbt/persist/tsv.rb', line 158

def self.persist_tsv(source, filename, options = {}, persist_options = {})
  persist_options[:prefix] ||= "TSV"

  data = case
         when persist_options[:data]
           persist_options[:data]
         when persist_options[:persist]

           filename ||= case
                        when Path === source
                          source
                        when (source.respond_to?(:filename) and source.filename)
                          source.filename
                        when source.respond_to?(:cmd)
                          "CMD-#{Misc.digest(source.cmd)}"
                        when TSV === source
                          "TSV[#{Misc.digest Misc.fingerprint(source)}]"
                        else
                          source.object_id.to_s
                        end

           filename ||= source.object_id.to_s

           path = persistence_path(filename, persist_options, options)

           if is_persisted? path and not persist_options[:update]
             Log.debug "TSV persistence up-to-date: #{ path }"
             lock_filename = Persist.persistence_path(path, {:dir => Rbbt.tmp.tsv_open_locks.find})
             return Misc.lock(lock_filename) do open_tokyocabinet(path, false, nil, persist_options[:engine] || TokyoCabinet::HDB); end
           else
             Log.medium "TSV persistence creating: #{ path }"
           end

           FileUtils.rm path if File.exists? path

           data = open_tokyocabinet(path, true, persist_options[:serializer], persist_options[:engine] || TokyoCabinet::HDB)
           data.serializer = :type if TSV === data and data.serializer.nil?

           data.close

           data
         else
           {}
         end

  begin
    if data.respond_to? :persistence_path and data != persist_options[:data]
      data.write_and_close do
        yield data
      end
    else
      yield data
    end
  rescue Exception
    FileUtils.rm path if path and File.exists? path
    raise $!
  ensure
    begin
      data.close if data.respond_to? :close
    rescue
      raise $!
    end
  end

  data.read if data.respond_to? :read and ((data.respond_to?(:write?) and data.write?) or (data.respond_to?(:closed?) and data.closed?))


  data
end

.persistence_path(file, persist_options = {}, options = {}) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/rbbt/persist.rb', line 44

def self.persistence_path(file, persist_options = {}, options = {})
  persistence_file = Misc.process_options persist_options, :file
  return persistence_file unless persistence_file.nil?

  prefix = Misc.process_options persist_options, :prefix

  if prefix.nil?
    perfile = file.gsub(/\//, '>') 
  else
    perfile = prefix.to_s + ":" + file.gsub(/\//, '>') 
  end

  if options.include? :filters
    options[:filters].each do |match,value|
      perfile = perfile + "&F[#{match}=#{Misc.digest(value.inspect)}]"
    end
  end

  persistence_dir = Misc.process_options(persist_options, :dir) || Persist.cachedir
  Path.setup(persistence_dir) unless Path === persistence_dir

  filename = perfile.gsub(/\s/,'_').gsub(/\//,'>')
  clean_options = options
  clean_options.delete :unnamed
  clean_options.delete "unnamed"

  filename = filename[0..MAX_FILE_LENGTH] << Misc.digest(filename[MAX_FILE_LENGTH+1..-1]) if filename.length > MAX_FILE_LENGTH + 10

  options_md5 = Misc.hash2md5 clean_options
  filename  << ":" << options_md5 unless options_md5.empty?

  persistence_dir[filename].find
end

.save_file(path, type, content) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/rbbt/persist.rb', line 118

def self.save_file(path, type, content)

  return if content.nil?
  
  case (type || "nil").to_sym
  when :nil
    nil
  when :boolean
    Open.write(path, content ? "true" : "false")
  when :fwt
    content.file.seek 0
    Open.write(path, content.file.read)
  when :tsv
    Open.write(path, content.to_s)
  when :annotations
    Open.write(path, Annotated.tsv(content, :all).to_s)
  when :string, :text
    Open.write(path, content)
  when :binary
    content.force_encoding("ASCII-8BIT") if content.respond_to? :force_encoding
    f = File.open(path, 'wb')
    f.puts content
    f.close
    content
  when :array
    if content.empty?
      Open.write(path, "")
    else
      Open.write(path, content * "\n" + "\n")
    end
  when :marshal_tsv
    Open.write(path, Marshal.dump(content.dup))
  when :marshal
    Open.write(path, Marshal.dump(content))
  when :yaml
    Open.write(path, YAML.dump(content))
  when :float, :integer, :tsv
    Open.write(path, content.to_s)
  else
    raise "Unknown persistence: #{ type }"
  end
end