Skip to content

runner

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)