Skip to content

Worker

worker

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

image_utils

job_guard

JobDismissedError

Bases: Exception

The job was dismissed while it ran.

Source code in src/qgis_server_light/worker/job_guard.py
11
12
class JobDismissedError(Exception):
    """The job was dismissed while it ran."""

JobGuard

Watches a running process job from its own thread, the algorithm blocks the thread of the worker. Once the job is dismissed, runs longer than timeout or its outputs grow beyond max_output_size, the guard cancels the feedback of the job. QGIS algorithms check it and stop. Native code which doesn't check it would keep the worker busy forever, so if the job doesn't stop within cancel_grace the guard abandons it and ends the worker process the hard way, its restart brings it back.

Used as context manager around the job, it hands out the feedback the job runs with and turns the error of a job it canceled into the reason it canceled it.

Attributes:

  • check_interval (float) –

    Seconds between two looks at the job.

  • cancel_grace (float) –

    Seconds a canceled job has to stop before the worker exits.

Source code in src/qgis_server_light/worker/job_guard.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 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
class JobGuard:
    """Watches a running process job from its own thread, the algorithm blocks the
    thread of the worker. Once the job is dismissed, runs longer than `timeout` or its
    outputs grow beyond `max_output_size`, the guard cancels the feedback of the job.
    QGIS algorithms check it and stop. Native code which doesn't check it would keep the
    worker busy forever, so if the job doesn't stop within `cancel_grace` the guard
    abandons it and ends the worker process the hard way, its restart brings it back.

    Used as context manager around the job, it hands out the feedback the job runs with
    and turns the error of a job it canceled into the reason it canceled it.

    Attributes:
        check_interval: Seconds between two looks at the job.
        cancel_grace: Seconds a canceled job has to stop before the worker exits.
    """

    check_interval: float = 1.0
    cancel_grace: float = 30.0

    def __init__(
        self,
        feedback: QgsProcessingFeedback,
        dismissed: Callable[[], bool],
        abandon: Callable[[Exception], None],
        timeout: float | None = None,
        output_dir: Path | None = None,
        max_output_size: int | None = None,
    ):
        """
        Args:
            feedback: The feedback the job runs with.
            dismissed: Tells if somebody dismissed the job.
            abandon: Finishes the job for good before the worker exits, it gets the
                reason the job was canceled for.
            timeout: Seconds the job may run, `None` for no limit.
            output_dir: The dir the job writes its outputs to.
            max_output_size: Bytes the job may write into `output_dir`, `None` for no
                limit.
        """
        self.feedback = feedback
        self.dismissed = dismissed
        self.abandon = abandon
        self.timeout = timeout
        self.output_dir = output_dir
        self.max_output_size = max_output_size
        self.reason: Exception | None = None
        self.finished = threading.Event()
        self.thread = threading.Thread(target=self.watch, name="job-guard", daemon=True)

    def __enter__(self) -> QgsProcessingFeedback:
        """Starts the clock of the timeout and the watch.

        Returns:
            The feedback the job has to run with, it is the line the guard pulls on.
        """
        self.started = time.monotonic()
        self.thread.start()
        return self.feedback

    def __exit__(self, exc_type, exc, traceback):
        """Stops the watch once the job is over, however it ended. The error of a job the
        guard canceled tells little more than "canceled", so it is replaced by the reason,
        the original stays attached as cause.

        Raises:
            JobDismissedError: If the guard canceled the job because it was dismissed.
            JobLimitExceededError: If the guard canceled the job because of a limit.
        """
        self.finished.set()
        self.thread.join()
        # a job which finished before it noticed the cancel keeps its result
        if exc is not None and self.reason is not None:
            raise self.reason from exc
        return False

    def watch(self):
        """The loop of the guard thread: it looks at the job every `check_interval`
        seconds until the job is over or there is a reason to cancel it. After the cancel
        it gives the job `cancel_grace` seconds to stop, a job ignoring it is abandoned
        together with the worker process.
        """
        while (reason := self.check()) is None:
            if self.finished.wait(self.check_interval):
                return
        self.reason = reason
        logging.warning(f"Canceling the job: {reason}")
        self.feedback.cancel()
        if self.finished.wait(self.cancel_grace):
            return
        logging.error(
            f"The job did not stop {self.cancel_grace} seconds after it was canceled, "
            "the worker exits"
        )
        self.abandon(reason)
        logging.shutdown()
        # the algorithm holds the main thread, only leaving the process stops it
        os._exit(1)

    def check(self) -> Exception | None:
        """Looks at the job once.

        Returns:
            The reason to cancel the job, `None` if it may go on.
        """
        try:
            if self.dismissed():
                return JobDismissedError("The job was dismissed.")
        except Exception as e:
            # a hiccup of redis must not end the guard, the next look asks again
            logging.warning(f"Could not check if the job was dismissed: {e}")
        if self.timeout and time.monotonic() - self.started > self.timeout:
            return JobLimitExceededError(f"The job ran longer than {self.timeout} seconds.")
        if self.max_output_size and self.output_size() > self.max_output_size:
            return JobLimitExceededError(
                f"The outputs of the job grew beyond {self.max_output_size} bytes."
            )
        return None

    def output_size(self) -> int:
        """The bytes the job has written so far."""
        if self.output_dir is None or not self.output_dir.is_dir():
            return 0
        size = 0
        for path in self.output_dir.rglob("*"):
            # the algorithm may remove a temporary file while we count
            try:
                if path.is_file():
                    size += path.stat().st_size
            except OSError:
                continue
        return size
abandon = abandon instance-attribute
cancel_grace: float = 30.0 class-attribute instance-attribute
check_interval: float = 1.0 class-attribute instance-attribute
dismissed = dismissed instance-attribute
feedback = feedback instance-attribute
finished = threading.Event() instance-attribute
max_output_size = max_output_size instance-attribute
output_dir = output_dir instance-attribute
reason: Exception | None = None instance-attribute
thread = threading.Thread(target=(self.watch), name='job-guard', daemon=True) instance-attribute
timeout = timeout instance-attribute
__enter__() -> QgsProcessingFeedback

Starts the clock of the timeout and the watch.

Returns:

  • QgsProcessingFeedback –

    The feedback the job has to run with, it is the line the guard pulls on.

Source code in src/qgis_server_light/worker/job_guard.py
68
69
70
71
72
73
74
75
76
def __enter__(self) -> QgsProcessingFeedback:
    """Starts the clock of the timeout and the watch.

    Returns:
        The feedback the job has to run with, it is the line the guard pulls on.
    """
    self.started = time.monotonic()
    self.thread.start()
    return self.feedback
__exit__(exc_type, exc, traceback)

Stops the watch once the job is over, however it ended. The error of a job the guard canceled tells little more than "canceled", so it is replaced by the reason, the original stays attached as cause.

Raises:

Source code in src/qgis_server_light/worker/job_guard.py
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
def __exit__(self, exc_type, exc, traceback):
    """Stops the watch once the job is over, however it ended. The error of a job the
    guard canceled tells little more than "canceled", so it is replaced by the reason,
    the original stays attached as cause.

    Raises:
        JobDismissedError: If the guard canceled the job because it was dismissed.
        JobLimitExceededError: If the guard canceled the job because of a limit.
    """
    self.finished.set()
    self.thread.join()
    # a job which finished before it noticed the cancel keeps its result
    if exc is not None and self.reason is not None:
        raise self.reason from exc
    return False
__init__(feedback: QgsProcessingFeedback, dismissed: Callable[[], bool], abandon: Callable[[Exception], None], timeout: float | None = None, output_dir: Path | None = None, max_output_size: int | None = None)

Parameters:

  • feedback (QgsProcessingFeedback) –

    The feedback the job runs with.

  • dismissed (Callable[[], bool]) –

    Tells if somebody dismissed the job.

  • abandon (Callable[[Exception], None]) –

    Finishes the job for good before the worker exits, it gets the reason the job was canceled for.

  • timeout (float | None, default: None ) –

    Seconds the job may run, None for no limit.

  • output_dir (Path | None, default: None ) –

    The dir the job writes its outputs to.

  • max_output_size (int | None, default: None ) –

    Bytes the job may write into output_dir, None for no limit.

Source code in src/qgis_server_light/worker/job_guard.py
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
def __init__(
    self,
    feedback: QgsProcessingFeedback,
    dismissed: Callable[[], bool],
    abandon: Callable[[Exception], None],
    timeout: float | None = None,
    output_dir: Path | None = None,
    max_output_size: int | None = None,
):
    """
    Args:
        feedback: The feedback the job runs with.
        dismissed: Tells if somebody dismissed the job.
        abandon: Finishes the job for good before the worker exits, it gets the
            reason the job was canceled for.
        timeout: Seconds the job may run, `None` for no limit.
        output_dir: The dir the job writes its outputs to.
        max_output_size: Bytes the job may write into `output_dir`, `None` for no
            limit.
    """
    self.feedback = feedback
    self.dismissed = dismissed
    self.abandon = abandon
    self.timeout = timeout
    self.output_dir = output_dir
    self.max_output_size = max_output_size
    self.reason: Exception | None = None
    self.finished = threading.Event()
    self.thread = threading.Thread(target=self.watch, name="job-guard", daemon=True)
check() -> Exception | None

Looks at the job once.

Returns:

  • Exception | None –

    The reason to cancel the job, None if it may go on.

Source code in src/qgis_server_light/worker/job_guard.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
def check(self) -> Exception | None:
    """Looks at the job once.

    Returns:
        The reason to cancel the job, `None` if it may go on.
    """
    try:
        if self.dismissed():
            return JobDismissedError("The job was dismissed.")
    except Exception as e:
        # a hiccup of redis must not end the guard, the next look asks again
        logging.warning(f"Could not check if the job was dismissed: {e}")
    if self.timeout and time.monotonic() - self.started > self.timeout:
        return JobLimitExceededError(f"The job ran longer than {self.timeout} seconds.")
    if self.max_output_size and self.output_size() > self.max_output_size:
        return JobLimitExceededError(
            f"The outputs of the job grew beyond {self.max_output_size} bytes."
        )
    return None
output_size() -> int

The bytes the job has written so far.

Source code in src/qgis_server_light/worker/job_guard.py
137
138
139
140
141
142
143
144
145
146
147
148
149
def output_size(self) -> int:
    """The bytes the job has written so far."""
    if self.output_dir is None or not self.output_dir.is_dir():
        return 0
    size = 0
    for path in self.output_dir.rglob("*"):
        # the algorithm may remove a temporary file while we count
        try:
            if path.is_file():
                size += path.stat().st_size
        except OSError:
            continue
    return size
watch()

The loop of the guard thread: it looks at the job every check_interval seconds until the job is over or there is a reason to cancel it. After the cancel it gives the job cancel_grace seconds to stop, a job ignoring it is abandoned together with the worker process.

Source code in src/qgis_server_light/worker/job_guard.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def watch(self):
    """The loop of the guard thread: it looks at the job every `check_interval`
    seconds until the job is over or there is a reason to cancel it. After the cancel
    it gives the job `cancel_grace` seconds to stop, a job ignoring it is abandoned
    together with the worker process.
    """
    while (reason := self.check()) is None:
        if self.finished.wait(self.check_interval):
            return
    self.reason = reason
    logging.warning(f"Canceling the job: {reason}")
    self.feedback.cancel()
    if self.finished.wait(self.cancel_grace):
        return
    logging.error(
        f"The job did not stop {self.cancel_grace} seconds after it was canceled, "
        "the worker exits"
    )
    self.abandon(reason)
    logging.shutdown()
    # the algorithm holds the main thread, only leaving the process stops it
    os._exit(1)

JobLimitExceededError

Bases: Exception

The job ran too long or wrote too much.

Source code in src/qgis_server_light/worker/job_guard.py
15
16
class JobLimitExceededError(Exception):
    """The job ran too long or wrote too much."""

layer_cache

DEFAULT_TTL_SECONDS = 24 * 60 * 60 module-attribute

LayerCache

Bases: MutableMapping[str, QgsMapLayer]

Layers opened by the worker, shared by all jobs of the worker process.

Entries which were not used for longer than the TTL are evicted by evict_expired. This bounds the growth caused by layers which are not requested anymore (e.g. after a project was changed). It does not bound the number of layers used within one TTL.

Not thread safe: only the thread processing the jobs may access it.

Source code in src/qgis_server_light/worker/layer_cache.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
class LayerCache(MutableMapping[str, QgsMapLayer]):
    """Layers opened by the worker, shared by all jobs of the worker process.

    Entries which were not used for longer than the TTL are evicted by
    `evict_expired`. This bounds the growth caused by layers which are not
    requested anymore (e.g. after a project was changed). It does not bound the
    number of layers used within one TTL.

    Not thread safe: only the thread processing the jobs may access it.
    """

    def __init__(self, ttl_seconds: float = DEFAULT_TTL_SECONDS) -> None:
        self.ttl_seconds = ttl_seconds
        self._layers: dict[str, QgsMapLayer] = {}
        self._last_used: dict[str, float] = {}

    def __getitem__(self, cache_name: str) -> QgsMapLayer:
        layer = self._layers[cache_name]
        self._last_used[cache_name] = monotonic()
        return layer

    def __setitem__(self, cache_name: str, layer: QgsMapLayer) -> None:
        self._layers[cache_name] = layer
        self._last_used[cache_name] = monotonic()

    def __delitem__(self, cache_name: str) -> None:
        del self._layers[cache_name]
        del self._last_used[cache_name]

    def __contains__(self, cache_name: object) -> bool:
        return cache_name in self._layers

    def __iter__(self) -> Iterator[str]:
        return iter(self._layers)

    def __len__(self) -> int:
        return len(self._layers)

    def evict_expired(self) -> int:
        """Evicts all layers which were not used within the TTL.

        Returns:
            The number of evicted layers.
        """
        expired_before = monotonic() - self.ttl_seconds
        expired = [name for name, used in self._last_used.items() if used < expired_before]
        for cache_name in expired:
            del self[cache_name]
        if expired:
            # cache names contain the layer source (credentials), they are not logged
            logging.info(
                f"Evicted {len(expired)} layers unused for more than {self.ttl_seconds}s "
                f"from cache, {len(self)} layers remain"
            )
        return len(expired)
ttl_seconds = ttl_seconds instance-attribute
__contains__(cache_name: object) -> bool
Source code in src/qgis_server_light/worker/layer_cache.py
39
40
def __contains__(self, cache_name: object) -> bool:
    return cache_name in self._layers
__delitem__(cache_name: str) -> None
Source code in src/qgis_server_light/worker/layer_cache.py
35
36
37
def __delitem__(self, cache_name: str) -> None:
    del self._layers[cache_name]
    del self._last_used[cache_name]
__getitem__(cache_name: str) -> QgsMapLayer
Source code in src/qgis_server_light/worker/layer_cache.py
26
27
28
29
def __getitem__(self, cache_name: str) -> QgsMapLayer:
    layer = self._layers[cache_name]
    self._last_used[cache_name] = monotonic()
    return layer
__init__(ttl_seconds: float = DEFAULT_TTL_SECONDS) -> None
Source code in src/qgis_server_light/worker/layer_cache.py
21
22
23
24
def __init__(self, ttl_seconds: float = DEFAULT_TTL_SECONDS) -> None:
    self.ttl_seconds = ttl_seconds
    self._layers: dict[str, QgsMapLayer] = {}
    self._last_used: dict[str, float] = {}
__iter__() -> Iterator[str]
Source code in src/qgis_server_light/worker/layer_cache.py
42
43
def __iter__(self) -> Iterator[str]:
    return iter(self._layers)
__len__() -> int
Source code in src/qgis_server_light/worker/layer_cache.py
45
46
def __len__(self) -> int:
    return len(self._layers)
__setitem__(cache_name: str, layer: QgsMapLayer) -> None
Source code in src/qgis_server_light/worker/layer_cache.py
31
32
33
def __setitem__(self, cache_name: str, layer: QgsMapLayer) -> None:
    self._layers[cache_name] = layer
    self._last_used[cache_name] = monotonic()
evict_expired() -> int

Evicts all layers which were not used within the TTL.

Returns:

  • int –

    The number of evicted layers.

Source code in src/qgis_server_light/worker/layer_cache.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def evict_expired(self) -> int:
    """Evicts all layers which were not used within the TTL.

    Returns:
        The number of evicted layers.
    """
    expired_before = monotonic() - self.ttl_seconds
    expired = [name for name, used in self._last_used.items() if used < expired_before]
    for cache_name in expired:
        del self[cache_name]
    if expired:
        # cache names contain the layer source (credentials), they are not logged
        logging.info(
            f"Evicted {len(expired)} layers unused for more than {self.ttl_seconds}s "
            f"from cache, {len(self)} layers remain"
        )
    return len(expired)

qgis

CredentialsHelper

Bases: QgsCredentials

Source code in src/qgis_server_light/worker/qgis.py
 8
 9
10
11
12
13
14
15
16
17
18
class CredentialsHelper(QgsCredentials):
    def __init__(self):
        super().__init__()
        self.setInstance(self)

    def request(self, realm, username, password, message):
        logging.warning(message)
        return True, None, None

    def requestMasterPassword(self, password, stored):
        logging.warning("Master password requested")
__init__()
Source code in src/qgis_server_light/worker/qgis.py
 9
10
11
def __init__(self):
    super().__init__()
    self.setInstance(self)
request(realm, username, password, message)
Source code in src/qgis_server_light/worker/qgis.py
13
14
15
def request(self, realm, username, password, message):
    logging.warning(message)
    return True, None, None
requestMasterPassword(password, stored)
Source code in src/qgis_server_light/worker/qgis.py
17
18
def requestMasterPassword(self, password, stored):
    logging.warning("Master password requested")

Qgis(svg_paths: list[str] | None, log_level)

Source code in src/qgis_server_light/worker/qgis.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def Qgis(svg_paths: list[str] | None, log_level):
    os.environ["QT_QPA_PLATFORM"] = "offscreen"
    qgs = QgsApplication([], False)
    qgs.initQgis()
    if svg_paths:
        _svg_paths = qgs.svgPaths()
        # we do fast set algebra to always have unique list of paths
        # https://docs.python.org/3/library/stdtypes.html#frozenset.union
        qgs.setSvgPaths(list(set(_svg_paths) | set(svg_paths)))
    logging.debug(f"Application Path: {qgs.prefixPath()}")
    logging.info(f"QGIS Version {Qgis_.version()}")

    if log_level == logging.DEBUG:
        logging.debug("QGIS Debugging enabled")

        def write_log_message(message, tag, level):
            logging.debug(f"{tag}({level}): {message}")

        QgsApplication.messageLog().messageReceived.connect(write_log_message)

        qgs.credentialsHelper = CredentialsHelper()

    return qgs

version() -> int

Source code in src/qgis_server_light/worker/qgis.py
46
47
def version() -> int:
    return Qgis_.versionInt()

version_name() -> str

Source code in src/qgis_server_light/worker/qgis.py
50
51
def version_name() -> str:
    return Qgis_.version()

qgis_type_serializer

QDateConverter

Bases: Converter

Source code in src/qgis_server_light/worker/qgis_type_serializer.py
 9
10
11
12
13
14
15
16
17
18
19
class QDateConverter(Converter):
    format = "yyyy-MM-dd"

    def deserialize(self, value: str, **kwargs: Any) -> QDate:
        return QDate.fromString(value, self.format)

    def serialize(self, value: QDate, **kwargs: Any) -> str | None:
        if value:
            return value.toString(self.format)
        else:
            return None
format = 'yyyy-MM-dd' class-attribute instance-attribute
deserialize(value: str, **kwargs: Any) -> QDate
Source code in src/qgis_server_light/worker/qgis_type_serializer.py
12
13
def deserialize(self, value: str, **kwargs: Any) -> QDate:
    return QDate.fromString(value, self.format)
serialize(value: QDate, **kwargs: Any) -> str | None
Source code in src/qgis_server_light/worker/qgis_type_serializer.py
15
16
17
18
19
def serialize(self, value: QDate, **kwargs: Any) -> str | None:
    if value:
        return value.toString(self.format)
    else:
        return None

QDateTimeConverter

Bases: Converter

Source code in src/qgis_server_light/worker/qgis_type_serializer.py
22
23
24
25
26
27
28
29
30
31
32
class QDateTimeConverter(Converter):
    format = Qt.DateFormat.ISODate

    def deserialize(self, value: str, **kwargs: Any) -> QDateTime:
        return QDateTime.fromString(value, self.format)

    def serialize(self, value: QDateTime, **kwargs: Any) -> str | None:
        if value:
            return value.toString(self.format)
        else:
            return None
format = Qt.DateFormat.ISODate class-attribute instance-attribute
deserialize(value: str, **kwargs: Any) -> QDateTime
Source code in src/qgis_server_light/worker/qgis_type_serializer.py
25
26
def deserialize(self, value: str, **kwargs: Any) -> QDateTime:
    return QDateTime.fromString(value, self.format)
serialize(value: QDateTime, **kwargs: Any) -> str | None
Source code in src/qgis_server_light/worker/qgis_type_serializer.py
28
29
30
31
32
def serialize(self, value: QDateTime, **kwargs: Any) -> str | None:
    if value:
        return value.toString(self.format)
    else:
        return None

register_converters_at_runtime()

Source code in src/qgis_server_light/worker/qgis_type_serializer.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@contextmanager
def register_converters_at_runtime():
    def register(custom_type, converter_instance, registered_types):
        converter.register_converter(custom_type, converter_instance)
        registered_types.append(custom_type)

    registered = []
    try:
        register(QDate, QDateConverter(), registered)
        register(QDateTime, QDateTimeConverter(), registered)
        # register further types here
        yield
    finally:
        for tp in registered:
            with contextlib.suppress(KeyError):
                converter.unregister_converter(tp)

redis

DEFAULT_DATA_ROOT = '/io/data' module-attribute

DEFAULT_PROCESS_ALLOWLIST = ','.join(['native:buffer', 'native:centroids']) module-attribute

DEFAULT_PROCESS_MAX_FEATURES = 1000000 module-attribute

DEFAULT_PROCESS_MAX_OUTPUT_SIZE = 1024 module-attribute

DEFAULT_PROCESS_OUTPUT_DIR = '/io/process_output' module-attribute

DEFAULT_PROCESS_TIMEOUT = 3600 module-attribute

DEFAULT_RUNNER_PLUGINS = ':'.join(['qgis_server_light.worker.runner.render.RenderRunner', 'qgis_server_light.worker.runner.legend.GetLegendRunner', 'qgis_server_light.worker.runner.feature.GetFeatureRunner', 'qgis_server_light.worker.runner.crs.CrsRunner']) module-attribute

DEFAULT_SVG_PATH = '/io/svg' module-attribute

engine_classes: dict[str, type[RedisEngine]] = {'publish': RedisPublishEngine, 'state': RedisStateEngine} module-attribute

JobProgress

Writes the progress a running job reports into its job hash. QGIS reports the progress per feature as float, so only a change of the full percentage is written, that's at most 101 writes per job.

Source code in src/qgis_server_light/worker/redis.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class JobProgress:
    """Writes the progress a running job reports into its job hash. QGIS
    reports the progress per feature as float, so only a change of the full
    percentage is written, that's at most 101 writes per job.
    """

    def __init__(self, client: Redis, job_key: str, progress_key: str):
        self.client = client
        self.job_key = job_key
        self.progress_key = progress_key
        self.percent: int | None = None

    def __call__(self, progress: float):
        percent = min(max(int(progress), 0), 100)
        if percent == self.percent:
            return
        self.percent = percent
        # written right away and not with the pipeline of the job, which is only
        # executed when the job is finished
        self.client.hset(self.job_key, self.progress_key, percent)
client = client instance-attribute
job_key = job_key instance-attribute
percent: int | None = None instance-attribute
progress_key = progress_key instance-attribute
__call__(progress: float)
Source code in src/qgis_server_light/worker/redis.py
73
74
75
76
77
78
79
80
def __call__(self, progress: float):
    percent = min(max(int(progress), 0), 100)
    if percent == self.percent:
        return
    self.percent = percent
    # written right away and not with the pipeline of the job, which is only
    # executed when the job is finished
    self.client.hset(self.job_key, self.progress_key, percent)
__init__(client: Redis, job_key: str, progress_key: str)
Source code in src/qgis_server_light/worker/redis.py
67
68
69
70
71
def __init__(self, client: Redis, job_key: str, progress_key: str):
    self.client = client
    self.job_key = job_key
    self.progress_key = progress_key
    self.percent: int | None = None

RedisEngine

Bases: Engine

The common part of the redis workers: connecting, registering, the heartbeat and the loop taking jobs from the queue. How a finished job is delivered is decided by the subclasses, so the loop does not need to know about it.

Attributes:

  • protocol (type[RedisProtocol]) –

    The protocol the engine is built on, it defines the queue the engine listens on.

Source code in src/qgis_server_light/worker/redis.py
 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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
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
class RedisEngine(Engine):
    """The common part of the redis workers: connecting, registering, the
    heartbeat and the loop taking jobs from the queue. How a finished job is
    delivered is decided by the subclasses, so the loop does not need to know
    about it.

    Attributes:
        protocol: The protocol the engine is built on, it defines the queue the
            engine listens on.
    """

    protocol: type[RedisProtocol]

    def __init__(
        self,
        context: EngineContext,
        runner_plugins: list[str],
        svg_paths: list | None = None,
        once: bool = False,
    ) -> None:
        self.boot_start = time.time()
        super().__init__(context, runner_plugins, svg_paths)
        # the worker exits after one job, so every job runs in a fresh process
        self.once = once
        # the worker only listens on the queue of its protocol
        self.queue_name = self.protocol.queue_name()
        self.shutdown = False
        self.retry_wait = 0.01
        self.max_retries = 11
        self.info_expire: int = 300
        self.heartbeat_interval = RedisProtocol.worker_heartbeat_interval
        self.heartbeat_thread = None
        self.redis_client: Redis | None = None
        self.processes_json: str | None = None

    def retry_handling_with_jitter(self, count: int):
        if count <= self.max_retries:
            sleep = math.pow(2, count) * self.retry_wait
            logging.warning(f"Retrying in {sleep} seconds...")
            time.sleep(sleep)
        else:
            self.exit_connection_error()

    @staticmethod
    def exit_connection_error():
        logging.error("Shutting down => now connection to Redis")
        exit(404)

    def exit_gracefully(self, signum, frame):
        logging.error(f"Received: {signum}")
        self.shutdown = True
        if self.redis_client is not None:
            self.unregister_worker(self.redis_client)
        exit(0)

    @staticmethod
    def set_job_runtime_status(
        job_id: str,
        pipeline: Pipeline,
        status: str,
        start_time: float,
    ):
        duration = time.time() - start_time
        ts = datetime.datetime.now().isoformat()
        pipeline.hset(RedisProtocol.job_key(job_id), RedisProtocol.job_status_key, status)
        pipeline.hset(
            RedisProtocol.job_key(job_id),
            f"{RedisProtocol.job_timestamp_key}.{status}",
            ts,
        )
        pipeline.hset(RedisProtocol.job_key(job_id), RedisProtocol.job_last_update_key, ts)
        pipeline.hset(RedisProtocol.job_key(job_id), RedisProtocol.job_duration_key, str(duration))
        pipeline.execute()

    def heartbeat(self, client: Redis) -> datetime.datetime:
        """Tells redis that this worker is still alive. Each beat is the full
        advertisement: the worker info with its current status, the last seen
        timestamp, the renewed expiry and the id in the list of workers. The beat
        does not ask redis what it still knows, it simply writes everything again. So
        when redis lost its keys (restart, flush, eviction) the worker is back within
        one heartbeat interval, without anybody having to notice the loss. Only the
        process descriptions are too big for that, the beat asks for them and writes
        them when they are missing.

        Args:
            client: The redis client.

        Returns:
            The UTC timestamp which was written as last seen.
        """
        now = datetime.datetime.now(datetime.UTC)
        pipeline = client.pipeline()
        # writing the full worker info with every beat, so it is back after redis lost
        # its keys (restart, flush, eviction) and it carries the current status
        pipeline.hset(
            RedisProtocol.worker_key(self.info.id),
            mapping={
                RedisProtocol.worker_info_key: JsonSerializer().render(self.info),
                RedisProtocol.worker_last_seen_key: now.isoformat(),
            },
        )
        # renewing the timer, otherwise the worker info expires while the worker is alive
        pipeline.expire(RedisProtocol.worker_key(self.info.id), self.info_expire)
        pipeline.sadd(RedisProtocol.worker_list_name, self.info.id)
        pipeline.execute()
        self.write_missing_processes(client)
        return now

    def register_worker(self, client: Redis):
        """Makes this worker known in redis and cleans up behind workers which vanished
        without unregistering. This way the list of workers heals itself with every
        worker start. The advertising itself is left to the first beat, there is only
        one place which knows what a worker writes.

        Args:
            client: The redis client.
        """
        self.prune_vanished_workers(client)
        # the first beat writes the worker info and adds the worker to the list
        self.heartbeat(client)
        logging.info("Worker was registered in Redis")

    @staticmethod
    def prune_vanished_workers(client: Redis):
        """Removes the ids of workers from the list whose hash expired already. Such a
        worker was killed or lost its container and could not say goodbye, so a
        starting colleague tidies up behind it.

        Args:
            client: The redis client.
        """
        # removing workers from the list which vanished without unregistering (e.g. killed),
        # their info expired already
        for worker_id in client.smembers(RedisProtocol.worker_list_name):
            if not client.exists(RedisProtocol.worker_key(worker_id)):
                client.srem(RedisProtocol.worker_list_name, worker_id)

    def unregister_worker(self, client: Redis):
        """Removes this worker from redis on a graceful shutdown. If redis is gone
        already, the worker does not insist: its info expires and the next registering
        worker cleans the list.

        Args:
            client: The redis client.
        """
        try:
            client.srem(RedisProtocol.worker_list_name, self.info.id)
            client.delete(RedisProtocol.worker_key(self.info.id))
        except RedisError as e:
            # the info expires on its own, the next registering worker cleans the list
            logging.warning(f"Worker could not be unregistered from Redis: {e}")
        else:
            logging.info("Worker was unregistered from Redis")

    def describe_processes(self):
        """Describes the processes the worker serves once on boot, the beats only pass
        the result on. Workers without the process runner don't serve processes and
        describe nothing."""
        process_runner_class = self.available_runner_classes_by_job_info.get(
            QslJobInfoExecuteProcess.__name__
        )
        if process_runner_class is None:
            return
        process_descriptions = process_runner_class.info(self.qgis, self.context)
        self.processes_json = JsonSerializer(dict_factory=DictFactory.FILTER_NONE).render(
            process_descriptions
        )

    def write_missing_processes(self, client: Redis):
        """Writes the process descriptions into the hash of the worker when they are not
        there. The descriptions are too big to be written with every beat, so the beat
        only asks whether redis still knows them. After redis lost its keys they are
        back within one heartbeat interval like the rest of the worker.

        Args:
            client: The redis client.
        """
        if self.processes_json is None:
            return
        worker_key = RedisProtocol.worker_key(self.info.id)
        if not client.hexists(worker_key, RedisProtocol.worker_processes_key):
            client.hset(worker_key, RedisProtocol.worker_processes_key, self.processes_json)
            logging.info(f"Processes {self.context.served_process_ids} were registered in Redis")

    def retry_connection(self, redis_url: str, count: int):
        logging.warning(f"Could not connect to redis on `{redis_url}`.")
        self.retry_handling_with_jitter(count)

    def start(self, redis_url) -> Redis:
        signal.signal(signal.SIGINT, self.exit_gracefully)
        signal.signal(signal.SIGTERM, self.exit_gracefully)
        r = Redis.from_url(redis_url, decode_responses=True, retry=Retry(ExponentialBackoff(), 0))
        self.wait_for_connection(r, redis_url)
        return r

    def wait_for_connection(self, client: Redis, redis_url: str):
        """Pings redis until it answers, waiting a bit longer after each refused ping.
        It is used on start and whenever the job loop lost the connection. Each outage
        gets the full number of retries, a worker which survived many short hiccups
        should not give up on the next one just because it used them up already.

        Args:
            client: The redis client.
            redis_url: The url of redis, only used to tell in the logs where the
                worker is knocking.
        """
        # the retries are counted per outage, so only one long outage makes the worker
        # give up and not the sum of all short ones
        retry_count = 0
        while True:
            try:
                retry_count += 1
                logging.debug(f"Looking up redis: {redis_url}")
                client.ping()
            except (RedisConnectionError, TimeoutError) as e:
                logging.debug(f"Connection on Redis not successful => {e}")
                self.retry_connection(redis_url, retry_count)
            else:
                break
        logging.info(f"Connection to redis on `{redis_url}`successful.")

    def start_heartbeat_worker(self, client: Redis):
        """Creates an own thread which is responsible for renewing the heartbeat info
        of the worker in redis"""

        def heartbeat_loop():
            while not self.shutdown:
                try:
                    self.heartbeat(client)
                except Exception as e:
                    logging.warning(f"Heartbeat failed: {e}")
                time.sleep(self.heartbeat_interval)

        self.heartbeat_thread = threading.Thread(target=heartbeat_loop, daemon=True)
        self.heartbeat_thread.start()
        logging.info("Heartbeat worker started")

    def run(self, redis_url):
        """Connects to redis, registers the worker, starts the heartbeat and serves jobs
        until the worker is told to stop, or with `once` until it served one. If
        something unexpected breaks the job loop, the worker reports its crash to redis
        before it goes down with the very same error, so the logs still show what
        happened. Exiting on purpose (a signal or giving up on redis) is not a crash.

        Args:
            redis_url: The url of redis, e.g. `redis://qsl-redis:6379`.
        """
        # described before registering, so the first beat writes them along
        self.describe_processes()
        r = self.start(redis_url)
        p = r.pipeline()
        # known before registering, so a signal during the registration still
        # gets unregistered
        self.redis_client = r
        self.register_worker(r)
        # Starte Heartbeat-Worker
        self.start_heartbeat_worker(r)
        try:
            self.serve_jobs(r, p, redis_url)
        except Exception:
            self.report_crash(r)
            raise
        # the loop only ends on its own with `once`. The worker doesn't unregister on
        # purpose, its last beat keeps its processes advertised until the next worker
        # booted, otherwise the consumer would see them vanish between two jobs
        exit(0)

    def report_crash(self, client: Redis):
        """Sets the status to crashed and tells redis right away. When redis is part of
        the trouble, the worker only logs that it couldn't report, the original error
        is the one which matters and must not be covered by a redis one.

        Args:
            client: The redis client.
        """
        self.set_crashed()
        try:
            # beating once more right away, the process might be gone before the
            # heartbeat thread gets its next turn
            self.heartbeat(client)
        except RedisError as e:
            logging.warning(f"Crash could not be reported to Redis: {e}")

    def serve_jobs(self, r: Redis, p: Pipeline, redis_url: str):
        """The job loop: takes the next job from the queue, processes it and publishes
        the result. A failing job is published as an error result, the loop goes on. A
        dismissed job is delivered the same way, but only noted in the log, somebody
        asked for it. With `once` the loop ends after the first job. When the connection
        to redis is lost, the loop waits for it to come back and carries on, the
        heartbeat thread takes care of advertising the worker again.

        Args:
            r: The redis client.
            p: The pipeline the job status and the result are written with.
            redis_url: The url of redis, used when waiting for the connection.
        """
        while not self.shutdown:
            try:
                logging.debug(f"Waiting for jobs on {self.queue_name}")
                self.set_waiting()
                # this is blocking the loop until a job is found in the redis
                # list/queue, if there is one we take it
                result = r.blpop(self.queue_name, timeout=0)
                if result is not None:
                    _, job_id = result
                    self.set_processing()
                    start_time = time.time()
                    job_info = None
                    try:
                        # we inform, that the job is running.
                        self.set_job_runtime_status(job_id, p, Status.RUNNING.value, start_time)

                        job_info_json = r.hget(
                            RedisProtocol.job_key(job_id), RedisProtocol.job_info_key
                        )
                        job_info_class_name = r.hget(
                            RedisProtocol.job_key(job_id), RedisProtocol.job_info_type_key
                        )
                        job_info_class = self.available_job_info_classes[job_info_class_name]
                        job_info = JsonParser().from_string(job_info_json, job_info_class)
                        with self.job_guard(r, job_id, job_info, start_time) as feedback:
                            result: JobResult = self.process(job_info, feedback)
                        self.succeed_job(job_id, job_info, result, p, start_time)
                    except JobDismissedError as e:
                        self.fail_job(job_id, job_info, e, p, start_time)
                        # somebody asked for it, nothing went wrong
                        logging.info(f"{job_id} {e}")
                    except Exception as e:
                        self.fail_job(job_id, job_info, e, p, start_time)

                        # we provide error information to the logs
                        logging.error(e, exc_info=True)
                    finally:
                        p.execute()
                    logging.debug(f"Job duration: {time.time() - start_time}")
                    if self.once:
                        self.shutdown = True
            except (RedisConnectionError, TimeoutError) as _:
                self.wait_for_connection(r, redis_url)
                continue

    def job_guard(
        self, client: Redis, job_id: str, job_info: QslJobInfoParameter, start_time: float
    ) -> AbstractContextManager[QgsProcessingFeedback | None]:
        """What watches the job while it runs, it hands out the feedback the job
        reports its progress to and is canceled through.

        Args:
            client: The redis client.
            job_id: The unique identifier of the job.
            job_info: The job info of the job.
            start_time: The time the job was taken from the queue.

        Returns:
            The context manager around the job, giving the feedback, `None` if nobody
            listens.
        """
        # map related jobs are short and their result is waited for anyway,
        # nobody asks for their progress or stops them
        return nullcontext()

    @abstractmethod
    def succeed_job(
        self,
        job_id: str,
        job_info: QslJobInfoParameter,
        result: JobResult,
        pipeline: Pipeline,
        start_time: float,
    ):
        """Delivers the result of a job which was solved.

        Args:
            job_id: The unique identifier of the job.
            job_info: The job info of the job.
            result: The result the runner returned.
            pipeline: The pipeline holding the transaction.
            start_time: The time the job was taken from the queue.
        """
        pass

    @abstractmethod
    def fail_job(
        self,
        job_id: str,
        job_info: QslJobInfoParameter | None,
        error: Exception,
        pipeline: Pipeline,
        start_time: float,
    ):
        """Delivers the error of a job which failed, or was dismissed while it ran.

        Args:
            job_id: The unique identifier of the job.
            job_info: The job info of the job, `None` if it failed before the
                job info could be read.
            error: The error the job failed with.
            pipeline: The pipeline holding the transaction.
            start_time: The time the job was taken from the queue.
        """
        pass
boot_start = time.time() instance-attribute
heartbeat_interval = RedisProtocol.worker_heartbeat_interval instance-attribute
heartbeat_thread = None instance-attribute
info_expire: int = 300 instance-attribute
max_retries = 11 instance-attribute
once = once instance-attribute
processes_json: str | None = None instance-attribute
protocol: type[RedisProtocol] instance-attribute
queue_name = self.protocol.queue_name() instance-attribute
redis_client: Redis | None = None instance-attribute
retry_wait = 0.01 instance-attribute
shutdown = False instance-attribute
__init__(context: EngineContext, runner_plugins: list[str], svg_paths: list | None = None, once: bool = False) -> None
Source code in src/qgis_server_light/worker/redis.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
def __init__(
    self,
    context: EngineContext,
    runner_plugins: list[str],
    svg_paths: list | None = None,
    once: bool = False,
) -> None:
    self.boot_start = time.time()
    super().__init__(context, runner_plugins, svg_paths)
    # the worker exits after one job, so every job runs in a fresh process
    self.once = once
    # the worker only listens on the queue of its protocol
    self.queue_name = self.protocol.queue_name()
    self.shutdown = False
    self.retry_wait = 0.01
    self.max_retries = 11
    self.info_expire: int = 300
    self.heartbeat_interval = RedisProtocol.worker_heartbeat_interval
    self.heartbeat_thread = None
    self.redis_client: Redis | None = None
    self.processes_json: str | None = None
describe_processes()

Describes the processes the worker serves once on boot, the beats only pass the result on. Workers without the process runner don't serve processes and describe nothing.

Source code in src/qgis_server_light/worker/redis.py
237
238
239
240
241
242
243
244
245
246
247
248
249
def describe_processes(self):
    """Describes the processes the worker serves once on boot, the beats only pass
    the result on. Workers without the process runner don't serve processes and
    describe nothing."""
    process_runner_class = self.available_runner_classes_by_job_info.get(
        QslJobInfoExecuteProcess.__name__
    )
    if process_runner_class is None:
        return
    process_descriptions = process_runner_class.info(self.qgis, self.context)
    self.processes_json = JsonSerializer(dict_factory=DictFactory.FILTER_NONE).render(
        process_descriptions
    )
exit_connection_error() staticmethod
Source code in src/qgis_server_light/worker/redis.py
126
127
128
129
@staticmethod
def exit_connection_error():
    logging.error("Shutting down => now connection to Redis")
    exit(404)
exit_gracefully(signum, frame)
Source code in src/qgis_server_light/worker/redis.py
131
132
133
134
135
136
def exit_gracefully(self, signum, frame):
    logging.error(f"Received: {signum}")
    self.shutdown = True
    if self.redis_client is not None:
        self.unregister_worker(self.redis_client)
    exit(0)
fail_job(job_id: str, job_info: QslJobInfoParameter | None, error: Exception, pipeline: Pipeline, start_time: float) abstractmethod

Delivers the error of a job which failed, or was dismissed while it ran.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

  • job_info (QslJobInfoParameter | None) –

    The job info of the job, None if it failed before the job info could be read.

  • error (Exception) –

    The error the job failed with.

  • pipeline (Pipeline) –

    The pipeline holding the transaction.

  • start_time (float) –

    The time the job was taken from the queue.

Source code in src/qgis_server_light/worker/redis.py
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
@abstractmethod
def fail_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter | None,
    error: Exception,
    pipeline: Pipeline,
    start_time: float,
):
    """Delivers the error of a job which failed, or was dismissed while it ran.

    Args:
        job_id: The unique identifier of the job.
        job_info: The job info of the job, `None` if it failed before the
            job info could be read.
        error: The error the job failed with.
        pipeline: The pipeline holding the transaction.
        start_time: The time the job was taken from the queue.
    """
    pass
heartbeat(client: Redis) -> datetime.datetime

Tells redis that this worker is still alive. Each beat is the full advertisement: the worker info with its current status, the last seen timestamp, the renewed expiry and the id in the list of workers. The beat does not ask redis what it still knows, it simply writes everything again. So when redis lost its keys (restart, flush, eviction) the worker is back within one heartbeat interval, without anybody having to notice the loss. Only the process descriptions are too big for that, the beat asks for them and writes them when they are missing.

Parameters:

  • client (Redis) –

    The redis client.

Returns:

  • datetime –

    The UTC timestamp which was written as last seen.

Source code in src/qgis_server_light/worker/redis.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def heartbeat(self, client: Redis) -> datetime.datetime:
    """Tells redis that this worker is still alive. Each beat is the full
    advertisement: the worker info with its current status, the last seen
    timestamp, the renewed expiry and the id in the list of workers. The beat
    does not ask redis what it still knows, it simply writes everything again. So
    when redis lost its keys (restart, flush, eviction) the worker is back within
    one heartbeat interval, without anybody having to notice the loss. Only the
    process descriptions are too big for that, the beat asks for them and writes
    them when they are missing.

    Args:
        client: The redis client.

    Returns:
        The UTC timestamp which was written as last seen.
    """
    now = datetime.datetime.now(datetime.UTC)
    pipeline = client.pipeline()
    # writing the full worker info with every beat, so it is back after redis lost
    # its keys (restart, flush, eviction) and it carries the current status
    pipeline.hset(
        RedisProtocol.worker_key(self.info.id),
        mapping={
            RedisProtocol.worker_info_key: JsonSerializer().render(self.info),
            RedisProtocol.worker_last_seen_key: now.isoformat(),
        },
    )
    # renewing the timer, otherwise the worker info expires while the worker is alive
    pipeline.expire(RedisProtocol.worker_key(self.info.id), self.info_expire)
    pipeline.sadd(RedisProtocol.worker_list_name, self.info.id)
    pipeline.execute()
    self.write_missing_processes(client)
    return now
job_guard(client: Redis, job_id: str, job_info: QslJobInfoParameter, start_time: float) -> AbstractContextManager[QgsProcessingFeedback | None]

What watches the job while it runs, it hands out the feedback the job reports its progress to and is canceled through.

Parameters:

  • client (Redis) –

    The redis client.

  • job_id (str) –

    The unique identifier of the job.

  • job_info (QslJobInfoParameter) –

    The job info of the job.

  • start_time (float) –

    The time the job was taken from the queue.

Returns:

  • AbstractContextManager[QgsProcessingFeedback | None] –

    The context manager around the job, giving the feedback, None if nobody

  • AbstractContextManager[QgsProcessingFeedback | None] –

    listens.

Source code in src/qgis_server_light/worker/redis.py
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
def job_guard(
    self, client: Redis, job_id: str, job_info: QslJobInfoParameter, start_time: float
) -> AbstractContextManager[QgsProcessingFeedback | None]:
    """What watches the job while it runs, it hands out the feedback the job
    reports its progress to and is canceled through.

    Args:
        client: The redis client.
        job_id: The unique identifier of the job.
        job_info: The job info of the job.
        start_time: The time the job was taken from the queue.

    Returns:
        The context manager around the job, giving the feedback, `None` if nobody
        listens.
    """
    # map related jobs are short and their result is waited for anyway,
    # nobody asks for their progress or stops them
    return nullcontext()
prune_vanished_workers(client: Redis) staticmethod

Removes the ids of workers from the list whose hash expired already. Such a worker was killed or lost its container and could not say goodbye, so a starting colleague tidies up behind it.

Parameters:

  • client (Redis) –

    The redis client.

Source code in src/qgis_server_light/worker/redis.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
@staticmethod
def prune_vanished_workers(client: Redis):
    """Removes the ids of workers from the list whose hash expired already. Such a
    worker was killed or lost its container and could not say goodbye, so a
    starting colleague tidies up behind it.

    Args:
        client: The redis client.
    """
    # removing workers from the list which vanished without unregistering (e.g. killed),
    # their info expired already
    for worker_id in client.smembers(RedisProtocol.worker_list_name):
        if not client.exists(RedisProtocol.worker_key(worker_id)):
            client.srem(RedisProtocol.worker_list_name, worker_id)
register_worker(client: Redis)

Makes this worker known in redis and cleans up behind workers which vanished without unregistering. This way the list of workers heals itself with every worker start. The advertising itself is left to the first beat, there is only one place which knows what a worker writes.

Parameters:

  • client (Redis) –

    The redis client.

Source code in src/qgis_server_light/worker/redis.py
191
192
193
194
195
196
197
198
199
200
201
202
203
def register_worker(self, client: Redis):
    """Makes this worker known in redis and cleans up behind workers which vanished
    without unregistering. This way the list of workers heals itself with every
    worker start. The advertising itself is left to the first beat, there is only
    one place which knows what a worker writes.

    Args:
        client: The redis client.
    """
    self.prune_vanished_workers(client)
    # the first beat writes the worker info and adds the worker to the list
    self.heartbeat(client)
    logging.info("Worker was registered in Redis")
report_crash(client: Redis)

Sets the status to crashed and tells redis right away. When redis is part of the trouble, the worker only logs that it couldn't report, the original error is the one which matters and must not be covered by a redis one.

Parameters:

  • client (Redis) –

    The redis client.

Source code in src/qgis_server_light/worker/redis.py
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
def report_crash(self, client: Redis):
    """Sets the status to crashed and tells redis right away. When redis is part of
    the trouble, the worker only logs that it couldn't report, the original error
    is the one which matters and must not be covered by a redis one.

    Args:
        client: The redis client.
    """
    self.set_crashed()
    try:
        # beating once more right away, the process might be gone before the
        # heartbeat thread gets its next turn
        self.heartbeat(client)
    except RedisError as e:
        logging.warning(f"Crash could not be reported to Redis: {e}")
retry_connection(redis_url: str, count: int)
Source code in src/qgis_server_light/worker/redis.py
267
268
269
def retry_connection(self, redis_url: str, count: int):
    logging.warning(f"Could not connect to redis on `{redis_url}`.")
    self.retry_handling_with_jitter(count)
retry_handling_with_jitter(count: int)
Source code in src/qgis_server_light/worker/redis.py
118
119
120
121
122
123
124
def retry_handling_with_jitter(self, count: int):
    if count <= self.max_retries:
        sleep = math.pow(2, count) * self.retry_wait
        logging.warning(f"Retrying in {sleep} seconds...")
        time.sleep(sleep)
    else:
        self.exit_connection_error()
run(redis_url)

Connects to redis, registers the worker, starts the heartbeat and serves jobs until the worker is told to stop, or with once until it served one. If something unexpected breaks the job loop, the worker reports its crash to redis before it goes down with the very same error, so the logs still show what happened. Exiting on purpose (a signal or giving up on redis) is not a crash.

Parameters:

  • redis_url –

    The url of redis, e.g. redis://qsl-redis:6379.

Source code in src/qgis_server_light/worker/redis.py
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
def run(self, redis_url):
    """Connects to redis, registers the worker, starts the heartbeat and serves jobs
    until the worker is told to stop, or with `once` until it served one. If
    something unexpected breaks the job loop, the worker reports its crash to redis
    before it goes down with the very same error, so the logs still show what
    happened. Exiting on purpose (a signal or giving up on redis) is not a crash.

    Args:
        redis_url: The url of redis, e.g. `redis://qsl-redis:6379`.
    """
    # described before registering, so the first beat writes them along
    self.describe_processes()
    r = self.start(redis_url)
    p = r.pipeline()
    # known before registering, so a signal during the registration still
    # gets unregistered
    self.redis_client = r
    self.register_worker(r)
    # Starte Heartbeat-Worker
    self.start_heartbeat_worker(r)
    try:
        self.serve_jobs(r, p, redis_url)
    except Exception:
        self.report_crash(r)
        raise
    # the loop only ends on its own with `once`. The worker doesn't unregister on
    # purpose, its last beat keeps its processes advertised until the next worker
    # booted, otherwise the consumer would see them vanish between two jobs
    exit(0)
serve_jobs(r: Redis, p: Pipeline, redis_url: str)

The job loop: takes the next job from the queue, processes it and publishes the result. A failing job is published as an error result, the loop goes on. A dismissed job is delivered the same way, but only noted in the log, somebody asked for it. With once the loop ends after the first job. When the connection to redis is lost, the loop waits for it to come back and carries on, the heartbeat thread takes care of advertising the worker again.

Parameters:

  • r (Redis) –

    The redis client.

  • p (Pipeline) –

    The pipeline the job status and the result are written with.

  • redis_url (str) –

    The url of redis, used when waiting for the connection.

Source code in src/qgis_server_light/worker/redis.py
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
def serve_jobs(self, r: Redis, p: Pipeline, redis_url: str):
    """The job loop: takes the next job from the queue, processes it and publishes
    the result. A failing job is published as an error result, the loop goes on. A
    dismissed job is delivered the same way, but only noted in the log, somebody
    asked for it. With `once` the loop ends after the first job. When the connection
    to redis is lost, the loop waits for it to come back and carries on, the
    heartbeat thread takes care of advertising the worker again.

    Args:
        r: The redis client.
        p: The pipeline the job status and the result are written with.
        redis_url: The url of redis, used when waiting for the connection.
    """
    while not self.shutdown:
        try:
            logging.debug(f"Waiting for jobs on {self.queue_name}")
            self.set_waiting()
            # this is blocking the loop until a job is found in the redis
            # list/queue, if there is one we take it
            result = r.blpop(self.queue_name, timeout=0)
            if result is not None:
                _, job_id = result
                self.set_processing()
                start_time = time.time()
                job_info = None
                try:
                    # we inform, that the job is running.
                    self.set_job_runtime_status(job_id, p, Status.RUNNING.value, start_time)

                    job_info_json = r.hget(
                        RedisProtocol.job_key(job_id), RedisProtocol.job_info_key
                    )
                    job_info_class_name = r.hget(
                        RedisProtocol.job_key(job_id), RedisProtocol.job_info_type_key
                    )
                    job_info_class = self.available_job_info_classes[job_info_class_name]
                    job_info = JsonParser().from_string(job_info_json, job_info_class)
                    with self.job_guard(r, job_id, job_info, start_time) as feedback:
                        result: JobResult = self.process(job_info, feedback)
                    self.succeed_job(job_id, job_info, result, p, start_time)
                except JobDismissedError as e:
                    self.fail_job(job_id, job_info, e, p, start_time)
                    # somebody asked for it, nothing went wrong
                    logging.info(f"{job_id} {e}")
                except Exception as e:
                    self.fail_job(job_id, job_info, e, p, start_time)

                    # we provide error information to the logs
                    logging.error(e, exc_info=True)
                finally:
                    p.execute()
                logging.debug(f"Job duration: {time.time() - start_time}")
                if self.once:
                    self.shutdown = True
        except (RedisConnectionError, TimeoutError) as _:
            self.wait_for_connection(r, redis_url)
            continue
set_job_runtime_status(job_id: str, pipeline: Pipeline, status: str, start_time: float) staticmethod
Source code in src/qgis_server_light/worker/redis.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
@staticmethod
def set_job_runtime_status(
    job_id: str,
    pipeline: Pipeline,
    status: str,
    start_time: float,
):
    duration = time.time() - start_time
    ts = datetime.datetime.now().isoformat()
    pipeline.hset(RedisProtocol.job_key(job_id), RedisProtocol.job_status_key, status)
    pipeline.hset(
        RedisProtocol.job_key(job_id),
        f"{RedisProtocol.job_timestamp_key}.{status}",
        ts,
    )
    pipeline.hset(RedisProtocol.job_key(job_id), RedisProtocol.job_last_update_key, ts)
    pipeline.hset(RedisProtocol.job_key(job_id), RedisProtocol.job_duration_key, str(duration))
    pipeline.execute()
start(redis_url) -> Redis
Source code in src/qgis_server_light/worker/redis.py
271
272
273
274
275
276
def start(self, redis_url) -> Redis:
    signal.signal(signal.SIGINT, self.exit_gracefully)
    signal.signal(signal.SIGTERM, self.exit_gracefully)
    r = Redis.from_url(redis_url, decode_responses=True, retry=Retry(ExponentialBackoff(), 0))
    self.wait_for_connection(r, redis_url)
    return r
start_heartbeat_worker(client: Redis)

Creates an own thread which is responsible for renewing the heartbeat info of the worker in redis

Source code in src/qgis_server_light/worker/redis.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
def start_heartbeat_worker(self, client: Redis):
    """Creates an own thread which is responsible for renewing the heartbeat info
    of the worker in redis"""

    def heartbeat_loop():
        while not self.shutdown:
            try:
                self.heartbeat(client)
            except Exception as e:
                logging.warning(f"Heartbeat failed: {e}")
            time.sleep(self.heartbeat_interval)

    self.heartbeat_thread = threading.Thread(target=heartbeat_loop, daemon=True)
    self.heartbeat_thread.start()
    logging.info("Heartbeat worker started")
succeed_job(job_id: str, job_info: QslJobInfoParameter, result: JobResult, pipeline: Pipeline, start_time: float) abstractmethod

Delivers the result of a job which was solved.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

  • job_info (QslJobInfoParameter) –

    The job info of the job.

  • result (JobResult) –

    The result the runner returned.

  • pipeline (Pipeline) –

    The pipeline holding the transaction.

  • start_time (float) –

    The time the job was taken from the queue.

Source code in src/qgis_server_light/worker/redis.py
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
@abstractmethod
def succeed_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter,
    result: JobResult,
    pipeline: Pipeline,
    start_time: float,
):
    """Delivers the result of a job which was solved.

    Args:
        job_id: The unique identifier of the job.
        job_info: The job info of the job.
        result: The result the runner returned.
        pipeline: The pipeline holding the transaction.
        start_time: The time the job was taken from the queue.
    """
    pass
unregister_worker(client: Redis)

Removes this worker from redis on a graceful shutdown. If redis is gone already, the worker does not insist: its info expires and the next registering worker cleans the list.

Parameters:

  • client (Redis) –

    The redis client.

Source code in src/qgis_server_light/worker/redis.py
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def unregister_worker(self, client: Redis):
    """Removes this worker from redis on a graceful shutdown. If redis is gone
    already, the worker does not insist: its info expires and the next registering
    worker cleans the list.

    Args:
        client: The redis client.
    """
    try:
        client.srem(RedisProtocol.worker_list_name, self.info.id)
        client.delete(RedisProtocol.worker_key(self.info.id))
    except RedisError as e:
        # the info expires on its own, the next registering worker cleans the list
        logging.warning(f"Worker could not be unregistered from Redis: {e}")
    else:
        logging.info("Worker was unregistered from Redis")
wait_for_connection(client: Redis, redis_url: str)

Pings redis until it answers, waiting a bit longer after each refused ping. It is used on start and whenever the job loop lost the connection. Each outage gets the full number of retries, a worker which survived many short hiccups should not give up on the next one just because it used them up already.

Parameters:

  • client (Redis) –

    The redis client.

  • redis_url (str) –

    The url of redis, only used to tell in the logs where the worker is knocking.

Source code in src/qgis_server_light/worker/redis.py
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
def wait_for_connection(self, client: Redis, redis_url: str):
    """Pings redis until it answers, waiting a bit longer after each refused ping.
    It is used on start and whenever the job loop lost the connection. Each outage
    gets the full number of retries, a worker which survived many short hiccups
    should not give up on the next one just because it used them up already.

    Args:
        client: The redis client.
        redis_url: The url of redis, only used to tell in the logs where the
            worker is knocking.
    """
    # the retries are counted per outage, so only one long outage makes the worker
    # give up and not the sum of all short ones
    retry_count = 0
    while True:
        try:
            retry_count += 1
            logging.debug(f"Looking up redis: {redis_url}")
            client.ping()
        except (RedisConnectionError, TimeoutError) as e:
            logging.debug(f"Connection on Redis not successful => {e}")
            self.retry_connection(redis_url, retry_count)
        else:
            break
    logging.info(f"Connection to redis on `{redis_url}`successful.")
write_missing_processes(client: Redis)

Writes the process descriptions into the hash of the worker when they are not there. The descriptions are too big to be written with every beat, so the beat only asks whether redis still knows them. After redis lost its keys they are back within one heartbeat interval like the rest of the worker.

Parameters:

  • client (Redis) –

    The redis client.

Source code in src/qgis_server_light/worker/redis.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def write_missing_processes(self, client: Redis):
    """Writes the process descriptions into the hash of the worker when they are not
    there. The descriptions are too big to be written with every beat, so the beat
    only asks whether redis still knows them. After redis lost its keys they are
    back within one heartbeat interval like the rest of the worker.

    Args:
        client: The redis client.
    """
    if self.processes_json is None:
        return
    worker_key = RedisProtocol.worker_key(self.info.id)
    if not client.hexists(worker_key, RedisProtocol.worker_processes_key):
        client.hset(worker_key, RedisProtocol.worker_processes_key, self.processes_json)
        logging.info(f"Processes {self.context.served_process_ids} were registered in Redis")

RedisPublishEngine

Bases: RedisEngine

The engine publishing the result to the waiting dispatcher (see RedisPublishProtocol). This is the default, map related jobs are served by it.

Source code in src/qgis_server_light/worker/redis.py
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
class RedisPublishEngine(RedisEngine):
    """The engine publishing the result to the waiting dispatcher (see
    `RedisPublishProtocol`). This is the default, map related jobs are served
    by it.
    """

    protocol = RedisPublishProtocol

    def publish_result(
        self, job_id: str, result: JobResult, pipeline: Pipeline, status: str, start_time: float
    ):
        """Sets the final status and publishes the pickled result. Success and
        failure only differ in the result and the status, so both end here.

        Args:
            job_id: The unique identifier of the job.
            result: The result to publish, the worker information is added.
            pipeline: The pipeline holding the transaction.
            status: The final status of the job.
            start_time: The time the job was taken from the queue.
        """
        result.worker_id = self.info.id
        result.worker_host_name = socket.gethostname()
        data = pickle.dumps(result)

        # we inform, that the job was finished
        self.set_job_runtime_status(job_id, pipeline, status, start_time)

        # we publish the result to any subscribers
        pipeline.publish(self.protocol.channel(job_id), data)

    def succeed_job(
        self,
        job_id: str,
        job_info: QslJobInfoParameter,
        result: JobResult,
        pipeline: Pipeline,
        start_time: float,
    ):
        self.publish_result(job_id, result, pipeline, Status.SUCCESS.value, start_time)

    def fail_job(
        self,
        job_id: str,
        job_info: QslJobInfoParameter | None,
        error: Exception,
        pipeline: Pipeline,
        start_time: float,
    ):
        # preparation of the result, containing error information
        result = JobResult(id=job_id, data=str(error), content_type="text")
        self.publish_result(job_id, result, pipeline, Status.FAILURE.value, start_time)
protocol = RedisPublishProtocol class-attribute instance-attribute
fail_job(job_id: str, job_info: QslJobInfoParameter | None, error: Exception, pipeline: Pipeline, start_time: float)
Source code in src/qgis_server_light/worker/redis.py
527
528
529
530
531
532
533
534
535
536
537
def fail_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter | None,
    error: Exception,
    pipeline: Pipeline,
    start_time: float,
):
    # preparation of the result, containing error information
    result = JobResult(id=job_id, data=str(error), content_type="text")
    self.publish_result(job_id, result, pipeline, Status.FAILURE.value, start_time)
publish_result(job_id: str, result: JobResult, pipeline: Pipeline, status: str, start_time: float)

Sets the final status and publishes the pickled result. Success and failure only differ in the result and the status, so both end here.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

  • result (JobResult) –

    The result to publish, the worker information is added.

  • pipeline (Pipeline) –

    The pipeline holding the transaction.

  • status (str) –

    The final status of the job.

  • start_time (float) –

    The time the job was taken from the queue.

Source code in src/qgis_server_light/worker/redis.py
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
def publish_result(
    self, job_id: str, result: JobResult, pipeline: Pipeline, status: str, start_time: float
):
    """Sets the final status and publishes the pickled result. Success and
    failure only differ in the result and the status, so both end here.

    Args:
        job_id: The unique identifier of the job.
        result: The result to publish, the worker information is added.
        pipeline: The pipeline holding the transaction.
        status: The final status of the job.
        start_time: The time the job was taken from the queue.
    """
    result.worker_id = self.info.id
    result.worker_host_name = socket.gethostname()
    data = pickle.dumps(result)

    # we inform, that the job was finished
    self.set_job_runtime_status(job_id, pipeline, status, start_time)

    # we publish the result to any subscribers
    pipeline.publish(self.protocol.channel(job_id), data)
succeed_job(job_id: str, job_info: QslJobInfoParameter, result: JobResult, pipeline: Pipeline, start_time: float)
Source code in src/qgis_server_light/worker/redis.py
517
518
519
520
521
522
523
524
525
def succeed_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter,
    result: JobResult,
    pipeline: Pipeline,
    start_time: float,
):
    self.publish_result(job_id, result, pipeline, Status.SUCCESS.value, start_time)

RedisStateEngine

Bases: RedisEngine

The engine keeping the result in the job hash (see RedisStateProtocol). Process-workers are started with it.

Source code in src/qgis_server_light/worker/redis.py
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
class RedisStateEngine(RedisEngine):
    """The engine keeping the result in the job hash (see `RedisStateProtocol`).
    Process-workers are started with it.
    """

    protocol = RedisStateProtocol

    def finish_job(
        self,
        job_id: str,
        job_info: QslJobInfoParameter | None,
        pipeline: Pipeline,
        status: str,
        start_time: float,
    ):
        """Renews the expiry, sets the final status and notifies a waiting
        dispatcher. Success and failure only differ in the fields written
        before, so both end here.

        Args:
            job_id: The unique identifier of the job.
            job_info: The job info of the job, `None` if it could not be read. A
                waiting dispatcher can not be ruled out then, so it is notified.
            pipeline: The pipeline holding the transaction.
            status: The final status of the job.
            start_time: The time the job was taken from the queue.
        """
        # the fields written before are executed in the same transaction as the
        # final status
        pipeline.expire(self.protocol.job_key(job_id), self.protocol.job_expire)
        self.set_job_runtime_status(job_id, pipeline, status, start_time)
        # the notification only wakes a waiting dispatcher, the job hash is
        # written already
        if job_info is None or job_info.execution_mode == ExecutionMode.SYNC:
            pipeline.publish(self.protocol.channel(job_id), status)

    def job_guard(
        self, client: Redis, job_id: str, job_info: QslJobInfoParameter, start_time: float
    ) -> JobGuard:
        job_key = self.protocol.job_key(job_id)
        feedback = QgsProcessingFeedback()
        # the algorithm runs in this thread, so the signal calls it directly
        feedback.progressChanged.connect(
            JobProgress(client, job_key, self.protocol.job_progress_key)
        )
        output_dir = self.context.process_output_dir
        return JobGuard(
            feedback,
            dismissed=lambda: bool(client.hexists(job_key, self.protocol.job_cancel_key)),
            abandon=lambda reason: self.abandon_job(client, job_id, job_info, reason, start_time),
            timeout=self.context.process_timeout,
            output_dir=Path(output_dir, job_id) if output_dir is not None else None,
            max_output_size=self.context.process_max_output_size,
        )

    def abandon_job(
        self,
        client: Redis,
        job_id: str,
        job_info: QslJobInfoParameter,
        reason: Exception,
        start_time: float,
    ):
        """Finishes a job which didn't stop after it was canceled, right before the
        worker exits. It runs in the thread of the guard, the thread of the worker is
        still stuck in the algorithm, so it has its own pipeline.

        Args:
            client: The redis client.
            job_id: The unique identifier of the job.
            job_info: The job info of the job.
            reason: Why the job was canceled.
            start_time: The time the job was taken from the queue.
        """
        pipeline = client.pipeline()
        self.fail_job(job_id, job_info, reason, pipeline, start_time)
        pipeline.execute()
        if self.context.process_output_dir is not None:
            shutil.rmtree(Path(self.context.process_output_dir, job_id), ignore_errors=True)
        self.unregister_worker(client)

    def succeed_job(
        self,
        job_id: str,
        job_info: QslJobInfoParameter,
        result: JobResult,
        pipeline: Pipeline,
        start_time: float,
    ):
        pipeline.hset(self.protocol.job_key(job_id), self.protocol.job_result_key, result.data)
        pipeline.hset(
            self.protocol.job_key(job_id),
            self.protocol.job_result_content_type_key,
            result.content_type,
        )
        self.finish_job(job_id, job_info, pipeline, Status.SUCCESS.value, start_time)

    def fail_job(
        self,
        job_id: str,
        job_info: QslJobInfoParameter | None,
        error: Exception,
        pipeline: Pipeline,
        start_time: float,
    ):
        pipeline.hset(self.protocol.job_key(job_id), self.protocol.job_message_key, str(error))
        status = Status.DISMISSED if isinstance(error, JobDismissedError) else Status.FAILURE
        self.finish_job(job_id, job_info, pipeline, status.value, start_time)
protocol = RedisStateProtocol class-attribute instance-attribute
abandon_job(client: Redis, job_id: str, job_info: QslJobInfoParameter, reason: Exception, start_time: float)

Finishes a job which didn't stop after it was canceled, right before the worker exits. It runs in the thread of the guard, the thread of the worker is still stuck in the algorithm, so it has its own pipeline.

Parameters:

  • client (Redis) –

    The redis client.

  • job_id (str) –

    The unique identifier of the job.

  • job_info (QslJobInfoParameter) –

    The job info of the job.

  • reason (Exception) –

    Why the job was canceled.

  • start_time (float) –

    The time the job was taken from the queue.

Source code in src/qgis_server_light/worker/redis.py
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
def abandon_job(
    self,
    client: Redis,
    job_id: str,
    job_info: QslJobInfoParameter,
    reason: Exception,
    start_time: float,
):
    """Finishes a job which didn't stop after it was canceled, right before the
    worker exits. It runs in the thread of the guard, the thread of the worker is
    still stuck in the algorithm, so it has its own pipeline.

    Args:
        client: The redis client.
        job_id: The unique identifier of the job.
        job_info: The job info of the job.
        reason: Why the job was canceled.
        start_time: The time the job was taken from the queue.
    """
    pipeline = client.pipeline()
    self.fail_job(job_id, job_info, reason, pipeline, start_time)
    pipeline.execute()
    if self.context.process_output_dir is not None:
        shutil.rmtree(Path(self.context.process_output_dir, job_id), ignore_errors=True)
    self.unregister_worker(client)
fail_job(job_id: str, job_info: QslJobInfoParameter | None, error: Exception, pipeline: Pipeline, start_time: float)
Source code in src/qgis_server_light/worker/redis.py
637
638
639
640
641
642
643
644
645
646
647
def fail_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter | None,
    error: Exception,
    pipeline: Pipeline,
    start_time: float,
):
    pipeline.hset(self.protocol.job_key(job_id), self.protocol.job_message_key, str(error))
    status = Status.DISMISSED if isinstance(error, JobDismissedError) else Status.FAILURE
    self.finish_job(job_id, job_info, pipeline, status.value, start_time)
finish_job(job_id: str, job_info: QslJobInfoParameter | None, pipeline: Pipeline, status: str, start_time: float)

Renews the expiry, sets the final status and notifies a waiting dispatcher. Success and failure only differ in the fields written before, so both end here.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

  • job_info (QslJobInfoParameter | None) –

    The job info of the job, None if it could not be read. A waiting dispatcher can not be ruled out then, so it is notified.

  • pipeline (Pipeline) –

    The pipeline holding the transaction.

  • status (str) –

    The final status of the job.

  • start_time (float) –

    The time the job was taken from the queue.

Source code in src/qgis_server_light/worker/redis.py
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
def finish_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter | None,
    pipeline: Pipeline,
    status: str,
    start_time: float,
):
    """Renews the expiry, sets the final status and notifies a waiting
    dispatcher. Success and failure only differ in the fields written
    before, so both end here.

    Args:
        job_id: The unique identifier of the job.
        job_info: The job info of the job, `None` if it could not be read. A
            waiting dispatcher can not be ruled out then, so it is notified.
        pipeline: The pipeline holding the transaction.
        status: The final status of the job.
        start_time: The time the job was taken from the queue.
    """
    # the fields written before are executed in the same transaction as the
    # final status
    pipeline.expire(self.protocol.job_key(job_id), self.protocol.job_expire)
    self.set_job_runtime_status(job_id, pipeline, status, start_time)
    # the notification only wakes a waiting dispatcher, the job hash is
    # written already
    if job_info is None or job_info.execution_mode == ExecutionMode.SYNC:
        pipeline.publish(self.protocol.channel(job_id), status)
job_guard(client: Redis, job_id: str, job_info: QslJobInfoParameter, start_time: float) -> JobGuard
Source code in src/qgis_server_light/worker/redis.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
def job_guard(
    self, client: Redis, job_id: str, job_info: QslJobInfoParameter, start_time: float
) -> JobGuard:
    job_key = self.protocol.job_key(job_id)
    feedback = QgsProcessingFeedback()
    # the algorithm runs in this thread, so the signal calls it directly
    feedback.progressChanged.connect(
        JobProgress(client, job_key, self.protocol.job_progress_key)
    )
    output_dir = self.context.process_output_dir
    return JobGuard(
        feedback,
        dismissed=lambda: bool(client.hexists(job_key, self.protocol.job_cancel_key)),
        abandon=lambda reason: self.abandon_job(client, job_id, job_info, reason, start_time),
        timeout=self.context.process_timeout,
        output_dir=Path(output_dir, job_id) if output_dir is not None else None,
        max_output_size=self.context.process_max_output_size,
    )
succeed_job(job_id: str, job_info: QslJobInfoParameter, result: JobResult, pipeline: Pipeline, start_time: float)
Source code in src/qgis_server_light/worker/redis.py
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
def succeed_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter,
    result: JobResult,
    pipeline: Pipeline,
    start_time: float,
):
    pipeline.hset(self.protocol.job_key(job_id), self.protocol.job_result_key, result.data)
    pipeline.hset(
        self.protocol.job_key(job_id),
        self.protocol.job_result_content_type_key,
        result.content_type,
    )
    self.finish_job(job_id, job_info, pipeline, Status.SUCCESS.value, start_time)

main() -> None

Source code in src/qgis_server_light/worker/redis.py
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
773
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
def main() -> None:
    parser = argparse.ArgumentParser()

    parser.add_argument("--redis-url", type=str, help="redis url")

    parser.add_argument(
        "--log-level",
        type=str,
        help="log level (debug, info, warning or error)",
        default="info",
    )

    parser.add_argument(
        "--data-root",
        type=str,
        help=f"Absolute path to the data dir. Defaults to {DEFAULT_DATA_ROOT}",
        default=DEFAULT_DATA_ROOT,
    )

    parser.add_argument(
        "--svg-path",
        type=str,
        help=f"Absolute path to additional svg files. Multiple paths "
        f"can be separated by `:`. Defaults to {DEFAULT_SVG_PATH}",
        default=DEFAULT_SVG_PATH,
    )

    parser.add_argument(
        "--runner-plugins",
        type=str,
        help="Runner classes the worker boots with, as dotted paths. Multiple plugins "
        "can be separated by `:`. The worker listens on the queues of their jobs only, "
        "e.g. `qgis_server_light.worker.runner.process.ProcessRunner` for a worker "
        "serving processes. Defaults to the map related runners.",
        default=DEFAULT_RUNNER_PLUGINS,
    )

    parser.add_argument(
        "--process-allowlist",
        type=str,
        help="Ids of the QGIS algorithms the worker serves as processes, separated by `,`. "
        "Only used when the worker boots with the process runner. "
        f"Defaults to {DEFAULT_PROCESS_ALLOWLIST}",
        default=DEFAULT_PROCESS_ALLOWLIST,
    )

    parser.add_argument(
        "--process-internal-allowlist",
        type=str,
        help="Ids of the QGIS algorithms the worker serves as processes for internal use of "
        "the consumer only, separated by `,`. Their descriptions are marked `internal`, the "
        "consumer must not publish them. Only used when the worker boots with the process "
        "runner. Defaults to none",
        default="",
    )

    parser.add_argument(
        "--process-output-dir",
        type=str,
        help="Absolute path to the dir the processes write their outputs to, each job "
        "into its own sub dir. Only used when the worker boots with the process runner. "
        f"Defaults to {DEFAULT_PROCESS_OUTPUT_DIR}",
        default=DEFAULT_PROCESS_OUTPUT_DIR,
    )

    parser.add_argument(
        "--process-timeout",
        type=float,
        help="Seconds a process job may run before it is canceled, 0 for no limit. Only "
        f"used when the worker boots with the process runner. Defaults to "
        f"{DEFAULT_PROCESS_TIMEOUT}",
        default=DEFAULT_PROCESS_TIMEOUT,
    )

    parser.add_argument(
        "--process-max-output-size",
        type=int,
        help="Megabytes a process job may write before it is canceled, 0 for no limit. "
        "Only used when the worker boots with the process runner. Defaults to "
        f"{DEFAULT_PROCESS_MAX_OUTPUT_SIZE}",
        default=DEFAULT_PROCESS_MAX_OUTPUT_SIZE,
    )

    parser.add_argument(
        "--process-max-features",
        type=int,
        help="Features a vector layer input of a process job may have, 0 for no limit. "
        "Only used when the worker boots with the process runner. Defaults to "
        f"{DEFAULT_PROCESS_MAX_FEATURES}",
        default=DEFAULT_PROCESS_MAX_FEATURES,
    )

    parser.add_argument(
        "--once",
        action="store_true",
        help="Exit after one job, so every job runs in a fresh process. The worker has "
        "to be started again for the next job, e.g. by a loop around it.",
    )

    parser.add_argument(
        "--engine",
        type=str,
        choices=list(engine_classes),
        help="How the worker delivers job results: `publish` publishes the result to the "
        "waiting dispatcher, `state` keeps it in the job hash. Defaults to publish",
        default="publish",
    )

    args = parser.parse_args()

    logging.basicConfig(
        level=args.log_level.upper(), format="%(asctime)s [%(levelname)s] %(message)s"
    )

    if not args.redis_url:
        raise AssertionError(
            "no redis host specified: start qgis-server-light with '--redis-url <QSL_REDIS_URL>'"
        )

    svg_paths = args.svg_path.split(":")
    runner_plugins = args.runner_plugins.split(":")
    process_allowlist = args.process_allowlist.split(",")
    process_internal_allowlist = [
        process_id for process_id in args.process_internal_allowlist.split(",") if process_id
    ]
    engine = engine_classes[args.engine](
        EngineContext(
            args.data_root,
            process_allowlist,
            args.process_output_dir,
            process_internal_allowlist,
            # 0 means no limit, the context knows no limit as `None`
            process_timeout=args.process_timeout or None,
            process_max_output_size=args.process_max_output_size * 1024 * 1024 or None,
            process_max_features=args.process_max_features or None,
        ),
        runner_plugins,
        svg_paths=svg_paths,
        once=args.once,
    )
    engine.run(
        args.redis_url,
    )

runner

common

ImageRunner

Bases: MapRunner

Base class for any map runner which answers with an encoded image. Not runnable by itself.

Source code in src/qgis_server_light/worker/runner/common.py
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
class ImageRunner(MapRunner):
    """Base class for any map runner which answers with an encoded image.
    Not runnable by itself.
    """

    @classmethod
    def image_formats(cls):
        return {"image/png": cls._encode_png, "image/jpeg": cls._encode_jpg}

    def _encode_image(self, image: QImage, fmt: str) -> tuple[str, bytearray]:
        """Encodes an image in a specific mime type
        Args:
            image (QImage): The image to encode
            fmt (str): The mime type of the format
        Returns:
            A tuple with mime type and bytes-like object of an encoded image in the desired format
        """
        try:
            fmt = fmt.lower()
            encoding_method = self.image_formats()[fmt]
            return fmt, encoding_method(image)
        except KeyError as e:
            raise RuntimeError(
                f"Requested mime type '{fmt}' was not found in {list(self.image_formats())}."
            ) from e

    @staticmethod
    def _encode_png(image: QImage):
        image = image.convertToFormat(QImage.Format_RGBA8888)
        image_data = fpng_encode_image_to_memory(
            image.constBits().asstring(image.sizeInBytes()),
            image.width(),
            image.height(),
            0,
            CompressionFlags.NONE,
        )
        return image_data

    @staticmethod
    def _encode_jpg(image: QImage):
        image_data = QByteArray()
        buf = QBuffer(image_data)
        buf.open(QIODevice.WriteOnly)
        image.save(buf, "JPG")
        return image_data
image_formats() classmethod
Source code in src/qgis_server_light/worker/runner/common.py
490
491
492
@classmethod
def image_formats(cls):
    return {"image/png": cls._encode_png, "image/jpeg": cls._encode_jpg}
JobContext dataclass

What a runner needs to know about the worker it runs on. The engine hands each job its own copy.

Attributes:

  • base_path (str | Path) –

    The absolute path to the data dir.

  • process_allowlist (list[str]) –

    The ids of the QGIS algorithms the worker serves as processes.

  • process_output_dir (str | Path | None) –

    The absolute path to the dir the processes write their outputs to, each job into its own sub dir. Only the process runner needs it, it refuses to run without.

  • process_internal_allowlist (list[str]) –

    The ids of the QGIS algorithms the worker serves as processes for internal use of the consumer only, they must not be published.

  • process_timeout (float | None) –

    Seconds a process job may run, None for no limit.

  • process_max_output_size (int | None) –

    Bytes a process job may write, None for no limit.

  • process_max_features (int | None) –

    Features a vector layer input of a process may have, None for no limit.

  • feedback (QgsProcessingFeedback | None) –

    The feedback a process job runs with, the engine reads the progress from it and cancels the job through it. It is set by the engine per job, None if nobody listens.

Source code in src/qgis_server_light/worker/runner/common.py
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
@dataclass
class JobContext:
    """What a runner needs to know about the worker it runs on. The engine hands each job
    its own copy.

    Attributes:
        base_path: The absolute path to the data dir.
        process_allowlist: The ids of the QGIS algorithms the worker serves as processes.
        process_output_dir: The absolute path to the dir the processes write their
            outputs to, each job into its own sub dir. Only the process runner needs
            it, it refuses to run without.
        process_internal_allowlist: The ids of the QGIS algorithms the worker serves as
            processes for internal use of the consumer only, they must not be published.
        process_timeout: Seconds a process job may run, `None` for no limit.
        process_max_output_size: Bytes a process job may write, `None` for no limit.
        process_max_features: Features a vector layer input of a process may have,
            `None` for no limit.
        feedback: The feedback a process job runs with, the engine reads the progress
            from it and cancels the job through it. It is set by the engine per job,
            `None` if nobody listens.
    """

    base_path: str | Path
    process_allowlist: list[str] = field(default_factory=list)
    process_output_dir: str | Path | None = None
    process_internal_allowlist: list[str] = field(default_factory=list)
    process_timeout: float | None = None
    process_max_output_size: int | None = None
    process_max_features: int | None = None
    feedback: QgsProcessingFeedback | None = None

    @property
    def served_process_ids(self) -> list[str]:
        """The ids of all algorithms the worker serves, published or internal."""
        return self.process_allowlist + self.process_internal_allowlist
base_path: str | Path instance-attribute
feedback: QgsProcessingFeedback | None = None class-attribute instance-attribute
process_allowlist: list[str] = field(default_factory=list) class-attribute instance-attribute
process_internal_allowlist: list[str] = field(default_factory=list) class-attribute instance-attribute
process_max_features: int | None = None class-attribute instance-attribute
process_max_output_size: int | None = None class-attribute instance-attribute
process_output_dir: str | Path | None = None class-attribute instance-attribute
process_timeout: float | None = None class-attribute instance-attribute
served_process_ids: list[str] property

The ids of all algorithms the worker serves, published or internal.

__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
MapRunner

Bases: Runner

Base class for any runner that interacts with a map. Not runnable by itself.

Source code in src/qgis_server_light/worker/runner/common.py
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
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
class MapRunner(Runner):
    """Base class for any runner that interacts with a map.
    Not runnable by itself.
    """

    map_layers: list[QgsMapLayer]
    vector_layer_drivers = [
        "ogr",
        "postgres",
        "spatialite",
        "mssql",
        "oracle",
        "wfs",
        "delimitedtext",
        "gpx",
        "arcgisfeatureserver",
    ]
    raster_layer_drivers = [
        "gdal",
        "wms",
        "xyz",
        "arcgismapserver",
        "wcs",
    ]
    custom_layer_drivers = ["xyzvectortiles", "mbtilesvectortiles"]
    default_style_name = "default"

    def __init__(
        self,
        qgis: QgsApplication,
        context: JobContext,
        job_info: QslJobInfoParameter,
        layer_cache: MutableMapping | None = None,
    ) -> None:
        self.qgis = qgis
        self.context = context
        self.job_info = job_info
        self.map_layers = list()
        self.layer_cache = layer_cache
        self._custom_prop_original_filter = "qsl.original_filter"
        self._custom_prop_source_modified = "qsl.source_modified"
        self._custom_prop_style_definition = "qsl.style_definition"
        # clients only know the job layer id, the cache name is internal
        self._job_layer_ids: dict[str, str] = {}

    def _get_map_settings(self, layers: list[QgsMapLayer]) -> QgsMapSettings:
        """Produces a QgsMapSettings object from a set of layers"""
        expression_context_scope = QgsExpressionContextScope()
        expression_context_scope.setVariable("map_id", str(uuid.uuid4()))
        expression_context = QgsExpressionContext()
        expression_context.appendScope(expression_context_scope)
        settings = QgsMapSettings()
        settings.setExpressionContext(expression_context)

        def preprocessor(path):
            return path

        settings.pathResolver().setPathPreprocessor(preprocessor)
        settings.setOutputSize(QSize(int(self.job_info.job.width), int(self.job_info.job.height)))
        if self.job_info.job.dpi:
            settings.setOutputDpi(self.job_info.job.dpi)

        crs = self.job_info.job.crs
        destination_crs = QgsCoordinateReferenceSystem.fromOgcWmsCrs(crs)
        minx, miny, maxx, maxy = self.job_info.job.bbox.to_2d_list()
        bbox = QgsRectangle(float(minx), float(miny), float(maxx), float(maxy))
        if destination_crs.hasAxisInverted():  # lat-lon, instead of lon-lat e.g. epsg:4326
            bbox.invert()
        settings.setExtent(bbox)
        settings.setLayers(layers)
        settings.setBackgroundColor(QColor(Qt.transparent))

        settings.setDestinationCrs(destination_crs)
        return settings

    def _load_style(self, qgs_layer: QgsMapLayer, job_layer_definition: QslJobLayer):
        logging.info(f"Preparing job_layer_definition Style: {job_layer_definition.style.name}")

        # a cached layer keeps its style between jobs, importing an unchanged
        # style again only costs time
        applied_style = qgs_layer.customProperty(self._custom_prop_style_definition, None)
        if applied_style == job_layer_definition.style.definition:
            logging.info(" ✓ Style unchanged, import skipped")
            return

        # the custom attributes on layers are stored in the style in fact, so
        # we first have to secure the custom property before applying the filter
        logging.debug("Preserving subset string")
        original_filter = qgs_layer.customProperty(self._custom_prop_original_filter, None)
        source_modified = qgs_layer.customProperty(self._custom_prop_source_modified, None)
        style_doc = QDomDocument()
        style_xml = zlib.decompress(urlsafe_b64decode(job_layer_definition.style.definition))
        style_doc.setContent(style_xml)
        success, _ = qgs_layer.importNamedStyle(style_doc)

        # we are apply the secured custom property since it was potentially wiped
        # by applying the style
        logging.debug("Re-apply subset string")
        qgs_layer.setCustomProperty(self._custom_prop_original_filter, original_filter)
        qgs_layer.setCustomProperty(self._custom_prop_source_modified, source_modified)
        if success:
            qgs_layer.setCustomProperty(
                self._custom_prop_style_definition, job_layer_definition.style.definition
            )
        logging.info(f" ✓ Style loaded: {success}")

    def _apply_filter(self, qgs_layer: QgsVectorLayer, job_layer_definition: QslJobLayer):
        if job_layer_definition.filter:
            logging.debug("Job definition has a filter")
            if isinstance(job_layer_definition.filter, OgcFilter110):
                # TODO: This is potentially bad: We always get all features from
                #  datasource. However, QGIS
                #   does not seem to support sliding window feature filter out of the box...
                logging.info(" QslJobLayer is filtered by:")
                logging.info(job_layer_definition.filter.definition)
                filter_doc = QDomDocument()
                filter_doc.setContent(job_layer_definition.filter.definition)
                filter_expression = QgsOgcUtils.expressionFromOgcFilter(
                    filter_doc.documentElement(),
                    QgsOgcUtils.FilterVersion.FILTER_OGC_1_1,
                    qgs_layer,
                )
                original_filter = qgs_layer.customProperty(self._custom_prop_original_filter, None)
                if original_filter:
                    # Combining with AND the originally defined expression always takes precedence
                    expression = f"({original_filter}) AND ({filter_expression.expression()})"
                    logging.debug(f"Layer filter existed AND combined with passed: {expression}")
                else:
                    expression = filter_expression.expression()
                    logging.debug(f"No filter existed will be just the passed one: {expression}")
                qgs_layer.setSubsetString(expression)
        else:
            logging.debug("Job definition has no filter")
            # reset filter to original filter (provided from project) or to empty filter
            original_filter = qgs_layer.customProperty(self._custom_prop_original_filter, None)
            if original_filter is None:
                logging.debug("No original Filter, resetting to empty substring ''")
                qgs_layer.setSubsetString("")
            else:
                logging.debug(f"Original Filter, resetting to {original_filter}")
                qgs_layer.setSubsetString(original_filter)

    def get_cache_name(self, job_layer_definition: QslJobLayer) -> str:
        """Central method to decide which name is used in the cache to
        identify a layer.
        """
        return (
            f"{job_layer_definition.id}"
            f"{job_layer_definition.name}"
            f"{job_layer_definition.source}"
            f"{job_layer_definition.remote}"
            f"{job_layer_definition.folder_name}"
            f"{job_layer_definition.driver}"
        )

    def _decide_drivers(self, job_layer_definition: QslJobLayer) -> QgsMapLayer:
        """Decides which type of layer we are dealing with and delegates initialization
        to the right method.

        Args:
            job_layer_definition: The job_layer_definition containing all
                information to initialize a QgsMapLayer.
        Returns:
            The newly created layer.
        Raises:
            LookupError: When the driver is not in the expected ranges.
        """
        if job_layer_definition.driver in self.vector_layer_drivers:
            qgs_layer = self._prepare_vector_layer(job_layer_definition)
        elif job_layer_definition.driver in self.raster_layer_drivers:
            qgs_layer = self._prepare_raster_layer(job_layer_definition)
        elif job_layer_definition.driver in self.custom_layer_drivers:
            qgs_layer = self._prepare_custom_layer(job_layer_definition)
        else:
            raise LookupError(f"Type not implemented: {job_layer_definition}")
        return qgs_layer

    def _handle_layer_cache(self, job_layer_definition: QslJobLayer) -> QgsMapLayer:
        """Checks if layer can be fetched directly from the cache or initiates the
        creation of a new layer otherwise.

        Args:
            job_layer_definition: The job_layer_definition containing all
                information to initialize a QgsMapLayer.
        Returns:
            The layer (from cache or newly created).
        """
        cache_name = self.get_cache_name(job_layer_definition)
        self._job_layer_ids[cache_name] = job_layer_definition.id
        if self.layer_cache is not None and cache_name in self.layer_cache:
            logging.debug(
                f"Using cached job_layer_definition {job_layer_definition.name} "
                f"(identifier: {self._job_layer_ids[cache_name]})"
            )
            qgs_layer = self.layer_cache[cache_name]
            # retrying is up to the client, the next job initializes the layer again
            if outdated_reason := self._outdated_reason(qgs_layer, job_layer_definition):
                self._raise_on_layer_errors({cache_name: outdated_reason})
        else:
            qgs_layer = self._decide_drivers(job_layer_definition)
            # the cache name is the central identifier, errors reported by QGIS
            # carry the layer id and therefore point directly into the cache
            qgs_layer.setId(cache_name)
            qgs_layer.setCustomProperty(
                self._custom_prop_source_modified, self._source_modified(job_layer_definition)
            )
            qgs_layer.setTitle(job_layer_definition.name)
            if qgs_layer.isValid():
                logging.debug(
                    f"Newly initialized layer {job_layer_definition.name} "
                    f"is valid: {qgs_layer.isValid()}"
                )
                if self.layer_cache is not None:
                    self.layer_cache[cache_name] = qgs_layer
            else:
                logging.error(qgs_layer.error().message())
                logging.error(qgs_layer.dataProvider().error().message())
                raise RuntimeError(
                    f"Newly initialized layer {job_layer_definition.name} "
                    f"is not valid. JobLayerDefinition: {job_layer_definition}"
                )
        return qgs_layer

    def _throw_out_layer(self, cache_name: str) -> None:
        """Throws a layer out of the cache, so the next job initializes it again."""
        if self.layer_cache is not None:
            self.layer_cache.pop(cache_name, None)
            logging.warning(
                f"Evicted layer from cache (identifier: {self._job_layer_ids[cache_name]})"
            )

    def _outdated_reason(
        self, qgs_layer: QgsMapLayer, job_layer_definition: QslJobLayer
    ) -> str | None:
        """Evaluates if a cached layer became invalid or its local data source
        changed since it was cached.

        OGR does not report read errors of opened datasets (missing or corrupted
        files result in empty feature iterators), that is why local sources are
        checked by a fingerprint of their file.

        Returns:
            The reason why the layer is outdated, None if it is still usable.
        """
        if not (qgs_layer.isValid() and qgs_layer.dataProvider().isValid()):
            return "Cached layer became invalid"
        source_modified = qgs_layer.customProperty(self._custom_prop_source_modified, None)
        if source_modified != self._source_modified(job_layer_definition):
            return "Data source changed since caching"
        return None

    def _source_modified(self, job_layer_definition: QslJobLayer) -> str | None:
        """Fingerprint of a local data source file to detect replaced, changed or
        deleted files. Sidecar files are not considered, changes reach the main
        file eventually (e.g. on a GeoPackage WAL checkpoint).

        Returns:
            Modification time, size and inode of the file, None for remote or
            missing sources.
        """
        if job_layer_definition.remote:
            return None
        path = self._handle_datasource_definition(job_layer_definition)["path"]
        try:
            stat = os.stat(path)
        except FileNotFoundError:
            return None
        return f"{stat.st_mtime_ns}:{stat.st_size}:{stat.st_ino}"

    def _raise_on_layer_errors(self, layer_errors: dict[str, str]) -> None:
        """Evicts all layers which failed during the job and lets the job fail.

        Args:
            layer_errors: Error messages by layer id (which is the cache name).
        Raises:
            RuntimeError: When at least one layer failed, the message names the
                job layer ids.
        """
        if layer_errors:
            for cache_name in layer_errors:
                self._throw_out_layer(cache_name)
            failed_job_layers = {
                self._job_layer_ids[cache_name]: message
                for cache_name, message in layer_errors.items()
            }
            raise RuntimeError(f"Layers failed: {failed_job_layers}")

    def _provide_layer(self, job_layer_definition: QslJobLayer) -> None:
        """Fetches the QGIS layer relevant for the requested job layer.

        Args:
            job_layer_definition: The job_layer_definition containing all
                information to initialize a QgsMapLayer.
        Returns:
            None
        """
        qgs_layer = self._handle_layer_cache(job_layer_definition)
        # applying the style to the job_layer_definition
        # this has to be before applying the filter!
        self._load_style(qgs_layer, job_layer_definition)
        if isinstance(qgs_layer, QgsVectorLayer):
            self._apply_filter(qgs_layer, job_layer_definition)
        self.map_layers.append(qgs_layer)

    def _handle_datasource_definition(self, job_layer_definition: QslJobLayer) -> dict:
        layer_source = json.loads(job_layer_definition.source)
        if not job_layer_definition.remote:
            # we make the relative path an absolute one with the configured base path
            layer_source["path"] = os.path.join(
                self.context.base_path,
                job_layer_definition.folder_name,
                layer_source["path"],
            )
        return layer_source

    def _decoded_layer_source_to_connection_string(self, driver: str, layer_source: dict) -> str:
        return QgsProviderRegistry.instance().encodeUri(driver, layer_source)

    def _prepare_vector_layer(self, job_layer_definition: QslJobLayer) -> QgsVectorLayer:
        """
        Initializes a QgsVectorLayer from a job_layer_definition.
        Args:
            job_layer_definition: The job_layer_definition definition as
                received from the runner.

        Returns:
            The QgsVectorLayer instance in case initialization went correctly.
        Raises:
            RuntimeError: In case the initialized job_layer_definition was not
                valid from QGIS point of view (mostly related to not available
                data sources).
        """

        layer_source = self._handle_datasource_definition(job_layer_definition)
        layer_source_path = self._decoded_layer_source_to_connection_string(
            job_layer_definition.driver, layer_source
        )

        # removed loadDefaultStyle=False because it seems to have no effect anymore
        options = QgsVectorLayer.LayerOptions(readExtentFromXml=False)
        options.skipCrValidation = True
        options.forceReadOnly = True

        qgs_layer = QgsVectorLayer(
            layer_source_path,
            job_layer_definition.name,
            job_layer_definition.driver,
            options,
        )
        logging.debug(f"Preserving predefined layer subset: {qgs_layer.subsetString()}")
        qgs_layer.setCustomProperty(self._custom_prop_original_filter, qgs_layer.subsetString())
        return qgs_layer

    def _prepare_custom_layer(self, job_layer_definition: QslJobLayer) -> QgsVectorTileLayer:
        """Initializes a custom job_layer_definition"""
        layer_source = self._handle_datasource_definition(job_layer_definition)
        layer_source_path = self._decoded_layer_source_to_connection_string(
            job_layer_definition.driver, layer_source
        )
        qgs_layer = QgsVectorTileLayer(layer_source_path, job_layer_definition.name)
        return qgs_layer

    def _prepare_raster_layer(self, job_layer_definition: QslJobLayer) -> QgsRasterLayer:
        """Initializes a raster job_layer_definition"""
        layer_source = self._handle_datasource_definition(job_layer_definition)
        layer_source_path = self._decoded_layer_source_to_connection_string(
            job_layer_definition.driver, layer_source
        )
        qgs_layer = QgsRasterLayer(
            layer_source_path,
            job_layer_definition.name,
            job_layer_definition.driver,
        )
        return qgs_layer
context = context instance-attribute
custom_layer_drivers = ['xyzvectortiles', 'mbtilesvectortiles'] class-attribute instance-attribute
default_style_name = 'default' class-attribute instance-attribute
job_info = job_info instance-attribute
layer_cache = layer_cache instance-attribute
map_layers: list[QgsMapLayer] = list() instance-attribute
qgis = qgis instance-attribute
raster_layer_drivers = ['gdal', 'wms', 'xyz', 'arcgismapserver', 'wcs'] class-attribute instance-attribute
vector_layer_drivers = ['ogr', 'postgres', 'spatialite', 'mssql', 'oracle', 'wfs', 'delimitedtext', 'gpx', 'arcgisfeatureserver'] class-attribute instance-attribute
__init__(qgis: QgsApplication, context: JobContext, job_info: QslJobInfoParameter, layer_cache: MutableMapping | None = None) -> None
Source code in src/qgis_server_light/worker/runner/common.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def __init__(
    self,
    qgis: QgsApplication,
    context: JobContext,
    job_info: QslJobInfoParameter,
    layer_cache: MutableMapping | None = None,
) -> None:
    self.qgis = qgis
    self.context = context
    self.job_info = job_info
    self.map_layers = list()
    self.layer_cache = layer_cache
    self._custom_prop_original_filter = "qsl.original_filter"
    self._custom_prop_source_modified = "qsl.source_modified"
    self._custom_prop_style_definition = "qsl.style_definition"
    # clients only know the job layer id, the cache name is internal
    self._job_layer_ids: dict[str, str] = {}
get_cache_name(job_layer_definition: QslJobLayer) -> str

Central method to decide which name is used in the cache to identify a layer.

Source code in src/qgis_server_light/worker/runner/common.py
251
252
253
254
255
256
257
258
259
260
261
262
def get_cache_name(self, job_layer_definition: QslJobLayer) -> str:
    """Central method to decide which name is used in the cache to
    identify a layer.
    """
    return (
        f"{job_layer_definition.id}"
        f"{job_layer_definition.name}"
        f"{job_layer_definition.source}"
        f"{job_layer_definition.remote}"
        f"{job_layer_definition.folder_name}"
        f"{job_layer_definition.driver}"
    )
Runner

Bases: ABC

Source code in src/qgis_server_light/worker/runner/common.py
 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
class Runner(ABC):
    job_info_class: type[QslJobInfoParameter]

    def __init__(
        self,
        qgis: QgsApplication,
        context: JobContext,
        job_info: QslJobInfoParameter,
        layer_cache: MutableMapping | None,
    ):
        # This is an abstract base class which is not runnable itself
        raise NotImplementedError()

    def run(self):
        # This is an abstract base class which is not runnable itself
        raise NotImplementedError()

    @classmethod  # noqa: B027
    def prepare(cls, qgis: QgsApplication) -> None:
        """Sets up what the runner needs from QGIS before it gets its first job. The
        engine calls it once per runner it boots with, so a worker only pays for the
        runners it actually serves. Most runners need nothing.

        Args:
            qgis: The QGIS application of the worker.
        """

    @classmethod
    def deserialize_job_info(cls, job_info: bytes):
        return JsonParser().from_bytes(job_info, cls.job_info_class)
job_info_class: type[QslJobInfoParameter] instance-attribute
__init__(qgis: QgsApplication, context: JobContext, job_info: QslJobInfoParameter, layer_cache: MutableMapping | None)
Source code in src/qgis_server_light/worker/runner/common.py
80
81
82
83
84
85
86
87
88
def __init__(
    self,
    qgis: QgsApplication,
    context: JobContext,
    job_info: QslJobInfoParameter,
    layer_cache: MutableMapping | None,
):
    # This is an abstract base class which is not runnable itself
    raise NotImplementedError()
deserialize_job_info(job_info: bytes) classmethod
Source code in src/qgis_server_light/worker/runner/common.py
104
105
106
@classmethod
def deserialize_job_info(cls, job_info: bytes):
    return JsonParser().from_bytes(job_info, cls.job_info_class)
prepare(qgis: QgsApplication) -> None classmethod

Sets up what the runner needs from QGIS before it gets its first job. The engine calls it once per runner it boots with, so a worker only pays for the runners it actually serves. Most runners need nothing.

Parameters:

  • qgis (QgsApplication) –

    The QGIS application of the worker.

Source code in src/qgis_server_light/worker/runner/common.py
 94
 95
 96
 97
 98
 99
100
101
102
@classmethod  # noqa: B027
def prepare(cls, qgis: QgsApplication) -> None:
    """Sets up what the runner needs from QGIS before it gets its first job. The
    engine calls it once per runner it boots with, so a worker only pays for the
    runners it actually serves. Most runners need nothing.

    Args:
        qgis: The QGIS application of the worker.
    """
run()
Source code in src/qgis_server_light/worker/runner/common.py
90
91
92
def run(self):
    # This is an abstract base class which is not runnable itself
    raise NotImplementedError()

crs

CrsRunner

Bases: Runner

Resolves crs identifiers, it needs neither a map nor layers.

Source code in src/qgis_server_light/worker/runner/crs.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
class CrsRunner(Runner):
    """Resolves crs identifiers, it needs neither a map nor layers."""

    job_info_class = QslJobInfoCrs

    def __init__(
        self,
        qgis: QgsApplication,
        context: JobContext,
        job_info: QslJobInfoCrs,
        layer_cache: MutableMapping | None = None,
    ) -> None:
        self.qgis = qgis
        self.context = context
        self.job_info = job_info

    def run(self):
        crs_collection = CrsCollection()
        for identifier in self.job_info.job.identifiers:
            crs = QgsCoordinateReferenceSystem.fromOgcWmsCrs(identifier)
            if not crs.isValid():
                raise RuntimeError(f"Crs `{identifier}` is not valid")
            crs_collection.crs.append(create_qsl_crs(crs))
            logging.info(f" Resolved crs `{identifier}`")
        return JobResult(
            id=self.job_info.id,
            data=JsonSerializer().render(crs_collection).encode(),
            content_type="application/qgis-server-light.interface.qgis.CrsCollection",
        )
context = context instance-attribute
job_info = job_info instance-attribute
job_info_class = QslJobInfoCrs class-attribute instance-attribute
qgis = qgis instance-attribute
__init__(qgis: QgsApplication, context: JobContext, job_info: QslJobInfoCrs, layer_cache: MutableMapping | None = None) -> None
Source code in src/qgis_server_light/worker/runner/crs.py
19
20
21
22
23
24
25
26
27
28
def __init__(
    self,
    qgis: QgsApplication,
    context: JobContext,
    job_info: QslJobInfoCrs,
    layer_cache: MutableMapping | None = None,
) -> None:
    self.qgis = qgis
    self.context = context
    self.job_info = job_info
run()
Source code in src/qgis_server_light/worker/runner/crs.py
30
31
32
33
34
35
36
37
38
39
40
41
42
def run(self):
    crs_collection = CrsCollection()
    for identifier in self.job_info.job.identifiers:
        crs = QgsCoordinateReferenceSystem.fromOgcWmsCrs(identifier)
        if not crs.isValid():
            raise RuntimeError(f"Crs `{identifier}` is not valid")
        crs_collection.crs.append(create_qsl_crs(crs))
        logging.info(f" Resolved crs `{identifier}`")
    return JobResult(
        id=self.job_info.id,
        data=JsonSerializer().render(crs_collection).encode(),
        content_type="application/qgis-server-light.interface.qgis.CrsCollection",
    )

feature

GetFeatureRunner

Bases: MapRunner

Source code in src/qgis_server_light/worker/runner/feature.py
 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
class GetFeatureRunner(MapRunner):
    job_info_class = QslJobInfoFeature

    def __init__(
        self,
        qgis: QgsApplication,
        context: JobContext,
        job_info: QslJobInfoFeature,
        layer_cache: MutableMapping | None = None,
        layer_style_cache: set | None = None,
    ) -> None:
        super().__init__(qgis, context, job_info, layer_cache)

    def _clean_attribute(self, attribute_value: Any, idx: int, layer: QgsVectorLayer):
        if attribute_value == NULL:
            return None
        return attribute_value

    def _clean_attributes(self, attributes, layer):
        return [self._clean_attribute(attr, idx, layer) for idx, attr in enumerate(attributes)]

    def _load_style(self, qgs_layer: QgsMapLayer, job_layer_definition: QslJobLayer):
        logging.info(" ✓ Omit style loading on WFS layer operation.")

    @staticmethod
    def _destination_crs(crs: Crs | None) -> QgsCoordinateReferenceSystem | None:
        if crs is None:
            return None
        # the identifiers are equivalent, the first one present is taken
        identifier = crs.ogc_urn or crs.ogc_uri or crs.auth_id
        destination_crs = QgsCoordinateReferenceSystem.fromOgcWmsCrs(identifier or "")
        if not destination_crs.isValid():
            raise RuntimeError(f"Crs `{crs}` of the query is not valid")
        return destination_crs

    def run(self):
        query_collection = QueryCollection()
        numbers_matched = 0
        for query in self.job_info.job.queries:
            # we need to reset this because we want always only the layers related to
            # the current query
            self.map_layers = []
            wfs_filter = query.filter
            destination_crs = self._destination_crs(query.crs)
            for job_layer_definition in query.layers:
                self._provide_layer(job_layer_definition)

            for job_layer_definition, layer in zip(query.layers, self.map_layers, strict=True):
                feature_collection = FeatureCollection(job_layer_definition.id)
                query_collection.feature_collections.append(feature_collection)
                if isinstance(layer, QgsVectorLayer):
                    if wfs_filter is not None and wfs_filter.definition is not None:
                        # TODO: This is potentially bad: We always get all features from
                        #  datasource. However, QGIS
                        #   does not seem to support sliding window feature filter out of the box...
                        logging.info(" QslJobLayer is filtered by:")
                        logging.info(f" {wfs_filter.definition}")
                        filter_doc = QDomDocument()
                        filter_doc.setContent(wfs_filter.definition)
                        # This is not correct in the WFS 2.0 way. We apply a filter
                        # to a job_layer_definition. But WFS 2.0
                        # allows filters on multiple layers.
                        # The layer is used to type literals by the field types.
                        expression = QgsOgcUtils.expressionFromOgcFilter(
                            filter_doc.documentElement(),
                            QgsOgcUtils.FilterVersion.FILTER_FES_2_0,
                            layer,
                        )
                        logging.info(
                            f" This was transformed to the QGIS expression "
                            f"(valid: {expression.isValid()})"
                        )
                        logging.info(f" '{expression.dump()}'")
                        feature_request = QgsFeatureRequest(expression)
                        # geom_from_gml takes the layer out of the expression context to
                        # transform geometry literals with srsName into the layer crs
                        feature_request.setExpressionContext(
                            QgsExpressionContext(
                                QgsExpressionContextUtils.globalProjectLayerScopes(layer)
                            )
                        )
                    else:
                        feature_request = QgsFeatureRequest()
                    if destination_crs is not None:
                        # filter expressions are still evaluated in the layer crs, only
                        # the returned geometries are transformed
                        feature_request.setDestinationCrs(destination_crs, layer.transformContext())
                    feature_iterator = layer.getFeatures(feature_request)
                    if not feature_iterator.isValid():
                        self._raise_on_layer_errors({layer.id(): "Data source invalid"})
                    layer_features = list(feature_iterator)
                    numbers_matched += len(layer_features)
                    logging.info(f" Found {len(layer_features)} features")
                    if self.job_info.job.count:
                        layer_features = layer_features[
                            self.job_info.job.start_index : self.job_info.job.start_index
                            + self.job_info.job.count
                        ]
                    for layer_feature in layer_features:
                        property_list = zip(
                            layer_feature.fields().names(),
                            self._clean_attributes(layer_feature.attributes(), layer),
                            strict=True,
                        )
                        feature = Feature(
                            geometry=Geometry(
                                value=bytes(layer_feature.geometry().asWkb()),
                            )
                        )
                        feature_collection.features.append(feature)
                        for name, value in property_list:
                            feature.attributes.append(Attribute(name=name, value=value))
                else:
                    raise RuntimeError(
                        f"QslJobLayer type `{layer.type().name}` of layer "
                        f"`{layer.shortName()}` not supported by GetFeatureInfo"
                    )
        if numbers_matched > 0:
            query_collection.numbers_matched = numbers_matched
        with register_converters_at_runtime():
            data = JsonSerializer().render(query_collection).encode()
            return JobResult(
                id=self.job_info.id,
                data=data,
                content_type="application/qgis-server-light.interface.qgis.QueryCollection",
            )
job_info_class = QslJobInfoFeature class-attribute instance-attribute
__init__(qgis: QgsApplication, context: JobContext, job_info: QslJobInfoFeature, layer_cache: MutableMapping | None = None, layer_style_cache: set | None = None) -> None
Source code in src/qgis_server_light/worker/runner/feature.py
37
38
39
40
41
42
43
44
45
def __init__(
    self,
    qgis: QgsApplication,
    context: JobContext,
    job_info: QslJobInfoFeature,
    layer_cache: MutableMapping | None = None,
    layer_style_cache: set | None = None,
) -> None:
    super().__init__(qgis, context, job_info, layer_cache)
run()
Source code in src/qgis_server_light/worker/runner/feature.py
 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
def run(self):
    query_collection = QueryCollection()
    numbers_matched = 0
    for query in self.job_info.job.queries:
        # we need to reset this because we want always only the layers related to
        # the current query
        self.map_layers = []
        wfs_filter = query.filter
        destination_crs = self._destination_crs(query.crs)
        for job_layer_definition in query.layers:
            self._provide_layer(job_layer_definition)

        for job_layer_definition, layer in zip(query.layers, self.map_layers, strict=True):
            feature_collection = FeatureCollection(job_layer_definition.id)
            query_collection.feature_collections.append(feature_collection)
            if isinstance(layer, QgsVectorLayer):
                if wfs_filter is not None and wfs_filter.definition is not None:
                    # TODO: This is potentially bad: We always get all features from
                    #  datasource. However, QGIS
                    #   does not seem to support sliding window feature filter out of the box...
                    logging.info(" QslJobLayer is filtered by:")
                    logging.info(f" {wfs_filter.definition}")
                    filter_doc = QDomDocument()
                    filter_doc.setContent(wfs_filter.definition)
                    # This is not correct in the WFS 2.0 way. We apply a filter
                    # to a job_layer_definition. But WFS 2.0
                    # allows filters on multiple layers.
                    # The layer is used to type literals by the field types.
                    expression = QgsOgcUtils.expressionFromOgcFilter(
                        filter_doc.documentElement(),
                        QgsOgcUtils.FilterVersion.FILTER_FES_2_0,
                        layer,
                    )
                    logging.info(
                        f" This was transformed to the QGIS expression "
                        f"(valid: {expression.isValid()})"
                    )
                    logging.info(f" '{expression.dump()}'")
                    feature_request = QgsFeatureRequest(expression)
                    # geom_from_gml takes the layer out of the expression context to
                    # transform geometry literals with srsName into the layer crs
                    feature_request.setExpressionContext(
                        QgsExpressionContext(
                            QgsExpressionContextUtils.globalProjectLayerScopes(layer)
                        )
                    )
                else:
                    feature_request = QgsFeatureRequest()
                if destination_crs is not None:
                    # filter expressions are still evaluated in the layer crs, only
                    # the returned geometries are transformed
                    feature_request.setDestinationCrs(destination_crs, layer.transformContext())
                feature_iterator = layer.getFeatures(feature_request)
                if not feature_iterator.isValid():
                    self._raise_on_layer_errors({layer.id(): "Data source invalid"})
                layer_features = list(feature_iterator)
                numbers_matched += len(layer_features)
                logging.info(f" Found {len(layer_features)} features")
                if self.job_info.job.count:
                    layer_features = layer_features[
                        self.job_info.job.start_index : self.job_info.job.start_index
                        + self.job_info.job.count
                    ]
                for layer_feature in layer_features:
                    property_list = zip(
                        layer_feature.fields().names(),
                        self._clean_attributes(layer_feature.attributes(), layer),
                        strict=True,
                    )
                    feature = Feature(
                        geometry=Geometry(
                            value=bytes(layer_feature.geometry().asWkb()),
                        )
                    )
                    feature_collection.features.append(feature)
                    for name, value in property_list:
                        feature.attributes.append(Attribute(name=name, value=value))
            else:
                raise RuntimeError(
                    f"QslJobLayer type `{layer.type().name}` of layer "
                    f"`{layer.shortName()}` not supported by GetFeatureInfo"
                )
    if numbers_matched > 0:
        query_collection.numbers_matched = numbers_matched
    with register_converters_at_runtime():
        data = JsonSerializer().render(query_collection).encode()
        return JobResult(
            id=self.job_info.id,
            data=data,
            content_type="application/qgis-server-light.interface.qgis.QueryCollection",
        )

feature_info

GetFeatureInfoRunner

Bases: MapRunner

Source code in src/qgis_server_light/worker/runner/feature_info.py
20
21
22
23
24
25
26
27
28
29
30
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
class GetFeatureInfoRunner(MapRunner):
    job_info_class = QslJobInfoFeatureInfo

    def __init__(
        self,
        qgis: QgsApplication,
        context: JobContext,
        job_info: QslJobInfoFeatureInfo,
        layer_cache: MutableMapping | None = None,
    ) -> None:
        super().__init__(qgis, context, job_info, layer_cache)

    def _clean_attribute(self, attribute, idx, layer):
        if attribute == NULL:
            return None
        setup = layer.editorWidgetSetup(idx)
        fieldFormatter = QgsApplication.fieldFormatterRegistry().fieldFormatter(setup.type())
        return fieldFormatter.representValue(layer, idx, setup.config(), None, attribute)

    def _clean_attributes(self, attributes, layer):
        return [self._clean_attribute(attr, idx, layer) for idx, attr in enumerate(attributes)]

    def run(self):
        for job_layer_definition in self.job_info.job.layers:
            self._provide_layer(job_layer_definition)
        map_settings = self._get_map_settings(self.map_layers)
        # Estimate queryable bbox (2mm)
        map_to_pixel = map_settings.mapToPixel()
        map_point = map_to_pixel.toMapCoordinates(self.job_info.job.x, self.job_info.job.y)
        # Create identifiable bbox in map coordinates, ±2mm
        tolerance = 0.002 * 39.37 * map_settings.outputDpi()
        tl = QgsPointXY(map_point.x() - tolerance, map_point.y() - tolerance)
        br = QgsPointXY(map_point.x() + tolerance, map_point.y() + tolerance)
        rect = QgsRectangle(tl, br)
        render_context = QgsRenderContext.fromMapSettings(map_settings)

        features = list()
        for layer in self.map_layers:
            renderer = layer.renderer().clone() if layer.renderer() else None
            if renderer:
                renderer.startRender(render_context, layer.fields())

            if layer.type() == QgsMapLayerType.VectorLayer:
                layer_rect = map_settings.mapToLayerCoordinates(layer, rect)
                request = (
                    QgsFeatureRequest()
                    .setFilterRect(layer_rect)
                    .setFlags(QgsFeatureRequest.ExactIntersect)
                )
                feature_iterator = layer.getFeatures(request)
                if not feature_iterator.isValid():
                    self._raise_on_layer_errors({layer.id(): "Data source invalid"})
                for feature in feature_iterator:
                    if renderer.willRenderFeature(feature, render_context):
                        properties = OrderedDict(
                            zip(
                                feature.fields().names(),
                                self._clean_attributes(feature.attributes(), layer),
                                strict=True,
                            )
                        )
                        features.append({"type": "Feature", "properties": properties})
            else:
                raise RuntimeError(
                    f"Layer type `{layer.type().name}` of layer `{layer.shortName()}` "
                    f"not supported by GetFeatureInfo"
                )
            if renderer:
                renderer.stopRender(render_context)

        featurecollection = {"features": features, "type": "FeatureCollection"}
        return JobResult(
            id=self.job_info.id,
            data=json.dumps(featurecollection).encode("utf-8"),
            content_type="application/json",
        )
job_info_class = QslJobInfoFeatureInfo class-attribute instance-attribute
__init__(qgis: QgsApplication, context: JobContext, job_info: QslJobInfoFeatureInfo, layer_cache: MutableMapping | None = None) -> None
Source code in src/qgis_server_light/worker/runner/feature_info.py
23
24
25
26
27
28
29
30
def __init__(
    self,
    qgis: QgsApplication,
    context: JobContext,
    job_info: QslJobInfoFeatureInfo,
    layer_cache: MutableMapping | None = None,
) -> None:
    super().__init__(qgis, context, job_info, layer_cache)
run()
Source code in src/qgis_server_light/worker/runner/feature_info.py
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
def run(self):
    for job_layer_definition in self.job_info.job.layers:
        self._provide_layer(job_layer_definition)
    map_settings = self._get_map_settings(self.map_layers)
    # Estimate queryable bbox (2mm)
    map_to_pixel = map_settings.mapToPixel()
    map_point = map_to_pixel.toMapCoordinates(self.job_info.job.x, self.job_info.job.y)
    # Create identifiable bbox in map coordinates, ±2mm
    tolerance = 0.002 * 39.37 * map_settings.outputDpi()
    tl = QgsPointXY(map_point.x() - tolerance, map_point.y() - tolerance)
    br = QgsPointXY(map_point.x() + tolerance, map_point.y() + tolerance)
    rect = QgsRectangle(tl, br)
    render_context = QgsRenderContext.fromMapSettings(map_settings)

    features = list()
    for layer in self.map_layers:
        renderer = layer.renderer().clone() if layer.renderer() else None
        if renderer:
            renderer.startRender(render_context, layer.fields())

        if layer.type() == QgsMapLayerType.VectorLayer:
            layer_rect = map_settings.mapToLayerCoordinates(layer, rect)
            request = (
                QgsFeatureRequest()
                .setFilterRect(layer_rect)
                .setFlags(QgsFeatureRequest.ExactIntersect)
            )
            feature_iterator = layer.getFeatures(request)
            if not feature_iterator.isValid():
                self._raise_on_layer_errors({layer.id(): "Data source invalid"})
            for feature in feature_iterator:
                if renderer.willRenderFeature(feature, render_context):
                    properties = OrderedDict(
                        zip(
                            feature.fields().names(),
                            self._clean_attributes(feature.attributes(), layer),
                            strict=True,
                        )
                    )
                    features.append({"type": "Feature", "properties": properties})
        else:
            raise RuntimeError(
                f"Layer type `{layer.type().name}` of layer `{layer.shortName()}` "
                f"not supported by GetFeatureInfo"
            )
        if renderer:
            renderer.stopRender(render_context)

    featurecollection = {"features": features, "type": "FeatureCollection"}
    return JobResult(
        id=self.job_info.id,
        data=json.dumps(featurecollection).encode("utf-8"),
        content_type="application/json",
    )

legend

GetLegendRunner

Bases: ImageRunner

Source code in src/qgis_server_light/worker/runner/legend.py
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 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
class GetLegendRunner(ImageRunner):
    job_info_class = QslJobInfoLegend

    def __init__(
        self,
        qgis: QgsApplication,
        context: JobContext,
        job_info: QslJobInfoLegend,
        layer_cache: MutableMapping | None = None,
    ) -> None:
        super().__init__(qgis, context, job_info, layer_cache)

    @classmethod
    def json_formats(cls):
        return ["application/json", "json"]

    def run(self):
        logging.info(f"Executing job: {self.job_info}")
        for job_layer_definition in self.job_info.job.layers:
            self._provide_layer(job_layer_definition)

        if not self.map_layers:
            raise RuntimeError("No legend entries available for requested layers")

        root = QgsLayerTree()
        for layer in self.map_layers:
            root.addLayer(layer)

        model = QgsLayerTreeModel(root)
        settings = QgsLegendSettings()
        # Wait for external legend requests to finish before rendering
        settings.setSynchronousLegendRequests(True)

        if (scale := self.job_info.job.scale) is not None:
            settings.setMapScale(scale)

        if not self.job_info.job.layer_title:
            style = QgsLegendStyle()
            style.setMargin(QgsLegendStyle.Bottom, 0)
            settings.setStyle(QgsLegendStyle.Title, style)
            for layer_node in root.children():
                QgsLegendRenderer.setNodeLegendStyle(layer_node, QgsLegendStyle.Hidden)

        renderer = QgsLegendRenderer(model, settings)

        if self.job_info.job.format.lower() in self.json_formats():
            return JobResult(
                id=self.job_info.id,
                data=self._export_json(renderer),
                content_type="application/json",
            )

        dpi = self.job_info.job.dpi
        px_per_mm = dpi / 25.4
        width = self.job_info.job.width
        height = self.job_info.job.height
        legend_size_mm = renderer.minimumSize()
        default_legend_width_px = int(legend_size_mm.width() * px_per_mm)
        default_legend_height_px = int(legend_size_mm.height() * px_per_mm)

        if width is None and height is None:
            # Default legend looks a bit too big, we scale it down by a bit
            width = int(0.75 * default_legend_width_px)
            height = int(0.75 * default_legend_height_px)
            painter_scale = 0.75
        elif width is None:
            painter_scale = height / default_legend_height_px
            width = int(default_legend_width_px * painter_scale)
        elif height is None:
            painter_scale = width / default_legend_width_px
            height = int(default_legend_height_px * painter_scale)
        else:
            x_scale = width / (legend_size_mm.width() * px_per_mm)
            y_scale = height / (legend_size_mm.height() * px_per_mm)
            painter_scale = min(x_scale, y_scale)

        image = QImage(width, height, QImage.Format_ARGB32)
        image.setDotsPerMeterX(int(dpi * 39.37))
        image.setDotsPerMeterY(int(dpi * 39.37))
        image.fill(Qt.white)

        painter = QPainter(image)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setRenderHint(QPainter.TextAntialiasing, True)
        painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
        painter.scale(painter_scale, painter_scale)

        renderer.drawLegend(painter)
        painter.end()

        content_type, image_data = self._encode_image(image, self.job_info.job.format)

        return JobResult(
            id=self.job_info.id,
            data=image_data,
            content_type=content_type,
        )

    @staticmethod
    def _export_json(renderer: QgsLegendRenderer) -> bytes:
        # same as QGIS Server does it, a default render context is enough here
        legend = renderer.exportLegendToJson(QgsRenderContext())
        return bytes(QJsonDocument(legend).toJson(QJsonDocument.JsonFormat.Compact))
job_info_class = QslJobInfoLegend class-attribute instance-attribute
__init__(qgis: QgsApplication, context: JobContext, job_info: QslJobInfoLegend, layer_cache: MutableMapping | None = None) -> None
Source code in src/qgis_server_light/worker/runner/legend.py
24
25
26
27
28
29
30
31
def __init__(
    self,
    qgis: QgsApplication,
    context: JobContext,
    job_info: QslJobInfoLegend,
    layer_cache: MutableMapping | None = None,
) -> None:
    super().__init__(qgis, context, job_info, layer_cache)
json_formats() classmethod
Source code in src/qgis_server_light/worker/runner/legend.py
33
34
35
@classmethod
def json_formats(cls):
    return ["application/json", "json"]
run()
Source code in src/qgis_server_light/worker/runner/legend.py
 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
def run(self):
    logging.info(f"Executing job: {self.job_info}")
    for job_layer_definition in self.job_info.job.layers:
        self._provide_layer(job_layer_definition)

    if not self.map_layers:
        raise RuntimeError("No legend entries available for requested layers")

    root = QgsLayerTree()
    for layer in self.map_layers:
        root.addLayer(layer)

    model = QgsLayerTreeModel(root)
    settings = QgsLegendSettings()
    # Wait for external legend requests to finish before rendering
    settings.setSynchronousLegendRequests(True)

    if (scale := self.job_info.job.scale) is not None:
        settings.setMapScale(scale)

    if not self.job_info.job.layer_title:
        style = QgsLegendStyle()
        style.setMargin(QgsLegendStyle.Bottom, 0)
        settings.setStyle(QgsLegendStyle.Title, style)
        for layer_node in root.children():
            QgsLegendRenderer.setNodeLegendStyle(layer_node, QgsLegendStyle.Hidden)

    renderer = QgsLegendRenderer(model, settings)

    if self.job_info.job.format.lower() in self.json_formats():
        return JobResult(
            id=self.job_info.id,
            data=self._export_json(renderer),
            content_type="application/json",
        )

    dpi = self.job_info.job.dpi
    px_per_mm = dpi / 25.4
    width = self.job_info.job.width
    height = self.job_info.job.height
    legend_size_mm = renderer.minimumSize()
    default_legend_width_px = int(legend_size_mm.width() * px_per_mm)
    default_legend_height_px = int(legend_size_mm.height() * px_per_mm)

    if width is None and height is None:
        # Default legend looks a bit too big, we scale it down by a bit
        width = int(0.75 * default_legend_width_px)
        height = int(0.75 * default_legend_height_px)
        painter_scale = 0.75
    elif width is None:
        painter_scale = height / default_legend_height_px
        width = int(default_legend_width_px * painter_scale)
    elif height is None:
        painter_scale = width / default_legend_width_px
        height = int(default_legend_height_px * painter_scale)
    else:
        x_scale = width / (legend_size_mm.width() * px_per_mm)
        y_scale = height / (legend_size_mm.height() * px_per_mm)
        painter_scale = min(x_scale, y_scale)

    image = QImage(width, height, QImage.Format_ARGB32)
    image.setDotsPerMeterX(int(dpi * 39.37))
    image.setDotsPerMeterY(int(dpi * 39.37))
    image.fill(Qt.white)

    painter = QPainter(image)
    painter.setRenderHint(QPainter.Antialiasing, True)
    painter.setRenderHint(QPainter.TextAntialiasing, True)
    painter.setRenderHint(QPainter.SmoothPixmapTransform, True)
    painter.scale(painter_scale, painter_scale)

    renderer.drawLegend(painter)
    painter.end()

    content_type, image_data = self._encode_image(image, self.job_info.job.format)

    return JobResult(
        id=self.job_info.id,
        data=image_data,
        content_type=content_type,
    )

process

ProcessRunner

Bases: MapRunner

Responsible for executing a QGIS processing algorithm as a process.

The runner decides on its own where the outputs go, the client only sends the inputs. This way concurrent jobs never write into the same file and a client can't make the worker write anywhere on its file system.

The format of a file output is chosen by the client among the media types the process description offers for it, without a choice the first offered one is used. Vector layers default to GeoJSON, because it takes any data: a GeoPackage takes an input attribute fid as its feature id and fails if the values are not unique, FlatGeobuf refuses features without geometry because of its spatial index.

Attributes:

Source code in src/qgis_server_light/worker/runner/process.py
 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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
class ProcessRunner(MapRunner):
    """Responsible for executing a QGIS processing algorithm as a process.

    The runner decides on its own where the outputs go, the client only sends
    the inputs. This way concurrent jobs never write into the same file and a
    client can't make the worker write anywhere on its file system.

    The format of a file output is chosen by the client among the media types
    the process description offers for it, without a choice the first offered
    one is used. Vector layers default to GeoJSON, because it takes any data:
    a GeoPackage takes an input attribute `fid` as its feature id and fails if
    the values are not unique, FlatGeobuf refuses features without geometry
    because of its spatial index.

    Attributes:
        extension_by_media_type: The file extension a destination gets for the
            media type of its output.
        media_type_by_extension: The media type of a destination file, by its
            extension.
    """

    job_info_class = QslJobInfoExecuteProcess
    extension_by_media_type = {
        "application/geo+json": "geojson",
        "application/geopackage+sqlite3": "gpkg",
        "application/flatgeobuf": "fgb",
        "image/tiff; application=geotiff": "tif",
        "text/html": "html",
    }
    media_type_by_extension = {
        "geojson": "application/geo+json",
        "gpkg": "application/geopackage+sqlite3",
        "fgb": "application/flatgeobuf",
        "tif": "image/tiff; application=geotiff",
        "html": "text/html",
    }

    def __init__(
        self,
        qgis: QgsApplication,
        context: JobContext,
        job_info: QslJobInfoExecuteProcess,
        layer_cache: MutableMapping | None = None,
    ):
        super().__init__(qgis, context, job_info, layer_cache)
        self.registry = self.qgis.processingRegistry()

    @classmethod
    def prepare(cls, qgis: QgsApplication) -> None:
        """Adds the `native:` algorithms the processes are served from. A bare
        QgsApplication knows no algorithms, and only a process-worker needs them.

        Args:
            qgis: The QGIS application of the worker.
        """
        registry = qgis.processingRegistry()
        # QGIS refuses a provider id twice and complains in the log, so a second
        # preparation of the same application (e.g. a second engine) leaves it as it is
        if registry.providerById("native") is None:
            registry.addProvider(QgsNativeAlgorithms())

    @classmethod
    def info(cls, qgis: QgsApplication, context: JobContext) -> ProcessDescriptions:
        """The descriptions of the processes the worker serves. An algorithm of the
        allowlist the worker can't serve is skipped and logged, so one entry can't empty
        the processes of the worker. That's the case for a parameter without mapping and
        for an algorithm requiring a project, the context of the runner has none.

        Args:
            qgis: The QGIS application holding the processing registry.
            context: The context holding the allowlists, the descriptions of the internal
                ones are marked `internal`.

        Returns:
            The descriptions of the processes the worker serves.

        Raises:
            LookupError: If an algorithm of the allowlist is not in the processing registry.
        """
        registry = qgis.processingRegistry()
        mapper = ProcessDescriptionMapper()
        process_descriptions = ProcessDescriptions()
        for process_id in context.served_process_ids:
            algorithm = registry.algorithmById(process_id)
            if algorithm is None:
                raise LookupError(f"Algorithm `{process_id}` of the allowlist not found")
            if cls.requires_project(algorithm):
                logging.warning(
                    f"Algorithm `{process_id}` of the allowlist skipped: requires a project"
                )
                continue
            try:
                process_description = mapper.process_description(algorithm)
            except ValueError as e:
                logging.warning(f"Algorithm `{process_id}` of the allowlist skipped: {e}")
                continue
            if process_id in context.process_internal_allowlist:
                process_description.internal = True
            process_descriptions.processes.append(process_description)
        return process_descriptions

    @staticmethod
    def requires_project(algorithm: QgsProcessingAlgorithm) -> bool:
        """If the algorithm needs a project, the processing context of the runner has none."""
        return bool(algorithm.flags() & Qgis.ProcessingAlgorithmFlag.RequiresProject)

    def run(self):
        """Run this runner.

        Every job writes into its own dir `{process_output_dir}/{job_id}`. If the
        job fails or is canceled, the dir is removed again, so only successful jobs
        leave files behind.

        Returns:
            A JobResult with the ProcessResult as JSON.

        Raises:
            RuntimeError: If the algorithm is not served by this worker, is not
                found, requires a project or no process output dir is configured.
        """
        job: QslJobParameterExecuteProcess = self.job_info.job
        if job.process_id not in self.context.served_process_ids:
            raise RuntimeError(f"Algorithm `{job.process_id}` is not served by this worker")
        algorithm = self.registry.algorithmById(job.process_id)
        if algorithm is None:
            raise RuntimeError(f"Algorithm `{job.process_id}` not found")
        if self.requires_project(algorithm):
            raise RuntimeError(f"Algorithm `{job.process_id}` requires a project")
        if self.context.process_output_dir is None:
            raise RuntimeError("No process output dir configured")

        parameters = self._parameters(algorithm, job)
        job_output_dir = Path(self.context.process_output_dir, self.job_info.id)
        destinations = self._destinations(algorithm, job_output_dir, job.outputs)
        parameters.update({name: str(path) for name, path in destinations.items()})

        job_output_dir.mkdir(parents=True)
        try:
            process_result = self._run_algorithm(algorithm, parameters, destinations)
        except Exception:
            # only successful jobs leave files behind (we avoid half created corpse)
            shutil.rmtree(job_output_dir, ignore_errors=True)
            raise

        return JobResult(
            id=self.job_info.id,
            data=JsonSerializer().render(process_result).encode(),
            content_type="application/qgis-server-light.interface.job.process.ProcessResult",
        )

    def _parameters(
        self, algorithm: QgsProcessingAlgorithm, job: QslJobParameterExecuteProcess
    ) -> dict:
        """The parameters the client sent, mapped to what the algorithm expects.
        Destinations are left out, the worker sets them on its own. A parameter
        taking multiple layers gets all values of its input as list, any other
        parameter the single value of its input.

        Args:
            algorithm: The algorithm the parameters are meant for.
            job: The job holding the parameters of the client.

        Returns:
            The parameters by name, ready to be passed to the algorithm.

        Raises:
            ValueError: If the client sent a destination, a value of an
                unexpected type or not exactly one value for a parameter which
                takes only one.
        """
        parameters = {}
        for execute_input in job.inputs:
            definition = algorithm.parameterDefinition(execute_input.id)
            if definition is not None and definition.isDestination():
                raise ValueError(f"Destination `{execute_input.id}` is set by the worker")
            values = [self._parameter_value(value) for value in execute_input.value]
            if isinstance(definition, QgsProcessingParameterMultipleLayers):
                parameters[execute_input.id] = values
            elif len(values) != 1:
                raise ValueError(f"Parameter `{execute_input.id}` takes exactly one value")
            else:
                parameters[execute_input.id] = values[0]
        return parameters

    def _parameter_value(self, value: QslJobLayer | str | int | float | bool):
        """The value as the algorithm takes it, a layer is loaded through the layer
        cache, a literal is passed as it is.

        Raises:
            ValueError: If the value is of an unexpected type.
        """
        if isinstance(value, QslJobLayer):
            layer = self._handle_layer_cache(value)
            self._check_feature_count(layer)
            return layer
        if isinstance(value, (str, int, float, bool)):
            return value
        raise ValueError(f"Unexpected value: {value}")

    def _check_feature_count(self, layer: QgsMapLayer):
        """Refuses a vector layer with more features than `process_max_features`, before
        the algorithm even starts on it. Rasters pass, their size says little about the
        work an algorithm has with them.

        Args:
            layer: The layer which was loaded for an input.

        Raises:
            ValueError: If the layer has too many features.
        """
        max_features = self.context.process_max_features
        if not max_features or not isinstance(layer, QgsVectorLayer):
            return
        # some providers only estimate the count, that's precise enough for a limit
        if layer.featureCount() > max_features:
            raise ValueError(f"Layer `{layer.title()}` has more than {max_features} features")

    def _destinations(
        self,
        algorithm: QgsProcessingAlgorithm,
        job_output_dir: Path,
        outputs: list[ExecuteOutput],
    ) -> dict[str, Path]:
        """The files the destinations of the algorithm are written to, by
        destination name. The worker sets them, so concurrent jobs never collide.
        The format is checked here, before the algorithm runs, so a job doesn't
        do all the work only to fail on an output nobody asked for.

        Args:
            algorithm: The algorithm whose destinations are set.
            job_output_dir: The dir of the job, the destination files go into.
            outputs: The formats the client chose for the outputs.

        Returns:
            The absolute destination files by destination name.

        Raises:
            ValueError: If the client chose a format for an output which is no
                destination or a format the description does not offer.
        """
        media_type_by_name = {output.id: output.format.media_type for output in outputs}
        destination_names = [
            definition.name() for definition in algorithm.destinationParameterDefinitions()
        ]
        if unknown_names := set(media_type_by_name) - set(destination_names):
            raise ValueError(f"Format chosen for unknown outputs: {sorted(unknown_names)}")

        mapper = ProcessDescriptionMapper()
        destinations = {}
        for name in destination_names:
            output_description = mapper.output_description(algorithm.outputDefinition(name))
            offered = [schema.content_media_type for schema in output_description.schema.one_of]
            media_type = media_type_by_name.get(name, offered[0])
            if media_type not in offered:
                raise ValueError(f"Format `{media_type}` is not offered for output `{name}`")
            destinations[name] = (
                job_output_dir / f"{name}.{self.extension_by_media_type[media_type]}"
            )
        return destinations

    def _reference(self, destination: Path) -> Reference:
        """The destination as the client sees it, relative to the process output
        dir, so the worker does not leak its own file system layout.

        Args:
            destination: The absolute destination file as set by `_destinations`.

        Returns:
            The relative path and the media type of the file.
        """
        return Reference(
            href=destination.relative_to(self.context.process_output_dir).as_posix(),
            type=self.media_type_by_extension[destination.suffix.removeprefix(".")],
        )

    def _run_algorithm(
        self,
        algorithm: QgsProcessingAlgorithm,
        parameters: dict,
        destinations: dict[str, Path],
    ) -> ProcessResult:
        """Runs the algorithm and collects its outputs. Outputs written to a
        file are referenced, all others are returned inline. For files the
        destination the worker set counts, not the path QGIS returns. The algorithm
        runs with the feedback of the job context, so whoever watches the job sees
        its progress and can cancel it.

        Args:
            algorithm: The algorithm to run.
            parameters: The parameters by name, destinations included.
            destinations: The destination files by destination name.

        Returns:
            The outputs and the log of the algorithm.

        Raises:
            RuntimeError: If the algorithm failed or was canceled.
            ValueError: If an output is neither a file nor a literal value.
        """
        context = QgsProcessingContext()
        feedback = self.context.feedback or QgsProcessingFeedback()
        result, ok = algorithm.run(parameters, context, feedback)
        # many algorithms stop their loop on cancel and still return what they have so far
        if feedback.isCanceled():
            raise RuntimeError(f"Algorithm `{algorithm.id()}` was canceled")
        if not ok:
            raise RuntimeError(f"Algorithm `{algorithm.id()}` failed: {feedback.textLog()}")

        process_result = ProcessResult(log=feedback.textLog())
        for name, value in result.items():
            if name in destinations:
                process_result.outputs.append(
                    ResultOutput(name, self._reference(destinations[name]))
                )
            elif isinstance(value, (str, int, float, bool)):
                process_result.outputs.append(ResultOutput(name, value))
            else:
                raise ValueError(f"Unexpected output value: {value}")
        return process_result
extension_by_media_type = {'application/geo+json': 'geojson', 'application/geopackage+sqlite3': 'gpkg', 'application/flatgeobuf': 'fgb', 'image/tiff; application=geotiff': 'tif', 'text/html': 'html'} class-attribute instance-attribute
job_info_class = QslJobInfoExecuteProcess class-attribute instance-attribute
media_type_by_extension = {'geojson': 'application/geo+json', 'gpkg': 'application/geopackage+sqlite3', 'fgb': 'application/flatgeobuf', 'tif': 'image/tiff; application=geotiff', 'html': 'text/html'} class-attribute instance-attribute
registry = self.qgis.processingRegistry() instance-attribute
__init__(qgis: QgsApplication, context: JobContext, job_info: QslJobInfoExecuteProcess, layer_cache: MutableMapping | None = None)
Source code in src/qgis_server_light/worker/runner/process.py
73
74
75
76
77
78
79
80
81
def __init__(
    self,
    qgis: QgsApplication,
    context: JobContext,
    job_info: QslJobInfoExecuteProcess,
    layer_cache: MutableMapping | None = None,
):
    super().__init__(qgis, context, job_info, layer_cache)
    self.registry = self.qgis.processingRegistry()
info(qgis: QgsApplication, context: JobContext) -> ProcessDescriptions classmethod

The descriptions of the processes the worker serves. An algorithm of the allowlist the worker can't serve is skipped and logged, so one entry can't empty the processes of the worker. That's the case for a parameter without mapping and for an algorithm requiring a project, the context of the runner has none.

Parameters:

  • qgis (QgsApplication) –

    The QGIS application holding the processing registry.

  • context (JobContext) –

    The context holding the allowlists, the descriptions of the internal ones are marked internal.

Returns:

Raises:

  • LookupError –

    If an algorithm of the allowlist is not in the processing registry.

Source code in src/qgis_server_light/worker/runner/process.py
 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
@classmethod
def info(cls, qgis: QgsApplication, context: JobContext) -> ProcessDescriptions:
    """The descriptions of the processes the worker serves. An algorithm of the
    allowlist the worker can't serve is skipped and logged, so one entry can't empty
    the processes of the worker. That's the case for a parameter without mapping and
    for an algorithm requiring a project, the context of the runner has none.

    Args:
        qgis: The QGIS application holding the processing registry.
        context: The context holding the allowlists, the descriptions of the internal
            ones are marked `internal`.

    Returns:
        The descriptions of the processes the worker serves.

    Raises:
        LookupError: If an algorithm of the allowlist is not in the processing registry.
    """
    registry = qgis.processingRegistry()
    mapper = ProcessDescriptionMapper()
    process_descriptions = ProcessDescriptions()
    for process_id in context.served_process_ids:
        algorithm = registry.algorithmById(process_id)
        if algorithm is None:
            raise LookupError(f"Algorithm `{process_id}` of the allowlist not found")
        if cls.requires_project(algorithm):
            logging.warning(
                f"Algorithm `{process_id}` of the allowlist skipped: requires a project"
            )
            continue
        try:
            process_description = mapper.process_description(algorithm)
        except ValueError as e:
            logging.warning(f"Algorithm `{process_id}` of the allowlist skipped: {e}")
            continue
        if process_id in context.process_internal_allowlist:
            process_description.internal = True
        process_descriptions.processes.append(process_description)
    return process_descriptions
prepare(qgis: QgsApplication) -> None classmethod

Adds the native: algorithms the processes are served from. A bare QgsApplication knows no algorithms, and only a process-worker needs them.

Parameters:

  • qgis (QgsApplication) –

    The QGIS application of the worker.

Source code in src/qgis_server_light/worker/runner/process.py
83
84
85
86
87
88
89
90
91
92
93
94
95
@classmethod
def prepare(cls, qgis: QgsApplication) -> None:
    """Adds the `native:` algorithms the processes are served from. A bare
    QgsApplication knows no algorithms, and only a process-worker needs them.

    Args:
        qgis: The QGIS application of the worker.
    """
    registry = qgis.processingRegistry()
    # QGIS refuses a provider id twice and complains in the log, so a second
    # preparation of the same application (e.g. a second engine) leaves it as it is
    if registry.providerById("native") is None:
        registry.addProvider(QgsNativeAlgorithms())
requires_project(algorithm: QgsProcessingAlgorithm) -> bool staticmethod

If the algorithm needs a project, the processing context of the runner has none.

Source code in src/qgis_server_light/worker/runner/process.py
137
138
139
140
@staticmethod
def requires_project(algorithm: QgsProcessingAlgorithm) -> bool:
    """If the algorithm needs a project, the processing context of the runner has none."""
    return bool(algorithm.flags() & Qgis.ProcessingAlgorithmFlag.RequiresProject)
run()

Run this runner.

Every job writes into its own dir {process_output_dir}/{job_id}. If the job fails or is canceled, the dir is removed again, so only successful jobs leave files behind.

Returns:

  • –

    A JobResult with the ProcessResult as JSON.

Raises:

  • RuntimeError –

    If the algorithm is not served by this worker, is not found, requires a project or no process output dir is configured.

Source code in src/qgis_server_light/worker/runner/process.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def run(self):
    """Run this runner.

    Every job writes into its own dir `{process_output_dir}/{job_id}`. If the
    job fails or is canceled, the dir is removed again, so only successful jobs
    leave files behind.

    Returns:
        A JobResult with the ProcessResult as JSON.

    Raises:
        RuntimeError: If the algorithm is not served by this worker, is not
            found, requires a project or no process output dir is configured.
    """
    job: QslJobParameterExecuteProcess = self.job_info.job
    if job.process_id not in self.context.served_process_ids:
        raise RuntimeError(f"Algorithm `{job.process_id}` is not served by this worker")
    algorithm = self.registry.algorithmById(job.process_id)
    if algorithm is None:
        raise RuntimeError(f"Algorithm `{job.process_id}` not found")
    if self.requires_project(algorithm):
        raise RuntimeError(f"Algorithm `{job.process_id}` requires a project")
    if self.context.process_output_dir is None:
        raise RuntimeError("No process output dir configured")

    parameters = self._parameters(algorithm, job)
    job_output_dir = Path(self.context.process_output_dir, self.job_info.id)
    destinations = self._destinations(algorithm, job_output_dir, job.outputs)
    parameters.update({name: str(path) for name, path in destinations.items()})

    job_output_dir.mkdir(parents=True)
    try:
        process_result = self._run_algorithm(algorithm, parameters, destinations)
    except Exception:
        # only successful jobs leave files behind (we avoid half created corpse)
        shutil.rmtree(job_output_dir, ignore_errors=True)
        raise

    return JobResult(
        id=self.job_info.id,
        data=JsonSerializer().render(process_result).encode(),
        content_type="application/qgis-server-light.interface.job.process.ProcessResult",
    )

render

RenderRunner

Bases: ImageRunner

Responsible for rendering a QslRenderJob to an image.

Source code in src/qgis_server_light/worker/runner/render.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
class RenderRunner(ImageRunner):
    """Responsible for rendering a QslRenderJob to an image."""

    job_info_class = QslJobInfoRender

    def __init__(
        self,
        qgis: QgsApplication,
        context: JobContext,
        job_info: QslJobInfoRender,
        layer_cache: MutableMapping | None = None,
    ) -> None:
        super().__init__(qgis, context, job_info, layer_cache)

    def run(self):
        """Run this runner.
        Returns:
            A JobResult with the content_type and image_data (bytes) of the rendered image.
        """
        logging.info(f"Executing job: {self.job_info}")
        feature_filter = QgsFeatureFilter()
        for job_layer_definition in self.job_info.job.layers:
            self._provide_layer(job_layer_definition)
        map_settings = self._get_map_settings(self.map_layers)
        # QGIS emits finished synchronously in start() on invalid settings (e.g.
        # an empty bbox), before the event loop runs, so it would wait forever
        if not map_settings.hasValidSettings():
            raise RuntimeError(
                f"Invalid map settings, bbox: {self.job_info.job.bbox}, "
                f"size: {self.job_info.job.width}x{self.job_info.job.height}"
            )
        # same as QGIS Server GetMap, enables the simplification on rendering
        # which is defined in the layer styles
        map_settings.setFlag(Qgis.MapSettingsFlag.UseRenderingOptimization)
        filter_providers = QgsFeatureFilterProviderGroup()
        filter_providers.addProvider(feature_filter)
        renderer = QgsMapRendererParallelJob(map_settings)
        renderer.setFeatureFilterProvider(filter_providers)
        event_loop = QEventLoop(self.qgis)
        renderer.finished.connect(event_loop.quit)
        renderer.start()
        event_loop.exec_()
        self._raise_on_layer_errors({error.layerID: error.message for error in renderer.errors()})
        img = renderer.renderedImage()
        img.setDotsPerMeterX(int(map_settings.outputDpi() * 39.37))
        img.setDotsPerMeterY(int(map_settings.outputDpi() * 39.37))
        content_type, image_data = self._encode_image(img, self.job_info.job.format)
        return JobResult(id=self.job_info.id, data=image_data, content_type=content_type)
job_info_class = QslJobInfoRender class-attribute instance-attribute
__init__(qgis: QgsApplication, context: JobContext, job_info: QslJobInfoRender, layer_cache: MutableMapping | None = None) -> None
Source code in src/qgis_server_light/worker/runner/render.py
18
19
20
21
22
23
24
25
def __init__(
    self,
    qgis: QgsApplication,
    context: JobContext,
    job_info: QslJobInfoRender,
    layer_cache: MutableMapping | None = None,
) -> None:
    super().__init__(qgis, context, job_info, layer_cache)
run()

Run this runner. Returns: A JobResult with the content_type and image_data (bytes) of the rendered image.

Source code in src/qgis_server_light/worker/runner/render.py
27
28
29
30
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
def run(self):
    """Run this runner.
    Returns:
        A JobResult with the content_type and image_data (bytes) of the rendered image.
    """
    logging.info(f"Executing job: {self.job_info}")
    feature_filter = QgsFeatureFilter()
    for job_layer_definition in self.job_info.job.layers:
        self._provide_layer(job_layer_definition)
    map_settings = self._get_map_settings(self.map_layers)
    # QGIS emits finished synchronously in start() on invalid settings (e.g.
    # an empty bbox), before the event loop runs, so it would wait forever
    if not map_settings.hasValidSettings():
        raise RuntimeError(
            f"Invalid map settings, bbox: {self.job_info.job.bbox}, "
            f"size: {self.job_info.job.width}x{self.job_info.job.height}"
        )
    # same as QGIS Server GetMap, enables the simplification on rendering
    # which is defined in the layer styles
    map_settings.setFlag(Qgis.MapSettingsFlag.UseRenderingOptimization)
    filter_providers = QgsFeatureFilterProviderGroup()
    filter_providers.addProvider(feature_filter)
    renderer = QgsMapRendererParallelJob(map_settings)
    renderer.setFeatureFilterProvider(filter_providers)
    event_loop = QEventLoop(self.qgis)
    renderer.finished.connect(event_loop.quit)
    renderer.start()
    event_loop.exec_()
    self._raise_on_layer_errors({error.layerID: error.message for error in renderer.errors()})
    img = renderer.renderedImage()
    img.setDotsPerMeterX(int(map_settings.outputDpi() * 39.37))
    img.setDotsPerMeterY(int(map_settings.outputDpi() * 39.37))
    content_type, image_data = self._encode_image(img, self.job_info.job.format)
    return JobResult(id=self.job_info.id, data=image_data, content_type=content_type)