Class: InstantRecord::SyncWindow

Inherits:
Object
  • Object
show all
Defined in:
lib/instant_record/sync_window.rb

Overview

A bounded sync window declared on a Syncable model: the newest limit rows, per partition when partition_by is set, ordered by (created_at, id). Bootstrap serializes in_window, history pages walk below it, and the browser client evicts beyond_window at boot.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, limit:, partition_by: nil) ⇒ SyncWindow

Returns a new instance of SyncWindow.



9
10
11
12
13
14
15
16
17
# File 'lib/instant_record/sync_window.rb', line 9

def initialize(model, limit:, partition_by: nil)
  unless limit.is_a?(Integer) && limit.positive?
    raise ArgumentError, "sync_window limit must be a positive integer (got #{limit.inspect})"
  end

  @model = model
  @limit = limit
  @partition_by = partition_by&.to_s
end

Instance Attribute Details

#limitObject (readonly)

Returns the value of attribute limit.



7
8
9
# File 'lib/instant_record/sync_window.rb', line 7

def limit
  @limit
end

#modelObject (readonly)

Returns the value of attribute model.



7
8
9
# File 'lib/instant_record/sync_window.rb', line 7

def model
  @model
end

#partition_byObject (readonly)

Returns the value of attribute partition_by.



7
8
9
# File 'lib/instant_record/sync_window.rb', line 7

def partition_by
  @partition_by
end

Instance Method Details

#beyond_window(scope = @model.all) ⇒ Object

Rows outside the window — eviction's target. An extra scope narrows further (e.g. excluding sync_state "pending").



26
27
28
# File 'lib/instant_record/sync_window.rb', line 26

def beyond_window(scope = @model.all)
  scope.where("#{quoted_primary_key} IN (#{ranked_ids_sql(">")})")
end

#in_windowObject

Rows inside the window (the newest limit per partition).



20
21
22
# File 'lib/instant_record/sync_window.rb', line 20

def in_window
  @model.where("#{quoted_primary_key} IN (#{ranked_ids_sql("<=")})")
end

#keyset_below(at:, id:, partition: nil) ⇒ Object

Keyset page scope: rows strictly below the (created_at, id) tuple within one partition, newest first. Shared by the records endpoint (server) and the client's local-page checks — one predicate, no OFFSET.



33
34
35
36
37
38
39
# File 'lib/instant_record/sync_window.rb', line 33

def keyset_below(at:, id:, partition: nil)
  pk = @model.primary_key
  scope = @partition_by ? @model.where(@partition_by => partition) : @model.all
  scope
    .where("created_at < :at OR (created_at = :at AND #{pk} < :id)", at: at, id: id)
    .order(created_at: :desc, pk => :desc)
end