Class: Parse::Agent::MCPSubscriptions::Manager

Inherits:
Object
  • Object
show all
Defined in:
lib/parse/agent/mcp_subscriptions.rb

Overview

Per-transport subscription coordinator.

One Manager is owned by each Parse::Agent::MCPRackApp that enables resource subscriptions. It is shared across that app's requests and SSE streams, so every public method is thread-safe.

Lifecycle:

  1. A GET listening stream opens → #attach_listener registers the stream's delivery callback under its session id.
  2. A resources/subscribe POST → #subscribe validates the URI, derives credentials from the agent, and starts a LiveQuery subscription whose events publish debounced updates.
  3. resources/unsubscribe → #unsubscribe stops that one LiveQuery subscription.
  4. The listening stream closes (client disconnect / DELETE session) → #detach_listener tears down every LiveQuery subscription for the session.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(logger: nil, debounce_interval: DEFAULT_DEBOUNCE_INTERVAL, notifier: nil, live_query_client: nil, supported: nil, timer: nil, live_query_admin_client: nil, live_query_scoped_client: nil, max_subscriptions_per_session: DEFAULT_MAX_SUBSCRIPTIONS_PER_SESSION, max_sessions: DEFAULT_MAX_SESSIONS, orphan_ttl: DEFAULT_ORPHAN_TTL, clock: nil) ⇒ Manager

Returns a new instance of Manager.

Parameters:

  • logger (#warn, nil) (defaults to: nil)
  • debounce_interval (Numeric) (defaults to: DEFAULT_DEBOUNCE_INTERVAL) —

    see Debouncer.

  • notifier (#register, #unregister, #publish) (defaults to: nil) —

    delivery seam. Defaults to LocalNotifier.

  • live_query_client (Object, nil) (defaults to: nil) —

    a single client used for BOTH master- and session-scoped subscriptions, overriding the admin/scoped split below. Mainly a test injection point. When set, live_query_admin_client / live_query_scoped_client are ignored.

  • live_query_admin_client (Object, nil) (defaults to: nil) —

    the client used for master-key-posture subscriptions. Must be an ADMIN connection (Parse::LiveQuery::Client.new(use_master_key: true)) so the socket bypasses ACL and the subscription actually sees every matching object — Parse Server has no per-subscription master key, so a non-admin connection would silently deliver only publicly-readable rows. Defaults to a lazily-constructed admin client.

  • live_query_scoped_client (Object, nil) (defaults to: nil) —

    the client used for session-token subscriptions. A normal (non-admin) connection; the per-subscription session_token scopes results to that user. Defaults to the process-wide Parse::LiveQuery.client.

  • supported (Boolean, nil) (defaults to: nil) —

    override the #supported? result. When nil (default), #supported? reflects the live LiveQuery enable/availability toggles. Tests pass true alongside a fake client.

  • timer (#call, nil) (defaults to: nil) —

    debounce timer mechanism (see Debouncer).

  • max_subscriptions_per_session (Integer) (defaults to: DEFAULT_MAX_SUBSCRIPTIONS_PER_SESSION) —

    ceiling on concurrent subscriptions for one session. #subscribe raises ValidationError past this. See DEFAULT_MAX_SUBSCRIPTIONS_PER_SESSION.

  • max_sessions (Integer) (defaults to: DEFAULT_MAX_SESSIONS) —

    global ceiling on the number of distinct sessions holding subscriptions. #subscribe raises ValidationError when a NEW session would exceed it. See DEFAULT_MAX_SESSIONS.

  • orphan_ttl (Numeric, nil) (defaults to: DEFAULT_ORPHAN_TTL) —

    seconds an orphaned session (holding subscriptions with no listening stream attached) is kept before #reap_orphans! tears its subscriptions down. See DEFAULT_ORPHAN_TTL. nil disables reaping.

  • clock (#call) (defaults to: nil) —

    monotonic clock returning seconds, injectable for tests. Defaults to Process::CLOCK_MONOTONIC.



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
# File 'lib/parse/agent/mcp_subscriptions.rb', line 370

def initialize(logger: nil, debounce_interval: DEFAULT_DEBOUNCE_INTERVAL,
               notifier: nil, live_query_client: nil, supported: nil,
               timer: nil,
               live_query_admin_client: nil, live_query_scoped_client: nil,
               max_subscriptions_per_session: DEFAULT_MAX_SUBSCRIPTIONS_PER_SESSION,
               max_sessions: DEFAULT_MAX_SESSIONS,
               orphan_ttl: DEFAULT_ORPHAN_TTL,
               clock: nil)
  if !orphan_ttl.nil? && !(orphan_ttl.is_a?(Numeric) && orphan_ttl.positive?)
    raise ArgumentError, "orphan_ttl must be a positive Numeric or nil (got #{orphan_ttl.inspect})"
  end
  @logger = logger
  @debounce_interval = debounce_interval
  @notifier = notifier || LocalNotifier.new
  @both_client = live_query_client
  @admin_client = live_query_admin_client
  @scoped_client = live_query_scoped_client
  @supported_override = supported
  @timer = timer
  @max_per_session = max_subscriptions_per_session
  @max_sessions = max_sessions
  @client_mutex = Mutex.new
  # session_id => { uri => { sub:, debouncer: } }
  @sessions = Hash.new { |h, k| h[k] = {} }
  @mutex = Mutex.new
  @orphan_ttl = orphan_ttl
  @clock = clock || -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }
  # Sessions with a listening stream attached, tracked here (under
  # @mutex) rather than read from the notifier, so {#reap_orphans!} and
  # {#attach_listener} decide "orphaned or not" under one lock and an
  # attach can never interleave with a reap of the same session.
  @attached = {}
  # session_id => clock time the session became orphaned.
  @orphaned_since = {}
end

Instance Attribute Details

#notifier ⇒ Object (readonly)

Returns the value of attribute notifier.



409
410
411
# File 'lib/parse/agent/mcp_subscriptions.rb', line 409

def notifier
  @notifier
end

#orphan_ttl ⇒ Numeric? (readonly)

Returns the configured orphan grace period.

Returns:

  • (Numeric, nil) —

    the configured orphan grace period.



407
408
409
# File 'lib/parse/agent/mcp_subscriptions.rb', line 407

def orphan_ttl
  @orphan_ttl
end

Instance Method Details

#attach_listener(session_id) {|notification_hash| ... }

This method returns an undefined value.

Register a listening stream's delivery callback for a session.

Parameters:

Yield Parameters:

  • notification_hash (Hash) —

    JSON-RPC notification to deliver.



428
429
430
431
432
433
434
435
436
437
438
439
440
441
# File 'lib/parse/agent/mcp_subscriptions.rb', line 428

def attach_listener(session_id, &callback)
  reap_orphans!
  @mutex.synchronize do
    # The latest stream owns the session. Remember its callback so a
    # superseded stream that closes later (a reconnect overlaps the
    # old stream) is recognized and does not tear the session down.
    @attached[session_id] = callback || true
    @orphaned_since.delete(session_id)
    # Registered under the same lock detach_listener uses, so an old
    # stream's teardown can never interleave between this stream's
    # attachment marker and its delivery registration.
    @notifier.register(session_id, &callback)
  end
end

#detach_listener(session_id, listener = nil) ⇒ Integer

Tear down a session: unregister its listener and stop every LiveQuery subscription it opened. Called when the listening stream closes or the session is terminated (DELETE).

Parameters:

  • session_id (String)
  • listener (Proc, nil) (defaults to: nil) —

    the closing stream's callback (as passed to #attach_listener). When a newer stream has since attached for the same session, the closing stream was superseded by a reconnect: nothing is unregistered or torn down, so the active stream keeps its delivery and subscriptions. nil (session termination via DELETE) always tears the session down.

Returns:

  • (Integer) —

    number of LiveQuery subscriptions stopped.



510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
# File 'lib/parse/agent/mcp_subscriptions.rb', line 510

def detach_listener(session_id, listener = nil)
  subs = @mutex.synchronize do
    current = @attached[session_id]
    if listener && current && !current.equal?(listener) && current != true
      next :superseded
    end
    @attached.delete(session_id)
    @orphaned_since.delete(session_id)
    # Unregister inside the lock: a replacement stream attaching
    # concurrently either sees this teardown complete first (and then
    # registers itself) or is seen here as current (superseded above).
    @notifier.unregister(session_id)
    @sessions.delete(session_id)
  end
  return 0 if subs == :superseded
  subs ||= {}
  subs.each_value { |entry| safe_unsubscribe(entry[:sub]) }
  subs.size
end

#listener?(session_id) ⇒ Boolean

Whether a listening stream is currently attached for the session.

Returns:

  • (Boolean)


480
481
482
# File 'lib/parse/agent/mcp_subscriptions.rb', line 480

def listener?(session_id)
  @notifier.respond_to?(:listener?) ? @notifier.listener?(session_id) : false
end

#orphaned_session_count ⇒ Integer

Returns number of sessions currently orphaned (holding subscriptions with no listening stream), whether or not their grace period has elapsed.

Returns:

  • (Integer) —

    number of sessions currently orphaned (holding subscriptions with no listening stream), whether or not their grace period has elapsed.



474
475
476
# File 'lib/parse/agent/mcp_subscriptions.rb', line 474

def orphaned_session_count
  @mutex.synchronize { @orphaned_since.size }
end

#publish(session_id, message_hash) ⇒ Boolean

Push an arbitrary JSON-RPC message (notification OR a server-initiated request carrying an id, e.g. elicitation/create) onto the session's listening stream. Returns false when no stream is attached.

Parameters:

Returns:

  • (Boolean)


492
493
494
495
# File 'lib/parse/agent/mcp_subscriptions.rb', line 492

def publish(session_id, message_hash)
  return false unless @notifier.respond_to?(:publish)
  @notifier.publish(session_id, message_hash)
end

#reap_orphans! ⇒ Integer

Tear down the subscriptions of every session that has been orphaned (subscriptions held, no listening stream attached) for at least #orphan_ttl seconds. Called opportunistically from #subscribe and #attach_listener; operators may also call it on a timer. The orphan check and the removal happen under one lock, so a session that attaches concurrently is either seen as attached (and kept) or attaches after its subscriptions were removed (and starts clean). LiveQuery unsubscribes run after the lock is released.

Returns:

  • (Integer) —

    number of sessions reaped.



453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
# File 'lib/parse/agent/mcp_subscriptions.rb', line 453

def reap_orphans!
  return 0 if @orphan_ttl.nil?
  now = @clock.call
  reaped = @mutex.synchronize do
    expired = @orphaned_since.select { |sid, since| !@attached[sid] && now - since >= @orphan_ttl }.keys
    expired.map do |sid|
      @orphaned_since.delete(sid)
      [sid, @sessions.delete(sid) || {}]
    end
  end
  reaped.each do |sid, subs|
    subs.each_value { |entry| safe_unsubscribe(entry[:sub]) }
    warn_logger("reaped orphaned session #{sid.to_s[0, 8]}... (#{subs.size} subscription(s), " \
                "no listening stream for #{@orphan_ttl}s)")
  end
  reaped.size
end

#subscribe(session_id:, uri:, agent:) ⇒ Boolean

Open a LiveQuery-backed subscription for a resource URI.

Parameters:

  • session_id (String) —

    the Mcp-Session-Id keying the listener.

  • uri (String) —

    parse://<Class>/{count|samples}.

  • agent (Parse::Agent) —

    the subscribing agent (credential source).

Returns:

  • (Boolean) —

    true on success (or already-subscribed no-op).

Raises:



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
# File 'lib/parse/agent/mcp_subscriptions.rb', line 540

def subscribe(session_id:, uri:, agent:)
  if session_id.nil? || session_id.to_s.empty?
    raise Parse::Agent::ValidationError,
          "resources/subscribe requires an established session (Mcp-Session-Id). " \
          "Complete initialize first, then open the GET listening stream."
  end
  class_name, resource = MCPSubscriptions.parse_subscribable_uri(uri)
  reap_orphans!

  # Authorization parity with the read path (resources/read →
  # agent.execute → assert_class_accessible!). Enforce agent_hidden, the
  # per-agent `classes:` allowlist, AND CLP BEFORE deriving credentials
  # or opening any socket. Parse Server LiveQuery enforces row ACL/CLP
  # for session-token subscriptions, but agent_hidden / classes: are
  # SDK-only constructs it knows nothing about — and a master-key socket
  # bypasses ACL/CLP entirely. Without this gate,
  # `resources/subscribe parse://_Session/count` (or any operator-hidden
  # PII class) becomes a change/timing oracle on a class the tool
  # surface refuses to even list. The CLP op mirrors the read path
  # exactly — `count` resources gate on `:count`, `samples` on `:find` —
  # so a subscribe is never stricter than the equivalent read. Raises
  # AccessDenied / ValidationError, which the dispatcher maps to
  # JSON-RPC -32602. Called unconditionally (not behind a
  # `defined?(Tools)` guard) so the gate fails CLOSED — if `Tools` were
  # somehow unloaded the call raises rather than silently skipping
  # authorization. `Parse::Agent::Tools` is a hard dependency of the
  # agent stack that mounts this bridge.
  op = resource == "count" ? :count : :find
  Parse::Agent::Tools.assert_class_accessible!(class_name, agent: agent, op: op)

  creds = MCPSubscriptions.live_query_credentials_for(agent)
  # Row scoping parity with the read path: tenant scope plus the
  # per-agent filter become the subscription's server-side `where`.
  where = MCPSubscriptions.subscription_where_for(agent, class_name)

  # Idempotent: a repeat subscribe to the same URI is a no-op rather
  # than a second LiveQuery socket subscription. Enforce the per-session
  # cap in the same critical section so a burst of distinct-URI
  # subscribes can't race past it.
  @mutex.synchronize do
    # Global cap: bound the number of DISTINCT sessions so an
    # authenticated client opening many sessions (subscribe-without-GET-
    # stream, never DELETE) can't grow `@sessions` without limit. Checked
    # BEFORE indexing `@sessions[session_id]`, which would auto-vivify the
    # entry (`Hash.new { {} }`) and defeat the size check. This is a
    # rejection cap (fails closed); the tradeoff is that a flood of orphan
    # sessions could lock out NEW sessions until they are torn down or the
    # process restarts — acceptable because every session requires a valid
    # authenticated agent and the per-session cap still bounds each one.
    if @max_sessions && !@sessions.key?(session_id) && @sessions.size >= @max_sessions
      raise Parse::Agent::ValidationError,
            "Global subscription session limit reached (#{@max_sessions}). Try again later."
    end
    subs = @sessions[session_id]
    return true if subs.key?(uri)
    if @max_per_session && subs.size >= @max_per_session
      raise Parse::Agent::ValidationError,
            "Session subscription limit reached (#{@max_per_session}). " \
            "Unsubscribe from a resource before adding another."
    end
  end

  debouncer = Debouncer.new(interval: @debounce_interval, timer: @timer) do
    publish_update(session_id, uri)
  end

  sub_opts = where.empty? ? creds : creds.merge(where: where)
  sub = client_for(creds).subscribe(class_name, **sub_opts)
  Parse::LiveQuery::EVENTS.each do |event|
    sub.on(event) { debouncer.trigger }
  end

  # Authoritative commit under the lock. The pre-check above is only a
  # fast path — the network subscribe just ran with the lock RELEASED,
  # so in the meantime the session may have been torn down
  # (detach_listener), a racing subscribe may have claimed this URI, or
  # a concurrent burst may have pushed the session to its cap. Re-check
  # before storing, and gate on `@sessions.key?(session_id)` BEFORE
  # indexing: `@sessions` auto-vivifies (`Hash.new { {} }`), so a bare
  # `@sessions[session_id][uri] = …` would silently RESURRECT a detached
  # session and leak its LiveQuery socket for the process lifetime.
  #
  # A subscribe may legitimately arrive before the GET listening stream
  # opens (the session entry exists, just no listener yet); updates
  # published before a listener attaches are dropped by the notifier
  # and start delivering once the stream is up.
  outcome = @mutex.synchronize do
    if !@sessions.key?(session_id)
      :session_gone
    elsif @sessions[session_id].key?(uri)
      :duplicate
    elsif @max_per_session && @sessions[session_id].size >= @max_per_session
      :over_cap
    else
      @sessions[session_id][uri] = { sub: sub, debouncer: debouncer }
      # A session holding subscriptions without a listening stream
      # starts its orphan grace period now (if not already running).
      @orphaned_since[session_id] ||= @clock.call unless @attached[session_id]
      :stored
    end
  end

  case outcome
  when :stored
    true
  when :duplicate
    # A concurrent subscribe to the same URI won; keep theirs and drop
    # the socket we just opened so we don't leak a duplicate.
    safe_unsubscribe(sub)
    true
  when :session_gone
    # The listening stream closed while we were subscribing — don't
    # resurrect it; tear the just-opened socket back down.
    safe_unsubscribe(sub)
    false
  when :over_cap
    safe_unsubscribe(sub)
    raise Parse::Agent::ValidationError,
          "Session subscription limit reached (#{@max_per_session}). " \
          "Unsubscribe from a resource before adding another."
  end
end

#subscription_count ⇒ Integer

Returns number of active (session, uri) subscriptions.

Returns:

  • (Integer) —

    number of active (session, uri) subscriptions.



688
689
690
# File 'lib/parse/agent/mcp_subscriptions.rb', line 688

def subscription_count
  @mutex.synchronize { @sessions.values.sum(&:size) }
end

#subscriptions?(session_id) ⇒ Boolean

Whether the session holds at least one resource subscription.

Returns:

  • (Boolean)


683
684
685
# File 'lib/parse/agent/mcp_subscriptions.rb', line 683

def subscriptions?(session_id)
  @mutex.synchronize { @sessions.key?(session_id) && !@sessions[session_id].empty? }
end

#supported? ⇒ Boolean

Whether this transport can honor resource subscriptions. Drives the resources.subscribe capability the dispatcher advertises — we never advertise the capability unless we can actually deliver.

Returns:

  • (Boolean)


416
417
418
419
420
421
# File 'lib/parse/agent/mcp_subscriptions.rb', line 416

def supported?
  return @supported_override unless @supported_override.nil?
  return false unless defined?(Parse::LiveQuery)
  Parse.respond_to?(:live_query_enabled?) && Parse.live_query_enabled? &&
    Parse::LiveQuery.available?
end

#unsubscribe(session_id:, uri:) ⇒ Boolean

Stop the LiveQuery subscription for one resource URI. Idempotent.

Returns:

  • (Boolean) —

    true if a subscription was removed.



666
667
668
669
670
671
672
673
674
675
676
677
678
679
# File 'lib/parse/agent/mcp_subscriptions.rb', line 666

def unsubscribe(session_id:, uri:)
  entry = @mutex.synchronize do
    subs = @sessions[session_id]
    e = subs.delete(uri)
    if subs.empty?
      @sessions.delete(session_id)
      @orphaned_since.delete(session_id)
    end
    e
  end
  return false unless entry
  safe_unsubscribe(entry[:sub])
  true
end