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.



44
45
46
47
48
49
50
# File 'lib/textus/store.rb', line 44

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, root: nil) ⇒ Object

Raises:



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

def self.discover(start_dir = Dir.pwd, root: nil)
  explicit = root || ENV.fetch("TEXTUS_ROOT", nil)
  return discover_explicit(explicit) if explicit

  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



207
208
209
# File 'lib/textus/store.rb', line 207

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

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

Raises:



174
175
176
177
178
179
180
181
182
183
184
185
186
187
# File 'lib/textus/store.rb', line 174

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



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

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

#fire_event(event, **kwargs) ⇒ Object



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/textus/store.rb', line 189

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:



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/textus/store.rb', line 79

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



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

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



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/textus/store.rb', line 52

def load_extensions
  Textus.with_registry(@registry) do
    BuiltinActions.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:



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
410
411
412
413
414
415
416
417
418
419
# File 'lib/textus/store.rb', line 343

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



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

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:



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
163
164
165
166
167
168
169
170
171
172
# File 'lib/textus/store.rb', line 134

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



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

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

#schema_envelope(key) ⇒ Object



122
123
124
125
126
127
128
129
130
131
# File 'lib/textus/store.rb', line 122

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



68
69
70
71
72
73
74
75
76
77
# File 'lib/textus/store.rb', line 68

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



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
320
321
322
323
324
325
326
327
328
329
# File 'lib/textus/store.rb', line 260

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.action
    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.



334
335
336
337
# File 'lib/textus/store.rb', line 334

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

#validate_allObject



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
248
249
250
251
252
253
254
255
256
257
# File 'lib/textus/store.rb', line 215

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



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

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