-
Notifications
You must be signed in to change notification settings - Fork 0
/
transform.rb
1145 lines (949 loc) · 37.3 KB
/
transform.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
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
248
249
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
320
321
322
323
324
325
326
327
328
329
330
331
332
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
require 'rdf'
require 'rdf/vocab'
require 'intertwingler/vocab/tfo'
require 'intertwingler/graphops'
require 'intertwingler/util'
require 'set'
require 'mimemagic'
require 'http/negotiate'
require 'time'
require 'intertwingler/handler'
require 'http/negotiate'
# This class represents the metadata about an individual service
# endpoint for a transformation function, and registers its
# parameters. It is meant to be congruent with the
# [`tfo:Function`](https://vocab.methodandstructure.com/transformation#Function)
# class in the [Transformation Functions
# Ontology](https://vocab.methodandstructure.com/transformation#).
class Intertwingler::Transform
include Intertwingler::GraphOps::Addressable
private
ITCV = Intertwingler::Vocab::ITCV
TFO = Intertwingler::Vocab::TFO
CI = Intertwingler::Vocab::CI
OWL = ::RDF::OWL
def engine ; harness.dispatcher.engine ; end
def repo; engine.repo; end
def resolver ; engine.resolver ; end
def registry ; engine.registry ; end
def coerce_params params
Intertwingler::Params.validate(params || {})
end
def coerce_types types
types ||= []
types = [types] unless types.is_a? Array
types.map { |t| t.is_a?(MimeMagic) ? t : MimeMagic[t.to_s] }
end
def gather_accepts_returns raw: false, predicate: TFO.accepts
literals = []
lists = []
objects(predicate).each do |o|
if o.literal?
literals << o
elsif o.blank?
lists << RDF::List.new(graph: repo, subject: o).to_a
end
end
# this is mainly to give us consistent results
out = (lists.sort.flatten + literals.sort).uniq
# raw as in raw literals
raw ? out : out.map { |o| MimeMagic[o.to_s] }
end
def fetch_types predicate
literals(predicate, datatype: TFO['content-type']).map do |x|
MimeMagic[x.to_s]
end
end
public
# this is meant to be called from a harness
def self.configure harness, subject
# haul together all the pieces
# give us the precious
new(harness, subject).refresh
end
# Initialize the representation of the transform.
#
# @param harness [Intertwingler::Transform::Harness] backreference
# to the harness (and by extension all the state data)
# @param subject [RDF::URI, URI] the subject URI
# @param implementation [RDF::URI, URI] the implementation URI
# @param params [Hash, Array, nil] any parameters to the
# @param accepts [Array<String,MimeMagic>] media types to accept
# @param returns [Array<String,MimeMagic>] media types to return
#
def initialize harness, subject, implementation: nil,
params: {}, accepts: [], returns: []
@harness = harness
@subject = resolver.coerce_resource subject
@impl = resolver.coerce_resource implementation if implementation
# we have to coerce params/accepts/returns
@params = registry[@subject] = coerce_params params
@accepts = coerce_types accepts
@returns = coerce_types returns
end
attr_reader :harness, :subject, :params
alias_method :id, :subject
# Return a dereferenceable URI for the transform. This is just a
# shorthand for `harness.resolver.uri_for subject`.
#
# @param as [:uri, :rdf, :str] coerce the return value to some other
# type.
#
# @return [URI, RDF::URI] the subject URI.
#
def uri as: :uri
@harness.resolver.uri_for @subject, as: as
end
# Return the implementation URI as something that can be passed a
# request (or not).
#
# @param as [:uri, :rdf, :str] cast the result to a type.
#
# @return [RDF::URI, URI] the address of the implementation.
#
def implementation as: :uri
resolver.coerce_resource @impl, as: as if @impl
end
# Refresh the state of the transform associated with the subject in
# the graph.
#
# @return [self]
#
def refresh
# get the implementation
@impl = resources(TFO.implementation).select do |o|
/^urn:x-ruby:/i.match? o.to_s
end.sort.first
# add the implementation to the dispatcher (via engine via
# harness; will be a noop if it's already in there)
# get the params. XXX this isn't exactly right. it should get the
# first tfo:parameter-list (there could be more than one of those,
# so it should disambiguate) and then look at tfo:parameter
# (though sorting those is an issue) if there are any that aren't
# defined in the list.
params = if pl = blanks(TFO['parameter-list']).sort.first
RDF::List.new(subject: pl, graph: repo).to_a.uniq
else
resources(TFO.parameter).sort
end
# note overloaded assignments do not return values so you can't
# just daisy-chain these two statements
registry[subject] = params
@params = registry[subject]
# get the accepts
@accepts = fetch_types TFO.accepts
# get the returns
@returns = fetch_types TFO.returns
# get the preferred serialization
@prefers = fetch_types(TFO.prefers).sort.first
self
end
# Determine if the _transform_ accepts the message body's content
# type.
#
# @param type [#to_s] the message body content type
#
# @return [false, true] whether the transform can parse it.
#
def accepts? type
type = MimeMagic[type.to_s.downcase]
headers = { Accept: @accepts.map { |t| t.to_s.downcase } }
variants = { type.to_s => { type: type.to_s } }
headers[:Accept] << type.to_s if !headers[:Accept].include?(type.to_s) and
headers[:Accept].any? { |t| type.descendant_of? t }
# don't forget the magic bullet
headers[:Accept] << '*/*;q=0'
# warn "headers: #{headers.inspect}, variants: #{variants.inspect}"
# warn "negotiated: #{HTTP::Negotiate.negotiate(headers, variants).inspect}"
!!HTTP::Negotiate.negotiate(headers, variants)
end
# Determine if the transform is capable of producing content the
# _caller_ will accept.
#
# @param types [Array<#to_s>] content types, either an `Accept:`
# header or split into an array.
#
# @return [false, true] whether the transform can satisfy the caller.
#
def returns? *types
headers = { Accept: types }
variants = @returns.map do |t|
t = t.to_s.downcase
[t, { type: t }]
end.to_h
!!HTTP::Negotiate.negotiate(headers, variants)
end
# Determine in one shot if the transform can process the message.
#
# @param header [#to_s, Array<#to_s>] the `Accept:` header, either
# whole or split into an array.
# @param type [#to_s] the message body `Content-Type`.
#
def can_process? header, type
returns?(header) and accepts?(type)
end
# Process a set of parameters.
#
# @param values [Object] can't remember what the type is
#
# @return [Params::Registry::Instance]
def process values
# warn @params.inspect
@params.process values
end
### BELOW THIS IS HANDLER/QUEUE STUFF
class ParamError < ::ArgumentError
# XXX TODO something coherent about which parameters were wrong
# (and irreparable by the transform) and a hint at what would fix
# them, preferably something machine-actionable so any prose can
# be localized (in addition to machine-actionable being generally
# good).
end
# A partial invocation is a collection of scalar parameter values
# *without* the message body input, such that all that is missing to
# complete the invocation is the input body itself. These are used
# to "curry" the transformation functions, for some interpretation
# of the term.
#
# Queues can accommodate either {Intertwingler::Transform}s or
# {Intertwingler::Transform::Partial}s. We use the latter when we
# want to statically configure a set of scalar parameters for a
# given transform. Indeed, the only time we would invoke this
# class's constructor directly is in the construction of addressable
# queues, when the parameters would be read off the request-URI.
#
class Partial
include Intertwingler::GraphOps::Addressable
private
def repo; transform.harness.dispatcher.engine.repo; end
def resolver ; transform.harness.dispatcher.engine.resolver ; end
public
def self.configure harness, subject, **rest
# get transform URI
transform = harness.dispatcher.engine.repo.objects_for(
subject, TFO.transform, only: :resource).sort.first
raise Intertwingler::Error::Config,
"partial #{subject} has no transform" unless transform
# get transform object
transform = harness.resolve transform
new(transform, subject: subject, **rest).refresh
end
def initialize transform, subject: nil, slug: nil, aliases: [], values: {}
@transform = transform
@subject = resolver.coerce_resource subject if subject
@slug = slug.to_s.to_sym if slug
@aliases = aliases.map { |a| a.to_s.to_sym }.sort.uniq
@params = transform.process(values) unless values.empty?
end
attr_reader :transform, :subject, :params
def refresh
if @subject
# get slug
@slug = literals(
CI['canonical-slug']).sort.map { |o| o.to_s.to_sym }.first
# get aliases
@aliases = literals(CI.slug).sort.map { |a| a.to_s.to_sym } - [@slug]
# get properties
@params = transform.process(
transform.params.keys.reduce({}) do |hash, k|
hash[k] = objects(k, entail: false).map do |o|
o.literal? ? o.object : o.to_s
end
hash
end)
end
self
end
# @!attribute [r] harness
# @return [Intertwingler::Transform::Harness]
def harness ; transform.harness ; end
end
# This is a union type to represent transforms in addressable queues
# that have the same name. It is possible that two or more
# transforms (represented by path parameters) have the same
# identifiers and arity, but different accept/return types. It may
# not be known which is viable until the response handler has been
# called. This class affords a superposition of transformation
# functions that can be determined when the necessary information is
# available.
#
# @note We anticipate this situation to arise when two functions do
# analogous things to different types, or otherwise, e.g., when the
# name of two completely _different_ functions is lexically
# identical when spelled in another language.
class Union < Partial
end
# This is intended to mirror `tfo:Invocation`, which is just a
# record of a particular invocation of a particular function with
# particular parameters and a particular input, which should always
# yield a particular output. There is almost no role for this beyond
# resolving cached transformations.
class Invocation < Partial
end
# This class represents an ordered collection of transforms. "Queue"
# is a slight misnomer as it's more like a _bag_ of transforms that
# will be sorted topologically when given a request, if not given an
# explicit sequence upon initialization. An explicit sequence
# supersedes the topological sort; unordered transforms will be
# ignored when it is present. An ordinary transform queue will
# attempt to run everything in its (potentially
# dynamically-determined) sequence, ignoring those transforms that
# do not match the intersection of least one available return type,
# and the content of the client's `Accept` header.
#
#
# I call the unordered incarnation of a transform queue a _bag_
# rather than a _set_ because some transforms may not match the
# payload or the request's `Accept:` header and will thus not be
# run. Conversely, two or more transforms can be *punned* into the
# same (human-readable) identifier, implying they do analogous
# things for different content-types.
class Queue
include Intertwingler::GraphOps::Addressable
# A strict queue differs from an ordinary queue insofar as *all*
# transforms in the queue *must* be run. This means a strict queue
# is liable to generate an error if *any* of its constituent
# transforms don't match the payload, *including* (and
# *especially*) transforms that are intended to process the result
# of a previous one. In general it only makes sense for a strict
# queue to be addressable, but we won't prevent you from using
# strict queues in other places.
class Strict < self
#
def can_serve! uri, type
raise "nope can't serve, lol"
end
end
# An addressable queue is a strict queue that is run in the
# addressable phase of response transforms, typically sandwiched
# between an early queue and a late queue. If more than one
# addressable queue is specified in the chain of transformation
# queues, then only the *last* addressable queue will be treated
# as such, while any preceding addressable queues will be treated
# as ordinary strict queues. This will probably be undesirable, so
# ensure that only one addressable queue is present in the chain.
class Addressable < Strict
end
private
def repo; harness.dispatcher.engine.repo; end
def initialize_copy *args
# warn 'sup lol'
@transforms = @transforms.dup
super
end
public
# Configure the queue out of the graph.
#
# @param harness [Intertwingler::Transform::Harness]
# @param subject [RDF::URI]
#
# @return [Intertwingler::Transform::Queue]
#
def self.configure harness, subject
new(harness, subject).refresh
end
# Initialize a (potentially empty) queue.
#
# @param harness [Intertwingler::Transform::Harness]
# @param subject [RDF::URI]
# @param transforms [Array<Intertwingler::Transform,
# Intertwingler::Transform::Partial>]
# @param next [nil, RDF::URI]
#
def initialize harness, subject, transforms: [], next: nil
@harness = harness
@subject = subject
@transforms = transforms || []
@next = binding.local_variable_get :next # next is a keyword
end
attr_reader :harness, :subject, :next
alias_method :id, :subject
# Refresh the queue against the graph.
#
# @return [self]
#
def refresh
# deal with list
if list = blanks(TFO['member-list']).sort.first
list = ::RDF::List.new(graph: repo, subject: list).to_a
@transforms = list.map do |member|
harness.resolve member, queues: false, partials: true, refresh: true
end
else
@transforms = []
end
# deal with next queue
if qnext = resources(TFO.next).sort.first
# qnext = harness.resolve qnext,
# transforms: false, partials: false, refresh: true
# XXX here is where we should check for cycles
@next = qnext
else
@next = nil
end
self
end
# This is like Array#push.
#
# @param member [Intertwingler::Transform,
# Intertwingler::Transform::Partial, RDF::URI]
#
def push member
# XXX this may blow up?
member = harness.resolve member
@transforms << member
end
alias_method :<<, :push
# Determine if the queue is strict.
#
# @return [false, true]
#
def strict?
is_a? Strict
end
# Determine if the queue is addressable.
#
# @return [false, true]
#
def addressable?
is_a? Addressable
end
private
# Test if the transform accepts the `Content-Type`. Intended to
# provide a hook to subclasses to raise an error if false.
def can_serve! transform, type
# XXX change this when we have a regime we can stand
transform.accepts? type
end
public
# Run this queue and return the altered message. Include the
# response in the second argument if this is a response queue.
#
# @note {::Rack::Response} has no reference back to the
# {::Rack::Request} that it responds to, so the request is always needed.
#
# @param req [Rack::Request] the request, upon which to base the subrequest.
# @param resp [Rack::Response, nil] the response, to use in response queues.
#
# @return [Rack::Request, Rack::Response] the resulting HTTP message.
#
def run req, resp = nil
# get some shortcuts
dispatcher = harness.dispatcher
engine = dispatcher.engine
resolver = engine.resolver
log = engine.log
# for each transform in the queue
# first we test if it accepts the message body (or is message/http)
# we gin up a POST subrequest for its uri + params if applicable
# we use the dispatcher to run the subrequest
# we shuck off the response body from the subrequest (TODO full http msg)
# if there is a subsequent transform, we repeat
# if not we try the next queue
# if no queues left, we return the message with the new body
# XXX okay here is where we whine if we run the whole queue and
# e.g. the Accept: header does not match
# if this is a response transform then resp will be non-nil
out = resp || req
body = out.body # note the body is different depending on req or resp
type = out.content_type || 'application/octet-stream'
# type = out.get_header( # so is this and that is dumb af
# out.is_a?(Rack::Request) ? 'CONTENT_TYPE' : 'content-type') ||
# 'application/octet-stream'
type = MimeMagic[type].canonical || MimeMagic['application/octet-stream']
log.debug "#{resp ? 'response' : 'request'} type #{type.inspect}"
# don't screw around dupping the message if there are no transforms
return out if @transforms.empty?
# transforms could be transforms or they could be partials; in
# the case that they're partials, we want to pull the parameters
# out and append them to the uri
@transforms.each_with_index do |transform, i|
if transform.is_a? Intertwingler::Transform::Partial
params = transform.params.to_h
transform = transform.transform
else
params = {}
end
# we just override this in strict
next unless can_serve! transform, type
# this already should be a uuid but eh
uuid = resolver.uuid_for transform.subject, as: :uri
# first check if the transform matches typewise
# XXX TODO handle `message/http`; not doing that one yet lol
uri = URI(req.base_url) + uuid.uuid
uri.query = URI.encode_www_form(params) unless params.empty?
log.debug "about to POST #{type} to #{uri}"
headers = { 'content-type' => type.to_s }
# note we pun the content-location header to communicate to
# the subrequest what entity it's looking at; this is totally
# legal to use this header in a request, go look it up:
# https://datatracker.ietf.org/doc/html/rfc9110#section-8.7
# but we only add this for response transforms
headers['content-location'] = req.url if resp
subreq = engine.dup_request req, uri: uri, method: :POST,
headers: headers, body: body
subresp = dispatcher.dispatch subreq, subrequest: true
# here is where we would break if this was an error or redirect
unless subresp.successful?
# XXX any failure in here is bad except 304 which is considered a noop
next if subresp.status == 304
# basically no matter what the situation is here it's a
# misconfiguration
raise Intertwingler::Handler::Error::Server,
"Transform #{uuid} returned error #{subresp.status}: #{subresp.body}"
# XXX HANDLE REDIRECTS WITH DEPTH LIMIT/CYCLE DETECTION: a
# redirect that is to the same URI but different
# parameters/values is legitimate and should bubble up IF
# AND ONLY IF the queue is addressable, otherwise we should
# silently follow the redirects (and blow up if it loops).
end
# warn "dios mio: " + subresp.inspect
# reassign content type
if type = subresp.get_header('content-type')
type = MimeMagic[type]
btype = subresp.body.type if subresp.body.respond_to? :type
type = btype if btype and btype != type and btype.descendant_of? type
# warn "btype: #{btype.inspect} #{btype.descendant_of? type}"
else
raise Intertwingler::Handler::Error::Server,
'Transform #{uuid} did not return a Content-Type header'
end
# reassign body
body = subresp.body
# XXX content-encoding content-language etc etc
end
# these headers are the same for either request or response
hdr = { 'content-type' => type.to_s, 'content-length' => nil }
hdr['content-length'] = body.size.to_s if body.respond_to? :size
# we shouldn't do this if nothing has been run
if resp
out = engine.replace_response_body out, body, headers: hdr
else
out = engine.dup_request req, body: body, headers: hdr
end
out
end
end
# A queue chain is like a disposable queue of queues. When a chain
# is created (e.g., with each HTTP request), it collects its
# constituent queues and creates shallow copies, enabling them to be
# manipulated over the course of the request without damaging the
# originals. The basic {Intertwingler::Transform::Chain} is an
# abstract class, with the (marginally) more specialized request and
# response chains building off of it.
#
class Chain
# Initialize a new queue chain. The `head` is the leading queue in
# the chain. We successively call `next` on the queues to build up
# a sequence and check for cycles.
#
# @param harness [Intertwingler::Transform::Harness] the transform
# harness that has all the master copies of everything.
# @param head [RDF::URI, Intertwingler::Transform::Queue] the
# initial queue to traverse to construct the chain.
#
def initialize harness, queue = nil
@harness = harness
@queues = {}
if queue and qobj = harness.resolve(queue)
@queues[queue] = qobj.dup
while queue = qobj.next
qobj = harness.resolve(queue)
raise Intertwingler::Error::Config,
"Cycle detected in queue #{queue}" if @queues.key? queue
@queues[queue] = qobj.dup
end
end
end
# Run the queues in the chain over the message and get back the
# transformed message.
#
# @note Unfortunately {Rack::Response} does not include a
# reference to the {Rack::Request} that called it, so we have to
# pass in both even if we only need one.
#
# @param request [Rack::Request] the HTTP request.
# @param response [nil, Rack::Request] the HTTP response, if
# applicable.
#
# @return [Rack::Request, Rack::Response] the transformed message.
#
def run request, response = nil
message = response || request
@queues.values.each do |q|
message = q.run request, response do |event|
# do stuff with side effects
end
# don't forget to reassign or this hands the unchanged one down the line
if response
response = message
else
request = message
end
# warn "in chain loop (#{q.subject}): #{message.content_type}"
end
message
end
# A request chain differs from a response chain insofar as it
# stores up state from request transforms to pass on to the
# response transforms. A factory method {#response_chain} then
# produces the appropriate chain to complete the response
# transforms.
class Request < self
# Apply all the request queues to the request (and collect any
# side effects).
#
# @param request [Rack::Request] an HTTP request.
#
# @return [Rack::Request] the transformed request.
#
def run request
super request
end
# Return the appropriate response chain for the given handler.
#
# @param handler [RDF::URI, URI] the address of the handler selected
# by the dispatcher.
# @param pp [nil, Array] optional path parameters
#
# @return [Intertwingler::Transform::Chain::Response] the response chain.
#
def response_chain handler, pp: nil
head = @harness.queue_head_for handler
warn "generating response chain for #{handler} lol: #{head.inspect}"
Intertwingler::Transform::Chain::Response.new @harness, head,
pp: pp, insertions: @insertions
end
end
# A response chain extends the abstract chain class with methods
# used to manipulate insertion events and addressable queues.
class Response < self
# Initialize a response chain.
#
# @param harness [Intertwingler::Transform::Harness]
# @param head [RDF::URI]
# @param pp [nil, Array]
# @param insertions [nil, Array]
#
def initialize harness, head, pp: nil, insertions: nil
super harness, head
set_addressable(*pp) if pp
apply_insertions insertions if insertions
end
# Transform the response.
#
# @param request [Rack::Request] an HTTP request.
# @param response [Rack::Response] an HTTP response.
#
# @return [Rack::Response] the transformed response.
#
def run request, response
super request, response
end
# Determine if the chain contains an addressable queue.
#
# @return [false, true] whether or not the chain has an
# addressable queue.
#
def has_addressable?
@queues.values.any? { |q| q.addressable? }
end
# Set the addressable queue in the chain.
def set_addressable *pp
warn "path parameters: #{pp}"
self
end
end
end
# The transformation harness is the part of the
# {Intertwingler::Engine} responsible for organizing and running the
# sequence of {Transform}s that manipulate the HTTP message on its
# way into, and out from, a {Intertwingler::Handler}. The proximate
# entities managed by the harness are transformation {Queue}s:
#
# * A queue can reference a subsequent queue (which can potentially
# cycle, which would be an error).
# * Queues contain either {Transform}s, or {Partial} invocations.
# * Every valid partial invocation _must_ point to a transform.
# * Transforms may reference an {Intertwingler::Params::Group}
# (keyed by the same subject URI), which in turn may share
# {Intertwingler::Params::Template} instances with other groups.
# * Transforms _must_ reference an {Intertwingler::Handler}, which
# supplies the actual implementation, and therefore _must_ respond
# to the same (resolved) URI as the transform itself.
# * Handlers may specify their own queues; lather, rinse, repeat.
#
# The engine's configuration record specifies entry points for both
# request and response queues. Other entry points (for response
# queues only) can be found attached to handler configurations. The
# queue records are then traversed to build up the entire structure.
#
# @note Since its internal state may change over the lifetime of a
# request, the harness must be duplicated at the beginning of every
# request, and that duplicate is the copy that ought to be used.
#
# @note XXX: this thing will never get used outside of the context
# of the dispatcher, so perhaps it should either be attached to the
# _dispatcher_ instead of the _engine_. Another option is to just
# merge this with the dispatcher, or the dispatcher with it.
#
class Harness
include Intertwingler::GraphOps::Addressable
private
def repo ; dispatcher.engine.repo ; end
def subject ; dispatcher.engine.subject ; end
def resolver ; dispatcher.engine.resolver ; end
public
# Inititalize the harness and populate it with configuration from
# the graph.
#
# @param dispatcher [Intertwingler::Engine::Dispatcher]
#
# @return [Intertwingler::Transform::Harness]
#
def self.configure dispatcher
new(dispatcher).refresh
end
# Initialize an empty harness. This will do nothing and it must be
# populated separately.
#
# @param dispatcher [Intertwingler::Engine::Dispatcher]
# @param queues [Array]
# @param request_head [RDF::URI] the default request queue head
# @param response_head [RDF::URI] the default response queue head
#
def initialize dispatcher, queues: [], request_head: nil, response_head: nil
# the dispatcher
@dispatcher = dispatcher
# maps
@queues = {}
@transforms = {}
@partials = {}
@handler_map = {}
# queue heads
@request_head = resolver.coerce_resource request_head if request_head
@response_head = resolver.coerce_resource response_head if response_head
end
# Refresh (recursively) the configuration in the graph.
#
# @return [self]
#
def refresh
@request_head = resources(ITCV['request-queue']).sort.first
@response_head = resources(ITCV['response-queue']).sort.first
# this is probably enough to get things started, actually
qs = [@request_head, @response_head]
while q = qs.shift
# warn "resolving queue #{q}"
qobj = resolve q, transforms: false, partials: false, refresh: true
qs << qobj.next if
qobj.next and !qs.include?(qobj.next) and [email protected]?(qobj.next)
end
#
self
end
private
# just making a mess here really
def resolve_queue uri, state, force: nil
return @queues[uri] if @queues.key? uri and !force
@queues[uri] = Intertwingler::Transform::Queue.configure self, uri
end
def resolve_transform uri, state, force: nil
return @transforms[uri] if @transforms.key? uri and !force
tfi = @transforms[uri] = Intertwingler::Transform.configure self, uri
# XXX this will not be necessary with manifest protocol; the
# dispatcher will just ask for the handler's manifest.
dispatcher.add_route uri, tfi.implementation, method: :POST
tfi
end
def resolve_partial uri, state, force: nil
return @partials[uri] if @partials.key? uri and !force
@partials[uri] = Intertwingler::Transform::Partial.configure self, uri
end
def resolve_handler uri, state, force: nil
engine.dispatcher.add uri, queues: false
if queue = repo.objects_for(uri, ITCV.queue, only: :resource).sort.first
queue = resolve_queue queue, state
@handlers[uri] = queue
end
end
def resolve_one uri, state, force: nil
ts = repo.asserted_types uri
if repo.type_is?(ts, TFO.Partial) and !repo.type_is?(ts, TFO.Invocation)
resolve_partial uri, state, force: force
elsif repo.type_is? ts, TFO.Function
resolve_transform uri, state, force: force
elsif repo.type_is? ts, TFO.Queue
resolve_queue uri, state, force: force
else
raise ArgumentError,
"Not sure what to do with #{uri} of type #{ts.join ?,}"
end
end
public
def resolve uri, queues: true, transforms: true, partials: true,
refresh: false
uri = resolver.coerce_resource uri
state = {}
resolve_one uri, state
end
attr_reader :dispatcher, :request_head, :response_head
# @!attribute [r] dispatcher
# @return [Intertwingler::Engine::Dispatcher] The dispatcher from
# the engine.
# @!attribute [rw] request_head
# @note The URI *must* already be known to the harness. The chain
# of queues will be recalculated on assignment.
# @return [RDF::URI] The initial *request* queue's URI.
# @raise [ArgumentError] on assignment, if it doesn't like your URI.
#
def request_head= uri
if uri
uri = engine.resolver.coerce_resource uri
register? uri
@request_head = uri
end
end
# @!attribute [rw] response_head
# @note The URI *must* already be known to the harness. The chain
# of queues will be recalculated on assignment.
# @return [RDF::URI] The initial *response* queue's URI.
# @raise [ArgumentError] on assignment, if it doesn't like your URI.
#
def response_head= uri
if uri
uri = engine.resolver.coerce_resource uri
register? uri
@response_head = uri
end
end
# Return the request transform chain.
#
# @return [Intertwingler:Transform::Chain::Request]
#
def request_chain
# warn "request head: #{request_head.inspect}"
Intertwingler::Transform::Chain::Request.new self, request_head
end
def queue_head_for handler
handler = resolver.coerce_resource handler
@handler_map[handler] || response_head
end
end
# This is the actual transform _handler_ class, that includes a number
class Handler < Intertwingler::Handler
private
NUMBER_RE = /^[+-]?(?=\.?\d)\d*\.?\d*(?:[Ee][+-]?\d+)?\z/
TOKEN_RE = /[^\x0-\x20\x7f-\xff()<>@,;:\\"\/\[\]?={}]+/n # srsly??