Class: Steep::Server::Master

Inherits:
Object
  • Object
show all
Defined in:
lib/steep/server/master.rb

Defined Under Namespace

Modules: MessageUtils Classes: GroupHandler, ResultController, ResultHandler, SendMessageJob

Constant Summary collapse

LSP =
LanguageServer::Protocol
ReceiveMessageJob =
_ = Struct.new(:source, :message, keyword_init: true) do
  # @implements ReceiveMessageJob

  def response?
    message.key?(:id) && !message.key?(:method)
  end

  include MessageUtils
end
COMMAND_SOCKET_ALLOWED_METHODS =

Methods that command socket clients cannot send because they control the server lifecycle The only methods a command socket client may send: what steep check and steep query use. Everything else is rejected -- lifecycle methods because the server belongs to whoever started it, and document synchronization because the LSP client owns the content of the files it opens.

[
  CustomMethods::TypeCheck::METHOD,
  CustomMethods::Query__Diagnostics::METHOD,
  CustomMethods::Query__Definition::METHOD,
  "textDocument/hover",
  "$/ping"
].freeze
COMMAND_SOCKET_FORWARDED_NOTIFICATIONS =

Notifications that are copied to command socket sessions with a pending $/steep/typecheck request

["textDocument/publishDiagnostics", "window/showMessage"].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(project:, reader:, writer:, interaction_worker:, typecheck_workers:, queue: Queue.new, refork: false) ⇒ Master

Returns a new instance of Master.



195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/steep/server/master.rb', line 195

def initialize(project:, reader:, writer:, interaction_worker:, typecheck_workers:, queue: Queue.new, refork: false)
  @project = project
  @reader = reader
  @writer = writer
  @interaction_worker = interaction_worker
  @typecheck_workers = typecheck_workers
  @current_type_check_request = nil
  @typecheck_automatically = true
  @commandline_args = []
  @job_queue = queue
  @write_queue = SizedQueue.new(100)
  @refork_mutex = Mutex.new
  @need_to_refork = refork
  @typecheck_quiescent_callbacks = []
  @pending_typecheck_requests = []
  @project_file_mtimes = nil
  @command_socket_requests = {}
  @command_socket_mutex = Mutex.new

  @controller = TypeCheckController.new(project: project)
  @result_controller = ResultController.new()
  @start_type_checking_queue = DelayQueue.new(delay: 0.3)
end

Instance Attribute Details

#commandline_argsObject (readonly)

Returns the value of attribute commandline_args.



173
174
175
# File 'lib/steep/server/master.rb', line 173

def commandline_args
  @commandline_args
end

#controllerObject (readonly)

Returns the value of attribute controller.



182
183
184
# File 'lib/steep/server/master.rb', line 182

def controller
  @controller
end

#current_type_check_requestObject (readonly)

Returns the value of attribute current_type_check_request.



180
181
182
# File 'lib/steep/server/master.rb', line 180

def current_type_check_request
  @current_type_check_request
end

#initialize_paramsObject (readonly)

Returns the value of attribute initialize_params.



185
186
187
# File 'lib/steep/server/master.rb', line 185

def initialize_params
  @initialize_params
end

#interaction_workerObject (readonly)

Returns the value of attribute interaction_worker.



175
176
177
# File 'lib/steep/server/master.rb', line 175

def interaction_worker
  @interaction_worker
end

#job_queueObject (readonly)

Returns the value of attribute job_queue.



178
179
180
# File 'lib/steep/server/master.rb', line 178

def job_queue
  @job_queue
end

#pending_typecheck_requestsObject (readonly)

Type check requests waiting for the current type check to finish



190
191
192
# File 'lib/steep/server/master.rb', line 190

def pending_typecheck_requests
  @pending_typecheck_requests
end

#projectObject (readonly)

Returns the value of attribute project.



171
172
173
# File 'lib/steep/server/master.rb', line 171

def project
  @project
end

#readerObject (readonly)

Returns the value of attribute reader.



172
173
174
# File 'lib/steep/server/master.rb', line 172

def reader
  @reader
end

#refork_mutexObject (readonly)

Returns the value of attribute refork_mutex.



181
182
183
# File 'lib/steep/server/master.rb', line 181

def refork_mutex
  @refork_mutex
end

#result_controllerObject (readonly)

Returns the value of attribute result_controller.



183
184
185
# File 'lib/steep/server/master.rb', line 183

def result_controller
  @result_controller
end

#start_type_checking_queueObject (readonly)

Returns the value of attribute start_type_checking_queue.



187
188
189
# File 'lib/steep/server/master.rb', line 187

def start_type_checking_queue
  @start_type_checking_queue
end

#typecheck_automaticallyObject

Returns the value of attribute typecheck_automatically.



186
187
188
# File 'lib/steep/server/master.rb', line 186

def typecheck_automatically
  @typecheck_automatically
end

#typecheck_quiescent_callbacksObject (readonly)

Callbacks to be called when no type check is running anymore



193
194
195
# File 'lib/steep/server/master.rb', line 193

def typecheck_quiescent_callbacks
  @typecheck_quiescent_callbacks
end

#typecheck_workersObject (readonly)

Returns the value of attribute typecheck_workers.



176
177
178
# File 'lib/steep/server/master.rb', line 176

def typecheck_workers
  @typecheck_workers
end

#write_queueObject (readonly)

Returns the value of attribute write_queue.



178
179
180
# File 'lib/steep/server/master.rb', line 178

def write_queue
  @write_queue
end

#writerObject (readonly)

Returns the value of attribute writer.



172
173
174
# File 'lib/steep/server/master.rb', line 172

def writer
  @writer
end

Instance Method Details

#assign_initialize_params(params) ⇒ Object



347
348
349
# File 'lib/steep/server/master.rb', line 347

def assign_initialize_params(params)
  @initialize_params = params
end

#broadcast_notification(message) ⇒ Object



1007
1008
1009
1010
1011
1012
# File 'lib/steep/server/master.rb', line 1007

def broadcast_notification(message)
  Steep.logger.info "Broadcasting notification #{message[:method]}"
  each_worker do |worker|
    enqueue_write_job SendMessageJob.new(dest: worker, message: message)
  end
end

#collect_query_diagnostics(id, paths) ⇒ Object

Collects the stored diagnostics from all typecheck workers and sends the response

paths is an array of absolute path strings to filter the result, or nil to return everything.



1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
# File 'lib/steep/server/master.rb', line 1135

def collect_query_diagnostics(id, paths)
  uris = paths&.map {|path| PathHelper.to_uri(Pathname(path)).to_s }

  result_controller << group_request do |group|
    typecheck_workers.each do |worker|
      group << send_request(method: CustomMethods::Query__Diagnostics::METHOD, params: nil, worker: worker)
    end

    group.on_completion do |handlers|
      diagnostics = {} #: Hash[String, Array[untyped]]

      handlers.each do |handler|
        result = handler.result or next
        result.each do |entry|
          array = diagnostics[entry[:uri]] ||= []
          array.concat(entry[:diagnostics] || [])
          array.uniq!
        end
      end

      # @type var result: CustomMethods::Query__Diagnostics::result
      result =
        if uris
          # Files the server has not type checked yet are reported with `diagnostics: nil`
          uris.sort.map do |uri|
            { uri: uri, diagnostics: diagnostics[uri] }
          end
        else
          diagnostics.keys.sort.map do |uri|
            { uri: uri, diagnostics: diagnostics.fetch(uri) }
          end
        end

      enqueue_write_job SendMessageJob.to_client(
        message: CustomMethods::Query__Diagnostics.response(id, result)
      )
    end
  end
end

#each_project_file_path(&block) ⇒ Object



1316
1317
1318
1319
1320
1321
1322
1323
# File 'lib/steep/server/master.rb', line 1316

def each_project_file_path(&block)
  loader = Services::FileLoader.new(base_dir: project.base_dir)
  project.targets.each do |target|
    loader.each_path_in_target(target) do |relative_path|
      yield project.absolute_path(relative_path)
    end
  end
end

#each_worker(&block) ⇒ Object



334
335
336
337
338
339
340
341
# File 'lib/steep/server/master.rb', line 334

def each_worker(&block)
  if block
    yield interaction_worker if interaction_worker
    typecheck_workers.each(&block)
  else
    enum_for :each_worker
  end
end

#enqueue_write_job(job) ⇒ Object



1065
1066
1067
1068
# File 'lib/steep/server/master.rb', line 1065

def enqueue_write_job(job)
  Steep.logger.info { "Write_queue has #{write_queue.size} items"}
  write_queue.push(job)
end

#file_mtime(path) ⇒ Object



1310
1311
1312
1313
1314
# File 'lib/steep/server/master.rb', line 1310

def file_mtime(path)
  File.mtime(path)
rescue SystemCallError
  nil
end

#file_system_watcher_supported?Boolean

Returns:

  • (Boolean)


356
357
358
359
# File 'lib/steep/server/master.rb', line 356

def file_system_watcher_supported?
  initialize_params or raise "`initialize` request is not receiged yet"
  initialize_params.dig(:capabilities, :workspace, :didChangeWatchedFiles, :dynamicRegistration) || false
end

#finish_command_socket_session(session) ⇒ Object

Deregisters the pending requests of a disconnected command socket session



1252
1253
1254
1255
1256
# File 'lib/steep/server/master.rb', line 1252

def finish_command_socket_session(session)
  @command_socket_mutex.synchronize do
    @command_socket_requests.delete_if {|_, entry| entry[0] == session }
  end
end

#finish_type_check(request) ⇒ Object



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
# File 'lib/steep/server/master.rb', line 803

def finish_type_check(request)
  request.work_done_progress.end()

  finished_at = Time.now
  duration = finished_at - request.started_at

  if request.needs_response
    enqueue_write_job(
      SendMessageJob.to_client(
        message: CustomMethods::TypeCheck.response(
          request.guid,
          {
            guid: request.guid,
            completed: request.finished?,
            started_at: request.started_at.iso8601,
            finished_at: finished_at.iso8601,
            duration: duration.to_i
          }
        )
      )
    )
  else
    Steep.logger.debug { "Skip sending response to #{CustomMethods::TypeCheck::METHOD} request" }
  end
end

#flush_typecheck_quiescent_callbacksObject

Calls the waiting quiescent callbacks, once a type check for the paths that went dirty in the meantime finishes



1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
# File 'lib/steep/server/master.rb', line 1115

def flush_typecheck_quiescent_callbacks
  return if typecheck_quiescent_callbacks.empty?
  return if current_type_check_request

  guid = SecureRandom.uuid
  if request = controller.make_request(guid: guid, progress: work_done_progress(guid))
    request.needs_response = false
    start_type_check(request: request, last_request: nil)
    return if current_type_check_request
  end

  callbacks = typecheck_quiescent_callbacks.dup
  typecheck_quiescent_callbacks.clear
  callbacks.each(&:call)
end

#forward_notification_to_command_sessions(message) ⇒ Object



1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
# File 'lib/steep/server/master.rb', line 1275

def forward_notification_to_command_sessions(message)
  return unless COMMAND_SOCKET_FORWARDED_NOTIFICATIONS.include?(message[:method].to_s)

  sessions = @command_socket_mutex.synchronize do
    @command_socket_requests.each_value.with_object([]) do |entry, array|
      session, _, typecheck = entry
      array << session if typecheck
    end
  end

  sessions.uniq!
  sessions.each {|session| session.write(message) }
end

#fresh_request_idObject



1019
1020
1021
# File 'lib/steep/server/master.rb', line 1019

def fresh_request_id
  SecureRandom.alphanumeric(10)
end

#group_requestObject



1053
1054
1055
1056
1057
# File 'lib/steep/server/master.rb', line 1053

def group_request()
  GroupHandler.new().tap do |group|
    yield group
  end
end

#killObject



1059
1060
1061
1062
1063
# File 'lib/steep/server/master.rb', line 1059

def kill
  each_worker do |worker|
    worker.kill
  end
end

#on_type_check_update(guid:, path:, target:, diagnostics:) ⇒ Object



905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
# File 'lib/steep/server/master.rb', line 905

def on_type_check_update(guid:, path:, target:, diagnostics:)
  if current = current_type_check_request()
    if current.guid == guid
      current.checked(path, target)

      Steep.logger.info { "Request updated: checked=#{path}, unchecked=#{current.each_unchecked_code_target_path.size}, diagnostics=#{diagnostics&.size}" }

      percentage = current.percentage
      current.work_done_progress.report(percentage, "#{current.checked_paths.size}/#{current.total}") if current.report_progress

      push_diagnostics(path, diagnostics)

      if current.finished?
        finish_type_check(current)
        @current_type_check_request = nil
        refork_workers
        start_pending_typecheck()
      end
    end
  end
end

#pathname(uri) ⇒ Object



343
344
345
# File 'lib/steep/server/master.rb', line 343

def pathname(uri)
  Steep::PathHelper.to_pathname(uri)
end

#paths_to_watch(pattern, extname:) ⇒ Object



1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
# File 'lib/steep/server/master.rb', line 1465

def paths_to_watch(pattern, extname:)
  result = [] #: Array[String]

  pattern.patterns.each do |pat|
    path = project.base_dir + pat
    result << path.to_s unless path.directory?
  end
  pattern.prefixes.each do |pat|
    path = project.base_dir + pat
    result << (path + "**/*#{extname}").to_s unless path.file?
  end

  result
end

#process_command_socket_message(message, session) ⇒ Object

Processes a message received from a command socket client

Requests are assigned a fresh id and enqueued as if they came from the LSP client, and the responses are routed back to the session through #write_message_to_client.

May be called from any thread.



1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
# File 'lib/steep/server/master.rb', line 1198

def process_command_socket_message(message, session)
  method = message[:method]
  id = message[:id]

  if method && !COMMAND_SOCKET_ALLOWED_METHODS.include?(method.to_s)
    Steep.logger.warn { "Command socket: rejected `#{method}`" }
    if id
      session.write({
        id: id,
        error: {
          code: LSP::Constant::ErrorCodes::INVALID_REQUEST,
          message: "`#{method}` is not allowed through the command socket"
        }
      })
    end
    return
  end

  unless initialize_params
    if id
      session.write({
        id: id,
        error: {
          code: LSP::Constant::ErrorCodes::SERVER_NOT_INITIALIZED,
          message: "The language server is not initialized yet"
        }
      })
    end
    return
  end

  case
  when method && id
    guid = SecureRandom.uuid
    @command_socket_mutex.synchronize do
      @command_socket_requests[guid] = [session, id, method.to_s == CustomMethods::TypeCheck::METHOD]
    end
    message = message.merge({ id: guid })
  when id
    # A response from the client, but nothing is waiting for it
    return
  end

  # Reload files changed on disk before processing, because command socket clients
  # modify files without sending `didChange` notifications
  job_queue << -> do
    sync_project_files_from_disk()
    process_message_from_client(message)
  end
rescue ClosedQueueError
  Steep.logger.warn { "Command socket: server is shutting down" }
end

#process_message_from_client(message) ⇒ Object



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
# File 'lib/steep/server/master.rb', line 361

def process_message_from_client(message)
  Steep.logger.info "Processing message from client: method=#{message[:method]}, id=#{message[:id]}"
  id = message[:id]

  case message[:method]
  when "initialize"
    assign_initialize_params(message[:params])

    result_controller << group_request do |group|
      each_worker do |worker|
        group << send_request(method: "initialize", params: message[:params], worker: worker)
      end

      group.on_completion do
        enqueue_write_job SendMessageJob.to_client(
          message: {
            id: id,
            result: LSP::Interface::InitializeResult.new(
              capabilities: LSP::Interface::ServerCapabilities.new(
                text_document_sync: LSP::Interface::TextDocumentSyncOptions.new(
                  change: LSP::Constant::TextDocumentSyncKind::INCREMENTAL,
                  open_close: true
                ),
                hover_provider: {
                  workDoneProgress: true,
                  partialResults: true,
                  partialResult: true
                },
                completion_provider: LSP::Interface::CompletionOptions.new(
                  trigger_characters: [".", "@", ":"],
                  work_done_progress: true
                ),
                signature_help_provider: {
                  triggerCharacters: ["("]
                },
                workspace_symbol_provider: true,
                definition_provider: true,
                declaration_provider: false,
                implementation_provider: true,
                type_definition_provider: true
              ),
              server_info: {
                name: "steep",
                version: VERSION
              }
            )
          }
        )

        progress = work_done_progress(SecureRandom.uuid)
        if typecheck_automatically
          progress.begin("Type checking", "loading projects...", request_id: fresh_request_id)
        end

        Steep.measure("Load files from disk...") do
          controller.load(command_line_args: commandline_args) do |input|
            input.transform_values! do |content|
              content.is_a?(String) or raise
              if content.valid_encoding?
                content
              else
                base64_encoded = [content].pack("m")
                { text: base64_encoded, binary: true }
              end
            end
            broadcast_notification(CustomMethods::FileLoad.notification({ content: input }))
          end
        end

        if typecheck_automatically
          progress.end()
        end

        reset_project_file_mtimes()

        if file_system_watcher_supported?
          setup_file_system_watcher()
        end

        # controller.changed_paths.clear()

        # if typecheck_automatically
        #   if request = controller.make_request(guid: progress.guid, include_unchanged: true, progress: progress)
        #     start_type_check(request: request, last_request: nil)
        #   end
        # end
      end
    end

  when "workspace/didChangeWatchedFiles"
    updated_watched_files = [] #: Array[Pathname]

    message[:params][:changes].each do |change|
      uri = change[:uri]
      type = change[:type]

      path = PathHelper.to_pathname!(uri)

      unless controller.open_paths.include?(path)
        updated_watched_files << path
        record_project_file_mtime(path)

        case type
        when LSP::Constant::FileChangeType::CREATED, LSP::Constant::FileChangeType::CHANGED
          content = path.read
        when LSP::Constant::FileChangeType::DELETED
          content = ""
        end

        content or raise

        case
        when controller.code_path?(path)
          controller.add_dirty_code_path(path)
        when controller.signature_path?(path)
          controller.add_dirty_signature_path(path)
        when controller.inline_path?(path)
          controller.add_dirty_inline_path(path, content)
        end

        broadcast_notification(CustomMethods::FileReset.notification({ uri: uri, content: content }))
      end
    end

    if updated_watched_files.empty?
      Steep.logger.info { "Exit from workspace/didChangeWatchedFiles notification because all of the changed files are already open" }
      return
    end

    if typecheck_automatically
      start_type_checking_queue.execute do
        job_queue.push(
          -> do
            last_request = current_type_check_request
            guid = SecureRandom.uuid

            start_type_check(
              last_request: last_request,
              progress: work_done_progress(guid),
              needs_response: false
            )
          end
        )
      end
    end

  when "textDocument/didChange"
    if path = pathname(message[:params][:textDocument][:uri])
      broadcast_notification(message)

      Steep.logger.debug { path.to_s }

      case
      when controller.code_path?(path)
        Steep.logger.debug { "code_path?" }
        controller.add_dirty_code_path(path)
      when controller.signature_path?(path)
        Steep.logger.debug { "signature_path?" }
        controller.add_dirty_signature_path(path)
      when controller.inline_path?(path)
        Steep.logger.debug { "inline_path?" }
        changes = Services::ContentChange.from_lsp(message[:params][:contentChanges])
        controller.add_dirty_inline_path(path, changes)
      end

      if typecheck_automatically
        start_type_checking_queue.execute do
          job_queue.push(
            -> do
              Steep.logger.info { "Starting type check from textDocument/didChange notification..." }

              last_request = current_type_check_request
              guid = SecureRandom.uuid

              start_type_check(
                last_request: last_request,
                progress: work_done_progress(guid),
                needs_response: false
              )
            end
          )
        end
      end
    end

  when "textDocument/didOpen"
    uri = message[:params][:textDocument][:uri]
    text = message[:params][:textDocument][:text]

    if path = pathname(uri)
      if target = project.group_for_path(path)
        if controller.inline_path?(path)
          controller.open_inline_path(path, text)
        else
          controller.open_path(path)
        end

        # broadcast_notification(CustomMethods::FileReset.notification({ uri: uri, content: text }))

        start_type_checking_queue.execute do
          guid = SecureRandom.uuid
          start_type_check(last_request: current_type_check_request, progress: work_done_progress(guid), needs_response: true)
        end
      end
    end

  when "textDocument/didClose"
    if path = pathname(message[:params][:textDocument][:uri])
      controller.close_path(path)
    end

  when "textDocument/hover", "textDocument/completion", "textDocument/signatureHelp"
    if interaction_worker
      if path = pathname(message[:params][:textDocument][:uri])
        result_controller << send_request(method: message[:method], params: message[:params], worker: interaction_worker) do |handler|
          handler.on_completion do |response|
            enqueue_write_job SendMessageJob.to_client(
              message: {
                id: message[:id],
                result: response[:result]
              }
            )
          end
        end
      else
        enqueue_write_job SendMessageJob.to_client(
          message: {
            id: message[:id],
            result: nil
          }
        )
      end
    end

  when "workspace/symbol"
    result_controller << group_request do |group|
      typecheck_workers.each do |worker|
        group << send_request(method: "workspace/symbol", params: message[:params], worker: worker)
      end

      group.on_completion do |handlers|
        result = handlers.flat_map(&:result)
        result.uniq!
        enqueue_write_job SendMessageJob.to_client(message: { id: message[:id], result: result })
      end
    end

  when CustomMethods::Stats::METHOD
    result_controller << group_request do |group|
      typecheck_workers.each do |worker|
        group << send_request(method: CustomMethods::Stats::METHOD, params: nil, worker: worker)
      end

      group.on_completion do |handlers|
        stats = handlers.flat_map(&:result) #: Server::CustomMethods::Stats::result
        enqueue_write_job SendMessageJob.to_client(
          message: CustomMethods::Stats.response(message[:id], stats)
        )
      end
    end

  when "textDocument/definition", "textDocument/implementation", "textDocument/typeDefinition"
    if path = pathname(message[:params][:textDocument][:uri])
      result_controller << group_request do |group|
        typecheck_workers.each do |worker|
          group << send_request(method: message[:method], params: message[:params], worker: worker)
        end

        group.on_completion do |handlers|
          links = handlers.flat_map(&:result)
          links.uniq!
          enqueue_write_job SendMessageJob.to_client(
            message: {
              id: message[:id],
              result: links
            }
          )
        end
      end
    else
      enqueue_write_job SendMessageJob.to_client(
        message: {
          id: message[:id],
          result: [] #: Array[untyped]
        }
      )
    end

  when CustomMethods::Query__Definition::METHOD
    params = message[:params] #: CustomMethods::Query__Definition::params
    result_controller << group_request do |group|
      typecheck_workers.each do |worker|
        group << send_request(method: CustomMethods::Query__Definition::METHOD, params: params, worker: worker)
      end

      group.on_completion do |handlers|
        kind = "unknown" #: CustomMethods::Query__Definition::kind
        locations = [] #: Array[CustomMethods::Query__Definition::location]

        handlers.each do |handler|
          result = handler.result #: CustomMethods::Query__Definition::result
          next unless result

          if kind == "unknown"
            kind = result[:kind]
          end
          locations.concat(result[:locations])
        end

        locations.uniq!

        enqueue_write_job SendMessageJob.to_client(
          message: CustomMethods::Query__Definition.response(
            message[:id],
            { name: params[:name], kind: kind, locations: locations }
          )
        )
      end
    end

  when CustomMethods::TypeCheck::METHOD
    id = message[:id]
    params = message[:params] #: CustomMethods::TypeCheck::params

    request = TypeCheckController::Request.new(guid: id, progress: work_done_progress(id))
    request.needs_response = true

    params[:code_paths].each do |target_name, path|
      request.code_paths << [target_name.to_sym, Pathname(path)]
    end
    params[:signature_paths].each do |target_name, path|
      request.signature_paths << [target_name.to_sym, Pathname(path)]
    end
    params[:library_paths].each do |target_name, path|
      request.library_paths << [target_name.to_sym, Pathname(path)]
    end
    params[:inline_paths].each do |target_name, path|
      request.inline_paths << [target_name.to_sym, Pathname(path)]
    end

    start_type_check(request: request, last_request: current_type_check_request)

  when CustomMethods::TypeCheckGroups::METHOD
    params = message[:params] #: CustomMethods::TypeCheckGroups::params

    groups = params.fetch(:groups)

    progress = work_done_progress(SecureRandom.uuid)
    progress.begin("Type checking #{groups.empty? ? "project" : groups.join(", ")}", request_id: fresh_request_id)

    if groups.empty?
      request = controller.make_all_request(progress: progress)
    else
      request = controller.make_group_request(groups, progress: progress)
    end

    request.needs_response = false
    start_type_check(request: request, last_request: current_type_check_request, report_progress_threshold: 0)

  when CustomMethods::Query__Diagnostics::METHOD
    id = message[:id]
    params = message[:params] #: CustomMethods::Query__Diagnostics::params
    paths = params[:paths]

    run_when_typecheck_quiescent do
      collect_query_diagnostics(id, paths)
    end

  when "$/ping"
    enqueue_write_job SendMessageJob.to_client(
      message: {
          id: message[:id],
          result: message[:params]
      }
    )

  when CustomMethods::Groups::METHOD
    groups = [] #: Array[String]

    project.targets.each do |target|
      unless target.source_pattern.empty? && target.signature_pattern.empty?
        groups << target.name.to_s
      end

      target.groups.each do |group|
        unless group.source_pattern.empty? && group.signature_pattern.empty?
          groups << "#{target.name}.#{group.name}"
        end
      end
    end

    enqueue_write_job(SendMessageJob.to_client(
      message: CustomMethods::Groups.response(message[:id], groups)
    ))

  when "shutdown"
    start_type_checking_queue.cancel

    result_controller << group_request do |group|
      each_worker do |worker|
        group << send_request(method: "shutdown", worker: worker)
      end

      group.on_completion do
        enqueue_write_job SendMessageJob.to_client(message: { id: message[:id], result: nil })
      end
    end

  when "exit"
    broadcast_notification(message)
  end
end

#process_message_from_worker(message, worker:) ⇒ Object



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
# File 'lib/steep/server/master.rb', line 774

def process_message_from_worker(message, worker:)
  Steep.logger.tagged "#process_message_from_worker (worker=#{worker.name})" do
    Steep.logger.info { "Processing message from worker: method=#{message[:method] || "-"}, id=#{message[:id] || "*"}" }

    case
    when message.key?(:id) && !message.key?(:method)
      Steep.logger.tagged "response(id=#{message[:id]})" do
        Steep.logger.error { "Received unexpected response" }
        Steep.logger.debug { "result = #{message[:result].inspect}" }
      end
    when message.key?(:method) && !message.key?(:id)
      case message[:method]
      when CustomMethods::TypeCheck__Progress::METHOD
        params = message[:params] #: CustomMethods::TypeCheck__Progress::params
        target = project.targets.find {|target| target.name.to_s == params[:target] } or raise
        on_type_check_update(
          guid: params[:guid],
          path: Pathname(params[:path]),
          target: target,
          diagnostics: params[:diagnostics]
        )
      else
        # Forward other notifications
        enqueue_write_job SendMessageJob.to_client(message: message)
      end
    end
  end
end

#push_diagnostics(path, diagnostics) ⇒ Object



1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
# File 'lib/steep/server/master.rb', line 1417

def push_diagnostics(path, diagnostics)
  if diagnostics
    write_queue.push SendMessageJob.to_client(
      message: {
        method: :"textDocument/publishDiagnostics",
        params: { uri: Steep::PathHelper.to_uri(path).to_s, diagnostics: diagnostics }
      }
    )
  end
end

#record_project_file_mtime(path) ⇒ Object



1304
1305
1306
1307
1308
# File 'lib/steep/server/master.rb', line 1304

def record_project_file_mtime(path)
  if mtimes = @project_file_mtimes
    mtimes[path] = file_mtime(path)
  end
end

#refork_workersObject



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
1001
1002
1003
1004
1005
# File 'lib/steep/server/master.rb', line 927

def refork_workers
  return unless @need_to_refork
  @need_to_refork = false

  Thread.new do
    Thread.current.abort_on_exception = true

    primary, *others = typecheck_workers
    primary or raise
    others.each do |worker|
      worker.index or raise

      refork_mutex.synchronize do
        refork_finished = Thread::Queue.new
        stdin_in, stdin_out = IO.pipe
        stdout_in, stdout_out = IO.pipe

        result_controller << send_refork_request(params: { index: worker.index, max_index: typecheck_workers.size }, worker: primary) do |handler|
          handler.on_completion do |response|
            writer = LanguageServer::Protocol::Transport::Io::Writer.new(stdin_out)
            reader = LanguageServer::Protocol::Transport::Io::Reader.new(stdout_in)

            pid = response[:result][:pid]
            # It does not need to wait worker process
            # because the primary worker monitors it instead.
            #
            # @type var wait_thread: Thread & WorkerProcess::_ProcessWaitThread
            wait_thread = _ = Thread.new { sleep }
            wait_thread.define_singleton_method(:pid) { pid }

            new_worker = WorkerProcess.new(reader:, writer:, stderr: nil, wait_thread:, name: "#{worker.name}-2", index: worker.index)
            old_worker = typecheck_workers[worker.index] or raise

            typecheck_workers[(new_worker.index or raise)] = new_worker

            original_old_worker = old_worker.dup
            old_worker.redirect_to new_worker

            refork_finished << true

            result_controller << send_request(method: 'shutdown', worker: original_old_worker) do |handler|
              handler.on_completion do
                send_request(method: 'exit', worker: original_old_worker)
              end
            end

            Thread.new do
              tags = Steep.logger.current_tags.dup
              Steep.logger.push_tags(*tags, "from-worker@#{new_worker.name}")
              new_worker.reader.read do |message|
                job_queue << ReceiveMessageJob.new(source: new_worker, message: message)
              end
            end
          end
        end

        # The primary worker starts forking when it receives the IOs.
        primary.io_socket or raise
        primary.io_socket.send_io(stdin_in)
        primary.io_socket.send_io(stdout_out)
        stdin_in.close
        stdout_out.close

        refork_finished.pop
      end
    end

    # The reforked workers started from a copy of the primary's state, which has the
    # results of the primary's assigned paths only, and the results the replaced workers
    # had computed are gone with them. Type check everything again so that queries
    # reading the stored results, like `$/steep/query/diagnostics`, see all files.
    job_queue << -> do
      guid = SecureRandom.uuid
      request = controller.make_all_request(guid: guid, progress: work_done_progress(guid))
      request.needs_response = false
      start_type_check(request: request, last_request: current_type_check_request, report_progress_threshold: 0)
    end
  end
end

#reset_project_file_mtimesObject

Records the mtimes of all project files, as the baseline of #sync_project_files_from_disk



1296
1297
1298
1299
1300
1301
1302
# File 'lib/steep/server/master.rb', line 1296

def reset_project_file_mtimes
  mtimes = {} #: Hash[Pathname, Time?]
  each_project_file_path do |path|
    mtimes[path] = file_mtime(path)
  end
  @project_file_mtimes = mtimes
end

#run_when_typecheck_quiescent(&block) ⇒ Object

Calls the block once no type check is running

Starts a type check for dirty paths first, so that the block observes up-to-date results.



1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
# File 'lib/steep/server/master.rb', line 1074

def run_when_typecheck_quiescent(&block)
  unless current_type_check_request
    guid = SecureRandom.uuid
    if request = controller.make_request(guid: guid, progress: work_done_progress(guid))
      request.needs_response = false
      start_type_check(request: request, last_request: nil)
    end
  end

  if current_type_check_request || !pending_typecheck_requests.empty?
    typecheck_quiescent_callbacks << block
  else
    yield
  end
end

#send_notification(message, worker:) ⇒ Object



1014
1015
1016
1017
# File 'lib/steep/server/master.rb', line 1014

def send_notification(message, worker:)
  Steep.logger.info "Sending notification #{message[:method]} to #{worker.name}"
  enqueue_write_job SendMessageJob.new(dest: worker, message: message)
end

#send_refork_request(id: fresh_request_id(), params:, worker:, &block) ⇒ Object



1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
# File 'lib/steep/server/master.rb', line 1034

def send_refork_request(id: fresh_request_id(), params:, worker:, &block)
  method = CustomMethods::Refork::METHOD
  Steep.logger.info "Sending request #{method}(#{id}) to #{worker.name}"

  # @type var message: lsp_request
  message = { method: method, id: id, params: params }
  ResultHandler.new(request: message).tap do |handler|
    yield handler if block

    job = SendMessageJob.to_worker(worker, message: message)
    case job.dest
    when WorkerProcess
      job.dest << job.message
    else
      raise "Unexpected destination: #{job.dest}"
    end
  end
end

#send_request(method:, id: fresh_request_id(), params: nil, worker:, &block) ⇒ Object



1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
# File 'lib/steep/server/master.rb', line 1023

def send_request(method:, id: fresh_request_id(), params: nil, worker:, &block)
  Steep.logger.info "Sending request #{method}(#{id}) to #{worker.name}"

  # @type var message: lsp_request
  message = { method: method, id: id, params: params }
  ResultHandler.new(request: message).tap do |handler|
    yield handler if block
    enqueue_write_job SendMessageJob.to_worker(worker, message: message)
  end
end

#setup_file_system_watcherObject



1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
# File 'lib/steep/server/master.rb', line 1428

def setup_file_system_watcher()
  patterns = [] #: Array[String]

  project.targets.each do |target|
    patterns.concat(paths_to_watch(target.source_pattern, extname: ".rb"))
    patterns.concat(paths_to_watch(target.signature_pattern, extname: ".rbs"))
    target.groups.each do |group|
      patterns.concat(paths_to_watch(group.source_pattern, extname: ".rb"))
      patterns.concat(paths_to_watch(group.signature_pattern, extname: ".rbs"))
    end
  end
  patterns.sort!
  patterns.uniq!

  Steep.logger.info { "Setting up didChangeWatchedFiles with pattern: #{patterns.inspect}" }

  enqueue_write_job SendMessageJob.to_client(
    message: {
      id: SecureRandom.uuid,
      method: "client/registerCapability",
      params: {
        registrations: [
          {
            id: SecureRandom.uuid,
            method: "workspace/didChangeWatchedFiles",
            registerOptions: {
              watchers: patterns.map do |pattern|
                { globPattern: pattern }
              end
            }
          }
        ]
      }
    }
  )
end

#startObject



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
# File 'lib/steep/server/master.rb', line 219

def start
  Steep.logger.tagged "master" do
    tags = Steep.logger.current_tags.dup

    # @type var worker_threads: Array[Thread]
    worker_threads = []

    if interaction_worker
      worker_threads << Thread.new do
        Steep.logger.push_tags(*tags, "from-worker@interaction")
        interaction_worker.reader.read do |message|
          job_queue << ReceiveMessageJob.new(source: interaction_worker, message: message)
        end
      end
    end

    typecheck_workers.each do |worker|
      worker_threads << Thread.new do
        Steep.logger.push_tags(*tags, "from-worker@#{worker.name}")
        worker.reader.read do |message|
          job_queue << ReceiveMessageJob.new(source: worker, message: message)
        end
      end
    end

    read_client_thread = Thread.new do
      reader.read do |message|
        job_queue << ReceiveMessageJob.new(source: :client, message: message)
        break if message[:method] == "exit"
      end
    end

    write_thread = Thread.new do
      Steep.logger.push_tags(*tags)
      Steep.logger.tagged "write" do
        while job = write_queue.deq
          # @type var job: SendMessageJob
          case job.dest
          when :client
            Steep.logger.info { "Processing SendMessageJob: dest=client, method=#{job.message[:method] || "-"}, id=#{job.message[:id] || "-"}" }
            write_message_to_client(job.message)
          when WorkerProcess
            refork_mutex.synchronize do
              Steep.logger.info { "Processing SendMessageJob: dest=#{job.dest.name}, method=#{job.message[:method] || "-"}, id=#{job.message[:id] || "-"}" }
              job.dest << job.message
            end
          end
        end
      end
    end

    loop_thread = Thread.new do
      Steep.logger.push_tags(*tags)
      Steep.logger.tagged "main" do
        while job = job_queue.deq
          case job
          when ReceiveMessageJob
            src = case job.source
                  when :client
                    :client
                  else
                    job.source.name
                  end
            Steep.logger.tagged("ReceiveMessageJob(#{src}/#{job.message[:method]}/#{job.message[:id]})") do
              if job.response? && result_controller.process_response(job.message)
                # nop
                Steep.logger.info { "Processed by ResultController" }
              else
                case job.source
                when :client
                  process_message_from_client(job.message)

                  if job.message[:method] == "exit"
                    job_queue.close()
                  end
                when WorkerProcess
                  process_message_from_worker(job.message, worker: job.source)
                end
              end
            end
          when Proc
            job.call()
          end
        end
      end
    end

    waiter = ThreadWaiter.new(each_worker.to_a) {|worker| worker.wait_thread }
    # @type var th: Thread & WorkerProcess::_ProcessWaitThread
    while th = _ = waiter.wait_one()
      if each_worker.any? { |worker| worker.pid == th.pid }
        break # The worker unexpectedly exited
      end
    end

    unless job_queue.closed?
      # Exit by error
      each_worker do |worker|
        worker.kill(force: true)
      end
      raise "Unexpected worker process exit"
    end

    write_queue.close()
    write_thread.join

    read_client_thread.join()
    worker_threads.each do |thread|
      thread.join
    end

    loop_thread.join
  end
end

#start_pending_typecheckObject

Starts the next queued type check request if any, or the automatic type check for dirty paths

Calls the quiescent callbacks when nothing is left to type check.



1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
# File 'lib/steep/server/master.rb', line 1094

def start_pending_typecheck
  while request = pending_typecheck_requests.shift
    start_type_check(request: request, last_request: nil)
    return if current_type_check_request
  end

  if typecheck_automatically && initialize_params
    guid = SecureRandom.uuid
    if request = controller.make_request(guid: guid, progress: work_done_progress(guid))
      request.needs_response = false
      start_type_check(request: request, last_request: nil)
      return if current_type_check_request
    end
  end

  flush_typecheck_quiescent_callbacks()
end

#start_type_check(request: nil, last_request:, progress: nil, include_unchanged: false, report_progress_threshold: 10, needs_response: nil) ⇒ Object



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
# File 'lib/steep/server/master.rb', line 829

def start_type_check(request: nil, last_request:, progress: nil, include_unchanged: false, report_progress_threshold: 10, needs_response: nil)
  Steep.logger.tagged "#start_type_check(#{progress&.guid || request&.guid}, #{last_request&.guid}" do
    if (current = current_type_check_request) && typecheck_request_from_command_socket?(current)
      # Never supersede a type check that a command socket client is waiting for
      if request
        Steep.logger.info { "Queueing type check request #{request.guid} until the command socket request finishes" }
        pending_typecheck_requests << request
      else
        Steep.logger.info { "Deferring automatic type checking until the command socket request finishes" }
      end
      return
    end

    if last_request
      finish_type_check(last_request)
    end

    unless request
      progress or raise
      request =
        if include_unchanged
          controller.make_all_request(guid: progress.guid, progress: progress)
        else
          controller.make_request(guid: progress.guid, progress: progress)
        end
      return unless request

      request.needs_response = needs_response ? true : false
    end

    if last_request
      request.merge!(last_request)
    end

    Steep.logger.debug {
      {
        code_paths: request.code_paths.map { _1[1].to_s },
        signature_paths: request.signature_paths.map { _1[1].to_s },
        inline_paths: request.inline_paths.map { _1[1].to_s }
      }.inspect
    }

    if request.total > report_progress_threshold
      request.report_progress!
    end

    if request.each_unchecked_target_path.to_a.empty?
      finish_type_check(request)
      @current_type_check_request = nil
      return
    end

    Steep.logger.info "Starting new progress..."

    @current_type_check_request = request

    if progress
      # If `request:` keyword arg is not given
      request.work_done_progress.begin("Type checking", request_id: fresh_request_id)
    end

    Steep.logger.info "Sending $/typecheck/start notifications"
    typecheck_workers.each do |worker|
      assignment = Services::PathAssignment.new(
        max_index: typecheck_workers.size,
        index: worker.index || raise
      )

      enqueue_write_job SendMessageJob.to_worker(
        worker,
        message: CustomMethods::TypeCheck__Start.notification(request.as_json(assignment: assignment))
      )
    end
  end
end

#sync_project_files_from_diskObject

Detects files changed on disk since the last load/sync, and reloads them

Skips files open in the editor because the client owns their contents. Does nothing until the initial project load finishes.



1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
# File 'lib/steep/server/master.rb', line 1330

def sync_project_files_from_disk
  mtimes = @project_file_mtimes or return

  changes = {} #: Hash[Pathname, Symbol]
  seen = Set[] #: Set[Pathname]

  each_project_file_path do |path|
    next if seen.include?(path)
    seen << path

    mtime = file_mtime(path)
    recorded = mtimes[path]

    case
    when recorded.nil? && mtime
      changes[path] = mtimes.key?(path) ? :changed : :created
    when recorded && mtime.nil?
      changes[path] = :deleted
    when recorded != mtime
      changes[path] = :changed
    end

    mtimes[path] = mtime
  end

  deleted_paths = mtimes.keys.select {|path| !seen.include?(path) && mtimes[path] && file_mtime(path).nil? }
  deleted_paths.each do |path|
    changes[path] = :deleted
    mtimes[path] = nil
  end

  changes.delete_if {|path, _| controller.open_paths.include?(path) }
  return if changes.empty?

  Steep.logger.info { "Command socket: reloading #{changes.size} file(s) changed on disk" }

  changes.each do |path, type|
    content =
      if type == :deleted
        ""
      else
        begin
          path.read
        rescue SystemCallError
          next
        end
      end

    case
    when controller.code_path?(path)
      controller.add_dirty_code_path(path)
    when controller.signature_path?(path)
      controller.add_dirty_signature_path(path)
    when controller.inline_path?(path)
      controller.add_dirty_inline_path(path, content)
    end

    broadcast_notification(CustomMethods::FileReset.notification({ uri: PathHelper.to_uri(path).to_s, content: content }))
  end

  if typecheck_automatically
    start_type_checking_queue.execute do
      job_queue.push(
        -> do
          start_type_check(
            last_request: current_type_check_request,
            progress: work_done_progress(SecureRandom.uuid),
            needs_response: false
          )
        end
      )
    end
  end
end

#typecheck_request_from_command_socket?(request) ⇒ Boolean

Returns:

  • (Boolean)


1289
1290
1291
1292
1293
# File 'lib/steep/server/master.rb', line 1289

def typecheck_request_from_command_socket?(request)
  @command_socket_mutex.synchronize do
    @command_socket_requests.key?(request.guid)
  end
end

#work_done_progress(guid) ⇒ Object



1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
# File 'lib/steep/server/master.rb', line 1405

def work_done_progress(guid)
  if work_done_progress_supported?
    WorkDoneProgress.new(guid) do |message|
      enqueue_write_job SendMessageJob.to_client(message: message)
    end
  else
    WorkDoneProgress.new(guid) do |message|
      # nop
    end
  end
end

#work_done_progress_supported?Boolean

Returns:

  • (Boolean)


351
352
353
354
# File 'lib/steep/server/master.rb', line 351

def work_done_progress_supported?
  initialize_params or raise "`initialize` request is not receiged yet"
  initialize_params.dig(:capabilities, :window, :workDoneProgress) ? true : false
end

#write_message_to_client(message) ⇒ Object



1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
# File 'lib/steep/server/master.rb', line 1258

def write_message_to_client(message)
  unless message.key?(:method)
    entry = @command_socket_mutex.synchronize { @command_socket_requests.delete(message[:id]) }
    if entry
      session, original_id, _ = entry
      session.write(message.merge({ id: original_id }))
      return
    end
  end

  writer.write(message)

  if message.key?(:method) && !message.key?(:id)
    forward_notification_to_command_sessions(message)
  end
end