Skip to content

common

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()