Skip to content

qgis_server_light

qgis_server_light

crs

This module contains the crs handling shared by the exporter and the worker. It is the only place where QGIS crs information is translated into the QGIS-Server-Light interface.

create_qsl_crs(crs: QgsCoordinateReferenceSystem) -> Crs

Translates a QGIS crs into an instance of the QGIS-Server-Light interface Crs.

Parameters:

  • crs (QgsCoordinateReferenceSystem) –

    The QGIS crs to take the information from.

Returns:

  • Crs –

    The instance of the QSL interface Crs.

Source code in src/qgis_server_light/crs.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def create_qsl_crs(crs: QgsCoordinateReferenceSystem) -> Crs:
    """
    Translates a QGIS crs into an instance of the QGIS-Server-Light interface Crs.

    Args:
        crs: The QGIS crs to take the information from.

    Returns:
        The instance of the QSL interface Crs.
    """
    return Crs(
        postgis_srid=crs.postgisSrid(),
        auth_id=crs.authid(),
        ogc_uri=crs.toOgcUri(),
        ogc_urn=crs.toOgcUrn(),
        axis_inverted=crs.hasAxisInverted(),
    )

debug

profile

profile_async(func)

A profiler which can be used as a decorator on ASYNC methods to produce profiles and call graphs.

The Callgraph might be inspected with QCacheGrind or KCacheGrind or sth. else.

Parameters:

  • func –

    the wrapped method

Returns:

  • –

    The wrapper

Source code in src/qgis_server_light/debug/profile.py
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def profile_async(func):
    """A profiler which can be used as a decorator on ASYNC methods to produce
    profiles and call graphs.

    The Callgraph might be inspected with QCacheGrind or KCacheGrind or sth. else.

    Args:
        func: the wrapped method

    Returns:
        The wrapper
    """

    async def wrapper(*args, **kwargs):
        import cProfile
        import pstats

        import pyprof2calltree

        pr = cProfile.Profile()
        pr.enable()

        result = await func(*args, **kwargs)

        pr.disable()
        stats = pstats.Stats(pr)
        path = Path(".profile")
        path.mkdir(parents=True, exist_ok=True)
        stats_file = os.path.join(str(path), f"{func.__module__}.{func.__name__}.profile_data.prof")
        callgrind_file = os.path.join(str(path), f"{func.__module__}.{func.__name__}.callgrind.out")
        stats.dump_stats(stats_file)
        call_tree = pyprof2calltree.CalltreeConverter(stats)
        with open(callgrind_file, "w+") as f:
            call_tree.output(f)
        print(f"Profiling data saved to: {stats_file}, CallTree saved t: {callgrind_file}")

        return result

    return wrapper
profile_sync(func)

A profiler which can be used as a decorator on SYNC methods to produce profiles and call graphs.

The Callgraph might be inspected with QCacheGrind or KCacheGrind or sth. else.

Parameters:

  • func –

    the wrapped method

Returns:

  • –

    The wrapper

Source code in src/qgis_server_light/debug/profile.py
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
def profile_sync(func):
    """A profiler which can be used as a decorator on SYNC methods to produce
    profiles and call graphs.

    The Callgraph might be inspected with QCacheGrind or KCacheGrind or sth. else.

    Args:
        func: the wrapped method

    Returns:
        The wrapper
    """

    def wrapper(*args, **kwargs):
        import cProfile
        import pstats

        import pyprof2calltree

        pr = cProfile.Profile()
        pr.enable()

        result = func(*args, **kwargs)

        pr.disable()
        stats = pstats.Stats(pr)
        path = Path(".profile")
        path.mkdir(parents=True, exist_ok=True)
        stats_file = os.path.join(str(path), f"{func.__module__}.{func.__name__}.profile_data.prof")
        callgrind_file = os.path.join(str(path), f"{func.__module__}.{func.__name__}.callgrind.out")
        stats.dump_stats(stats_file)
        call_tree = pyprof2calltree.CalltreeConverter(stats)
        with open(callgrind_file, "w+") as f:
            call_tree.output(f)
        print(f"Profiling data saved to: {stats_file}, CallTree saved t: {callgrind_file}")

        return result

    return wrapper

dispatcher

redis_asio

This contains the dispatcher which passes a job info around a redis queue.

RedisDispatcher

Bases: RedisProtocol

The common part of the dispatchers: the connection to redis and how a job is put into it. How the result comes back is up to the subclasses, they are combined with the matching protocol.

Attributes:

Source code in src/qgis_server_light/dispatcher/redis_asio.py
 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
class RedisDispatcher(RedisProtocol):
    """The common part of the dispatchers: the connection to redis and how a job
    is put into it. How the result comes back is up to the subclasses, they are
    combined with the matching protocol.

    Attributes:
        job_info_classes: The job info class per job parameter class, used to
            wrap a job parameter into its job info.
    """

    job_info_classes: ClassVar[dict[type[QslJobParameter], type[QslJobInfoParameter]]] = {
        QslJobParameterRender: QslJobInfoRender,
        QslJobParameterFeatureInfo: QslJobInfoFeatureInfo,
        QslJobParameterLegend: QslJobInfoLegend,
        QslJobParameterFeature: QslJobInfoFeature,
        QslJobParameterCrs: QslJobInfoCrs,
        QslJobParameterExecuteProcess: QslJobInfoExecuteProcess,
    }

    def __init__(self, redis_client: redis_aio.Redis) -> None:
        # we use this to hold connections to redis in a pool, this way we are
        # event loop safe and when creating the redis client for every call of
        # post, we only instantiate a minimal wrapper object which is cheap.

        self.client = redis_client

    @classmethod
    def create(cls, url: str):
        redis_client = redis_aio.Redis.from_url(url)
        return cls(redis_client)

    async def is_reachable(self) -> bool:
        """Pings redis. The caller only needs to know whether jobs could be queued, so
        the redis exceptions stay in here and are logged.

        Returns:
            True if redis answered, False if it could not be reached.
        """
        try:
            return await self.client.ping()
        except RedisError as e:
            logging.warning(f"Redis is not reachable: {e}")
            return False

    async def registered_workers(self) -> list[Worker]:
        """Collects every worker redis still knows, no matter how old its last heartbeat
        is. This way crashed or silently vanished workers can be shown until their info
        expires, the consumer tells them apart by `info.status` and `last_seen`.

        Returns:
            The registered workers, sorted by their id to give a stable order.
        """
        workers = []
        for worker_id in sorted(await self.client.smembers(self.worker_list_name)):
            last_seen, info = await self.client.hmget(
                self.worker_key(worker_id.decode()),
                [self.worker_last_seen_key, self.worker_info_key],
            )
            if last_seen is None or info is None:
                # the worker vanished, its info expired already
                continue
            workers.append(
                Worker(
                    id=worker_id.decode(),
                    last_seen=self.parse_last_seen(last_seen),
                    info=JsonParser().from_bytes(info, EngineInfo),
                )
            )
        return workers

    async def alive_workers(self) -> list[Worker]:
        """Collects the workers which sent a heartbeat within `worker_alive_age` and did
        not crash. Workers which are still registered but stopped beating (e.g. killed)
        or reported a crash are left out, so the result tells who is really there to
        process jobs.

        Returns:
            The alive workers, sorted by their id to give a stable order.
        """
        now = datetime.datetime.now(datetime.UTC)
        alive_age = datetime.timedelta(seconds=self.worker_alive_age)
        return [
            worker
            for worker in await self.registered_workers()
            if now - worker.last_seen <= alive_age and worker.info.status != WorkerStatus.CRASHED
        ]

    @staticmethod
    def parse_last_seen(last_seen: bytes) -> datetime.datetime:
        """Reads the heartbeat timestamp of a worker as it is stored in redis.

        Args:
            last_seen: The ISO timestamp as redis returns it.

        Returns:
            The timezone aware timestamp, naive ones are taken as UTC.
        """
        timestamp = datetime.datetime.fromisoformat(last_seen.decode())
        if timestamp.tzinfo is None:
            # workers before the UTC heartbeat wrote their local time without offset, in
            # containers this is UTC usually
            timestamp = timestamp.replace(tzinfo=datetime.UTC)
        return timestamp

    @classmethod
    def derive_job_info(cls, job_id: str, job_parameter: QslJobParameter) -> QslJobInfoParameter:
        """Wraps the job parameter into the job info matching its type.

        Args:
            job_id: The unique identifier of the job.
            job_parameter: The parameter for the job which should be executed.

        Returns:
            The job info carrying the job parameter.

        Raises:
            TypeError: If there is no job info for the type of the job parameter.
        """
        job_info_class = cls.job_info_classes.get(type(job_parameter))
        if job_info_class is None:
            raise TypeError(f"Unsupported runner type: {type(job_parameter)}")
        return job_info_class(
            id=job_id,
            type=job_info_class.__name__,
            job=job_parameter,
        )

    async def set_job_runtime_status(
        self,
        job_id,
        pipeline: Pipeline,
        status: str,
        start_time: float,
        execute: bool = True,
    ):
        """Sets the status of the job together with its timestamps and duration.

        Args:
            job_id: The unique identifier of the job.
            pipeline: The pipeline holding the transaction.
            status: The status to set.
            start_time: The time the job was posted, used for the duration.
            execute: False if the caller adds more to the transaction and executes it
                itself.
        """
        duration = time.time() - start_time
        ts = datetime.datetime.now().isoformat()
        await pipeline.hset(self.job_key(job_id), self.job_status_key, status)
        await pipeline.hset(
            self.job_key(job_id),
            f"{self.job_timestamp_key}.{status}",
            ts,
        )
        await pipeline.hset(self.job_key(job_id), self.job_last_update_key, ts)
        await pipeline.hset(self.job_key(job_id), self.job_duration_key, str(duration))
        if execute:
            await pipeline.execute()

    async def queue_job(
        self, job_info: QslJobInfoParameter, pipeline: Pipeline, start_time: float
    ) -> None:
        """Puts the job info into the job hash, sets the queued status and pushes
        the job id onto the queue of the protocol. Nothing is executed here, the
        caller adds what belongs to its protocol to the same transaction and
        executes it.

        Args:
            job_info: The job info of the job which should be queued.
            pipeline: The pipeline holding the transaction.
            start_time: The time the job was posted, used for the duration.
        """
        # Putting job info into redis
        await pipeline.hset(
            self.job_key(job_info.id), self.job_info_key, JsonSerializer().render(job_info)
        )
        await pipeline.hset(
            self.job_key(job_info.id), self.job_info_type_key, job_info.__class__.__name__
        )
        # we inform, that the job was queued. This happens in the same
        # transaction as the queuing, so it can not overwrite a status
        # already set by the worker.
        await self.set_job_runtime_status(
            job_info.id, pipeline, Status.QUEUED.value, start_time, execute=False
        )
        # Queuing the job onto the list/queue of the protocol
        await pipeline.rpush(self.queue_name(), job_info.id)
client = redis_client instance-attribute
job_info_classes: dict[type[QslJobParameter], type[QslJobInfoParameter]] = {QslJobParameterRender: QslJobInfoRender, QslJobParameterFeatureInfo: QslJobInfoFeatureInfo, QslJobParameterLegend: QslJobInfoLegend, QslJobParameterFeature: QslJobInfoFeature, QslJobParameterCrs: QslJobInfoCrs, QslJobParameterExecuteProcess: QslJobInfoExecuteProcess} class-attribute
__init__(redis_client: redis_aio.Redis) -> None
Source code in src/qgis_server_light/dispatcher/redis_asio.py
83
84
85
86
87
88
def __init__(self, redis_client: redis_aio.Redis) -> None:
    # we use this to hold connections to redis in a pool, this way we are
    # event loop safe and when creating the redis client for every call of
    # post, we only instantiate a minimal wrapper object which is cheap.

    self.client = redis_client
alive_workers() -> list[Worker] async

Collects the workers which sent a heartbeat within worker_alive_age and did not crash. Workers which are still registered but stopped beating (e.g. killed) or reported a crash are left out, so the result tells who is really there to process jobs.

Returns:

  • list[Worker] –

    The alive workers, sorted by their id to give a stable order.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
async def alive_workers(self) -> list[Worker]:
    """Collects the workers which sent a heartbeat within `worker_alive_age` and did
    not crash. Workers which are still registered but stopped beating (e.g. killed)
    or reported a crash are left out, so the result tells who is really there to
    process jobs.

    Returns:
        The alive workers, sorted by their id to give a stable order.
    """
    now = datetime.datetime.now(datetime.UTC)
    alive_age = datetime.timedelta(seconds=self.worker_alive_age)
    return [
        worker
        for worker in await self.registered_workers()
        if now - worker.last_seen <= alive_age and worker.info.status != WorkerStatus.CRASHED
    ]
create(url: str) classmethod
Source code in src/qgis_server_light/dispatcher/redis_asio.py
90
91
92
93
@classmethod
def create(cls, url: str):
    redis_client = redis_aio.Redis.from_url(url)
    return cls(redis_client)
derive_job_info(job_id: str, job_parameter: QslJobParameter) -> QslJobInfoParameter classmethod

Wraps the job parameter into the job info matching its type.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

  • job_parameter (QslJobParameter) –

    The parameter for the job which should be executed.

Returns:

Raises:

  • TypeError –

    If there is no job info for the type of the job parameter.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
@classmethod
def derive_job_info(cls, job_id: str, job_parameter: QslJobParameter) -> QslJobInfoParameter:
    """Wraps the job parameter into the job info matching its type.

    Args:
        job_id: The unique identifier of the job.
        job_parameter: The parameter for the job which should be executed.

    Returns:
        The job info carrying the job parameter.

    Raises:
        TypeError: If there is no job info for the type of the job parameter.
    """
    job_info_class = cls.job_info_classes.get(type(job_parameter))
    if job_info_class is None:
        raise TypeError(f"Unsupported runner type: {type(job_parameter)}")
    return job_info_class(
        id=job_id,
        type=job_info_class.__name__,
        job=job_parameter,
    )
is_reachable() -> bool async

Pings redis. The caller only needs to know whether jobs could be queued, so the redis exceptions stay in here and are logged.

Returns:

  • bool –

    True if redis answered, False if it could not be reached.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
async def is_reachable(self) -> bool:
    """Pings redis. The caller only needs to know whether jobs could be queued, so
    the redis exceptions stay in here and are logged.

    Returns:
        True if redis answered, False if it could not be reached.
    """
    try:
        return await self.client.ping()
    except RedisError as e:
        logging.warning(f"Redis is not reachable: {e}")
        return False
parse_last_seen(last_seen: bytes) -> datetime.datetime staticmethod

Reads the heartbeat timestamp of a worker as it is stored in redis.

Parameters:

  • last_seen (bytes) –

    The ISO timestamp as redis returns it.

Returns:

  • datetime –

    The timezone aware timestamp, naive ones are taken as UTC.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
@staticmethod
def parse_last_seen(last_seen: bytes) -> datetime.datetime:
    """Reads the heartbeat timestamp of a worker as it is stored in redis.

    Args:
        last_seen: The ISO timestamp as redis returns it.

    Returns:
        The timezone aware timestamp, naive ones are taken as UTC.
    """
    timestamp = datetime.datetime.fromisoformat(last_seen.decode())
    if timestamp.tzinfo is None:
        # workers before the UTC heartbeat wrote their local time without offset, in
        # containers this is UTC usually
        timestamp = timestamp.replace(tzinfo=datetime.UTC)
    return timestamp
queue_job(job_info: QslJobInfoParameter, pipeline: Pipeline, start_time: float) -> None async

Puts the job info into the job hash, sets the queued status and pushes the job id onto the queue of the protocol. Nothing is executed here, the caller adds what belongs to its protocol to the same transaction and executes it.

Parameters:

  • job_info (QslJobInfoParameter) –

    The job info of the job which should be queued.

  • pipeline (Pipeline) –

    The pipeline holding the transaction.

  • start_time (float) –

    The time the job was posted, used for the duration.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
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
async def queue_job(
    self, job_info: QslJobInfoParameter, pipeline: Pipeline, start_time: float
) -> None:
    """Puts the job info into the job hash, sets the queued status and pushes
    the job id onto the queue of the protocol. Nothing is executed here, the
    caller adds what belongs to its protocol to the same transaction and
    executes it.

    Args:
        job_info: The job info of the job which should be queued.
        pipeline: The pipeline holding the transaction.
        start_time: The time the job was posted, used for the duration.
    """
    # Putting job info into redis
    await pipeline.hset(
        self.job_key(job_info.id), self.job_info_key, JsonSerializer().render(job_info)
    )
    await pipeline.hset(
        self.job_key(job_info.id), self.job_info_type_key, job_info.__class__.__name__
    )
    # we inform, that the job was queued. This happens in the same
    # transaction as the queuing, so it can not overwrite a status
    # already set by the worker.
    await self.set_job_runtime_status(
        job_info.id, pipeline, Status.QUEUED.value, start_time, execute=False
    )
    # Queuing the job onto the list/queue of the protocol
    await pipeline.rpush(self.queue_name(), job_info.id)
registered_workers() -> list[Worker] async

Collects every worker redis still knows, no matter how old its last heartbeat is. This way crashed or silently vanished workers can be shown until their info expires, the consumer tells them apart by info.status and last_seen.

Returns:

  • list[Worker] –

    The registered workers, sorted by their id to give a stable order.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
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
async def registered_workers(self) -> list[Worker]:
    """Collects every worker redis still knows, no matter how old its last heartbeat
    is. This way crashed or silently vanished workers can be shown until their info
    expires, the consumer tells them apart by `info.status` and `last_seen`.

    Returns:
        The registered workers, sorted by their id to give a stable order.
    """
    workers = []
    for worker_id in sorted(await self.client.smembers(self.worker_list_name)):
        last_seen, info = await self.client.hmget(
            self.worker_key(worker_id.decode()),
            [self.worker_last_seen_key, self.worker_info_key],
        )
        if last_seen is None or info is None:
            # the worker vanished, its info expired already
            continue
        workers.append(
            Worker(
                id=worker_id.decode(),
                last_seen=self.parse_last_seen(last_seen),
                info=JsonParser().from_bytes(info, EngineInfo),
            )
        )
    return workers
set_job_runtime_status(job_id, pipeline: Pipeline, status: str, start_time: float, execute: bool = True) async

Sets the status of the job together with its timestamps and duration.

Parameters:

  • job_id –

    The unique identifier of the job.

  • pipeline (Pipeline) –

    The pipeline holding the transaction.

  • status (str) –

    The status to set.

  • start_time (float) –

    The time the job was posted, used for the duration.

  • execute (bool, default: True ) –

    False if the caller adds more to the transaction and executes it itself.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
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
async def set_job_runtime_status(
    self,
    job_id,
    pipeline: Pipeline,
    status: str,
    start_time: float,
    execute: bool = True,
):
    """Sets the status of the job together with its timestamps and duration.

    Args:
        job_id: The unique identifier of the job.
        pipeline: The pipeline holding the transaction.
        status: The status to set.
        start_time: The time the job was posted, used for the duration.
        execute: False if the caller adds more to the transaction and executes it
            itself.
    """
    duration = time.time() - start_time
    ts = datetime.datetime.now().isoformat()
    await pipeline.hset(self.job_key(job_id), self.job_status_key, status)
    await pipeline.hset(
        self.job_key(job_id),
        f"{self.job_timestamp_key}.{status}",
        ts,
    )
    await pipeline.hset(self.job_key(job_id), self.job_last_update_key, ts)
    await pipeline.hset(self.job_key(job_id), self.job_duration_key, str(duration))
    if execute:
        await pipeline.execute()
RedisQueue

Bases: RedisDispatcher, RedisPublishProtocol

The dispatcher for short living jobs a caller waits for. The result is received over the channel and nothing is kept in redis afterwards.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
477
478
479
480
481
482
483
484
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
class RedisQueue(RedisDispatcher, RedisPublishProtocol):
    """The dispatcher for short living jobs a caller waits for. The result is
    received over the channel and nothing is kept in redis afterwards.
    """

    async def post(
        self,
        job_parameter: (
            QslJobParameterRender
            | QslJobParameterFeatureInfo
            | QslJobParameterLegend
            | QslJobParameterFeature
            | QslJobParameterCrs
        ),
        to: float = 10.0,
    ) -> tuple[JobResult, str]:
        """
        Posts a new `runner` to the runner queue and waits maximum `timeout` seconds to complete.
        Will return a JobResult if successful or raise an error.

        Args:
            job_parameter: The parameter for the job which should be executed.
            to: The timeout a job is expected to be waited for before canceling
                job execution.
        """
        job_id = str(uuid4())
        start_time = time.time()
        try:
            job_info = self.derive_job_info(job_id, job_parameter)
        except TypeError as e:
            return (
                JobResult(
                    id=job_id,
                    data=str(e),
                    content_type="application/text",
                ),
                Status.FAILURE.value,
            )
        try:
            async with self.client.pubsub() as ps:
                # We subscribe to `notifications:{job_id}` *before* the job is
                # queued. Redis pub/sub does not buffer messages, so a fast job
                # (e.g. a legend) could otherwise be published by the worker
                # before we listen, and its result would be lost.
                await ps.subscribe(self.channel(job_id))
                async with self.client.pipeline() as p:
                    await self.queue_job(job_info, p, start_time)
                    await p.execute()

                logging.info(f"{job_id} queued")
                try:
                    # this puts a timeout trigger on the subscription, after timeout
                    # an asyncio.TimeoutError or asyncio.exceptions.CancelledError
                    # is raised. See except block below.
                    async with timeout(to):
                        while True:
                            message = await ps.get_message(
                                timeout=to, ignore_subscribe_messages=True
                            )
                            if not message:
                                continue  # https://github.com/redis/redis-py/issues/733
                            status_binary = await self.client.hget(
                                self.job_key(job_id), self.job_status_key
                            )
                            status = status_binary.decode()
                            result: JobResult = pickle.loads(message["data"])
                            duration = time.time() - start_time
                            if status == Status.SUCCESS.value:
                                logging.info(
                                    f"Job id: {job_id}, status: {status}, duration: {duration}"
                                )
                            elif status == Status.FAILURE.value:
                                logging.info(
                                    f"Job id: {job_id}, status: {status}, "
                                    f"duration: {duration}, error: {result.data}"
                                )
                            return result, status
                except (TimeoutError, asyncio.exceptions.CancelledError):
                    logging.info(f"{job_id} timeout")
                    raise
        except Exception as e:
            duration = time.time() - start_time
            logging.info(
                f"Job id: {job_id}, status: {Status.FAILURE.value}, duration: {duration}",
                exc_info=True,
            )
            return (
                JobResult(
                    id=job_id,
                    data=str(e),
                    content_type="application/text",
                ),
                Status.FAILURE.value,
            )
        finally:
            try:
                await self.client.delete(self.job_key(job_id))
            except Exception:
                logging.warning(
                    f"Cleanup failed for {job_id}",
                    exc_info=True,
                )
post(job_parameter: QslJobParameterRender | QslJobParameterFeatureInfo | QslJobParameterLegend | QslJobParameterFeature | QslJobParameterCrs, to: float = 10.0) -> tuple[JobResult, str] async

Posts a new runner to the runner queue and waits maximum timeout seconds to complete. Will return a JobResult if successful or raise an error.

Parameters:

Source code in src/qgis_server_light/dispatcher/redis_asio.py
482
483
484
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
async def post(
    self,
    job_parameter: (
        QslJobParameterRender
        | QslJobParameterFeatureInfo
        | QslJobParameterLegend
        | QslJobParameterFeature
        | QslJobParameterCrs
    ),
    to: float = 10.0,
) -> tuple[JobResult, str]:
    """
    Posts a new `runner` to the runner queue and waits maximum `timeout` seconds to complete.
    Will return a JobResult if successful or raise an error.

    Args:
        job_parameter: The parameter for the job which should be executed.
        to: The timeout a job is expected to be waited for before canceling
            job execution.
    """
    job_id = str(uuid4())
    start_time = time.time()
    try:
        job_info = self.derive_job_info(job_id, job_parameter)
    except TypeError as e:
        return (
            JobResult(
                id=job_id,
                data=str(e),
                content_type="application/text",
            ),
            Status.FAILURE.value,
        )
    try:
        async with self.client.pubsub() as ps:
            # We subscribe to `notifications:{job_id}` *before* the job is
            # queued. Redis pub/sub does not buffer messages, so a fast job
            # (e.g. a legend) could otherwise be published by the worker
            # before we listen, and its result would be lost.
            await ps.subscribe(self.channel(job_id))
            async with self.client.pipeline() as p:
                await self.queue_job(job_info, p, start_time)
                await p.execute()

            logging.info(f"{job_id} queued")
            try:
                # this puts a timeout trigger on the subscription, after timeout
                # an asyncio.TimeoutError or asyncio.exceptions.CancelledError
                # is raised. See except block below.
                async with timeout(to):
                    while True:
                        message = await ps.get_message(
                            timeout=to, ignore_subscribe_messages=True
                        )
                        if not message:
                            continue  # https://github.com/redis/redis-py/issues/733
                        status_binary = await self.client.hget(
                            self.job_key(job_id), self.job_status_key
                        )
                        status = status_binary.decode()
                        result: JobResult = pickle.loads(message["data"])
                        duration = time.time() - start_time
                        if status == Status.SUCCESS.value:
                            logging.info(
                                f"Job id: {job_id}, status: {status}, duration: {duration}"
                            )
                        elif status == Status.FAILURE.value:
                            logging.info(
                                f"Job id: {job_id}, status: {status}, "
                                f"duration: {duration}, error: {result.data}"
                            )
                        return result, status
            except (TimeoutError, asyncio.exceptions.CancelledError):
                logging.info(f"{job_id} timeout")
                raise
    except Exception as e:
        duration = time.time() - start_time
        logging.info(
            f"Job id: {job_id}, status: {Status.FAILURE.value}, duration: {duration}",
            exc_info=True,
        )
        return (
            JobResult(
                id=job_id,
                data=str(e),
                content_type="application/text",
            ),
            Status.FAILURE.value,
        )
    finally:
        try:
            await self.client.delete(self.job_key(job_id))
        except Exception:
            logging.warning(
                f"Cleanup failed for {job_id}",
                exc_info=True,
            )
RedisStateQueue

Bases: RedisDispatcher, RedisStateProtocol

The dispatcher for jobs which keep their state. A job is submitted and its state can be read at any time later, until the job hash expires. A caller who wants to wait for the result uses wait.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
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
class RedisStateQueue(RedisDispatcher, RedisStateProtocol):
    """The dispatcher for jobs which keep their state. A job is submitted and
    its state can be read at any time later, until the job hash expires. A
    caller who wants to wait for the result uses `wait`.
    """

    async def process_descriptions(self) -> ProcessDescriptions:
        """The descriptions of the processes the alive process-workers serve, each worker
        keeps its own in its hash. Empty as long as no process-worker is alive.

        Returns:
            The processes merged over all workers, see `merge_process_descriptions`.
        """
        served = []
        for worker in await self.alive_workers():
            processes_json = await self.client.hget(
                self.worker_key(worker.id), self.worker_processes_key
            )
            if processes_json is None:
                # the worker serves no processes or redis lost them until its next beat
                continue
            process_descriptions = JsonParser().from_bytes(processes_json, ProcessDescriptions)
            served.append((worker.info.qgis_info, process_descriptions))
        return self.merge_process_descriptions(served)

    @staticmethod
    def merge_process_descriptions(
        served: list[tuple[QgisInfo, ProcessDescriptions]],
    ) -> ProcessDescriptions:
        """Merges the processes of several workers into one list. Workers on one redis
        should all run the same QGIS and serve the same processes. When they don't, the
        description of the newest QGIS is taken and the process gets a warning, so the
        deployment can be corrected.

        Args:
            served: The QGIS of each worker and the processes it serves.

        Returns:
            Each process once, with a warning for each process the workers don't agree on.
        """
        descriptions_by_process_id: dict[str, list[tuple[QgisInfo, ProcessDescription]]] = {}
        # the newest QGIS first, its description is the one taken
        for qgis_info, process_descriptions in sorted(
            served, key=lambda item: item[0].version, reverse=True
        ):
            for process in process_descriptions.processes:
                descriptions_by_process_id.setdefault(process.id, []).append((qgis_info, process))

        merged = ProcessDescriptions()
        for process_id, described in descriptions_by_process_id.items():
            newest = described[0][1]
            merged.processes.append(newest)
            # each version once, the newest first
            qgis_versions = list(dict.fromkeys(qgis.version_name for qgis, _ in described))
            descriptions_differ = any(process != newest for _, process in described)
            if len(qgis_versions) > 1 or descriptions_differ:
                logging.warning(
                    f"Process `{process_id}` is served by QGIS {qgis_versions}, "
                    f"descriptions differ: {descriptions_differ}"
                )
                merged.warnings.append(
                    ProcessWarning(
                        process_id=process_id,
                        qgis_versions=qgis_versions,
                        descriptions_differ=descriptions_differ,
                    )
                )
        return merged

    async def submit(
        self,
        job_id: str,
        job_parameter: QslJobParameterExecuteProcess,
        execution_mode: ExecutionMode = ExecutionMode.ASYNC,
    ) -> None:
        """Queues a process job and returns right away. The expiry is set in the
        same transaction, so a job which is never picked up does not stay in
        redis forever.

        Args:
            job_id: The unique identifier of the job, given by the caller so it
                can refer to the job later.
            job_parameter: The parameter for the process which should be executed.
            execution_mode: `ExecutionMode.SYNC` if the caller is going to
                `wait` for the job, the worker only notifies then.
        """
        job_info = self.derive_job_info(job_id, job_parameter)
        job_info.execution_mode = execution_mode
        async with self.client.pipeline() as p:
            await self.queue_job(job_info, p, time.time())
            await p.expire(self.job_key(job_id), self.job_expire)
            await p.execute()
        logging.info(f"{job_id} submitted")

    async def dismiss(self, job_id: str) -> JobState | None:
        """Dismisses a job. A queued job is taken off the queue and is dismissed right
        away. A job a worker took already gets the cancel flag, the worker cancels it
        and finishes it as dismissed, so its state changes a moment later. A finished
        job stays as it is, there is nothing left to stop.

        Args:
            job_id: The unique identifier of the job.

        Returns:
            The state of the job after dismissing, `None` if the job does not exist
            (anymore).
        """
        job_state = await self.state(job_id)
        if job_state is None or job_state.finished:
            return job_state
        async with self.client.pipeline() as p:
            # in one transaction, so a worker taking the job meanwhile still sees the flag
            await p.lrem(self.queue_name(), 0, job_id)
            await p.hset(self.job_key(job_id), self.job_cancel_key, 1)
            removed, _ = await p.execute()
        if removed:
            # no worker will ever see the job, so the dispatcher finishes it itself
            async with self.client.pipeline() as p:
                await p.hset(self.job_key(job_id), self.job_message_key, "The job was dismissed.")
                await self.set_job_runtime_status(
                    job_id, p, Status.DISMISSED.value, time.time(), execute=False
                )
                await p.expire(self.job_key(job_id), self.job_expire)
                # a dispatcher waiting for a synchronous job wakes up
                await p.publish(self.channel(job_id), Status.DISMISSED.value)
                await p.execute()
        logging.info(f"{job_id} dismissed")
        return await self.state(job_id)

    async def state(self, job_id: str) -> JobState | None:
        """Reads the current state of the job from its job hash.

        Args:
            job_id: The unique identifier of the job.

        Returns:
            The state of the job, `None` if the job does not exist (anymore).
        """
        job_hash = await self.client.hgetall(self.job_key(job_id))
        if not job_hash:
            return None
        job_hash = {key.decode(): value for key, value in job_hash.items()}
        return JobState(
            id=job_id,
            status=Status(job_hash[self.job_status_key].decode()),
            last_update=self.decode_optional(job_hash.get(self.job_last_update_key)),
            result=self.job_result(job_id, job_hash),
            message=self.decode_optional(job_hash.get(self.job_message_key)),
            progress=self.decode_progress(job_hash.get(self.job_progress_key)),
        )

    @staticmethod
    def decode_optional(value: bytes | None) -> str | None:
        """Decodes a hash field which might not be set."""
        return value.decode() if value is not None else None

    @staticmethod
    def decode_progress(value: bytes | None) -> int | None:
        """Decodes the progress, which is only set if the job reported one."""
        return int(value) if value is not None else None

    def job_result(self, job_id: str, job_hash: dict[str, bytes]) -> JobResult | None:
        """Assembles the result of the job from its decoded job hash. The data
        stays bytes, the content type tells the caller how to read it.

        Args:
            job_id: The unique identifier of the job.
            job_hash: The job hash with decoded field names.

        Returns:
            The result, `None` as long as the job has not succeeded.
        """
        if self.job_result_key not in job_hash:
            return None
        return JobResult(
            id=job_id,
            data=job_hash[self.job_result_key],
            content_type=job_hash[self.job_result_content_type_key].decode(),
        )

    async def wait(self, job_id: str, to: float = 10.0) -> JobState | None:
        """Waits maximum `to` seconds for the job to finish. This is what makes a
        synchronous execution possible on top of a job which keeps its state.
        It only gets notified if the job was submitted with
        `ExecutionMode.SYNC`, otherwise it runs into the timeout.

        Args:
            job_id: The unique identifier of the job.
            to: The timeout in seconds.

        Returns:
            The state of the job after it finished or the timeout passed, `None`
            if the job does not exist (anymore).
        """
        async with self.client.pubsub() as ps:
            # We subscribe before reading the state, so a notification published in
            # between is not lost.
            await ps.subscribe(self.channel(job_id))
            job_state = await self.state(job_id)
            if job_state is None or job_state.finished:
                return job_state
            await self.wait_for_notification(ps, job_id, to)
        return await self.state(job_id)

    @staticmethod
    async def wait_for_notification(ps: PubSub, job_id: str, to: float) -> None:
        """Blocks until a message arrives on the subscribed channel or the timeout
        passes. The message itself is not of interest, the state is read from
        the job hash afterwards.

        Args:
            ps: The pubsub which is subscribed to the channel of the job.
            job_id: The unique identifier of the job, used for logging.
            to: The timeout in seconds.
        """
        try:
            async with timeout(to):
                while True:
                    message = await ps.get_message(timeout=to, ignore_subscribe_messages=True)
                    if message:
                        return
        except (TimeoutError, asyncio.exceptions.CancelledError):
            logging.info(f"{job_id} timeout")
decode_optional(value: bytes | None) -> str | None staticmethod

Decodes a hash field which might not be set.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
403
404
405
406
@staticmethod
def decode_optional(value: bytes | None) -> str | None:
    """Decodes a hash field which might not be set."""
    return value.decode() if value is not None else None
decode_progress(value: bytes | None) -> int | None staticmethod

Decodes the progress, which is only set if the job reported one.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
408
409
410
411
@staticmethod
def decode_progress(value: bytes | None) -> int | None:
    """Decodes the progress, which is only set if the job reported one."""
    return int(value) if value is not None else None
dismiss(job_id: str) -> JobState | None async

Dismisses a job. A queued job is taken off the queue and is dismissed right away. A job a worker took already gets the cancel flag, the worker cancels it and finishes it as dismissed, so its state changes a moment later. A finished job stays as it is, there is nothing left to stop.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

Returns:

  • JobState | None –

    The state of the job after dismissing, None if the job does not exist

  • JobState | None –

    (anymore).

Source code in src/qgis_server_light/dispatcher/redis_asio.py
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
async def dismiss(self, job_id: str) -> JobState | None:
    """Dismisses a job. A queued job is taken off the queue and is dismissed right
    away. A job a worker took already gets the cancel flag, the worker cancels it
    and finishes it as dismissed, so its state changes a moment later. A finished
    job stays as it is, there is nothing left to stop.

    Args:
        job_id: The unique identifier of the job.

    Returns:
        The state of the job after dismissing, `None` if the job does not exist
        (anymore).
    """
    job_state = await self.state(job_id)
    if job_state is None or job_state.finished:
        return job_state
    async with self.client.pipeline() as p:
        # in one transaction, so a worker taking the job meanwhile still sees the flag
        await p.lrem(self.queue_name(), 0, job_id)
        await p.hset(self.job_key(job_id), self.job_cancel_key, 1)
        removed, _ = await p.execute()
    if removed:
        # no worker will ever see the job, so the dispatcher finishes it itself
        async with self.client.pipeline() as p:
            await p.hset(self.job_key(job_id), self.job_message_key, "The job was dismissed.")
            await self.set_job_runtime_status(
                job_id, p, Status.DISMISSED.value, time.time(), execute=False
            )
            await p.expire(self.job_key(job_id), self.job_expire)
            # a dispatcher waiting for a synchronous job wakes up
            await p.publish(self.channel(job_id), Status.DISMISSED.value)
            await p.execute()
    logging.info(f"{job_id} dismissed")
    return await self.state(job_id)
job_result(job_id: str, job_hash: dict[str, bytes]) -> JobResult | None

Assembles the result of the job from its decoded job hash. The data stays bytes, the content type tells the caller how to read it.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

  • job_hash (dict[str, bytes]) –

    The job hash with decoded field names.

Returns:

  • JobResult | None –

    The result, None as long as the job has not succeeded.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
def job_result(self, job_id: str, job_hash: dict[str, bytes]) -> JobResult | None:
    """Assembles the result of the job from its decoded job hash. The data
    stays bytes, the content type tells the caller how to read it.

    Args:
        job_id: The unique identifier of the job.
        job_hash: The job hash with decoded field names.

    Returns:
        The result, `None` as long as the job has not succeeded.
    """
    if self.job_result_key not in job_hash:
        return None
    return JobResult(
        id=job_id,
        data=job_hash[self.job_result_key],
        content_type=job_hash[self.job_result_content_type_key].decode(),
    )
merge_process_descriptions(served: list[tuple[QgisInfo, ProcessDescriptions]]) -> ProcessDescriptions staticmethod

Merges the processes of several workers into one list. Workers on one redis should all run the same QGIS and serve the same processes. When they don't, the description of the newest QGIS is taken and the process gets a warning, so the deployment can be corrected.

Parameters:

Returns:

  • ProcessDescriptions –

    Each process once, with a warning for each process the workers don't agree on.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
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
@staticmethod
def merge_process_descriptions(
    served: list[tuple[QgisInfo, ProcessDescriptions]],
) -> ProcessDescriptions:
    """Merges the processes of several workers into one list. Workers on one redis
    should all run the same QGIS and serve the same processes. When they don't, the
    description of the newest QGIS is taken and the process gets a warning, so the
    deployment can be corrected.

    Args:
        served: The QGIS of each worker and the processes it serves.

    Returns:
        Each process once, with a warning for each process the workers don't agree on.
    """
    descriptions_by_process_id: dict[str, list[tuple[QgisInfo, ProcessDescription]]] = {}
    # the newest QGIS first, its description is the one taken
    for qgis_info, process_descriptions in sorted(
        served, key=lambda item: item[0].version, reverse=True
    ):
        for process in process_descriptions.processes:
            descriptions_by_process_id.setdefault(process.id, []).append((qgis_info, process))

    merged = ProcessDescriptions()
    for process_id, described in descriptions_by_process_id.items():
        newest = described[0][1]
        merged.processes.append(newest)
        # each version once, the newest first
        qgis_versions = list(dict.fromkeys(qgis.version_name for qgis, _ in described))
        descriptions_differ = any(process != newest for _, process in described)
        if len(qgis_versions) > 1 or descriptions_differ:
            logging.warning(
                f"Process `{process_id}` is served by QGIS {qgis_versions}, "
                f"descriptions differ: {descriptions_differ}"
            )
            merged.warnings.append(
                ProcessWarning(
                    process_id=process_id,
                    qgis_versions=qgis_versions,
                    descriptions_differ=descriptions_differ,
                )
            )
    return merged
process_descriptions() -> ProcessDescriptions async

The descriptions of the processes the alive process-workers serve, each worker keeps its own in its hash. Empty as long as no process-worker is alive.

Returns:

  • ProcessDescriptions –

    The processes merged over all workers, see merge_process_descriptions.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
async def process_descriptions(self) -> ProcessDescriptions:
    """The descriptions of the processes the alive process-workers serve, each worker
    keeps its own in its hash. Empty as long as no process-worker is alive.

    Returns:
        The processes merged over all workers, see `merge_process_descriptions`.
    """
    served = []
    for worker in await self.alive_workers():
        processes_json = await self.client.hget(
            self.worker_key(worker.id), self.worker_processes_key
        )
        if processes_json is None:
            # the worker serves no processes or redis lost them until its next beat
            continue
        process_descriptions = JsonParser().from_bytes(processes_json, ProcessDescriptions)
        served.append((worker.info.qgis_info, process_descriptions))
    return self.merge_process_descriptions(served)
state(job_id: str) -> JobState | None async

Reads the current state of the job from its job hash.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

Returns:

  • JobState | None –

    The state of the job, None if the job does not exist (anymore).

Source code in src/qgis_server_light/dispatcher/redis_asio.py
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
async def state(self, job_id: str) -> JobState | None:
    """Reads the current state of the job from its job hash.

    Args:
        job_id: The unique identifier of the job.

    Returns:
        The state of the job, `None` if the job does not exist (anymore).
    """
    job_hash = await self.client.hgetall(self.job_key(job_id))
    if not job_hash:
        return None
    job_hash = {key.decode(): value for key, value in job_hash.items()}
    return JobState(
        id=job_id,
        status=Status(job_hash[self.job_status_key].decode()),
        last_update=self.decode_optional(job_hash.get(self.job_last_update_key)),
        result=self.job_result(job_id, job_hash),
        message=self.decode_optional(job_hash.get(self.job_message_key)),
        progress=self.decode_progress(job_hash.get(self.job_progress_key)),
    )
submit(job_id: str, job_parameter: QslJobParameterExecuteProcess, execution_mode: ExecutionMode = ExecutionMode.ASYNC) -> None async

Queues a process job and returns right away. The expiry is set in the same transaction, so a job which is never picked up does not stay in redis forever.

Parameters:

  • job_id (str) –

    The unique identifier of the job, given by the caller so it can refer to the job later.

  • job_parameter (QslJobParameterExecuteProcess) –

    The parameter for the process which should be executed.

  • execution_mode (ExecutionMode, default: ASYNC ) –

    ExecutionMode.SYNC if the caller is going to wait for the job, the worker only notifies then.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
async def submit(
    self,
    job_id: str,
    job_parameter: QslJobParameterExecuteProcess,
    execution_mode: ExecutionMode = ExecutionMode.ASYNC,
) -> None:
    """Queues a process job and returns right away. The expiry is set in the
    same transaction, so a job which is never picked up does not stay in
    redis forever.

    Args:
        job_id: The unique identifier of the job, given by the caller so it
            can refer to the job later.
        job_parameter: The parameter for the process which should be executed.
        execution_mode: `ExecutionMode.SYNC` if the caller is going to
            `wait` for the job, the worker only notifies then.
    """
    job_info = self.derive_job_info(job_id, job_parameter)
    job_info.execution_mode = execution_mode
    async with self.client.pipeline() as p:
        await self.queue_job(job_info, p, time.time())
        await p.expire(self.job_key(job_id), self.job_expire)
        await p.execute()
    logging.info(f"{job_id} submitted")
wait(job_id: str, to: float = 10.0) -> JobState | None async

Waits maximum to seconds for the job to finish. This is what makes a synchronous execution possible on top of a job which keeps its state. It only gets notified if the job was submitted with ExecutionMode.SYNC, otherwise it runs into the timeout.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

  • to (float, default: 10.0 ) –

    The timeout in seconds.

Returns:

  • JobState | None –

    The state of the job after it finished or the timeout passed, None

  • JobState | None –

    if the job does not exist (anymore).

Source code in src/qgis_server_light/dispatcher/redis_asio.py
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
async def wait(self, job_id: str, to: float = 10.0) -> JobState | None:
    """Waits maximum `to` seconds for the job to finish. This is what makes a
    synchronous execution possible on top of a job which keeps its state.
    It only gets notified if the job was submitted with
    `ExecutionMode.SYNC`, otherwise it runs into the timeout.

    Args:
        job_id: The unique identifier of the job.
        to: The timeout in seconds.

    Returns:
        The state of the job after it finished or the timeout passed, `None`
        if the job does not exist (anymore).
    """
    async with self.client.pubsub() as ps:
        # We subscribe before reading the state, so a notification published in
        # between is not lost.
        await ps.subscribe(self.channel(job_id))
        job_state = await self.state(job_id)
        if job_state is None or job_state.finished:
            return job_state
        await self.wait_for_notification(ps, job_id, to)
    return await self.state(job_id)
wait_for_notification(ps: PubSub, job_id: str, to: float) -> None async staticmethod

Blocks until a message arrives on the subscribed channel or the timeout passes. The message itself is not of interest, the state is read from the job hash afterwards.

Parameters:

  • ps (PubSub) –

    The pubsub which is subscribed to the channel of the job.

  • job_id (str) –

    The unique identifier of the job, used for logging.

  • to (float) –

    The timeout in seconds.

Source code in src/qgis_server_light/dispatcher/redis_asio.py
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
@staticmethod
async def wait_for_notification(ps: PubSub, job_id: str, to: float) -> None:
    """Blocks until a message arrives on the subscribed channel or the timeout
    passes. The message itself is not of interest, the state is read from
    the job hash afterwards.

    Args:
        ps: The pubsub which is subscribed to the channel of the job.
        job_id: The unique identifier of the job, used for logging.
        to: The timeout in seconds.
    """
    try:
        async with timeout(to):
            while True:
                message = await ps.get_message(timeout=to, ignore_subscribe_messages=True)
                if message:
                    return
    except (TimeoutError, asyncio.exceptions.CancelledError):
        logging.info(f"{job_id} timeout")

exporter

api

DATA_ROOT: Path | None = Path(env_data_root) if env_data_root is not None else None module-attribute
LOGLEVEL: str = 'INFO' module-attribute
app = Flask(__name__) module-attribute
env_data_root = os.environ.get('QSL_DATA_ROOT', None) module-attribute
api_export()
Source code in src/qgis_server_light/exporter/api.py
 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
@app.route(
    "/export",
    methods=["POST"],
)
def api_export():
    global DATA_ROOT, LOGLEVEL
    response_mime_type = "text/json"
    if DATA_ROOT is None:
        e = (
            "Something is wrong with the DATA_ROOT, it has the value None."
            "This means the api has started wrongly, we cant run the export."
        )
        app.logger.error(e)
        result = ExportResult(successful=False, content=e)
        return Response(JsonSerializer().render(result), mimetype=response_mime_type)
    body = request.get_json()
    app.logger.debug(f"Received a new task to export {type(body)} {body}")
    parser_config = ParserConfig(fail_on_unknown_properties=True)
    try:
        parameters = JsonParser(config=parser_config).from_string(body, ExportParameters)
    except Exception as e:
        app.logger.exception(e)
        result = ExportResult(successful=False, content=str(e))
        return Response(JsonSerializer().render(result), mimetype=response_mime_type)

    qualified_path = assemble_project_base_path(DATA_ROOT, parameters.project_path)
    if not qualified_path.exists():
        e = f"project_file: {parameters.project_path} DOES NOT EXISTS in dataroot"
        app.logger.info(e)
        result = ExportResult(successful=False, content=str(e))
        return Response(JsonSerializer().render(result), mimetype=response_mime_type)

    try:
        process = subprocess.run(
            [
                sys.executable,
                "-m",
                "qgis_server_light.exporter.cli",
                "export",
                "--project",
                str(qualified_path),
                "--unify_layer_names_by_group",
                str(parameters.unify_layer_names_by_group),
                "--output_format",
                parameters.output_format,
            ],
            text=True,
            check=True,
            capture_output=True,
        )
        result = ExportResult(successful=True, content=process.stdout)
        app.logger.debug(f"Successfully extracted information from QGIS Project {result}")
    except subprocess.CalledProcessError as e:
        if e.returncode == ExportFailure.EXIT_CODE:
            result = ExportResult(successful=False, content=e.stdout)
            app.logger.debug(f"Unsuccessful extraction with structured error: {result}")
        else:
            app.logger.exception(e.stderr)
            error_message = ExportMessage(
                level=ExportMessage.Level.ERROR,
                code=ExportMessage.Code.UNEXPECTED_ERROR,
                message=str(e),
            )
            result_content = ResultWithMessages(
                project=Project(name=parameters.project_path, version=""),
                exporter=Exporter(qgis_version=""),
                messages=[error_message],
            )
            if parameters.output_format.lower() == "xml":
                serializer = XmlSerializer()
            else:
                serializer = JsonSerializer()
            result = ExportResult(successful=False, content=serializer.render(result_content))
    return Response(JsonSerializer().render(result), mimetype=response_mime_type)
assemble_output_file_path(project_base_path: Path, output_format: str) -> Path
Source code in src/qgis_server_light/exporter/api.py
35
36
def assemble_output_file_path(project_base_path: Path, output_format: str) -> Path:
    return Path(str(project_base_path) + f".{output_format}")
assemble_project_base_path(data_path: Path, project_path: str) -> Path
Source code in src/qgis_server_light/exporter/api.py
31
32
def assemble_project_base_path(data_path: Path, project_path: str) -> Path:
    return Path(data_path, project_path)
main() -> None

Just the central cli entry command. Currently, we don't use it, but its here for future content.

Source code in src/qgis_server_light/exporter/api.py
115
116
117
118
119
120
121
122
@click.group
def main() -> None:
    """
    Just the central cli entry command. Currently, we don't use it, but its here
    for future content.

    """
    pass
start(data_root, host: str = '127.0.0.1', port: int = 5000, log_level: str = 'info')
Source code in src/qgis_server_light/exporter/api.py
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
@click.option(
    "--data-root",
    help="The host address the service will be started on.",
)
@click.option(
    "--host",
    type=str,
    default="127.0.0.1",
    help="The host address the service will be started on.",
)
@click.option(
    "--port",
    type=int,
    default=5000,
    help="The port the service will be exposed to.",
)
@click.option(
    "--log-level",
    type=str,
    default="info",
    help="log level (debug, info, warning or error)",
)
@main.command(
    "start",
    context_settings={"max_content_width": 120},
    help="""
    Starts the exporter API. be sure to set the data_root to an accessible directory!
    """,
)
def start(
    data_root,
    host: str = "127.0.0.1",
    port: int = 5000,
    log_level: str = "info",
):
    global DATA_ROOT, LOGLEVEL
    root_path = Path(data_root)
    if root_path.exists() and root_path.is_dir():
        # we reset root path to the passed variable value and ignore ENV!
        DATA_ROOT = root_path
        LOGLEVEL = log_level.upper()
        app.run(
            host=host,
            debug=log_level.upper() in ["DEBUG"],
            threaded=False,
            port=port,
        )
    else:
        raise RuntimeError(f"Mandatory 'data_root' => {data_root} does not exist or is not a dir.")

cli

allowed_extensions = ('qgz', 'qgs') module-attribute
allowed_output_formats = ('json', 'xml') module-attribute
qgs = QgsApplication([], False) module-attribute
export(project: str, unify_layer_names_by_group: bool = False, output_format: str | None = None) -> None
Source code in src/qgis_server_light/exporter/cli.py
 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
@click.option("--project", help="Absolute path to the QGIS project.")
@click.option(
    "--unify_layer_names_by_group",
    default=False,
    help="Use the full tree path to unify job_layer_definition names.",
)
@click.option(
    "--output_format",
    default="json",
    help=f"The desired output format. Allowed are {'|'.join(allowed_output_formats)}.",
)
@main.command(
    "export",
    context_settings={"max_content_width": 120},
    help=f"""
    Export a QGIS project ({"|".join(allowed_extensions)}) (1st argument) file
    to {"|".join(allowed_output_formats)} format.

    Layers referencing a pg_service need the PGSERVICEFILE environment variable so
    that QGIS can open them during the export. The cli might be called with:

      PGSERVICEFILE=<absolute-path-to-pg_service.conf> python -m qgis_server_light.exporter.cli ...
    """,
)
def export(
    project: str,
    unify_layer_names_by_group: bool = False,
    output_format: str | None = None,
) -> None:
    logging.getLogger().setLevel(logging.DEBUG)
    serializer_config = SerializerConfig(indent="  ")
    output_format = "json" if output_format is None else output_format.lower()
    if not project.lower().endswith(allowed_extensions):
        raise click.BadParameter(
            f"Allowed qgis project file extensions "
            f"are: {'|'.join(allowed_extensions)} not => {project}",
            param_hint="--project",
        )
    if output_format not in allowed_output_formats:
        raise click.BadParameter(
            f"Allowed output formats are: {'|'.join(allowed_output_formats)} "
            f"not => {output_format}",
            param_hint="--output_format",
        )
    if not os.path.isfile(project):
        raise click.BadParameter(
            f"Project file '{project}' does not exist",
            param_hint="--project",
        )

    exporter = Exporter(
        project,
        unify_layer_names_by_group=bool(unify_layer_names_by_group),
    )

    if output_format == "json":
        serializer = JsonSerializer(config=serializer_config)
    elif output_format == "xml":
        serializer = XmlSerializer(config=serializer_config)
    else:
        raise RuntimeError(f"Unexpected output format {output_format}")

    try:
        config = exporter.run()
    except ExportFailure as err:
        click.echo(serializer.render(err.get_result()))
        raise click.exceptions.Exit(code=err.EXIT_CODE) from err
    else:
        click.echo(serializer.render(config))
main() -> None

Just the central cli entry command. Currently, we don't use it, but its here for future content.

Source code in src/qgis_server_light/exporter/cli.py
24
25
26
27
28
29
30
@click.group
def main() -> None:
    """
    Just the central cli entry command. Currently, we don't use it, but its here
    for future content.

    """

exceptions

ExportFailure

Bases: Exception

Source code in src/qgis_server_light/exporter/exceptions.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class ExportFailure(Exception):
    EXIT_CODE = 3

    def __init__(
        self,
        *,
        messages: list[ExportMessage],
        project: Project,
        exporter: Exporter,
    ) -> None:
        super().__init__("QGIS project export failed")
        self.messages = messages
        self.project = project
        self.exporter = exporter

    def get_result(self) -> ResultWithMessages:
        return ResultWithMessages(
            project=self.project,
            exporter=self.exporter,
            messages=self.messages,
        )
EXIT_CODE = 3 class-attribute instance-attribute
exporter = exporter instance-attribute
messages = messages instance-attribute
project = project instance-attribute
__init__(*, messages: list[ExportMessage], project: Project, exporter: Exporter) -> None
Source code in src/qgis_server_light/exporter/exceptions.py
12
13
14
15
16
17
18
19
20
21
22
def __init__(
    self,
    *,
    messages: list[ExportMessage],
    project: Project,
    exporter: Exporter,
) -> None:
    super().__init__("QGIS project export failed")
    self.messages = messages
    self.project = project
    self.exporter = exporter
get_result() -> ResultWithMessages
Source code in src/qgis_server_light/exporter/exceptions.py
24
25
26
27
28
29
def get_result(self) -> ResultWithMessages:
    return ResultWithMessages(
        project=self.project,
        exporter=self.exporter,
        messages=self.messages,
    )

extract

Exporter
Source code in src/qgis_server_light/exporter/extract.py
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 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
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
class Exporter:
    def __init__(
        self,
        qgis_project_path: str,
        unify_layer_names_by_group=False,
        unify_layer_names_by_group_separator=".",
    ):
        self.unify_layer_names_by_group_separator = unify_layer_names_by_group_separator
        self.path = qgis_project_path
        self.unify_layer_names_by_group = unify_layer_names_by_group

        # prepare QGIS instances
        self.qgis_project = self.open_qgis_project(qgis_project_path)
        self.qgis_project_tree_root = self.qgis_project.layerTreeRoot()
        self.name = self.prepare_qgis_project_name(self.qgis_project)
        self.version = self.qgis_project.lastSaveVersion()

        # prepare QSL interface instances
        self.qsl_tree = Tree()
        self.qsl_datasets = Datasets()
        self.qsl_project = Project(name=self.name, version=self.version.text())
        self.qsl_project_metadata = self.extract_metadata(self.qgis_project)
        self.qsl_config = Config(
            exporter=ExporterMeta(qgis_version=Qgis.version()),
            project=self.qsl_project,
            meta_data=self.qsl_project_metadata,
            tree=self.qsl_tree,
            datasets=self.qsl_datasets,
        )

    def run(self) -> Config:
        if project_error := self.qgis_project.error():
            self.qsl_config.error(
                project_error,
                code=ExportMessage.Code.PROJECT_READ_FAILED,
            )
            raise self.build_export_failure()
        if self.version.majorVersion() > 4:
            self.qsl_config.error(
                f"QGIS project version {self.version.text()} is not supported.",
                code=ExportMessage.Code.PROJECT_VERSION_UNSUPPORTED,
            )
            raise self.build_export_failure()
        self.walk_qgis_project_tree(self.qgis_project_tree_root, [])
        self.qsl_config.relations = self.create_qsl_relations(self.qgis_project)
        return self.qsl_config

    def walk_qgis_project_tree(
        self,
        entity: QgsLayerTreeNode,
        path: list[str],
    ):
        """
        This is a highly recursive function which walks to the qgis job_layer_definition
        tree to extract all knowledge out
        of it. It is called from itself again for each level of group like elements
        which are found.

        Args:
            entity: The QGIS projects tree node which can be a QgsLayerTree, QgsLayerTreeGroup or
                QgsLayerTreeLayer.
            path: The path is a list of string which stores the information of the current
                tree path. This is
                used to construct a string for unifying job_layer_definition names by their
                tree path.
        """
        if isinstance(entity, QgsLayerTreeLayer):
            # this is a job_layer_definition, we can extract its information
            self.extract_save_layer(
                entity,
                path,
            )
        elif isinstance(entity, (QgsLayerTreeGroup, QgsLayerTree)):
            # these are "group like" elements, we need to step into them one level deeper.
            short_name = self.get_group_short_name(entity)
            if short_name != "":
                # '' is the root of the tree, we don't want it to be part of the path
                path = path + [short_name]
            self.extract_group(
                entity,
                path,
            )
            for child in entity.children():
                # we handle all the children of the group like thing.
                self.walk_qgis_project_tree(
                    child,
                    path,
                )
        else:
            self.qsl_config.warning(
                "This element was not expected while walking QGIS project tree: "
                f"{type(entity).__name__} at {'/'.join(path)}",
                code=ExportMessage.Code.TREE_NODE_UNSUPPORTED,
            )

    def extract_group(
        self,
        group: QgsLayerTreeGroup,
        path: list[str],
    ):
        """
        Collects data pertaining to a QGIS job_layer_definition tree group. Basically
        this translates a QgsLayerTreeGroup
        into a QGIS-Server-Light TreeGroup.

        Args:
            group: The group which is handled.
            path: The path is a list of string which stores the information of the current
                tree path. This is
                used to construct a string for unifying job_layer_definition names by
                their tree path.
        """
        children = []
        for child in group.children():
            if isinstance(child, QgsLayerTreeGroup):
                children.append(
                    self.create_unified_short_name(self.get_group_short_name(child), path)
                )
            else:
                children.append(child.layer().id())
        short_name = self.create_unified_short_name(self.get_group_short_name(group), path[:-1])
        self.qsl_tree.members.append(
            TreeGroup(
                id=short_name,
                name=short_name,
                children=children,
                is_checked=group.itemVisibilityChecked(),
                is_expanded=group.isExpanded(),
            )
        )
        self.qsl_datasets.group.append(
            Group(
                id=short_name,
                name=short_name,
                title=self.get_group_title(group),
                is_checked=group.itemVisibilityChecked(),
                is_expanded=group.isExpanded(),
            )
        )

    def extract_save_layer(
        self,
        child: QgsLayerTreeLayer,
        path: list[str],
        types_from_editor_widget: bool = False,
    ):
        """Save the given job_layer_definition to the output path."""
        layer = child.layer()
        is_checked = child.itemVisibilityChecked()
        layer_type = self.get_layer_type(layer)
        if layer_type is None:
            self.qsl_config.warning(
                f"Layer type {layer.type().name} of layer "
                f"{layer.title() or layer.name()!r} is not supported.",
                code=ExportMessage.Code.LAYER_TYPE_UNSUPPORTED,
                layer_id=layer.id(),
            )
            return

        self.rewrite_datasource_with_qgis3_compatible_uri(layer)
        if not self.is_layer_valid(layer):
            error_message = (
                layer.error().summary()
                or layer.dataProvider().error().summary()
                or f"Layer with name {layer.title() or layer.name()!r} is not valid."
            )
            self.qsl_config.error(
                error_message,
                code=ExportMessage.Code.LAYER_INVALID,
                layer_id=layer.id(),
            )
            raise self.build_export_failure()

        decoded = self.extract_datasource_dict(layer)
        short_name = self.short_name(self.get_layer_short_name(child), path)
        if layer.isSpatial():
            crs = self.create_qsl_crs_from_qgs_layer(layer)
            layer_extent = self.get_layer_extent(layer)
            if layer_extent is None:
                self.qsl_config.error(
                    "Could not determine an extent for layer",
                    code=ExportMessage.Code.LAYER_EXTENT_MISSING,
                    layer_id=layer.id(),
                )
                raise self.build_export_failure()
            bbox_wgs84 = self.create_qsl_bbox_from_qgis_rectangle_wgs84(
                self.qgis_project, layer, layer_extent
            )
            bbox = self.create_qsl_bbox_from_qgis_rectangle_extent(layer_extent)
            is_spatial = True
        else:
            crs = None
            bbox_wgs84 = None
            bbox = None
            is_spatial = False

        if layer_type == "vector":
            data_provider: QgsVectorDataProvider = layer.dataProvider()
            if data_provider.isValid() and data_provider.empty():
                self.qsl_config.warning(
                    "Vector layer is empty",
                    code=ExportMessage.Code.LAYER_EMPTY,
                    layer_id=layer.id(),
                )
            if layer.providerType().lower() == "ogr":
                source = DataSource(ogr=self.create_qsl_source_ogr(decoded))
            elif layer.providerType().lower() == "postgres":
                source = DataSource(postgres=self.create_qsl_source_postgresql(decoded))
            elif layer.providerType().lower() == "wfs":
                # TODO: Correctly implement source!
                source = WfsSource()
            else:
                self.qsl_config.warning(
                    f"Unknown provider type {layer.providerType().lower()} "
                    f"for vector job_layer_definition {layer.title() or layer.name()}",
                    code=ExportMessage.Code.LAYER_PROVIDER_UNSUPPORTED,
                    layer_id=layer.id(),
                )
                return
            qsl_vector_dataset_fields = self.create_qsl_fields_from_qgis_field(layer)
            self.qsl_datasets.vector.append(
                Vector(
                    name=short_name,
                    title=layer.title() or layer.name(),
                    styles=self.create_style_list(layer),
                    driver=layer.providerType(),
                    bbox_wgs84=bbox_wgs84,
                    fields=qsl_vector_dataset_fields,
                    source=source,
                    id=layer.id(),
                    crs=crs,
                    bbox=bbox,
                    minimum_scale=layer.minimumScale(),
                    maximum_scale=layer.maximumScale(),
                    geometry_type_simple=layer.geometryType().name,
                    geometry_type_wkb=layer.wkbType().name,
                    is_spatial=is_spatial,
                    is_checked=is_checked,
                    # Qgis server property WMSBackgroundLayer can only be set for raster layers
                    is_background=False,
                )
            )
        elif layer_type == "raster":
            if layer.providerType() == "gdal":
                source = DataSource(gdal=self.create_qsl_source_gdal(decoded))
            elif layer.providerType() == "wms":
                if "tileMatrixSet" in decoded:
                    source = DataSource(wmts=self.create_qsl_source_wmts(decoded))
                else:
                    if decoded.get("type") == "xyz":
                        source = DataSource(xyz=self.create_qsl_source_xyz(decoded))
                    else:
                        source = DataSource(wms=self.create_qsl_source_wms(decoded))
            elif layer.providerType() == "wcs":
                source = DataSource(wcs=self.create_qsl_source_wcs(decoded))
            else:
                self.qsl_config.warning(
                    f"Unknown provider type in raster layer: {layer.providerType().lower()}",
                    code=ExportMessage.Code.LAYER_PROVIDER_UNSUPPORTED,
                    layer_id=layer.id(),
                )
                return

            self.qsl_datasets.raster.append(
                Raster(
                    name=short_name,
                    title=layer.title() or layer.name(),
                    styles=self.create_style_list(layer),
                    driver=layer.providerType(),
                    bbox_wgs84=bbox_wgs84,
                    source=source,
                    id=layer.id(),
                    crs=crs,
                    bbox=bbox,
                    minimum_scale=layer.minimumScale(),
                    maximum_scale=layer.maximumScale(),
                    is_spatial=is_spatial,
                    is_checked=is_checked,
                    is_background=self.is_wms_background_layer(layer),
                )
            )

        elif layer_type == "custom":
            if layer.providerType().lower() in ["xyzvectortiles", "mbtilesvectortiles"]:
                source = DataSource(vector_tile=self.create_qsl_source_vector_tiles(decoded))
            else:
                # TODO: make this more configurable
                self.qsl_config.warning(
                    f"Unknown provider type: {layer.providerType().lower()} "
                    f"in layer with short_name {short_name}",
                    code=ExportMessage.Code.LAYER_PROVIDER_UNSUPPORTED,
                    layer_id=layer.id(),
                )
                return
            self.qsl_datasets.custom.append(
                Custom(
                    name=short_name,
                    title=layer.title() or layer.name(),
                    styles=self.create_style_list(layer),
                    driver=layer.providerType(),
                    bbox_wgs84=bbox_wgs84,
                    source=source,
                    id=layer.id(),
                    crs=crs,
                    bbox=bbox,
                    minimum_scale=layer.minimumScale(),
                    maximum_scale=layer.maximumScale(),
                    is_spatial=is_spatial,
                    is_checked=is_checked,
                    # Qgis server property WMSBackgroundLayer can only be set for raster layers
                    is_background=False,
                )
            )

    def short_name(self, short_name: str, path: list[str]) -> str:
        """
        Decides if to use the short name itself or the unified version by the tree path.

        Args:
            short_name: The short name either of the group or the job_layer_definition.
            path: The path is a list of string which stores the information of the current
                tree path. This is
                used to construct a string for unifying job_layer_definition names by
                their tree path.

        Returns:
            The short name itself or its unified tree path.
        """
        if self.unify_layer_names_by_group:
            return self.create_unified_short_name(short_name, path)
        else:
            return short_name

    def create_unified_short_name(self, short_name: str, path: list[str]):
        """
        Creates the unified short name, separated by the configured separator.

        Args:
            short_name: The short name either of the group or the job_layer_definition.
            path: The path is a list of string which stores the information of the current
                tree path. This is
                used to construct a string for unifying job_layer_definition names by
                their tree path.

        Returns:

        """
        short_name_parts = path + [short_name]
        return self.unify_layer_names_by_group_separator.join(short_name_parts)

    def rewrite_datasource_with_qgis3_compatible_uri(self, layer: QgsMapLayer):
        # QGIS 3 is inconsistent in how it encodes/decodes source URIs, whereas
        # QGIS 4 systematically percent-encodes reserved characters inside datasource values.
        # A project saved by QGIS >= 4 and read by a QGIS 3 build (QSL is based on
        # QGIS 3) therefore needs an unquote() pass to get clean values.
        if not Qgis.version().startswith("3."):
            return

        if self.version.majorVersion() >= 4:
            registry = QgsProviderRegistry.instance()
            original_uri = layer.source()
            qgis3_compatible_uri = registry.encodeUri(
                layer.providerType(),
                {
                    key: unquote(value) if isinstance(value, str) else value
                    for (key, value) in registry.decodeUri(
                        layer.providerType(), original_uri
                    ).items()
                },
            )
            logging.debug(
                f"Layer {layer.id()} datasource URI from QGIS 4 project is rewritten: "
                f"original={original_uri!r}, QGIS 3 compatible={qgis3_compatible_uri!r}"
            )
            layer.setDataSource(qgis3_compatible_uri)

    def extract_datasource_dict(self, layer: QgsMapLayer) -> dict:
        """
        Decodes a QGIS map job_layer_definition datasource into a dict and ensures that
        types are pythonic and pathes are
        clean for further usage.

        Args:
            layer: The job_layer_definition which the datasource should be extracted from.

        Returns:
            The decoded and cleaned datasource.
        """
        decoded = QgsProviderRegistry.instance().decodeUri(
            layer.providerType(), layer.dataProvider().dataSourceUri()
        )
        logging.debug(f"Layer source: {decoded}")
        for key in decoded:
            if str(decoded[key]) in ("None", "NULL"):
                decoded[key] = None
                continue
            if key == "path":
                # QGIS 3 returns url encoded paths, which leads to incorrect operations,
                # eg: ".%2Fdata%2Fhiroshima.mbtiles" instead of "./data/hiroshima.mbtiles"
                # For QGIS 4 projects, the value is expected to be decoded already.
                if self.version.majorVersion() <= 3:
                    decoded_path = unquote(decoded[key])
                else:
                    decoded_path = decoded[key]
                # Make path relative to the qgis_project
                decoded[key] = decoded_path.replace(f"{self.qgis_project.readPath('./')}/", "")
            else:
                decoded[key] = str(decoded[key])
        return decoded

    @staticmethod
    def create_qsl_field_from_qgis_field(
        field: QgsField,
        is_primary_key: bool,
        is_generated: bool = False,
    ) -> Field:
        attribute_type_xml = Exporter.obtain_simple_types_from_qgis_field_xml(field)
        (
            editor_widget_type,
            editor_widget_type_wfs,
            editor_widget_type_json,
            editor_widget_type_json_format,
        ) = Exporter.obtain_editor_widget_type_from_qgis_field(field)
        (
            attribute_type_json,
            attribute_type_json_format,
        ) = Exporter.obtain_simple_types_from_qgis_field_json(field)
        return Field(
            is_primary_key=is_primary_key,
            is_generated=is_generated,
            name=field.name(),
            type=field.typeName(),
            type_wfs=attribute_type_xml,
            type_oapif=attribute_type_json,
            type_oapif_format=attribute_type_json_format,
            alias=field.alias() or field.name().title(),
            comment=field.comment(),
            nullable=not is_primary_key and Exporter.obtain_nullable(field),
            length=Exporter.provide_field_length(field),
            precision=Exporter.provide_field_precision(field),
            editor_widget_type=editor_widget_type,
            editor_widget_type_wfs=editor_widget_type_wfs,
            editor_widget_type_oapif=editor_widget_type_json,
            editor_widget_type_oapif_format=editor_widget_type_json_format,
            editor_widget=Exporter.create_qsl_editor_widget(field.editorWidgetSetup()),
            constraints=Exporter.create_qsl_field_constraints(field),
        )

    @staticmethod
    def create_qsl_editor_widget(setup: QgsEditorWidgetSetup) -> EditorWidget | None:
        """
        Translates the configuration of the editor widgets which define value lists or
        domains. Layer and relation references are exported as they are, resolving
        them is left to the consumer!

        Args:
            setup: The editor widget setup of a field of an `QgsVectorLayer`.

        Returns:
            The editor widget configuration or None if the widget type is not exported.
        """
        editor_widget_type = setup.type()
        config = setup.config()
        if editor_widget_type == "ValueMap":
            return EditorWidget(value_map=Exporter.create_qsl_value_map(config))
        elif editor_widget_type == "ValueRelation":
            return EditorWidget(value_relation=Exporter.create_qsl_value_relation(config))
        elif editor_widget_type == "RelationReference":
            return EditorWidget(
                relation_reference=RelationReference(relation_id=config.get("Relation", ""))
            )
        elif editor_widget_type == "Range":
            return EditorWidget(range=Exporter.create_qsl_range(config))
        return None

    @staticmethod
    def create_qsl_value_map(config: dict) -> ValueMap:
        """
        Reads the value map as QGIS knows them (2 kinds): the current one, a list of single
        entry dicts, and the old one, a single dict. Both map description to key, the
        key `QgsValueMapFieldFormatter.NULL_VALUE` stands for NULL.

        Args:
            config: The editor widget configuration of a `ValueMap` widget.

        Returns:
            The value map in the order defined in QGIS.
        """
        value_map_config = config.get("map", [])
        if isinstance(value_map_config, dict):
            value_map_config = [value_map_config]
        value_map = ValueMap()
        for value_map_item in value_map_config:
            for description, key in value_map_item.items():
                if key == QgsValueMapFieldFormatter.NULL_VALUE:
                    value_map.null_representation = description
                else:
                    value_map.entries.append(ValueMapEntry(key=str(key), description=description))
        return value_map

    @staticmethod
    def create_qsl_value_relation(config: dict) -> ValueRelation:
        """Builder function to create the interface instance."""
        return ValueRelation(
            layer_id=config.get("Layer", ""),
            key_field=config.get("Key", ""),
            value_field=config.get("Value", ""),
            filter_expression=config.get("FilterExpression") or None,
            allow_multi=bool(config.get("AllowMulti", False)),
            order_by_value=bool(config.get("OrderByValue", False)),
        )

    @staticmethod
    def create_qsl_range(config: dict) -> Range:
        """Builder function to create the interface instance."""
        return Range(
            minimum=Exporter.provide_float(config.get("Min")),
            maximum=Exporter.provide_float(config.get("Max")),
            step=Exporter.provide_float(config.get("Step")),
        )

    @staticmethod
    def provide_float(value) -> float | None:
        """Just an internal helper"""
        if value is None:
            return None
        return float(value)

    @staticmethod
    def create_qsl_field_constraints(field: QgsField) -> FieldConstraints:
        """Builder function to create the interface instance."""
        field_constraints = field.constraints()
        constraints = field_constraints.constraints()
        return FieldConstraints(
            not_null=bool(constraints & QgsFieldConstraints.Constraint.ConstraintNotNull),
            unique=bool(constraints & QgsFieldConstraints.Constraint.ConstraintUnique),
            expression=field_constraints.constraintExpression() or None,
        )

    @staticmethod
    def create_qsl_relations(project: QgsProject) -> list[Relation]:
        """
        Translates the relations of the project. All relations are exported, also the
        ones whose layers are not part of the export.

        Args:
            project: The instantiated QGIS project.

        Returns:
            The relations of the project.
        """
        relations = []
        for relation in project.relationManager().relations().values():
            relations.append(
                Relation(
                    id=relation.id(),
                    name=relation.name(),
                    referencing_layer_id=relation.referencingLayerId(),
                    referenced_layer_id=relation.referencedLayerId(),
                    field_pairs=[
                        RelationFieldPair(
                            referencing_field=referencing_field,
                            referenced_field=referenced_field,
                        )
                        for referencing_field, referenced_field in relation.fieldPairs().items()
                    ],
                    strength=relation.strength().name,
                )
            )
        return relations

    @staticmethod
    def obtain_nullable(field: QgsField) -> bool:
        """

        Args:
            field: The field of an `QgsVectorLayer`.

        Returns:
            False if the field carries a NotNull constraint (possibly combined with
            others like Unique or Expression), True otherwise.
        """
        constraints = field.constraints().constraints()
        return not constraints & QgsFieldConstraints.Constraint.ConstraintNotNull

    @staticmethod
    def provide_field_length(field: QgsField) -> int | None:
        length = field.length()
        if length > 0:
            return length
        else:
            return None

    @staticmethod
    def provide_field_precision(field: QgsField) -> int | None:
        precision = field.precision()
        if precision > 0:
            return precision
        else:
            return None

    def create_qsl_fields_from_qgis_field(
        self,
        layer: QgsVectorLayer,
    ) -> list[Field]:
        fields = []
        provider = layer.dataProvider()
        pk_indexes = provider.pkAttributeIndexes()
        for field_index, field in enumerate(layer.fields().toList()):
            is_primary_key = field_index in pk_indexes
            qsl_field = self.create_qsl_field_from_qgis_field(
                field,
                is_primary_key,
                is_generated=is_primary_key and self.obtain_is_generated(provider, field_index),
            )
            if (
                qsl_field.editor_widget_type
                and qsl_field.editor_widget_type_wfs is None
                and qsl_field.editor_widget_type_oapif is None
                and qsl_field.editor_widget_type_oapif_format is None
            ):
                self.qsl_config.warning(
                    f"Editor widget type {qsl_field.editor_widget_type!r} for field "
                    f"{field.name()!r} was not handled as expected.",
                    code=ExportMessage.Code.FIELD_EDITOR_WIDGET_TYPE_UNSUPPORTED,
                    layer_id=layer.id(),
                )
            fields.append(qsl_field)
        return fields

    @staticmethod
    def obtain_is_generated(provider, field_index: int) -> bool:
        # the OGR provider (GeoPackage fid, ...) lets GDAL assign the identifier on insert,
        # other providers tell it with a default value, e.g. a sequence
        if provider.name() == "ogr":
            return True
        return bool(provider.defaultValueClause(field_index))

    @staticmethod
    def obtain_simple_types_from_qgis_field_xml(field: QgsField) -> str:
        """

        Args:
            field: The field of an `QgsVectorLayer`.

        Returns:
            Unified type name regarding
            [XSD spec](https://www.w3.org/TR/xmlschema11-2/#built-in-primitive-datatypes)
            IMPORTANT: If type is not matched within the function it will be `string` always!
        """
        attribute_type = field.type()
        if attribute_type == QMetaType.Type.Int:
            return "int"
        elif attribute_type == QMetaType.Type.UInt:
            return "unsignedInt"
        elif attribute_type == QMetaType.Type.LongLong:
            return "long"
        elif attribute_type == QMetaType.Type.ULongLong:
            return "unsignedLong"
        elif attribute_type == QMetaType.Type.Double:
            if field.length() > 0 and field.precision() == 0:
                return "integer"
            else:
                return "decimal"
        elif attribute_type == QMetaType.Type.Bool:
            return "boolean"
        elif attribute_type == QMetaType.Type.QDate:
            return "date"
        elif attribute_type == QMetaType.Type.QTime:
            return "time"
        elif attribute_type == QMetaType.Type.QDateTime:
            return "dateTime"
        else:
            return "string"

    @staticmethod
    def is_wms_background_layer(layer: QgsMapLayer) -> bool:
        return bool(layer.customProperty("WMSBackgroundLayer", False))

    @staticmethod
    def get_group_title(group: QgsLayerTreeGroup) -> str:
        if group.customProperty("wmsTitle"):
            return group.customProperty("wmsTitle")
        elif hasattr(group, "groupLayer"):  # noqa: SIM102
            # since QGIS 3.38
            if (
                group.groupLayer()
                and group.groupLayer().serverProperties()
                and group.groupLayer().serverProperties().title()
            ):
                return group.groupLayer().serverProperties().title()
        return group.name()

    @staticmethod
    def get_group_short_name(group: QgsLayerTreeGroup) -> str:
        if group.customProperty("wmsShortName"):
            return group.customProperty("wmsShortName")
        elif hasattr(group, "groupLayer"):  # noqa: SIM102
            # since QGIS 3.38
            if (
                group.groupLayer()
                and group.groupLayer().serverProperties()
                and group.groupLayer().serverProperties().shortName()
            ):
                return group.groupLayer().serverProperties().shortName()
        short_name = Exporter.sanitize_name(group.name(), lower=True)
        if short_name == "_":
            # this is the tree root, we return empty string here
            return ""
        return short_name

    @staticmethod
    def sanitize_name(raw: str, lower: bool = False) -> str:
        """
        Transforms an arbitrary string into a WMS/WFS and URL compatible short name for a
        job_layer_definition or group.

        Steps:
        1. Unicode‑NFD → ASCII‑transliteration (removes umlauts/diacritics).
        2. All chars, which are NOT [A‑Za‑z0‑9_.‑], will be replaced by '_' ersetzen.
        3. Reduce multiple underscore '_' to a single one.
        4. Remove leading '_', '.', '-'.
        5. If the string is empty OR does not start with a letter OR not start with '_',
           a leading '_' will be added.
        6. Optional all will be converted to lowercase (lower=True).
        """
        # 1. cleaning to ASCII
        ascii_str = unicodedata.normalize("NFKD", raw).encode("ascii", "ignore").decode()
        # 2. not allowed → '_'
        ascii_str = re.sub(r"[^A-Za-z0-9_.-]+", "_", ascii_str)
        # 3. remove multiple '_'
        ascii_str = re.sub(r"_+", "_", ascii_str)
        # 4. remove trailing chars
        ascii_str = ascii_str.strip("._-")
        # 5. ensure first char is correct (mainly xml stuff and URL)
        if not ascii_str or not re.match(r"[A-Za-z_]", ascii_str[0]):
            ascii_str = "_" + ascii_str
        # 6. Optional lowercase
        if lower:
            ascii_str = ascii_str.lower()
        return ascii_str

    @staticmethod
    def obtain_editor_widget_type_from_qgis_field(
        field: QgsField,
    ) -> tuple[str, str, str, str] | tuple[str, None, None, None]:
        """
        We simply mimikri [QGIS Server here](https://github.com/qgis/QGIS/blob/de98779ebb117547364ec4cff433f062374e84a3/src/server/services/wfs/qgswfsdescribefeaturetype.cpp#L153-L192)

        TODO: This could be improved alot! Maybe we can also backport that to QGIS core some day?

        Args:
            field: The field of an `QgsVectorLayer`.

        Returns:
            Unified type name regarding
            [XSD spec](https://www.w3.org/TR/xmlschema11-2/#built-in-primitive-datatypes)
        """
        attribute_type = field.type()
        setup = field.editorWidgetSetup()
        config = setup.config()
        editor_widget_type = setup.type()
        if editor_widget_type == "DateTime":
            field_format = config.get(
                "field_format", QgsDateTimeFieldFormatter.defaultFormat(attribute_type)
            )
            if field_format == QgsDateTimeFieldFormatter.TIME_FORMAT:
                return editor_widget_type, "time", "string", "time"
            elif field_format == QgsDateTimeFieldFormatter.DATE_FORMAT:
                return editor_widget_type, "date", "string", "date"
            elif (
                field_format == QgsDateTimeFieldFormatter.DATETIME_FORMAT
                or field_format == QgsDateTimeFieldFormatter.QT_ISO_FORMAT
            ):
                return editor_widget_type, "dateTime", "string", "date-time"
        elif editor_widget_type == "Range":
            if config.get("Precision"):
                config_precision = int(config["Precision"])
                if config_precision != field.precision():
                    if config_precision == 0:
                        return editor_widget_type, "integer", "integer", "int64"
                    else:
                        return editor_widget_type, "decimal", "number", "double"

        return editor_widget_type, None, None, None

    @staticmethod
    def obtain_simple_types_from_qgis_field_json(
        field: QgsField,
    ) -> tuple[str, str] | tuple[str, None]:
        """
        Delivers the type match for json based on the field QgsField type.

        Args:
            field: The field of an `QgsVectorLayer`.

        Returns:
            Unified type name and format in a tuple.
        """
        attribute_type = field.type()
        if attribute_type == QMetaType.Type.Int:
            return "integer", None
        elif attribute_type == QMetaType.Type.UInt:
            return "integer", "uint32"
        elif attribute_type == QMetaType.Type.LongLong:
            return "integer", "int64"
        elif attribute_type == QMetaType.Type.ULongLong:
            return "integer", "uint64"
        elif attribute_type == QMetaType.Type.Double:
            return "number", "double"
        elif attribute_type == QMetaType.Type.Float:
            return "number", "float"
        elif attribute_type == QMetaType.Type.Bool:
            return "boolean", None
        elif attribute_type == QMetaType.Type.QDate:
            return "string", "date"
        elif attribute_type == QMetaType.Type.QTime:
            return "string", "time"
        elif attribute_type == QMetaType.Type.QDateTime:
            return "string", "date-time"
        else:
            # we handle all unknown types as string. Since its for JavaScript, this should be safe.
            return "string", None

    @staticmethod
    def create_qsl_source_wms(datasource: dict) -> WmsSource:
        return WmsSource.from_qgis_decoded_uri(datasource)

    @staticmethod
    def create_qsl_source_vector_tiles(datasource: dict) -> VectorTileSource:
        return VectorTileSource.from_qgis_decoded_uri(datasource)

    @staticmethod
    def create_qsl_source_xyz(datasource: dict) -> XYZSource:
        return XYZSource.from_qgis_decoded_uri(datasource)

    @staticmethod
    def create_qsl_source_wmts(datasource: dict) -> WmtsSource:
        return WmtsSource.from_qgis_decoded_uri(datasource)

    @staticmethod
    def create_qsl_source_wcs(datasource: dict) -> WcsSource:
        return WcsSource.from_qgis_decoded_uri(datasource)

    @staticmethod
    def create_qsl_source_gdal(datasource: dict) -> GdalSource:
        return GdalSource.from_qgis_decoded_uri(datasource)

    @staticmethod
    def create_qsl_source_ogr(datasource: dict) -> OgrSource:
        return OgrSource.from_qgis_decoded_uri(datasource)

    @staticmethod
    def create_qsl_source_postgresql(datasource: dict) -> PostgresSource:
        """
        Creates the QSL postgres source from the datasource as it is stored in the
        QGIS project. A referenced pg_service is NOT resolved: connection info and
        credentials stay in the pg_service.conf (PGSERVICEFILE) and are resolved by
        libpq at connection time on the consumer side.

        Args:
            datasource: The decoded and cleaned datasource of the layer. Its sslmode,
                if any, is the stringified QGIS int (e.g. "3" for require).

        Returns:
            The QSL postgres source.
        """
        postgres_source = PostgresSource.from_qgis_decoded_uri(datasource)
        if postgres_source.sslmode is not None:
            postgres_source.ssl_mode_text = Exporter.sslmode_int_to_str(postgres_source.sslmode)
        return postgres_source

    @staticmethod
    def sslmode_int_to_str(ssl_mode: int) -> str:
        """
        Mapper to map ssl modes from QGIS int to plain postgres.

        Args:
            ssl_mode: The ssl mode of the datasource as a int value matching one of
                https://qgis.org/pyqgis/3.44/core/QgsDataSourceUri.html#qgis.core.QgsDataSourceUri.SslMode

        Returns:
            The string representation of the ssl mode as it is used by postgres connections.
        """
        return QgsDataSourceUri.encodeSslMode(int(ssl_mode))

    @staticmethod
    def create_qsl_crs_from_qgs_layer(layer: QgsMapLayer) -> Crs:
        """
        Translates the QGIS job_layer_definition crs information into an instance of the
        QGIS-Server-Light interface Crs
        instance.

        Args:
            layer: The job_layer_definition to take the crs information from.

        Returns:
            The instance of the QSL interface Crs.
        """
        crs = layer.dataProvider().crs()
        if not crs.isValid():
            # some providers (e.g. PostGIS geometry columns without SRID) report no CRS,
            # the project CRS of the layer is the one the data is shown in
            crs = layer.crs()
        return create_qsl_crs(crs)

    @staticmethod
    def get_layer_short_name(layer: QgsLayerTreeLayer) -> str:
        """
        This method determines which name is used as the short name of the job_layer_definition.

        Args:
            layer: The job_layer_definition which the short name should be derived from.

        Returns:
            The short name.
        """
        if layer.layer().shortName():
            return layer.layer().shortName()
        elif (
            hasattr(layer.layer(), "serverProperties")
            and layer.layer().serverProperties().shortName()
        ):
            return layer.layer().serverProperties().shortName()
        return layer.layer().id()

    @staticmethod
    def make_wgs84_geom_transform(project, layer) -> QgsCoordinateTransform:
        """
        Creates a QgisCoordinateTransform context to transform a job_layer_definition
        to EPSG:4326 aka wgs84.

        Args:
            project: The QGIS project instance.
            layer: The job_layer_definition which's extent should be reprojected.

        Returns:
            The QGIS transformation context.
        """
        source_crs = layer.crs()
        epsg_4326 = QgsCoordinateReferenceSystem("EPSG:4326")
        return QgsCoordinateTransform(source_crs, epsg_4326, project)

    def create_qsl_bbox_from_qgis_rectangle_wgs84(
        self, project: QgsProject, layer: QgsMapLayer, extent: QgsRectangle
    ) -> BBox:
        """
        Reprojects the job_layer_definition's extent using WGS84.

        Args:
            project: The QGIS project instance for projection context.
            layer: The job_layer_definition which for the projection context.
            extent: The extent which will be reprojected.

        Returns:
            The QSL bbox reprojected to WGS84.
        """
        try:
            transformation_context = Exporter.make_wgs84_geom_transform(project, layer)
            reprojected_extent = transformation_context.transform(extent)
        except QgsCsException as err:
            self.qsl_config.error(
                f"Layer extent could not be reprojected from "
                f"{layer.crs().authid()} to EPSG:4326: {err}",
                code=ExportMessage.Code.LAYER_EXTENT_REPROJECTION_FAILED,
                layer_id=layer.id(),
            )
            raise self.build_export_failure() from err
        return self.create_qsl_bbox_from_qgis_rectangle_extent(reprojected_extent)

    @staticmethod
    def create_qsl_bbox_from_qgis_rectangle_extent(extent: QgsRectangle) -> BBox:
        return BBox(
            x_min=extent.xMinimum(),
            x_max=extent.xMaximum(),
            y_min=extent.yMinimum(),
            y_max=extent.yMaximum(),
        )

    @staticmethod
    def get_project_extent(project: QgsProject) -> QgsReferencedRectangle | None:
        """WMS advertised extent, else View Settings full extent, else project CRS area of use."""
        wms = QgsServerProjectUtils.wmsExtent(project)
        if not wms.isNull():
            return QgsReferencedRectangle(wms, project.crs())

        full = project.viewSettings().fullExtent()
        if not full.isNull():
            return full

        crs_bounds = project.crs().bounds()  # area of use, always in EPSG:4326
        if not crs_bounds.isNull():
            return QgsReferencedRectangle(crs_bounds, QgsCoordinateReferenceSystem("EPSG:4326"))

        return None

    def get_layer_extent(self, layer: QgsMapLayer) -> QgsReferencedRectangle | None:
        """Layer extent in the layer CRS, else the project fallback reprojected into it."""
        ext = layer.extent()
        if not ext.isNull() and ext.isFinite():
            return QgsReferencedRectangle(ext, layer.crs())

        project = layer.project()
        fallback = self.get_project_extent(project) if project else None
        if fallback is None:
            return None

        ct = QgsCoordinateTransform(fallback.crs(), layer.crs(), project.transformContext())
        try:
            transformed = ct.transformBoundingBox(fallback)
        except QgsCsException as err:
            self.qsl_config.error(
                "Layer extent could not be determined by the data provider and the "
                f"project fallback extent could not be reprojected from "
                f"{fallback.crs().authid()} to {layer.crs().authid()}: {err}",
                code=ExportMessage.Code.LAYER_EXTENT_REPROJECTION_FAILED,
                layer_id=layer.id(),
            )
            raise self.build_export_failure() from err

        self.qsl_config.warning(
            "Layer extent could not be determined by the data provider "
            "and is derived from the project instead.",
            code=ExportMessage.Code.LAYER_EXTENT_FROM_PROJECT,
            layer_id=layer.id(),
        )
        return QgsReferencedRectangle(transformed, layer.crs())

    @staticmethod
    def get_layer_type(layer: QgsMapLayer) -> str | None:
        """
        Gets the type of the given Qgis job_layer_definition as a string if the type is supported.
        This is to flatten the
        understanding of layers from qgis into something we can handle.

        Args:
            layer: The job_layer_definition to decide the type for.

        Returns:
            "raster", "vector" or "custom" if a job_layer_definition matched and None otherwise.
        """
        if isinstance(layer, QgsRasterLayer):
            return "raster"
        elif isinstance(layer, QgsVectorLayer):
            return "vector"
        elif isinstance(
            layer, (QgsVectorTileLayer, QgsTiledSceneLayer, QgsPointCloudLayer, QgsMeshLayer)
        ):
            return "custom"
        return None

    @staticmethod
    def is_layer_valid(layer: QgsMapLayer) -> bool:
        if not layer.isValid():
            logging.debug(f"Layer error: {layer.error().summary()}")
            return False
        if not layer.dataProvider().isValid():
            logging.debug(f"Data provider error: {layer.dataProvider().error().summary()}")
            return False
        return True

    @staticmethod
    def open_qgis_project(path_to_project: str) -> QgsProject:
        """


        Args:
            path_to_project: The absolute path on the file system where the project
            can be read from.

        Returns:
            The opened project (read).
        """
        project = QgsProject.instance()
        project.read(path_to_project)
        return project

    @staticmethod
    def prepare_qgis_project_name(project: QgsProject) -> str:
        """


        Args:
            project: The instantiated QGIS project.

        Returns:
            Project name
        """
        return project.title() or project.baseName()

    @staticmethod
    def extract_metadata(project: QgsProject) -> MetaData:
        """
        Creates a QSL interface instance for metadate pulled out of the QGIS project.

        Args:
            project: The instantiated QGIS project.

        Returns:
            The metadata interface instance.
        """
        _meta = project.metadata()
        wms_entries = Exporter.get_project_server_entries(project, "wms")
        service = Service(**dict(sorted({**wms_entries}.items())))
        return MetaData(
            service=service,
            author=_meta.author(),
            categories=_meta.categories(),
            creationDateTime=_meta.creationDateTime().toPyDateTime().isoformat(),
            language=_meta.language(),
            links=[link.url for link in _meta.links()],
        )

    @staticmethod
    def get_project_server_entries(project, scope_or_scopes: str | list) -> dict:
        """
        Gets values from the fields displayed in QGIS under Project > Properties > Server.
        Returns a Dictionary holding all pairs of <key, value> found at the corresponding scopes.
        Example:
            given   scope_or_scope = "wms" (or: ["wms"])
            returns { <wms_key1>: <wms_key1_value>, <wms_key2>: <wms_key2_value> ... }
        For now the implementation supports only WMS fields but can be easily expanded by
        adding <key/values> to the Dictionary below.
        """
        supported_scopes = {
            "wms": {
                "scopes": [
                    ("WMSContactOrganization", "contact_organization"),
                    ("WMSContactMail", "contact_mail"),
                    ("WMSContactPerson", "contact_person"),
                    ("WMSContactPhone", "contact_phone"),
                    ("WMSContactPosition", "contact_position"),
                    ("WMSFees", "fees"),
                    ("WMSKeywordList", "keyword_list"),
                    ("WMSOnlineResource", "online_resource"),
                    ("WMSServiceAbstract", "service_abstract"),
                    ("WMSServiceTitle", "service_title"),
                    ("WMSUrl", "resource_url"),
                ],
                "keys": ["/"],
            }
        }

        scopes = [scope_or_scopes] if isinstance(scope_or_scopes, str) else scope_or_scopes

        for scope in scopes:
            if scope not in supported_scopes:
                supported = ", ".join(supported_scopes.keys())
                error_detail = (
                    f"This scope is not supported: {scope}. Supported scopes: {supported}"
                )
                raise ValueError(error_detail)

            scope_entries = supported_scopes[scope]["scopes"]
            key_entries = supported_scopes[scope]["keys"]
            to_collect = zip_longest(scope_entries, key_entries, fillvalue=key_entries[0])

            def collect(acc, pair):
                scope, key = pair
                qgis_scope_name, our_scope_name = scope

                if "list" in qgis_scope_name.lower():
                    # PyQGIS sometimes violates Liskov's substitution principle so naming
                    # tricks needed
                    list_as_text = ", ".join(project.readListEntry(qgis_scope_name, key)[0])
                    acc.append((our_scope_name, list_as_text))
                else:
                    acc.append(
                        (
                            our_scope_name,
                            project.readEntry(qgis_scope_name, key)[0],
                        )
                    )

                return acc

            return dict(reduce(collect, to_collect, []))

    @staticmethod
    def create_style_list(qgs_layer: QgsMapLayer) -> list[Style]:
        style_names = qgs_layer.styleManager().styles()
        style_list = []
        for style_name in style_names:
            style_doc = QDomDocument()
            qgs_layer.styleManager().setCurrentStyle(style_name)
            qgs_layer.exportNamedStyle(style_doc)
            style_list.append(
                Style(
                    name=style_name,
                    definition=urlsafe_b64encode(zlib.compress(style_doc.toByteArray())).decode(),
                )
            )
        return style_list

    def build_export_failure(self):
        return ExportFailure(
            project=self.qsl_config.project,
            exporter=self.qsl_config.exporter,
            messages=self.qsl_config.messages,
        )
name = self.prepare_qgis_project_name(self.qgis_project) instance-attribute
path = qgis_project_path instance-attribute
qgis_project = self.open_qgis_project(qgis_project_path) instance-attribute
qgis_project_tree_root = self.qgis_project.layerTreeRoot() instance-attribute
qsl_config = Config(exporter=(ExporterMeta(qgis_version=(Qgis.version()))), project=(self.qsl_project), meta_data=(self.qsl_project_metadata), tree=(self.qsl_tree), datasets=(self.qsl_datasets)) instance-attribute
qsl_datasets = Datasets() instance-attribute
qsl_project = Project(name=(self.name), version=(self.version.text())) instance-attribute
qsl_project_metadata = self.extract_metadata(self.qgis_project) instance-attribute
qsl_tree = Tree() instance-attribute
unify_layer_names_by_group = unify_layer_names_by_group instance-attribute
unify_layer_names_by_group_separator = unify_layer_names_by_group_separator instance-attribute
version = self.qgis_project.lastSaveVersion() instance-attribute
__init__(qgis_project_path: str, unify_layer_names_by_group=False, unify_layer_names_by_group_separator='.')
Source code in src/qgis_server_light/exporter/extract.py
 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
def __init__(
    self,
    qgis_project_path: str,
    unify_layer_names_by_group=False,
    unify_layer_names_by_group_separator=".",
):
    self.unify_layer_names_by_group_separator = unify_layer_names_by_group_separator
    self.path = qgis_project_path
    self.unify_layer_names_by_group = unify_layer_names_by_group

    # prepare QGIS instances
    self.qgis_project = self.open_qgis_project(qgis_project_path)
    self.qgis_project_tree_root = self.qgis_project.layerTreeRoot()
    self.name = self.prepare_qgis_project_name(self.qgis_project)
    self.version = self.qgis_project.lastSaveVersion()

    # prepare QSL interface instances
    self.qsl_tree = Tree()
    self.qsl_datasets = Datasets()
    self.qsl_project = Project(name=self.name, version=self.version.text())
    self.qsl_project_metadata = self.extract_metadata(self.qgis_project)
    self.qsl_config = Config(
        exporter=ExporterMeta(qgis_version=Qgis.version()),
        project=self.qsl_project,
        meta_data=self.qsl_project_metadata,
        tree=self.qsl_tree,
        datasets=self.qsl_datasets,
    )
build_export_failure()
Source code in src/qgis_server_light/exporter/extract.py
1279
1280
1281
1282
1283
1284
def build_export_failure(self):
    return ExportFailure(
        project=self.qsl_config.project,
        exporter=self.qsl_config.exporter,
        messages=self.qsl_config.messages,
    )
create_qsl_bbox_from_qgis_rectangle_extent(extent: QgsRectangle) -> BBox staticmethod
Source code in src/qgis_server_light/exporter/extract.py
1055
1056
1057
1058
1059
1060
1061
1062
@staticmethod
def create_qsl_bbox_from_qgis_rectangle_extent(extent: QgsRectangle) -> BBox:
    return BBox(
        x_min=extent.xMinimum(),
        x_max=extent.xMaximum(),
        y_min=extent.yMinimum(),
        y_max=extent.yMaximum(),
    )
create_qsl_bbox_from_qgis_rectangle_wgs84(project: QgsProject, layer: QgsMapLayer, extent: QgsRectangle) -> BBox

Reprojects the job_layer_definition's extent using WGS84.

Parameters:

  • project (QgsProject) –

    The QGIS project instance for projection context.

  • layer (QgsMapLayer) –

    The job_layer_definition which for the projection context.

  • extent (QgsRectangle) –

    The extent which will be reprojected.

Returns:

  • BBox –

    The QSL bbox reprojected to WGS84.

Source code in src/qgis_server_light/exporter/extract.py
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
def create_qsl_bbox_from_qgis_rectangle_wgs84(
    self, project: QgsProject, layer: QgsMapLayer, extent: QgsRectangle
) -> BBox:
    """
    Reprojects the job_layer_definition's extent using WGS84.

    Args:
        project: The QGIS project instance for projection context.
        layer: The job_layer_definition which for the projection context.
        extent: The extent which will be reprojected.

    Returns:
        The QSL bbox reprojected to WGS84.
    """
    try:
        transformation_context = Exporter.make_wgs84_geom_transform(project, layer)
        reprojected_extent = transformation_context.transform(extent)
    except QgsCsException as err:
        self.qsl_config.error(
            f"Layer extent could not be reprojected from "
            f"{layer.crs().authid()} to EPSG:4326: {err}",
            code=ExportMessage.Code.LAYER_EXTENT_REPROJECTION_FAILED,
            layer_id=layer.id(),
        )
        raise self.build_export_failure() from err
    return self.create_qsl_bbox_from_qgis_rectangle_extent(reprojected_extent)
create_qsl_crs_from_qgs_layer(layer: QgsMapLayer) -> Crs staticmethod

Translates the QGIS job_layer_definition crs information into an instance of the QGIS-Server-Light interface Crs instance.

Parameters:

  • layer (QgsMapLayer) –

    The job_layer_definition to take the crs information from.

Returns:

  • Crs –

    The instance of the QSL interface Crs.

Source code in src/qgis_server_light/exporter/extract.py
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
@staticmethod
def create_qsl_crs_from_qgs_layer(layer: QgsMapLayer) -> Crs:
    """
    Translates the QGIS job_layer_definition crs information into an instance of the
    QGIS-Server-Light interface Crs
    instance.

    Args:
        layer: The job_layer_definition to take the crs information from.

    Returns:
        The instance of the QSL interface Crs.
    """
    crs = layer.dataProvider().crs()
    if not crs.isValid():
        # some providers (e.g. PostGIS geometry columns without SRID) report no CRS,
        # the project CRS of the layer is the one the data is shown in
        crs = layer.crs()
    return create_qsl_crs(crs)
create_qsl_editor_widget(setup: QgsEditorWidgetSetup) -> EditorWidget | None staticmethod

Translates the configuration of the editor widgets which define value lists or domains. Layer and relation references are exported as they are, resolving them is left to the consumer!

Parameters:

  • setup (QgsEditorWidgetSetup) –

    The editor widget setup of a field of an QgsVectorLayer.

Returns:

  • EditorWidget | None –

    The editor widget configuration or None if the widget type is not exported.

Source code in src/qgis_server_light/exporter/extract.py
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
@staticmethod
def create_qsl_editor_widget(setup: QgsEditorWidgetSetup) -> EditorWidget | None:
    """
    Translates the configuration of the editor widgets which define value lists or
    domains. Layer and relation references are exported as they are, resolving
    them is left to the consumer!

    Args:
        setup: The editor widget setup of a field of an `QgsVectorLayer`.

    Returns:
        The editor widget configuration or None if the widget type is not exported.
    """
    editor_widget_type = setup.type()
    config = setup.config()
    if editor_widget_type == "ValueMap":
        return EditorWidget(value_map=Exporter.create_qsl_value_map(config))
    elif editor_widget_type == "ValueRelation":
        return EditorWidget(value_relation=Exporter.create_qsl_value_relation(config))
    elif editor_widget_type == "RelationReference":
        return EditorWidget(
            relation_reference=RelationReference(relation_id=config.get("Relation", ""))
        )
    elif editor_widget_type == "Range":
        return EditorWidget(range=Exporter.create_qsl_range(config))
    return None
create_qsl_field_constraints(field: QgsField) -> FieldConstraints staticmethod

Builder function to create the interface instance.

Source code in src/qgis_server_light/exporter/extract.py
613
614
615
616
617
618
619
620
621
622
@staticmethod
def create_qsl_field_constraints(field: QgsField) -> FieldConstraints:
    """Builder function to create the interface instance."""
    field_constraints = field.constraints()
    constraints = field_constraints.constraints()
    return FieldConstraints(
        not_null=bool(constraints & QgsFieldConstraints.Constraint.ConstraintNotNull),
        unique=bool(constraints & QgsFieldConstraints.Constraint.ConstraintUnique),
        expression=field_constraints.constraintExpression() or None,
    )
create_qsl_field_from_qgis_field(field: QgsField, is_primary_key: bool, is_generated: bool = False) -> Field staticmethod
Source code in src/qgis_server_light/exporter/extract.py
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
@staticmethod
def create_qsl_field_from_qgis_field(
    field: QgsField,
    is_primary_key: bool,
    is_generated: bool = False,
) -> Field:
    attribute_type_xml = Exporter.obtain_simple_types_from_qgis_field_xml(field)
    (
        editor_widget_type,
        editor_widget_type_wfs,
        editor_widget_type_json,
        editor_widget_type_json_format,
    ) = Exporter.obtain_editor_widget_type_from_qgis_field(field)
    (
        attribute_type_json,
        attribute_type_json_format,
    ) = Exporter.obtain_simple_types_from_qgis_field_json(field)
    return Field(
        is_primary_key=is_primary_key,
        is_generated=is_generated,
        name=field.name(),
        type=field.typeName(),
        type_wfs=attribute_type_xml,
        type_oapif=attribute_type_json,
        type_oapif_format=attribute_type_json_format,
        alias=field.alias() or field.name().title(),
        comment=field.comment(),
        nullable=not is_primary_key and Exporter.obtain_nullable(field),
        length=Exporter.provide_field_length(field),
        precision=Exporter.provide_field_precision(field),
        editor_widget_type=editor_widget_type,
        editor_widget_type_wfs=editor_widget_type_wfs,
        editor_widget_type_oapif=editor_widget_type_json,
        editor_widget_type_oapif_format=editor_widget_type_json_format,
        editor_widget=Exporter.create_qsl_editor_widget(field.editorWidgetSetup()),
        constraints=Exporter.create_qsl_field_constraints(field),
    )
create_qsl_fields_from_qgis_field(layer: QgsVectorLayer) -> list[Field]
Source code in src/qgis_server_light/exporter/extract.py
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
def create_qsl_fields_from_qgis_field(
    self,
    layer: QgsVectorLayer,
) -> list[Field]:
    fields = []
    provider = layer.dataProvider()
    pk_indexes = provider.pkAttributeIndexes()
    for field_index, field in enumerate(layer.fields().toList()):
        is_primary_key = field_index in pk_indexes
        qsl_field = self.create_qsl_field_from_qgis_field(
            field,
            is_primary_key,
            is_generated=is_primary_key and self.obtain_is_generated(provider, field_index),
        )
        if (
            qsl_field.editor_widget_type
            and qsl_field.editor_widget_type_wfs is None
            and qsl_field.editor_widget_type_oapif is None
            and qsl_field.editor_widget_type_oapif_format is None
        ):
            self.qsl_config.warning(
                f"Editor widget type {qsl_field.editor_widget_type!r} for field "
                f"{field.name()!r} was not handled as expected.",
                code=ExportMessage.Code.FIELD_EDITOR_WIDGET_TYPE_UNSUPPORTED,
                layer_id=layer.id(),
            )
        fields.append(qsl_field)
    return fields
create_qsl_range(config: dict) -> Range staticmethod

Builder function to create the interface instance.

Source code in src/qgis_server_light/exporter/extract.py
597
598
599
600
601
602
603
604
@staticmethod
def create_qsl_range(config: dict) -> Range:
    """Builder function to create the interface instance."""
    return Range(
        minimum=Exporter.provide_float(config.get("Min")),
        maximum=Exporter.provide_float(config.get("Max")),
        step=Exporter.provide_float(config.get("Step")),
    )
create_qsl_relations(project: QgsProject) -> list[Relation] staticmethod

Translates the relations of the project. All relations are exported, also the ones whose layers are not part of the export.

Parameters:

  • project (QgsProject) –

    The instantiated QGIS project.

Returns:

  • list[Relation] –

    The relations of the project.

Source code in src/qgis_server_light/exporter/extract.py
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
@staticmethod
def create_qsl_relations(project: QgsProject) -> list[Relation]:
    """
    Translates the relations of the project. All relations are exported, also the
    ones whose layers are not part of the export.

    Args:
        project: The instantiated QGIS project.

    Returns:
        The relations of the project.
    """
    relations = []
    for relation in project.relationManager().relations().values():
        relations.append(
            Relation(
                id=relation.id(),
                name=relation.name(),
                referencing_layer_id=relation.referencingLayerId(),
                referenced_layer_id=relation.referencedLayerId(),
                field_pairs=[
                    RelationFieldPair(
                        referencing_field=referencing_field,
                        referenced_field=referenced_field,
                    )
                    for referencing_field, referenced_field in relation.fieldPairs().items()
                ],
                strength=relation.strength().name,
            )
        )
    return relations
create_qsl_source_gdal(datasource: dict) -> GdalSource staticmethod
Source code in src/qgis_server_light/exporter/extract.py
929
930
931
@staticmethod
def create_qsl_source_gdal(datasource: dict) -> GdalSource:
    return GdalSource.from_qgis_decoded_uri(datasource)
create_qsl_source_ogr(datasource: dict) -> OgrSource staticmethod
Source code in src/qgis_server_light/exporter/extract.py
933
934
935
@staticmethod
def create_qsl_source_ogr(datasource: dict) -> OgrSource:
    return OgrSource.from_qgis_decoded_uri(datasource)
create_qsl_source_postgresql(datasource: dict) -> PostgresSource staticmethod

Creates the QSL postgres source from the datasource as it is stored in the QGIS project. A referenced pg_service is NOT resolved: connection info and credentials stay in the pg_service.conf (PGSERVICEFILE) and are resolved by libpq at connection time on the consumer side.

Parameters:

  • datasource (dict) –

    The decoded and cleaned datasource of the layer. Its sslmode, if any, is the stringified QGIS int (e.g. "3" for require).

Returns:

Source code in src/qgis_server_light/exporter/extract.py
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
@staticmethod
def create_qsl_source_postgresql(datasource: dict) -> PostgresSource:
    """
    Creates the QSL postgres source from the datasource as it is stored in the
    QGIS project. A referenced pg_service is NOT resolved: connection info and
    credentials stay in the pg_service.conf (PGSERVICEFILE) and are resolved by
    libpq at connection time on the consumer side.

    Args:
        datasource: The decoded and cleaned datasource of the layer. Its sslmode,
            if any, is the stringified QGIS int (e.g. "3" for require).

    Returns:
        The QSL postgres source.
    """
    postgres_source = PostgresSource.from_qgis_decoded_uri(datasource)
    if postgres_source.sslmode is not None:
        postgres_source.ssl_mode_text = Exporter.sslmode_int_to_str(postgres_source.sslmode)
    return postgres_source
create_qsl_source_vector_tiles(datasource: dict) -> VectorTileSource staticmethod
Source code in src/qgis_server_light/exporter/extract.py
913
914
915
@staticmethod
def create_qsl_source_vector_tiles(datasource: dict) -> VectorTileSource:
    return VectorTileSource.from_qgis_decoded_uri(datasource)
create_qsl_source_wcs(datasource: dict) -> WcsSource staticmethod
Source code in src/qgis_server_light/exporter/extract.py
925
926
927
@staticmethod
def create_qsl_source_wcs(datasource: dict) -> WcsSource:
    return WcsSource.from_qgis_decoded_uri(datasource)
create_qsl_source_wms(datasource: dict) -> WmsSource staticmethod
Source code in src/qgis_server_light/exporter/extract.py
909
910
911
@staticmethod
def create_qsl_source_wms(datasource: dict) -> WmsSource:
    return WmsSource.from_qgis_decoded_uri(datasource)
create_qsl_source_wmts(datasource: dict) -> WmtsSource staticmethod
Source code in src/qgis_server_light/exporter/extract.py
921
922
923
@staticmethod
def create_qsl_source_wmts(datasource: dict) -> WmtsSource:
    return WmtsSource.from_qgis_decoded_uri(datasource)
create_qsl_source_xyz(datasource: dict) -> XYZSource staticmethod
Source code in src/qgis_server_light/exporter/extract.py
917
918
919
@staticmethod
def create_qsl_source_xyz(datasource: dict) -> XYZSource:
    return XYZSource.from_qgis_decoded_uri(datasource)
create_qsl_value_map(config: dict) -> ValueMap staticmethod

Reads the value map as QGIS knows them (2 kinds): the current one, a list of single entry dicts, and the old one, a single dict. Both map description to key, the key QgsValueMapFieldFormatter.NULL_VALUE stands for NULL.

Parameters:

  • config (dict) –

    The editor widget configuration of a ValueMap widget.

Returns:

  • ValueMap –

    The value map in the order defined in QGIS.

Source code in src/qgis_server_light/exporter/extract.py
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@staticmethod
def create_qsl_value_map(config: dict) -> ValueMap:
    """
    Reads the value map as QGIS knows them (2 kinds): the current one, a list of single
    entry dicts, and the old one, a single dict. Both map description to key, the
    key `QgsValueMapFieldFormatter.NULL_VALUE` stands for NULL.

    Args:
        config: The editor widget configuration of a `ValueMap` widget.

    Returns:
        The value map in the order defined in QGIS.
    """
    value_map_config = config.get("map", [])
    if isinstance(value_map_config, dict):
        value_map_config = [value_map_config]
    value_map = ValueMap()
    for value_map_item in value_map_config:
        for description, key in value_map_item.items():
            if key == QgsValueMapFieldFormatter.NULL_VALUE:
                value_map.null_representation = description
            else:
                value_map.entries.append(ValueMapEntry(key=str(key), description=description))
    return value_map
create_qsl_value_relation(config: dict) -> ValueRelation staticmethod

Builder function to create the interface instance.

Source code in src/qgis_server_light/exporter/extract.py
585
586
587
588
589
590
591
592
593
594
595
@staticmethod
def create_qsl_value_relation(config: dict) -> ValueRelation:
    """Builder function to create the interface instance."""
    return ValueRelation(
        layer_id=config.get("Layer", ""),
        key_field=config.get("Key", ""),
        value_field=config.get("Value", ""),
        filter_expression=config.get("FilterExpression") or None,
        allow_multi=bool(config.get("AllowMulti", False)),
        order_by_value=bool(config.get("OrderByValue", False)),
    )
create_style_list(qgs_layer: QgsMapLayer) -> list[Style] staticmethod
Source code in src/qgis_server_light/exporter/extract.py
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
@staticmethod
def create_style_list(qgs_layer: QgsMapLayer) -> list[Style]:
    style_names = qgs_layer.styleManager().styles()
    style_list = []
    for style_name in style_names:
        style_doc = QDomDocument()
        qgs_layer.styleManager().setCurrentStyle(style_name)
        qgs_layer.exportNamedStyle(style_doc)
        style_list.append(
            Style(
                name=style_name,
                definition=urlsafe_b64encode(zlib.compress(style_doc.toByteArray())).decode(),
            )
        )
    return style_list
create_unified_short_name(short_name: str, path: list[str])

Creates the unified short name, separated by the configured separator.

Parameters:

  • short_name (str) –

    The short name either of the group or the job_layer_definition.

  • path (list[str]) –

    The path is a list of string which stores the information of the current tree path. This is used to construct a string for unifying job_layer_definition names by their tree path.

Returns:

Source code in src/qgis_server_light/exporter/extract.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
def create_unified_short_name(self, short_name: str, path: list[str]):
    """
    Creates the unified short name, separated by the configured separator.

    Args:
        short_name: The short name either of the group or the job_layer_definition.
        path: The path is a list of string which stores the information of the current
            tree path. This is
            used to construct a string for unifying job_layer_definition names by
            their tree path.

    Returns:

    """
    short_name_parts = path + [short_name]
    return self.unify_layer_names_by_group_separator.join(short_name_parts)
extract_datasource_dict(layer: QgsMapLayer) -> dict

Decodes a QGIS map job_layer_definition datasource into a dict and ensures that types are pythonic and pathes are clean for further usage.

Parameters:

  • layer (QgsMapLayer) –

    The job_layer_definition which the datasource should be extracted from.

Returns:

  • dict –

    The decoded and cleaned datasource.

Source code in src/qgis_server_light/exporter/extract.py
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
def extract_datasource_dict(self, layer: QgsMapLayer) -> dict:
    """
    Decodes a QGIS map job_layer_definition datasource into a dict and ensures that
    types are pythonic and pathes are
    clean for further usage.

    Args:
        layer: The job_layer_definition which the datasource should be extracted from.

    Returns:
        The decoded and cleaned datasource.
    """
    decoded = QgsProviderRegistry.instance().decodeUri(
        layer.providerType(), layer.dataProvider().dataSourceUri()
    )
    logging.debug(f"Layer source: {decoded}")
    for key in decoded:
        if str(decoded[key]) in ("None", "NULL"):
            decoded[key] = None
            continue
        if key == "path":
            # QGIS 3 returns url encoded paths, which leads to incorrect operations,
            # eg: ".%2Fdata%2Fhiroshima.mbtiles" instead of "./data/hiroshima.mbtiles"
            # For QGIS 4 projects, the value is expected to be decoded already.
            if self.version.majorVersion() <= 3:
                decoded_path = unquote(decoded[key])
            else:
                decoded_path = decoded[key]
            # Make path relative to the qgis_project
            decoded[key] = decoded_path.replace(f"{self.qgis_project.readPath('./')}/", "")
        else:
            decoded[key] = str(decoded[key])
    return decoded
extract_group(group: QgsLayerTreeGroup, path: list[str])

Collects data pertaining to a QGIS job_layer_definition tree group. Basically this translates a QgsLayerTreeGroup into a QGIS-Server-Light TreeGroup.

Parameters:

  • group (QgsLayerTreeGroup) –

    The group which is handled.

  • path (list[str]) –

    The path is a list of string which stores the information of the current tree path. This is used to construct a string for unifying job_layer_definition names by their tree path.

Source code in src/qgis_server_light/exporter/extract.py
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
def extract_group(
    self,
    group: QgsLayerTreeGroup,
    path: list[str],
):
    """
    Collects data pertaining to a QGIS job_layer_definition tree group. Basically
    this translates a QgsLayerTreeGroup
    into a QGIS-Server-Light TreeGroup.

    Args:
        group: The group which is handled.
        path: The path is a list of string which stores the information of the current
            tree path. This is
            used to construct a string for unifying job_layer_definition names by
            their tree path.
    """
    children = []
    for child in group.children():
        if isinstance(child, QgsLayerTreeGroup):
            children.append(
                self.create_unified_short_name(self.get_group_short_name(child), path)
            )
        else:
            children.append(child.layer().id())
    short_name = self.create_unified_short_name(self.get_group_short_name(group), path[:-1])
    self.qsl_tree.members.append(
        TreeGroup(
            id=short_name,
            name=short_name,
            children=children,
            is_checked=group.itemVisibilityChecked(),
            is_expanded=group.isExpanded(),
        )
    )
    self.qsl_datasets.group.append(
        Group(
            id=short_name,
            name=short_name,
            title=self.get_group_title(group),
            is_checked=group.itemVisibilityChecked(),
            is_expanded=group.isExpanded(),
        )
    )
extract_metadata(project: QgsProject) -> MetaData staticmethod

Creates a QSL interface instance for metadate pulled out of the QGIS project.

Parameters:

  • project (QgsProject) –

    The instantiated QGIS project.

Returns:

  • MetaData –

    The metadata interface instance.

Source code in src/qgis_server_light/exporter/extract.py
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
@staticmethod
def extract_metadata(project: QgsProject) -> MetaData:
    """
    Creates a QSL interface instance for metadate pulled out of the QGIS project.

    Args:
        project: The instantiated QGIS project.

    Returns:
        The metadata interface instance.
    """
    _meta = project.metadata()
    wms_entries = Exporter.get_project_server_entries(project, "wms")
    service = Service(**dict(sorted({**wms_entries}.items())))
    return MetaData(
        service=service,
        author=_meta.author(),
        categories=_meta.categories(),
        creationDateTime=_meta.creationDateTime().toPyDateTime().isoformat(),
        language=_meta.language(),
        links=[link.url for link in _meta.links()],
    )
extract_save_layer(child: QgsLayerTreeLayer, path: list[str], types_from_editor_widget: bool = False)

Save the given job_layer_definition to the output path.

Source code in src/qgis_server_light/exporter/extract.py
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
def extract_save_layer(
    self,
    child: QgsLayerTreeLayer,
    path: list[str],
    types_from_editor_widget: bool = False,
):
    """Save the given job_layer_definition to the output path."""
    layer = child.layer()
    is_checked = child.itemVisibilityChecked()
    layer_type = self.get_layer_type(layer)
    if layer_type is None:
        self.qsl_config.warning(
            f"Layer type {layer.type().name} of layer "
            f"{layer.title() or layer.name()!r} is not supported.",
            code=ExportMessage.Code.LAYER_TYPE_UNSUPPORTED,
            layer_id=layer.id(),
        )
        return

    self.rewrite_datasource_with_qgis3_compatible_uri(layer)
    if not self.is_layer_valid(layer):
        error_message = (
            layer.error().summary()
            or layer.dataProvider().error().summary()
            or f"Layer with name {layer.title() or layer.name()!r} is not valid."
        )
        self.qsl_config.error(
            error_message,
            code=ExportMessage.Code.LAYER_INVALID,
            layer_id=layer.id(),
        )
        raise self.build_export_failure()

    decoded = self.extract_datasource_dict(layer)
    short_name = self.short_name(self.get_layer_short_name(child), path)
    if layer.isSpatial():
        crs = self.create_qsl_crs_from_qgs_layer(layer)
        layer_extent = self.get_layer_extent(layer)
        if layer_extent is None:
            self.qsl_config.error(
                "Could not determine an extent for layer",
                code=ExportMessage.Code.LAYER_EXTENT_MISSING,
                layer_id=layer.id(),
            )
            raise self.build_export_failure()
        bbox_wgs84 = self.create_qsl_bbox_from_qgis_rectangle_wgs84(
            self.qgis_project, layer, layer_extent
        )
        bbox = self.create_qsl_bbox_from_qgis_rectangle_extent(layer_extent)
        is_spatial = True
    else:
        crs = None
        bbox_wgs84 = None
        bbox = None
        is_spatial = False

    if layer_type == "vector":
        data_provider: QgsVectorDataProvider = layer.dataProvider()
        if data_provider.isValid() and data_provider.empty():
            self.qsl_config.warning(
                "Vector layer is empty",
                code=ExportMessage.Code.LAYER_EMPTY,
                layer_id=layer.id(),
            )
        if layer.providerType().lower() == "ogr":
            source = DataSource(ogr=self.create_qsl_source_ogr(decoded))
        elif layer.providerType().lower() == "postgres":
            source = DataSource(postgres=self.create_qsl_source_postgresql(decoded))
        elif layer.providerType().lower() == "wfs":
            # TODO: Correctly implement source!
            source = WfsSource()
        else:
            self.qsl_config.warning(
                f"Unknown provider type {layer.providerType().lower()} "
                f"for vector job_layer_definition {layer.title() or layer.name()}",
                code=ExportMessage.Code.LAYER_PROVIDER_UNSUPPORTED,
                layer_id=layer.id(),
            )
            return
        qsl_vector_dataset_fields = self.create_qsl_fields_from_qgis_field(layer)
        self.qsl_datasets.vector.append(
            Vector(
                name=short_name,
                title=layer.title() or layer.name(),
                styles=self.create_style_list(layer),
                driver=layer.providerType(),
                bbox_wgs84=bbox_wgs84,
                fields=qsl_vector_dataset_fields,
                source=source,
                id=layer.id(),
                crs=crs,
                bbox=bbox,
                minimum_scale=layer.minimumScale(),
                maximum_scale=layer.maximumScale(),
                geometry_type_simple=layer.geometryType().name,
                geometry_type_wkb=layer.wkbType().name,
                is_spatial=is_spatial,
                is_checked=is_checked,
                # Qgis server property WMSBackgroundLayer can only be set for raster layers
                is_background=False,
            )
        )
    elif layer_type == "raster":
        if layer.providerType() == "gdal":
            source = DataSource(gdal=self.create_qsl_source_gdal(decoded))
        elif layer.providerType() == "wms":
            if "tileMatrixSet" in decoded:
                source = DataSource(wmts=self.create_qsl_source_wmts(decoded))
            else:
                if decoded.get("type") == "xyz":
                    source = DataSource(xyz=self.create_qsl_source_xyz(decoded))
                else:
                    source = DataSource(wms=self.create_qsl_source_wms(decoded))
        elif layer.providerType() == "wcs":
            source = DataSource(wcs=self.create_qsl_source_wcs(decoded))
        else:
            self.qsl_config.warning(
                f"Unknown provider type in raster layer: {layer.providerType().lower()}",
                code=ExportMessage.Code.LAYER_PROVIDER_UNSUPPORTED,
                layer_id=layer.id(),
            )
            return

        self.qsl_datasets.raster.append(
            Raster(
                name=short_name,
                title=layer.title() or layer.name(),
                styles=self.create_style_list(layer),
                driver=layer.providerType(),
                bbox_wgs84=bbox_wgs84,
                source=source,
                id=layer.id(),
                crs=crs,
                bbox=bbox,
                minimum_scale=layer.minimumScale(),
                maximum_scale=layer.maximumScale(),
                is_spatial=is_spatial,
                is_checked=is_checked,
                is_background=self.is_wms_background_layer(layer),
            )
        )

    elif layer_type == "custom":
        if layer.providerType().lower() in ["xyzvectortiles", "mbtilesvectortiles"]:
            source = DataSource(vector_tile=self.create_qsl_source_vector_tiles(decoded))
        else:
            # TODO: make this more configurable
            self.qsl_config.warning(
                f"Unknown provider type: {layer.providerType().lower()} "
                f"in layer with short_name {short_name}",
                code=ExportMessage.Code.LAYER_PROVIDER_UNSUPPORTED,
                layer_id=layer.id(),
            )
            return
        self.qsl_datasets.custom.append(
            Custom(
                name=short_name,
                title=layer.title() or layer.name(),
                styles=self.create_style_list(layer),
                driver=layer.providerType(),
                bbox_wgs84=bbox_wgs84,
                source=source,
                id=layer.id(),
                crs=crs,
                bbox=bbox,
                minimum_scale=layer.minimumScale(),
                maximum_scale=layer.maximumScale(),
                is_spatial=is_spatial,
                is_checked=is_checked,
                # Qgis server property WMSBackgroundLayer can only be set for raster layers
                is_background=False,
            )
        )
get_group_short_name(group: QgsLayerTreeGroup) -> str staticmethod
Source code in src/qgis_server_light/exporter/extract.py
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
@staticmethod
def get_group_short_name(group: QgsLayerTreeGroup) -> str:
    if group.customProperty("wmsShortName"):
        return group.customProperty("wmsShortName")
    elif hasattr(group, "groupLayer"):  # noqa: SIM102
        # since QGIS 3.38
        if (
            group.groupLayer()
            and group.groupLayer().serverProperties()
            and group.groupLayer().serverProperties().shortName()
        ):
            return group.groupLayer().serverProperties().shortName()
    short_name = Exporter.sanitize_name(group.name(), lower=True)
    if short_name == "_":
        # this is the tree root, we return empty string here
        return ""
    return short_name
get_group_title(group: QgsLayerTreeGroup) -> str staticmethod
Source code in src/qgis_server_light/exporter/extract.py
764
765
766
767
768
769
770
771
772
773
774
775
776
@staticmethod
def get_group_title(group: QgsLayerTreeGroup) -> str:
    if group.customProperty("wmsTitle"):
        return group.customProperty("wmsTitle")
    elif hasattr(group, "groupLayer"):  # noqa: SIM102
        # since QGIS 3.38
        if (
            group.groupLayer()
            and group.groupLayer().serverProperties()
            and group.groupLayer().serverProperties().title()
        ):
            return group.groupLayer().serverProperties().title()
    return group.name()
get_layer_extent(layer: QgsMapLayer) -> QgsReferencedRectangle | None

Layer extent in the layer CRS, else the project fallback reprojected into it.

Source code in src/qgis_server_light/exporter/extract.py
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
def get_layer_extent(self, layer: QgsMapLayer) -> QgsReferencedRectangle | None:
    """Layer extent in the layer CRS, else the project fallback reprojected into it."""
    ext = layer.extent()
    if not ext.isNull() and ext.isFinite():
        return QgsReferencedRectangle(ext, layer.crs())

    project = layer.project()
    fallback = self.get_project_extent(project) if project else None
    if fallback is None:
        return None

    ct = QgsCoordinateTransform(fallback.crs(), layer.crs(), project.transformContext())
    try:
        transformed = ct.transformBoundingBox(fallback)
    except QgsCsException as err:
        self.qsl_config.error(
            "Layer extent could not be determined by the data provider and the "
            f"project fallback extent could not be reprojected from "
            f"{fallback.crs().authid()} to {layer.crs().authid()}: {err}",
            code=ExportMessage.Code.LAYER_EXTENT_REPROJECTION_FAILED,
            layer_id=layer.id(),
        )
        raise self.build_export_failure() from err

    self.qsl_config.warning(
        "Layer extent could not be determined by the data provider "
        "and is derived from the project instead.",
        code=ExportMessage.Code.LAYER_EXTENT_FROM_PROJECT,
        layer_id=layer.id(),
    )
    return QgsReferencedRectangle(transformed, layer.crs())
get_layer_short_name(layer: QgsLayerTreeLayer) -> str staticmethod

This method determines which name is used as the short name of the job_layer_definition.

Parameters:

  • layer (QgsLayerTreeLayer) –

    The job_layer_definition which the short name should be derived from.

Returns:

  • str –

    The short name.

Source code in src/qgis_server_light/exporter/extract.py
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
@staticmethod
def get_layer_short_name(layer: QgsLayerTreeLayer) -> str:
    """
    This method determines which name is used as the short name of the job_layer_definition.

    Args:
        layer: The job_layer_definition which the short name should be derived from.

    Returns:
        The short name.
    """
    if layer.layer().shortName():
        return layer.layer().shortName()
    elif (
        hasattr(layer.layer(), "serverProperties")
        and layer.layer().serverProperties().shortName()
    ):
        return layer.layer().serverProperties().shortName()
    return layer.layer().id()
get_layer_type(layer: QgsMapLayer) -> str | None staticmethod

Gets the type of the given Qgis job_layer_definition as a string if the type is supported. This is to flatten the understanding of layers from qgis into something we can handle.

Parameters:

  • layer (QgsMapLayer) –

    The job_layer_definition to decide the type for.

Returns:

  • str | None –

    "raster", "vector" or "custom" if a job_layer_definition matched and None otherwise.

Source code in src/qgis_server_light/exporter/extract.py
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
@staticmethod
def get_layer_type(layer: QgsMapLayer) -> str | None:
    """
    Gets the type of the given Qgis job_layer_definition as a string if the type is supported.
    This is to flatten the
    understanding of layers from qgis into something we can handle.

    Args:
        layer: The job_layer_definition to decide the type for.

    Returns:
        "raster", "vector" or "custom" if a job_layer_definition matched and None otherwise.
    """
    if isinstance(layer, QgsRasterLayer):
        return "raster"
    elif isinstance(layer, QgsVectorLayer):
        return "vector"
    elif isinstance(
        layer, (QgsVectorTileLayer, QgsTiledSceneLayer, QgsPointCloudLayer, QgsMeshLayer)
    ):
        return "custom"
    return None
get_project_extent(project: QgsProject) -> QgsReferencedRectangle | None staticmethod

WMS advertised extent, else View Settings full extent, else project CRS area of use.

Source code in src/qgis_server_light/exporter/extract.py
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
@staticmethod
def get_project_extent(project: QgsProject) -> QgsReferencedRectangle | None:
    """WMS advertised extent, else View Settings full extent, else project CRS area of use."""
    wms = QgsServerProjectUtils.wmsExtent(project)
    if not wms.isNull():
        return QgsReferencedRectangle(wms, project.crs())

    full = project.viewSettings().fullExtent()
    if not full.isNull():
        return full

    crs_bounds = project.crs().bounds()  # area of use, always in EPSG:4326
    if not crs_bounds.isNull():
        return QgsReferencedRectangle(crs_bounds, QgsCoordinateReferenceSystem("EPSG:4326"))

    return None
get_project_server_entries(project, scope_or_scopes: str | list) -> dict staticmethod

Gets values from the fields displayed in QGIS under Project > Properties > Server. Returns a Dictionary holding all pairs of found at the corresponding scopes. Example: given scope_or_scope = "wms" (or: ["wms"]) returns { : , : ... } For now the implementation supports only WMS fields but can be easily expanded by adding to the Dictionary below.

Source code in src/qgis_server_light/exporter/extract.py
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
@staticmethod
def get_project_server_entries(project, scope_or_scopes: str | list) -> dict:
    """
    Gets values from the fields displayed in QGIS under Project > Properties > Server.
    Returns a Dictionary holding all pairs of <key, value> found at the corresponding scopes.
    Example:
        given   scope_or_scope = "wms" (or: ["wms"])
        returns { <wms_key1>: <wms_key1_value>, <wms_key2>: <wms_key2_value> ... }
    For now the implementation supports only WMS fields but can be easily expanded by
    adding <key/values> to the Dictionary below.
    """
    supported_scopes = {
        "wms": {
            "scopes": [
                ("WMSContactOrganization", "contact_organization"),
                ("WMSContactMail", "contact_mail"),
                ("WMSContactPerson", "contact_person"),
                ("WMSContactPhone", "contact_phone"),
                ("WMSContactPosition", "contact_position"),
                ("WMSFees", "fees"),
                ("WMSKeywordList", "keyword_list"),
                ("WMSOnlineResource", "online_resource"),
                ("WMSServiceAbstract", "service_abstract"),
                ("WMSServiceTitle", "service_title"),
                ("WMSUrl", "resource_url"),
            ],
            "keys": ["/"],
        }
    }

    scopes = [scope_or_scopes] if isinstance(scope_or_scopes, str) else scope_or_scopes

    for scope in scopes:
        if scope not in supported_scopes:
            supported = ", ".join(supported_scopes.keys())
            error_detail = (
                f"This scope is not supported: {scope}. Supported scopes: {supported}"
            )
            raise ValueError(error_detail)

        scope_entries = supported_scopes[scope]["scopes"]
        key_entries = supported_scopes[scope]["keys"]
        to_collect = zip_longest(scope_entries, key_entries, fillvalue=key_entries[0])

        def collect(acc, pair):
            scope, key = pair
            qgis_scope_name, our_scope_name = scope

            if "list" in qgis_scope_name.lower():
                # PyQGIS sometimes violates Liskov's substitution principle so naming
                # tricks needed
                list_as_text = ", ".join(project.readListEntry(qgis_scope_name, key)[0])
                acc.append((our_scope_name, list_as_text))
            else:
                acc.append(
                    (
                        our_scope_name,
                        project.readEntry(qgis_scope_name, key)[0],
                    )
                )

            return acc

        return dict(reduce(collect, to_collect, []))
is_layer_valid(layer: QgsMapLayer) -> bool staticmethod
Source code in src/qgis_server_light/exporter/extract.py
1136
1137
1138
1139
1140
1141
1142
1143
1144
@staticmethod
def is_layer_valid(layer: QgsMapLayer) -> bool:
    if not layer.isValid():
        logging.debug(f"Layer error: {layer.error().summary()}")
        return False
    if not layer.dataProvider().isValid():
        logging.debug(f"Data provider error: {layer.dataProvider().error().summary()}")
        return False
    return True
is_wms_background_layer(layer: QgsMapLayer) -> bool staticmethod
Source code in src/qgis_server_light/exporter/extract.py
760
761
762
@staticmethod
def is_wms_background_layer(layer: QgsMapLayer) -> bool:
    return bool(layer.customProperty("WMSBackgroundLayer", False))
make_wgs84_geom_transform(project, layer) -> QgsCoordinateTransform staticmethod

Creates a QgisCoordinateTransform context to transform a job_layer_definition to EPSG:4326 aka wgs84.

Parameters:

  • project –

    The QGIS project instance.

  • layer –

    The job_layer_definition which's extent should be reprojected.

Returns:

  • QgsCoordinateTransform –

    The QGIS transformation context.

Source code in src/qgis_server_light/exporter/extract.py
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
@staticmethod
def make_wgs84_geom_transform(project, layer) -> QgsCoordinateTransform:
    """
    Creates a QgisCoordinateTransform context to transform a job_layer_definition
    to EPSG:4326 aka wgs84.

    Args:
        project: The QGIS project instance.
        layer: The job_layer_definition which's extent should be reprojected.

    Returns:
        The QGIS transformation context.
    """
    source_crs = layer.crs()
    epsg_4326 = QgsCoordinateReferenceSystem("EPSG:4326")
    return QgsCoordinateTransform(source_crs, epsg_4326, project)
obtain_editor_widget_type_from_qgis_field(field: QgsField) -> tuple[str, str, str, str] | tuple[str, None, None, None] staticmethod

We simply mimikri QGIS Server here

TODO: This could be improved alot! Maybe we can also backport that to QGIS core some day?

Parameters:

  • field (QgsField) –

    The field of an QgsVectorLayer.

Returns:

  • tuple[str, str, str, str] | tuple[str, None, None, None] –

    Unified type name regarding

  • tuple[str, str, str, str] | tuple[str, None, None, None] –
Source code in src/qgis_server_light/exporter/extract.py
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
@staticmethod
def obtain_editor_widget_type_from_qgis_field(
    field: QgsField,
) -> tuple[str, str, str, str] | tuple[str, None, None, None]:
    """
    We simply mimikri [QGIS Server here](https://github.com/qgis/QGIS/blob/de98779ebb117547364ec4cff433f062374e84a3/src/server/services/wfs/qgswfsdescribefeaturetype.cpp#L153-L192)

    TODO: This could be improved alot! Maybe we can also backport that to QGIS core some day?

    Args:
        field: The field of an `QgsVectorLayer`.

    Returns:
        Unified type name regarding
        [XSD spec](https://www.w3.org/TR/xmlschema11-2/#built-in-primitive-datatypes)
    """
    attribute_type = field.type()
    setup = field.editorWidgetSetup()
    config = setup.config()
    editor_widget_type = setup.type()
    if editor_widget_type == "DateTime":
        field_format = config.get(
            "field_format", QgsDateTimeFieldFormatter.defaultFormat(attribute_type)
        )
        if field_format == QgsDateTimeFieldFormatter.TIME_FORMAT:
            return editor_widget_type, "time", "string", "time"
        elif field_format == QgsDateTimeFieldFormatter.DATE_FORMAT:
            return editor_widget_type, "date", "string", "date"
        elif (
            field_format == QgsDateTimeFieldFormatter.DATETIME_FORMAT
            or field_format == QgsDateTimeFieldFormatter.QT_ISO_FORMAT
        ):
            return editor_widget_type, "dateTime", "string", "date-time"
    elif editor_widget_type == "Range":
        if config.get("Precision"):
            config_precision = int(config["Precision"])
            if config_precision != field.precision():
                if config_precision == 0:
                    return editor_widget_type, "integer", "integer", "int64"
                else:
                    return editor_widget_type, "decimal", "number", "double"

    return editor_widget_type, None, None, None
obtain_is_generated(provider, field_index: int) -> bool staticmethod
Source code in src/qgis_server_light/exporter/extract.py
715
716
717
718
719
720
721
@staticmethod
def obtain_is_generated(provider, field_index: int) -> bool:
    # the OGR provider (GeoPackage fid, ...) lets GDAL assign the identifier on insert,
    # other providers tell it with a default value, e.g. a sequence
    if provider.name() == "ogr":
        return True
    return bool(provider.defaultValueClause(field_index))
obtain_nullable(field: QgsField) -> bool staticmethod

Parameters:

  • field (QgsField) –

    The field of an QgsVectorLayer.

Returns:

  • bool –

    False if the field carries a NotNull constraint (possibly combined with

  • bool –

    others like Unique or Expression), True otherwise.

Source code in src/qgis_server_light/exporter/extract.py
656
657
658
659
660
661
662
663
664
665
666
667
668
@staticmethod
def obtain_nullable(field: QgsField) -> bool:
    """

    Args:
        field: The field of an `QgsVectorLayer`.

    Returns:
        False if the field carries a NotNull constraint (possibly combined with
        others like Unique or Expression), True otherwise.
    """
    constraints = field.constraints().constraints()
    return not constraints & QgsFieldConstraints.Constraint.ConstraintNotNull
obtain_simple_types_from_qgis_field_json(field: QgsField) -> tuple[str, str] | tuple[str, None] staticmethod

Delivers the type match for json based on the field QgsField type.

Parameters:

  • field (QgsField) –

    The field of an QgsVectorLayer.

Returns:

  • tuple[str, str] | tuple[str, None] –

    Unified type name and format in a tuple.

Source code in src/qgis_server_light/exporter/extract.py
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
@staticmethod
def obtain_simple_types_from_qgis_field_json(
    field: QgsField,
) -> tuple[str, str] | tuple[str, None]:
    """
    Delivers the type match for json based on the field QgsField type.

    Args:
        field: The field of an `QgsVectorLayer`.

    Returns:
        Unified type name and format in a tuple.
    """
    attribute_type = field.type()
    if attribute_type == QMetaType.Type.Int:
        return "integer", None
    elif attribute_type == QMetaType.Type.UInt:
        return "integer", "uint32"
    elif attribute_type == QMetaType.Type.LongLong:
        return "integer", "int64"
    elif attribute_type == QMetaType.Type.ULongLong:
        return "integer", "uint64"
    elif attribute_type == QMetaType.Type.Double:
        return "number", "double"
    elif attribute_type == QMetaType.Type.Float:
        return "number", "float"
    elif attribute_type == QMetaType.Type.Bool:
        return "boolean", None
    elif attribute_type == QMetaType.Type.QDate:
        return "string", "date"
    elif attribute_type == QMetaType.Type.QTime:
        return "string", "time"
    elif attribute_type == QMetaType.Type.QDateTime:
        return "string", "date-time"
    else:
        # we handle all unknown types as string. Since its for JavaScript, this should be safe.
        return "string", None
obtain_simple_types_from_qgis_field_xml(field: QgsField) -> str staticmethod

Parameters:

  • field (QgsField) –

    The field of an QgsVectorLayer.

Returns:

  • str –

    Unified type name regarding

  • str –
  • IMPORTANT ( str ) –

    If type is not matched within the function it will be string always!

Source code in src/qgis_server_light/exporter/extract.py
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
@staticmethod
def obtain_simple_types_from_qgis_field_xml(field: QgsField) -> str:
    """

    Args:
        field: The field of an `QgsVectorLayer`.

    Returns:
        Unified type name regarding
        [XSD spec](https://www.w3.org/TR/xmlschema11-2/#built-in-primitive-datatypes)
        IMPORTANT: If type is not matched within the function it will be `string` always!
    """
    attribute_type = field.type()
    if attribute_type == QMetaType.Type.Int:
        return "int"
    elif attribute_type == QMetaType.Type.UInt:
        return "unsignedInt"
    elif attribute_type == QMetaType.Type.LongLong:
        return "long"
    elif attribute_type == QMetaType.Type.ULongLong:
        return "unsignedLong"
    elif attribute_type == QMetaType.Type.Double:
        if field.length() > 0 and field.precision() == 0:
            return "integer"
        else:
            return "decimal"
    elif attribute_type == QMetaType.Type.Bool:
        return "boolean"
    elif attribute_type == QMetaType.Type.QDate:
        return "date"
    elif attribute_type == QMetaType.Type.QTime:
        return "time"
    elif attribute_type == QMetaType.Type.QDateTime:
        return "dateTime"
    else:
        return "string"
open_qgis_project(path_to_project: str) -> QgsProject staticmethod

Parameters:

  • path_to_project (str) –

    The absolute path on the file system where the project

Returns:

  • QgsProject –

    The opened project (read).

Source code in src/qgis_server_light/exporter/extract.py
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
@staticmethod
def open_qgis_project(path_to_project: str) -> QgsProject:
    """


    Args:
        path_to_project: The absolute path on the file system where the project
        can be read from.

    Returns:
        The opened project (read).
    """
    project = QgsProject.instance()
    project.read(path_to_project)
    return project
prepare_qgis_project_name(project: QgsProject) -> str staticmethod

Parameters:

  • project (QgsProject) –

    The instantiated QGIS project.

Returns:

  • str –

    Project name

Source code in src/qgis_server_light/exporter/extract.py
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
@staticmethod
def prepare_qgis_project_name(project: QgsProject) -> str:
    """


    Args:
        project: The instantiated QGIS project.

    Returns:
        Project name
    """
    return project.title() or project.baseName()
provide_field_length(field: QgsField) -> int | None staticmethod
Source code in src/qgis_server_light/exporter/extract.py
670
671
672
673
674
675
676
@staticmethod
def provide_field_length(field: QgsField) -> int | None:
    length = field.length()
    if length > 0:
        return length
    else:
        return None
provide_field_precision(field: QgsField) -> int | None staticmethod
Source code in src/qgis_server_light/exporter/extract.py
678
679
680
681
682
683
684
@staticmethod
def provide_field_precision(field: QgsField) -> int | None:
    precision = field.precision()
    if precision > 0:
        return precision
    else:
        return None
provide_float(value) -> float | None staticmethod

Just an internal helper

Source code in src/qgis_server_light/exporter/extract.py
606
607
608
609
610
611
@staticmethod
def provide_float(value) -> float | None:
    """Just an internal helper"""
    if value is None:
        return None
    return float(value)
rewrite_datasource_with_qgis3_compatible_uri(layer: QgsMapLayer)
Source code in src/qgis_server_light/exporter/extract.py
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
def rewrite_datasource_with_qgis3_compatible_uri(self, layer: QgsMapLayer):
    # QGIS 3 is inconsistent in how it encodes/decodes source URIs, whereas
    # QGIS 4 systematically percent-encodes reserved characters inside datasource values.
    # A project saved by QGIS >= 4 and read by a QGIS 3 build (QSL is based on
    # QGIS 3) therefore needs an unquote() pass to get clean values.
    if not Qgis.version().startswith("3."):
        return

    if self.version.majorVersion() >= 4:
        registry = QgsProviderRegistry.instance()
        original_uri = layer.source()
        qgis3_compatible_uri = registry.encodeUri(
            layer.providerType(),
            {
                key: unquote(value) if isinstance(value, str) else value
                for (key, value) in registry.decodeUri(
                    layer.providerType(), original_uri
                ).items()
            },
        )
        logging.debug(
            f"Layer {layer.id()} datasource URI from QGIS 4 project is rewritten: "
            f"original={original_uri!r}, QGIS 3 compatible={qgis3_compatible_uri!r}"
        )
        layer.setDataSource(qgis3_compatible_uri)
run() -> Config
Source code in src/qgis_server_light/exporter/extract.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def run(self) -> Config:
    if project_error := self.qgis_project.error():
        self.qsl_config.error(
            project_error,
            code=ExportMessage.Code.PROJECT_READ_FAILED,
        )
        raise self.build_export_failure()
    if self.version.majorVersion() > 4:
        self.qsl_config.error(
            f"QGIS project version {self.version.text()} is not supported.",
            code=ExportMessage.Code.PROJECT_VERSION_UNSUPPORTED,
        )
        raise self.build_export_failure()
    self.walk_qgis_project_tree(self.qgis_project_tree_root, [])
    self.qsl_config.relations = self.create_qsl_relations(self.qgis_project)
    return self.qsl_config
sanitize_name(raw: str, lower: bool = False) -> str staticmethod

Transforms an arbitrary string into a WMS/WFS and URL compatible short name for a job_layer_definition or group.

Steps: 1. Unicode‑NFD → ASCII‑transliteration (removes umlauts/diacritics). 2. All chars, which are NOT [A‑Za‑z0‑9_.‑], will be replaced by '' ersetzen. 3. Reduce multiple underscore '' to a single one. 4. Remove leading '', '.', '-'. 5. If the string is empty OR does not start with a letter OR not start with '', a leading '_' will be added. 6. Optional all will be converted to lowercase (lower=True).

Source code in src/qgis_server_light/exporter/extract.py
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
@staticmethod
def sanitize_name(raw: str, lower: bool = False) -> str:
    """
    Transforms an arbitrary string into a WMS/WFS and URL compatible short name for a
    job_layer_definition or group.

    Steps:
    1. Unicode‑NFD → ASCII‑transliteration (removes umlauts/diacritics).
    2. All chars, which are NOT [A‑Za‑z0‑9_.‑], will be replaced by '_' ersetzen.
    3. Reduce multiple underscore '_' to a single one.
    4. Remove leading '_', '.', '-'.
    5. If the string is empty OR does not start with a letter OR not start with '_',
       a leading '_' will be added.
    6. Optional all will be converted to lowercase (lower=True).
    """
    # 1. cleaning to ASCII
    ascii_str = unicodedata.normalize("NFKD", raw).encode("ascii", "ignore").decode()
    # 2. not allowed → '_'
    ascii_str = re.sub(r"[^A-Za-z0-9_.-]+", "_", ascii_str)
    # 3. remove multiple '_'
    ascii_str = re.sub(r"_+", "_", ascii_str)
    # 4. remove trailing chars
    ascii_str = ascii_str.strip("._-")
    # 5. ensure first char is correct (mainly xml stuff and URL)
    if not ascii_str or not re.match(r"[A-Za-z_]", ascii_str[0]):
        ascii_str = "_" + ascii_str
    # 6. Optional lowercase
    if lower:
        ascii_str = ascii_str.lower()
    return ascii_str
short_name(short_name: str, path: list[str]) -> str

Decides if to use the short name itself or the unified version by the tree path.

Parameters:

  • short_name (str) –

    The short name either of the group or the job_layer_definition.

  • path (list[str]) –

    The path is a list of string which stores the information of the current tree path. This is used to construct a string for unifying job_layer_definition names by their tree path.

Returns:

  • str –

    The short name itself or its unified tree path.

Source code in src/qgis_server_light/exporter/extract.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def short_name(self, short_name: str, path: list[str]) -> str:
    """
    Decides if to use the short name itself or the unified version by the tree path.

    Args:
        short_name: The short name either of the group or the job_layer_definition.
        path: The path is a list of string which stores the information of the current
            tree path. This is
            used to construct a string for unifying job_layer_definition names by
            their tree path.

    Returns:
        The short name itself or its unified tree path.
    """
    if self.unify_layer_names_by_group:
        return self.create_unified_short_name(short_name, path)
    else:
        return short_name
sslmode_int_to_str(ssl_mode: int) -> str staticmethod

Mapper to map ssl modes from QGIS int to plain postgres.

Parameters:

  • ssl_mode (int) –

    The ssl mode of the datasource as a int value matching one of https://qgis.org/pyqgis/3.44/core/QgsDataSourceUri.html#qgis.core.QgsDataSourceUri.SslMode

Returns:

  • str –

    The string representation of the ssl mode as it is used by postgres connections.

Source code in src/qgis_server_light/exporter/extract.py
957
958
959
960
961
962
963
964
965
966
967
968
969
@staticmethod
def sslmode_int_to_str(ssl_mode: int) -> str:
    """
    Mapper to map ssl modes from QGIS int to plain postgres.

    Args:
        ssl_mode: The ssl mode of the datasource as a int value matching one of
            https://qgis.org/pyqgis/3.44/core/QgsDataSourceUri.html#qgis.core.QgsDataSourceUri.SslMode

    Returns:
        The string representation of the ssl mode as it is used by postgres connections.
    """
    return QgsDataSourceUri.encodeSslMode(int(ssl_mode))
walk_qgis_project_tree(entity: QgsLayerTreeNode, path: list[str])

This is a highly recursive function which walks to the qgis job_layer_definition tree to extract all knowledge out of it. It is called from itself again for each level of group like elements which are found.

Parameters:

  • entity (QgsLayerTreeNode) –

    The QGIS projects tree node which can be a QgsLayerTree, QgsLayerTreeGroup or QgsLayerTreeLayer.

  • path (list[str]) –

    The path is a list of string which stores the information of the current tree path. This is used to construct a string for unifying job_layer_definition names by their tree path.

Source code in src/qgis_server_light/exporter/extract.py
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
def walk_qgis_project_tree(
    self,
    entity: QgsLayerTreeNode,
    path: list[str],
):
    """
    This is a highly recursive function which walks to the qgis job_layer_definition
    tree to extract all knowledge out
    of it. It is called from itself again for each level of group like elements
    which are found.

    Args:
        entity: The QGIS projects tree node which can be a QgsLayerTree, QgsLayerTreeGroup or
            QgsLayerTreeLayer.
        path: The path is a list of string which stores the information of the current
            tree path. This is
            used to construct a string for unifying job_layer_definition names by their
            tree path.
    """
    if isinstance(entity, QgsLayerTreeLayer):
        # this is a job_layer_definition, we can extract its information
        self.extract_save_layer(
            entity,
            path,
        )
    elif isinstance(entity, (QgsLayerTreeGroup, QgsLayerTree)):
        # these are "group like" elements, we need to step into them one level deeper.
        short_name = self.get_group_short_name(entity)
        if short_name != "":
            # '' is the root of the tree, we don't want it to be part of the path
            path = path + [short_name]
        self.extract_group(
            entity,
            path,
        )
        for child in entity.children():
            # we handle all the children of the group like thing.
            self.walk_qgis_project_tree(
                child,
                path,
            )
    else:
        self.qsl_config.warning(
            "This element was not expected while walking QGIS project tree: "
            f"{type(entity).__name__} at {'/'.join(path)}",
            code=ExportMessage.Code.TREE_NODE_UNSUPPORTED,
        )

interface

common

This module contains common logic, shared beyond all specialised parts of the QGIS-Server-Light interface.

BBox dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/common.py
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
@dataclass(repr=False)
class BBox(BaseInterface):
    x_min: float = field(metadata={"type": "Element"})
    x_max: float = field(metadata={"type": "Element"})
    y_min: float = field(metadata={"type": "Element"})
    y_max: float = field(metadata={"type": "Element"})
    z_min: float = field(default=0.0, metadata={"type": "Element"})
    z_max: float = field(default=0.0, metadata={"type": "Element"})

    def to_list(self) -> list:
        return [self.x_min, self.y_min, self.z_min, self.x_max, self.y_max, self.z_max]

    def to_string(self) -> str:
        return ",".join([str(item) for item in self.to_list()])

    def to_2d_list(self) -> list:
        return [self.x_min, self.y_min, self.x_max, self.y_max]

    def to_2d_string(self) -> str:
        return ",".join([str(item) for item in self.to_2d_list()])

    @staticmethod
    def from_string(bbox_string: str) -> "BBox":
        """
        Takes a CSV string representation of a BBox in the form:
            '<x_min>,<y_min>,<x_max>,<y_max>' or
            '<x_min>,<y_min>,<z_min>,<x_max>,<y_max>,<z_max>'
        """
        coordinates = bbox_string.split(",")
        if len(coordinates) == 4:
            return BBox(
                x_min=float(coordinates[0]),
                y_min=float(coordinates[1]),
                x_max=float(coordinates[2]),
                y_max=float(coordinates[3]),
            )
        elif len(coordinates) == 6:
            return BBox(
                x_min=float(coordinates[0]),
                y_min=float(coordinates[1]),
                z_min=float(coordinates[2]),
                x_max=float(coordinates[3]),
                y_max=float(coordinates[4]),
                z_max=float(coordinates[5]),
            )
        else:
            raise ValueError(f"Invalid bbox string: {bbox_string}")

    @staticmethod
    def from_list(bbox_list: list[float]) -> "BBox":
        """
        Takes a list representation of a BBox in the form:
            [<x_min>,<y_min>,<x_max>,<y_max>] or
            [<x_min>,<y_min>,<z_min>,<x_max>,<y_max>,<z_max>]
        """
        if len(bbox_list) == 4:
            return BBox(
                x_min=bbox_list[0],
                y_min=bbox_list[1],
                x_max=bbox_list[2],
                y_max=bbox_list[3],
            )
        elif len(bbox_list) == 6:
            return BBox(
                x_min=bbox_list[0],
                y_min=bbox_list[1],
                z_min=bbox_list[2],
                x_max=bbox_list[3],
                y_max=bbox_list[4],
                z_max=bbox_list[5],
            )
        else:
            raise ValueError(f"Invalid bbox list: {bbox_list}")
x_max: float = field(metadata={'type': 'Element'}) class-attribute instance-attribute
x_min: float = field(metadata={'type': 'Element'}) class-attribute instance-attribute
y_max: float = field(metadata={'type': 'Element'}) class-attribute instance-attribute
y_min: float = field(metadata={'type': 'Element'}) class-attribute instance-attribute
z_max: float = field(default=0.0, metadata={'type': 'Element'}) class-attribute instance-attribute
z_min: float = field(default=0.0, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(x_min: float, x_max: float, y_min: float, y_max: float, z_min: float = 0.0, z_max: float = 0.0) -> None
from_list(bbox_list: list[float]) -> BBox staticmethod
Takes a list representation of a BBox in the form

[,,,] or [,,,,,]

Source code in src/qgis_server_light/interface/common.py
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
@staticmethod
def from_list(bbox_list: list[float]) -> "BBox":
    """
    Takes a list representation of a BBox in the form:
        [<x_min>,<y_min>,<x_max>,<y_max>] or
        [<x_min>,<y_min>,<z_min>,<x_max>,<y_max>,<z_max>]
    """
    if len(bbox_list) == 4:
        return BBox(
            x_min=bbox_list[0],
            y_min=bbox_list[1],
            x_max=bbox_list[2],
            y_max=bbox_list[3],
        )
    elif len(bbox_list) == 6:
        return BBox(
            x_min=bbox_list[0],
            y_min=bbox_list[1],
            z_min=bbox_list[2],
            x_max=bbox_list[3],
            y_max=bbox_list[4],
            z_max=bbox_list[5],
        )
    else:
        raise ValueError(f"Invalid bbox list: {bbox_list}")
from_string(bbox_string: str) -> BBox staticmethod
Takes a CSV string representation of a BBox in the form

',,,' or ',,,,,'

Source code in src/qgis_server_light/interface/common.py
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
@staticmethod
def from_string(bbox_string: str) -> "BBox":
    """
    Takes a CSV string representation of a BBox in the form:
        '<x_min>,<y_min>,<x_max>,<y_max>' or
        '<x_min>,<y_min>,<z_min>,<x_max>,<y_max>,<z_max>'
    """
    coordinates = bbox_string.split(",")
    if len(coordinates) == 4:
        return BBox(
            x_min=float(coordinates[0]),
            y_min=float(coordinates[1]),
            x_max=float(coordinates[2]),
            y_max=float(coordinates[3]),
        )
    elif len(coordinates) == 6:
        return BBox(
            x_min=float(coordinates[0]),
            y_min=float(coordinates[1]),
            z_min=float(coordinates[2]),
            x_max=float(coordinates[3]),
            y_max=float(coordinates[4]),
            z_max=float(coordinates[5]),
        )
    else:
        raise ValueError(f"Invalid bbox string: {bbox_string}")
to_2d_list() -> list
Source code in src/qgis_server_light/interface/common.py
158
159
def to_2d_list(self) -> list:
    return [self.x_min, self.y_min, self.x_max, self.y_max]
to_2d_string() -> str
Source code in src/qgis_server_light/interface/common.py
161
162
def to_2d_string(self) -> str:
    return ",".join([str(item) for item in self.to_2d_list()])
to_list() -> list
Source code in src/qgis_server_light/interface/common.py
152
153
def to_list(self) -> list:
    return [self.x_min, self.y_min, self.z_min, self.x_max, self.y_max, self.z_max]
to_string() -> str
Source code in src/qgis_server_light/interface/common.py
155
156
def to_string(self) -> str:
    return ",".join([str(item) for item in self.to_list()])
BaseInterface dataclass

This class should be used as base class for all dataclasses in the interface. It offers useful methods to handle exposed content in a centralized way. Mainly for logging redaction.

Since dataclasses gets a repr method installed automatically when they are created, a dataclass inheriting from this base class has to be defined as follows:

@dataclass(repr=False)
class Config(BaseInterface):
    id: int = field(metadata={"type": "Element"})
    secure: str = field(metadata={"type": "Element"})
    long_content: str = field(metadata={"type": "Element"})

    @property
    def shortened_fields(self) -> set:
        return {"long_content"}

    @property
    def redacted_fields(self) -> set:
        return {"secure"}

This way, when an instance of this example class gets logged somewhere it the output will be redacted, meaning the logging output might look like this:

Config(id=1, secure=**REDACTED**, long_content=abc12...io345)
Source code in src/qgis_server_light/interface/common.py
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 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
@dataclass
class BaseInterface:
    """
    This class should be used as base class for all dataclasses in the interface. It offers
    useful methods to
    handle exposed content in a centralized way. Mainly for logging redaction.

    Since dataclasses gets a __repr__ method installed automatically when they are
    created, a dataclass
    inheriting from this base class has to be defined as follows:

        @dataclass(repr=False)
        class Config(BaseInterface):
            id: int = field(metadata={"type": "Element"})
            secure: str = field(metadata={"type": "Element"})
            long_content: str = field(metadata={"type": "Element"})

            @property
            def shortened_fields(self) -> set:
                return {"long_content"}

            @property
            def redacted_fields(self) -> set:
                return {"secure"}

    This way, when an instance of this example class gets logged somewhere it the output
    will be redacted,
    meaning the logging output might look like this:

        Config(id=1, secure=**REDACTED**, long_content=abc12...io345)

    """

    @property
    def shorten_limit(self) -> int:
        """
        The limit to which the content of a field should be shortened.

        Returns:
            The limit.
        """
        return 5

    @property
    def redacted_fields(self) -> set:
        """
        Field which contents should get redacted before printing them on the log. This is
        mainly used to
        prevent passwords in logs.

        Returns:
            The set of field names which should be redacted
        """
        return set()

    @property
    def shortened_fields(self) -> set:
        """
        Fields which should be shortened to a length, this is manly useful for large content
        fields with
        BLOB etc.

        Returns:
            The set field names which should be shortened.
        """
        return set()

    def _value_string(self, repr_value: str | bytes):
        return (
            f"{repr_value[: self.shorten_limit]}...{repr_value[((1 + self.shorten_limit) * -1) :]}"
        )

    def _type_aware_value_string(self, value, repr_value):
        value_string = self._value_string(repr_value)
        if type(value) in [str]:
            return f"'{value_string}'"
        else:
            return f"{value_string}"

    def __repr__(self):
        members = []
        cls = self.__class__.__name__
        for obj_field in fields(self):
            # this is the original switch dataclasses allow on fields
            if obj_field.repr:
                value = getattr(self, obj_field.name)
                repr_value = str(value)
                if obj_field.name in self.redacted_fields:
                    members.append(f"{obj_field.name}=**REDACTED**")
                elif (
                    obj_field.name in self.shortened_fields
                    and value is not None
                    and len(repr_value) > self.shorten_limit * 2
                ):
                    members.append(
                        f"{obj_field.name}={self._type_aware_value_string(value, repr_value)}"
                    )
                else:
                    members.append(f"{obj_field.name}={value!r}")
        return f"{cls}({', '.join(members)})"
redacted_fields: set property

Field which contents should get redacted before printing them on the log. This is mainly used to prevent passwords in logs.

Returns:

  • set –

    The set of field names which should be redacted

shorten_limit: int property

The limit to which the content of a field should be shortened.

Returns:

  • int –

    The limit.

shortened_fields: set property

Fields which should be shortened to a length, this is manly useful for large content fields with BLOB etc.

Returns:

  • set –

    The set field names which should be shortened.

__init__() -> None
__repr__()
Source code in src/qgis_server_light/interface/common.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def __repr__(self):
    members = []
    cls = self.__class__.__name__
    for obj_field in fields(self):
        # this is the original switch dataclasses allow on fields
        if obj_field.repr:
            value = getattr(self, obj_field.name)
            repr_value = str(value)
            if obj_field.name in self.redacted_fields:
                members.append(f"{obj_field.name}=**REDACTED**")
            elif (
                obj_field.name in self.shortened_fields
                and value is not None
                and len(repr_value) > self.shorten_limit * 2
            ):
                members.append(
                    f"{obj_field.name}={self._type_aware_value_string(value, repr_value)}"
                )
            else:
                members.append(f"{obj_field.name}={value!r}")
    return f"{cls}({', '.join(members)})"
Crs dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/common.py
218
219
220
221
222
223
224
225
226
227
228
229
@dataclass(repr=False)
class Crs(BaseInterface):
    auth_id: str = field(default=None, metadata={"type": "Element"})
    postgis_srid: int = field(
        default=None,
        metadata={"type": "Element"},
    )
    ogc_uri: str = field(default=None, metadata={"type": "Element"})
    ogc_urn: str = field(default=None, metadata={"type": "Element"})
    # True when the axis order of the crs is north/east (lat/lon) e.g. EPSG:4326, coordinates
    # written with the URN or URI notation have to be swapped
    axis_inverted: bool = field(default=False, metadata={"type": "Element"})
auth_id: str = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
axis_inverted: bool = field(default=False, metadata={'type': 'Element'}) class-attribute instance-attribute
ogc_uri: str = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
ogc_urn: str = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
postgis_srid: int = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(auth_id: str = None, postgis_srid: int = None, ogc_uri: str = None, ogc_urn: str = None, axis_inverted: bool = False) -> None
RedactedString

This special string class can be used to handle secret strings in the application. It works like a normal string but in case it's used to print or log its value is not reveled to the output.

Source code in src/qgis_server_light/interface/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
class RedactedString:
    """
    This special string class can be used to handle secret strings in the application.
    It works like a normal
    string but in case it's used to print or log its value is not reveled to the output.
    """

    def __init__(self, value, redacted_text="**REDACTED**"):
        self._value = value
        self._redacted_text = redacted_text

    def __str__(self):
        return self._redacted_text

    def __repr__(self):
        return f"<RedactedString {self._redacted_text}>"

    def __format__(self, format_spec):
        return self._redacted_text

    def __json__(self):
        return self._redacted_text

    def reveal(self):
        """
        Allows access to the original value when necessary.

        Returns:
            The secret string.
        """

        return self._value
__format__(format_spec)
Source code in src/qgis_server_light/interface/common.py
126
127
def __format__(self, format_spec):
    return self._redacted_text
__init__(value, redacted_text='**REDACTED**')
Source code in src/qgis_server_light/interface/common.py
116
117
118
def __init__(self, value, redacted_text="**REDACTED**"):
    self._value = value
    self._redacted_text = redacted_text
__json__()
Source code in src/qgis_server_light/interface/common.py
129
130
def __json__(self):
    return self._redacted_text
__repr__()
Source code in src/qgis_server_light/interface/common.py
123
124
def __repr__(self):
    return f"<RedactedString {self._redacted_text}>"
__str__()
Source code in src/qgis_server_light/interface/common.py
120
121
def __str__(self):
    return self._redacted_text
reveal()

Allows access to the original value when necessary.

Returns:

  • –

    The secret string.

Source code in src/qgis_server_light/interface/common.py
132
133
134
135
136
137
138
139
140
def reveal(self):
    """
    Allows access to the original value when necessary.

    Returns:
        The secret string.
    """

    return self._value
Style dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/common.py
232
233
234
235
236
237
238
239
@dataclass(repr=False)
class Style(BaseInterface):
    name: str = field(metadata={"type": "Element"})
    definition: str = field(metadata={"type": "Element"})

    @property
    def shortened_fields(self) -> set:
        return {"definition"}
definition: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
name: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
shortened_fields: set property
__init__(name: str, definition: str) -> None

dispatcher

common
JobState dataclass

The state of a job which keeps its state (see RedisStateProtocol) as it was read from the job hash. It gives the dispatcher one thing to hand over instead of the raw redis fields.

Attributes:

  • id (str) –

    The unique identifier of the job.

  • status (Status) –

    The current status of the job.

  • last_update (str | None) –

    ISO timestamp of the last status change.

  • result (JobResult | None) –

    The result of a succeeded job.

  • message (str | None) –

    The error message of a failed job, or why a dismissed one stopped.

  • progress (int | None) –

    The percentage (0-100) the job reported last, None if it reported none (yet).

Source code in src/qgis_server_light/interface/dispatcher/common.py
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
@dataclass
class JobState:
    """The state of a job which keeps its state (see `RedisStateProtocol`) as
    it was read from the job hash. It gives the dispatcher one thing to hand
    over instead of the raw redis fields.

    Attributes:
        id: The unique identifier of the job.
        status: The current status of the job.
        last_update: ISO timestamp of the last status change.
        result: The result of a succeeded job.
        message: The error message of a failed job, or why a dismissed one stopped.
        progress: The percentage (0-100) the job reported last, `None` if it
            reported none (yet).
    """

    id: str = field(metadata={"type": "Element"})
    status: Status = field(metadata={"type": "Element"})
    last_update: str | None = field(default=None, metadata={"type": "Element"})
    result: JobResult | None = field(default=None, metadata={"type": "Element"})
    message: str | None = field(default=None, metadata={"type": "Element"})
    progress: int | None = field(default=None, metadata={"type": "Element"})

    @property
    def finished(self) -> bool:
        """If the job reached a final status, nothing changes on it anymore."""
        return self.status in (Status.SUCCESS, Status.FAILURE, Status.DISMISSED)
finished: bool property

If the job reached a final status, nothing changes on it anymore.

id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
last_update: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
message: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
progress: int | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
result: JobResult | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
status: Status = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, status: Status, last_update: str | None = None, result: JobResult | None = None, message: str | None = None, progress: int | None = None) -> None
Status

Bases: Enum

Source code in src/qgis_server_light/interface/dispatcher/common.py
 9
10
11
12
13
14
class Status(Enum):
    SUCCESS = "succeed"
    FAILURE = "failed"
    RUNNING = "running"
    QUEUED = "queued"
    DISMISSED = "dismissed"
DISMISSED = 'dismissed' class-attribute instance-attribute
FAILURE = 'failed' class-attribute instance-attribute
QUEUED = 'queued' class-attribute instance-attribute
RUNNING = 'running' class-attribute instance-attribute
SUCCESS = 'succeed' class-attribute instance-attribute
Worker dataclass

A worker the dispatcher has seen alive on the queue. It carries what a consumer needs to tell whether jobs can be served and what the worker is doing right now.

Attributes:

  • id (str) –

    The unique identifier of the worker.

  • last_seen (datetime) –

    The time of the last heartbeat of the worker, always timezone aware.

  • info (EngineInfo) –

    The info the worker published with its last heartbeat (status, QGIS version, start time).

Source code in src/qgis_server_light/interface/dispatcher/common.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@dataclass
class Worker:
    """A worker the dispatcher has seen alive on the queue. It carries what a
    consumer needs to tell whether jobs can be served and what the worker is doing
    right now.

    Attributes:
        id: The unique identifier of the worker.
        last_seen: The time of the last heartbeat of the worker, always timezone aware.
        info: The info the worker published with its last heartbeat (status, QGIS
            version, start time).
    """

    id: str
    last_seen: datetime
    info: EngineInfo
id: str instance-attribute
info: EngineInfo instance-attribute
last_seen: datetime instance-attribute
__init__(id: str, last_seen: datetime, info: EngineInfo) -> None
protocol

This contains the protocol definition about how a job is passed around a redis queue. It is shared by the dispatcher and the worker and therefore must not depend on anything else than the standard library.

RedisProtocol

Names of the redis queue, the job hash fields and the notification channel a job is exchanged with. It is the common ground of both ways a job result is delivered, the concrete queue is defined by the subclasses RedisPublishProtocol and RedisStateProtocol.

A job is put into redis as hash under job:{id} (see job_key) and its id is pushed onto the list returned by queue_name. A worker listens on the queue of the protocol it is built on. The hash holds the fields:

  • info: The job info serialized as JSON.
  • info_type: The class name of the job info, used to parse info.
  • status: The current Status value of the job.
  • timestamp.{status}: ISO timestamp when the job entered that status.
  • timestamp.last_update: ISO timestamp of the last status change.
  • duration: Seconds since the job was posted, as string.

The channel notifications:{id} (see channel) is used to tell a waiting dispatcher that the job is finished. What is sent over it depends on the subclass.

A worker registers itself as hash under worker:{id} (see worker_key) and adds its id to the set worker_list_name. The hash holds the fields:

  • info: The engine info serialized as JSON.
  • last_seen: ISO timestamp (UTC) of the last heartbeat.
  • processes: The descriptions of the processes a process-worker serves (ProcessDescriptions) as JSON, only written by process-workers.

Attributes:

Source code in src/qgis_server_light/interface/dispatcher/protocol.py
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 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
class RedisProtocol:
    """Names of the redis queue, the job hash fields and the notification
    channel a job is exchanged with. It is the common ground of both ways a
    job result is delivered, the concrete queue is defined by the subclasses
    `RedisPublishProtocol` and `RedisStateProtocol`.

    A job is put into redis as hash under `job:{id}` (see `job_key`) and its
    id is pushed onto the list returned by `queue_name`. A worker listens on
    the queue of the protocol it is built on. The hash holds the fields:

    - `info`: The job info serialized as JSON.
    - `info_type`: The class name of the job info, used to parse `info`.
    - `status`: The current `Status` value of the job.
    - `timestamp.{status}`: ISO timestamp when the job entered that status.
    - `timestamp.last_update`: ISO timestamp of the last status change.
    - `duration`: Seconds since the job was posted, as string.

    The channel `notifications:{id}` (see `channel`) is used to tell a waiting
    dispatcher that the job is finished. What is sent over it depends on the
    subclass.

    A worker registers itself as hash under `worker:{id}` (see `worker_key`) and
    adds its id to the set `worker_list_name`. The hash holds the fields:

    - `info`: The engine info serialized as JSON.
    - `last_seen`: ISO timestamp (UTC) of the last heartbeat.
    - `processes`: The descriptions of the processes a process-worker serves
      (`ProcessDescriptions`) as JSON, only written by process-workers.

    Attributes:
        job_queue_name: The name of the redis list the ids of the jobs are
            queued on. Set by the subclasses.
        job_info_key: The hash field holding the serialized job info.
        job_info_type_key: The hash field holding the class name of the job info.
        job_channel_name: The prefix of the channel a finished job is notified on.
        job_status_key: The hash field holding the job status.
        job_duration_key: The hash field holding the job duration.
        job_timestamp_key: The prefix of the hash fields holding the timestamps.
        job_last_update_key: The hash field holding the timestamp of the last update.
        worker_list_name: The name of the redis set the worker ids are registered in.
        worker_info_key: The hash field holding the serialized engine info.
        worker_last_seen_key: The hash field holding the timestamp of the last heartbeat.
        worker_heartbeat_interval: Seconds between two heartbeats of a worker.
        worker_alive_age: Seconds a heartbeat may be old for the worker to count as alive.
        worker_processes_key: The hash field holding the descriptions of the processes
            the worker serves.
    """

    job_queue_name: str
    job_info_key: str = "info"
    job_info_type_key: str = "info_type"
    job_channel_name: str = "notifications"
    job_status_key: str = "status"
    job_duration_key: str = "duration"
    job_timestamp_key: str = "timestamp"
    job_last_update_key: str = f"{job_timestamp_key}.last_update"
    worker_list_name: str = "workers"
    worker_info_key: str = "info"
    worker_last_seen_key: str = "last_seen"
    worker_heartbeat_interval: int = 1
    worker_alive_age: int = 10 * worker_heartbeat_interval
    worker_processes_key: str = "processes"

    @staticmethod
    def job_key(job_id: str) -> str:
        """The key of the redis hash holding the job.

        Args:
            job_id: The unique identifier of the job.
        """
        return f"job:{job_id}"

    @classmethod
    def queue_name(cls) -> str:
        """The name of the queue the jobs of this protocol are queued on. It is
        a method on purpose, so the place where the name is decided stays the
        same if it ever needs to be assembled."""
        return cls.job_queue_name

    @classmethod
    def channel(cls, job_id: str) -> str:
        """The channel a finished job is notified on.

        Args:
            job_id: The unique identifier of the job.
        """
        return f"{cls.job_channel_name}:{job_id}"

    @staticmethod
    def worker_key(worker_id: str) -> str:
        """The key of the redis hash holding the worker registration.

        Args:
            worker_id: The unique identifier of the worker.
        """
        return f"worker:{worker_id}"
job_channel_name: str = 'notifications' class-attribute instance-attribute
job_duration_key: str = 'duration' class-attribute instance-attribute
job_info_key: str = 'info' class-attribute instance-attribute
job_info_type_key: str = 'info_type' class-attribute instance-attribute
job_last_update_key: str = f'{job_timestamp_key}.last_update' class-attribute instance-attribute
job_queue_name: str instance-attribute
job_status_key: str = 'status' class-attribute instance-attribute
job_timestamp_key: str = 'timestamp' class-attribute instance-attribute
worker_alive_age: int = 10 * worker_heartbeat_interval class-attribute instance-attribute
worker_heartbeat_interval: int = 1 class-attribute instance-attribute
worker_info_key: str = 'info' class-attribute instance-attribute
worker_last_seen_key: str = 'last_seen' class-attribute instance-attribute
worker_list_name: str = 'workers' class-attribute instance-attribute
worker_processes_key: str = 'processes' class-attribute instance-attribute
channel(job_id: str) -> str classmethod

The channel a finished job is notified on.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

Source code in src/qgis_server_light/interface/dispatcher/protocol.py
87
88
89
90
91
92
93
94
@classmethod
def channel(cls, job_id: str) -> str:
    """The channel a finished job is notified on.

    Args:
        job_id: The unique identifier of the job.
    """
    return f"{cls.job_channel_name}:{job_id}"
job_key(job_id: str) -> str staticmethod

The key of the redis hash holding the job.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

Source code in src/qgis_server_light/interface/dispatcher/protocol.py
71
72
73
74
75
76
77
78
@staticmethod
def job_key(job_id: str) -> str:
    """The key of the redis hash holding the job.

    Args:
        job_id: The unique identifier of the job.
    """
    return f"job:{job_id}"
queue_name() -> str classmethod

The name of the queue the jobs of this protocol are queued on. It is a method on purpose, so the place where the name is decided stays the same if it ever needs to be assembled.

Source code in src/qgis_server_light/interface/dispatcher/protocol.py
80
81
82
83
84
85
@classmethod
def queue_name(cls) -> str:
    """The name of the queue the jobs of this protocol are queued on. It is
    a method on purpose, so the place where the name is decided stays the
    same if it ever needs to be assembled."""
    return cls.job_queue_name
worker_key(worker_id: str) -> str staticmethod

The key of the redis hash holding the worker registration.

Parameters:

  • worker_id (str) –

    The unique identifier of the worker.

Source code in src/qgis_server_light/interface/dispatcher/protocol.py
 96
 97
 98
 99
100
101
102
103
@staticmethod
def worker_key(worker_id: str) -> str:
    """The key of the redis hash holding the worker registration.

    Args:
        worker_id: The unique identifier of the worker.
    """
    return f"worker:{worker_id}"
RedisPublishProtocol

Bases: RedisProtocol

The protocol of short living jobs a dispatcher waits for, like rendering a map or a legend. The worker publishes the pickled JobResult over the channel and the dispatcher deletes the job hash after it has received it. Nothing is kept, a result is only there for the one who is listening.

Attributes:

  • job_queue_name (str) –

    The name of the redis list the ids of the jobs are queued on.

Source code in src/qgis_server_light/interface/dispatcher/protocol.py
106
107
108
109
110
111
112
113
114
115
116
117
118
class RedisPublishProtocol(RedisProtocol):
    """The protocol of short living jobs a dispatcher waits for, like
    rendering a map or a legend. The worker publishes the pickled `JobResult`
    over the channel and the dispatcher deletes the job hash after it has
    received it. Nothing is kept, a result is only there for the one who is
    listening.

    Attributes:
        job_queue_name: The name of the redis list the ids of the jobs are
            queued on.
    """

    job_queue_name: str = "jobs"
job_queue_name: str = 'jobs' class-attribute instance-attribute
RedisStateProtocol

Bases: RedisProtocol

The protocol of jobs which keep their state, these are the processes. The worker writes the result (or the error message) into the job hash in the same transaction as the final status, so whoever reads the hash never sees a finished job without its result. The hash expires after job_expire seconds, it is the only place the result lives.

Only the status value is sent over the channel and only if the job was submitted with ExecutionMode.SYNC. It just wakes the waiting dispatcher, which then reads the job hash. Asynchronous jobs are polled, nobody waits for a notification there.

Processes are queued on their own list, so long-running processes never block map related jobs.

Additional hash fields:

  • result: The data of the JobResult of a succeeded job.
  • result_content_type: The content type of result.
  • message: The error message of a failed job.
  • progress: The percentage (0-100) the running job reported, only if it reports any. It is written while the job runs, outside the transaction.
  • cancel: Set by the dispatcher to dismiss a job the worker took already. The worker cancels the job and finishes it as dismissed.

Attributes:

  • job_queue_name (str) –

    The name of the redis list the ids of the jobs are queued on.

  • job_result_key (str) –

    The hash field holding the result data.

  • job_result_content_type_key (str) –

    The hash field holding the content type of the result data.

  • job_message_key (str) –

    The hash field holding the error message.

  • job_progress_key (str) –

    The hash field holding the progress in percent.

  • job_cancel_key (str) –

    The hash field asking the worker to cancel the job.

  • job_expire (int) –

    Seconds the job hash is kept after it was submitted and again after it is finished.

Source code in src/qgis_server_light/interface/dispatcher/protocol.py
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
class RedisStateProtocol(RedisProtocol):
    """The protocol of jobs which keep their state, these are the processes.
    The worker writes the result (or the error message) into the job hash in
    the same transaction as the final status, so whoever reads the hash never
    sees a finished job without its result. The hash expires after
    `job_expire` seconds, it is the only place the result lives.

    Only the status value is sent over the channel and only if the job was
    submitted with `ExecutionMode.SYNC`. It just wakes the waiting dispatcher,
    which then reads the job hash. Asynchronous jobs are polled, nobody waits
    for a notification there.

    Processes are queued on their own list, so long-running processes never
    block map related jobs.

    Additional hash fields:

    - `result`: The data of the `JobResult` of a succeeded job.
    - `result_content_type`: The content type of `result`.
    - `message`: The error message of a failed job.
    - `progress`: The percentage (0-100) the running job reported, only if it
      reports any. It is written while the job runs, outside the transaction.
    - `cancel`: Set by the dispatcher to dismiss a job the worker took already.
      The worker cancels the job and finishes it as `dismissed`.

    Attributes:
        job_queue_name: The name of the redis list the ids of the jobs are
            queued on.
        job_result_key: The hash field holding the result data.
        job_result_content_type_key: The hash field holding the content type
            of the result data.
        job_message_key: The hash field holding the error message.
        job_progress_key: The hash field holding the progress in percent.
        job_cancel_key: The hash field asking the worker to cancel the job.
        job_expire: Seconds the job hash is kept after it was submitted and
            again after it is finished.
    """

    job_queue_name: str = "jobs:process"
    job_result_key: str = "result"
    job_result_content_type_key: str = "result_content_type"
    job_message_key: str = "message"
    job_progress_key: str = "progress"
    job_cancel_key: str = "cancel"
    job_expire: int = 86400
job_cancel_key: str = 'cancel' class-attribute instance-attribute
job_expire: int = 86400 class-attribute instance-attribute
job_message_key: str = 'message' class-attribute instance-attribute
job_progress_key: str = 'progress' class-attribute instance-attribute
job_queue_name: str = 'jobs:process' class-attribute instance-attribute
job_result_content_type_key: str = 'result_content_type' class-attribute instance-attribute
job_result_key: str = 'result' class-attribute instance-attribute

exporter

api
ExportParameters dataclass

Bases: BaseInterface

The serializable request parameters which are accepted by the exporter service.

Source code in src/qgis_server_light/interface/exporter/api.py
 6
 7
 8
 9
10
11
12
13
14
@dataclass(repr=False)
class ExportParameters(BaseInterface):
    """
    The serializable request parameters which are accepted by the exporter service.
    """

    project_path: str = field(metadata={"type": "Element"})
    unify_layer_names_by_group: bool = field(metadata={"type": "Element"}, default=False)
    output_format: str = field(metadata={"type": "Element"}, default="json")
output_format: str = field(metadata={'type': 'Element'}, default='json') class-attribute instance-attribute
project_path: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
unify_layer_names_by_group: bool = field(metadata={'type': 'Element'}, default=False) class-attribute instance-attribute
__init__(project_path: str, unify_layer_names_by_group: bool = False, output_format: str = 'json') -> None
ExportResult dataclass

Bases: BaseInterface

The serializable response which is provided by the exporter service.

Source code in src/qgis_server_light/interface/exporter/api.py
17
18
19
20
21
22
23
24
@dataclass(repr=False)
class ExportResult(BaseInterface):
    """
    The serializable response which is provided by the exporter service.
    """

    successful: bool = field(metadata={"type": "Element"})
    content: str = field(metadata={"type": "Element"})
content: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
successful: bool = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(successful: bool, content: str) -> None
extract

This module contains all interface definition to translate from QGIS project to QGIS-Server-Light logic and to write the JSON export of the QGIS project

AbstractDataset dataclass

Bases: LayerLike

Source code in src/qgis_server_light/interface/exporter/extract.py
222
223
224
@dataclass(repr=False)
class AbstractDataset(LayerLike):
    title: str = field(metadata={"type": "Element"})
title: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, name: str, is_checked: bool, title: str) -> None
Config dataclass

Bases: ResultWithMessages

Source code in src/qgis_server_light/interface/exporter/extract.py
951
952
953
954
955
956
957
958
959
@dataclass(repr=False)
class Config(ResultWithMessages):
    meta_data: MetaData = field(metadata={"type": "Element"})
    tree: Tree = field(metadata={"type": "Element"})
    datasets: Datasets = field(metadata={"type": "Element"})
    relations: list[Relation] = field(
        default_factory=list,
        metadata={"type": "Element"},
    )
datasets: Datasets = field(metadata={'type': 'Element'}) class-attribute instance-attribute
meta_data: MetaData = field(metadata={'type': 'Element'}) class-attribute instance-attribute
relations: list[Relation] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
tree: Tree = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(project: Project, exporter: Exporter, meta_data: MetaData, tree: Tree, datasets: Datasets, relations: list[Relation] = list(), *, messages: list[ExportMessage] = list()) -> None
Custom dataclass

Bases: DataSet

Source code in src/qgis_server_light/interface/exporter/extract.py
707
708
709
@dataclass(repr=False)
class Custom(DataSet):
    pass
__init__(id: str, name: str, is_checked: bool, title: str, source: DataSource, driver: str, bbox: BBox | None = None, bbox_wgs84: BBox | None = None, crs: Crs | None = None, styles: list[Style] = list(), minimum_scale: float | None = None, maximum_scale: float | None = None, style_name: str = 'default', is_spatial: bool = True, is_background: bool = False) -> None
DataSet dataclass

Bases: AbstractDataset

Source code in src/qgis_server_light/interface/exporter/extract.py
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
@dataclass(repr=False)
class DataSet(AbstractDataset):
    source: DataSource = field(metadata={"type": "Element"})
    driver: str = field(metadata={"type": "Element"})
    bbox: BBox | None = field(default=None, metadata={"type": "Element"})
    bbox_wgs84: BBox | None = field(default=None, metadata={"type": "Element"})
    crs: Crs | None = field(default=None, metadata={"type": "Element"})
    styles: list[Style] = field(default_factory=list, metadata={"type": "Element"})
    minimum_scale: float | None = field(default=None, metadata={"type": "Element"})
    maximum_scale: float | None = field(default=None, metadata={"type": "Element"})
    style_name: str = field(default="default", metadata={"type": "Element"})
    is_spatial: bool = field(default=True, metadata={"type": "Element"})
    is_background: bool = field(default=False, metadata={"type": "Element"})

    def get_style_by_name(self, name: str) -> Style | None:
        for style in self.styles:
            if name == style.name:
                return style
        return None

    def style(self) -> Style | None:
        return self.get_style_by_name(self.style_name)
bbox: BBox | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
bbox_wgs84: BBox | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
crs: Crs | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
driver: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
is_background: bool = field(default=False, metadata={'type': 'Element'}) class-attribute instance-attribute
is_spatial: bool = field(default=True, metadata={'type': 'Element'}) class-attribute instance-attribute
maximum_scale: float | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
minimum_scale: float | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
source: DataSource = field(metadata={'type': 'Element'}) class-attribute instance-attribute
style_name: str = field(default='default', metadata={'type': 'Element'}) class-attribute instance-attribute
styles: list[Style] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, name: str, is_checked: bool, title: str, source: DataSource, driver: str, bbox: BBox | None = None, bbox_wgs84: BBox | None = None, crs: Crs | None = None, styles: list[Style] = list(), minimum_scale: float | None = None, maximum_scale: float | None = None, style_name: str = 'default', is_spatial: bool = True, is_background: bool = False) -> None
get_style_by_name(name: str) -> Style | None
Source code in src/qgis_server_light/interface/exporter/extract.py
660
661
662
663
664
def get_style_by_name(self, name: str) -> Style | None:
    for style in self.styles:
        if name == style.name:
            return style
    return None
style() -> Style | None
Source code in src/qgis_server_light/interface/exporter/extract.py
666
667
def style(self) -> Style | None:
    return self.get_style_by_name(self.style_name)
DataSource dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/exporter/extract.py
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
@dataclass(repr=False)
class DataSource(BaseInterface):
    postgres: PostgresSource | None = field(default=None, metadata={"type": "Element"})
    wmts: WmtsSource | None = field(default=None, metadata={"type": "Element"})
    wms: WmsSource | None = field(default=None, metadata={"type": "Element"})
    ogr: OgrSource | None = field(default=None, metadata={"type": "Element"})
    gdal: GdalSource | None = field(default=None, metadata={"type": "Element"})
    wfs: WfsSource | None = field(default=None, metadata={"type": "Element"})
    vector_tile: VectorTileSource | None = field(default=None, metadata={"type": "Element"})
    xyz: XYZSource | None = field(default=None, metadata={"type": "Element"})
    wcs: WcsSource | None = field(default=None, metadata={"type": "Element"})

    @property
    def definition(
        self,
    ) -> (
        PostgresSource
        | WmtsSource
        | WmsSource
        | OgrSource
        | GdalSource
        | WfsSource
        | VectorTileSource
        | XYZSource
        | WcsSource
        | None
    ):
        for dataclass_field in fields(self):
            name = dataclass_field.name
            value = getattr(self, name)
            if value:
                return value
        logging.error(f"No source was definied at {self.__class__.__name__}, this is not expected")
        return None
definition: PostgresSource | WmtsSource | WmsSource | OgrSource | GdalSource | WfsSource | VectorTileSource | XYZSource | WcsSource | None property
gdal: GdalSource | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
ogr: OgrSource | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
postgres: PostgresSource | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
vector_tile: VectorTileSource | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
wcs: WcsSource | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
wfs: WfsSource | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
wms: WmsSource | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
wmts: WmtsSource | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
xyz: XYZSource | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(postgres: PostgresSource | None = None, wmts: WmtsSource | None = None, wms: WmsSource | None = None, ogr: OgrSource | None = None, gdal: GdalSource | None = None, wfs: WfsSource | None = None, vector_tile: VectorTileSource | None = None, xyz: XYZSource | None = None, wcs: WcsSource | None = None) -> None
Datasets dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/exporter/extract.py
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
@dataclass(repr=False)
class Datasets(BaseInterface):
    vector: list[Vector] = field(
        default_factory=list,
        metadata={"type": "Element"},
    )
    raster: list[Raster] = field(
        default_factory=list,
        metadata={"type": "Element"},
    )
    custom: list[Custom] = field(
        default_factory=list,
        metadata={"type": "Element"},
    )
    group: list[Group] = field(
        default_factory=list,
        metadata={"type": "Element"},
    )

    def find_dataset_by_id(self, id: str) -> Vector | Raster | Custom | None:
        """
        Finds a dataset by id in the list of passed datasets.

        Args:
            id: The id value which should be looked up

        Returns:
            The found dataset or None
        """
        for dataset in self.vector + self.raster + self.custom:
            if dataset.id == id:
                return dataset
        return None

    def find_group_by_id(self, identifier: str) -> Group | None:
        for g in self.group:
            if g.id == identifier:
                return g
        return None
custom: list[Custom] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
group: list[Group] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
raster: list[Raster] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
vector: list[Vector] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(vector: list[Vector] = list(), raster: list[Raster] = list(), custom: list[Custom] = list(), group: list[Group] = list()) -> None
find_dataset_by_id(id: str) -> Vector | Raster | Custom | None

Finds a dataset by id in the list of passed datasets.

Parameters:

  • id (str) –

    The id value which should be looked up

Returns:

Source code in src/qgis_server_light/interface/exporter/extract.py
831
832
833
834
835
836
837
838
839
840
841
842
843
844
def find_dataset_by_id(self, id: str) -> Vector | Raster | Custom | None:
    """
    Finds a dataset by id in the list of passed datasets.

    Args:
        id: The id value which should be looked up

    Returns:
        The found dataset or None
    """
    for dataset in self.vector + self.raster + self.custom:
        if dataset.id == id:
            return dataset
    return None
find_group_by_id(identifier: str) -> Group | None
Source code in src/qgis_server_light/interface/exporter/extract.py
846
847
848
849
850
def find_group_by_id(self, identifier: str) -> Group | None:
    for g in self.group:
        if g.id == identifier:
            return g
    return None
EditorWidget dataclass

Bases: BaseInterface

Holds the configuration of the editor widget of a field. Only one of the attributes is set, matching Field.editor_widget_type.

Source code in src/qgis_server_light/interface/exporter/extract.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
@dataclass(repr=False)
class EditorWidget(BaseInterface):
    """
    Holds the configuration of the editor widget of a field. Only one of the
    attributes is set, matching `Field.editor_widget_type`.
    """

    value_map: ValueMap | None = field(default=None, metadata={"type": "Element"})
    value_relation: ValueRelation | None = field(default=None, metadata={"type": "Element"})
    relation_reference: RelationReference | None = field(default=None, metadata={"type": "Element"})
    range: Range | None = field(default=None, metadata={"type": "Element"})

    @property
    def definition(self) -> ValueMap | ValueRelation | RelationReference | Range | None:
        for dataclass_field in fields(self):
            value = getattr(self, dataclass_field.name)
            if value:
                return value
        logging.error(
            f"No configuration was defined at {self.__class__.__name__}, this is not expected"
        )
        return None
definition: ValueMap | ValueRelation | RelationReference | Range | None property
range: Range | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
relation_reference: RelationReference | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
value_map: ValueMap | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
value_relation: ValueRelation | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(value_map: ValueMap | None = None, value_relation: ValueRelation | None = None, relation_reference: RelationReference | None = None, range: Range | None = None) -> None
ExportMessage dataclass

Bases: BaseInterface

A warning or error produced while exporting the QGIS project.

Source code in src/qgis_server_light/interface/exporter/extract.py
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
@dataclass(repr=False)
class ExportMessage(BaseInterface):
    """A warning or error produced while exporting the QGIS project."""

    class Level(StrEnum):
        WARNING = "warning"
        ERROR = "error"

    class Code(StrEnum):
        PROJECT_READ_FAILED = "project_read_failed"
        PROJECT_VERSION_UNSUPPORTED = "project_version_unsupported"
        TREE_NODE_UNSUPPORTED = "tree_node_unsupported"
        LAYER_INVALID = "layer_invalid"
        LAYER_EMPTY = "layer_empty"
        LAYER_EXTENT_MISSING = "layer_extent_missing"
        LAYER_EXTENT_FROM_PROJECT = "layer_extent_from_project"
        LAYER_EXTENT_REPROJECTION_FAILED = "layer_extent_reprojection_failed"
        LAYER_PROVIDER_UNSUPPORTED = "layer_provider_unsupported"
        LAYER_TYPE_UNSUPPORTED = "layer_type_unsupported"
        FIELD_EDITOR_WIDGET_TYPE_UNSUPPORTED = "field_editor_widget_type_unsupported"
        UNEXPECTED_ERROR = "unexpected_error"

    level: Level = field(metadata={"type": "Element"})
    message: str = field(metadata={"type": "Element"})
    code: Code = field(metadata={"type": "Element"})
    layer_id: str | None = field(default=None, metadata={"type": "Element"})
code: Code = field(metadata={'type': 'Element'}) class-attribute instance-attribute
layer_id: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
level: Level = field(metadata={'type': 'Element'}) class-attribute instance-attribute
message: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
Code

Bases: StrEnum

Source code in src/qgis_server_light/interface/exporter/extract.py
906
907
908
909
910
911
912
913
914
915
916
917
918
class Code(StrEnum):
    PROJECT_READ_FAILED = "project_read_failed"
    PROJECT_VERSION_UNSUPPORTED = "project_version_unsupported"
    TREE_NODE_UNSUPPORTED = "tree_node_unsupported"
    LAYER_INVALID = "layer_invalid"
    LAYER_EMPTY = "layer_empty"
    LAYER_EXTENT_MISSING = "layer_extent_missing"
    LAYER_EXTENT_FROM_PROJECT = "layer_extent_from_project"
    LAYER_EXTENT_REPROJECTION_FAILED = "layer_extent_reprojection_failed"
    LAYER_PROVIDER_UNSUPPORTED = "layer_provider_unsupported"
    LAYER_TYPE_UNSUPPORTED = "layer_type_unsupported"
    FIELD_EDITOR_WIDGET_TYPE_UNSUPPORTED = "field_editor_widget_type_unsupported"
    UNEXPECTED_ERROR = "unexpected_error"
FIELD_EDITOR_WIDGET_TYPE_UNSUPPORTED = 'field_editor_widget_type_unsupported' class-attribute instance-attribute
LAYER_EMPTY = 'layer_empty' class-attribute instance-attribute
LAYER_EXTENT_FROM_PROJECT = 'layer_extent_from_project' class-attribute instance-attribute
LAYER_EXTENT_MISSING = 'layer_extent_missing' class-attribute instance-attribute
LAYER_EXTENT_REPROJECTION_FAILED = 'layer_extent_reprojection_failed' class-attribute instance-attribute
LAYER_INVALID = 'layer_invalid' class-attribute instance-attribute
LAYER_PROVIDER_UNSUPPORTED = 'layer_provider_unsupported' class-attribute instance-attribute
LAYER_TYPE_UNSUPPORTED = 'layer_type_unsupported' class-attribute instance-attribute
PROJECT_READ_FAILED = 'project_read_failed' class-attribute instance-attribute
PROJECT_VERSION_UNSUPPORTED = 'project_version_unsupported' class-attribute instance-attribute
TREE_NODE_UNSUPPORTED = 'tree_node_unsupported' class-attribute instance-attribute
UNEXPECTED_ERROR = 'unexpected_error' class-attribute instance-attribute
Level

Bases: StrEnum

Source code in src/qgis_server_light/interface/exporter/extract.py
902
903
904
class Level(StrEnum):
    WARNING = "warning"
    ERROR = "error"
ERROR = 'error' class-attribute instance-attribute
WARNING = 'warning' class-attribute instance-attribute
__init__(level: Level, message: str, code: Code, layer_id: str | None = None) -> None
Exporter dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/exporter/extract.py
893
894
895
@dataclass(repr=False)
class Exporter(BaseInterface):
    qgis_version: str = field(metadata={"type": "Element"})
qgis_version: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(qgis_version: str) -> None
Field dataclass

Bases: BaseInterface

Transportable (serializable) form of a QGIS vector job_layer_definition fiel (attribute). It contains the information of the original data datatype and its translated versions and the editor widget one as well.

Attributes:

Source code in src/qgis_server_light/interface/exporter/extract.py
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
@dataclass(repr=False)
class Field(BaseInterface):
    """
    Transportable (serializable) form of a QGIS vector job_layer_definition fiel (attribute).
    It contains the information of
    the original data datatype and its translated versions and the editor widget one as well.

    Attributes:
        name: Machine readable name of the field
        type: Original type as defined by data source (PostGIS, GPKG, etc.)
        is_primary_key: if the field is considered to be primary key.
        is_generated: if the value of the primary key is generated by the source on insert.
        type_wfs: Translated type for further usage. Based on the simple types of
            [XSD spec](https://www.w3.org/TR/xmlschema11-2/#built-in-primitive-datatypes).
        type_oapif: Translated type based on the types of the
            [OpenAPI Spec](https://spec.openapis.org/oas/latest.html#data-types)
        type_oapif_format: Format of the above-mentioned type based on the
            [OpenAPI Spec](https://spec.openapis.org/oas/latest.html#data-types)
        alias: Human readable name.
        comment: Field description.
        nullable: If this field can be NULL or not.
        length: The limitation in length on the field value.
        precision: The precision of the field value (float types)
        editor_widget_type: The original type how it is defined in the QGIS form.
        editor_widget_type_wfs: The translated type based on the simple types of
            [XSD spec](https://www.w3.org/TR/xmlschema11-2/#built-in-primitive-datatypes).
        editor_widget_type_oapif: Translated type based on the types of the
            [OpenAPI Spec](https://spec.openapis.org/oas/latest.html#data-types)
        editor_widget_type_oapif_format: Format of the above-mentioned type based on the
            [OpenAPI Spec](https://spec.openapis.org/oas/latest.html#data-types)
        editor_widget: The configuration of the editor widget. None if the widget type
            is not one of the exported ones.
        constraints: The constraints of the field. None for exports which did not
            contain constraints yet.
    """

    name: str = field(metadata={"type": "Element"})
    type: str = field(metadata={"type": "Element"})
    is_primary_key: bool = field(
        default=False,
        metadata={"type": "Element"},
    )
    is_generated: bool = field(
        default=False,
        metadata={"type": "Element"},
    )
    type_wfs: str | None = field(default=None, metadata={"type": "Element"})
    type_oapif: str | None = field(default=None, metadata={"type": "Element"})
    type_oapif_format: str | None = field(default=None, metadata={"type": "Element"})
    alias: str | None = field(default=None, metadata={"type": "Element"})
    comment: str | None = field(default=None, metadata={"type": "Element"})
    nullable: bool = field(default=True, metadata={"type": "Element"})
    length: int | None = field(default=None, metadata={"type": "Element"})
    precision: int | None = field(default=None, metadata={"type": "Element"})
    editor_widget_type: str | None = field(default=None, metadata={"type": "Element"})
    editor_widget_type_wfs: str | None = field(default=None, metadata={"type": "Element"})
    editor_widget_type_oapif: str | None = field(default=None, metadata={"type": "Element"})
    editor_widget_type_oapif_format: str | None = field(default=None, metadata={"type": "Element"})
    editor_widget: EditorWidget | None = field(default=None, metadata={"type": "Element"})
    constraints: FieldConstraints | None = field(default=None, metadata={"type": "Element"})
alias: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
comment: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
constraints: FieldConstraints | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
editor_widget: EditorWidget | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
editor_widget_type: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
editor_widget_type_oapif: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
editor_widget_type_oapif_format: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
editor_widget_type_wfs: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
is_generated: bool = field(default=False, metadata={'type': 'Element'}) class-attribute instance-attribute
is_primary_key: bool = field(default=False, metadata={'type': 'Element'}) class-attribute instance-attribute
length: int | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
name: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
nullable: bool = field(default=True, metadata={'type': 'Element'}) class-attribute instance-attribute
precision: int | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
type: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
type_oapif: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
type_oapif_format: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
type_wfs: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(name: str, type: str, is_primary_key: bool = False, is_generated: bool = False, type_wfs: str | None = None, type_oapif: str | None = None, type_oapif_format: str | None = None, alias: str | None = None, comment: str | None = None, nullable: bool = True, length: int | None = None, precision: int | None = None, editor_widget_type: str | None = None, editor_widget_type_wfs: str | None = None, editor_widget_type_oapif: str | None = None, editor_widget_type_oapif_format: str | None = None, editor_widget: EditorWidget | None = None, constraints: FieldConstraints | None = None) -> None
FieldConstraints dataclass

Bases: BaseInterface

The constraints of a field as defined in QGIS (provider or layer).

Attributes:

  • not_null (bool) –

    If the field must not be NULL.

  • unique (bool) –

    If the field value must be unique.

  • expression (str | None) –

    The QGIS expression the field value has to fulfill.

Source code in src/qgis_server_light/interface/exporter/extract.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
@dataclass(repr=False)
class FieldConstraints(BaseInterface):
    """
    The constraints of a field as defined in QGIS (provider or layer).

    Attributes:
        not_null: If the field must not be NULL.
        unique: If the field value must be unique.
        expression: The QGIS expression the field value has to fulfill.
    """

    not_null: bool = field(default=False, metadata={"type": "Element"})
    unique: bool = field(default=False, metadata={"type": "Element"})
    expression: str | None = field(default=None, metadata={"type": "Element"})
expression: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
not_null: bool = field(default=False, metadata={'type': 'Element'}) class-attribute instance-attribute
unique: bool = field(default=False, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(not_null: bool = False, unique: bool = False, expression: str | None = None) -> None
GdalSource dataclass

Bases: Source

Source code in src/qgis_server_light/interface/exporter/extract.py
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
@dataclass(repr=False)
class GdalSource(Source):
    path: str = field(metadata={"type": "Element"})
    layer_name: str | None = field(default=None, metadata={"type": "Element"})
    vsi_prefix: str | None = field(default=None, metadata={"type": "Element"})

    @property
    def remote(self):
        return self.decide_remote(self.path)

    @property
    def to_qgis_decoded_uri(self) -> dict:
        connection_dict = {"path": self.path}
        if self.layer_name is not None:
            connection_dict["layerName"] = self.layer_name
        if self.vsi_prefix is not None:
            connection_dict["vsiPrefix"] = self.vsi_prefix
        return connection_dict

    @classmethod
    def from_qgis_decoded_uri(cls, decoded_uri: dict):
        return cls(
            path=decoded_uri["path"],
            layer_name=decoded_uri.get("layerName"),
            vsi_prefix=decoded_uri.get("vsiPrefix"),
        )
layer_name: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
path: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
remote property
to_qgis_decoded_uri: dict property
vsi_prefix: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(path: str, layer_name: str | None = None, vsi_prefix: str | None = None) -> None
from_qgis_decoded_uri(decoded_uri: dict) classmethod
Source code in src/qgis_server_light/interface/exporter/extract.py
265
266
267
268
269
270
271
@classmethod
def from_qgis_decoded_uri(cls, decoded_uri: dict):
    return cls(
        path=decoded_uri["path"],
        layer_name=decoded_uri.get("layerName"),
        vsi_prefix=decoded_uri.get("vsiPrefix"),
    )
Group dataclass

Bases: AbstractDataset

Holds meta information of a group. It's position in the tree and its children can be derived by id matching.

Source code in src/qgis_server_light/interface/exporter/extract.py
712
713
714
715
716
717
@dataclass(repr=False)
class Group(AbstractDataset):
    """Holds meta information of a group. It's position in the tree and its children can
    be derived by id matching."""

    is_expanded: bool = field(metadata={"type": "Element"})
is_expanded: bool = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, name: str, is_checked: bool, title: str, is_expanded: bool) -> None
LayerLike dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/exporter/extract.py
16
17
18
19
20
@dataclass(repr=False)
class LayerLike(BaseInterface):
    id: str = field(metadata={"type": "Element"})
    name: str = field(metadata={"type": "Element"})
    is_checked: bool = field(metadata={"type": "Element"})
id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
is_checked: bool = field(metadata={'type': 'Element'}) class-attribute instance-attribute
name: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, name: str, is_checked: bool) -> None
MetaData dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/exporter/extract.py
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
@dataclass(repr=False)
class MetaData(BaseInterface):
    service: Service = field(metadata={"type": "Element"})
    links: list[str] | None = field(
        default_factory=list,
        metadata={"type": "Element"},
    )
    language: str | None = field(
        default=None,
        metadata={"type": "Element"},
    )
    categories: list[str] | None = field(
        default_factory=list,
        metadata={"type": "Element"},
    )
    creationDateTime: str = field(
        default=None,
        metadata={"type": "Element"},
    )
    author: str | None = field(default=None, metadata={"type": "Element"})

    def __post_init__(self):
        if self.creationDateTime is None:
            self.creationDateTime = datetime.now(UTC).isoformat()
author: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
categories: list[str] | None = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
creationDateTime: str = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
language: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
links: list[str] | None = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
service: Service = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(service: Service, links: list[str] | None = list(), language: str | None = None, categories: list[str] | None = list(), creationDateTime: str = None, author: str | None = None) -> None
__post_init__()
Source code in src/qgis_server_light/interface/exporter/extract.py
777
778
779
def __post_init__(self):
    if self.creationDateTime is None:
        self.creationDateTime = datetime.now(UTC).isoformat()
OgrSource dataclass

Bases: GdalSource

Source code in src/qgis_server_light/interface/exporter/extract.py
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
@dataclass(repr=False)
class OgrSource(GdalSource):
    layer_id: str | None = field(default=None, metadata={"type": "Element"})
    subset: str | None = field(default=None, metadata={"type": "Element"})

    @property
    def to_qgis_decoded_uri(self) -> dict:
        connection_dict = super().to_qgis_decoded_uri
        if self.layer_id:
            connection_dict["layerId"] = self.layer_id
        if self.subset:
            connection_dict["subset"] = self.subset
        return connection_dict

    @classmethod
    def from_qgis_decoded_uri(cls, decoded_uri: dict):
        base_class_instance = GdalSource.from_qgis_decoded_uri(decoded_uri)
        return cls(
            path=base_class_instance.path,
            layer_name=base_class_instance.layer_name,
            vsi_prefix=base_class_instance.vsi_prefix,
            layer_id=decoded_uri.get("layerId"),
            subset=decoded_uri.get("subset"),
        )

    @property
    def encoded_uri_separator(self) -> str:
        return "|"
encoded_uri_separator: str property
layer_id: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
subset: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
to_qgis_decoded_uri: dict property
__init__(path: str, layer_name: str | None = None, vsi_prefix: str | None = None, layer_id: str | None = None, subset: str | None = None) -> None
from_qgis_decoded_uri(decoded_uri: dict) classmethod
Source code in src/qgis_server_light/interface/exporter/extract.py
288
289
290
291
292
293
294
295
296
297
@classmethod
def from_qgis_decoded_uri(cls, decoded_uri: dict):
    base_class_instance = GdalSource.from_qgis_decoded_uri(decoded_uri)
    return cls(
        path=base_class_instance.path,
        layer_name=base_class_instance.layer_name,
        vsi_prefix=base_class_instance.vsi_prefix,
        layer_id=decoded_uri.get("layerId"),
        subset=decoded_uri.get("subset"),
    )
PostgresSource dataclass

Bases: Source

Source code in src/qgis_server_light/interface/exporter/extract.py
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
@dataclass(repr=False)
class PostgresSource(Source):
    key: str = field(metadata={"type": "Element"})
    table: str = field(metadata={"type": "Element"})
    schema: str | None = field(default=None, metadata={"type": "Element"})
    geometry_column: str | None = field(default=None, metadata={"type": "Element"})
    dbname: str | None = field(default=None, metadata={"type": "Element"})
    host: str | None = field(default=None, metadata={"type": "Element"})
    password: str | None = field(default=None, metadata={"type": "Element"})
    port: int | None = field(default=None, metadata={"type": "Element"})
    type: int | None = field(default=None, metadata={"type": "Element"})
    username: str | None = field(default=None, metadata={"type": "Element"})
    srid: str | None = field(default=None, metadata={"type": "Element"})
    sslmode: int | None = field(default=None, metadata={"type": "Element"})
    ssl_mode_text: str | None = field(default=None, metadata={"type": "Element"})
    service: str | None = field(default=None, metadata={"type": "Element"})
    check_primary_key_unicity: str | None = field(default=None, metadata={"type": "Element"})
    sql: str | None = field(default=None, metadata={"type": "Element"})

    @property
    def redacted_fields(self) -> set:
        return {"password"}

    @property
    def to_qgis_decoded_uri(self) -> dict:
        connection_dict = {"key": self.key, "schema": self.schema, "table": self.table}
        if self.geometry_column is not None:
            connection_dict["geometrycolumn"] = self.geometry_column
        if self.dbname is not None:
            connection_dict["dbname"] = self.dbname
        if self.host is not None:
            connection_dict["host"] = self.host
        if self.password is not None:
            connection_dict["password"] = self.password
        if self.port is not None:
            connection_dict["port"] = self.port
        if self.type is not None:
            connection_dict["type"] = self.type
        if self.username is not None:
            connection_dict["username"] = self.username
        if self.srid is not None:
            connection_dict["srid"] = self.srid
        if self.sslmode is not None:
            connection_dict["sslmode"] = self.sslmode
        if self.service is not None:
            connection_dict["service"] = self.service
        if self.check_primary_key_unicity is not None:
            connection_dict["checkPrimaryKeyUnicity"] = self.check_primary_key_unicity
        if self.sql is not None:
            connection_dict["sql"] = self.sql
        return connection_dict

    @classmethod
    def from_qgis_decoded_uri(cls, decoded_uri: dict):
        return cls(
            key=decoded_uri["key"],
            schema=decoded_uri.get("schema"),
            table=decoded_uri["table"],
            geometry_column=decoded_uri.get("geometrycolumn"),
            dbname=decoded_uri.get("dbname"),
            host=decoded_uri.get("host"),
            password=decoded_uri.get("password"),
            port=int(decoded_uri.get("port")) if decoded_uri.get("port") is not None else None,
            type=int(decoded_uri.get("type")) if decoded_uri.get("type") is not None else None,
            username=decoded_uri.get("username") or decoded_uri.get("user"),
            srid=decoded_uri.get("srid"),
            sslmode=(
                int(decoded_uri.get("sslmode")) if decoded_uri.get("sslmode") is not None else None
            ),
            service=decoded_uri.get("service"),
            check_primary_key_unicity=decoded_uri.get("check_primary_key_unicity"),
            sql=decoded_uri.get("sql"),
        )

    @property
    def remote(self):
        return True
check_primary_key_unicity: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
dbname: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
geometry_column: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
host: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
key: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
password: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
port: int | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
redacted_fields: set property
remote property
schema: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
service: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
sql: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
srid: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
ssl_mode_text: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
sslmode: int | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
table: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
to_qgis_decoded_uri: dict property
type: int | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
username: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(key: str, table: str, schema: str | None = None, geometry_column: str | None = None, dbname: str | None = None, host: str | None = None, password: str | None = None, port: int | None = None, type: int | None = None, username: str | None = None, srid: str | None = None, sslmode: int | None = None, ssl_mode_text: str | None = None, service: str | None = None, check_primary_key_unicity: str | None = None, sql: str | None = None) -> None
from_qgis_decoded_uri(decoded_uri: dict) classmethod
Source code in src/qgis_server_light/interface/exporter/extract.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
@classmethod
def from_qgis_decoded_uri(cls, decoded_uri: dict):
    return cls(
        key=decoded_uri["key"],
        schema=decoded_uri.get("schema"),
        table=decoded_uri["table"],
        geometry_column=decoded_uri.get("geometrycolumn"),
        dbname=decoded_uri.get("dbname"),
        host=decoded_uri.get("host"),
        password=decoded_uri.get("password"),
        port=int(decoded_uri.get("port")) if decoded_uri.get("port") is not None else None,
        type=int(decoded_uri.get("type")) if decoded_uri.get("type") is not None else None,
        username=decoded_uri.get("username") or decoded_uri.get("user"),
        srid=decoded_uri.get("srid"),
        sslmode=(
            int(decoded_uri.get("sslmode")) if decoded_uri.get("sslmode") is not None else None
        ),
        service=decoded_uri.get("service"),
        check_primary_key_unicity=decoded_uri.get("check_primary_key_unicity"),
        sql=decoded_uri.get("sql"),
    )
Project dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/exporter/extract.py
782
783
784
785
@dataclass(repr=False)
class Project(BaseInterface):
    version: str = field(metadata={"type": "Element"})
    name: str = field(metadata={"type": "Element"})
name: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
version: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(version: str, name: str) -> None
Range dataclass

Bases: BaseInterface

Configuration of the QGIS Range editor widget.

Attributes:

  • minimum (float | None) –

    The smallest allowed value.

  • maximum (float | None) –

    The biggest allowed value.

  • step (float | None) –

    The step of the widget.

Source code in src/qgis_server_light/interface/exporter/extract.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
@dataclass(repr=False)
class Range(BaseInterface):
    """
    Configuration of the QGIS `Range` editor widget.

    Attributes:
        minimum: The smallest allowed value.
        maximum: The biggest allowed value.
        step: The step of the widget.
    """

    minimum: float | None = field(default=None, metadata={"type": "Element"})
    maximum: float | None = field(default=None, metadata={"type": "Element"})
    step: float | None = field(default=None, metadata={"type": "Element"})
maximum: float | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
minimum: float | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
step: float | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(minimum: float | None = None, maximum: float | None = None, step: float | None = None) -> None
Raster dataclass

Bases: DataSet

A real QGIS Raster job_layer_definition. That are usually all QgsRasterLayer in opposition to QgsVectorTileLayer which is not a real QgsRasterLayer.

Source code in src/qgis_server_light/interface/exporter/extract.py
670
671
672
673
674
675
676
@dataclass(repr=False)
class Raster(DataSet):
    """
    A real QGIS Raster job_layer_definition. That are usually all `QgsRasterLayer`
    in opposition to `QgsVectorTileLayer`
    which is not a real `QgsRasterLayer`.
    """
__init__(id: str, name: str, is_checked: bool, title: str, source: DataSource, driver: str, bbox: BBox | None = None, bbox_wgs84: BBox | None = None, crs: Crs | None = None, styles: list[Style] = list(), minimum_scale: float | None = None, maximum_scale: float | None = None, style_name: str = 'default', is_spatial: bool = True, is_background: bool = False) -> None
Relation dataclass

Bases: BaseInterface

Transportable form of a QGIS project relation (QgsRelation). The layers are exported as QGIS layer ids, they are not resolved.

Attributes:

  • id (str) –

    The id of the relation, referenced by RelationReference.relation_id.

  • name (str) –

    The human readable name of the relation.

  • referencing_layer_id (str) –

    The QGIS layer id of the referencing (child) layer.

  • referenced_layer_id (str) –

    The QGIS layer id of the referenced (parent) layer.

  • field_pairs (list[RelationFieldPair]) –

    The field pairs, more than one for composite keys.

  • strength (str) –

    The strength as named by QGIS, Association or Composition.

Source code in src/qgis_server_light/interface/exporter/extract.py
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
@dataclass(repr=False)
class Relation(BaseInterface):
    """
    Transportable form of a QGIS project relation (`QgsRelation`). The layers are
    exported as QGIS layer ids, they are not resolved.

    Attributes:
        id: The id of the relation, referenced by `RelationReference.relation_id`.
        name: The human readable name of the relation.
        referencing_layer_id: The QGIS layer id of the referencing (child) layer.
        referenced_layer_id: The QGIS layer id of the referenced (parent) layer.
        field_pairs: The field pairs, more than one for composite keys.
        strength: The strength as named by QGIS, `Association` or `Composition`.
    """

    id: str = field(metadata={"type": "Element"})
    name: str = field(metadata={"type": "Element"})
    referencing_layer_id: str = field(metadata={"type": "Element"})
    referenced_layer_id: str = field(metadata={"type": "Element"})
    field_pairs: list[RelationFieldPair] = field(
        default_factory=list,
        metadata={"type": "Element"},
    )
    strength: str = field(default="Association", metadata={"type": "Element"})
field_pairs: list[RelationFieldPair] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
name: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
referenced_layer_id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
referencing_layer_id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
strength: str = field(default='Association', metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, name: str, referencing_layer_id: str, referenced_layer_id: str, field_pairs: list[RelationFieldPair] = list(), strength: str = 'Association') -> None
RelationFieldPair dataclass

Bases: BaseInterface

One field pair of a QGIS project relation.

Attributes:

Source code in src/qgis_server_light/interface/exporter/extract.py
853
854
855
856
857
858
859
860
861
862
863
864
@dataclass(repr=False)
class RelationFieldPair(BaseInterface):
    """
    One field pair of a QGIS project relation.

    Attributes:
        referencing_field: The field of the referencing (child) layer.
        referenced_field: The field of the referenced (parent) layer.
    """

    referencing_field: str = field(metadata={"type": "Element"})
    referenced_field: str = field(metadata={"type": "Element"})
referenced_field: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
referencing_field: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(referencing_field: str, referenced_field: str) -> None
RelationReference dataclass

Bases: BaseInterface

Configuration of the QGIS RelationReference editor widget.

Attributes:

  • relation_id (str) –

    The id of the project relation, see Relation.id.

Source code in src/qgis_server_light/interface/exporter/extract.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
@dataclass(repr=False)
class RelationReference(BaseInterface):
    """
    Configuration of the QGIS `RelationReference` editor widget.

    Attributes:
        relation_id: The id of the project relation, see `Relation.id`.
    """

    relation_id: str = field(metadata={"type": "Element"})
relation_id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(relation_id: str) -> None
ResultWithMessages dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/exporter/extract.py
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
@dataclass(repr=False)
class ResultWithMessages(BaseInterface):
    project: Project = field(metadata={"type": "Element"})
    exporter: Exporter = field(metadata={"type": "Element"})
    messages: list[ExportMessage] = field(
        default_factory=list, kw_only=True, metadata={"type": "Element"}
    )

    def warning(self, message: str, code: ExportMessage.Code, layer_id: str | None = None):
        logging.warning(message, extra={"code": code, "layer_id": layer_id})
        self.messages.append(
            ExportMessage(ExportMessage.Level.WARNING, message, code=code, layer_id=layer_id)
        )

    def error(self, message: str, code: ExportMessage.Code, layer_id: str | None = None):
        logging.error(message, extra={"code": code, "layer_id": layer_id})
        self.messages.append(
            ExportMessage(ExportMessage.Level.ERROR, message, code=code, layer_id=layer_id)
        )

    @property
    def has_errors(self) -> bool:
        return any(m.level == ExportMessage.Level.ERROR for m in self.messages)
exporter: Exporter = field(metadata={'type': 'Element'}) class-attribute instance-attribute
has_errors: bool property
messages: list[ExportMessage] = field(default_factory=list, kw_only=True, metadata={'type': 'Element'}) class-attribute instance-attribute
project: Project = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(project: Project, exporter: Exporter, *, messages: list[ExportMessage] = list()) -> None
error(message: str, code: ExportMessage.Code, layer_id: str | None = None)
Source code in src/qgis_server_light/interface/exporter/extract.py
940
941
942
943
944
def error(self, message: str, code: ExportMessage.Code, layer_id: str | None = None):
    logging.error(message, extra={"code": code, "layer_id": layer_id})
    self.messages.append(
        ExportMessage(ExportMessage.Level.ERROR, message, code=code, layer_id=layer_id)
    )
warning(message: str, code: ExportMessage.Code, layer_id: str | None = None)
Source code in src/qgis_server_light/interface/exporter/extract.py
934
935
936
937
938
def warning(self, message: str, code: ExportMessage.Code, layer_id: str | None = None):
    logging.warning(message, extra={"code": code, "layer_id": layer_id})
    self.messages.append(
        ExportMessage(ExportMessage.Level.WARNING, message, code=code, layer_id=layer_id)
    )
Service dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/exporter/extract.py
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
@dataclass(repr=False)
class Service(BaseInterface):
    contact_organization: str | None = field(metadata={"type": "Element"})
    contact_mail: str | None = field(metadata={"type": "Element"})
    contact_person: str | None = field(
        default=None,
        metadata={"type": "Element"},
    )
    contact_phone: str | None = field(
        default=None,
        metadata={"type": "Element"},
    )
    contact_position: str | None = field(
        default=None,
        metadata={"type": "Element"},
    )
    fees: str | None = field(default=None, metadata={"type": "Element"})
    keyword_list: str | None = field(
        default=None,
        metadata={"type": "Element"},
    )
    online_resource: str | None = field(
        default=None,
        metadata={"type": "Element"},
    )
    service_abstract: str | None = field(
        default=None,
        metadata={"type": "Element"},
    )
    service_title: str | None = field(
        default=None,
        metadata={"type": "Element"},
    )
    resource_url: str | None = field(default=None, metadata={"type": "Element"})
contact_mail: str | None = field(metadata={'type': 'Element'}) class-attribute instance-attribute
contact_organization: str | None = field(metadata={'type': 'Element'}) class-attribute instance-attribute
contact_person: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
contact_phone: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
contact_position: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
fees: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
keyword_list: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
online_resource: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
resource_url: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
service_abstract: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
service_title: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(contact_organization: str | None, contact_mail: str | None, contact_person: str | None = None, contact_phone: str | None = None, contact_position: str | None = None, fees: str | None = None, keyword_list: str | None = None, online_resource: str | None = None, service_abstract: str | None = None, service_title: str | None = None, resource_url: str | None = None) -> None
Source dataclass

Bases: BaseInterface, ABC

Source code in src/qgis_server_light/interface/exporter/extract.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
@dataclass(repr=False)
class Source(BaseInterface, ABC):
    @staticmethod
    def decide_remote(path: str) -> bool:
        return path.startswith("http")

    @property
    def to_qgis_decoded_uri(self) -> dict:
        raise NotImplementedError(
            "This is a base class, the method has to be defined at implementation level."
        )

    @classmethod
    def from_qgis_decoded_uri(cls, decoded_uri: dict):
        raise NotImplementedError(
            "This is a base class, the method has to be defined at implementation level."
        )
to_qgis_decoded_uri: dict property
__init__() -> None
decide_remote(path: str) -> bool staticmethod
Source code in src/qgis_server_light/interface/exporter/extract.py
229
230
231
@staticmethod
def decide_remote(path: str) -> bool:
    return path.startswith("http")
from_qgis_decoded_uri(decoded_uri: dict) classmethod
Source code in src/qgis_server_light/interface/exporter/extract.py
239
240
241
242
243
@classmethod
def from_qgis_decoded_uri(cls, decoded_uri: dict):
    raise NotImplementedError(
        "This is a base class, the method has to be defined at implementation level."
    )
Tree dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/exporter/extract.py
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
@dataclass(repr=False)
class Tree(BaseInterface):
    members: list[TreeGroup] = field(
        default_factory=list,
        metadata={"type": "Element"},
    )

    @property
    def root(self):
        return self.find_by_name("")

    def find_by_name(self, name: str) -> TreeGroup | None:
        for member in self.members:
            if member.name == name:
                return member
        return None

    def find_by_id(self, identifier: str) -> TreeGroup | None:
        for member in self.members:
            if member.id == identifier:
                return member
        return None
members: list[TreeGroup] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
root property
__init__(members: list[TreeGroup] = list()) -> None
find_by_id(identifier: str) -> TreeGroup | None
Source code in src/qgis_server_light/interface/exporter/extract.py
805
806
807
808
809
def find_by_id(self, identifier: str) -> TreeGroup | None:
    for member in self.members:
        if member.id == identifier:
            return member
    return None
find_by_name(name: str) -> TreeGroup | None
Source code in src/qgis_server_light/interface/exporter/extract.py
799
800
801
802
803
def find_by_name(self, name: str) -> TreeGroup | None:
    for member in self.members:
        if member.name == name:
            return member
    return None
TreeGroup dataclass

Bases: TreeLayer

Source code in src/qgis_server_light/interface/exporter/extract.py
28
29
30
31
@dataclass(repr=False)
class TreeGroup(TreeLayer):
    children: list[str] = field(metadata={"type": "Element"})
    is_expanded: bool = field(metadata={"type": "Element"})
children: list[str] = field(metadata={'type': 'Element'}) class-attribute instance-attribute
is_expanded: bool = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, name: str, is_checked: bool, children: list[str], is_expanded: bool) -> None
TreeLayer dataclass

Bases: LayerLike

Source code in src/qgis_server_light/interface/exporter/extract.py
23
24
25
@dataclass(repr=False)
class TreeLayer(LayerLike):
    pass
__init__(id: str, name: str, is_checked: bool) -> None
ValueMap dataclass

Bases: BaseInterface

Configuration of the QGIS ValueMap editor widget.

Attributes:

  • entries (list[ValueMapEntry]) –

    The key / description pairs in the order defined in QGIS. The entry representing NULL is not part of it.

  • null_representation (str | None) –

    The description QGIS shows for NULL, if the widget defines one.

Source code in src/qgis_server_light/interface/exporter/extract.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
@dataclass(repr=False)
class ValueMap(BaseInterface):
    """
    Configuration of the QGIS `ValueMap` editor widget.

    Attributes:
        entries: The key / description pairs in the order defined in QGIS. The entry
            representing NULL is not part of it.
        null_representation: The description QGIS shows for NULL, if the widget
            defines one.
    """

    entries: list[ValueMapEntry] = field(
        default_factory=list,
        metadata={"type": "Element"},
    )
    null_representation: str | None = field(default=None, metadata={"type": "Element"})
entries: list[ValueMapEntry] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
null_representation: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(entries: list[ValueMapEntry] = list(), null_representation: str | None = None) -> None
ValueMapEntry dataclass

Bases: BaseInterface

One entry of a QGIS ValueMap editor widget.

Attributes:

  • key (str) –

    The value which is stored in the field.

  • description (str) –

    The human readable representation of the value.

Source code in src/qgis_server_light/interface/exporter/extract.py
34
35
36
37
38
39
40
41
42
43
44
45
@dataclass(repr=False)
class ValueMapEntry(BaseInterface):
    """
    One entry of a QGIS `ValueMap` editor widget.

    Attributes:
        key: The value which is stored in the field.
        description: The human readable representation of the value.
    """

    key: str = field(metadata={"type": "Element"})
    description: str = field(metadata={"type": "Element"})
description: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
key: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(key: str, description: str) -> None
ValueRelation dataclass

Bases: BaseInterface

Configuration of the QGIS ValueRelation editor widget. The referenced layer is exported as QGIS layer id, it is not resolved.

Attributes:

  • layer_id (str) –

    The QGIS layer id of the layer the values are taken from.

  • key_field (str) –

    The field of the referenced layer which is stored.

  • value_field (str) –

    The field of the referenced layer which is shown.

  • filter_expression (str | None) –

    The QGIS expression to filter the referenced layer. It may use form context functions like current_value().

  • allow_multi (bool) –

    If more than one value can be selected.

  • order_by_value (bool) –

    If the values are ordered by the value field instead of the key field.

Source code in src/qgis_server_light/interface/exporter/extract.py
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
@dataclass(repr=False)
class ValueRelation(BaseInterface):
    """
    Configuration of the QGIS `ValueRelation` editor widget. The referenced layer is
    exported as QGIS layer id, it is not resolved.

    Attributes:
        layer_id: The QGIS layer id of the layer the values are taken from.
        key_field: The field of the referenced layer which is stored.
        value_field: The field of the referenced layer which is shown.
        filter_expression: The QGIS expression to filter the referenced layer. It may
            use form context functions like `current_value()`.
        allow_multi: If more than one value can be selected.
        order_by_value: If the values are ordered by the value field instead of the
            key field.
    """

    layer_id: str = field(metadata={"type": "Element"})
    key_field: str = field(metadata={"type": "Element"})
    value_field: str = field(metadata={"type": "Element"})
    filter_expression: str | None = field(default=None, metadata={"type": "Element"})
    allow_multi: bool = field(default=False, metadata={"type": "Element"})
    order_by_value: bool = field(default=False, metadata={"type": "Element"})
allow_multi: bool = field(default=False, metadata={'type': 'Element'}) class-attribute instance-attribute
filter_expression: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
key_field: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
layer_id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
order_by_value: bool = field(default=False, metadata={'type': 'Element'}) class-attribute instance-attribute
value_field: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(layer_id: str, key_field: str, value_field: str, filter_expression: str | None = None, allow_multi: bool = False, order_by_value: bool = False) -> None
Vector dataclass

Bases: DataSet

A real QGIS Vector job_layer_definition. That are usually all QgsVectorLayer in opposition to QgsVectorTileLayer which is not a real QgsVectorLayer.

Source code in src/qgis_server_light/interface/exporter/extract.py
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
@dataclass(repr=False)
class Vector(DataSet):
    """
    A real QGIS Vector job_layer_definition. That are usually all `QgsVectorLayer`
    in opposition to `QgsVectorTileLayer`
    which is not a real `QgsVectorLayer`.
    """

    fields: list[Field] = field(
        default_factory=list,
        metadata={"type": "Element"},
    )
    geometry_type_simple: str | None = field(
        default=None,
        metadata={"type": "Element"},
    )
    geometry_type_wkb: str | None = field(
        default=None,
        metadata={"type": "Element"},
    )

    def get_field_by_name(self, name: str) -> Field | None:
        for dataclass_field in self.fields:
            if dataclass_field.name == name:
                return dataclass_field
        return None
fields: list[Field] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
geometry_type_simple: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
geometry_type_wkb: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, name: str, is_checked: bool, title: str, source: DataSource, driver: str, bbox: BBox | None = None, bbox_wgs84: BBox | None = None, crs: Crs | None = None, styles: list[Style] = list(), minimum_scale: float | None = None, maximum_scale: float | None = None, style_name: str = 'default', is_spatial: bool = True, is_background: bool = False, fields: list[Field] = list(), geometry_type_simple: str | None = None, geometry_type_wkb: str | None = None) -> None
get_field_by_name(name: str) -> Field | None
Source code in src/qgis_server_light/interface/exporter/extract.py
700
701
702
703
704
def get_field_by_name(self, name: str) -> Field | None:
    for dataclass_field in self.fields:
        if dataclass_field.name == name:
            return dataclass_field
    return None
VectorTileSource dataclass

Bases: Source

Source code in src/qgis_server_light/interface/exporter/extract.py
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
@dataclass(repr=False)
class VectorTileSource(Source):
    type: str = field(metadata={"type": "Element"})
    zmin: int | None = field(metadata={"type": "Element"})
    zmax: int | None = field(metadata={"type": "Element"})
    url: str | None = field(default=None, metadata={"type": "Element"})
    path: str | None = field(default=None, metadata={"type": "Element"})
    style_url: str | None = field(default=None, metadata={"type": "Element"})

    @property
    def remote(self):
        return self.decide_remote(self.path or self.url)

    @property
    def to_qgis_decoded_uri(self) -> dict:
        connection_dict = {"type": self.type, "zmin": self.zmin, "zmax": self.zmax}
        if self.url is not None:
            connection_dict["url"] = self.url
        if self.path is not None:
            connection_dict["path"] = self.path
        if self.style_url is not None:
            connection_dict["styleUrl"] = self.style_url
        return connection_dict

    @classmethod
    def from_qgis_decoded_uri(cls, decoded_uri: dict):
        return cls(
            type=decoded_uri["type"],
            zmin=decoded_uri.get("zmin"),
            zmax=decoded_uri.get("zmax"),
            url=decoded_uri.get("url"),
            path=decoded_uri.get("path"),
            style_url=decoded_uri.get("styleUrl"),
        )
path: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
remote property
style_url: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
to_qgis_decoded_uri: dict property
type: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
url: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
zmax: int | None = field(metadata={'type': 'Element'}) class-attribute instance-attribute
zmin: int | None = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(type: str, zmin: int | None, zmax: int | None, url: str | None = None, path: str | None = None, style_url: str | None = None) -> None
from_qgis_decoded_uri(decoded_uri: dict) classmethod
Source code in src/qgis_server_light/interface/exporter/extract.py
598
599
600
601
602
603
604
605
606
607
@classmethod
def from_qgis_decoded_uri(cls, decoded_uri: dict):
    return cls(
        type=decoded_uri["type"],
        zmin=decoded_uri.get("zmin"),
        zmax=decoded_uri.get("zmax"),
        url=decoded_uri.get("url"),
        path=decoded_uri.get("path"),
        style_url=decoded_uri.get("styleUrl"),
    )
WcsSource dataclass

Bases: Source

Source of a layer of the QGIS wcs provider. The attributes are the uri parameters read by the provider (QgsWcsProvider::parseUri and QgsWcsCapabilities in QGIS src/providers/wcs). Credentials (username, password, authcfg) and http headers are intentionally not exported.

Source code in src/qgis_server_light/interface/exporter/extract.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
@dataclass(repr=False)
class WcsSource(Source):
    """
    Source of a layer of the QGIS `wcs` provider. The attributes are the uri
    parameters read by the provider (`QgsWcsProvider::parseUri` and
    `QgsWcsCapabilities` in QGIS `src/providers/wcs`). Credentials (`username`,
    `password`, `authcfg`) and http headers are intentionally not exported.
    """

    url: str = field(metadata={"type": "Element"})
    identifier: str = field(metadata={"type": "Element"})
    crs: str | None = field(default=None, metadata={"type": "Element"})
    format: str | None = field(default=None, metadata={"type": "Element"})
    time: str | None = field(default=None, metadata={"type": "Element"})
    bbox: str | None = field(default=None, metadata={"type": "Element"})
    version: str | None = field(default=None, metadata={"type": "Element"})
    cache: str | None = field(default=None, metadata={"type": "Element"})
    # workarounds for misconfigured servers, set from the checkboxes of the QGIS WCS
    # connection. The provider enables them when the parameter is present in the
    # uri, whatever its value.
    ignore_get_map_url: bool = field(default=False, metadata={"type": "Element"})
    ignore_axis_orientation: bool = field(default=False, metadata={"type": "Element"})
    invert_axis_orientation: bool = field(default=False, metadata={"type": "Element"})

    @property
    def to_qgis_decoded_uri(self) -> dict:
        connection_dict = {
            "url": self.url,
            "identifier": self.identifier,
            "crs": self.crs,
            "format": self.format,
            "time": self.time,
            "bbox": self.bbox,
            "version": self.version,
            "cache": self.cache,
        }
        # the WCS provider applies its own defaults to the missing keys
        connection_dict = {
            key: value for key, value in connection_dict.items() if value is not None
        }
        # "1" is the value QGIS writes for these parameters
        if self.ignore_get_map_url:
            connection_dict["IgnoreGetMapUrl"] = "1"
        if self.ignore_axis_orientation:
            connection_dict["IgnoreAxisOrientation"] = "1"
        if self.invert_axis_orientation:
            connection_dict["InvertAxisOrientation"] = "1"
        return connection_dict

    @classmethod
    def from_qgis_decoded_uri(cls, decoded_uri: dict):
        return cls(
            url=decoded_uri["url"],
            identifier=decoded_uri["identifier"],
            crs=decoded_uri.get("crs"),
            format=decoded_uri.get("format"),
            time=decoded_uri.get("time"),
            bbox=decoded_uri.get("bbox"),
            version=decoded_uri.get("version"),
            cache=decoded_uri.get("cache"),
            ignore_get_map_url="IgnoreGetMapUrl" in decoded_uri,
            ignore_axis_orientation="IgnoreAxisOrientation" in decoded_uri,
            invert_axis_orientation="InvertAxisOrientation" in decoded_uri,
        )

    @property
    def remote(self):
        return True
bbox: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
cache: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
crs: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
format: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
identifier: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
ignore_axis_orientation: bool = field(default=False, metadata={'type': 'Element'}) class-attribute instance-attribute
ignore_get_map_url: bool = field(default=False, metadata={'type': 'Element'}) class-attribute instance-attribute
invert_axis_orientation: bool = field(default=False, metadata={'type': 'Element'}) class-attribute instance-attribute
remote property
time: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
to_qgis_decoded_uri: dict property
url: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
version: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(url: str, identifier: str, crs: str | None = None, format: str | None = None, time: str | None = None, bbox: str | None = None, version: str | None = None, cache: str | None = None, ignore_get_map_url: bool = False, ignore_axis_orientation: bool = False, invert_axis_orientation: bool = False) -> None
from_qgis_decoded_uri(decoded_uri: dict) classmethod
Source code in src/qgis_server_light/interface/exporter/extract.py
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
@classmethod
def from_qgis_decoded_uri(cls, decoded_uri: dict):
    return cls(
        url=decoded_uri["url"],
        identifier=decoded_uri["identifier"],
        crs=decoded_uri.get("crs"),
        format=decoded_uri.get("format"),
        time=decoded_uri.get("time"),
        bbox=decoded_uri.get("bbox"),
        version=decoded_uri.get("version"),
        cache=decoded_uri.get("cache"),
        ignore_get_map_url="IgnoreGetMapUrl" in decoded_uri,
        ignore_axis_orientation="IgnoreAxisOrientation" in decoded_uri,
        invert_axis_orientation="InvertAxisOrientation" in decoded_uri,
    )
WfsSource dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/exporter/extract.py
304
305
306
307
308
@dataclass(repr=False)
class WfsSource(BaseInterface):
    # currently not implemented because qgis does not allow to
    # use the decode uri approach on that URI
    pass
__init__() -> None
WmsSource dataclass

Bases: Source

Source code in src/qgis_server_light/interface/exporter/extract.py
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
@dataclass(repr=False)
class WmsSource(Source):
    crs: str = field(metadata={"type": "Element"})
    format: str = field(metadata={"type": "Element"})
    layers: str = field(metadata={"type": "Element"})
    url: str = field(metadata={"type": "Element"})
    dpi_mode: str | None = field(default=None, metadata={"type": "Element"})
    feature_count: int | None = field(default=None, metadata={"type": "Element"})
    contextual_wms_legend: str | None = field(default=None, metadata={"type": "Element"})
    styles: str | None = field(default=None, metadata={"type": "Element"})

    @property
    def to_qgis_decoded_uri(self) -> dict:
        connection_dict = {
            "crs": self.crs,
            "format": self.format,
            "layers": self.layers,
            "url": self.url,
            "styles": self.styles,
        }
        if self.dpi_mode is not None:
            connection_dict["dpiMode"] = self.dpi_mode
        if self.feature_count is not None:
            connection_dict["featureCount"] = self.feature_count
        if self.contextual_wms_legend is not None:
            connection_dict["contextualWMSLegend"] = self.contextual_wms_legend
        return connection_dict

    @classmethod
    def from_qgis_decoded_uri(cls, decoded_uri: dict):
        return cls(
            crs=decoded_uri["crs"],
            format=decoded_uri["format"],
            layers=decoded_uri["layers"],
            url=decoded_uri["url"],
            dpi_mode=decoded_uri.get("dpiMode"),
            feature_count=decoded_uri.get("featureCount"),
            contextual_wms_legend=decoded_uri.get("contextualWMSLegend"),
            styles=decoded_uri.get("styles"),
        )

    @property
    def remote(self):
        return True
contextual_wms_legend: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
crs: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
dpi_mode: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
feature_count: int | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
format: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
layers: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
remote property
styles: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
to_qgis_decoded_uri: dict property
url: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(crs: str, format: str, layers: str, url: str, dpi_mode: str | None = None, feature_count: int | None = None, contextual_wms_legend: str | None = None, styles: str | None = None) -> None
from_qgis_decoded_uri(decoded_uri: dict) classmethod
Source code in src/qgis_server_light/interface/exporter/extract.py
370
371
372
373
374
375
376
377
378
379
380
381
@classmethod
def from_qgis_decoded_uri(cls, decoded_uri: dict):
    return cls(
        crs=decoded_uri["crs"],
        format=decoded_uri["format"],
        layers=decoded_uri["layers"],
        url=decoded_uri["url"],
        dpi_mode=decoded_uri.get("dpiMode"),
        feature_count=decoded_uri.get("featureCount"),
        contextual_wms_legend=decoded_uri.get("contextualWMSLegend"),
        styles=decoded_uri.get("styles"),
    )
WmtsSource dataclass

Bases: WmsSource

Source code in src/qgis_server_light/interface/exporter/extract.py
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
@dataclass(repr=False, kw_only=True)
class WmtsSource(WmsSource):
    tile_matrix_set: str = field(metadata={"type": "Element"})
    tile_dimensions: str | None = field(
        default=None,
        metadata={"type": "Element"},
    )
    tile_pixel_ratio: str | None = field(default=None, metadata={"type": "Element"})

    @property
    def to_qgis_decoded_uri(self) -> dict:
        connection_dict = super().to_qgis_decoded_uri
        connection_dict["tileMatrixSet"] = self.tile_matrix_set
        if self.tile_dimensions is not None:
            connection_dict["tileDimensions"] = self.tile_dimensions
        if self.tile_pixel_ratio is not None:
            connection_dict["tilePixelRatio"] = self.tile_pixel_ratio
        return connection_dict

    @classmethod
    def from_qgis_decoded_uri(cls, decoded_uri: dict):
        base_class_instance = WmsSource.from_qgis_decoded_uri(decoded_uri)
        return cls(
            crs=base_class_instance.crs,
            format=base_class_instance.format,
            layers=base_class_instance.layers,
            url=base_class_instance.url,
            dpi_mode=base_class_instance.dpi_mode,
            feature_count=base_class_instance.feature_count,
            contextual_wms_legend=base_class_instance.contextual_wms_legend,
            styles=base_class_instance.styles,
            tile_matrix_set=decoded_uri["tileMatrixSet"],
            tile_dimensions=decoded_uri.get("tileDimensions"),
            tile_pixel_ratio=decoded_uri.get("tilePixelRatio"),
        )
tile_dimensions: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
tile_matrix_set: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
tile_pixel_ratio: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
to_qgis_decoded_uri: dict property
__init__(crs: str, format: str, layers: str, url: str, dpi_mode: str | None = None, feature_count: int | None = None, contextual_wms_legend: str | None = None, styles: str | None = None, *, tile_matrix_set: str, tile_dimensions: str | None = None, tile_pixel_ratio: str | None = None) -> None
from_qgis_decoded_uri(decoded_uri: dict) classmethod
Source code in src/qgis_server_light/interface/exporter/extract.py
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
@classmethod
def from_qgis_decoded_uri(cls, decoded_uri: dict):
    base_class_instance = WmsSource.from_qgis_decoded_uri(decoded_uri)
    return cls(
        crs=base_class_instance.crs,
        format=base_class_instance.format,
        layers=base_class_instance.layers,
        url=base_class_instance.url,
        dpi_mode=base_class_instance.dpi_mode,
        feature_count=base_class_instance.feature_count,
        contextual_wms_legend=base_class_instance.contextual_wms_legend,
        styles=base_class_instance.styles,
        tile_matrix_set=decoded_uri["tileMatrixSet"],
        tile_dimensions=decoded_uri.get("tileDimensions"),
        tile_pixel_ratio=decoded_uri.get("tilePixelRatio"),
    )
XYZSource dataclass

Bases: Source

Source code in src/qgis_server_light/interface/exporter/extract.py
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
@dataclass(repr=False)
class XYZSource(Source):
    url: str = field(metadata={"type": "Element"})
    zmin: int | None = field(default=None, metadata={"type": "Element"})
    zmax: int | None = field(default=None, metadata={"type": "Element"})
    type: str | None = field(default=None, metadata={"type": "Element"})

    @property
    def to_qgis_decoded_uri(self) -> dict:
        connection_dict = {
            "url": self.url,
            "zmin": self.zmin,
            "zmax": self.zmax,
            "type": self.type,
        }
        return connection_dict

    @classmethod
    def from_qgis_decoded_uri(cls, decoded_uri: dict):
        return cls(
            url=decoded_uri["url"],
            zmin=decoded_uri.get("zmin"),
            zmax=decoded_uri.get("zmax"),
            type=decoded_uri.get("type"),
        )

    @property
    def remote(self):
        return self.decide_remote(self.url)
remote property
to_qgis_decoded_uri: dict property
type: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
url: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
zmax: int | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
zmin: int | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(url: str, zmin: int | None = None, zmax: int | None = None, type: str | None = None) -> None
from_qgis_decoded_uri(decoded_uri: dict) classmethod
Source code in src/qgis_server_light/interface/exporter/extract.py
328
329
330
331
332
333
334
335
@classmethod
def from_qgis_decoded_uri(cls, decoded_uri: dict):
    return cls(
        url=decoded_uri["url"],
        zmin=decoded_uri.get("zmin"),
        zmax=decoded_uri.get("zmax"),
        type=decoded_uri.get("type"),
    )

job

common
input
AbstractFilter dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/job/common/input.py
66
67
68
69
70
71
72
@dataclass(repr=False)
class AbstractFilter(BaseInterface):
    definition: str = field(metadata={"type": "Element"})

    @property
    def shortened_fields(self) -> set:
        return {"definition"}
definition: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
shortened_fields: set property
__init__(definition: str) -> None
ExecutionMode

Bases: Enum

If the dispatcher waits for the job (SYNC) or asks for its state later (ASYNC). Only jobs which keep their state (RedisStateProtocol) use it.

Source code in src/qgis_server_light/interface/job/common/input.py
17
18
19
20
21
22
23
class ExecutionMode(Enum):
    """If the dispatcher waits for the job (`SYNC`) or asks for its state later
    (`ASYNC`). Only jobs which keep their state (`RedisStateProtocol`) use it.
    """

    SYNC = "sync"
    ASYNC = "async"
ASYNC = 'async' class-attribute instance-attribute
SYNC = 'sync' class-attribute instance-attribute
OgcFilter110 dataclass

Bases: AbstractFilter

A filter which definition conforms to https://schemas.opengis.net/filter/1.1.0/filter.xsd and which is consumable by qgis.core.QgsOgcUtils.expressionFromOgcFilter.

Source code in src/qgis_server_light/interface/job/common/input.py
75
76
77
78
79
80
81
@dataclass(repr=False)
class OgcFilter110(AbstractFilter):
    """
    A filter which definition conforms to
    https://schemas.opengis.net/filter/1.1.0/filter.xsd
    and which is consumable by `qgis.core.QgsOgcUtils.expressionFromOgcFilter`.
    """
__init__(definition: str) -> None
OgcFilterFES20 dataclass

Bases: AbstractFilter

A filter which definition conforms to https://www.opengis.net/fes/2.0 and which is consumable by qgis.core.QgsOgcUtils.expressionFromOgcFilter.

Source code in src/qgis_server_light/interface/job/common/input.py
84
85
86
87
88
89
@dataclass(repr=False)
class OgcFilterFES20(AbstractFilter):
    """
    A filter which definition conforms to https://www.opengis.net/fes/2.0
    and which is consumable by `qgis.core.QgsOgcUtils.expressionFromOgcFilter`.
    """
__init__(definition: str) -> None
QslJobInfoParameter dataclass

Bases: ABC

The common minimal interface of a job which is shipped around. Each job for QSL has to implement at least this interface.

Attributes:

  • id (str) –

    The unique identifier which is used to recognize the job all over its lifecycle.

  • type (str) –

    A string based identifier of the job, this is used to quickly determine its nature serialized state.

  • job (QslJobParameter) –

    The actual job parameters. This is a domain specific dataclass depending on the nature of the actual job.

  • execution_mode (ExecutionMode) –

    With ExecutionMode.SYNC the worker notifies the waiting dispatcher when the job is finished. Only used by jobs which keep their state.

Source code in src/qgis_server_light/interface/job/common/input.py
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
@dataclass
class QslJobInfoParameter(ABC):  # noqa: B024
    """The common minimal interface of a job which is
    shipped around. Each job for QSL has to implement at least this
    interface.

    Attributes:
        id: The unique identifier which is used to recognize the job
            all over its lifecycle.
        type: A string based identifier of the job, this is used to quickly
            determine its nature serialized state.
        job: The actual job parameters. This is a domain specific dataclass
            depending on the nature of the actual job.
        execution_mode: With `ExecutionMode.SYNC` the worker notifies the waiting
            dispatcher when the job is finished. Only used by jobs which keep their
            state.
    """

    id: str = field(metadata={"type": "Element"})
    type: str = field(metadata={"type": "Element"})
    job: QslJobParameter = field(metadata={"type": "Element"})
    execution_mode: ExecutionMode = field(metadata={"type": "Element"}, default=ExecutionMode.SYNC)

    @property
    def channel_name(self) -> str:
        return f"notification_{self.execution_mode.value}"
channel_name: str property
execution_mode: ExecutionMode = field(metadata={'type': 'Element'}, default=(ExecutionMode.SYNC)) class-attribute instance-attribute
id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
job: QslJobParameter = field(metadata={'type': 'Element'}) class-attribute instance-attribute
type: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, type: str, job: QslJobParameter, execution_mode: ExecutionMode = ExecutionMode.SYNC) -> None
QslJobLayer dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/job/common/input.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
@dataclass(repr=False)
class QslJobLayer(BaseInterface):
    id: str = field(metadata={"type": "Element"})
    name: str = field(metadata={"type": "Element"})
    source: str = field(metadata={"type": "Element"})
    remote: bool = field(metadata={"type": "Element"})
    folder_name: str = field(metadata={"type": "Element"})
    driver: str = field(metadata={"type": "Element"})
    style: Style | None = field(default=None, metadata={"type": "Element"})
    filter: OgcFilter110 | OgcFilterFES20 | None = field(default=None, metadata={"type": "Element"})

    @property
    def redacted_fields(self) -> set:
        return {"source"}
driver: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
filter: OgcFilter110 | OgcFilterFES20 | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
folder_name: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
name: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
redacted_fields: set property
remote: bool = field(metadata={'type': 'Element'}) class-attribute instance-attribute
source: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
style: Style | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, name: str, source: str, remote: bool, folder_name: str, driver: str, style: Style | None = None, filter: OgcFilter110 | OgcFilterFES20 | None = None) -> None
QslJobParameter dataclass

Bases: ABC

The minimal interface of a job parameter interface. In the domain specific refinement it holds the relevant information about a job.

Source code in src/qgis_server_light/interface/job/common/input.py
 8
 9
10
11
12
13
14
@dataclass
class QslJobParameter(ABC):  # noqa: B024
    """The minimal interface of a job parameter interface. In the domain
    specific refinement it holds the relevant information about a job.
    """

    pass
__init__() -> None
QslJobParameterMapRelated dataclass

Bases: QslJobParameter

The minimal interface of a job parameter interface for jobs rendering things in the end.

Attributes:

  • svg_paths (list[str]) –

    A list of paths to svg's (folders) which are necessary for the job to render nicely.

Source code in src/qgis_server_light/interface/job/common/input.py
54
55
56
57
58
59
60
61
62
63
@dataclass
class QslJobParameterMapRelated(QslJobParameter):
    """The minimal interface of a job parameter interface for jobs rendering things in the end.

    Attributes:
        svg_paths: A list of paths to svg's (folders) which are necessary for
            the job to render nicely.
    """

    svg_paths: list[str] = field(default_factory=list, metadata={"type": "Element"})
svg_paths: list[str] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(svg_paths: list[str] = list()) -> None
output
JobResult dataclass

Bases: BaseInterface

Source code in src/qgis_server_light/interface/job/common/output.py
 7
 8
 9
10
11
12
13
14
15
16
17
@dataclass
class JobResult(BaseInterface):
    id: str = field(metadata={"type": "Element"})
    data: Any = field(metadata={"type": "Element"})
    content_type: str = field(metadata={"type": "Element"})
    worker_id: str | None = field(default=None, metadata={"type": "Element"})
    worker_host_name: str | None = field(default=None, metadata={"type": "Element"})

    @property
    def shortened_fields(self) -> set:
        return {"data"}
content_type: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
data: Any = field(metadata={'type': 'Element'}) class-attribute instance-attribute
id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
shortened_fields: set property
worker_host_name: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
worker_id: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, data: Any, content_type: str, worker_id: str | None = None, worker_host_name: str | None = None) -> None
crs
input
QslJobInfoCrs dataclass

Bases: QslJobInfoParameter

Source code in src/qgis_server_light/interface/job/crs/input.py
22
23
24
@dataclass
class QslJobInfoCrs(QslJobInfoParameter):
    job: QslJobParameterCrs = field(metadata={"type": "Element"})
job: QslJobParameterCrs = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, type: str, job: QslJobParameterCrs, execution_mode: ExecutionMode = ExecutionMode.SYNC) -> None
QslJobParameterCrs dataclass

Bases: QslJobParameter

Resolves crs identifiers into the full crs information as QGIS knows it. This way consuming applications get all identifiers and the axis order without own crs knowledge.

Attributes:

  • identifiers (list[str]) –

    The crs identifiers to resolve, e.g. EPSG:4326, URN or URI notation.

Source code in src/qgis_server_light/interface/job/crs/input.py
 9
10
11
12
13
14
15
16
17
18
19
@dataclass
class QslJobParameterCrs(QslJobParameter):
    """Resolves crs identifiers into the full crs information as QGIS knows it. This way
    consuming applications get all identifiers and the axis order without own crs
    knowledge.

    Attributes:
        identifiers: The crs identifiers to resolve, e.g. `EPSG:4326`, URN or URI notation.
    """

    identifiers: list[str] = field(metadata={"type": "Element"})
identifiers: list[str] = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(identifiers: list[str]) -> None
output
CrsCollection dataclass

Bases: BaseInterface

Holds the resolved crs. The order in the list has to be not changed, so that consuming applications can map the response to the passed identifiers.

Attributes:

  • crs (list[Crs]) –

    The resolved crs in the order of the passed identifiers.

Source code in src/qgis_server_light/interface/job/crs/output.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@dataclass(repr=False)
class CrsCollection(BaseInterface):
    """Holds the resolved crs. The order in the list has to be not changed, so that
    consuming applications can map the response to the passed identifiers.

    Attributes:
        crs: The resolved crs in the order of the passed identifiers.
    """

    crs: list[Crs] = field(
        default_factory=list,
        metadata={"type": "Element"},
    )
crs: list[Crs] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(crs: list[Crs] = list()) -> None
feature
input
FeatureQuery dataclass

Bases: BaseInterface

Represents definitions of a query to obtain features from a list of layers. Be aware, that filters are not applied to the QslJobLayer in this implementation since passed filters can contain inter-layer-references.

Attributes:

  • layers (list[QslJobLayer]) –

    A list layers which should only reference vector sources and be queried.

  • aliases (list[str]) –

    An optional list of alias names. This has to be the same length as the

  • filter (OgcFilterFES20) –

    An optional filter which might reference all passed layers thats why layers has to be added

  • crs (Crs | None) –

    An optional crs the geometries of the features are transformed to. If not set, geometries stay in the crs of the layer.

Source code in src/qgis_server_light/interface/job/feature/input.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@dataclass
class FeatureQuery(BaseInterface):
    """Represents definitions of a query to obtain features from a list of layers.
    Be aware, that filters are not applied to the QslJobLayer in this implementation
    since passed filters can contain inter-layer-references.

    Attributes:
        layers: A list layers which should only reference vector sources and be queried.
        aliases: An optional list of alias names. This has to be the same length as the
        list of datasets.
        filter: An optional filter which might reference all passed layers thats why layers
            has to be added
        crs: An optional crs the geometries of the features are transformed to. If not
            set, geometries stay in the crs of the layer.
    """

    layers: list[QslJobLayer] = field(metadata={"type": "Element"})
    aliases: list[str] = field(default_factory=list, metadata={"type": "Element"})
    filter: OgcFilterFES20 = field(default=None, metadata={"type": "Element"})
    crs: Crs | None = field(default=None, metadata={"type": "Element"})
aliases: list[str] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
crs: Crs | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
filter: OgcFilterFES20 = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
layers: list[QslJobLayer] = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(layers: list[QslJobLayer], aliases: list[str] = list(), filter: OgcFilterFES20 = None, crs: Crs | None = None) -> None
QslJobInfoFeature dataclass

Bases: QslJobInfoParameter

Source code in src/qgis_server_light/interface/job/feature/input.py
60
61
62
@dataclass
class QslJobInfoFeature(QslJobInfoParameter):
    job: QslJobParameterFeature = field(metadata={"type": "Element"})
job: QslJobParameterFeature = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, type: str, job: QslJobParameterFeature, execution_mode: ExecutionMode = ExecutionMode.SYNC) -> None
QslJobParameterFeature dataclass

Bases: QslJobParameter

As defined in WFS 2.0 specs, a request can be subdivided in a list of queries. This class is representing that.

Attributes:

  • queries (list[FeatureQuery]) –

    A list of queries which features should be extracted for.

  • start_index (int) –

    The offset for paging reason.

  • count (int | None) –

    The number of results to return.

Source code in src/qgis_server_light/interface/job/feature/input.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
@dataclass
class QslJobParameterFeature(QslJobParameter):
    """As defined in WFS 2.0 specs, a request can be subdivided in a list of queries.
    This class is representing that.

    Attributes:
        queries: A list of queries which features should be extracted for.
        start_index: The offset for paging reason.
        count: The number of results to return.
    """

    queries: list[FeatureQuery] = field(metadata={"type": "Element"})
    start_index: int = field(
        default=0,
        metadata={
            "type": "Element",
        },
    )
    count: int | None = field(
        default=None,
        metadata={
            "type": "Element",
        },
    )
count: int | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
queries: list[FeatureQuery] = field(metadata={'type': 'Element'}) class-attribute instance-attribute
start_index: int = field(default=0, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(queries: list[FeatureQuery], start_index: int = 0, count: int | None = None) -> None
output
Attribute dataclass

Bases: BaseInterface

An attribute belonging to a feature. The aim here is to drill down to simple types which can be used in consuming applications without further handling. This does not include the geometry attribute!

Attributes:

  • name (str) –

    The name of the attribute. Has to match with the name used for exported fields with Field class.

  • value (int | float | str | bool | bytes | None) –

    Value as simple as possible. It has to be pickleable

Source code in src/qgis_server_light/interface/job/feature/output.py
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@dataclass(repr=False)
class Attribute(BaseInterface):
    """An attribute belonging to a feature. The aim here is to
    drill down to simple types which can be used in consuming
    applications without further handling. This does not include
    the geometry attribute!

    Attributes:
        name: The name of the attribute. Has to match with the
            name used for exported fields with `Field` class.
        value: Value as simple as possible. It has to be
            [pickleable](https://docs.python.org/3/library/pickle.html#what-can-be-pickled-and-unpickled)

    """

    name: str = field(metadata={"type": "Element"})
    value: int | float | str | bool | bytes | None = field(
        metadata={"type": "Element", "format": "base64"}
    )
name: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
value: int | float | str | bool | bytes | None = field(metadata={'type': 'Element', 'format': 'base64'}) class-attribute instance-attribute
__init__(name: str, value: int | float | str | bool | bytes | None) -> None
Feature dataclass

Bases: BaseInterface

Feature to hold information of extracted QgsFeature.

Attributes:

Source code in src/qgis_server_light/interface/job/feature/output.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@dataclass(repr=False)
class Feature(BaseInterface):
    """Feature to hold information of extracted QgsFeature.

    Attributes:
        geometry: The geometry representing the feature.
        attributes: List of attributes defined in this feature.
    """

    geometry: Geometry | None = field(default=None, metadata={"type": "Element"})
    attributes: list[Attribute] = field(
        default_factory=list,
        metadata={"type": "Element"},
    )
attributes: list[Attribute] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
geometry: Geometry | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(geometry: Geometry | None = None, attributes: list[Attribute] = list()) -> None
FeatureCollection dataclass

Bases: BaseInterface

This construction is used to abstract the content of extracted features for pickelable transportation from QSL to the queue. This way we ensure how things are constructed and transported.

Attributes:

  • name (str) –

    The name of the feature collection. This is the key to match it to requested layers.

  • features (list[Feature]) –

    The features belonging to the feature collection.

Source code in src/qgis_server_light/interface/job/feature/output.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
@dataclass(repr=False)
class FeatureCollection(BaseInterface):
    """This construction is used to abstract the content of extracted
    features for pickelable transportation from QSL to the queue.
    This way we ensure how things are constructed and transported.

    Attributes:
        name: The name of the feature collection. This is the key to
            match it to requested layers.
        features: The features belonging to the feature collection.
    """

    name: str = field(metadata={"type": "Element"})
    features: list[Feature] = field(
        default_factory=list,
        metadata={"type": "Element"},
    )
features: list[Feature] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
name: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(name: str, features: list[Feature] = list()) -> None
Geometry dataclass

Bases: Attribute

Source code in src/qgis_server_light/interface/job/feature/output.py
27
28
29
30
31
32
33
34
@dataclass(repr=False)
class Geometry(Attribute):
    name: str = field(default="geometry", metadata={"type": "Element"})
    value: bytes | None = field(default=None, metadata={"type": "Element", "format": "base64"})

    @property
    def shortened_fields(self) -> set:
        return {"value"}
name: str = field(default='geometry', metadata={'type': 'Element'}) class-attribute instance-attribute
shortened_fields: set property
value: bytes | None = field(default=None, metadata={'type': 'Element', 'format': 'base64'}) class-attribute instance-attribute
__init__(name: str = 'geometry', value: bytes | None = None) -> None
QueryCollection dataclass

Bases: BaseInterface

Holds all feature collections which are bound to the passed queries. The order in the list has to be not changed, so that consuming applications can map the response to the passed queries.

Attributes:

Source code in src/qgis_server_light/interface/job/feature/output.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
@dataclass(repr=False)
class QueryCollection(BaseInterface):
    """Holds all feature collections which are bound to the
    passed queries. The order in the list has to be not changed,
    so that consuming applications can map the response to the
    passed queries.

    Attributes:
        numbers_matched: Information about how many matches are fund for the executed query.
        feature_collections: The feature collections belonging to the passed queries.
    """

    numbers_matched: str | int = field(
        default="unknown",
        metadata={"type": "Element"},
    )
    feature_collections: list[FeatureCollection] = field(
        default_factory=list,
        metadata={"type": "Element"},
    )
feature_collections: list[FeatureCollection] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
numbers_matched: str | int = field(default='unknown', metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(numbers_matched: str | int = 'unknown', feature_collections: list[FeatureCollection] = list()) -> None
feature_info
input
QslJobInfoFeatureInfo dataclass

Bases: QslJobInfoParameter

Source code in src/qgis_server_light/interface/job/feature_info/input.py
42
43
44
@dataclass
class QslJobInfoFeatureInfo(QslJobInfoParameter):
    job: QslJobParameterFeatureInfo = field(metadata={"type": "Element", "required": True})
job: QslJobParameterFeatureInfo = field(metadata={'type': 'Element', 'required': True}) class-attribute instance-attribute
__init__(id: str, type: str, job: QslJobParameterFeatureInfo, execution_mode: ExecutionMode = ExecutionMode.SYNC) -> None
QslJobParameterFeatureInfo dataclass

Bases: QslJobParameter

A runner to extract feature info

Source code in src/qgis_server_light/interface/job/feature_info/input.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@dataclass(kw_only=True)
class QslJobParameterFeatureInfo(QslJobParameter):
    """A runner to extract feature info"""

    # mime type, only application/json supported
    INFO_FORMAT: str = field(metadata={"type": "Element"})
    QUERY_LAYERS: str = field(metadata={"type": "Element"})
    X: str | None = field(default=None, metadata={"type": "Element"})
    Y: str | None = field(default=None, metadata={"type": "Element"})
    I: str | None = field(default=None, metadata={"type": "Element"})  # noqa: E741
    J: str | None = field(default=None, metadata={"type": "Element"})

    def __post_init__(self):
        x = int(self.I or self.X)
        y = int(self.J or self.Y)
        if x is None or y is None:
            raise KeyError("Parameter `I` or `X` and `J` or `Y`  are mandatory for GetFeatureInfo")
        if self.QUERY_LAYERS is None:
            raise KeyError("QUERY_LAYERS is mandatory in this request")

    @property
    def decide_x(self) -> int:
        return int(self.I or self.X)

    @property
    def decide_y(self) -> int:
        return int(self.J or self.Y)

    @property
    def query_layers_list(self):
        return self.QUERY_LAYERS.split(",")
I: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
INFO_FORMAT: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
J: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
QUERY_LAYERS: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
X: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
Y: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
decide_x: int property
decide_y: int property
query_layers_list property
__init__(*, INFO_FORMAT: str, QUERY_LAYERS: str, X: str | None = None, Y: str | None = None, I: str | None = None, J: str | None = None) -> None
__post_init__()
Source code in src/qgis_server_light/interface/job/feature_info/input.py
21
22
23
24
25
26
27
def __post_init__(self):
    x = int(self.I or self.X)
    y = int(self.J or self.Y)
    if x is None or y is None:
        raise KeyError("Parameter `I` or `X` and `J` or `Y`  are mandatory for GetFeatureInfo")
    if self.QUERY_LAYERS is None:
        raise KeyError("QUERY_LAYERS is mandatory in this request")
output
legend
input
QslJobInfoLegend dataclass

Bases: QslJobInfoParameter

Source code in src/qgis_server_light/interface/job/legend/input.py
29
30
31
@dataclass
class QslJobInfoLegend(QslJobInfoParameter):
    job: QslJobParameterLegend = field(metadata={"type": "Element", "required": True})
job: QslJobParameterLegend = field(metadata={'type': 'Element', 'required': True}) class-attribute instance-attribute
__init__(id: str, type: str, job: QslJobParameterLegend, execution_mode: ExecutionMode = ExecutionMode.SYNC) -> None
QslJobParameterLegend dataclass

Bases: QslJobParameter

Render legend graphics for one or more layers.

Source code in src/qgis_server_light/interface/job/legend/input.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@dataclass(kw_only=True)
class QslJobParameterLegend(QslJobParameter):
    """Render legend graphics for one or more layers."""

    layers: list[QslJobLayer] = field(metadata={"type": "Element"})
    format: str = field(default="image/png", metadata={"type": "Element"})
    width: int | None = field(default=None, metadata={"type": "Element"})
    height: int | None = field(default=None, metadata={"type": "Element"})
    dpi: int = field(default=91, metadata={"type": "Element"})
    scale: float | None = field(default=None, metadata={"type": "Element"})
    layer_title: bool = field(default=False, metadata={"type": "Element"})

    def get_layer_by_name(self, name: str) -> QslJobLayer:
        for layer in self.layers:
            if layer.name == name:
                return layer
        raise LookupError(f'No layer with name "{name}" was found.')
dpi: int = field(default=91, metadata={'type': 'Element'}) class-attribute instance-attribute
format: str = field(default='image/png', metadata={'type': 'Element'}) class-attribute instance-attribute
height: int | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
layer_title: bool = field(default=False, metadata={'type': 'Element'}) class-attribute instance-attribute
layers: list[QslJobLayer] = field(metadata={'type': 'Element'}) class-attribute instance-attribute
scale: float | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
width: int | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(*, layers: list[QslJobLayer], format: str = 'image/png', width: int | None = None, height: int | None = None, dpi: int = 91, scale: float | None = None, layer_title: bool = False) -> None
get_layer_by_name(name: str) -> QslJobLayer
Source code in src/qgis_server_light/interface/job/legend/input.py
22
23
24
25
26
def get_layer_by_name(self, name: str) -> QslJobLayer:
    for layer in self.layers:
        if layer.name == name:
            return layer
    raise LookupError(f'No layer with name "{name}" was found.')
output
process
description

This module contains the description of the processes a process-worker serves. It is shaped along the process description of OGC API - Processes - Part 1: Core (https://schemas.opengis.net/ogcapi/processes/part1/1.0/openapi/schemas/process.yaml), so a consumer can expose its elements as they are and only adds what belongs to the API around (links, job control options, conformance, ...).

Optional values default to None. Serialized with xsdata.formats.dataclass.serializers.dict.DictFactory.FILTER_NONE they are left out, which gives a plain JSON Schema for each Schema.

QSL_LAYER_FORMAT = 'qsl-layer' module-attribute
InputDescription dataclass

Bases: BaseInterface

The description of one input of a process.

OGC API - Processes holds the inputs as map by id. xsdata can't bind a map of dataclasses, therefore the id is part of the description and the inputs are a list.

Attributes:

  • id (str) –

    The identifier of the input, the QGIS parameter name.

  • title (str) –

    Human readable name.

  • description (str | None) –

    Human readable help text.

  • schema (Schema) –

    The schema of one value.

  • min_occurs (int) –

    The minimal number of values.

  • max_occurs (int | str) –

    The maximal number of values, unbounded for any.

Source code in src/qgis_server_light/interface/job/process/description.py
 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
@dataclass(repr=False, kw_only=True)
class InputDescription(BaseInterface):
    """The description of one input of a process.

    OGC API - Processes holds the inputs as map by id. xsdata can't bind a map of
    dataclasses, therefore the id is part of the description and the inputs are a list.

    Attributes:
        id: The identifier of the input, the QGIS parameter name.
        title: Human readable name.
        description: Human readable help text.
        schema: The schema of one value.
        min_occurs: The minimal number of values.
        max_occurs: The maximal number of values, `unbounded` for any.
    """

    id: str = field(metadata={"type": "Element"})
    title: str = field(metadata={"type": "Element"})
    description: str | None = field(default=None, metadata={"type": "Element"})
    schema: Schema = field(metadata={"type": "Element"})
    min_occurs: int = field(default=1, metadata={"type": "Element", "name": "minOccurs"})
    max_occurs: int | str = field(default=1, metadata={"type": "Element", "name": "maxOccurs"})

    @property
    def shortened_fields(self) -> set:
        return {"description"}
description: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
max_occurs: int | str = field(default=1, metadata={'type': 'Element', 'name': 'maxOccurs'}) class-attribute instance-attribute
min_occurs: int = field(default=1, metadata={'type': 'Element', 'name': 'minOccurs'}) class-attribute instance-attribute
schema: Schema = field(metadata={'type': 'Element'}) class-attribute instance-attribute
shortened_fields: set property
title: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(*, id: str, title: str, description: str | None = None, schema: Schema, min_occurs: int = 1, max_occurs: int | str = 1) -> None
OutputDescription dataclass

Bases: BaseInterface

The description of one output of a process. The id is part of the description, see InputDescription.

Attributes:

  • id (str) –

    The identifier of the output, the QGIS output name.

  • title (str) –

    Human readable name.

  • schema (Schema) –

    The schema of the value.

Source code in src/qgis_server_light/interface/job/process/description.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
@dataclass(repr=False, kw_only=True)
class OutputDescription(BaseInterface):
    """The description of one output of a process. The id is part of the description,
    see `InputDescription`.

    Attributes:
        id: The identifier of the output, the QGIS output name.
        title: Human readable name.
        schema: The schema of the value.
    """

    id: str = field(metadata={"type": "Element"})
    title: str = field(metadata={"type": "Element"})
    schema: Schema = field(metadata={"type": "Element"})
id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
schema: Schema = field(metadata={'type': 'Element'}) class-attribute instance-attribute
title: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(*, id: str, title: str, schema: Schema) -> None
ProcessDescription dataclass

Bases: BaseInterface

The description of one process.

Attributes:

  • id (str) –

    The identifier of the process, the QGIS algorithm id.

  • title (str) –

    Human readable name.

  • description (str | None) –

    Human readable help text.

  • inputs (list[InputDescription]) –

    The inputs which are passed by the client. Destinations are not part of it, they are set by the worker.

  • outputs (list[OutputDescription]) –

    The outputs the process produces.

  • internal (bool | None) –

    If the process is for internal use of the consumer only and must not be published. Left out (None) for a publishable process.

Source code in src/qgis_server_light/interface/job/process/description.py
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
@dataclass(repr=False, kw_only=True)
class ProcessDescription(BaseInterface):
    """The description of one process.

    Attributes:
        id: The identifier of the process, the QGIS algorithm id.
        title: Human readable name.
        description: Human readable help text.
        inputs: The inputs which are passed by the client. Destinations are not part of
            it, they are set by the worker.
        outputs: The outputs the process produces.
        internal: If the process is for internal use of the consumer only and must not be
            published. Left out (`None`) for a publishable process.
    """

    id: str = field(metadata={"type": "Element"})
    title: str = field(metadata={"type": "Element"})
    description: str | None = field(default=None, metadata={"type": "Element"})
    inputs: list[InputDescription] = field(default_factory=list, metadata={"type": "Element"})
    outputs: list[OutputDescription] = field(default_factory=list, metadata={"type": "Element"})
    internal: bool | None = field(default=None, metadata={"type": "Element"})

    @property
    def shortened_fields(self) -> set:
        return {"description"}
description: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
inputs: list[InputDescription] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
internal: bool | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
outputs: list[OutputDescription] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
shortened_fields: set property
title: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(*, id: str, title: str, description: str | None = None, inputs: list[InputDescription] = list(), outputs: list[OutputDescription] = list(), internal: bool | None = None) -> None
ProcessDescriptions dataclass

Bases: BaseInterface

The processes a process-worker serves (see RedisProtocol.worker_processes_key), or all process-workers together as the dispatcher merges them.

Attributes:

Source code in src/qgis_server_light/interface/job/process/description.py
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
@dataclass(repr=False)
class ProcessDescriptions(BaseInterface):
    """The processes a process-worker serves (see `RedisProtocol.worker_processes_key`),
    or all process-workers together as the dispatcher merges them.

    Attributes:
        processes: The description per process.
        warnings: The processes the workers don't agree on, only set by the dispatcher.
    """

    processes: list[ProcessDescription] = field(default_factory=list, metadata={"type": "Element"})
    warnings: list[ProcessWarning] = field(default_factory=list, metadata={"type": "Element"})

    def process_by_id(self, process_id: str) -> ProcessDescription:
        """
        Args:
            process_id: The identifier of the process.

        Raises:
            LookupError: If no process with this id is described.
        """
        for process in self.processes:
            if process.id == process_id:
                return process
        raise LookupError(f"Process `{process_id}` is not described")
processes: list[ProcessDescription] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
warnings: list[ProcessWarning] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(processes: list[ProcessDescription] = list(), warnings: list[ProcessWarning] = list()) -> None
process_by_id(process_id: str) -> ProcessDescription

Parameters:

  • process_id (str) –

    The identifier of the process.

Raises:

  • LookupError –

    If no process with this id is described.

Source code in src/qgis_server_light/interface/job/process/description.py
187
188
189
190
191
192
193
194
195
196
197
198
def process_by_id(self, process_id: str) -> ProcessDescription:
    """
    Args:
        process_id: The identifier of the process.

    Raises:
        LookupError: If no process with this id is described.
    """
    for process in self.processes:
        if process.id == process_id:
            return process
    raise LookupError(f"Process `{process_id}` is not described")
ProcessWarning dataclass

Bases: BaseInterface

Tells that the process-workers serving a process don't agree on it. They run different QGIS versions or describe the process differently, so a job behaves differently depending on the worker which takes it. The deployment needs to be corrected then.

Attributes:

  • process_id (str) –

    The identifier of the process.

  • qgis_versions (list[str]) –

    The QGIS versions of the workers serving the process, the newest first.

  • descriptions_differ (bool) –

    If the workers describe the process differently.

Source code in src/qgis_server_light/interface/job/process/description.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
@dataclass(repr=False, kw_only=True)
class ProcessWarning(BaseInterface):
    """Tells that the process-workers serving a process don't agree on it. They run
    different QGIS versions or describe the process differently, so a job behaves
    differently depending on the worker which takes it. The deployment needs to be
    corrected then.

    Attributes:
        process_id: The identifier of the process.
        qgis_versions: The QGIS versions of the workers serving the process, the newest
            first.
        descriptions_differ: If the workers describe the process differently.
    """

    process_id: str = field(metadata={"type": "Element"})
    qgis_versions: list[str] = field(default_factory=list, metadata={"type": "Element"})
    descriptions_differ: bool = field(default=False, metadata={"type": "Element"})
descriptions_differ: bool = field(default=False, metadata={'type': 'Element'}) class-attribute instance-attribute
process_id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
qgis_versions: list[str] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(*, process_id: str, qgis_versions: list[str] = list(), descriptions_differ: bool = False) -> None
QslLayerKind

Bases: Enum

The kinds of layer QSL can load as value of a process input.

Source code in src/qgis_server_light/interface/job/process/description.py
20
21
22
23
24
class QslLayerKind(Enum):
    """The kinds of layer QSL can load as value of a process input."""

    VECTOR = "vector"
    RASTER = "raster"
RASTER = 'raster' class-attribute instance-attribute
VECTOR = 'vector' class-attribute instance-attribute
QslLayerMarker dataclass

Bases: BaseInterface

Marks a schema whose value is a layer (QslJobLayer) instead of a literal. A consumer replaces the marked schema with the layers it offers which match the marker.

Attributes:

  • kinds (list[QslLayerKind]) –

    The kinds of layer which are accepted.

  • geometry_types (list[str]) –

    The geometry types of a vector layer which are accepted, named as qgis.core.Qgis.GeometryType (Point, Line, Polygon, Null). Matches Vector.geometry_type_simple of the exported project. Applies to vector layers only, empty when no vector layer is accepted.

  • source (str | None) –

    The class name of the QGIS parameter or output the marker was derived from.

Source code in src/qgis_server_light/interface/job/process/description.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
@dataclass(repr=False)
class QslLayerMarker(BaseInterface):
    """Marks a schema whose value is a layer (`QslJobLayer`) instead of a literal. A
    consumer replaces the marked schema with the layers it offers which match the marker.

    Attributes:
        kinds: The kinds of layer which are accepted.
        geometry_types: The geometry types of a vector layer which are accepted, named as
            `qgis.core.Qgis.GeometryType` (`Point`, `Line`, `Polygon`, `Null`). Matches
            `Vector.geometry_type_simple` of the exported project. Applies to vector layers
            only, empty when no vector layer is accepted.
        source: The class name of the QGIS parameter or output the marker was derived from.
    """

    kinds: list[QslLayerKind] = field(metadata={"type": "Element"})
    geometry_types: list[str] = field(default_factory=list, metadata={"type": "Element"})
    source: str | None = field(default=None, metadata={"type": "Element"})
geometry_types: list[str] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
kinds: list[QslLayerKind] = field(metadata={'type': 'Element'}) class-attribute instance-attribute
source: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(kinds: list[QslLayerKind], geometry_types: list[str] = list(), source: str | None = None) -> None
Schema dataclass

Bases: BaseInterface

The subset of JSON Schema which is used to describe the values of inputs and outputs.

Attributes:

  • type (str | None) –

    The JSON Schema type (string, number, integer, boolean, ...).

  • format (str | None) –

    The format of the value. Layer values carry QSL_LAYER_FORMAT.

  • title (str | None) –

    Human readable name, used on the entries of one_of.

  • minimum (int | float | None) –

    The inclusive minimum of a numeric value.

  • maximum (int | float | None) –

    The inclusive maximum of a numeric value.

  • const (bool | int | float | str | None) –

    The only valid value, used on the entries of one_of.

  • default (bool | int | float | str | None) –

    The value used when none is passed.

  • one_of (list[Schema] | None) –

    The valid values, each as schema with const and title. For a file output the formats it is offered in, each as schema with content_media_type, the first one is the default.

  • content_media_type (str | None) –

    The media type of a value which is a file.

  • x_qsl_layer (QslLayerMarker | None) –

    The marker of a layer value.

Source code in src/qgis_server_light/interface/job/process/description.py
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
@dataclass(repr=False, kw_only=True)
class Schema(BaseInterface):
    """The subset of JSON Schema which is used to describe the values of inputs and
    outputs.

    Attributes:
        type: The JSON Schema type (`string`, `number`, `integer`, `boolean`, ...).
        format: The format of the value. Layer values carry `QSL_LAYER_FORMAT`.
        title: Human readable name, used on the entries of `one_of`.
        minimum: The inclusive minimum of a numeric value.
        maximum: The inclusive maximum of a numeric value.
        const: The only valid value, used on the entries of `one_of`.
        default: The value used when none is passed.
        one_of: The valid values, each as schema with `const` and `title`. For a file
            output the formats it is offered in, each as schema with
            `content_media_type`, the first one is the default.
        content_media_type: The media type of a value which is a file.
        x_qsl_layer: The marker of a layer value.
    """

    type: str | None = field(default=None, metadata={"type": "Element"})
    format: str | None = field(default=None, metadata={"type": "Element"})
    title: str | None = field(default=None, metadata={"type": "Element"})
    minimum: int | float | None = field(default=None, metadata={"type": "Element"})
    maximum: int | float | None = field(default=None, metadata={"type": "Element"})
    const: bool | int | float | str | None = field(default=None, metadata={"type": "Element"})
    default: bool | int | float | str | None = field(default=None, metadata={"type": "Element"})
    one_of: list["Schema"] | None = field(
        default=None, metadata={"type": "Element", "name": "oneOf"}
    )
    content_media_type: str | None = field(
        default=None, metadata={"type": "Element", "name": "contentMediaType"}
    )
    x_qsl_layer: QslLayerMarker | None = field(
        default=None, metadata={"type": "Element", "name": "x-qsl-layer"}
    )
const: bool | int | float | str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
content_media_type: str | None = field(default=None, metadata={'type': 'Element', 'name': 'contentMediaType'}) class-attribute instance-attribute
default: bool | int | float | str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
format: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
maximum: int | float | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
minimum: int | float | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
one_of: list[Schema] | None = field(default=None, metadata={'type': 'Element', 'name': 'oneOf'}) class-attribute instance-attribute
title: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
type: str | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
x_qsl_layer: QslLayerMarker | None = field(default=None, metadata={'type': 'Element', 'name': 'x-qsl-layer'}) class-attribute instance-attribute
__init__(*, type: str | None = None, format: str | None = None, title: str | None = None, minimum: int | float | None = None, maximum: int | float | None = None, const: bool | int | float | str | None = None, default: bool | int | float | str | None = None, one_of: list[Schema] | None = None, content_media_type: str | None = None, x_qsl_layer: QslLayerMarker | None = None) -> None
input

This module contains the execute request of a process job. It is shaped along the execute request of OGC API - Processes - Part 1: Core (https://schemas.opengis.net/ogcapi/processes/part1/1.0/openapi/schemas/execute.yaml), carrying its inputs and outputs. OGC API - Processes holds them as maps by id, xsdata can't bind a map of dataclasses, therefore the id is part of each entry and they are lists (see InputDescription).

ExecuteInput dataclass

The value of one input of a process.

Attributes:

  • id (str) –

    The identifier of the input, the QGIS parameter name.

  • value (list[QslJobLayer | str | int | float | bool]) –

    The values of the input, one entry for an input taking a single value. A layer value is substituted in place by its QslJobLayer.

Source code in src/qgis_server_light/interface/job/process/input.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@dataclass
class ExecuteInput:
    """The value of one input of a process.

    Attributes:
        id: The identifier of the input, the QGIS parameter name.
        value: The values of the input, one entry for an input taking a single value. A
            layer value is substituted in place by its `QslJobLayer`.
    """

    id: str = field(metadata={"type": "Element"})
    value: list[QslJobLayer | str | int | float | bool] = field(
        default_factory=list, metadata={"type": "Element"}
    )
id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
value: list[QslJobLayer | str | int | float | bool] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, value: list[QslJobLayer | str | int | float | bool] = list()) -> None
ExecuteOutput dataclass

The format a client wants a file output in.

Attributes:

  • id (str) –

    The identifier of the output, the QGIS output name.

  • format (Format) –

    The format the output is written in.

Source code in src/qgis_server_light/interface/job/process/input.py
45
46
47
48
49
50
51
52
53
54
55
@dataclass
class ExecuteOutput:
    """The format a client wants a file output in.

    Attributes:
        id: The identifier of the output, the QGIS output name.
        format: The format the output is written in.
    """

    id: str = field(metadata={"type": "Element"})
    format: Format = field(metadata={"type": "Element"})
format: Format = field(metadata={'type': 'Element'}) class-attribute instance-attribute
id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, format: Format) -> None
Format dataclass

The format of a file output.

Attributes:

  • media_type (str) –

    One of the media types the description offers for the output.

Source code in src/qgis_server_light/interface/job/process/input.py
34
35
36
37
38
39
40
41
42
@dataclass
class Format:
    """The format of a file output.

    Attributes:
        media_type: One of the media types the description offers for the output.
    """

    media_type: str = field(metadata={"type": "Element", "name": "mediaType"})
media_type: str = field(metadata={'type': 'Element', 'name': 'mediaType'}) class-attribute instance-attribute
__init__(media_type: str) -> None
QslJobInfoExecuteProcess dataclass

Bases: QslJobInfoParameter

The job of a process execution, queued with RedisStateQueue.submit.

Source code in src/qgis_server_light/interface/job/process/input.py
74
75
76
77
78
@dataclass
class QslJobInfoExecuteProcess(QslJobInfoParameter):
    """The job of a process execution, queued with `RedisStateQueue.submit`."""

    job: QslJobParameterExecuteProcess = field(metadata={"type": "Element", "required": True})
job: QslJobParameterExecuteProcess = field(metadata={'type': 'Element', 'required': True}) class-attribute instance-attribute
__init__(id: str, type: str, job: QslJobParameterExecuteProcess, execution_mode: ExecutionMode = ExecutionMode.SYNC) -> None
QslJobParameterExecuteProcess dataclass

Bases: QslJobParameter

The execute request of a process.

Attributes:

  • process_id (str) –

    The identifier of the process, the QGIS algorithm id.

  • inputs (list[ExecuteInput]) –

    The values of the inputs, an input which is left out takes its default.

  • outputs (list[ExecuteOutput]) –

    The formats chosen for file outputs, an output which is left out is written in the first format its description offers.

Source code in src/qgis_server_light/interface/job/process/input.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
@dataclass(kw_only=True)
class QslJobParameterExecuteProcess(QslJobParameter):
    """The execute request of a process.

    Attributes:
        process_id: The identifier of the process, the QGIS algorithm id.
        inputs: The values of the inputs, an input which is left out takes its default.
        outputs: The formats chosen for file outputs, an output which is left out is
            written in the first format its description offers.
    """

    process_id: str = field(metadata={"type": "Element"})
    inputs: list[ExecuteInput] = field(default_factory=list, metadata={"type": "Element"})
    outputs: list[ExecuteOutput] = field(default_factory=list, metadata={"type": "Element"})
inputs: list[ExecuteInput] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
outputs: list[ExecuteOutput] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
process_id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(*, process_id: str, inputs: list[ExecuteInput] = list(), outputs: list[ExecuteOutput] = list()) -> None
output

This module contains the result of a process job. It is shaped along the results of OGC API - Processes - Part 1: Core (https://schemas.opengis.net/ogcapi/processes/part1/1.0/openapi/schemas/results.yaml), per output either the literal value or a reference to the file. The outputs are a list of entries with their id instead of a map by id, see ExecuteInput.

ProcessResult dataclass

Bases: BaseInterface

The result of a process. A worker ships it as xsdata JSON in the data of the JobResult, so the dispatcher can parse it back without knowing anything about QGIS.

Attributes:

  • outputs (list[ResultOutput]) –

    The outputs of the process.

  • log (str) –

    The log the QGIS algorithm wrote while it was running. It has no place in the results of OGC API - Processes and travels next to the outputs.

Source code in src/qgis_server_light/interface/job/process/output.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
@dataclass(repr=False)
class ProcessResult(BaseInterface):
    """The result of a process. A worker ships it as xsdata JSON in the data of
    the `JobResult`, so the dispatcher can parse it back without knowing
    anything about QGIS.

    Attributes:
        outputs: The outputs of the process.
        log: The log the QGIS algorithm wrote while it was running. It has no place in
            the results of OGC API - Processes and travels next to the outputs.
    """

    outputs: list[ResultOutput] = field(default_factory=list, metadata={"type": "Element"})
    log: str = field(default="", metadata={"type": "Element"})

    @property
    def shortened_fields(self) -> set:
        return {"log"}
log: str = field(default='', metadata={'type': 'Element'}) class-attribute instance-attribute
outputs: list[ResultOutput] = field(default_factory=list, metadata={'type': 'Element'}) class-attribute instance-attribute
shortened_fields: set property
__init__(outputs: list[ResultOutput] = list(), log: str = '') -> None
Reference dataclass

A file a process wrote into the process output dir of the worker.

Attributes:

  • href (str) –

    The path of the file relative to the process output dir.

  • type (str) –

    The media type of the file.

Source code in src/qgis_server_light/interface/job/process/output.py
13
14
15
16
17
18
19
20
21
22
23
@dataclass
class Reference:
    """A file a process wrote into the process output dir of the worker.

    Attributes:
        href: The path of the file relative to the process output dir.
        type: The media type of the file.
    """

    href: str = field(metadata={"type": "Element"})
    type: str = field(metadata={"type": "Element"})
href: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
type: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(href: str, type: str) -> None
ResultOutput dataclass

A single output of a process, the counterpart of ExecuteInput.

Attributes:

  • id (str) –

    The identifier of the output, the QGIS output name.

  • value (Reference | str | int | float | bool) –

    The file the output was written to, or the literal value of the output.

Source code in src/qgis_server_light/interface/job/process/output.py
26
27
28
29
30
31
32
33
34
35
36
37
@dataclass
class ResultOutput:
    """A single output of a process, the counterpart of `ExecuteInput`.

    Attributes:
        id: The identifier of the output, the QGIS output name.
        value: The file the output was written to, or the literal value of the
            output.
    """

    id: str = field(metadata={"type": "Element"})
    value: Reference | str | int | float | bool = field(metadata={"type": "Element"})
id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
value: Reference | str | int | float | bool = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, value: Reference | str | int | float | bool) -> None
render
input
QslJobInfoRender dataclass

Bases: QslJobInfoParameter

Source code in src/qgis_server_light/interface/job/render/input.py
30
31
32
@dataclass
class QslJobInfoRender(QslJobInfoParameter):
    job: QslJobParameterRender = field(metadata={"type": "Element", "required": True})
job: QslJobParameterRender = field(metadata={'type': 'Element', 'required': True}) class-attribute instance-attribute
__init__(id: str, type: str, job: QslJobParameterRender, execution_mode: ExecutionMode = ExecutionMode.SYNC) -> None
QslJobParameterRender dataclass

Bases: QslJobParameter

A runner to be rendered as an image

Source code in src/qgis_server_light/interface/job/render/input.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@dataclass(kw_only=True)
class QslJobParameterRender(QslJobParameter):
    """A runner to be rendered as an image"""

    layers: list[QslJobLayer] = field(metadata={"type": "Element"})
    bbox: BBox = field(metadata={"type": "Element"})
    crs: str = field(metadata={"type": "Element"})
    width: int = field(metadata={"type": "Element"})
    height: int = field(metadata={"type": "Element"})
    dpi: int | None = field(default=None, metadata={"type": "Element"})
    format: str = field(default="image/png", metadata={"type": "Element"})

    def get_layer_by_name(self, name: str) -> QslJobLayer:
        for layer in self.layers:
            if layer.name == name:
                return layer
        raise LookupError(f'No layer with name "{name}" was found."')
bbox: BBox = field(metadata={'type': 'Element'}) class-attribute instance-attribute
crs: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
dpi: int | None = field(default=None, metadata={'type': 'Element'}) class-attribute instance-attribute
format: str = field(default='image/png', metadata={'type': 'Element'}) class-attribute instance-attribute
height: int = field(metadata={'type': 'Element'}) class-attribute instance-attribute
layers: list[QslJobLayer] = field(metadata={'type': 'Element'}) class-attribute instance-attribute
width: int = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(*, layers: list[QslJobLayer], bbox: BBox, crs: str, width: int, height: int, dpi: int | None = None, format: str = 'image/png') -> None
get_layer_by_name(name: str) -> QslJobLayer
Source code in src/qgis_server_light/interface/job/render/input.py
23
24
25
26
27
def get_layer_by_name(self, name: str) -> QslJobLayer:
    for layer in self.layers:
        if layer.name == name:
            return layer
    raise LookupError(f'No layer with name "{name}" was found."')
output

worker

info

This part defines the structure how a running QSL worker exposes its capabilities.

EngineInfo dataclass
Source code in src/qgis_server_light/interface/worker/info.py
33
34
35
36
37
38
@dataclass
class EngineInfo:
    id: str = field(metadata={"type": "Element"})
    qgis_info: QgisInfo = field(metadata={"type": "Element"})
    status: Status = field(metadata={"type": "Element"})
    started: float = field(metadata={"type": "Element"})
id: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
qgis_info: QgisInfo = field(metadata={'type': 'Element'}) class-attribute instance-attribute
started: float = field(metadata={'type': 'Element'}) class-attribute instance-attribute
status: Status = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(id: str, qgis_info: QgisInfo, status: Status, started: float) -> None
QgisInfo dataclass

Information container to ship minimal knowledge of the underlying QGIS.

Attributes:

  • version (int) –

    The integer representation of the QGIS version e.g. 34400

  • version_name (str) –

    The string representation which also includes the codename e.g. "QGIS Version 4.0.0-Norrköping"

Source code in src/qgis_server_light/interface/worker/info.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@dataclass
class QgisInfo:
    """
    Information container to ship minimal knowledge of the underlying
    QGIS.

    Attributes:
        version: The integer representation of the QGIS version e.g. 34400
        version_name: The string representation which also includes the codename e.g.
            "QGIS Version 4.0.0-Norrköping"

    """

    version: int = field(metadata={"type": "Element"})
    version_name: str = field(metadata={"type": "Element"})
    path: str = field(metadata={"type": "Element"})
path: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
version: int = field(metadata={'type': 'Element'}) class-attribute instance-attribute
version_name: str = field(metadata={'type': 'Element'}) class-attribute instance-attribute
__init__(version: int, version_name: str, path: str) -> None
Status

Bases: StrEnum

Source code in src/qgis_server_light/interface/worker/info.py
 8
 9
10
11
12
class Status(StrEnum):
    STARTING = "starting"
    CRASHED = "crashed"
    WAITING = "waiting"
    PROCESSING = "processing"
CRASHED = 'crashed' class-attribute instance-attribute
PROCESSING = 'processing' class-attribute instance-attribute
STARTING = 'starting' class-attribute instance-attribute
WAITING = 'waiting' class-attribute instance-attribute

processing

This package contains the processing handling shared by the exporter and the worker. It is the only place where QGIS processing definitions are translated into the QGIS-Server-Light interface.

description

This module translates QGIS processing algorithms into the process descriptions of the QGIS-Server-Light interface (interface.job.process.description), shaped along OGC API - Processes.

The schemas are mapped with the strategy pattern. Each kind of QGIS parameter or output definition has its SchemaStrategy, ProcessDescriptionMapper picks it from a flat lookup table by the exact QGIS class. The layer strategies share the derivation of the QslLayerMarker as template method (LayerSchemaStrategy.map_schema), each one only tells which source types it accepts.

It was chosen because QGIS knows many definition classes and each one maps differently. Supporting a new one is one strategy and one entry in the table, nothing else changes. The exact class is looked up on purpose: a QGIS subclass is never served by accident through its parent, a definition without strategy is unsupported and its algorithm is skipped.

EnumSchemaStrategy

Bases: SchemaStrategy[QgsProcessingParameterEnum]

The options as one_of. The value is the option itself when the parameter uses static strings, otherwise the index of the option, as QGIS expects it.

Source code in src/qgis_server_light/processing/description.py
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
class EnumSchemaStrategy(SchemaStrategy[QgsProcessingParameterEnum]):
    """The options as `one_of`. The value is the option itself when the parameter uses
    static strings, otherwise the index of the option, as QGIS expects it."""

    def map_schema(self, definition: QgsProcessingParameterEnum) -> Schema:
        """The schema of the enum, each option an entry of `one_of` with `const` and
        `title`.

        Raises:
            ValueError: If the parameter allows multiple options.
        """
        if definition.allowMultiple():
            raise ValueError(f"unsupported enum with multiple options: {definition.name()}")
        options = definition.options()
        if definition.usesStaticStrings():
            value_type, values = "string", options
        else:
            value_type, values = "integer", list(range(len(options)))
        return Schema(
            type=value_type,
            default=self.default(definition),
            one_of=[
                Schema(const=value, title=option)
                for value, option in zip(values, options, strict=True)
            ],
        )
map_schema(definition: QgsProcessingParameterEnum) -> Schema

The schema of the enum, each option an entry of one_of with const and title.

Raises:

  • ValueError –

    If the parameter allows multiple options.

Source code in src/qgis_server_light/processing/description.py
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def map_schema(self, definition: QgsProcessingParameterEnum) -> Schema:
    """The schema of the enum, each option an entry of `one_of` with `const` and
    `title`.

    Raises:
        ValueError: If the parameter allows multiple options.
    """
    if definition.allowMultiple():
        raise ValueError(f"unsupported enum with multiple options: {definition.name()}")
    options = definition.options()
    if definition.usesStaticStrings():
        value_type, values = "string", options
    else:
        value_type, values = "integer", list(range(len(options)))
    return Schema(
        type=value_type,
        default=self.default(definition),
        one_of=[
            Schema(const=value, title=option)
            for value, option in zip(values, options, strict=True)
        ],
    )
FeatureSourceSchemaStrategy

Bases: LayerSchemaStrategy[QgsProcessingParameterFeatureSource | QgsProcessingParameterVectorLayer]

A vector layer, restricted to the geometry types the parameter accepts.

Source code in src/qgis_server_light/processing/description.py
269
270
271
272
273
274
275
276
277
278
279
class FeatureSourceSchemaStrategy(
    LayerSchemaStrategy[QgsProcessingParameterFeatureSource | QgsProcessingParameterVectorLayer]
):
    """A vector layer, restricted to the geometry types the parameter accepts."""

    def source_types(
        self, definition: QgsProcessingParameterFeatureSource | QgsProcessingParameterVectorLayer
    ) -> list[int]:
        # QGIS accepts any vector layer when no source type is set, see
        # `QgsProcessingUtils::canUseLayer`
        return definition.dataTypes() or [Qgis.ProcessingSourceType.Vector]
source_types(definition: QgsProcessingParameterFeatureSource | QgsProcessingParameterVectorLayer) -> list[int]
Source code in src/qgis_server_light/processing/description.py
274
275
276
277
278
279
def source_types(
    self, definition: QgsProcessingParameterFeatureSource | QgsProcessingParameterVectorLayer
) -> list[int]:
    # QGIS accepts any vector layer when no source type is set, see
    # `QgsProcessingUtils::canUseLayer`
    return definition.dataTypes() or [Qgis.ProcessingSourceType.Vector]
FileOutputSchemaStrategy

Bases: SchemaStrategy[QgsProcessingOutputDefinition]

An output the worker writes to a file, offered in each of the given media types. The first one is the default.

Source code in src/qgis_server_light/processing/description.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
class FileOutputSchemaStrategy(SchemaStrategy[QgsProcessingOutputDefinition]):
    """An output the worker writes to a file, offered in each of the given media types.
    The first one is the default."""

    def __init__(self, media_types: list[str]):
        self.media_types = media_types

    def map_schema(self, definition: QgsProcessingOutputDefinition) -> Schema:
        return Schema(
            one_of=[
                Schema(type="string", content_media_type=media_type)
                for media_type in self.media_types
            ]
        )
media_types = media_types instance-attribute
__init__(media_types: list[str])
Source code in src/qgis_server_light/processing/description.py
316
317
def __init__(self, media_types: list[str]):
    self.media_types = media_types
map_schema(definition: QgsProcessingOutputDefinition) -> Schema
Source code in src/qgis_server_light/processing/description.py
319
320
321
322
323
324
325
def map_schema(self, definition: QgsProcessingOutputDefinition) -> Schema:
    return Schema(
        one_of=[
            Schema(type="string", content_media_type=media_type)
            for media_type in self.media_types
        ]
    )
LayerSchemaStrategy

Bases: SchemaStrategy[D], ABC

A layer value (QslJobLayer), marked with a QslLayerMarker. The marker is derived from the Qgis.ProcessingSourceType values the definition accepts. Source types QSL can't serve as layer (mesh, point cloud, vector tile, file, ...) are left out.

Source code in src/qgis_server_light/processing/description.py
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
class LayerSchemaStrategy[D: QgsProcessingParameterDefinition | QgsProcessingOutputDefinition](
    SchemaStrategy[D], ABC
):
    """A layer value (`QslJobLayer`), marked with a `QslLayerMarker`. The marker is derived
    from the `Qgis.ProcessingSourceType` values the definition accepts. Source types QSL
    can't serve as layer (mesh, point cloud, vector tile, file, ...) are left out."""

    layer_kinds_by_source_type: dict[Qgis.ProcessingSourceType, list[QslLayerKind]] = {
        Qgis.ProcessingSourceType.MapLayer: [QslLayerKind.VECTOR, QslLayerKind.RASTER],
        Qgis.ProcessingSourceType.Vector: [QslLayerKind.VECTOR],
        Qgis.ProcessingSourceType.VectorAnyGeometry: [QslLayerKind.VECTOR],
        Qgis.ProcessingSourceType.VectorPoint: [QslLayerKind.VECTOR],
        Qgis.ProcessingSourceType.VectorLine: [QslLayerKind.VECTOR],
        Qgis.ProcessingSourceType.VectorPolygon: [QslLayerKind.VECTOR],
        Qgis.ProcessingSourceType.Raster: [QslLayerKind.RASTER],
    }
    # the geometry types a layer of the source type may have, see
    # `QgsProcessingUtils::canUseLayer` in QGIS `src/core/processing/qgsprocessingutils.cpp`.
    # The PyQGIS stubs lack `name` on the `Qgis.GeometryType` members although they are
    # python enums at runtime, hence the ignored attribute checks.
    geometry_types_by_source_type: dict[Qgis.ProcessingSourceType, list[str]] = {
        Qgis.ProcessingSourceType.MapLayer: [
            Qgis.GeometryType.Point.name,  # type: ignore[attr-defined]
            Qgis.GeometryType.Line.name,  # type: ignore[attr-defined]
            Qgis.GeometryType.Polygon.name,  # type: ignore[attr-defined]
            Qgis.GeometryType.Null.name,  # type: ignore[attr-defined]
        ],
        Qgis.ProcessingSourceType.Vector: [
            Qgis.GeometryType.Point.name,  # type: ignore[attr-defined]
            Qgis.GeometryType.Line.name,  # type: ignore[attr-defined]
            Qgis.GeometryType.Polygon.name,  # type: ignore[attr-defined]
            Qgis.GeometryType.Null.name,  # type: ignore[attr-defined]
        ],
        Qgis.ProcessingSourceType.VectorAnyGeometry: [
            Qgis.GeometryType.Point.name,  # type: ignore[attr-defined]
            Qgis.GeometryType.Line.name,  # type: ignore[attr-defined]
            Qgis.GeometryType.Polygon.name,  # type: ignore[attr-defined]
        ],
        Qgis.ProcessingSourceType.VectorPoint: [Qgis.GeometryType.Point.name],  # type: ignore[attr-defined]
        Qgis.ProcessingSourceType.VectorLine: [Qgis.GeometryType.Line.name],  # type: ignore[attr-defined]
        Qgis.ProcessingSourceType.VectorPolygon: [Qgis.GeometryType.Polygon.name],  # type: ignore[attr-defined]
        Qgis.ProcessingSourceType.Raster: [],
    }

    @abstractmethod
    def source_types(self, definition: D) -> list[int]:
        """The `Qgis.ProcessingSourceType` values the definition accepts.

        Args:
            definition: The QGIS parameter or output definition.

        Returns:
            The source types as QGIS hands them out, as int.
        """
        raise NotImplementedError

    def map_schema(self, definition: D) -> Schema:
        """The schema of a layer value, a string marked with `QSL_LAYER_FORMAT` and the
        kinds and geometry types of all servable source types in the marker.

        Raises:
            ValueError: If none of the source types can be served as layer.
        """
        source_types = list(map(Qgis.ProcessingSourceType, self.source_types(definition)))
        servable_source_types = [
            source_type
            for source_type in source_types
            if source_type in self.layer_kinds_by_source_type
        ]
        if not servable_source_types:
            raise ValueError(f"unsupported ProcessingSourceTypes: {source_types}")
        kinds = []
        geometry_types = []
        for source_type in servable_source_types:
            for kind in self.layer_kinds_by_source_type[source_type]:
                if kind not in kinds:
                    kinds.append(kind)
            for geometry_type in self.geometry_types_by_source_type[source_type]:
                if geometry_type not in geometry_types:
                    geometry_types.append(geometry_type)
        return Schema(
            type="string",
            format=QSL_LAYER_FORMAT,
            x_qsl_layer=QslLayerMarker(
                kinds=kinds,
                geometry_types=geometry_types,
                source=type(definition).__name__,
            ),
        )
geometry_types_by_source_type: dict[Qgis.ProcessingSourceType, list[str]] = {Qgis.ProcessingSourceType.MapLayer: [Qgis.GeometryType.Point.name, Qgis.GeometryType.Line.name, Qgis.GeometryType.Polygon.name, Qgis.GeometryType.Null.name], Qgis.ProcessingSourceType.Vector: [Qgis.GeometryType.Point.name, Qgis.GeometryType.Line.name, Qgis.GeometryType.Polygon.name, Qgis.GeometryType.Null.name], Qgis.ProcessingSourceType.VectorAnyGeometry: [Qgis.GeometryType.Point.name, Qgis.GeometryType.Line.name, Qgis.GeometryType.Polygon.name], Qgis.ProcessingSourceType.VectorPoint: [Qgis.GeometryType.Point.name], Qgis.ProcessingSourceType.VectorLine: [Qgis.GeometryType.Line.name], Qgis.ProcessingSourceType.VectorPolygon: [Qgis.GeometryType.Polygon.name], Qgis.ProcessingSourceType.Raster: []} class-attribute instance-attribute
layer_kinds_by_source_type: dict[Qgis.ProcessingSourceType, list[QslLayerKind]] = {Qgis.ProcessingSourceType.MapLayer: [QslLayerKind.VECTOR, QslLayerKind.RASTER], Qgis.ProcessingSourceType.Vector: [QslLayerKind.VECTOR], Qgis.ProcessingSourceType.VectorAnyGeometry: [QslLayerKind.VECTOR], Qgis.ProcessingSourceType.VectorPoint: [QslLayerKind.VECTOR], Qgis.ProcessingSourceType.VectorLine: [QslLayerKind.VECTOR], Qgis.ProcessingSourceType.VectorPolygon: [QslLayerKind.VECTOR], Qgis.ProcessingSourceType.Raster: [QslLayerKind.RASTER]} class-attribute instance-attribute
map_schema(definition: D) -> Schema

The schema of a layer value, a string marked with QSL_LAYER_FORMAT and the kinds and geometry types of all servable source types in the marker.

Raises:

  • ValueError –

    If none of the source types can be served as layer.

Source code in src/qgis_server_light/processing/description.py
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
def map_schema(self, definition: D) -> Schema:
    """The schema of a layer value, a string marked with `QSL_LAYER_FORMAT` and the
    kinds and geometry types of all servable source types in the marker.

    Raises:
        ValueError: If none of the source types can be served as layer.
    """
    source_types = list(map(Qgis.ProcessingSourceType, self.source_types(definition)))
    servable_source_types = [
        source_type
        for source_type in source_types
        if source_type in self.layer_kinds_by_source_type
    ]
    if not servable_source_types:
        raise ValueError(f"unsupported ProcessingSourceTypes: {source_types}")
    kinds = []
    geometry_types = []
    for source_type in servable_source_types:
        for kind in self.layer_kinds_by_source_type[source_type]:
            if kind not in kinds:
                kinds.append(kind)
        for geometry_type in self.geometry_types_by_source_type[source_type]:
            if geometry_type not in geometry_types:
                geometry_types.append(geometry_type)
    return Schema(
        type="string",
        format=QSL_LAYER_FORMAT,
        x_qsl_layer=QslLayerMarker(
            kinds=kinds,
            geometry_types=geometry_types,
            source=type(definition).__name__,
        ),
    )
source_types(definition: D) -> list[int] abstractmethod

The Qgis.ProcessingSourceType values the definition accepts.

Parameters:

  • definition (D) –

    The QGIS parameter or output definition.

Returns:

  • list[int] –

    The source types as QGIS hands them out, as int.

Source code in src/qgis_server_light/processing/description.py
222
223
224
225
226
227
228
229
230
231
232
@abstractmethod
def source_types(self, definition: D) -> list[int]:
    """The `Qgis.ProcessingSourceType` values the definition accepts.

    Args:
        definition: The QGIS parameter or output definition.

    Returns:
        The source types as QGIS hands them out, as int.
    """
    raise NotImplementedError
LiteralOutputSchemaStrategy

Bases: SchemaStrategy[QgsProcessingOutputDefinition]

An output with a plain JSON Schema type.

Source code in src/qgis_server_light/processing/description.py
103
104
105
106
107
108
109
110
class LiteralOutputSchemaStrategy(SchemaStrategy[QgsProcessingOutputDefinition]):
    """An output with a plain JSON Schema type."""

    def __init__(self, json_type: str):
        self.json_type = json_type

    def map_schema(self, definition: QgsProcessingOutputDefinition) -> Schema:
        return Schema(type=self.json_type)
json_type = json_type instance-attribute
__init__(json_type: str)
Source code in src/qgis_server_light/processing/description.py
106
107
def __init__(self, json_type: str):
    self.json_type = json_type
map_schema(definition: QgsProcessingOutputDefinition) -> Schema
Source code in src/qgis_server_light/processing/description.py
109
110
def map_schema(self, definition: QgsProcessingOutputDefinition) -> Schema:
    return Schema(type=self.json_type)
LiteralSchemaStrategy

Bases: SchemaStrategy[QgsProcessingParameterDefinition]

A parameter with a plain JSON Schema type and the QGIS default as default.

Source code in src/qgis_server_light/processing/description.py
 93
 94
 95
 96
 97
 98
 99
100
class LiteralSchemaStrategy(SchemaStrategy[QgsProcessingParameterDefinition]):
    """A parameter with a plain JSON Schema type and the QGIS default as default."""

    def __init__(self, json_type: str):
        self.json_type = json_type

    def map_schema(self, definition: QgsProcessingParameterDefinition) -> Schema:
        return Schema(type=self.json_type, default=self.default(definition))
json_type = json_type instance-attribute
__init__(json_type: str)
Source code in src/qgis_server_light/processing/description.py
96
97
def __init__(self, json_type: str):
    self.json_type = json_type
map_schema(definition: QgsProcessingParameterDefinition) -> Schema
Source code in src/qgis_server_light/processing/description.py
 99
100
def map_schema(self, definition: QgsProcessingParameterDefinition) -> Schema:
    return Schema(type=self.json_type, default=self.default(definition))
MapLayerSchemaStrategy

Bases: LayerSchemaStrategy[QgsProcessingParameterMapLayer]

Any layer QSL can serve, a vector or a raster layer.

Source code in src/qgis_server_light/processing/description.py
282
283
284
285
286
287
class MapLayerSchemaStrategy(LayerSchemaStrategy[QgsProcessingParameterMapLayer]):
    """Any layer QSL can serve, a vector or a raster layer."""

    def source_types(self, definition: QgsProcessingParameterMapLayer) -> list[int]:
        # QGIS accepts any map layer when no source type is set
        return definition.dataTypes() or [Qgis.ProcessingSourceType.MapLayer]
source_types(definition: QgsProcessingParameterMapLayer) -> list[int]
Source code in src/qgis_server_light/processing/description.py
285
286
287
def source_types(self, definition: QgsProcessingParameterMapLayer) -> list[int]:
    # QGIS accepts any map layer when no source type is set
    return definition.dataTypes() or [Qgis.ProcessingSourceType.MapLayer]
MultipleLayersSchemaStrategy

Bases: LayerSchemaStrategy[QgsProcessingParameterMultipleLayers]

Multiple layers are multiple values of the input, each one layer.

Source code in src/qgis_server_light/processing/description.py
297
298
299
300
301
302
303
304
305
306
307
308
309
class MultipleLayersSchemaStrategy(LayerSchemaStrategy[QgsProcessingParameterMultipleLayers]):
    """Multiple layers are multiple values of the input, each one layer."""

    def source_types(self, definition: QgsProcessingParameterMultipleLayers) -> list[int]:
        return [definition.layerType()]

    def occurs(
        self, definition: QgsProcessingParameterMultipleLayers, optional: bool
    ) -> tuple[int, int | str]:
        # QGIS sets no upper limit, the lower one only counts for a required parameter
        if optional:
            return 0, "unbounded"
        return max(1, definition.minimumNumberInputs()), "unbounded"
occurs(definition: QgsProcessingParameterMultipleLayers, optional: bool) -> tuple[int, int | str]
Source code in src/qgis_server_light/processing/description.py
303
304
305
306
307
308
309
def occurs(
    self, definition: QgsProcessingParameterMultipleLayers, optional: bool
) -> tuple[int, int | str]:
    # QGIS sets no upper limit, the lower one only counts for a required parameter
    if optional:
        return 0, "unbounded"
    return max(1, definition.minimumNumberInputs()), "unbounded"
source_types(definition: QgsProcessingParameterMultipleLayers) -> list[int]
Source code in src/qgis_server_light/processing/description.py
300
301
def source_types(self, definition: QgsProcessingParameterMultipleLayers) -> list[int]:
    return [definition.layerType()]
NumberSchemaStrategy

Bases: SchemaStrategy[QgsProcessingParameterNumber]

A number with its bounds, number or integer as QGIS types it.

Source code in src/qgis_server_light/processing/description.py
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
class NumberSchemaStrategy(SchemaStrategy[QgsProcessingParameterNumber]):
    """A number with its bounds, `number` or `integer` as QGIS types it."""

    def bounds(self, definition: QgsProcessingParameterNumber) -> tuple[float | None, float | None]:
        """The bounds of the number, `None` where QGIS sets no bound."""
        if (minimum := definition.minimum()) <= -sys.float_info.max:
            minimum = None
        if (maximum := definition.maximum()) >= sys.float_info.max:
            maximum = None
        return minimum, maximum

    def map_schema(self, definition: QgsProcessingParameterNumber) -> Schema:
        """The schema of the number, the bounds QGIS sets are its minimum and maximum.

        Raises:
            ValueError: If the number type is not supported.
        """
        minimum, maximum = self.bounds(definition)
        match definition.dataType():
            case Qgis.ProcessingNumberParameterType.Double:
                return Schema(
                    type="number",
                    minimum=minimum,
                    maximum=maximum,
                    default=self.default(definition),
                )
            case Qgis.ProcessingNumberParameterType.Integer:
                return Schema(
                    type="integer",
                    minimum=None if minimum is None else int(minimum),
                    maximum=None if maximum is None else int(maximum),
                    default=self.default(definition),
                )
            case unsupported:
                raise ValueError(f"unsupported ProcessingNumberParameterType: {unsupported}")
bounds(definition: QgsProcessingParameterNumber) -> tuple[float | None, float | None]

The bounds of the number, None where QGIS sets no bound.

Source code in src/qgis_server_light/processing/description.py
116
117
118
119
120
121
122
def bounds(self, definition: QgsProcessingParameterNumber) -> tuple[float | None, float | None]:
    """The bounds of the number, `None` where QGIS sets no bound."""
    if (minimum := definition.minimum()) <= -sys.float_info.max:
        minimum = None
    if (maximum := definition.maximum()) >= sys.float_info.max:
        maximum = None
    return minimum, maximum
map_schema(definition: QgsProcessingParameterNumber) -> Schema

The schema of the number, the bounds QGIS sets are its minimum and maximum.

Raises:

  • ValueError –

    If the number type is not supported.

Source code in src/qgis_server_light/processing/description.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def map_schema(self, definition: QgsProcessingParameterNumber) -> Schema:
    """The schema of the number, the bounds QGIS sets are its minimum and maximum.

    Raises:
        ValueError: If the number type is not supported.
    """
    minimum, maximum = self.bounds(definition)
    match definition.dataType():
        case Qgis.ProcessingNumberParameterType.Double:
            return Schema(
                type="number",
                minimum=minimum,
                maximum=maximum,
                default=self.default(definition),
            )
        case Qgis.ProcessingNumberParameterType.Integer:
            return Schema(
                type="integer",
                minimum=None if minimum is None else int(minimum),
                maximum=None if maximum is None else int(maximum),
                default=self.default(definition),
            )
        case unsupported:
            raise ValueError(f"unsupported ProcessingNumberParameterType: {unsupported}")
ProcessDescriptionMapper

Maps a QGIS processing algorithm onto its process description. The schema of each parameter and output is mapped by the strategy registered for its exact QGIS class, definitions without a strategy are not supported.

Source code in src/qgis_server_light/processing/description.py
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
class ProcessDescriptionMapper:
    """Maps a QGIS processing algorithm onto its process description. The schema of each
    parameter and output is mapped by the strategy registered for its exact QGIS class,
    definitions without a strategy are not supported."""

    def __init__(self) -> None:
        self._parameter_strategies: dict[type, SchemaStrategy] = {
            QgsProcessingParameterFeatureSource: FeatureSourceSchemaStrategy(),
            QgsProcessingParameterVectorLayer: FeatureSourceSchemaStrategy(),
            QgsProcessingParameterRasterLayer: RasterLayerSchemaStrategy(),
            QgsProcessingParameterMapLayer: MapLayerSchemaStrategy(),
            QgsProcessingParameterMultipleLayers: MultipleLayersSchemaStrategy(),
            QgsProcessingParameterNumber: NumberSchemaStrategy(),
            QgsProcessingParameterDistance: NumberSchemaStrategy(),
            QgsProcessingParameterBoolean: LiteralSchemaStrategy("boolean"),
            QgsProcessingParameterString: LiteralSchemaStrategy("string"),
            QgsProcessingParameterEnum: EnumSchemaStrategy(),
        }
        self._output_strategies: dict[type, SchemaStrategy] = {
            QgsProcessingOutputVectorLayer: FileOutputSchemaStrategy(
                [
                    "application/geo+json",
                    "application/geopackage+sqlite3",
                    "application/flatgeobuf",
                ]
            ),
            QgsProcessingOutputRasterLayer: FileOutputSchemaStrategy(
                ["image/tiff; application=geotiff"]
            ),
            QgsProcessingOutputHtml: FileOutputSchemaStrategy(["text/html"]),
            QgsProcessingOutputNumber: LiteralOutputSchemaStrategy("number"),
            QgsProcessingOutputString: LiteralOutputSchemaStrategy("string"),
            QgsProcessingOutputBoolean: LiteralOutputSchemaStrategy("boolean"),
        }

    def process_description(self, algorithm: QgsProcessingAlgorithm) -> ProcessDescription:
        """The description of the algorithm as process. Destination parameters are no
        inputs, the worker sets them."""
        return ProcessDescription(
            id=algorithm.id(),
            title=algorithm.displayName(),
            description=algorithm.shortHelpString() or None,
            inputs=[
                self.input_description(param)
                for param in algorithm.parameterDefinitions()
                if not param.isDestination()
            ],
            outputs=[self.output_description(output) for output in algorithm.outputDefinitions()],
        )

    def input_description(self, param: QgsProcessingParameterDefinition) -> InputDescription:
        """The description of a parameter as input, an optional one needs no value.

        Raises:
            ValueError: If the parameter type is not supported.
        """
        strategy = self._parameter_strategies.get(type(param))
        if strategy is None:
            raise ValueError(f"unsupported parameter: {param.name()}, {type(param).__name__}")
        optional = bool(param.flags() & Qgis.ProcessingParameterFlag.Optional)
        min_occurs, max_occurs = strategy.occurs(param, optional)
        return InputDescription(
            id=param.name(),
            title=param.description(),
            description=param.help() or None,
            schema=strategy.map_schema(param),
            min_occurs=min_occurs,
            max_occurs=max_occurs,
        )

    def output_description(self, output: QgsProcessingOutputDefinition) -> OutputDescription:
        """The description of an output, a file output with the formats it is offered in.

        Raises:
            ValueError: If the output type is not supported.
        """
        strategy = self._output_strategies.get(type(output))
        if strategy is None:
            raise ValueError(f"unsupported output: {output.name()}, {type(output).__name__}")
        return OutputDescription(
            id=output.name(),
            title=output.description(),
            schema=strategy.map_schema(output),
        )
__init__() -> None
Source code in src/qgis_server_light/processing/description.py
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
def __init__(self) -> None:
    self._parameter_strategies: dict[type, SchemaStrategy] = {
        QgsProcessingParameterFeatureSource: FeatureSourceSchemaStrategy(),
        QgsProcessingParameterVectorLayer: FeatureSourceSchemaStrategy(),
        QgsProcessingParameterRasterLayer: RasterLayerSchemaStrategy(),
        QgsProcessingParameterMapLayer: MapLayerSchemaStrategy(),
        QgsProcessingParameterMultipleLayers: MultipleLayersSchemaStrategy(),
        QgsProcessingParameterNumber: NumberSchemaStrategy(),
        QgsProcessingParameterDistance: NumberSchemaStrategy(),
        QgsProcessingParameterBoolean: LiteralSchemaStrategy("boolean"),
        QgsProcessingParameterString: LiteralSchemaStrategy("string"),
        QgsProcessingParameterEnum: EnumSchemaStrategy(),
    }
    self._output_strategies: dict[type, SchemaStrategy] = {
        QgsProcessingOutputVectorLayer: FileOutputSchemaStrategy(
            [
                "application/geo+json",
                "application/geopackage+sqlite3",
                "application/flatgeobuf",
            ]
        ),
        QgsProcessingOutputRasterLayer: FileOutputSchemaStrategy(
            ["image/tiff; application=geotiff"]
        ),
        QgsProcessingOutputHtml: FileOutputSchemaStrategy(["text/html"]),
        QgsProcessingOutputNumber: LiteralOutputSchemaStrategy("number"),
        QgsProcessingOutputString: LiteralOutputSchemaStrategy("string"),
        QgsProcessingOutputBoolean: LiteralOutputSchemaStrategy("boolean"),
    }
input_description(param: QgsProcessingParameterDefinition) -> InputDescription

The description of a parameter as input, an optional one needs no value.

Raises:

  • ValueError –

    If the parameter type is not supported.

Source code in src/qgis_server_light/processing/description.py
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
def input_description(self, param: QgsProcessingParameterDefinition) -> InputDescription:
    """The description of a parameter as input, an optional one needs no value.

    Raises:
        ValueError: If the parameter type is not supported.
    """
    strategy = self._parameter_strategies.get(type(param))
    if strategy is None:
        raise ValueError(f"unsupported parameter: {param.name()}, {type(param).__name__}")
    optional = bool(param.flags() & Qgis.ProcessingParameterFlag.Optional)
    min_occurs, max_occurs = strategy.occurs(param, optional)
    return InputDescription(
        id=param.name(),
        title=param.description(),
        description=param.help() or None,
        schema=strategy.map_schema(param),
        min_occurs=min_occurs,
        max_occurs=max_occurs,
    )
output_description(output: QgsProcessingOutputDefinition) -> OutputDescription

The description of an output, a file output with the formats it is offered in.

Raises:

  • ValueError –

    If the output type is not supported.

Source code in src/qgis_server_light/processing/description.py
398
399
400
401
402
403
404
405
406
407
408
409
410
411
def output_description(self, output: QgsProcessingOutputDefinition) -> OutputDescription:
    """The description of an output, a file output with the formats it is offered in.

    Raises:
        ValueError: If the output type is not supported.
    """
    strategy = self._output_strategies.get(type(output))
    if strategy is None:
        raise ValueError(f"unsupported output: {output.name()}, {type(output).__name__}")
    return OutputDescription(
        id=output.name(),
        title=output.description(),
        schema=strategy.map_schema(output),
    )
process_description(algorithm: QgsProcessingAlgorithm) -> ProcessDescription

The description of the algorithm as process. Destination parameters are no inputs, the worker sets them.

Source code in src/qgis_server_light/processing/description.py
363
364
365
366
367
368
369
370
371
372
373
374
375
376
def process_description(self, algorithm: QgsProcessingAlgorithm) -> ProcessDescription:
    """The description of the algorithm as process. Destination parameters are no
    inputs, the worker sets them."""
    return ProcessDescription(
        id=algorithm.id(),
        title=algorithm.displayName(),
        description=algorithm.shortHelpString() or None,
        inputs=[
            self.input_description(param)
            for param in algorithm.parameterDefinitions()
            if not param.isDestination()
        ],
        outputs=[self.output_description(output) for output in algorithm.outputDefinitions()],
    )
RasterLayerSchemaStrategy

Bases: LayerSchemaStrategy[QgsProcessingParameterRasterLayer]

A raster layer.

Source code in src/qgis_server_light/processing/description.py
290
291
292
293
294
class RasterLayerSchemaStrategy(LayerSchemaStrategy[QgsProcessingParameterRasterLayer]):
    """A raster layer."""

    def source_types(self, definition: QgsProcessingParameterRasterLayer) -> list[int]:
        return [Qgis.ProcessingSourceType.Raster]
source_types(definition: QgsProcessingParameterRasterLayer) -> list[int]
Source code in src/qgis_server_light/processing/description.py
293
294
def source_types(self, definition: QgsProcessingParameterRasterLayer) -> list[int]:
    return [Qgis.ProcessingSourceType.Raster]
SchemaStrategy

Bases: ABC

Maps one kind of QGIS parameter or output definition onto the schema of its value. D is the QGIS definition class the strategy handles.

Source code in src/qgis_server_light/processing/description.py
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
class SchemaStrategy[D: QgsProcessingParameterDefinition | QgsProcessingOutputDefinition](ABC):
    """Maps one kind of QGIS parameter or output definition onto the schema of its value.
    `D` is the QGIS definition class the strategy handles."""

    @abstractmethod
    def map_schema(self, definition: D) -> Schema:
        """The schema of a single value of the parameter or output.

        Args:
            definition: The QGIS parameter or output definition.

        Returns:
            The schema of the value.
        """
        raise NotImplementedError

    def occurs(self, definition: D, optional: bool) -> tuple[int, int | str]:
        """The minimal and maximal number of values of an input.

        Args:
            definition: The QGIS parameter definition.
            optional: If the parameter is optional.

        Returns:
            The minimal and the maximal number, a single value by default.
        """
        return (0 if optional else 1), 1

    @staticmethod
    def default(definition: QgsProcessingParameterDefinition):
        """The default of the parameter, `None` if it has none."""
        default = definition.defaultValue()
        # QGIS hands out a NULL QVariant for a parameter without default, it is no value
        if isinstance(default, QVariant) and default.isNull():
            return None
        return default
default(definition: QgsProcessingParameterDefinition) staticmethod

The default of the parameter, None if it has none.

Source code in src/qgis_server_light/processing/description.py
83
84
85
86
87
88
89
90
@staticmethod
def default(definition: QgsProcessingParameterDefinition):
    """The default of the parameter, `None` if it has none."""
    default = definition.defaultValue()
    # QGIS hands out a NULL QVariant for a parameter without default, it is no value
    if isinstance(default, QVariant) and default.isNull():
        return None
    return default
map_schema(definition: D) -> Schema abstractmethod

The schema of a single value of the parameter or output.

Parameters:

  • definition (D) –

    The QGIS parameter or output definition.

Returns:

  • Schema –

    The schema of the value.

Source code in src/qgis_server_light/processing/description.py
59
60
61
62
63
64
65
66
67
68
69
@abstractmethod
def map_schema(self, definition: D) -> Schema:
    """The schema of a single value of the parameter or output.

    Args:
        definition: The QGIS parameter or output definition.

    Returns:
        The schema of the value.
    """
    raise NotImplementedError
occurs(definition: D, optional: bool) -> tuple[int, int | str]

The minimal and maximal number of values of an input.

Parameters:

  • definition (D) –

    The QGIS parameter definition.

  • optional (bool) –

    If the parameter is optional.

Returns:

  • tuple[int, int | str] –

    The minimal and the maximal number, a single value by default.

Source code in src/qgis_server_light/processing/description.py
71
72
73
74
75
76
77
78
79
80
81
def occurs(self, definition: D, optional: bool) -> tuple[int, int | str]:
    """The minimal and maximal number of values of an input.

    Args:
        definition: The QGIS parameter definition.
        optional: If the parameter is optional.

    Returns:
        The minimal and the maximal number, a single value by default.
    """
    return (0 if optional else 1), 1

worker

engine

Engine

Bases: ABC

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

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

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

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

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

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

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

        return cls

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

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

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

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

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

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

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

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

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

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

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

    def set_processing(self):
        self.info.status = Status.PROCESSING
available_job_info_classes: dict[str, type[QslJobInfoParameter]] = {} instance-attribute
available_runner_classes: dict[str, type[Runner]] = {} instance-attribute
available_runner_classes_by_job_info: dict[str, type[Runner]] = {} instance-attribute
context = context instance-attribute
info = self._initialize_infos() instance-attribute
layer_cache = LayerCache() instance-attribute
qgis = Qgis(svg_paths, log_level) instance-attribute
status property
__del__()
Source code in src/qgis_server_light/worker/engine.py
51
52
def __del__(self):
    self.qgis.exitQgis()
__init__(context: EngineContext, runner_plugins: list[str], svg_paths: list[str] | None = None, log_level=logging.WARNING)
Source code in src/qgis_server_light/worker/engine.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def __init__(
    self,
    context: EngineContext,
    runner_plugins: list[str],
    svg_paths: list[str] | None = None,
    log_level=logging.WARNING,
):
    self.qgis = Qgis(svg_paths, log_level)
    self.context = context
    self.layer_cache = LayerCache()
    self.available_runner_classes: dict[str, type[Runner]] = {}
    self.available_runner_classes_by_job_info: dict[str, type[Runner]] = {}
    self.available_job_info_classes: dict[str, type[QslJobInfoParameter]] = {}
    self._load_runner_plugins(runner_plugins)
    logging.debug(self.available_runner_classes)
    logging.debug(self.available_runner_classes_by_job_info)
    logging.debug(self.available_job_info_classes)
    self.info = self._initialize_infos()
process(job_info: QslJobInfoParameter, feedback: QgsProcessingFeedback | None = None) -> JobResult

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

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

Parameters:

  • job_info (QslJobInfoParameter) –

    The job to solve.

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

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

Returns:

  • JobResult –

    The result the runner produced.

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

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

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

    Returns:
        The result the runner produced.
    """
    self.layer_cache.evict_expired()
    runner_class = self.runner_plugin_by_job_info(job_info)
    context = JobContext(**asdict(self.context))
    context.feedback = feedback
    runner = runner_class(
        self.qgis,
        context,
        job_info,
        layer_cache=self.layer_cache,
    )
    return runner.run()
runner_plugin_by_job_info(job_info: QslJobInfoParameter) -> type[Runner]

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

Parameters:

  • job_info (QslJobInfoParameter) –

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

Returns:

  • type[Runner] –

    The selected runner class

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

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

    Returns:
        The selected runner class
    """
    try:
        return self.available_runner_classes_by_job_info[job_info.__class__.__name__]
    except KeyError as e:
        raise RuntimeError(f"Type {type(job_info)} not supported") from e
set_crashed()
Source code in src/qgis_server_light/worker/engine.py
158
159
def set_crashed(self):
    self.info.status = Status.CRASHED
set_processing()
Source code in src/qgis_server_light/worker/engine.py
161
162
def set_processing(self):
    self.info.status = Status.PROCESSING
set_waiting()
Source code in src/qgis_server_light/worker/engine.py
155
156
def set_waiting(self):
    self.info.status = Status.WAITING
EngineContext dataclass

Bases: JobContext

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

Source code in src/qgis_server_light/worker/engine.py
24
25
26
27
28
@dataclass
class EngineContext(JobContext):
    """The engine hands its context on to every job, so it carries exactly the
    attributes of `JobContext`. A new attribute is therefore added in one place only.
    """
__init__(base_path: str | Path, process_allowlist: list[str] = list(), process_output_dir: str | Path | None = None, process_internal_allowlist: list[str] = list(), process_timeout: float | None = None, process_max_output_size: int | None = None, process_max_features: int | None = None, feedback: QgsProcessingFeedback | None = None) -> None

image_utils

job_guard

JobDismissedError

Bases: Exception

The job was dismissed while it ran.

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

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

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

Attributes:

  • check_interval (float) –

    Seconds between two looks at the job.

  • cancel_grace (float) –

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

Source code in src/qgis_server_light/worker/job_guard.py
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
class JobGuard:
    """Watches a running process job from its own thread, the algorithm blocks the
    thread of the worker. Once the job is dismissed, runs longer than `timeout` or its
    outputs grow beyond `max_output_size`, the guard cancels the feedback of the job.
    QGIS algorithms check it and stop. Native code which doesn't check it would keep the
    worker busy forever, so if the job doesn't stop within `cancel_grace` the guard
    abandons it and ends the worker process the hard way, its restart brings it back.

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

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

    check_interval: float = 1.0
    cancel_grace: float = 30.0

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

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

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

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

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

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

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

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

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

Starts the clock of the timeout and the watch.

Returns:

  • QgsProcessingFeedback –

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

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

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

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

Raises:

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

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

Parameters:

  • feedback (QgsProcessingFeedback) –

    The feedback the job runs with.

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

    Tells if somebody dismissed the job.

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

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

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

    Seconds the job may run, None for no limit.

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

    The dir the job writes its outputs to.

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

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

Source code in src/qgis_server_light/worker/job_guard.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
def __init__(
    self,
    feedback: QgsProcessingFeedback,
    dismissed: Callable[[], bool],
    abandon: Callable[[Exception], None],
    timeout: float | None = None,
    output_dir: Path | None = None,
    max_output_size: int | None = None,
):
    """
    Args:
        feedback: The feedback the job runs with.
        dismissed: Tells if somebody dismissed the job.
        abandon: Finishes the job for good before the worker exits, it gets the
            reason the job was canceled for.
        timeout: Seconds the job may run, `None` for no limit.
        output_dir: The dir the job writes its outputs to.
        max_output_size: Bytes the job may write into `output_dir`, `None` for no
            limit.
    """
    self.feedback = feedback
    self.dismissed = dismissed
    self.abandon = abandon
    self.timeout = timeout
    self.output_dir = output_dir
    self.max_output_size = max_output_size
    self.reason: Exception | None = None
    self.finished = threading.Event()
    self.thread = threading.Thread(target=self.watch, name="job-guard", daemon=True)
check() -> Exception | None

Looks at the job once.

Returns:

  • Exception | None –

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

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

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

The bytes the job has written so far.

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

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

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

Bases: Exception

The job ran too long or wrote too much.

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

layer_cache

DEFAULT_TTL_SECONDS = 24 * 60 * 60 module-attribute
LayerCache

Bases: MutableMapping[str, QgsMapLayer]

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

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

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

Source code in src/qgis_server_light/worker/layer_cache.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class LayerCache(MutableMapping[str, QgsMapLayer]):
    """Layers opened by the worker, shared by all jobs of the worker process.

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

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

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

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

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

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

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

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

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

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

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

Evicts all layers which were not used within the TTL.

Returns:

  • int –

    The number of evicted layers.

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

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

qgis

CredentialsHelper

Bases: QgsCredentials

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

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

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

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

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

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

        qgs.credentialsHelper = CredentialsHelper()

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

qgis_type_serializer

QDateConverter

Bases: Converter

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

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

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

Bases: Converter

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

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

    def serialize(self, value: QDateTime, **kwargs: Any) -> str | None:
        if value:
            return value.toString(self.format)
        else:
            return None
format = Qt.DateFormat.ISODate class-attribute instance-attribute
deserialize(value: str, **kwargs: Any) -> QDateTime
Source code in src/qgis_server_light/worker/qgis_type_serializer.py
25
26
def deserialize(self, value: str, **kwargs: Any) -> QDateTime:
    return QDateTime.fromString(value, self.format)
serialize(value: QDateTime, **kwargs: Any) -> str | None
Source code in src/qgis_server_light/worker/qgis_type_serializer.py
28
29
30
31
32
def serialize(self, value: QDateTime, **kwargs: Any) -> str | None:
    if value:
        return value.toString(self.format)
    else:
        return None
register_converters_at_runtime()
Source code in src/qgis_server_light/worker/qgis_type_serializer.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@contextmanager
def register_converters_at_runtime():
    def register(custom_type, converter_instance, registered_types):
        converter.register_converter(custom_type, converter_instance)
        registered_types.append(custom_type)

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

redis

DEFAULT_DATA_ROOT = '/io/data' module-attribute
DEFAULT_PROCESS_ALLOWLIST = ','.join(['native:buffer', 'native:centroids']) module-attribute
DEFAULT_PROCESS_MAX_FEATURES = 1000000 module-attribute
DEFAULT_PROCESS_MAX_OUTPUT_SIZE = 1024 module-attribute
DEFAULT_PROCESS_OUTPUT_DIR = '/io/process_output' module-attribute
DEFAULT_PROCESS_TIMEOUT = 3600 module-attribute
DEFAULT_RUNNER_PLUGINS = ':'.join(['qgis_server_light.worker.runner.render.RenderRunner', 'qgis_server_light.worker.runner.legend.GetLegendRunner', 'qgis_server_light.worker.runner.feature.GetFeatureRunner', 'qgis_server_light.worker.runner.crs.CrsRunner']) module-attribute
DEFAULT_SVG_PATH = '/io/svg' module-attribute
engine_classes: dict[str, type[RedisEngine]] = {'publish': RedisPublishEngine, 'state': RedisStateEngine} module-attribute
JobProgress

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

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

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

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

Bases: Engine

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

Attributes:

  • protocol (type[RedisProtocol]) –

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

Source code in src/qgis_server_light/worker/redis.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
class RedisEngine(Engine):
    """The common part of the redis workers: connecting, registering, the
    heartbeat and the loop taking jobs from the queue. How a finished job is
    delivered is decided by the subclasses, so the loop does not need to know
    about it.

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

    protocol: type[RedisProtocol]

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

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

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

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

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

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

        Args:
            client: The redis client.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Parameters:

  • job_id (str) –

    The unique identifier of the job.

  • job_info (QslJobInfoParameter | None) –

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

  • error (Exception) –

    The error the job failed with.

  • pipeline (Pipeline) –

    The pipeline holding the transaction.

  • start_time (float) –

    The time the job was taken from the queue.

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

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

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

Parameters:

  • client (Redis) –

    The redis client.

Returns:

  • datetime –

    The UTC timestamp which was written as last seen.

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

    Args:
        client: The redis client.

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

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

Parameters:

  • client (Redis) –

    The redis client.

  • job_id (str) –

    The unique identifier of the job.

  • job_info (QslJobInfoParameter) –

    The job info of the job.

  • start_time (float) –

    The time the job was taken from the queue.

Returns:

  • AbstractContextManager[QgsProcessingFeedback | None] –

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

  • AbstractContextManager[QgsProcessingFeedback | None] –

    listens.

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

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

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

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

Parameters:

  • client (Redis) –

    The redis client.

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

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

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

Parameters:

  • client (Redis) –

    The redis client.

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

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

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

Parameters:

  • client (Redis) –

    The redis client.

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

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

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

Parameters:

  • redis_url –

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

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

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

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

Parameters:

  • r (Redis) –

    The redis client.

  • p (Pipeline) –

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

  • redis_url (str) –

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

Source code in src/qgis_server_light/worker/redis.py
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def serve_jobs(self, r: Redis, p: Pipeline, redis_url: str):
    """The job loop: takes the next job from the queue, processes it and publishes
    the result. A failing job is published as an error result, the loop goes on. A
    dismissed job is delivered the same way, but only noted in the log, somebody
    asked for it. With `once` the loop ends after the first job. When the connection
    to redis is lost, the loop waits for it to come back and carries on, the
    heartbeat thread takes care of advertising the worker again.

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

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

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

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

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

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

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

Delivers the result of a job which was solved.

Parameters:

  • job_id (str) –

    The unique identifier of the job.

  • job_info (QslJobInfoParameter) –

    The job info of the job.

  • result (JobResult) –

    The result the runner returned.

  • pipeline (Pipeline) –

    The pipeline holding the transaction.

  • start_time (float) –

    The time the job was taken from the queue.

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

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

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

Parameters:

  • client (Redis) –

    The redis client.

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

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

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

Parameters:

  • client (Redis) –

    The redis client.

  • redis_url (str) –

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

Source code in src/qgis_server_light/worker/redis.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
def wait_for_connection(self, client: Redis, redis_url: str):
    """Pings redis until it answers, waiting a bit longer after each refused ping.
    It is used on start and whenever the job loop lost the connection. Each outage
    gets the full number of retries, a worker which survived many short hiccups
    should not give up on the next one just because it used them up already.

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

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

Parameters:

  • client (Redis) –

    The redis client.

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

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

Bases: RedisEngine

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

Source code in src/qgis_server_light/worker/redis.py
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
class RedisPublishEngine(RedisEngine):
    """The engine publishing the result to the waiting dispatcher (see
    `RedisPublishProtocol`). This is the default, map related jobs are served
    by it.
    """

    protocol = RedisPublishProtocol

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

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

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

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

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

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

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

Parameters:

  • job_id (str) –

    The unique identifier of the job.

  • result (JobResult) –

    The result to publish, the worker information is added.

  • pipeline (Pipeline) –

    The pipeline holding the transaction.

  • status (str) –

    The final status of the job.

  • start_time (float) –

    The time the job was taken from the queue.

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

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

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

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

Bases: RedisEngine

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

Source code in src/qgis_server_light/worker/redis.py
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
class RedisStateEngine(RedisEngine):
    """The engine keeping the result in the job hash (see `RedisStateProtocol`).
    Process-workers are started with it.
    """

    protocol = RedisStateProtocol

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

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

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

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

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

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

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

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

Parameters:

  • client (Redis) –

    The redis client.

  • job_id (str) –

    The unique identifier of the job.

  • job_info (QslJobInfoParameter) –

    The job info of the job.

  • reason (Exception) –

    Why the job was canceled.

  • start_time (float) –

    The time the job was taken from the queue.

Source code in src/qgis_server_light/worker/redis.py
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
def abandon_job(
    self,
    client: Redis,
    job_id: str,
    job_info: QslJobInfoParameter,
    reason: Exception,
    start_time: float,
):
    """Finishes a job which didn't stop after it was canceled, right before the
    worker exits. It runs in the thread of the guard, the thread of the worker is
    still stuck in the algorithm, so it has its own pipeline.

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

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

Parameters:

  • job_id (str) –

    The unique identifier of the job.

  • job_info (QslJobInfoParameter | None) –

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

  • pipeline (Pipeline) –

    The pipeline holding the transaction.

  • status (str) –

    The final status of the job.

  • start_time (float) –

    The time the job was taken from the queue.

Source code in src/qgis_server_light/worker/redis.py
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
def finish_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter | None,
    pipeline: Pipeline,
    status: str,
    start_time: float,
):
    """Renews the expiry, sets the final status and notifies a waiting
    dispatcher. Success and failure only differ in the fields written
    before, so both end here.

    Args:
        job_id: The unique identifier of the job.
        job_info: The job info of the job, `None` if it could not be read. A
            waiting dispatcher can not be ruled out then, so it is notified.
        pipeline: The pipeline holding the transaction.
        status: The final status of the job.
        start_time: The time the job was taken from the queue.
    """
    # the fields written before are executed in the same transaction as the
    # final status
    pipeline.expire(self.protocol.job_key(job_id), self.protocol.job_expire)
    self.set_job_runtime_status(job_id, pipeline, status, start_time)
    # the notification only wakes a waiting dispatcher, the job hash is
    # written already
    if job_info is None or job_info.execution_mode == ExecutionMode.SYNC:
        pipeline.publish(self.protocol.channel(job_id), status)
job_guard(client: Redis, job_id: str, job_info: QslJobInfoParameter, start_time: float) -> JobGuard
Source code in src/qgis_server_light/worker/redis.py
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
def job_guard(
    self, client: Redis, job_id: str, job_info: QslJobInfoParameter, start_time: float
) -> JobGuard:
    job_key = self.protocol.job_key(job_id)
    feedback = QgsProcessingFeedback()
    # the algorithm runs in this thread, so the signal calls it directly
    feedback.progressChanged.connect(
        JobProgress(client, job_key, self.protocol.job_progress_key)
    )
    output_dir = self.context.process_output_dir
    return JobGuard(
        feedback,
        dismissed=lambda: bool(client.hexists(job_key, self.protocol.job_cancel_key)),
        abandon=lambda reason: self.abandon_job(client, job_id, job_info, reason, start_time),
        timeout=self.context.process_timeout,
        output_dir=Path(output_dir, job_id) if output_dir is not None else None,
        max_output_size=self.context.process_max_output_size,
    )
succeed_job(job_id: str, job_info: QslJobInfoParameter, result: JobResult, pipeline: Pipeline, start_time: float)
Source code in src/qgis_server_light/worker/redis.py
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
def succeed_job(
    self,
    job_id: str,
    job_info: QslJobInfoParameter,
    result: JobResult,
    pipeline: Pipeline,
    start_time: float,
):
    pipeline.hset(self.protocol.job_key(job_id), self.protocol.job_result_key, result.data)
    pipeline.hset(
        self.protocol.job_key(job_id),
        self.protocol.job_result_content_type_key,
        result.content_type,
    )
    self.finish_job(job_id, job_info, pipeline, Status.SUCCESS.value, start_time)
main() -> None
Source code in src/qgis_server_light/worker/redis.py
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
def main() -> None:
    parser = argparse.ArgumentParser()

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

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

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

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

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

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

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

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

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

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

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

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

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

    args = parser.parse_args()

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

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

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

runner

common
ImageRunner

Bases: MapRunner

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

Source code in src/qgis_server_light/worker/runner/common.py
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
class ImageRunner(MapRunner):
    """Base class for any map runner which answers with an encoded image.
    Not runnable by itself.
    """

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

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

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

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

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

Attributes:

  • base_path (str | Path) –

    The absolute path to the data dir.

  • process_allowlist (list[str]) –

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

  • process_output_dir (str | Path | None) –

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

  • process_internal_allowlist (list[str]) –

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

  • process_timeout (float | None) –

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

  • process_max_output_size (int | None) –

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

  • process_max_features (int | None) –

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

  • feedback (QgsProcessingFeedback | None) –

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

Source code in src/qgis_server_light/worker/runner/common.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
@dataclass
class JobContext:
    """What a runner needs to know about the worker it runs on. The engine hands each job
    its own copy.

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

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

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

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

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

Bases: Runner

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

Source code in src/qgis_server_light/worker/runner/common.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
class MapRunner(Runner):
    """Base class for any runner that interacts with a map.
    Not runnable by itself.
    """

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

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

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

        def preprocessor(path):
            return path

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

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

        settings.setDestinationCrs(destination_crs)
        return settings

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Bases: ABC

Source code in src/qgis_server_light/worker/runner/common.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
class Runner(ABC):
    job_info_class: type[QslJobInfoParameter]

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

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

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

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

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

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

Parameters:

  • qgis (QgsApplication) –

    The QGIS application of the worker.

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

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

Bases: Runner

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

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

    job_info_class = QslJobInfoCrs

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

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

Bases: MapRunner

Source code in src/qgis_server_light/worker/runner/feature.py
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
class GetFeatureRunner(MapRunner):
    job_info_class = QslJobInfoFeature

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

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

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

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

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

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

            for job_layer_definition, layer in zip(query.layers, self.map_layers, strict=True):
                feature_collection = FeatureCollection(job_layer_definition.id)
                query_collection.feature_collections.append(feature_collection)
                if isinstance(layer, QgsVectorLayer):
                    if wfs_filter is not None and wfs_filter.definition is not None:
                        # TODO: This is potentially bad: We always get all features from
                        #  datasource. However, QGIS
                        #   does not seem to support sliding window feature filter out of the box...
                        logging.info(" QslJobLayer is filtered by:")
                        logging.info(f" {wfs_filter.definition}")
                        filter_doc = QDomDocument()
                        filter_doc.setContent(wfs_filter.definition)
                        # This is not correct in the WFS 2.0 way. We apply a filter
                        # to a job_layer_definition. But WFS 2.0
                        # allows filters on multiple layers.
                        # The layer is used to type literals by the field types.
                        expression = QgsOgcUtils.expressionFromOgcFilter(
                            filter_doc.documentElement(),
                            QgsOgcUtils.FilterVersion.FILTER_FES_2_0,
                            layer,
                        )
                        logging.info(
                            f" This was transformed to the QGIS expression "
                            f"(valid: {expression.isValid()})"
                        )
                        logging.info(f" '{expression.dump()}'")
                        feature_request = QgsFeatureRequest(expression)
                        # geom_from_gml takes the layer out of the expression context to
                        # transform geometry literals with srsName into the layer crs
                        feature_request.setExpressionContext(
                            QgsExpressionContext(
                                QgsExpressionContextUtils.globalProjectLayerScopes(layer)
                            )
                        )
                    else:
                        feature_request = QgsFeatureRequest()
                    if destination_crs is not None:
                        # filter expressions are still evaluated in the layer crs, only
                        # the returned geometries are transformed
                        feature_request.setDestinationCrs(destination_crs, layer.transformContext())
                    feature_iterator = layer.getFeatures(feature_request)
                    if not feature_iterator.isValid():
                        self._raise_on_layer_errors({layer.id(): "Data source invalid"})
                    layer_features = list(feature_iterator)
                    numbers_matched += len(layer_features)
                    logging.info(f" Found {len(layer_features)} features")
                    if self.job_info.job.count:
                        layer_features = layer_features[
                            self.job_info.job.start_index : self.job_info.job.start_index
                            + self.job_info.job.count
                        ]
                    for layer_feature in layer_features:
                        property_list = zip(
                            layer_feature.fields().names(),
                            self._clean_attributes(layer_feature.attributes(), layer),
                            strict=True,
                        )
                        feature = Feature(
                            geometry=Geometry(
                                value=bytes(layer_feature.geometry().asWkb()),
                            )
                        )
                        feature_collection.features.append(feature)
                        for name, value in property_list:
                            feature.attributes.append(Attribute(name=name, value=value))
                else:
                    raise RuntimeError(
                        f"QslJobLayer type `{layer.type().name}` of layer "
                        f"`{layer.shortName()}` not supported by GetFeatureInfo"
                    )
        if numbers_matched > 0:
            query_collection.numbers_matched = numbers_matched
        with register_converters_at_runtime():
            data = JsonSerializer().render(query_collection).encode()
            return JobResult(
                id=self.job_info.id,
                data=data,
                content_type="application/qgis-server-light.interface.qgis.QueryCollection",
            )
job_info_class = QslJobInfoFeature class-attribute instance-attribute
__init__(qgis: QgsApplication, context: JobContext, job_info: QslJobInfoFeature, layer_cache: MutableMapping | None = None, layer_style_cache: set | None = None) -> None
Source code in src/qgis_server_light/worker/runner/feature.py
37
38
39
40
41
42
43
44
45
def __init__(
    self,
    qgis: QgsApplication,
    context: JobContext,
    job_info: QslJobInfoFeature,
    layer_cache: MutableMapping | None = None,
    layer_style_cache: set | None = None,
) -> None:
    super().__init__(qgis, context, job_info, layer_cache)
run()
Source code in src/qgis_server_light/worker/runner/feature.py
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def run(self):
    query_collection = QueryCollection()
    numbers_matched = 0
    for query in self.job_info.job.queries:
        # we need to reset this because we want always only the layers related to
        # the current query
        self.map_layers = []
        wfs_filter = query.filter
        destination_crs = self._destination_crs(query.crs)
        for job_layer_definition in query.layers:
            self._provide_layer(job_layer_definition)

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

Bases: MapRunner

Source code in src/qgis_server_light/worker/runner/feature_info.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class GetFeatureInfoRunner(MapRunner):
    job_info_class = QslJobInfoFeatureInfo

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

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

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

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

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

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

        featurecollection = {"features": features, "type": "FeatureCollection"}
        return JobResult(
            id=self.job_info.id,
            data=json.dumps(featurecollection).encode("utf-8"),
            content_type="application/json",
        )
job_info_class = QslJobInfoFeatureInfo class-attribute instance-attribute
__init__(qgis: QgsApplication, context: JobContext, job_info: QslJobInfoFeatureInfo, layer_cache: MutableMapping | None = None) -> None
Source code in src/qgis_server_light/worker/runner/feature_info.py
23
24
25
26
27
28
29
30
def __init__(
    self,
    qgis: QgsApplication,
    context: JobContext,
    job_info: QslJobInfoFeatureInfo,
    layer_cache: MutableMapping | None = None,
) -> None:
    super().__init__(qgis, context, job_info, layer_cache)
run()
Source code in src/qgis_server_light/worker/runner/feature_info.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
def run(self):
    for job_layer_definition in self.job_info.job.layers:
        self._provide_layer(job_layer_definition)
    map_settings = self._get_map_settings(self.map_layers)
    # Estimate queryable bbox (2mm)
    map_to_pixel = map_settings.mapToPixel()
    map_point = map_to_pixel.toMapCoordinates(self.job_info.job.x, self.job_info.job.y)
    # Create identifiable bbox in map coordinates, ±2mm
    tolerance = 0.002 * 39.37 * map_settings.outputDpi()
    tl = QgsPointXY(map_point.x() - tolerance, map_point.y() - tolerance)
    br = QgsPointXY(map_point.x() + tolerance, map_point.y() + tolerance)
    rect = QgsRectangle(tl, br)
    render_context = QgsRenderContext.fromMapSettings(map_settings)

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

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

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

Bases: ImageRunner

Source code in src/qgis_server_light/worker/runner/legend.py
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
class GetLegendRunner(ImageRunner):
    job_info_class = QslJobInfoLegend

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

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

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

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

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

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

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

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

        renderer = QgsLegendRenderer(model, settings)

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

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

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

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

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

        renderer.drawLegend(painter)
        painter.end()

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

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

    @staticmethod
    def _export_json(renderer: QgsLegendRenderer) -> bytes:
        # same as QGIS Server does it, a default render context is enough here
        legend = renderer.exportLegendToJson(QgsRenderContext())
        return bytes(QJsonDocument(legend).toJson(QJsonDocument.JsonFormat.Compact))
job_info_class = QslJobInfoLegend class-attribute instance-attribute
__init__(qgis: QgsApplication, context: JobContext, job_info: QslJobInfoLegend, layer_cache: MutableMapping | None = None) -> None
Source code in src/qgis_server_light/worker/runner/legend.py
24
25
26
27
28
29
30
31
def __init__(
    self,
    qgis: QgsApplication,
    context: JobContext,
    job_info: QslJobInfoLegend,
    layer_cache: MutableMapping | None = None,
) -> None:
    super().__init__(qgis, context, job_info, layer_cache)
json_formats() classmethod
Source code in src/qgis_server_light/worker/runner/legend.py
33
34
35
@classmethod
def json_formats(cls):
    return ["application/json", "json"]
run()
Source code in src/qgis_server_light/worker/runner/legend.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def run(self):
    logging.info(f"Executing job: {self.job_info}")
    for job_layer_definition in self.job_info.job.layers:
        self._provide_layer(job_layer_definition)

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

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

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

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

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

    renderer = QgsLegendRenderer(model, settings)

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

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

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

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

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

    renderer.drawLegend(painter)
    painter.end()

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

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

Bases: MapRunner

Responsible for executing a QGIS processing algorithm as a process.

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

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

Attributes:

Source code in src/qgis_server_light/worker/runner/process.py
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
class ProcessRunner(MapRunner):
    """Responsible for executing a QGIS processing algorithm as a process.

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

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

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

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

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

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

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

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

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

        Returns:
            The descriptions of the processes the worker serves.

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

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

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

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

        Returns:
            A JobResult with the ProcessResult as JSON.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        Returns:
            The absolute destination files by destination name.

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

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

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

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

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

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

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

        Returns:
            The outputs and the log of the algorithm.

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

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

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

Parameters:

  • qgis (QgsApplication) –

    The QGIS application holding the processing registry.

  • context (JobContext) –

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

Returns:

Raises:

  • LookupError –

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

Source code in src/qgis_server_light/worker/runner/process.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
@classmethod
def info(cls, qgis: QgsApplication, context: JobContext) -> ProcessDescriptions:
    """The descriptions of the processes the worker serves. An algorithm of the
    allowlist the worker can't serve is skipped and logged, so one entry can't empty
    the processes of the worker. That's the case for a parameter without mapping and
    for an algorithm requiring a project, the context of the runner has none.

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

    Returns:
        The descriptions of the processes the worker serves.

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

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

Parameters:

  • qgis (QgsApplication) –

    The QGIS application of the worker.

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

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

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

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

Run this runner.

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

Returns:

  • –

    A JobResult with the ProcessResult as JSON.

Raises:

  • RuntimeError –

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

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

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

    Returns:
        A JobResult with the ProcessResult as JSON.

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

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

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

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

Bases: ImageRunner

Responsible for rendering a QslRenderJob to an image.

Source code in src/qgis_server_light/worker/runner/render.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class RenderRunner(ImageRunner):
    """Responsible for rendering a QslRenderJob to an image."""

    job_info_class = QslJobInfoRender

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

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

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

Source code in src/qgis_server_light/worker/runner/render.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def run(self):
    """Run this runner.
    Returns:
        A JobResult with the content_type and image_data (bytes) of the rendered image.
    """
    logging.info(f"Executing job: {self.job_info}")
    feature_filter = QgsFeatureFilter()
    for job_layer_definition in self.job_info.job.layers:
        self._provide_layer(job_layer_definition)
    map_settings = self._get_map_settings(self.map_layers)
    # QGIS emits finished synchronously in start() on invalid settings (e.g.
    # an empty bbox), before the event loop runs, so it would wait forever
    if not map_settings.hasValidSettings():
        raise RuntimeError(
            f"Invalid map settings, bbox: {self.job_info.job.bbox}, "
            f"size: {self.job_info.job.width}x{self.job_info.job.height}"
        )
    # same as QGIS Server GetMap, enables the simplification on rendering
    # which is defined in the layer styles
    map_settings.setFlag(Qgis.MapSettingsFlag.UseRenderingOptimization)
    filter_providers = QgsFeatureFilterProviderGroup()
    filter_providers.addProvider(feature_filter)
    renderer = QgsMapRendererParallelJob(map_settings)
    renderer.setFeatureFilterProvider(filter_providers)
    event_loop = QEventLoop(self.qgis)
    renderer.finished.connect(event_loop.quit)
    renderer.start()
    event_loop.exec_()
    self._raise_on_layer_errors({error.layerID: error.message for error in renderer.errors()})
    img = renderer.renderedImage()
    img.setDotsPerMeterX(int(map_settings.outputDpi() * 39.37))
    img.setDotsPerMeterY(int(map_settings.outputDpi() * 39.37))
    content_type, image_data = self._encode_image(img, self.job_info.job.format)
    return JobResult(id=self.job_info.id, data=image_data, content_type=content_type)