contextimpl.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. # Copyright 2021 EMQ Technologies Co., Ltd.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import json
  15. import logging
  16. import sys
  17. from .connection import SourceChannel
  18. from .context import Context
  19. class ContextImpl(Context):
  20. def __init__(self, meta: dict):
  21. self.ruleId = meta['ruleId']
  22. self.opId = meta['opId']
  23. self.instanceId = meta['instanceId']
  24. self.emitter = None
  25. def set_emitter(self, emitter: SourceChannel):
  26. self.emitter = emitter
  27. def get_rule_id(self) -> str:
  28. return self.ruleId
  29. def get_op_id(self) -> str:
  30. return self.opId
  31. def get_instance_id(self) -> int:
  32. return self.instanceId
  33. def get_logger(self) -> logging:
  34. return sys.stdout
  35. def emit(self, message: dict, meta: dict):
  36. data = {'message': message, 'meta': meta}
  37. json_str = json.dumps(data)
  38. return self.emitter.send(str.encode(json_str))
  39. def emit_error(self, error: str):
  40. data = {'error': error}
  41. json_str = json.dumps(data)
  42. return self.emitter.send(str.encode(json_str))