Class: DTAS::Mlib

Inherits:
Object
  • Object
show all
Includes:
Process
Defined in:
lib/dtas/mlib.rb

Overview

For the DTAS Music Library, based on what MPD uses.

Defined Under Namespace

Classes: Job

Constant Summary collapse

DM_DIR =
-1
DM_IGN =
-2
TAGS =

same capitalization as in mpd

Hash[*(
    %w(Artist ArtistSort
Album AlbumSort
AlbumArtist AlbumArtistSort
Title Track Name
Genre Date Composer Performer Comment Disc
MUSICBRAINZ_ARTISTID MUSICBRAINZ_ALBUMID
MUSICBRAINZ_ALBUMARTISTID
MUSICBRAINZ_TRACKID
MUSICBRAINZ_RELEASETRACKID).map! { |x| [ x.downcase, x ]

Constants included from Process

Process::PIDS

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Process

#dtas_spawn, #env_expand, #env_expand_ary, #env_expand_i, #qx, reaper

Methods included from XS

#xs

Constructor Details

#initialize(db) ⇒ Mlib

Returns a new instance of Mlib.



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
# File 'lib/dtas/mlib.rb', line 39

def initialize(db)
  if String === db
    require 'sequel'
    opts = { single_threaded: true }
    db = "sqlite://#{db}" unless db.include?('://')
    opts[:transaction_mode] = :immediate
    opts[:synchronous] = :off
    opts[:case_sensitive_like] = false # only for 'search'
    db = Sequel.connect(db, opts)
  end
  @db = db
  @pwd = nil
  @follow_outside_symlinks = true
  @follow_inside_symlinks = true
  @root_node = nil
  @tags = TAGS.dup
  @tag_map = nil
  @suffixes = nil
  @work = nil
  @sources = [ # order matters
    (sox = DTAS::Source::Sox.new),
    DTAS::Source::Av.new,
    DTAS::Source::Ff.new,
    DTAS::Source::SplitFX.new(sox),
  ]
end

Instance Attribute Details

Returns the value of attribute follow_inside_symlinks.



18
19
20
# File 'lib/dtas/mlib.rb', line 18

def follow_inside_symlinks
  @follow_inside_symlinks
end

:nodoc:



17
18
19
# File 'lib/dtas/mlib.rb', line 17

def follow_outside_symlinks
  @follow_outside_symlinks
end

#tagsObject

Returns the value of attribute tags.



19
20
21
# File 'lib/dtas/mlib.rb', line 19

def tags
  @tags
end

Instance Method Details

#cd(path) ⇒ Object



304
305
306
307
308
309
310
311
312
# File 'lib/dtas/mlib.rb', line 304

def cd(path)
  prev_wd = @pwd
  Dir.chdir(path)
  cur = @pwd = Dir.pwd.b
  yield
ensure
  Dir.chdir(prev_wd) if cur && prev_wd
  @pwd = prev_wd
end

#count_distinct(tag) ⇒ Object



398
399
400
401
# File 'lib/dtas/mlib.rb', line 398

def count_distinct(tag)
  s = 'SELECT COUNT(DISTINCT(val_id)) FROM comments WHERE tag_id = ?'
  @db.fetch(s, @tag_map[tag]).single_value
end

#count_songsObject



403
404
405
# File 'lib/dtas/mlib.rb', line 403

def count_songs
  @db.fetch('SELECT COUNT(*) FROM nodes WHERE tlen >= 0').single_value
end

#db_playtimeObject



407
408
409
# File 'lib/dtas/mlib.rb', line 407

def db_playtime
  @db.fetch('SELECT SUM(tlen) FROM nodes WHERE tlen >= 0').single_value
end

#dir_vivify(parts, ctime) ⇒ Object



261
262
263
264
265
266
267
268
269
270
# File 'lib/dtas/mlib.rb', line 261

def dir_vivify(parts, ctime)
  synchronize do
    dir = root_node
    last = parts.pop
    parts.each do |name|
      dir = node_ensure(dir[:id], name, DM_DIR)
    end
    node_ensure(dir[:id], last, DM_DIR, ctime)
  end
end

#dump(path, cache, cb) ⇒ Object

returns an array on error



372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
# File 'lib/dtas/mlib.rb', line 372

def dump(path, cache, cb)
  dir = path
  base = nil
  retried = false
  begin
    found = cd(dir) { find_dump_part(root_node, base) }
  rescue Errno::ENOTDIR
    raise if retried || found
    dir, base = File.split(path)
    retried = true
    retry
  end
  return found if Array === found # error

  # success
  load_tags
  if found[:tlen] == DM_DIR
    emit_recurse(found, cache, cb)
  else
    parent = @db[:nodes][id: found[:parent_id]]
    parent or abort "missing parent for #{found.inspect}"
    parent[:dirname] ||= path_of(parent, cache)
    emit_1(found, parent, cache, cb)
  end
end

#emit_1(node, parent, cb) ⇒ Object



448
449
450
451
452
453
454
455
456
# File 'lib/dtas/mlib.rb', line 448

def emit_1(node, parent, cb)
  comments = Hash.new { |h,k| h[k] = [] }
  @db['SELECT c.tag_id, v.val FROM comments c ' \
      'LEFT JOIN vals v ON v.id = c.val_id ' \
      "WHERE c.node_id = #{node[:id]} ORDER BY c.tag_id"].each do |c|
    comments[@tag_rmap[c[:tag_id]]] << c[:val]
  end
  cb.call(parent, node, comments)
end

#emit_recurse(node, cache, cb) ⇒ Object



435
436
437
438
439
440
441
442
443
444
445
446
# File 'lib/dtas/mlib.rb', line 435

def emit_recurse(node, cache, cb)
  node[:dirname] ||= path_of(node, cache)
  @db[:nodes].where(parent_id: node[:id]).order(:name).each do |nd|
    next if nd[:id] == node[:id] # root_node
    case nd[:tlen]
    when DM_DIR then emit_recurse(nd, cache, cb)
    when DM_IGN then next
    else
      emit_1(nd, node, cb)
    end
  end
end

#find(type, what, offset = 0, limit = nil) ⇒ Object

based on the MPD command of the same name, unstable API



496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'lib/dtas/mlib.rb', line 496

def find(type, what, offset = 0, limit = nil)
  load_tags
  type = type.downcase
  q = []
  case type
  when 'any'
    # TODO: add path name matches
    q << 'SELECT DISTINCT(n.id),n.* FROM nodes n ' \
         'LEFT JOIN comments c ON c.node_id = n.id ' \
         'LEFT JOIN vals v ON v.id = c.val_id ' \
         'WHERE v.val = ?'
  when *(@tags.keys)
    tag_id = @tag_map[type]
    q << 'SELECT DISTINCT(n.id),n.* FROM nodes n ' \
         'LEFT JOIN comments c ON c.node_id = n.id ' \
         'LEFT JOIN vals v ON v.id = c.val_id ' \
         'LEFT JOIN tags t ON t.id = c.tag_id ' \
         "WHERE v.val = ? AND t.id = #{tag_id}"
  else
    raise ArgumentError, "invalid type=#{type.inspect}"
  end
  q << 'ORDER by n.parent_id,n.name'
  offset_limit(q, offset, limit)
  @db[q.join(' '), what].each { |node| yield node }
end

#find_dump_part(cur, base) ⇒ Object



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'lib/dtas/mlib.rb', line 351

def find_dump_part(cur, base)
  parts = @pwd.split(%r{/+}n)
  parts.shift # no first part
  parts << base if base
  parts.each do |name|
    if cur = node_lookup(cur[:id], name)
      case cur[:tlen]
      when DM_DIR then next # keep going
      when DM_IGN then return [ :ignored, cur ]
      else # regular audio
        return cur if name.object_id == parts[-1].object_id
        return [ :notdir, cur ]
      end
    else
      return [ :missing, name ]
    end
  end
  cur
end

#ignore(job) ⇒ Object



95
96
97
98
99
# File 'lib/dtas/mlib.rb', line 95

def ignore(job)
  synchronize do
    node_ensure(job.parent_id, job.path, DM_IGN, job.ctime)
  end
end

#init_suffixesObject



73
74
75
76
77
# File 'lib/dtas/mlib.rb', line 73

def init_suffixes
  `sox --help 2>/dev/null` =~ /\nAUDIO FILE FORMATS:\s*([^\n]+)/
  re = $1.split(/\s+/).map! { |x| Regexp.quote(x) }.join('|')
  @suffixes = Regexp.new("\\.(?:#{re}|yml)\\z", Regexp::IGNORECASE)
end

#load_tagsObject



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/dtas/mlib.rb', line 187

def load_tags
  return @tag_map if @tag_map
  tag_map = {}
  tags = @db[:tags]
  @tags.each do |lc, mc|
    unless q = tags[tag: mc]
      q = { tag: mc }
      q[:id] = tags.insert(q)
    end
    tag_map[lc] = q[:id]
  end

  # Xiph tags use "tracknumber" and "discnumber"
  %w(track disc).each do |x|
    tag_id = tag_map[x] and tag_map["#{x}number"] = tag_id
  end
  @tag_rmap = tag_map.invert.freeze
  tag_map.merge!(Hash[*(tag_map.map { |k,v| [-(k.upcase), v] }.flatten!)])
  @tag_map = tag_map.freeze
end

#maybe_blob(path) ⇒ Object



219
220
221
# File 'lib/dtas/mlib.rb', line 219

def maybe_blob(path)
  path.valid_encoding? ? path : Sequel.blob(path)
end

#migrateObject



177
178
179
180
181
182
183
184
185
# File 'lib/dtas/mlib.rb', line 177

def migrate
  require 'sequel'
  Sequel.extension(:migration, :core_extensions) # ugh...
  @db.transaction do
    Sequel::Migrator.apply(@db, "#{File.dirname(__FILE__)}/mlib/migrations")
    root_node # ensure this exists
    load_tags
  end
end

#node_ensure(parent_id, name, tlen, ctime = nil) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/dtas/mlib.rb', line 288

def node_ensure(parent_id, name, tlen, ctime = nil)
  q = { name: maybe_blob(name), parent_id: parent_id }
  if node = @db[:nodes][q]
    node_update_maybe(node, tlen, ctime)
  else
    # brand new node
    node = q.dup
    node[:tlen] = tlen
    node[:ctime] = ctime
    node[:id] = @db[:nodes].insert(node)
  end
  node
rescue => e
  warn "E: #{e.message} (#{e.class}) q=#{q.inspect}"
end

#node_lookup(parent_id, name) ⇒ Object



284
285
286
# File 'lib/dtas/mlib.rb', line 284

def node_lookup(parent_id, name)
  @db[:nodes][name: maybe_blob(name), parent_id: parent_id]
end

#node_update_maybe(node, tlen, ctime) ⇒ Object



272
273
274
275
276
277
278
279
280
281
282
# File 'lib/dtas/mlib.rb', line 272

def node_update_maybe(node, tlen, ctime)
  q = {}
  q[:ctime] = ctime if ctime && ctime != node[:ctime]
  q[:tlen] = tlen if tlen != node[:tlen]
  return if q.empty?
  node_id = node.delete(:id)
  @db[:nodes].where(id: node_id).update(node.merge(q))
  node[:id] = node_id
rescue => e
  warn "E: #{e.message} (#{e.class}) node=#{node.inspect}"
end

#offset_limit(q, offset, limit) ⇒ Object



485
486
487
488
489
490
491
492
493
# File 'lib/dtas/mlib.rb', line 485

def offset_limit(q, offset, limit)
  offset = offset.to_s
  limit = limit.to_s
  if limit =~ %r{\A\d+\z}
    q << "LIMIT #{limit}"
    q << "OFFSET #{offset}" if offset =~ %r{\A\d+\z} && offset != '0'
  end
  q
end

#path_of(node, cache) ⇒ Object



417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
# File 'lib/dtas/mlib.rb', line 417

def path_of(node, cache)
  base = node[:name]
  return '/' if base == '' # root_node
  parent_id = node[:parent_id]
  base += '/' unless node[:tlen] >= 0
  ppath = cache[parent_id] and return -"#{ppath}/#{base}"
  parts = []
  begin
    node = @db[:nodes][id: node[:parent_id]]
    break if node[:id] == node[:parent_id]
    parts.unshift node[:name]
  end while true
  parts.unshift('')
  cache[parent_id] = -(parts.join('/'))
  parts << base
  -(parts.join('/'))
end

#remove_entry(node) ⇒ Object



458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'lib/dtas/mlib.rb', line 458

def remove_entry(node)
  root_id = root_node[:id]
  node_id = node[:id]
  q = { parent_id: node_id }
  nodes = @db[:nodes]
  comments = @db[:comments]

  # remove children, step 1
  nodes.where(q).each do |nd|
    nd_id = nd[:id]
    next if nd_id == root_id
    case nd[:tlen]
    when DM_DIR, DM_IGN
      remove_entry(nd)
    else
      comments.where(node_id: nd_id).delete
    end
  end

  # remove children, step 2
  nodes.where(q).delete

  # finally remove ourselves
  comments.where(node_id: node_id).delete
  nodes.where(id: node_id).delete
end

#root_nodeObject



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'lib/dtas/mlib.rb', line 237

def root_node
  q = @root_node and return q
  # root node always has parent_id: 1
  q = {
    parent_id: 1, # self
    name: '',
  }
  node = @db[:nodes][q]
  if node
    node[:dirname] = ''
    @root_node = node
    return node
  end
  begin
    q[:tlen] = DM_DIR
    q[:id] = @db[:nodes].insert(q)
    q
  rescue Sequel::DatabaseError
    # we may conflict on insert if we didn't use a transaction
    raise if @db.in_transaction?
    @root_node = @db[:paths][q] or raise
  end
end

#scan_any(path, parent_id) ⇒ Object



208
209
210
211
212
213
214
215
216
217
# File 'lib/dtas/mlib.rb', line 208

def scan_any(path, parent_id)
  st = File.lstat(path) rescue return
  if st.directory?
    scan_dir(path, st, parent_id)
  elsif st.file?
    scan_file(path, st, parent_id)
  # elsif st.symlink? TODO
    # scan_link(path, st, parent_id)
  end
end

#scan_dir(path, st, parent_id = nil) ⇒ Object



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
# File 'lib/dtas/mlib.rb', line 314

def scan_dir(path, st, parent_id = nil)
  cd(path) do
    # TODO: use parent_id if given
    dir = dir_vivify(@pwd.split(%r{/+}n), st.ctime.to_i)
    dir_id = dir[:id]

    synchronize do
      @db[:nodes].where(parent_id: dir_id).each do |node|
        File.exist?(node[:name]) or remove_entry(node)
      end
    end

    Dir.foreach('.', encoding: Encoding::BINARY) do |x|
      case x
      when '.', '..', %r{\n}n
        # files with newlines in them are rare and last I checked (in 2008),
        # mpd could not support them, either.  So lets not bother for now.
        next
      else
        scan_any(x, dir_id)
      end
    end
  end
end

#scan_file(path, st, parent_id) ⇒ Object



223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/dtas/mlib.rb', line 223

def scan_file(path, st, parent_id)
  return if @suffixes !~ path || st.size == 0

  # no-op if no change
  unless @force
    if node = @db[:nodes][name: maybe_blob(path), parent_id: parent_id]
      return if st.ctime.to_i == node[:ctime] || node[:tlen] == DM_IGN
    end
  end

  job = Job.new(@pwd, st.ctime.to_i, parent_id, path)
  send_harder(@work, Marshal.dump(job))
end

#search(type, what, offset = 0, limit = nil) ⇒ Object

based on the MPD command of the same name



523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/dtas/mlib.rb', line 523

def search(type, what, offset = 0, limit = nil)
  load_tags
  type = type.downcase
  q = []
  what = @db.literal(%Q(%#{what}%))
  case type
  when 'any'
    # TODO: add path name matches
    q << 'SELECT DISTINCT(n.id),n.* FROM nodes n ' \
         'LEFT JOIN comments c ON c.node_id = n.id ' \
         'LEFT JOIN vals v ON v.id = c.val_id ' \
         "WHERE v.val LIKE #{what}"
  when *(@tags.keys)
    tag_id = @tag_map[type]
    q << 'SELECT DISTINCT(n.id),n.* FROM nodes n ' \
         'LEFT JOIN comments c ON c.node_id = n.id ' \
         'LEFT JOIN vals v ON v.id = c.val_id ' \
         'LEFT JOIN tags t ON t.id = c.tag_id ' \
         "WHERE t.id = #{tag_id} AND v.val LIKE #{what}"
  else
    raise ArgumentError, "invalid type=#{type.inspect}"
  end
  q << 'ORDER by n.parent_id,n.name'
  offset_limit(q, offset, limit)
  @db[q.join(' ')].each { |node| yield node }
end

#send_harder(sock, msg) ⇒ Object



339
340
341
342
343
344
345
346
347
348
349
# File 'lib/dtas/mlib.rb', line 339

def send_harder(sock, msg)
  sock.sendmsg(msg)
rescue Errno::EMSGSIZE
  sock.setsockopt(:SOL_SOCKET, :SO_SNDBUF, msg.bytesize + 1024)
  # if it still fails, oh well...
  begin
    sock.sendmsg(msg)
  rescue => e
    warn "#{msg.bytesize} too big, dropped #{e.class}"
  end
end

#statsObject



411
412
413
414
415
# File 'lib/dtas/mlib.rb', line 411

def stats
  rv = { songs: count_songs, db_playtime: db_playtime }
  %w(artist album).each { |k| rv[:"#{k}s"] = count_distinct(k) }
  rv
end

#synchronizeObject



66
67
68
69
70
71
# File 'lib/dtas/mlib.rb', line 66

def synchronize
  @lock.flock(File::LOCK_EX)
  @db.transaction { yield }
ensure
  @lock.flock(File::LOCK_UN)
end

#update(path, opts = nil) ⇒ Object



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/dtas/mlib.rb', line 143

def update(path, opts = nil)
  # n.b. "jobs" is for CPU concurrency.  Audio media is typically stored
  # on high-latency media or slow network file systems; so we use a high
  # number of jobs by default to compensate for the seek-heavy workload
  # this generates
  opts ||= {}
  jobs = opts[:jobs] || 8
  @force = opts[:force] || false

  init_suffixes
  st = File.stat(path) # we always follow the first dir even if it's a symlink
  st.directory? or
    raise ArgumentError, "path: #{path.inspect} is not a directory"
  @work and raise 'update already running'
  todo, @work = UNIXSocket.pair(:SOCK_SEQPACKET)
  @db.disconnect

  # like a Mutex between processes
  @lock = Tempfile.new('dtas.mlib.lock')
  jobs.times do |i|
    lock = File.open(@lock.path, 'w')
    fork { worker(todo, lock) }
    lock.close
  end
  @lock.unlink
  todo.close
  scan_dir(path, st)
  @work.close
  Process.waitall
  @lock.close
ensure
  @work = nil
end

#worker(todo, lock) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/dtas/mlib.rb', line 79

def worker(todo, lock)
  @lock = lock
  @work.close
  synchronize { @db.tables } # reconnect before chdir
  @pwd = Dir.pwd.b
  begin
    buf = todo.recv(16384) # 4x bigger than PATH_MAX ought to be enough
    exit if buf.empty?
    job = Marshal.load(buf)
    buf.clear
    worker_work(job)
  rescue => e
    warn "#{e.message} (#{e.class}) #{e.backtrace.join("\n")}\n"
  end while true
end

#worker_work(job) ⇒ Object



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
# File 'lib/dtas/mlib.rb', line 101

def worker_work(job)
  tlen = nil
  wd = job.wd
  if wd != @pwd
    Dir.chdir(wd)
    @pwd = wd
  end
  path = job.path
  found = nil
  @sources.each do |src|
    found = src.try(path) and break
  end
  return ignore(job) unless found
  tlen = found.duration
  return ignore(job) if tlen.nil? || tlen < 0
  tlen = tlen.round
  tmp = {}
  if comments = found.comments
    comments.each do |tag, value|
      tag_id = @tag_map[tag] or next
      tmp[tag_id] = value if value.valid_encoding?
    end
  end
  synchronize do
    node_id = node_ensure(job.parent_id, path, tlen, job.ctime)[:id]
    vals = @db[:vals]
    comments = @db[:comments]
    q = { node_id: node_id }
    comments.where(q).delete
    tmp.each do |tid, val|
      v = vals[val: val]
      begin
        q[:val_id] = v ? v[:id] : vals.insert(val: val)
        q[:tag_id] = tid
        comments.insert(q)
      rescue => e
        warn "E: #{e.message} (#{e.class}) q=#{q.inspect} val=#{val.inspect}"
      end
    end
  end
end