Class: Textus::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/textus/store.rb

Overview

rubocop:disable Metrics/ClassLength

Constant Summary collapse

HOOK_TIMEOUT_SECONDS =
2

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ Store

Returns a new instance of Store.



34
35
36
37
38
39
40
# File 'lib/textus/store.rb', line 34

def initialize(root)
  @root = File.expand_path(root)
  @manifest = Manifest.load(@root)
  @registry = ExtensionRegistry.new
  @schemas = {}
  load_extensions
end

Instance Attribute Details

#manifestObject (readonly)

Returns the value of attribute manifest.



11
12
13
# File 'lib/textus/store.rb', line 11

def manifest
  @manifest
end

#registryObject (readonly)

Returns the value of attribute registry.



11
12
13
# File 'lib/textus/store.rb', line 11

def registry
  @registry
end

#rootObject (readonly)

Returns the value of attribute root.



11
12
13
# File 'lib/textus/store.rb', line 11

def root
  @root
end

Class Method Details

.discover(start_dir = Dir.pwd) ⇒ Object

Raises:



20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/textus/store.rb', line 20

def self.discover(start_dir = Dir.pwd)
  dir = File.expand_path(start_dir)
  loop do
    candidate = File.join(dir, ".textus")
    return new(candidate) if File.directory?(candidate) && File.exist?(File.join(candidate, "manifest.yaml"))

    parent = File.dirname(dir)
    break if parent == dir

    dir = parent
  end
  raise IoError.new("no .textus directory found from #{start_dir}")
end

.mint_uidObject

A Textus UID: 16 lowercase hex chars (SecureRandom.hex(8)). Not a UUID —short on purpose. Random enough for collision-never-in-practice within a single store.



16
17
18
# File 'lib/textus/store.rb', line 16

def self.mint_uid
  SecureRandom.hex(8)
end

Instance Method Details

#accept(key, as:) ⇒ Object



197
198
199
# File 'lib/textus/store.rb', line 197

def accept(key, as:)
  Proposal.accept(self, key, as: as)
end

#delete(key, if_etag: nil, as: Role::DEFAULT, suppress_events: false) ⇒ Object

Raises:



164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/textus/store.rb', line 164

def delete(key, if_etag: nil, as: Role::DEFAULT, suppress_events: false)
  mentry, path, = @manifest.resolve(key)
  writers = @manifest.zone_writers(mentry.zone)
  raise WriteForbidden.new(key, mentry.zone, writers: writers) unless writers.include?(as)
  raise UnknownKey.new(key, suggestions: @manifest.suggestions_for(key)) unless File.exist?(path)

  etag_before = Etag.for_file(path)
  raise EtagMismatch.new(key, if_etag, etag_before) if if_etag && if_etag != etag_before

  File.delete(path)
  audit_log.append(role: as, verb: "delete", key: key, etag_before: etag_before, etag_after: nil)
  fire_event(:delete, key: key) unless suppress_events
  { "protocol" => PROTOCOL, "ok" => true, "key" => key, "deleted" => true }
end

#deps(key) ⇒ Object



201
# File 'lib/textus/store.rb', line 201

def deps(key)      = Dependencies.deps_of(@manifest, key)

#fire_event(event, **kwargs) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
# File 'lib/textus/store.rb', line 179

def fire_event(event, **kwargs)
  view = StoreView.new(self)
  @registry.hooks(event).each do |entry|
    name = entry[:name]
    Timeout.timeout(HOOK_TIMEOUT_SECONDS) { entry[:callable].call(store: view, **kwargs) }
  rescue StandardError => e
    extras = { "event" => event.to_s, "hook" => name.to_s, "error" => "#{e.class}: #{e.message}" }
    extras["target_key"]  = kwargs[:target_key]  if kwargs.key?(:target_key)
    extras["pending_key"] = kwargs[:pending_key] if kwargs.key?(:pending_key)
    audit_log.append(
      role: "script", verb: "event_error",
      key: kwargs[:key] || kwargs[:target_key] || kwargs[:pending_key] || "-",
      etag_before: nil, etag_after: nil,
      extras: extras
    )
  end
end

#get(key) ⇒ Object

Raises:



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/textus/store.rb', line 69

def get(key)
  mentry, path, = @manifest.resolve(key)
  raise UnknownKey.new(key, suggestions: @manifest.suggestions_for(key)) unless File.exist?(path)

  raw = File.binread(path)
  parsed = Entry.for_format(mentry.format).parse(raw, path: path)
  fm = parsed["frontmatter"]
  content = parsed["content"]
  enforce_name_match!(path, fm, mentry.format)
  schema = schema_for(mentry.schema)
  if schema
    case mentry.format
    when "markdown" then schema.validate!(fm)
    when "json", "yaml" then schema.validate!(content || {})
      # text: schema forbidden by manifest validation
    end
  end
  build_envelope(key, mentry, path, fm, parsed["body"], Etag.for_bytes(raw), content: content)
end

#list(prefix: nil, zone: nil) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
# File 'lib/textus/store.rb', line 100

def list(prefix: nil, zone: nil)
  rows = @manifest.enumerate(prefix: prefix)
  rows = rows.select { |r| r[:manifest_entry].zone == zone } if zone
  rows.map do |row|
    {
      "key" => row[:key],
      "zone" => row[:manifest_entry].zone,
      "path" => row[:path],
    }
  end
end

#load_extensionsObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/textus/store.rb', line 42

def load_extensions
  Textus.with_registry(@registry) do
    BuiltinFetchers.register_all
    dir = File.join(@root, "extensions")
    return unless File.directory?(dir)

    Dir.glob(File.join(dir, "*.rb")).sort.each do |f| # rubocop:disable Lint/RedundantDirGlobSort
      begin
        load(f)
      rescue StandardError, ScriptError => e
        raise UsageError.new("failed loading extension #{File.basename(f)}: #{e.class}: #{e.message}")
      end
    end
  end
end

#mv(old_key, new_key, as: Role::DEFAULT, dry_run: false) ⇒ Object

Move an entry from old_key to new_key within the same zone. Preserves uid (minting one first if absent), validates both keys against the manifest, refuses to clobber, and writes one mv audit row. rubocop:disable Metrics/AbcSize, Metrics/MethodLength

Raises:



333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
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
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'lib/textus/store.rb', line 333

def mv(old_key, new_key, as: Role::DEFAULT, dry_run: false)
  @manifest.validate_key!(old_key)
  @manifest.validate_key!(new_key)
  raise UsageError.new("mv: old and new keys are identical") if old_key == new_key

  old_mentry, old_path, = @manifest.resolve(old_key)
  raise UnknownKey.new(old_key) unless File.exist?(old_path)

  new_mentry, new_path, = @manifest.resolve(new_key)

  if old_mentry.zone != new_mentry.zone
    raise UsageError.new(
      "mv: cross-zone move refused (#{old_mentry.zone}#{new_mentry.zone}). " \
      "Use put+delete for cross-zone moves.",
    )
  end
  if old_mentry.format != new_mentry.format
    raise UsageError.new(
      "mv: format mismatch (#{old_mentry.format}#{new_mentry.format}); refusing.",
    )
  end

  writers = @manifest.zone_writers(old_mentry.zone)
  raise WriteForbidden.new(old_key, old_mentry.zone, writers: writers) unless writers.include?(as)

  raise UsageError.new("mv: target '#{new_key}' already exists at #{new_path}") if File.exist?(new_path)

  # Mint uid before the move so the audit row carries it.
  pre_env = get(old_key)
  current_uid = pre_env["uid"]
  etag_before = pre_env["etag"]

  if dry_run
    return {
      "protocol" => PROTOCOL, "ok" => true, "dry_run" => true,
      "from_key" => old_key, "to_key" => new_key,
      "from_path" => old_path, "to_path" => new_path,
      "uid" => current_uid
    }
  end

  if current_uid.nil?
    # Write the uid in place first so the source file carries it before mv.
    pre_env = put(old_key,
                  frontmatter: pre_env["frontmatter"],
                  body: pre_env["body"],
                  content: pre_env["content"],
                  as: as,
                  suppress_events: true)
    current_uid = pre_env["uid"]
    etag_before = pre_env["etag"]
  end

  FileUtils.mkdir_p(File.dirname(new_path))
  FileUtils.mv(old_path, new_path)
  rewrite_name_for_mv!(new_mentry, new_path, new_key)
  etag_after = Etag.for_file(new_path)

  audit_log.append(
    role: as, verb: "mv", key: new_key,
    etag_before: etag_before, etag_after: etag_after,
    extras: {
      "from_key" => old_key, "to_key" => new_key,
      "from_path" => old_path, "to_path" => new_path,
      "uid" => current_uid
    }
  )

  env = get(new_key)
  {
    "protocol" => PROTOCOL, "ok" => true,
    "from_key" => old_key, "to_key" => new_key,
    "from_path" => old_path, "to_path" => new_path,
    "uid" => current_uid,
    "envelope" => env
  }
end

#publishedObject



203
# File 'lib/textus/store.rb', line 203

def published      = Dependencies.published_of(@manifest)

#put(key, frontmatter: nil, body: nil, content: nil, if_etag: nil, as: Role::DEFAULT, suppress_events: false) ⇒ Object

rubocop:disable Metrics/ParameterLists

Raises:



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
160
161
162
# File 'lib/textus/store.rb', line 124

def put(key, frontmatter: nil, body: nil, content: nil, if_etag: nil, as: Role::DEFAULT, suppress_events: false)
  # rubocop:enable Metrics/ParameterLists
  @manifest.validate_key!(key)
  mentry, path, = @manifest.resolve(key)
  writers = @manifest.zone_writers(mentry.zone)
  raise WriteForbidden.new(key, mentry.zone, writers: writers) unless writers.include?(as)

  frontmatter ||= {}
  strategy = Entry.for_format(mentry.format)

  existing_uid = existing_uid_for(mentry, path)
  frontmatter, content = ensure_uid(mentry.format, frontmatter, content, existing_uid)

  bytes, eff_fm, eff_body, eff_content = serialize_for_put(
    mentry: mentry, path: path, strategy: strategy,
    frontmatter: frontmatter, body: body, content: content
  )

  enforce_name_match!(path, eff_fm, mentry.format)

  schema = schema_for(mentry.schema)
  if schema
    case mentry.format
    when "markdown" then schema.validate!(eff_fm)
    when "json", "yaml" then schema.validate!(eff_content || {})
    end
  end

  etag_before = File.exist?(path) ? Etag.for_file(path) : nil
  raise EtagMismatch.new(key, if_etag, etag_before) if if_etag && (etag_before != if_etag)

  FileUtils.mkdir_p(File.dirname(path))
  File.binwrite(path, bytes)
  etag_after = Etag.for_bytes(bytes)
  audit_log.append(role: as, verb: "put", key: key, etag_before: etag_before, etag_after: etag_after)
  envelope = build_envelope(key, mentry, path, eff_fm, eff_body, etag_after, content: eff_content)
  fire_event(:put, key: key, envelope: envelope) unless suppress_events
  envelope
end

#rdeps(key) ⇒ Object



202
# File 'lib/textus/store.rb', line 202

def rdeps(key)     = Dependencies.rdeps_of(@manifest, key)

#schema_envelope(key) ⇒ Object



112
113
114
115
116
117
118
119
120
121
# File 'lib/textus/store.rb', line 112

def schema_envelope(key)
  mentry, = @manifest.resolve(key)
  schema = schema_for(mentry.schema)
  {
    "protocol" => PROTOCOL,
    "key" => key,
    "schema_ref" => mentry.schema,
    "schema" => schema&.to_h,
  }
end

#schema_for(name) ⇒ Object



58
59
60
61
62
63
64
65
66
67
# File 'lib/textus/store.rb', line 58

def schema_for(name)
  return nil if name.nil?

  @schemas[name] ||= begin
    sp = File.join(@root, "schemas", "#{name}.yaml")
    raise IoError.new("schema not found: #{sp}") unless File.exist?(sp)

    Schema.load(sp)
  end
end

#stale(prefix: nil, zone: nil) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity, Metrics/BlockLength



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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/textus/store.rb', line 250

def stale(prefix: nil, zone: nil)
  out = []
  @manifest.entries.each do |mentry|
    next unless mentry.zone == "derived"
    next if zone && mentry.zone != zone

    gen = mentry.generator
    next unless gen
    next if prefix && !(mentry.key == prefix || mentry.key.start_with?("#{prefix}."))

    path = path_for_entry(mentry)

    unless File.exist?(path)
      out << stale_row(mentry, path, "derived entry has never been generated")
      next
    end

    raw = File.binread(path)
    parsed = Entry.for_format(mentry.format).parse(raw, path: path)
    generated_at = parsed["frontmatter"].dig("generated", "at")
    unless generated_at
      out << stale_row(mentry, path, "missing generated.at frontmatter")
      next
    end
    gen_time = begin
      Time.parse(generated_at.to_s)
    rescue StandardError
      nil
    end
    unless gen_time
      out << stale_row(mentry, path, "unparseable generated.at: #{generated_at.inspect}")
      next
    end

    offender = newest_source_after(gen, gen_time)
    out << stale_row(mentry, path, "source '#{offender}' modified after generated.at") if offender
  end

  @manifest.entries.each do |mentry|
    next unless mentry.fetcher
    next if zone && mentry.zone != zone
    next if prefix && !(mentry.key == prefix || mentry.key.start_with?("#{prefix}."))

    ttl = parse_ttl(mentry.ttl)
    next unless ttl

    path = path_for_entry(mentry)

    unless File.exist?(path)
      out << intake_stale_row(mentry, path, "never refreshed")
      next
    end

    fm = Entry.for_format(mentry.format).parse(File.binread(path), path: path)["frontmatter"]
    last_str = fm["last_refreshed_at"]
    if last_str.nil?
      out << intake_stale_row(mentry, path, "never refreshed (no last_refreshed_at)")
      next
    end

    last = begin
      Time.parse(last_str.to_s)
    rescue StandardError
      nil
    end
    out << intake_stale_row(mentry, path, "ttl exceeded (#{ttl}s)") if last.nil? || (Time.now - last) > ttl
  end

  out
end

#uid(key) ⇒ Object

Returns the Textus UID for a key (or nil if the entry has none yet). Raises UnknownKey if the key doesn’t resolve to a real file.



324
325
326
327
# File 'lib/textus/store.rb', line 324

def uid(key)
  env = get(key)
  env["uid"]
end

#validate_allObject



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
# File 'lib/textus/store.rb', line 205

def validate_all
  violations = []
  @manifest.enumerate.each do |row|
    begin
      get(row[:key])
    rescue Textus::Error => e
      violations << { "key" => row[:key], "code" => e.code, "message" => e.message }
    end
  end

  @manifest.enumerate.each do |row|
    mentry = row[:manifest_entry]
    next unless mentry.schema

    schema = schema_for(mentry.schema)
    next unless schema

    env = begin
      get(row[:key])
    rescue StandardError
      next
    end
    last_writer = audit_log.last_writer_for(row[:key])
    next if last_writer.nil?

    env["frontmatter"].each_key do |field|
      owner = schema.maintained_by(field)
      next if owner.nil?
      next if last_writer == owner
      next if last_writer == "human"

      violations << {
        "key" => row[:key],
        "code" => "role_authority",
        "field" => field,
        "expected" => owner,
        "last_writer" => last_writer,
      }
    end
  end

  { "protocol" => PROTOCOL, "ok" => violations.empty?, "violations" => violations }
end

#where(key) ⇒ Object



89
90
91
92
93
94
95
96
97
98
# File 'lib/textus/store.rb', line 89

def where(key)
  mentry, path, = @manifest.resolve(key)
  {
    "protocol" => PROTOCOL,
    "key" => key,
    "zone" => mentry.zone,
    "owner" => mentry.owner,
    "path" => path,
  }
end