fast-proxy-status 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,642 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Fast
4
+ # RFC 9213 Targeted HTTP Cache Control: the framework of response
5
+ # fields that carry cache directives targeted at a specific class of
6
+ # cache — "a targeted field is an HTTP response header field that has
7
+ # the same semantics as the Cache-Control response header field.
8
+ # However, it has a distinct field name that indicates the target for
9
+ # its cache directives" (§2) — and this class is its value object:
10
+ # the RFC 9651 Dictionary of cache directives with §2.1's
11
+ # type-inference rules read on parse and enforced on emit. It does
12
+ # not include the List engine: a Dictionary's members are key-value,
13
+ # and its leniency is per-directive, not whole-field.
14
+ #
15
+ # The registered instance is FIELD_NAME — §3's CDN-Cache-Control, "a
16
+ # targeted field (Section 2) that allows origin servers to control
17
+ # the behavior of CDN caches interposed between them and clients
18
+ # separately from other caches that might handle the response." The
19
+ # class itself is name-agnostic and carries no "-Cache-Control"
20
+ # suffix matcher: §2.4 — "By convention, targeted fields have the
21
+ # suffix '-Cache-Control' ... However, this suffix MUST NOT be used
22
+ # on its own to identify targeted fields; it is only a convention."
23
+ #
24
+ # §2.2's target-list semantics are cache policy, the caller's
25
+ # context, and are never implemented here: a cache "maintains a
26
+ # target list", "MUST select the first (in target-list order) field
27
+ # with a valid, non-empty value", and "MUST ignore the Cache-Control
28
+ # and Expires header fields in that response" — none of which a
29
+ # single field value can decide.
30
+ #
31
+ # parse is the recipient's view with §2.1's own leniency split: a
32
+ # field that is empty or fails to parse is the ENTIRE field ignored
33
+ # — "If a targeted field in a given response is empty, or a parsing
34
+ # error is encountered, that field MUST be ignored by the cache"
35
+ # (§2.1) — the shared frozen empty value, the same answer an absent
36
+ # field gives; while a member whose value violates the inferred
37
+ # constraints is PRESERVED in the data and FLAGGED: "Implementations
38
+ # SHOULD NOT consume values that violate these inferred constraints"
39
+ # (§2.1) — #violating answers those directive keys, in held order,
40
+ # so the caller can do exactly that, and the rest of the field stays
41
+ # readable. The flag is data, never a wire change: a parsed value
42
+ # re-emits faithfully, violating values included. Parameters on
43
+ # directives are ignored — "Parameters received on cache directives
44
+ # are to be ignored, unless other handling is explicitly specified"
45
+ # (§2.1): never a flag, preserved in the raw member data, re-emitted
46
+ # by a round-trip. A String is one field value; an Array is the
47
+ # field's lines, combined with ", " (RFC 9651 §4.2) — duplicate keys:
48
+ # last value wins, first position kept. A wrong input type is a
49
+ # caller bug and raises TypeError.
50
+ #
51
+ # parse! is strict truth: the Dictionary failure wrapped with its
52
+ # message and byte offset, then the inferred constraints, the FIRST
53
+ # offender in Dictionary order raised positioned at its VALUE.
54
+ # valid? answers the same question with a boolean and never raises.
55
+ #
56
+ # to_s and construction are ALWAYS strict, in every family gem:
57
+ # "Implementations MUST NOT generate values that violate these
58
+ # inferred constraints" (§2.1) — every value one of the five
59
+ # inferred types, a known directive's value carrying its section's
60
+ # type, the keys Structured Fields keys. §2.1's digit-initial rule
61
+ # holds structurally: "string values whose first character is not
62
+ # alphabetic or '*' MUST be generated as Strings so that they are not
63
+ # mistaken for other types" — a plain String always emits quoted,
64
+ # and a Token's own grammar (RFC 9651 §3.3.4, ALPHA or "*" first)
65
+ # refuses the form at its construction, so this class needs no check
66
+ # of its own.
67
+ #
68
+ # The answer is a frozen value object: members (the directive key =>
69
+ # Fast::SFV::Item and InnerList view, parameters preserved), keys,
70
+ # violating, the bare #[] view (an inner list member's raw view is
71
+ # its items — a Dictionary value may be an InnerList, which has no
72
+ # #value), key?, size, empty?, each, the canonical to_s ("" when
73
+ # nothing is held), and class-checked canonical equality. Unknown
74
+ # directives pass through untouched (§2.2: "unrecognized extension
75
+ # directives are ignored").
76
+ class TargetedCacheControl
77
+ # RFC 9651 value shapes aliased here, private to this class, so
78
+ # the checks and the readers read them by the short name.
79
+ Item = SFV::Item
80
+ Token = SFV::Token
81
+ private_constant :Item, :Token
82
+
83
+ # The Byte Sequence tag: a String tagged ASCII-8BIT IS the Byte
84
+ # Sequence on the wire (RFC 9651 §3.3.5 — the encoding is the
85
+ # wire-type tag), so the inferred-type constraint reads the same
86
+ # fact, and a UTF-8 String would emit as a quoted sf-string.
87
+ BINARY = Encoding::ASCII_8BIT
88
+ private_constant :BINARY
89
+
90
+ # Directives this class builds carry no parameters — §2.1: they
91
+ # "are to be ignored" — so they all share the one frozen empty
92
+ # Hash, the parse path's own shape.
93
+ EMPTY_PARAMS = {}.freeze
94
+ private_constant :EMPTY_PARAMS
95
+
96
+ # The family root, one rescue for the whole gem: every
97
+ # Fast::TargetedCacheControl failure descends from
98
+ # Fast::ProxyStatus::Error, so a caller can guard this class and
99
+ # its siblings with one rescue. This class is never raised in its
100
+ # own right — every failure here is either a parse defect or a
101
+ # serialization defect. A wrong input type is a caller bug, not
102
+ # field content: it raises plain TypeError and never this class.
103
+ class Error < ProxyStatus::Error; end
104
+
105
+ # A targeted field this gem cannot read. Two shapes meet here: the
106
+ # underlying RFC 9651 Dictionary failed to parse — the failure is
107
+ # wrapped with its message and byte offset preserved — or, under
108
+ # the strict parse, a member broke §2.1's inferred constraints (a
109
+ # known directive of the wrong type, or a value outside the five
110
+ # inferred types), and #offset is the byte position of the
111
+ # offending member's VALUE in the combined field value (just past
112
+ # the "="; the key's end for the valueless form; the LAST
113
+ # occurrence of a duplicated key — the member the last-wins parse
114
+ # kept). The lenient parse never raises it: §2.1 MUSTs the field
115
+ # ignored, and the violating member is preserved and flagged
116
+ # instead.
117
+ class ParseError < Error
118
+ attr_reader :offset
119
+
120
+ def initialize(message, offset)
121
+ super(message)
122
+ @offset = offset
123
+ end
124
+ end
125
+
126
+ # A value cannot go on the wire: the field under construction breaks
127
+ # §2.1's "Implementations MUST NOT generate values that violate
128
+ # these inferred constraints" — a value outside the five inferred
129
+ # types, a known directive's value of the wrong type, a key outside
130
+ # the Structured Fields key grammar, or members that are not a
131
+ # Hash. #offset is the byte position in the output built so far —
132
+ # 0, because the check runs before anything is emitted; the whole
133
+ # emit path raises this class and never TypeError: on emit the
134
+ # wrongness is in the value being sent, which is field content,
135
+ # not a caller protocol bug.
136
+ class SerializeError < Error
137
+ attr_reader :offset
138
+
139
+ def initialize(message, offset)
140
+ super(message)
141
+ @offset = offset
142
+ end
143
+ end
144
+
145
+ # §3: "The CDN-Cache-Control response header field is a targeted
146
+ # field (Section 2) that allows origin servers to control the
147
+ # behavior of CDN caches interposed between them and clients
148
+ # separately from other caches that might handle the response." The
149
+ # one registered instance this document defines; the class is
150
+ # name-agnostic otherwise (§2.4's suffix MUST NOT).
151
+ FIELD_NAME = "CDN-Cache-Control"
152
+
153
+ # §2.2's MUST-implement five, key => the type its value carries —
154
+ # the types from §2.1's own mapping and the Cache-Control sections
155
+ # it cites (RFC 9111 §5.2.2: max-age "an integer number of
156
+ # seconds", must-revalidate and no-store no argument, no-cache and
157
+ # private "a field-name list" in a quoted string). Frozen public
158
+ # data, its own lookup (a Hash IS its registry's read); the table
159
+ # never gates a parse — an unknown directive parses, is preserved
160
+ # and round-trips (§2.2: "unrecognized extension directives are
161
+ # ignored"; a future registration must not break an old gem
162
+ # version).
163
+ DIRECTIVES = {
164
+ "max-age" => "an Integer", # 9111 5.2.2.1
165
+ "must-revalidate" => "Boolean true", # 9111 5.2.2.2
166
+ "no-store" => "Boolean true", # 9111 5.2.2.5
167
+ "no-cache" => "Boolean true or a String", # 9111 5.2.2.4
168
+ "private" => "Boolean true or a String" # 9111 5.2.2.7
169
+ }.freeze
170
+
171
+ # §2.1's rule for a directive the table does not carry: the mapping
172
+ # the section itself spells — "cache directives that have no value
173
+ # will be mapped to a Boolean ... When the value is a
174
+ # quoted-string, it will be mapped to a String, and when it is a
175
+ # token, it will map to a Token, an Integer, or a Decimal,
176
+ # depending on the content of the value." The wording the
177
+ # ParseError and the SerializeError both carry for a value outside
178
+ # the mapping.
179
+ INFERRED = "one of the inferred types (a Boolean, a String, a Token, an Integer or a Decimal)"
180
+
181
+ # The strict parse's positioning walk: where each member's VALUE
182
+ # sits in the combined field value — the byte offset a §2.1
183
+ # ParseError points at. The field value already parsed when this
184
+ # runs, so the walk only tracks the boundaries: members split on
185
+ # commas at inner-list depth zero outside quoted strings (RFC 9651
186
+ # §4.2's separators), a quoted string's commas and parens do not
187
+ # count (§4.2.5's escapes are skipped two bytes), and a member
188
+ # without "=" — the implicit Boolean true — offsets at its key's
189
+ # end, where its value would be written. Every key's offset is
190
+ # recorded, a later occurrence overwriting an earlier one, because
191
+ # Fast::SFV applies §4.2's last-wins before the checks read these
192
+ # offsets — the effective member is the one its value came from.
193
+ # The walk runs ONLY where an error needs an offset — the clean and
194
+ # lenient paths pay nothing for positioning.
195
+ class Scan
196
+ # A 256-entry byte class: true for every byte of +spec+ — the
197
+ # byte-table shape the family's scanners walk with.
198
+ def self.byte_class(spec)
199
+ table = Array.new(256, false)
200
+ spec.each_byte { |byte| table[byte] = true }
201
+ table.freeze
202
+ end
203
+
204
+ # A Dictionary key's first byte: lcalpha or "*" (§4.2.3.3 step 1).
205
+ KEY_FIRST = byte_class("abcdefghijklmnopqrstuvwxyz*")
206
+ # A key's continuation: lcalpha, DIGIT, "_", "-", "." or "*"
207
+ # (§4.2.3.3) — the class the walk reads a whole key with, the
208
+ # first byte being a member of it, and the construction's key
209
+ # check too.
210
+ KEY_BODY = byte_class("abcdefghijklmnopqrstuvwxyz0123456789_-.*")
211
+ # The optional whitespace around a member separator (§4.2.1).
212
+ OWS = byte_class(" \t")
213
+
214
+ COMMA = 0x2C
215
+ EQUALS = 0x3D
216
+ LPAREN = 0x28
217
+ RPAREN = 0x29
218
+ DQUOTE = 0x22
219
+ BACKSLASH = 0x5C
220
+
221
+ def initialize(combined)
222
+ @combined = combined
223
+ @size = combined.bytesize
224
+ end
225
+
226
+ # One walk answers the value offset of every key the Dictionary
227
+ # parsed — the LAST one seen for each, since the effective member
228
+ # is the last one Fast::SFV kept.
229
+ def offsets
230
+ @offsets = {}
231
+ index = 0
232
+ index = member_at(index) while index < @size
233
+ @offsets
234
+ end
235
+
236
+ private
237
+
238
+ # Walks one member from +index+ and answers the index the next
239
+ # member starts at: leading OWS, the key, the value — its offset
240
+ # recorded — then the separator. A member that is not followed by
241
+ # a comma ends the walk.
242
+ def member_at(index)
243
+ index += 1 while index < @size && OWS[@combined.getbyte(index)]
244
+ key_start = index
245
+ index += 1 while index < @size && KEY_BODY[@combined.getbyte(index)]
246
+ key_end = index
247
+ value_offset = index
248
+ if @combined.getbyte(index) == EQUALS
249
+ index += 1
250
+ value_offset = index
251
+ index = value_end(index)
252
+ end
253
+ record(key_start, key_end - key_start, value_offset)
254
+ index += 1 while index < @size && OWS[@combined.getbyte(index)]
255
+ return @size unless index < @size && @combined.getbyte(index) == COMMA
256
+
257
+ index + 1
258
+ end
259
+
260
+ # Records one member's value offset under its key — the bytes the
261
+ # Dictionary itself parsed the same key from, so an equal key
262
+ # overwrites (the last-wins member).
263
+ def record(key_start, key_size, value_offset)
264
+ @offsets[@combined.byteslice(key_start, key_size)] = value_offset
265
+ end
266
+
267
+ # The index just past the member VALUE starting at +index+:
268
+ # quoted strings (§4.2.5 — a DQUOTE opens, a backslash escapes the
269
+ # next byte, a DQUOTE closes) and inner-list depth (§4.2.1.1's
270
+ # parens) are tracked, and a comma at depth zero outside a string
271
+ # — the §4.2 member boundary — stops the walk.
272
+ def value_end(index)
273
+ depth = 0
274
+ quoted = false
275
+ while index < @size
276
+ byte = @combined.getbyte(index)
277
+ if quoted
278
+ index += byte == BACKSLASH ? 2 : 1
279
+ quoted = false if byte == DQUOTE
280
+ else
281
+ case byte
282
+ when DQUOTE then quoted = true
283
+ when LPAREN then depth += 1
284
+ when RPAREN then depth -= 1
285
+ when COMMA then return index if depth.zero?
286
+ end
287
+ index += 1
288
+ end
289
+ end
290
+ index
291
+ end
292
+ end
293
+ private_constant :Scan
294
+
295
+ class << self
296
+ # RFC 9213 §2.1, the recipient semantics — never raises on field
297
+ # content. A field that is empty or fails to parse is the ENTIRE
298
+ # field ignored ("If a targeted field in a given response is
299
+ # empty, or a parsing error is encountered, that field MUST be
300
+ # ignored by the cache"): the shared frozen empty value, the same
301
+ # answer an absent field gives. A member whose value violates
302
+ # §2.1's inferred constraints is PRESERVED in the data and
303
+ # FLAGGED — "Implementations SHOULD NOT consume values that
304
+ # violate these inferred constraints" — #violating answers those
305
+ # directive keys in held order, and the rest of the field stays
306
+ # readable. Parameters on directives are ignored: never a flag,
307
+ # preserved in the raw member data, re-emitted by a round-trip.
308
+ # A String is one field value; an Array is the field's lines,
309
+ # combined with ", " (RFC 9651 §4.2) — duplicate keys: last value
310
+ # wins, first position kept. A wrong input type is a caller bug
311
+ # and raises TypeError.
312
+ def parse(input)
313
+ walk(input, false)
314
+ rescue ParseError
315
+ empty_value
316
+ end
317
+
318
+ # Strict truth. The RFC 9651 Dictionary failure is wrapped with
319
+ # its message and byte offset preserved; then §2.1's inferred
320
+ # constraints, the FIRST offender in Dictionary order raised
321
+ # positioned at that member's VALUE (just past the "="; the key's
322
+ # end for the valueless form; the LAST occurrence of a duplicated
323
+ # key — the member the last-wins parse kept), the message naming
324
+ # the directive and its rule. TypeError for a wrong input type,
325
+ # as parse.
326
+ def parse!(input)
327
+ walk(input, true)
328
+ end
329
+
330
+ # The boolean mirror: true exactly when parse! returns — false
331
+ # for malformed content, violating members and a wrong input type
332
+ # alike (a caller bug is not field content either). The empty
333
+ # value is true: the empty Dictionary is valid RFC 9651 content,
334
+ # and §2.1's empty-ignored MUST governs cache behavior, never the
335
+ # field's syntax.
336
+ def valid?(input)
337
+ walk(input, true)
338
+ true
339
+ rescue TypeError, ParseError
340
+ false
341
+ end
342
+
343
+ private
344
+
345
+ # The one walk behind parse and parse!: the RFC 9651 Dictionary
346
+ # parse, then §2.1's inferred constraints over the effective
347
+ # (last-wins) Dictionary in held order — the first offender raised
348
+ # positioned under the strict policy, the offenders' keys
349
+ # collected under the lenient one (the flag IS the strict/lenient
350
+ # delta, the one-walk discipline the List fields spell: the checks
351
+ # collect instead of raise). The lenient walk answers the shared
352
+ # empty value for the empty Dictionary too — §2.1: "If a targeted
353
+ # field in a given response is empty, or a parsing error is
354
+ # encountered, that field MUST be ignored by the cache" — while
355
+ # the strict walk answers the strict empty value. The underlying
356
+ # Dictionary failure is wrapped with its message and offset.
357
+ def walk(input, strict)
358
+ dict = SFV.parse_dict(input)
359
+ return empty_value if dict.empty? && !strict
360
+
361
+ members_from_dict(dict, combined(input), strict)
362
+ rescue SFV::ParseError => e
363
+ raise ParseError.new(e.message, e.offset)
364
+ end
365
+
366
+ # The field value the Scan positions into: the lines joined with
367
+ # ", " — the same RFC 9651 §4.2 combining Fast::SFV.parse_dict
368
+ # applies — a String as given.
369
+ def combined(input)
370
+ input.is_a?(Array) ? input.join(", ") : input
371
+ end
372
+
373
+ # The directive walk over a parsed Dictionary: §2.1's constraints
374
+ # on every member in held order, the first offender in Dictionary
375
+ # order raised positioned under the strict policy, the offenders'
376
+ # keys collected — the SHOULD-NOT-consume set #violating answers —
377
+ # under the lenient one, the member kept in the data either way.
378
+ def members_from_dict(dict, field_value, strict)
379
+ violations = []
380
+ dict.each do |key, member|
381
+ next if directive_ok?(key, member)
382
+
383
+ if strict
384
+ fail_member!(key, member, field_value)
385
+ else
386
+ violations << key
387
+ end
388
+ end
389
+ from_members(dict, violations)
390
+ end
391
+
392
+ # §2.1's constraint, positioned: the offender raised at that
393
+ # member's VALUE in the combined field value.
394
+ def fail_member!(key, member, field_value)
395
+ offset = Scan.new(field_value).offsets[key]
396
+ raise ParseError.new("#{key}: the value is #{rule_for(key)} (got #{shown(member)})", offset)
397
+ end
398
+
399
+ # §2.1's constraint for one directive: a known directive (the
400
+ # §2.2 MUST-implement five, or any a future registration adds)
401
+ # carries the type its section states; every directive's value is
402
+ # one of the five inferred types — an inner list, a Byte Sequence,
403
+ # a Date or a Display String is not in §2.1's mapping, so it
404
+ # violates. Parameters never matter here (§2.1: they "are to be
405
+ # ignored"): the member's own params ride along untouched.
406
+ def directive_ok?(key, member)
407
+ return false unless member.is_a?(Item)
408
+
409
+ value_ok?(key, member.value)
410
+ end
411
+
412
+ # One directive's value against §2.1's constraints — the read the
413
+ # parse walk and the construction boundary share, so the lenient
414
+ # flag, the strict raise and the emit refusal cannot drift.
415
+ def value_ok?(key, value)
416
+ case key
417
+ when "max-age" then value.is_a?(Integer)
418
+ when "must-revalidate", "no-store" then value == true
419
+ when "no-cache", "private" then value == true || plain_string?(value)
420
+ else inferred?(value)
421
+ end
422
+ end
423
+
424
+ # §2.1's inferred set: the five types a cache directive's value
425
+ # maps into — Boolean, String, Token, Integer or Decimal. A Byte
426
+ # Sequence (a String tagged ASCII-8BIT), a Date, a Display String
427
+ # or an inner list is outside the mapping.
428
+ def inferred?(value)
429
+ case value
430
+ when true, false, Integer, Float, Token then true
431
+ else value.is_a?(String) && value.encoding != BINARY
432
+ end
433
+ end
434
+
435
+ # §2.1's quoted-string mapping: a plain String — not a Token (a
436
+ # different wire type) and not a Byte Sequence.
437
+ def plain_string?(value)
438
+ value.is_a?(String) && !value.is_a?(Token) && value.encoding != BINARY
439
+ end
440
+
441
+ # The rule one directive's value must satisfy, worded for the
442
+ # message: the known-directive table's own wording, or the
443
+ # inferred set for a directive the table does not carry.
444
+ def rule_for(key)
445
+ DIRECTIVES[key] || INFERRED
446
+ end
447
+
448
+ # What a member error shows of the offender: the bare value when
449
+ # it is an Item (a wrong type), the member's class when it is not
450
+ # an Item at all — an inner list.
451
+ def shown(member)
452
+ member.is_a?(Item) ? member.value : member.class
453
+ end
454
+
455
+ # The value object behind a Dictionary that passed the walk: the
456
+ # members held as parsed (Items and InnerLists, parameters
457
+ # preserved), the violating keys held beside them.
458
+ def from_members(members, violations)
459
+ field = allocate
460
+ field.send(:hold, members, violations)
461
+ field
462
+ end
463
+
464
+ # The shared frozen empty value: the answer an absent, empty or
465
+ # malformed field parses to — one object, stable identity.
466
+ def empty_value
467
+ EMPTY
468
+ end
469
+ end
470
+
471
+ # The held members: the directive key => Fast::SFV::Item (or
472
+ # InnerList) view, frozen and ordered — the parse's order, or the
473
+ # construction Hash's. The bare values are the #[] view; the raw
474
+ # member data — parameters included — is here.
475
+ attr_reader :members
476
+
477
+ # The directive keys in held order, frozen.
478
+ attr_reader :keys
479
+
480
+ # §2.1's SHOULD-NOT-consume set: the keys whose values violate the
481
+ # inferred constraints, in held order — [] when the field is clean.
482
+ # Data, never a wire change: the values stay in #members and
483
+ # round-trip through to_s.
484
+ attr_reader :violating
485
+
486
+ # Strict construction — a sender never puts garbage on the wire:
487
+ # §2.1's "Implementations MUST NOT generate values that violate
488
+ # these inferred constraints." +members+ is a Hash of directive
489
+ # key => bare value: every value one of the five inferred types
490
+ # (a Boolean, an Integer, a Float, a Token or a plain String — a
491
+ # Byte Sequence, a Date, a Display String, an Array or nil is
492
+ # refused), a known directive's value carrying its section's type,
493
+ # the keys Structured Fields keys. Values freeze in place; each
494
+ # member wraps as an Fast::SFV::Item with no parameters (§2.1:
495
+ # parameters "are to be ignored", and no directive defines any, so
496
+ # a sender never invents the syntax). The empty Hash builds the
497
+ # empty value: a sender omits the field entirely — §3.1's own
498
+ # advice, "avoid sending a header field with an empty value, which
499
+ # would be ignored."
500
+ def initialize(members = {})
501
+ check_members!(members)
502
+ end
503
+
504
+ # The bare value of one directive — nil for an absent key. An inner
505
+ # list member's raw view is its items (a Dictionary value may be an
506
+ # InnerList, which has no #value).
507
+ def [](key)
508
+ member = @members[key]
509
+ return nil if member.nil?
510
+ return member.value if member.is_a?(Item)
511
+
512
+ member.items
513
+ end
514
+
515
+ # Does the field hold a member under +key+?
516
+ def key?(key)
517
+ @members.key?(key)
518
+ end
519
+
520
+ # How many directives the field holds.
521
+ def size
522
+ @members.size
523
+ end
524
+
525
+ # No directives held — an absent, empty or ignored field.
526
+ def empty?
527
+ @members.empty?
528
+ end
529
+
530
+ # Yields each held directive key and its bare value, in held order.
531
+ def each
532
+ @members.each do |key, member|
533
+ yield key, member.is_a?(Item) ? member.value : member.items
534
+ end
535
+ end
536
+
537
+ # The canonical wire form: the RFC 9651 §4.1.2 Dictionary
538
+ # serialization of the held members, "" when none are held (a
539
+ # sender omits the field entirely). Never raises: construction
540
+ # validated every value, and a parsed value re-emits its canonical
541
+ # form — what parsed round-trips faithfully, the violating values
542
+ # included (the flag is data, never a wire change), the explicit
543
+ # ?1 canonicalizing valueless.
544
+ def to_s
545
+ SFV.serialize_dict(@members) || ""
546
+ end
547
+
548
+ # Canonical-wire-form equality WITHIN the class: two fields are the
549
+ # same when they serialize the same.
550
+ def ==(other)
551
+ other.instance_of?(self.class) && to_s == other.to_s
552
+ end
553
+ alias eql? ==
554
+
555
+ # Consistent with eql? — the canonical form's hash.
556
+ def hash
557
+ to_s.hash
558
+ end
559
+
560
+ def inspect
561
+ wire = to_s
562
+ wire.empty? ? "#<#{self.class.name}>" : "#<#{self.class.name} #{wire}>"
563
+ end
564
+
565
+ private
566
+
567
+ # The construction boundary over a Hash of directive key => bare
568
+ # value, then the one place the held state is written, frozen: the
569
+ # members Hash, the keys view derived from it, the clean flag.
570
+ def check_members!(members)
571
+ raise SerializeError.new("members are a Hash (got #{members.class})", 0) unless members.is_a?(Hash)
572
+
573
+ held = {}
574
+ members.each do |key, value|
575
+ check_key!(key)
576
+ check_value!(key, value)
577
+ held[key] = Item.new(value.freeze, EMPTY_PARAMS)
578
+ end
579
+ hold(held, [])
580
+ end
581
+
582
+ # One directive's key at the boundary: the Structured Fields key
583
+ # grammar, RFC 9651 §4.2.3.3 read from the value side — a String
584
+ # whose first byte is lcalpha or "*" and whose bytes continue in
585
+ # lcalpha, DIGIT, "_", "-", "." or "*".
586
+ def check_key!(key)
587
+ return if valid_key?(key)
588
+
589
+ raise SerializeError.new("#{key.inspect} is not a Structured Fields key", 0)
590
+ end
591
+
592
+ # The walk behind check_key! — manual and allocation-free, the
593
+ # shape the substrate's own key parse uses.
594
+ def valid_key?(key)
595
+ return false unless key.is_a?(String)
596
+
597
+ size = key.bytesize
598
+ return false if size.zero? || !Scan::KEY_FIRST[key.getbyte(0)]
599
+
600
+ index = 1
601
+ while index < size
602
+ return false unless Scan::KEY_BODY[key.getbyte(index)]
603
+
604
+ index += 1
605
+ end
606
+ true
607
+ end
608
+
609
+ # One directive's value at the boundary: the constraint the parse
610
+ # walk reads (a known directive of its section's type, every value
611
+ # one of the five inferred types), refused here so no unvalidated
612
+ # value reaches the wire.
613
+ def check_value!(key, value)
614
+ return if self.class.send(:value_ok?, key, value)
615
+
616
+ raise SerializeError.new("#{key}: the value is #{rule_for(key)} (got #{value.inspect})", 0)
617
+ end
618
+
619
+ # The rule one directive's value must satisfy, worded for the
620
+ # message — the class-level rule_for, reached from the instance.
621
+ def rule_for(key)
622
+ self.class.send(:rule_for, key)
623
+ end
624
+
625
+ # The one place the held state is written, then frozen: the members
626
+ # Hash (frozen already on the parse path), the keys view derived
627
+ # from it, and the SHOULD-NOT-consume keys.
628
+ def hold(members, violations)
629
+ @members = members.freeze
630
+ @keys = members.keys.freeze
631
+ @violating = violations.freeze
632
+ freeze
633
+ end
634
+
635
+ # The shared frozen empty value: the answer an absent, empty or
636
+ # malformed field parses to — one object, stable identity. Defined
637
+ # at the end of the class body because the constant's initializer
638
+ # calls new, and initialize is defined above.
639
+ EMPTY = new({})
640
+ private_constant :EMPTY
641
+ end
642
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Fast
4
+ class ProxyStatus
5
+ VERSION = "0.1.0"
6
+ end
7
+ end