Skip to content

process

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",
    )