phlex-reactive 0.17.0 → 0.19.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.
@@ -18,7 +18,9 @@
18
18
 
19
19
  # verify_authorized (ON by default): an action that completes WITHOUT any
20
20
  # authorization call raises Phlex::Reactive::AuthorizationNotVerified inside the
21
- # transaction — the mutation rolls back (fail-closed). Satisfy it by calling one
21
+ # transaction — the mutation rolls back (fail-closed; an action declared
22
+ # `transaction: false` has no endpoint transaction to roll back). Satisfy
23
+ # it by calling one
22
24
  # of authorization_methods, calling `mark_authorized!` after a bespoke check, or
23
25
  # declaring `skip_verify_authorized` on a genuinely public component/action.
24
26
  # Set the method names to match your authorization library:
@@ -56,7 +56,10 @@ module Phlex
56
56
  end
57
57
 
58
58
  # The enforcement decision, called by the endpoint AFTER the action runs,
59
- # INSIDE the transaction (so a raise rolls the mutation back). A no-op
59
+ # INSIDE the transaction (so a raise rolls the mutation back) — except for
60
+ # an action declared `transaction: false` (issue #481), which has no
61
+ # endpoint transaction: the raise still fails the request, but the
62
+ # endpoint rolls back nothing the action already wrote. A no-op
60
63
  # unless verify_authorized is on, the action isn't skipped, and nothing
61
64
  # marked the window. Otherwise raises AuthorizationNotVerified naming the
62
65
  # component#action and the three remedies.
@@ -302,8 +302,19 @@ module Phlex
302
302
  # }
303
303
  # Array params accept BOTH a JSON array and a Rails-style index hash
304
304
  # ({ "0" => ..., "1" => ... }), so a fields_for collection works either way.
305
- def action(name, params: {})
305
+ #
306
+ # `transaction: false` (issue #481) runs this one action without the
307
+ # endpoint's transaction, for an action that waits on something slow
308
+ # that is not the database (a remote API). verify_authorized still
309
+ # raises after it, but there is nothing to roll back: authorize before
310
+ # any side effect, and wrap the writes in your own transaction.
311
+ # action :refresh, transaction: false
312
+ def action(name, params: {}, transaction: true)
306
313
  require_server_actions!(:action)
314
+ unless [true, false].include?(transaction)
315
+ raise ArgumentError,
316
+ "action #{name.inspect} transaction: must be true or false, got #{transaction.inspect}"
317
+ end
307
318
  # Issue #276: the endpoint routes `__materialize` to the lazy render
308
319
  # before the action registry is consulted — a declared one would be
309
320
  # dead code that looks invokable.
@@ -323,7 +334,9 @@ module Phlex
323
334
  assert_no_scope_double_nesting!(scope, params, name.to_sym) if scope
324
335
  Registry.write_entry(
325
336
  self, :actions, name.to_sym,
326
- ActionDefinition.new(name: name.to_sym, params: params, schema: Phlex::Reactive::ParamSchema.compile(params))
337
+ ActionDefinition.new(
338
+ name: name.to_sym, params: params, schema: Phlex::Reactive::ParamSchema.compile(params), transaction:
339
+ )
327
340
  )
328
341
  end
329
342
 
@@ -91,7 +91,20 @@ module Phlex
91
91
  # autoloading (Kit's LazyLoader resolves through the calling class's
92
92
  # const_get). Keep every constant here suffixed / implausible as a kit
93
93
  # component name — and never alias the old name back.
94
- ActionDefinition = Data.define(:name, :params, :schema)
94
+ #
95
+ # `transaction` (issue #481) is whether the endpoint runs the action inside
96
+ # its transaction wrapper: true unless declared `transaction: false`. It
97
+ # defaults here too, so a caller that builds a definition with only
98
+ # name/params/schema keeps working.
99
+ ActionDefinition = Data.define(:name, :params, :schema, :transaction) do
100
+ def initialize(name:, params:, schema:, transaction: true)
101
+ unless [true, false].include?(transaction)
102
+ raise ArgumentError, "transaction: must be true or false, got #{transaction.inspect}"
103
+ end
104
+
105
+ super
106
+ end
107
+ end
95
108
 
96
109
  # A declared client-side computation (data binding). `inputs`/`outputs` are
97
110
  # the action-param names of the fields the reducer reads/writes; `reducer`
@@ -60,11 +60,17 @@ module Phlex
60
60
  return [[info.name, "(no actions)", "", location_str(info.path), ""]] if info.actions.empty?
61
61
 
62
62
  info.actions.map do
63
- [info.name, it.name.to_s, params_str(it.params),
63
+ [info.name, action_str(it), params_str(it.params),
64
64
  location_str(it.source_location), auth_str(it)]
65
65
  end
66
66
  end
67
67
 
68
+ # The action's name, marked when it runs without the endpoint's
69
+ # transaction (issue #481). Every other row prints the bare name.
70
+ def action_str(action)
71
+ action.transaction ? action.name.to_s : "#{action.name} (no endpoint transaction)"
72
+ end
73
+
68
74
  # A minimal fixed-column table: each column padded to its widest cell.
69
75
  # No ANSI, no external dependency.
70
76
  def render_table(headers, rows)
@@ -94,6 +100,7 @@ module Phlex
94
100
  header = " action :#{action.name}"
95
101
  header += " params: #{params_str(action.params)}" unless action.params.empty?
96
102
  header += " (#{location_str(action.source_location)}) auth: #{auth_str(action)}"
103
+ header += " transaction: false" unless action.transaction
97
104
  body = action.definition ? indent(action.definition) : " (method not defined)"
98
105
  [header, body, ""]
99
106
  end
@@ -125,7 +132,8 @@ module Phlex
125
132
  source_location: location_str(action.source_location),
126
133
  authorization_call_detected: action.authorization_call_detected?,
127
134
  authorization: action.authorization_state.to_s,
128
- authorization_skip: action.authorization_skip&.to_s
135
+ authorization_skip: action.authorization_skip&.to_s,
136
+ transaction: action.transaction
129
137
  }
130
138
  end
131
139
 
@@ -34,7 +34,12 @@ module Phlex
34
34
  # * authorization_skip — :class (a bare skip_verify_authorized, own or
35
35
  # inherited), :action (this action is named in one),
36
36
  # or nil. The author's declared opt-out (issue #278).
37
- ActionInfo = Data.define(:name, :params, :source_location, :definition, :authorization_skip) do
37
+ # * transaction — false when the action is declared
38
+ # `transaction: false` and runs without the
39
+ # endpoint's transaction (issue #481), else true.
40
+ ActionInfo = Data.define(:name, :params, :source_location, :definition, :authorization_skip, :transaction) do
41
+ def initialize(name:, params:, source_location:, definition:, authorization_skip:, transaction: true) = super
42
+
38
43
  # Was any authorization method (or mark_authorized!) called directly in
39
44
  # the method body? Heuristic — a Prism scan of `definition`. False when
40
45
  # the definition is unavailable.
@@ -176,7 +181,8 @@ module Phlex
176
181
  params: action.params,
177
182
  source_location: location,
178
183
  definition: (extract_definition(location) if location),
179
- authorization_skip: authorization_skip(klass, action.name)
184
+ authorization_skip: authorization_skip(klass, action.name),
185
+ transaction: action.transaction
180
186
  )
181
187
  end
182
188
 
@@ -17,7 +17,9 @@ module Phlex
17
17
  mark_authorized! call was detected in the body — advisory only, since a
18
18
  helper may authorize indirectly), plus `authorization` — detected,
19
19
  skipped (declared skip_verify_authorized; `authorization_skip` says
20
- class or action) or none. Pass `component:` to scope to one
20
+ class or action) or none, and `transaction` — false when the action
21
+ is declared `transaction: false` and runs without the endpoint's
22
+ transaction. Pass `component:` to scope to one
21
23
  component (exact name). Read-only — schemas and paths, never runtime
22
24
  values.
23
25
  DESC
@@ -15,8 +15,9 @@ module Phlex
15
15
  Fuzzy-find reactive components by name (exact > prefix > substring >
16
16
  subsequence, on both the demodulized and full name). Returns the ranked
17
17
  matches, each with its actions' param schema, source location,
18
- authorization (detected / skipped / none, plus the skip form), and the
19
- full method-definition SOURCE
18
+ authorization (detected / skipped / none, plus the skip form), its
19
+ transaction flag (false for `transaction: false`), and the full
20
+ method-definition SOURCE
20
21
  (extracted with Prism). Read-only.
21
22
 
22
23
  NOTE: unlike the other tools (which report names/paths/schemas only),
@@ -56,6 +57,7 @@ module Phlex
56
57
  authorization_call_detected: action.authorization_call_detected?,
57
58
  authorization: action.authorization_state.to_s,
58
59
  authorization_skip: action.authorization_skip&.to_s,
60
+ transaction: action.transaction,
59
61
  # The full method SOURCE — this is the one field that exposes an
60
62
  # action body verbatim (see the tool description). A secret hardcoded
61
63
  # in an action would surface here; keep secrets out of action bodies.
@@ -131,9 +131,10 @@ module Phlex
131
131
 
132
132
  # Mark targets PENDING and let the app's own job settle them (issue #248).
133
133
  # For an action that ENQUEUES the work rather than doing it: the endpoint
134
- # renders the reply inside the transaction while the queue publishes on
135
- # commit, so a `reply.morph` after an enqueue is guaranteed to draw the
136
- # pre-job world. This replies truthfully instead.
134
+ # renders the reply inside the transaction, so publish-on-commit keeps a
135
+ # `reply.morph` after an enqueue on the pre-job world. With
136
+ # `transaction: false` the enqueue can publish at once and the job races
137
+ # the render. This replies truthfully either way.
137
138
  #
138
139
  # def re_execute(transfer_id:)
139
140
  # transfer = @bulk_payment.transfers.re_executable.find(transfer_id)
@@ -67,11 +67,14 @@ module Phlex
67
67
  # integration uses, and it looked like the enqueue-time hook — but under
68
68
  # Rails' `enqueue_after_transaction_commit = true` (the 7.2+ recommended
69
69
  # setting) `job.enqueue` is deferred to
70
- # ActiveRecord.after_all_transactions_commit, and the endpoint runs every
71
- # action inside a transaction. So the deferral — and with it `serialize` —
72
- # always fires AFTER reply.pending's `with_handle` block has exited, with
70
+ # ActiveRecord.after_all_transactions_commit, and the endpoint runs a
71
+ # default action inside a transaction. So for such an action the deferral
72
+ # — and with it `serialize` — fires AFTER reply.pending's `with_handle`
73
+ # block has exited, with
73
74
  # an empty thread-local: no metadata key, a no-op `reactive_settle`, and a
74
- # row left shimmering until someone reloads.
75
+ # row left shimmering until someone reloads. (A `transaction: false`
76
+ # action with no enclosing transaction enqueues at once, inside the block;
77
+ # capturing at instantiation covers both.)
75
78
  #
76
79
  # `new` is the one moment guaranteed to be inside the block:
77
80
  # `perform_later` → `job_or_instantiate` → `new` is synchronous, deferral
@@ -25,9 +25,16 @@ module Phlex
25
25
  # pgbus only: the src is a pgbus signed stream name, the one
26
26
  # pgbus_stream_from (and turbo_stream_from under pgbus) renders. Without
27
27
  # pgbus (Action Cable) a subscribing root raises ConfigurationError at
28
- # render, naming turbo_stream_from as the alternative. There is no replay:
29
- # a broadcast sent before the source connects is missed (pgbus streams are
30
- # ephemeral by default), as with any live subscription.
28
+ # render, naming turbo_stream_from as the alternative.
29
+ #
30
+ # Catching up (issue #478). A durable stream's root also carries the
31
+ # stream's watermark at render (data-reactive-subscribe-since, read the
32
+ # way pgbus_stream_from reads it), and its source replays from there: a
33
+ # broadcast sent between the render and the connection still arrives. An
34
+ # ephemeral stream (pgbus's default) has no archive to replay, so it gets
35
+ # no watermark; the client dispatches reactive:subscribed on the root each
36
+ # time its source connects, and a component that must not miss a change
37
+ # refetches on it.
31
38
  module Subscribe
32
39
  # What reactive_subscribe declared: the stream name's last part (nil
33
40
  # with key:), and key: — the stream's parts as an Array, or a callable
@@ -70,6 +77,20 @@ module Phlex
70
77
 
71
78
  # The signed SSE URL a <pgbus-stream-source> subscribes with.
72
79
  def source_src(stream_name) = Phlex::Reactive::Defer.stream_src(stream_name)
80
+
81
+ # The since-id the source replays from: a durable stream's watermark
82
+ # (MAX msg_id, 0 for a stream nothing was published to yet), read live
83
+ # like pgbus_stream_from reads it. nil for an ephemeral stream (no
84
+ # archive to replay) or a pgbus that cannot tell. One query per render
85
+ # of a durable subscribing root, never cached: pgbus's own cache is
86
+ # cleared only between Rack requests, and a broadcast renders in a job.
87
+ def since_id(stream_name)
88
+ config = ::Pgbus.configuration if ::Pgbus.respond_to?(:configuration)
89
+ return unless config.respond_to?(:stream_durable?) && config.stream_durable?(stream_name)
90
+
91
+ stream = ::Pgbus.stream(stream_name)
92
+ stream.current_msg_id if stream.respond_to?(:current_msg_id)
93
+ end
73
94
  end
74
95
 
75
96
  # What reactive_subscribe adds to a component's instances. Included only
@@ -95,11 +116,15 @@ module Phlex
95
116
  end
96
117
 
97
118
  # The root's subscription marker (reactive_attrs): the signed src the
98
- # client mints its <pgbus-stream-source> from.
119
+ # client mints its <pgbus-stream-source> from, and for a durable stream
120
+ # the watermark it replays from (issue #478).
99
121
  def reactive_subscribe_data
100
122
  Subscribe.require_capable!(self.class)
101
123
  name = Subscribe.stream_name(self.class, reactive_subscribe_parts)
102
- { reactive_subscribe: Subscribe.source_src(name) }
124
+ data = { reactive_subscribe: Subscribe.source_src(name) }
125
+ since = Subscribe.since_id(name)
126
+ data[:reactive_subscribe_since] = since unless since.nil?
127
+ data
103
128
  end
104
129
 
105
130
  private
@@ -20,7 +20,8 @@ module Phlex
20
20
  #
21
21
  # The driver goes THROUGH the endpoint's security contract on purpose —
22
22
  # default-deny, signed identity round-trip (record re-find), schema coercion,
23
- # the same transaction wrapper. A helper that skipped it would teach users to
23
+ # the same transaction wrapper (skipped for a `transaction: false` action,
24
+ # as the endpoint skips it). A helper that skipped it would teach users to
24
25
  # test a component that would fail at the real endpoint.
25
26
  #
26
27
  # NB: `verbose_errors` defaults ON in the test env (Rails.env.local? — issue
@@ -90,7 +91,8 @@ module Phlex
90
91
  # 3. coercion — params pass through the action's compiled ParamSchema
91
92
  # (issue #109); undeclared keys are dropped, declared ones cast.
92
93
  # 4. transaction — run inside the endpoint's transaction wrapper so
93
- # after_commit broadcasts behave.
94
+ # after_commit broadcasts behave, unless the action is declared
95
+ # `transaction: false` (issue #481), as at the endpoint.
94
96
  # 5. authorization — a registered authorization error RAISES (the endpoint
95
97
  # maps it to 403; a unit test asserts the real exception).
96
98
  #
@@ -185,12 +187,24 @@ module Phlex
185
187
  end
186
188
  end
187
189
 
188
- # Run inside the endpoint's transaction wrapper. `coerced` already has
189
- # symbol keys (ParamSchema#coerce symbolizes to splat as kwargs), so we
190
- # splat it exactly as the endpoint does. Kept tiny and dependency tolerant:
191
- # no ActiveRecord (a state-only component in a bare app) just yields.
190
+ # Run inside the endpoint's transaction wrapper, unless the action is
191
+ # declared `transaction: false` (issue #481), exactly as the endpoint
192
+ # decides. `coerced` already has symbol keys (ParamSchema#coerce
193
+ # symbolizes to splat as kwargs), so we splat it exactly as the endpoint
194
+ # does. Kept tiny and dependency tolerant: no ActiveRecord (a state-only
195
+ # component in a bare app) just yields.
192
196
  def run_reactive_action(component, action_def, coerced)
193
- transaction_wrapper do
197
+ return invoke_reactive_action(component, action_def, coerced) unless action_def.transaction
198
+
199
+ transaction_wrapper { invoke_reactive_action(component, action_def, coerced) }
200
+ end
201
+
202
+ # Inside a verify_authorized tracking window, as at the endpoint, so a mark
203
+ # (mark_authorized!, an intercepted authorization call) is scoped to this
204
+ # action and never left set on the thread for the next test. The driver
205
+ # does not run verify! itself: an unauthorized action still returns.
206
+ def invoke_reactive_action(component, action_def, coerced)
207
+ Phlex::Reactive::Authorization.with_tracking do
194
208
  if coerced.any?
195
209
  component.public_send(action_def.name, **coerced)
196
210
  else
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Phlex
4
4
  module Reactive
5
- VERSION = "0.17.0"
5
+ VERSION = "0.19.0"
6
6
  end
7
7
  end
@@ -59,7 +59,8 @@ module Phlex
59
59
  # Raised when the default-ON verify_authorized guard (issue #168) finds an
60
60
  # action completed WITHOUT any authorization call — the fail-closed
61
61
  # presence-side complement to authorization_errors. It fires INSIDE the
62
- # action's transaction, so the mutation rolls back, and it is NOT rescued
62
+ # action's transaction, so the mutation rolls back (an action declared
63
+ # `transaction: false`, issue #481, has none to roll back), and it is NOT rescued
63
64
  # into a 4xx: it bubbles as a developer error (a 500 your error tracker
64
65
  # must see) because a missing authorize! is a bug, not a client fault. The
65
66
  # message names the component#action and all three remedies (call an
@@ -293,7 +294,8 @@ module Phlex
293
294
  # verify_authorized (issue #168): the default-ON runtime guard. When true,
294
295
  # an action that completes without any authorization call raises
295
296
  # AuthorizationNotVerified inside its transaction (fail-closed — the
296
- # mutation rolls back). Default ON is a deliberate, pre-1.0 breaking change:
297
+ # mutation rolls back; a `transaction: false` action has no endpoint
298
+ # transaction to roll back). Default ON is a deliberate, pre-1.0 breaking change:
297
299
  # a forgotten authorize! becomes a loud 500, not a silent hole. Opt out per
298
300
  # component with `skip_verify_authorized`, mark a bespoke check with
299
301
  # `mark_authorized!`, or turn it off globally here. The `defined?` guard
@@ -6,6 +6,9 @@ module Phlex
6
6
  attr_reader name: Symbol
7
7
  attr_reader params: Hash[Symbol | String, untyped]
8
8
  attr_reader schema: ParamSchema
9
+ attr_reader transaction: bool
10
+
11
+ def initialize: (name: Symbol, params: Hash[Symbol | String, untyped], schema: ParamSchema, ?transaction: bool) -> void
9
12
  end
10
13
 
11
14
  class ComputeDefinition < ::Data
@@ -45,7 +48,7 @@ module Phlex
45
48
  def from_identity: (Hash[String, untyped] payload) -> untyped
46
49
 
47
50
  # --- actions ---
48
- def action: (Symbol | String name, ?params: Hash[Symbol | String, untyped] | Symbol) -> ActionDefinition
51
+ def action: (Symbol | String name, ?params: Hash[Symbol | String, untyped] | Symbol, ?transaction: bool) -> ActionDefinition
49
52
  def reactive_actions: () -> Hash[Symbol, ActionDefinition]
50
53
  def reactive_action: (untyped name) -> bot
51
54
  def reactive_action?: (untyped name) -> bot
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: phlex-reactive
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.17.0
4
+ version: 0.19.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Mikael Henriksson