Class: MrMurano::EventHandler

Inherits:
ServiceBase show all
Defined in:
lib/MrMurano/Solution-Services.rb

Overview

Services aka EventHandlers

Direct Known Subclasses

EventHandlerSolnApp, EventHandlerSolnPrd

Defined Under Namespace

Classes: EventHandlerItem

Constant Summary

Constants included from Verbose

Verbose::TABULARIZE_DATA_FORMAT_ERROR

Constants included from SolutionId

SolutionId::INVALID_API_ID, SolutionId::UNEXPECTED_TYPE_OR_ERROR_MSG

Constants included from AccountBase

AccountBase::LOGIN_ADVICE, AccountBase::LOGIN_NOTICE

Instance Attribute Summary

Attributes included from SolutionId

#api_id, #sid, #valid_api_id

Instance Method Summary collapse

Methods inherited from ServiceBase

#cache_dump_filename, #cache_dump_filepath, #cache_file_name, #cache_update_time_for, #cached_update_time_for, #create_new_cache_file, #docmp, #dodiff, #dump_cache_file, #local_path_file_hash, #remove, #remove_or_clear, #upload, #upload_script, #write_updated_cache_file

Methods inherited from SolutionBase

#==, #endpoint, #search

Methods included from SyncUpDown

#debug_print_localitems, #diff_download, #diff_item_write, #docmp, #download, #ignore?, #ignoring, #localitems, #locallist, #locallist_add_item, #locallist_complain_missing, #locallist_mark_seen, #location, #remove, #remove_or_clear, #removelocal, #searchFor, #syncdown_after, #syncdown_before, #syncup_after, #syncup_before, #tolocalpath, #update_mtime, #upload

Methods included from Verbose

ask_yes_no, #ask_yes_no, #assert, assert, cmd_confirm_delete!, #cmd_confirm_delete!, debug, #debug, dump_file_json, dump_file_plain, dump_file_yaml, #dump_output_file, #error, error, #error_file_format!, fancy_ticks, #fancy_ticks, #load_file_json, #load_file_plain, #load_file_yaml, #load_input_file, outf, #outf, #outformat_engine, #pluralize?, pluralize?, #prepare_hash_csv, #read_hashf!, #tabularize, tabularize, verbose, #verbose, warning, #warning, #whirly_interject, whirly_interject, #whirly_linger, whirly_linger, #whirly_msg, whirly_msg, #whirly_pause, whirly_pause, #whirly_start, whirly_start, #whirly_stop, whirly_stop, #whirly_unpause, whirly_unpause

Methods included from SyncCore

#debug_selected, #dodiff, #dodiff_build_cmd, #dodiff_cull_tempfile_paths, #dodiff_do_diff, #dodiff_download_remote, #dodiff_flexible, #dodiff_header_aware, #dodiff_local_to_tempfile, #dodiff_prepare_local_and_diff, #dodiff_resolve_localname, #dodiff_tempfile_paths, #filter_solution, #init_mods_and_chgs_arrs, #item_dirty_set_status, #item_local_there_merged, #item_merged_diff_status, #item_merged_set_status, #item_select_selected!, #items_classify_and_find_duplicates, #items_cull_clashes!, #items_lists, #items_log_duplicates, #items_log_duplicates_there_local, #items_mods_and_chgs!, #items_new_and_old!, #select_selected!, #sort_by_name, #status, #sync_update_progress, #syncable_validate_api_id, #syncdown, #syncdown_item, #syncup, #syncup_item

Methods included from SyncAllowed

#download_item_allowed, #remove_item_allowed, #removelocal_item_allowed, #sync_item_allowed, #upload_item_allowed

Methods included from SolutionId

#affirm_valid, #api_id?, #endpoint, #init_api_id!, #valid_api_id?

Methods included from AccountBase

#add_headers, #ask_for_password!, #ask_for_user!, #cfg_clear_user_and_business, #credentials_reset, #get, #invalidate_token, #login_info, #logout, #must_prompt_if_logged_off!, #token, #token_reset, #verify_cfg_auth!, #verify_cfg_auth_persist, #verify_cfg_auth_scheme!, #verify_cfg_auth_ttl, #verify_set, warn_configfile_env_maybe

Methods included from Http

#add_headers, #curldebug, curldebug_after, curldebug_elapsed, curldebug_log, #delete, #endpoint, #get, #host, #http, #http_reset, #isJSON, #json_opts, #patch, #post, #postf, #put, #showHttpError, #user, #workit, #workit_response

Constructor Details

#initialize(api_id = nil) ⇒ EventHandler

Returns a new instance of EventHandler.



519
520
521
522
523
524
525
526
# File 'lib/MrMurano/Solution-Services.rb', line 519

def initialize(api_id=nil)
  super
  @uriparts << :eventhandler
  @itemkey = :alias
  #@project_section = :services
  raise 'Subclass missing @project_section' unless @project_section
  @match_header = /--#EVENT (?<service>\S+) (?<event>\S+)/
end

Instance Method Details

#build_svc_alias_map_from_local(encode_items, local) ⇒ Object



571
572
573
574
575
576
# File 'lib/MrMurano/Solution-Services.rb', line 571

def build_svc_alias_map_from_local(encode_items, local)
  local.each do |item|
    encode_items[item.service] = {} if encode_items[item.service].nil?
    encode_items[item.service][item.event] = item.svc_alias
  end
end

#cmp_svc_evt(item, svc_evt) ⇒ Object



605
606
607
608
609
610
611
612
613
614
615
616
617
618
# File 'lib/MrMurano/Solution-Services.rb', line 605

def cmp_svc_evt(item, svc_evt)
  service, event = svc_evt.split('.', 2)
  svc_match = (
    service == item[:service] ||
    (!item[:svc_alias].to_s.empty? && service == item[:svc_alias])
  )
  if event.nil? || item[:event] == '*'
    svc_match
  elsif service == '*'
    event == item[:event]
  else
    svc_match && event == item[:event]
  end
end

#config_vars_decode(script, event_event = nil) ⇒ Object



752
753
754
# File 'lib/MrMurano/Solution-Services.rb', line 752

def config_vars_decode(script, event_event=nil)
  config_vars_translate(script, event_event, method(:decode_config_var))
end

#config_vars_encode(script, event_event = nil) ⇒ Object



756
757
758
# File 'lib/MrMurano/Solution-Services.rb', line 756

def config_vars_encode(script, event_event=nil)
  config_vars_translate(script, event_event, method(:encode_config_var))
end

#config_vars_translate(script, event_event, codec) ⇒ Object



760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
# File 'lib/MrMurano/Solution-Services.rb', line 760

def config_vars_translate(script, event_event, codec)
  new_script = ''
  # Replace the service with a {config.variable} if appropriate.
  script.lines.each do |line|
    # @match_header finds a service and an event string, e.g., "--EVENT svc evt\n"
    md = @match_header.match(line)
    unless md.nil?
      service, _config_var = codec.call(md[:service])
      if event_event.nil?
        # Preserve the event (use a group name reference).
        replace_fmt = "--#EVENT #{service} \\k<event>"
      else
        # Use the event we sussed (e.g., "data_in" → "event").
        replace_fmt = "--#EVENT #{service} #{event_event}"
      end
      line = line.gsub(/--#EVENT (?<service>\S+) (?<event>\S+)/, replace_fmt)
    end
    new_script += line
  end
  new_script
end

#decode_config_var(term) ⇒ Object



782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
# File 'lib/MrMurano/Solution-Services.rb', line 782

def decode_config_var(term)
  decoded = term
  config_var = nil
  # Try to match svc against a {config.variable}.
  mat = /^\{([^\.}]+)\.([^\.}]+)\}$/.match(term)
  unless mat.nil?
    # User specified a config value, e.g., "--#EVENT {product.id} event".
    config_var = "#{mat[1]}.#{mat[2]}"
    decoded = $cfg[config_var]
    if decoded.nil?
      warning "Config value not found for variable: #{fancy_ticks(term)}"
      # The platform should complain about file not found,
      # and we'll process everything else.
      decoded = term
      config_var = nil
    end
  end
  [decoded, config_var]
end

#default_event_script(service_or_api_id, &block) ⇒ Object



645
646
647
648
649
650
651
652
653
654
655
656
# File 'lib/MrMurano/Solution-Services.rb', line 645

def default_event_script(service_or_api_id, &block)
  post(
    '/',
    {
      solution_id: @api_id,
      service: service_or_api_id,
      event: 'event',
      script: 'print(event)',
    },
    &block
  )
end

#encode_config_var(term) ⇒ Object



802
803
804
805
806
807
808
809
810
811
812
813
# File 'lib/MrMurano/Solution-Services.rb', line 802

def encode_config_var(term)
  encoded = term
  config_var = nil
  # MEH/2017-08-22: For now, only matching against one config var.
  #   Maybe in the future we'd want to examine all the config vars?
  # MAGIC_STRING: {config.variable} substitution.
  if term == $cfg['product.id']
    encoded = '{product.id}'
    config_var = 'product.id'
  end
  [encoded, config_var]
end

#fetch(name, _untainted = false) ⇒ Object



620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
# File 'lib/MrMurano/Solution-Services.rb', line 620

def fetch(name, _untainted=false)
  ret = get('/' + CGI.escape(name))
  unless ret.is_a?(Hash) && !ret.key?(:error)
    error "Fetch for #{name} returned nil or error; skipping"
    return ''
  end
  aheader = (ret[:script].lines.first || '').chomp
  dheader = "--#EVENT #{ret[:service]} #{ret[:event]}"
  # FIXME/2018-04-24: (lb): What about untainted ?? And this weird double-yield?
  #   We may want to yield/return unadulterated ret[:script] if just diffing.
  if block_given?
    # ANSWER/2018-04-24: (lb): If header's do not match, what about ret[:script]?
    #   Or do both yields get called?? Smells very strange.
    yield dheader + "\n" if aheader != dheader
    yield ret[:script]
  else
    # 2017-07-02: Changing shovel operator << to +=
    # to support Ruby 3.0 frozen string literals.
    res = ''
    res += dheader + "\n" if aheader != dheader
    res += ret[:script]
    res
  end
end

#list(call = nil, data = nil, &block) ⇒ Object



545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
# File 'lib/MrMurano/Solution-Services.rb', line 545

def list(call=nil, data=nil, &block)
  ret = get(call, data, &block)
  return [] unless ret.is_a?(Hash) && !ret.key?(:error)
  return [] unless ret.key?(:items)
  # eventhandler.skiplist is a list of whitespace separated dot-paired values.
  # fe: service.event service service service.event
  skiplist = ($cfg['eventhandler.skiplist'] || '').split
  items = ret[:items].reject do |item|
    toss = skip?(item, skiplist)
    debug "skiplist excludes: #{item[:service]}.#{item[:event]}" if toss
    toss
  end
  items.map { |item| EventHandlerItem.new(item) }
  # MAYBE/2017-08-17:
  #   items.map! ...
  #   sort_by_name(items)
end

#match(item, pattern) ⇒ Object



735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
# File 'lib/MrMurano/Solution-Services.rb', line 735

def match(item, pattern)
  # Pattern is: #{service}#{event}
  pattern_pattern = /^#(?<service>[^#]*)#(?<event>.*)/i
  md = pattern_pattern.match(pattern)
  return false if md.nil?
  debug "match pattern: '#{md[:service]}' '#{md[:event]}'"
  if (
    !md[:service].empty? &&
    !item[:service].casecmp(md[:service]).zero? &&
    (item[:svc_alias].to_s.empty? || !item[:svc_alias].casecmp(md[:service]).zero?)
  )
    return false
  end
  return false unless md[:event].empty? || item[:event].casecmp(md[:event]).zero?
  true # Both match (or both empty).
end

#mkalias(remote) ⇒ Object



528
529
530
531
532
533
# File 'lib/MrMurano/Solution-Services.rb', line 528

def mkalias(remote)
  missing_parts = remote.service.nil? || remote.event.nil?
  raise "Missing parts! #{remote.to_h.to_json}" if missing_parts
  #[$cfg[@solntype], remote[:service], remote[:event]].join('_')
  [@api_id, remote[:service], remote[:event]].join('_')
end

#mkname(remote) ⇒ Object



535
536
537
538
539
# File 'lib/MrMurano/Solution-Services.rb', line 535

def mkname(remote)
  missing_parts = remote.service.nil? || remote.event.nil?
  raise "Missing parts! #{remote.to_h.to_json}" if missing_parts
  [remote[:service], remote[:event]].join('_')
end

#resolve_config_var_usage!(there, local) ⇒ Object



563
564
565
566
567
568
569
# File 'lib/MrMurano/Solution-Services.rb', line 563

def resolve_config_var_usage!(there, local)
  # Substitute '{product.id}' for the actual product.id if a corresponding
  # local file does not exist, or if the local file already uses the alias.
  encode_items = {}
  build_svc_alias_map_from_local(encode_items, local)
  resolve_name_svc_alias!(encode_items, there)
end

#resolve_event_type(service, event) ⇒ Object



815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
# File 'lib/MrMurano/Solution-Services.rb', line 815

def resolve_event_type(service, event)
  # FIXME/2017-08-09: device2.event is now in the skiplist,
  #   but some tests have a "device2 data_in" script, which
  #   gets changed to "device2.event" here and then uploaded
  #   (note that skiplist does not apply to local items).
  #   You can test this code via:
  #     rspec ./spec/cmd_syncdown_spec.rb
  #   which has a fixture with device2.data_in specified.
  #   QUESTION: Does writing device2.event do anything?
  #     You cannot edit that handler from the web UI...
  #     - Should we change the test?
  #     - Should we get rid of this device2 hack?
  #   NOTE: All `event_event` usage is for supporting legacy `data_in`.
  if service == 'device2'
    event_event = 'event' # Override 'data_in'.
    event_type = event
    # FIXME/CONFIRM/2017-07-02: 'data_in' was the old event name? It's now 'event'?
    #   Want this?:
    #     event_type = 'event' if event_type == 'data_in'
  else
    event_event = event
    event_type = nil
  end
  [event_event, event_type]
end

#resolve_name_svc_alias!(encode_items, there) ⇒ Object



578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
# File 'lib/MrMurano/Solution-Services.rb', line 578

def resolve_name_svc_alias!(encode_items, there)
  there.map! do |item|
    if (
      !encode_items[item.service].nil? &&
      !encode_items[item.service][item.event].nil?
    )
      svc_alias = encode_items[item.service][item.event]
    else
      # There's no corresponding local item.
      _encoded, svc_alias = encode_config_var(item.service)
    end
    svc_alias = nil if svc_alias == item.service
    unless svc_alias.nil?
      item.svc_alias = svc_alias
      item.name.sub!($cfg[svc_alias], "{#{svc_alias}}")
    end
    item
  end
end

#resurrect_undeletable(key, localbox, therebox, thereitem) ⇒ Object



874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
# File 'lib/MrMurano/Solution-Services.rb', line 874

def resurrect_undeletable(key, localbox, therebox, thereitem)
  debug "Undeletable: #{key}"
  undeletable = EventHandlerItem.new(thereitem)
  undeletable.id = nil
  undeletable.created_at = nil
  undeletable.updated_at = nil
  # Even if the user deletes the contents of a script,
  # the platform still sends the magic header.
  undeletable.header = (
    "--#EVENT #{therebox[key].service} #{therebox[key].event}"
  )
  undeletable.script = ''
  undeletable.local_path = Pathname.new(
    File.join(location, tolocalname(thereitem, key))
  )
  undeletable.phantom = true
  undeletable.undeletable = true
  localbox[key] = undeletable
end

#resurrect_undeletables(localbox, therebox) ⇒ Object



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
# File 'lib/MrMurano/Solution-Services.rb', line 841

def resurrect_undeletables(localbox, therebox)
  localbox = super
  undeletables = ($cfg['eventhandler.undeletable'] || '').split
  (therebox.keys & localbox.keys).each do |key|
    # The key exists in both the local project and on the remote.
    # If the service is an undeletable, the server will have created
    # the service automatically. If the user has a local file for the
    # same service, we wouldn't know that the two services differ
    # except for the timestamps. But under rspec, the server will create
    # the service at near the same time that the test creates the local
    # file, so the timestamps might fall within 1 second of each other,
    # which the CLI would consider the same. So mark undeletables
    # specially, so that later we can do an explicit dodiff if needed.
    localitem = localbox[key]
    next unless undeletable?(localitem, undeletables)
    localitem.undeletable = true
  end
  (therebox.keys - localbox.keys).each do |key|
    # The key exists in therebox but not localbox.
    thereitem = therebox[key]
    next unless undeletable?(thereitem, undeletables)
    resurrect_undeletable(key, localbox, therebox, thereitem)
  end
  localbox
end

#skip?(item, skiplist) ⇒ Boolean

Returns:

  • (Boolean)


598
599
600
601
602
603
# File 'lib/MrMurano/Solution-Services.rb', line 598

def skip?(item, skiplist)
  return false unless item.key?(:service) && item.key?(:event)
  skiplist.any? do |svc_evt|
    cmp_svc_evt(item, svc_evt)
  end
end

#synckey(item) ⇒ Object



541
542
543
# File 'lib/MrMurano/Solution-Services.rb', line 541

def synckey(item)
  "#{item[:service]}_#{item[:event]}"
end

#to_remote_item_create(md, path, header, lineno) ⇒ Object



694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
# File 'lib/MrMurano/Solution-Services.rb', line 694

def to_remote_item_create(md, path, header, lineno)
  service, config_var = decode_config_var(md[:service])
  event_event, event_type = resolve_event_type(service, md[:event])
  header = config_vars_decode(header, event_event)
  svc_alias = config_var if service != md[:service]
  EventHandlerItem.new(
    # Skipping: alias, updated_at, created_at, solution_id, phantom, undeletable
    # name, id, line_end, diff, selected, synckey, synctype, updated_at, dup_count
    local_path: path,
    header: header,
    script: '',
    line_beg: lineno,
    service: service,
    event: event_event,
    type: event_type,
    svc_alias: svc_alias,
  )
end

#to_remote_item_legacy_check(cur, path, from, line_end) ⇒ Object



713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
# File 'lib/MrMurano/Solution-Services.rb', line 713

def to_remote_item_legacy_check(cur, path, from, line_end)
  return cur unless cur.nil? && $project['services.legacy'].is_a?(Hash)
  spath = path.relative_path_from(from)
  debug "No headers: #{spath}"
  service, event = $project['services.legacy'][spath.to_s]
  debug "Legacy lookup #{spath} => [#{service}, #{event}]"
  unless service.nil? || event.nil?
    warning %(Event in #{spath} missing header, but has legacy support.)
    warning %(Please add the header "--#EVENT #{service} #{event}")
    cur = EventHandlerItem.new(
      service: service,
      event: event,
      type: nil,
      local_path: path,
      line_beg: 1,
      line_end: line_end,
      script: path.read, # FIXME: ick, fix this.
    )
  end
  cur
end

#to_remote_items(from, path) ⇒ Object



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
# File 'lib/MrMurano/Solution-Services.rb', line 662

def to_remote_items(from, path)
  # Parses file which may contain multiple events. Return array of Items.
  items = []
  cur = nil
  lineno = 0
  path = Pathname.new(path) unless path.is_a?(Pathname)
  path.readlines.each do |line|
    lineno += 1
    # @match_header finds a service and an event string, e.g., "--EVENT svc evt\n"
    md = @match_header.match(line)
    if !md.nil?
      cur[:line_end] = lineno - 1 unless cur.nil?
      header = line.strip
      cur = to_remote_item_create(md, path, header, lineno)
      items << cur
    elsif !cur.nil? && !cur[:script].nil?
      cur[:script] += line
    end
    # else, cur.nil?, or no :script (not used by item), so skip this line.
  end

  if !cur.nil?
    cur[:line_end] = lineno
  else
    # If cur is nil here, then we need to do a :legacy check.
    cur = to_remote_item_legacy_check(cur, path, from, lineno)
    items << cur unless cur.nil?
  end

  items
end

#tolocalname(item, _key) ⇒ Object



658
659
660
# File 'lib/MrMurano/Solution-Services.rb', line 658

def tolocalname(item, _key)
  "#{item[:name]}.lua"
end

#undeletable?(item, undeletables) ⇒ Boolean

Returns:

  • (Boolean)


867
868
869
870
871
872
# File 'lib/MrMurano/Solution-Services.rb', line 867

def undeletable?(item, undeletables)
  return false if item.service.to_s.empty? || item.event.to_s.empty?
  undeletables.any? do |svc_evt|
    cmp_svc_evt(item, svc_evt)
  end
end