Skip to content

engine

engine

Engine

Bases: ABC

Source code in src/qgis_server_light/worker/engine.py
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
class Engine(ABC):  # noqa: B024
    def __init__(
        self,
        context: EngineContext,
        runner_plugins: list[str],
        svg_paths: list[str] | None = None,
        log_level=logging.WARNING,
    ):
        self.qgis = Qgis(svg_paths, log_level)
        self.context = context
        self.layer_cache = LayerCache()
        self.available_runner_classes: dict[str, type[Runner]] = {}
        self.available_runner_classes_by_job_info: dict[str, type[Runner]] = {}
        self.available_job_info_classes: dict[str, type[QslJobInfoParameter]] = {}
        self._load_runner_plugins(runner_plugins)
        logging.debug(self.available_runner_classes)
        logging.debug(self.available_runner_classes_by_job_info)
        logging.debug(self.available_job_info_classes)
        self.info = self._initialize_infos()

    def __del__(self):
        self.qgis.exitQgis()

    def _load_runner_plugins(self, worker_plugins: list[str]):
        for path in worker_plugins:
            loaded_class = self._load_runner_class(path)
            if loaded_class is not None:
                # the runner sets up what it needs from QGIS before any job comes in
                loaded_class.prepare(self.qgis)
                self.available_runner_classes[path] = loaded_class
                self.available_runner_classes_by_job_info[loaded_class.job_info_class.__name__] = (
                    loaded_class
                )
                self.available_job_info_classes[loaded_class.job_info_class.__name__] = (
                    loaded_class.job_info_class
                )

    @staticmethod
    def _load_runner_class(path: str) -> type[Runner] | None:
        """
        Loads a class dynamically at runtime, like:
        "mypackage.mymodule.MyClass"
        """

        module_path, class_name = path.rsplit(".", 1)
        module = importlib.import_module(module_path)
        cls = getattr(module, class_name, None)

        # Ensure the class was loaded correctly
        if cls is None:
            raise ImportError(f"Class '{class_name}' not found in module '{module_path}'.")
        if not inspect.isclass(cls):
            raise TypeError(f"Passed '{class_name}' is not a class.")

        if not issubclass(cls, Runner):
            raise TypeError(
                f"{cls.__name__} is not a plugin as expected (each plugin has to inherit "
                f"from qgis_server_light.worker.job.common.Job)."
            )

        return cls

    def _initialize_infos(self):
        worker_info = EngineInfo(
            id=str(uuid.uuid4()),
            qgis_info=QgisInfo(
                version=version(),
                version_name=version_name(),
                path=self.qgis.prefixPath(),
            ),
            status=Status.STARTING,
            started=datetime.datetime.now().timestamp(),
        )
        logging.debug(json.dumps(asdict(worker_info), indent=2))
        return worker_info

    def runner_plugin_by_job_info(self, job_info: QslJobInfoParameter) -> type[Runner]:
        """
        Here we decide which plugin we load dynamically out of the available ones.

        Args:
            job_info: Is the parameter instance we check the available worker classes and there the
                job_info_class at each.

        Returns:
            The selected runner class
        """
        try:
            return self.available_runner_classes_by_job_info[job_info.__class__.__name__]
        except KeyError as e:
            raise RuntimeError(f"Type {type(job_info)} not supported") from e

    def process(
        self, job_info: QslJobInfoParameter, feedback: QgsProcessingFeedback | None = None
    ) -> JobResult:
        """Hands the job to the runner which is responsible for it.

        Every runner gets its own copy of the context, so a runner can't change
        what the next job sees.

        Args:
            job_info: The job to solve.
            feedback: The feedback the job reports its progress to and is canceled
                through, `None` if nobody listens.

        Returns:
            The result the runner produced.
        """
        self.layer_cache.evict_expired()
        runner_class = self.runner_plugin_by_job_info(job_info)
        context = JobContext(**asdict(self.context))
        context.feedback = feedback
        runner = runner_class(
            self.qgis,
            context,
            job_info,
            layer_cache=self.layer_cache,
        )
        return runner.run()

    @property
    def status(self):
        return self.info.status.value

    def set_waiting(self):
        self.info.status = Status.WAITING

    def set_crashed(self):
        self.info.status = Status.CRASHED

    def set_processing(self):
        self.info.status = Status.PROCESSING

available_job_info_classes: dict[str, type[QslJobInfoParameter]] = {} instance-attribute

available_runner_classes: dict[str, type[Runner]] = {} instance-attribute

available_runner_classes_by_job_info: dict[str, type[Runner]] = {} instance-attribute

context = context instance-attribute

info = self._initialize_infos() instance-attribute

layer_cache = LayerCache() instance-attribute

qgis = Qgis(svg_paths, log_level) instance-attribute

status property

__del__()

Source code in src/qgis_server_light/worker/engine.py
51
52
def __del__(self):
    self.qgis.exitQgis()

__init__(context: EngineContext, runner_plugins: list[str], svg_paths: list[str] | None = None, log_level=logging.WARNING)

Source code in src/qgis_server_light/worker/engine.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def __init__(
    self,
    context: EngineContext,
    runner_plugins: list[str],
    svg_paths: list[str] | None = None,
    log_level=logging.WARNING,
):
    self.qgis = Qgis(svg_paths, log_level)
    self.context = context
    self.layer_cache = LayerCache()
    self.available_runner_classes: dict[str, type[Runner]] = {}
    self.available_runner_classes_by_job_info: dict[str, type[Runner]] = {}
    self.available_job_info_classes: dict[str, type[QslJobInfoParameter]] = {}
    self._load_runner_plugins(runner_plugins)
    logging.debug(self.available_runner_classes)
    logging.debug(self.available_runner_classes_by_job_info)
    logging.debug(self.available_job_info_classes)
    self.info = self._initialize_infos()

process(job_info: QslJobInfoParameter, feedback: QgsProcessingFeedback | None = None) -> JobResult

Hands the job to the runner which is responsible for it.

Every runner gets its own copy of the context, so a runner can't change what the next job sees.

Parameters:

  • job_info (QslJobInfoParameter) –

    The job to solve.

  • feedback (QgsProcessingFeedback | None, default: None ) –

    The feedback the job reports its progress to and is canceled through, None if nobody listens.

Returns:

  • JobResult –

    The result the runner produced.

Source code in src/qgis_server_light/worker/engine.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
def process(
    self, job_info: QslJobInfoParameter, feedback: QgsProcessingFeedback | None = None
) -> JobResult:
    """Hands the job to the runner which is responsible for it.

    Every runner gets its own copy of the context, so a runner can't change
    what the next job sees.

    Args:
        job_info: The job to solve.
        feedback: The feedback the job reports its progress to and is canceled
            through, `None` if nobody listens.

    Returns:
        The result the runner produced.
    """
    self.layer_cache.evict_expired()
    runner_class = self.runner_plugin_by_job_info(job_info)
    context = JobContext(**asdict(self.context))
    context.feedback = feedback
    runner = runner_class(
        self.qgis,
        context,
        job_info,
        layer_cache=self.layer_cache,
    )
    return runner.run()

runner_plugin_by_job_info(job_info: QslJobInfoParameter) -> type[Runner]

Here we decide which plugin we load dynamically out of the available ones.

Parameters:

  • job_info (QslJobInfoParameter) –

    Is the parameter instance we check the available worker classes and there the job_info_class at each.

Returns:

  • type[Runner] –

    The selected runner class

Source code in src/qgis_server_light/worker/engine.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def runner_plugin_by_job_info(self, job_info: QslJobInfoParameter) -> type[Runner]:
    """
    Here we decide which plugin we load dynamically out of the available ones.

    Args:
        job_info: Is the parameter instance we check the available worker classes and there the
            job_info_class at each.

    Returns:
        The selected runner class
    """
    try:
        return self.available_runner_classes_by_job_info[job_info.__class__.__name__]
    except KeyError as e:
        raise RuntimeError(f"Type {type(job_info)} not supported") from e

set_crashed()

Source code in src/qgis_server_light/worker/engine.py
158
159
def set_crashed(self):
    self.info.status = Status.CRASHED

set_processing()

Source code in src/qgis_server_light/worker/engine.py
161
162
def set_processing(self):
    self.info.status = Status.PROCESSING

set_waiting()

Source code in src/qgis_server_light/worker/engine.py
155
156
def set_waiting(self):
    self.info.status = Status.WAITING

EngineContext dataclass

Bases: JobContext

The engine hands its context on to every job, so it carries exactly the attributes of JobContext. A new attribute is therefore added in one place only.

Source code in src/qgis_server_light/worker/engine.py
24
25
26
27
28
@dataclass
class EngineContext(JobContext):
    """The engine hands its context on to every job, so it carries exactly the
    attributes of `JobContext`. A new attribute is therefore added in one place only.
    """

__init__(base_path: str | Path, process_allowlist: list[str] = list(), process_output_dir: str | Path | None = None, process_internal_allowlist: list[str] = list(), process_timeout: float | None = None, process_max_output_size: int | None = None, process_max_features: int | None = None, feedback: QgsProcessingFeedback | None = None) -> None