upr.git  about / heads / tags
Upload Progress for Rack
blob ec285c90bd4664d84bfd66a0e1701ffbe3d79138 1301 bytes (raw)
$ git show HEAD:lib/upr/monitor.rb	# shows this blob on the CLI

 1
 2
 3
 4
 5
 6
 7
 8
 9
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
 
# -*- encoding: binary -*-
module Upr

  # Keeps track of the status of all currently processing uploads
  # This uses any {Moneta}[http://github.com/wycats/moneta]
  # store to monitor upload progress.
  #
  # Usage (in config.ru with Moneta Memory store):
  #   require 'upr'
  #   require 'moneta'
  #   use Upr, :backend => Upr::Monitor.new(Moneta.new(:Memory, :serializer => nil))
  #   run YourApplication.new
  class Monitor < Struct.new(:moneta)
    # nuke anything not read/updated in 60 seconds
    OPT = { :expires_in => 60 }

    def initialize(moneta_store = nil)
      super
      if moneta_store.nil?
        self.moneta = Moneta.new(:Memory, :serializer => nil)
      end
    end

    def start(upid, length)
      moneta.store(upid, Status.new(0, length), OPT)
    end

    def read(upid)
      moneta[upid]
    end

    def incr(upid, nr)
      status = moneta[upid] or return
      status.seen += nr if status.seen >= 0
      moneta.store(upid, status, OPT)
    end

    def finish(upid)
      status = moneta[upid] or return
      status.length ||= status.seen
      status.seen = status.length
      moneta.store(upid, status, OPT)
    end

    def error!(upid)
      status = moneta[upid] or return
      status.seen = -1
      moneta.store(upid, status, OPT)
    end

  end
end

git clone https://yhbt.net/upr.git