38 lines
1.2 KiB
Plaintext
38 lines
1.2 KiB
Plaintext
import Model from require "lapis.db.model"
|
|
|
|
import Deltas from require "models"
|
|
import bytes from require "resty.random"
|
|
import to_hex from require "resty.string"
|
|
import abort from require "helpers"
|
|
|
|
class Sessions extends Model
|
|
@create: (input) =>
|
|
-- make sure a unique id is generated
|
|
id = input.id or to_hex bytes 16
|
|
while Sessions\find id: id
|
|
id = to_hex bytes 16
|
|
|
|
-- take user input time or when this request started processing
|
|
time = tonumber(input.started_at) or ngx.req.start_time!
|
|
values = {
|
|
started_at: time
|
|
updated_at: time
|
|
id: id
|
|
}
|
|
return super values
|
|
|
|
@update: (input) =>
|
|
-- user can manually change started_at and updated_at if they want
|
|
-- this will potentially invalidate data in the Deltas
|
|
values = {
|
|
started_at: tonumber(input.started_at) or nil
|
|
updated_at: tonumber(input.updated_at) or ngx.req.start_time!
|
|
}
|
|
local delta
|
|
if input.type
|
|
delta, err = Deltas\create session_id: @id, type: input.type, time: values.updated_at - @updated_at
|
|
unless delta
|
|
-- abort "Invalid type (must be <=255 bytes)."
|
|
abort "Failed to create delta: #{err}"
|
|
return super(values), delta
|