├── .editorconfig
├── .github
└── workflows
│ ├── build.yml
│ └── package.yml
├── .gitignore
├── CONFIGURATION.md
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── pyproject.toml
├── sample
├── admin.sql.jinja2
├── config.yaml
├── country.sql.jinja2
├── ne-admin.sql.jinja2
└── water.sql.jinja2
├── tests
├── test_config.py
├── test_definition.py
├── test_storage.py
├── test_tile.py
└── test_tilerange.py
├── tilekiln
├── __init__.py
├── config.py
├── definition.py
├── dev
│ └── __init__.py
├── errors.py
├── generator.py
├── kiln.py
├── main.py
├── metric.py
├── prometheus.py
├── scripts
│ ├── __init__.py
│ ├── config.py
│ ├── generate.py
│ ├── serve.py
│ └── storage.py
├── server
│ └── __init__.py
├── storage.py
├── tile.py
├── tilerange.py
└── tileset.py
└── tox.ini
/.editorconfig:
--------------------------------------------------------------------------------
1 | # EditorConfig is awesome: https://EditorConfig.org
2 |
3 | root = true
4 |
5 | [*]
6 | charset = utf-8
7 | indent_style = space
8 | trim_trailing_whitespace = true
9 | insert_final_newline = true
10 | end_of_line = lf
11 | indent_size = 4
12 |
13 | [*.sql.jinja2]
14 | indent_style = space
15 | indent_size = 2
16 |
17 | [*.yaml]
18 | indent_style = space
19 | indent_size = 2
20 |
--------------------------------------------------------------------------------
/.github/workflows/build.yml:
--------------------------------------------------------------------------------
1 | ---
2 | name: Python build
3 | on: [push, pull_request]
4 | jobs:
5 | build:
6 | runs-on: ubuntu-latest
7 | strategy:
8 | fail-fast: false
9 | matrix:
10 | python-version: ["3.10", "3.11", "3.12"]
11 | steps:
12 | - uses: actions/checkout@v4
13 | - name: Set up Python ${{ matrix.python-version }}
14 | uses: actions/setup-python@v5
15 | with:
16 | python-version: ${{ matrix.python-version }}
17 | - name: Install dependencies
18 | run: |
19 | python -m pip install --upgrade pip
20 | python -m pip install flake8 mypy pytest types-PyYAML types-tqdm
21 | - name: Install tilekiln
22 | run: python -m pip install -e .
23 | - name: Lint with flake8
24 | run: flake8 tilekiln tests --count
25 | - name: Static analysis with mypy
26 | run: mypy tilekiln tests
27 | - name: Test with pytest
28 | run: pytest
29 |
--------------------------------------------------------------------------------
/.github/workflows/package.yml:
--------------------------------------------------------------------------------
1 | ---
2 | name: Python package
3 | on:
4 | workflow_dispatch:
5 | push:
6 | branches: [main]
7 | tags: "v*"
8 | pull_request:
9 | release:
10 | types: [published]
11 | jobs:
12 | package:
13 | name: Build & inspect our package.
14 | runs-on: ubuntu-latest
15 | steps:
16 | - uses: actions/checkout@v4
17 | with:
18 | fetch-depth: 0
19 | - uses: hynek/build-and-inspect-python-package@v2
20 | publish-to-testpypi:
21 | name: Upload release to TestPyPI
22 | needs: [package]
23 | runs-on: ubuntu-latest
24 | if: github.event_name == 'push'
25 | environment:
26 | name: testpypi
27 | url: https://test.pypi.org/p/tilekiln
28 | permissions:
29 | id-token: write
30 | steps:
31 | - uses: actions/download-artifact@v4
32 | with:
33 | name: Packages
34 | path: dist
35 | - uses: pypa/gh-action-pypi-publish@release/v1
36 | with:
37 | repository-url: https://test.pypi.org/legacy/
38 | skip-existing: true
39 |
40 | publish-to-pypi:
41 | name: Publish tagged versions to PyPi
42 | runs-on: ubuntu-latest
43 | if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags')
44 | needs: [publish-to-testpypi]
45 | environment:
46 | name: pypi
47 | url: https://pypi.org/p/tilekiln
48 | permissions:
49 | id-token: write
50 | steps:
51 | - uses: actions/download-artifact@v4
52 | with:
53 | name: Packages
54 | path: dist
55 | - uses: pypa/gh-action-pypi-publish@release/v1
56 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | __pycache__/
2 |
3 | # Tests
4 | .tox/
5 |
6 | # Distribution / packaging
7 | .eggs/
8 | *.egg-info/
9 |
10 | # Environments
11 | venv/
12 |
--------------------------------------------------------------------------------
/CONFIGURATION.md:
--------------------------------------------------------------------------------
1 | # Tilekiln Configuration Specification
2 |
3 | The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt).
4 |
5 | ## Overview
6 |
7 | A tilekiln configuration is composed of a REQUIRED YAML configuration file with zero or more OPTIONAL SQL Jinja2 files.
8 |
9 | ## Configuration
10 |
11 | The configuration SHALL be a [YAML](https://yaml.org/spec/1.2/spec.html) document. It MUST NOT be a YAML stream containing multiple documents.
12 |
13 | ## SQL Files
14 |
15 | SQL Jinja files are processed with Jinja2 as documented below. They SHOULD form a valid PostgreSQL SELECT statement with one column which is a PostGIS geometry in the coordinates space of the vector tile. This SHOULD be done with `ST_AsMVTGeom(geom, {{bbox}}, {{extent}}))`.
16 |
17 | ### Jinja substitutions
18 |
19 | #### `{{ zoom }}`
20 |
21 | The zoom of the tile being generated.
22 |
23 | #### `{{ x }}`
24 |
25 | The x coordinate of the tile being generated.
26 |
27 | #### `{{ y }}`
28 |
29 | The y coordinate of the tile being generated.
30 |
31 | #### `{{ bbox }}`
32 |
33 | A SQL statement that evaluates to the buffered bounding box of the tile being generated.
34 |
35 | #### `{{ unbuffered_bbox }}`
36 |
37 | A SQL statement that evaluates to the unbuffered bounding box of the tile being generated.
38 |
39 | #### `{{ extent }}`
40 |
41 | The tile [extent](https://github.com/mapbox/vector-tile-spec/tree/master/2.1#3-projection-and-bounds) in screen space.
42 |
43 | #### `{{ buffer }}`
44 |
45 | The tile buffer, in units of tile coordinate space.
46 |
47 | #### `{{ tile_length }}`
48 |
49 | The side length of the tile being generated in web mercator meters.
50 |
51 | #### `{{ tile_area }}`
52 |
53 | The area of the tile being generated in square web mercator meters. Equal to `{{ tile_length }}` squared.
54 |
55 | #### `{{ coordinate_length }}`
56 |
57 | The side length of one unit in the coordinate space of the tile being generated in web mercator meters. Equal to `{{ tile_length }} / {{ extent }}`.
58 |
59 | #### `{{ coordinate_area }}`
60 |
61 | The area of one unit in the coordinate space of the tile being generated in square web mercator meters. Equal to `{{ coordinate_length }}` squared.
62 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | ## General guidance
4 |
5 | Tilekiln is an open source project and welcomes contributions from others. If it's something big that you want to do, you should open issue first to make sure it will fit in with the plans. Please keep in mind the following guidelines
6 |
7 | 1. Keep the codebase small and simple. Easier development means more time writing styles.
8 | 2. Make writing simple schemas easy and complex ones possible. There are a lot of specialized tasks needed for some styles, and it needs to be possible to implement them, but we want a simple experience for simple styles.
9 | 3. Consider if what you want can be done with Jinja2 templates already, and if so if it should be added.
10 | 4. Consider adding functionality to PostGIS. If a task that needs doing has wider applicability than just vector tiles, consider if it should be added to PostGIS.
11 | 5. Keep all knowledge of the Mapbox Vector Tile format confined to PostGIS. See point #1 above. Trying to write vector tile generation code is fraught with difficulties. That's why Tilekiln doesn't, instead it relies on PostGIS knowing how to generate vector tiles. Because so many people use ST_AsMVT and ST_AsMVTGeom, they are well tested, reliable, and well supported functions.
12 |
13 | ## Development install
14 |
15 | A development install requires Python 3.10+, and normally will require a PostgreSQL 10+ PostGIS 3.1+ server.
16 |
17 | For a conventional development install on a machine running a recent common Linux distribution with standard settings,
18 |
19 | ```bash
20 | python3 -m venv venv
21 | . venv/bin/activate
22 | pip install -e .
23 | pip install flake8 pytest
24 | ```
25 |
26 | You can then edit code and run the `tilekiln` command.
27 |
28 | ## Pre-commit checks
29 | Make sure to run pre-commit checks so that your PR won't fail in CI
30 |
31 | ```sh
32 | flake8 tilekiln tests
33 | mypy tilekiln tests
34 | pytest
35 | ```
36 |
37 | If you have pytest installed elsewhere on your system, it might not know to use the one associated with the venv. If so, instead run `venv/bin/pytest`.
38 |
39 | ## Releases
40 |
41 | Releases are automatically built from tagged commits. Tag the version number, beginning with `v`. If you want to use a development version, these are automatically built for TestPyPI.
42 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type 'show c' for details.
659 |
660 | The hypothetical commands 'show w' and 'show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Tilekiln
2 |
3 | ## Background
4 |
5 | Tilekiln is a set of command-line utilities to generate and serve Mapbox Vector Tiles (MVTs).
6 |
7 | Generation relies on the standard method of a PostgreSQL + PostGIS server as a data source, and ST_AsMVT to serialize the MVTs.
8 |
9 | The target use-case is vector tiles for a worldwide complex basemap under high load which requires minutely updates. If only daily updates are required options like [tilemaker](https://tilemaker.org/) or [planetiler](https://github.com/onthegomap/planetiler) may be simpler to host.
10 |
11 | ## Requirements
12 |
13 | Tilekiln requires a PostGIS database with data loaded to generate vector tiles.
14 |
15 | [OpenStreetMap Carto's](https://github.com/gravitystorm/openstreetmap-carto/blob/master/INSTALL.md#openstreetmap-data) directions are a good starting place for loading OpenStreetMap data into a PostGIS database, but any PostGIS data source in EPSG 3857 will work.
16 |
17 | - PostgreSQL 10+
18 | - PostGIS 3.1+
19 | - Python 3.10
20 |
21 | ## Concepts
22 |
23 | Tilekiln issues queries against a *source* database to generate Mapbox Vector Tile (MVT) layers, assembles the layers into a tile, then either serves the tile to the user or stores it in a *storage* database. It can also serve previously generated tiles from the *storage* database which completely removes the *source* database out of the critical path for serving tiles.
24 |
25 | Utility commands allow checking of configurations, storage management, and debugging as well as commands for monitoring metrics needed in production.
26 |
27 | ## Usage
28 | Tilekiln commands can be broken into two sets, commands which involve serving tiles, and CLI commands. Command-line options can be found with `tilekiln --help`, which includes a listing and description of all options.
29 |
30 | ### CLI commands
31 | CLI commands will perform a task then exit, returning to ther shell.
32 |
33 | #### `config`
34 | Commands to work with and check config files
35 |
36 | ##### `config test`
37 | Tests a config for validity.
38 |
39 | The process will exit with exit code 0 if tilekiln can load the config.
40 |
41 | This is intended for build and CI scripts used by configs.
42 |
43 | ##### `config sql`
44 | Print the SQL for a tile or layer.
45 |
46 | Prints the SQL that would be issued to generate a particular tile layer,
47 | or if no layer is given, the entire tile. This allows manual debugging of
48 | a tile query.
49 |
50 | #### `generate`
51 | Commands for tile generation.
52 |
53 | All tile generation commands run queries against the source database which
54 | has the geospatial data.
55 |
56 | ##### `generate tiles`
57 | Generate specific tiles.
58 |
59 | A list of z/x/y tiles is read from stdin and those tiles are generated and
60 | saved to storage. The entire list is read before deletion starts.
61 |
62 | ##### `generate zoom`
63 | Generate all tiles by zoom.
64 |
65 | ##### `generate layers`
66 | Generate specific layers for specific tiles.
67 |
68 | #### `storage`
69 | Commands working with tile storage.
70 |
71 | These commands allow creation and manipulation of the tile storage database.
72 |
73 | ##### `storage init`
74 | Initialize storage for a tileset.
75 |
76 | Creates the storage for a tile layer and stores its metadata in the database.
77 | If the metadata tables have not yet been created they will also be setup.
78 |
79 | ##### `storage destroy`
80 | Destroy storage for a tileset.
81 |
82 | Removes the storage for a tile layer and deletes its associated metadata.
83 | The metadata tables themselves are not removed.
84 |
85 | ##### `storage inspect`
86 | Print data about a stored tile
87 |
88 | ##### `storage delete`
89 | Mass-delete tiles from a tileset
90 |
91 | Deletes tiles from a tileset, by zoom, or delete all zooms.
92 |
93 | ##### `storage tiledelete`
94 | Delete specific tiles.
95 |
96 | A list of z/x/y tiles is read from stdin and those tiles are deleted from
97 | storage. The entire list is read before deletion starts.
98 |
99 | ### Serving commands
100 | These commands start a HTTP server to serve content.
101 | #### `serve`
102 | Commands for tile serving.
103 |
104 | All tile serving commands serve tiles and a tilejson over HTTP.
105 |
106 | ##### `dev`
107 | Starts a server to live-render tiles with no caching, intended for development. It presents a tilejson at `//tilejson.json`, and for convience `/tilejson.json` redirects to it.
108 |
109 | ##### `live`
110 | Like `serve`, but fall back to live generation if a tile is missing from storage.
111 |
112 | It presents a tilejson at `//tilejson.json`.
113 |
114 | ##### `static`
115 | Serves tiles from tile storage. This is highly scalable and the preferred mode for production.
116 |
117 | It presents a tilejson at `//tilejson.json`. In the future it will allow serving multiple tilesets.
118 |
119 | #### `prometheus`
120 | Starts a prometheus exporter for metrics on tiles. By default it presents metrics at `http://127.0.0.1:10013/metrics`.
121 |
122 | ## Quick-start
123 | These instructions give you a setup based on osm2pgsql-themepark and their shortbread setup. They assume you have PostgreSQL with PostGIS and Python 3.10+ with venv set up, and a recent version of osm2pgsql.
124 |
125 | ### Install and setup
126 |
127 | ```sh
128 | python3 -m venv tilekiln
129 | tilekiln/bin/pip install tilekiln
130 | tilekiln/bin/tilekiln --help
131 | ```
132 |
133 | ### Configuration Setup
134 |
135 | Tilekiln requires a configuration file that defines the contents of your vector tiles. Most configurations are designed to work with OpenStreetMap data loaded into PostgreSQL using osm2pgsql.
136 |
137 | For a configuration, you can use the one provided by the [Street Spirit](https://github.com/pnorman/spirit) project. Follow its [installation guide](https://github.com/pnorman/spirit/blob/main/INSTALL.md) to get started.
138 |
139 | ## History
140 | The tilekiln configuration syntax is based on studies and experience with other vector tile and map generation configurations. In particular, it is heavily inspired by Tilezen's use of Jinja2 templates and TileJSON for necessary metadata.
141 |
142 | ## License
143 |
144 | ### Code
145 |
146 | Copyright © 2022-2024 Paul Norman
147 |
148 | The code is licensed terms of the GNU General Public License as
149 | published by the Free Software Foundation, either version 3 of
150 | the License, or (at your option) any later version.
151 |
152 | This program is distributed in the hope that it will be useful,
153 | but WITHOUT ANY WARRANTY; without even the implied warranty of
154 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
155 | GNU General Public License for more details.
156 |
157 | You should have received a copy of the GNU General Public License
158 | along with this program. If not, see .
159 |
160 | ### Documentation
161 |
162 | The text of the documentation and configuration format specification is licensed under a [Creative Commons Attribution 4.0 International License](https://creativecommons.org/licenses/by/4.0/). However, the use of the specification in products and code is entirely free: there are no royalties, restrictions, or requirements.
163 |
164 | ### Sample configuration
165 |
166 | The sample configuration files are released under the CC0 Public
167 | Domain Dedication, version 1.0, as published by Creative Commons.
168 | To the extent possible under law, the author(s) have dedicated all
169 | copyright and related and neighboring rights to the Software to
170 | the public domain worldwide. The Software is distributed WITHOUT
171 | ANY WARRANTY.
172 |
173 | If you did not receive a copy of the CC0 Public Domain Dedication
174 | along with the Software, see
175 |
176 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["hatchling", "hatch-vcs"]
3 | build-backend = "hatchling.build"
4 |
5 | [tool.hatch.version]
6 | source = "vcs"
7 |
8 | # Allows pypi uploads. ref: https://github.com/ofek/hatch-vcs/discussions/12
9 | [tool.hatch.version.raw-options]
10 | local_scheme = "no-local-version"
11 |
12 | [project]
13 | name = "tilekiln"
14 | dynamic = ["version"]
15 |
16 | description = "A set of command-line utilities to generate and serve Mapbox Vector Tiles (MVTs)"
17 | readme = "README.md"
18 | license = "GPL-3.0-or-later"
19 | requires-python = ">=3.10, <4"
20 | authors = [
21 | { name = "Paul Norman", email = "osm@paulnorman.ca" },
22 | ]
23 | keywords = [
24 | "mvt",
25 | "openstreetmap",
26 | "osm",
27 | ]
28 | classifiers = [
29 | "Development Status :: 4 - Beta",
30 | "Environment :: Console",
31 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
32 | "Operating System :: OS Independent",
33 | "Programming Language :: Python :: 3",
34 | "Topic :: Scientific/Engineering :: GIS",
35 | ]
36 | dependencies = [
37 | "Click",
38 | "fastapi",
39 | "fs",
40 | "Jinja2",
41 | "pmtiles",
42 | "prometheus_client",
43 | "psycopg",
44 | "psycopg_pool",
45 | "pyyaml",
46 | "tqdm",
47 | "uvicorn",
48 | ]
49 |
50 | [project.optional-dependencies]
51 | test = [
52 | "pytest",
53 | ]
54 |
55 | [project.scripts]
56 | tilekiln = "tilekiln.main:cli"
57 |
58 | [project.urls]
59 | "Bug Reports" = "https://github.com/pnorman/tilekiln/issues"
60 | Homepage = "https://github.com/pnorman/tilekiln"
61 | Source = "https://github.com/pnorman/tilekiln/"
62 |
63 | [tool.hatch.build.targets.sdist]
64 | include = [
65 | "/tilekiln",
66 | ]
67 |
--------------------------------------------------------------------------------
/sample/admin.sql.jinja2:
--------------------------------------------------------------------------------
1 | SELECT
2 | ST_AsMVTGeom(way, {{bbox}}, {{extent}}) AS way,
3 | admin_level::integer
4 | {% if zoom <= 10 %}
5 | FROM planet_osm_roads
6 | {% else %}
7 | FROM planet_osm_line
8 | {% endif %}
9 | WHERE way && {{bbox}}
10 | AND boundary = 'administrative'
11 | {% if zoom <= 2 %}
12 | AND admin_level IN ('0', '1', '2')
13 | {% elif zoom <= 10 %}
14 | AND admin_level IN ('0', '1', '2', '3', '4')
15 | {% elif zoom <= 12 %}
16 | AND admin_level IN ('0', '1', '2', '3', '4', '5', '6')
17 | {% endif %}
18 | AND osm_id < 0
19 |
--------------------------------------------------------------------------------
/sample/config.yaml:
--------------------------------------------------------------------------------
1 | # This config is designed to be used with an OpenStreetMap Carto database with
2 | # shapefiles loaded into the DB.
3 | # https://github.com/gravitystorm/openstreetmap-carto/pull/4092
4 | metadata:
5 | id: v1 # Required, used for storage by Tilekiln
6 | bounds: [-180, -85.05112877980659, 180, 85.0511287798066 ] # Optional bounds
7 | name: name for tilejson, optional
8 | description: description for tilejson, optional
9 | version: version for tilejson, optional
10 | attribution: attribution for tilejson, optional
11 | center: [0, 0, 4] # center for tilejson, optional
12 | vector_layers:
13 | water:
14 | fields:
15 | water: Type of water
16 | description: Waterbody and ocean areas
17 | sql:
18 | - minzoom: 0
19 | maxzoom: 8
20 | extent: 2048
21 | file: water.sql.jinja2
22 | admin:
23 | fields:
24 | admin_level: Level of admin boundary
25 | description: Administrative boundaries
26 | sql:
27 | - minzoom: 1 # Must not overlap with other templates
28 | maxzoom: 3
29 | file: ne-admin.sql.jinja2
30 | - minzoom: 4 # Must not overlap with other templates
31 | maxzoom: 10
32 | file: admin.sql.jinja2
33 | country_names:
34 | fields:
35 | name: Name of country
36 | area: Area of country
37 | description: Points for country names
38 | sql:
39 | - minzoom: 3
40 | maxzoom: 14
41 | file: country.sql.jinja2
42 |
--------------------------------------------------------------------------------
/sample/country.sql.jinja2:
--------------------------------------------------------------------------------
1 | SELECT
2 | ST_AsMVTGeom(ST_PointOnSurface(way), {{bbox}}, {{extent}}) AS way
3 | FROM planet_osm_polygon
4 | WHERE way && {{bbox}}
5 | AND boundary = 'administrative'
6 | AND admin_level = '2'
7 | AND name IS NOT NULL
8 | {% if zoom <= 12 %}
9 | AND way_area > {{tile_area}}*0.05^2
10 | {% endif %}
11 | AND osm_id < 0
12 |
--------------------------------------------------------------------------------
/sample/ne-admin.sql.jinja2:
--------------------------------------------------------------------------------
1 | SELECT
2 | ST_AsMVTGeom(way, {{bbox}}, {{extent}}) AS way,
3 | 2 AS admin_level
4 | FROM ne_110m_admin_0_boundary_lines_land
5 | WHERE way && {{bbox}}
6 |
--------------------------------------------------------------------------------
/sample/water.sql.jinja2:
--------------------------------------------------------------------------------
1 | SELECT
2 | ST_AsMVTGeom(way, {{bbox}}, {{extent}}) AS way,
3 | NULL as osm_id,
4 | 'ocean' AS water
5 | FROM simplified_water_polygons
6 | WHERE way && {{bbox}}
7 | UNION ALL
8 | SELECT
9 | ST_AsMVTGeom(way, {{bbox}}) AS way,
10 | osm_id,
11 | water
12 | FROM planet_osm_polygon
13 | WHERE way && {{bbox}}
14 | AND (waterway IN ('dock', 'riverbank')
15 | OR landuse IN ('reservoir', 'basin')
16 | OR "natural" IN ('water'))
17 | {% if zoom <= 12 %}
18 | AND way_area > 400 * {{coordinate_area}}
19 | {% endif %}
20 |
--------------------------------------------------------------------------------
/tests/test_config.py:
--------------------------------------------------------------------------------
1 | import yaml
2 | from unittest import TestCase
3 |
4 | from fs.memoryfs import MemoryFS
5 |
6 | from tilekiln.config import Config, LayerConfig
7 | from tilekiln.tile import Tile
8 | import tilekiln.errors
9 |
10 |
11 | class TestConfig(TestCase):
12 | maxDiff = None
13 |
14 | def test_properties(self):
15 | with MemoryFS() as fs:
16 | c = Config('''{"metadata": {"id":"foo"}}''', fs)
17 | self.assertEqual(c.id, "foo")
18 | self.assertEqual(c.name, None)
19 | self.assertEqual(c.description, None)
20 | self.assertEqual(c.attribution, None)
21 | self.assertEqual(c.version, None)
22 | self.assertEqual(c.bounds, None)
23 | self.assertEqual(c.center, None)
24 | self.assertEqual(c.minzoom, None)
25 | self.assertEqual(c.maxzoom, None)
26 |
27 | self.assertEqual(c.tilejson("bar"), '''{
28 | "scheme": "xyz",
29 | "tilejson": "3.0.0",
30 | "tiles": [
31 | "bar/foo/{z}/{x}/{y}.mvt"
32 | ],
33 | "vector_layers": []
34 | }''')
35 | with MemoryFS() as fs:
36 | fs.writetext("blank.sql.jinja2", "")
37 | c_str = ('''{"metadata": {"id":"id", '''
38 | '''"name": "name", '''
39 | '''"description":"description", '''
40 | '''"attribution":"attribution", "version": "1.0.0",'''
41 | '''"bounds": [-180, -85, 180, 85], "center": [0, 0]},'''
42 | '''"vector_layers": {"building":{'''
43 | '''"description": "buildings",'''
44 | '''"fields":{"foo": "bar"},'''
45 | '''"sql": [{"minzoom":13, "maxzoom":14, "file": "blank.sql.jinja2"}]}}}''')
46 |
47 | # Check the test is valid yaml to save debugging
48 | yaml.safe_load(c_str)
49 | c = Config(c_str, fs)
50 | self.assertEqual(c.id, "id")
51 | self.assertEqual(c.name, "name")
52 | self.assertEqual(c.description, "description")
53 | self.assertEqual(c.attribution, "attribution")
54 | self.assertEqual(c.version, "1.0.0")
55 | self.assertEqual(c.bounds, [-180, -85, 180, 85])
56 | self.assertEqual(c.center, [0, 0])
57 | self.assertEqual(c.attribution, "attribution")
58 | self.assertEqual(c.minzoom, 13)
59 | self.assertEqual(c.maxzoom, 14)
60 |
61 | self.assertSequenceEqual([*c.layer_names()], ["building"])
62 |
63 | self.assertEqual(c.layer_query("building", Tile(13, 0, 0)),
64 | "WITH mvtgeom AS -- building/13/0/0\n(\n\n)\n"
65 | "SELECT ST_AsMVT(mvtgeom.*, 'building', 4096)\nFROM mvtgeom;")
66 | self.assertEqual(c.layer_query("building", Tile(13, 0, 0)),
67 | c.layer_queries(Tile(13, 0, 0))["building"])
68 |
69 | self.assertEqual(c.tilejson("foo"), '''{
70 | "attribution": "attribution",
71 | "bounds": [
72 | -180,
73 | -85,
74 | 180,
75 | 85
76 | ],
77 | "center": [
78 | 0,
79 | 0
80 | ],
81 | "description": "description",
82 | "maxzoom": 14,
83 | "minzoom": 13,
84 | "name": "name",
85 | "scheme": "xyz",
86 | "tilejson": "3.0.0",
87 | "tiles": [
88 | "foo/id/{z}/{x}/{y}.mvt"
89 | ],
90 | "vector_layers": [
91 | {
92 | "description": "buildings",
93 | "fields": {
94 | "foo": "bar"
95 | },
96 | "id": "building",
97 | "maxzoom": 14,
98 | "minzoom": 13
99 | }
100 | ]
101 | }''')
102 |
103 | # Test without fields for the layer
104 | fs.writetext("blank.sql.jinja2", "")
105 | c_str = ('''{"metadata": {"id":"id", '''
106 | '''"name": "name", '''
107 | '''"description":"description", '''
108 | '''"attribution":"attribution", "version": "1.0.0",'''
109 | '''"bounds": [-180, -85, 180, 85], "center": [0, 0]},'''
110 | '''"vector_layers": {"building":{'''
111 | '''"sql": [{"minzoom":13, "maxzoom":14, "file": "blank.sql.jinja2"}]}}}''')
112 |
113 | # Check the test is valid yaml to save debugging
114 | yaml.safe_load(c_str)
115 | c = Config(c_str, fs)
116 |
117 | self.assertEqual(c.tilejson("foo"), '''{
118 | "attribution": "attribution",
119 | "bounds": [
120 | -180,
121 | -85,
122 | 180,
123 | 85
124 | ],
125 | "center": [
126 | 0,
127 | 0
128 | ],
129 | "description": "description",
130 | "maxzoom": 14,
131 | "minzoom": 13,
132 | "name": "name",
133 | "scheme": "xyz",
134 | "tilejson": "3.0.0",
135 | "tiles": [
136 | "foo/id/{z}/{x}/{y}.mvt"
137 | ],
138 | "vector_layers": [
139 | {
140 | "fields": {},
141 | "id": "building",
142 | "maxzoom": 14,
143 | "minzoom": 13
144 | }
145 | ]
146 | }''')
147 |
148 | def test_exceptions(self):
149 | with MemoryFS() as fs:
150 | # Check some invalid or silly YAML
151 | self.assertRaises(tilekiln.errors.ConfigYAMLError, Config, '''{}''', fs)
152 | self.assertRaises(tilekiln.errors.ConfigYAMLError, Config, '''? :''', fs)
153 | self.assertRaises(tilekiln.errors.ConfigYAMLError, Config, ''':3c''', fs)
154 |
155 | # Check ID
156 | self.assertRaises(tilekiln.errors.ConfigYAMLError, Config, '''metadata: {}''', fs)
157 | self.assertRaises(tilekiln.errors.ConfigYAMLError, Config,
158 | '''metadata: {id: 1}''', fs)
159 |
160 | fs.writetext("blank.sql.jinja2", "")
161 | c_str = ('''{"metadata": {"id":"id", '''
162 | '''"name": "name", '''
163 | '''"description":"description", '''
164 | '''"attribution":"attribution", "version": "1.0.0",'''
165 | '''"bounds": [-180, -85, 180, 85], "center": [0, 0]},'''
166 | '''"vector_layers": {"\"":{'''
167 | '''"description": "buildings",'''
168 | '''"fields":{"foo": "bar"},'''
169 | '''"sql": [{"minzoom":13, "maxzoom":14, "file": "blank.sql.jinja2"}]}}}''')
170 | self.assertRaises(tilekiln.errors.ConfigError, Config, c_str, fs)
171 |
172 |
173 | class TestLayerConfig(TestCase):
174 | def test_render(self):
175 | with MemoryFS() as fs:
176 | fs.writetext("one.sql.jinja2", "one")
177 | fs.writetext("two.sql.jinja2", "two")
178 | layer = LayerConfig("foo", {"sql": [{"minzoom": 4, "maxzoom": 8,
179 | "file": "one.sql.jinja2"}]}, fs)
180 |
181 | self.assertIsNone(layer.render_sql(Tile(2, 0, 0)))
182 | self.assertIsNotNone(layer.render_sql(Tile(6, 0, 0)))
183 | self.assertIsNone(layer.render_sql(Tile(10, 0, 0)))
184 |
185 | layer = LayerConfig("foo",
186 | {"sql": [{"minzoom": 4, "maxzoom": 4, "file": "one.sql.jinja2"},
187 | {"minzoom": 6, "maxzoom": 6, "file": "two.sql.jinja2"}]},
188 | fs)
189 | self.assertIsNone(layer.render_sql(Tile(3, 0, 0)))
190 | self.assertIsNone(layer.render_sql(Tile(5, 0, 0)))
191 | self.assertIsNone(layer.render_sql(Tile(7, 0, 0)))
192 |
193 | self.assertEqual(layer.render_sql(Tile(4, 0, 0)), '''WITH mvtgeom AS -- foo/4/0/0
194 | (
195 | one
196 | )
197 | SELECT ST_AsMVT(mvtgeom.*, 'foo', 4096)
198 | FROM mvtgeom;''')
199 | self.assertEqual(layer.render_sql(Tile(6, 0, 0)), '''WITH mvtgeom AS -- foo/6/0/0
200 | (
201 | two
202 | )
203 | SELECT ST_AsMVT(mvtgeom.*, 'foo', 4096)
204 | FROM mvtgeom;''')
205 |
--------------------------------------------------------------------------------
/tests/test_definition.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | from fs.memoryfs import MemoryFS
4 |
5 | from tilekiln.definition import Definition
6 | from tilekiln.tile import Tile
7 | from tilekiln.errors import DefinitionError
8 |
9 |
10 | class TestDefinition(TestCase):
11 | def test_attributes(self):
12 | with MemoryFS() as fs:
13 | fs.writetext("blank.sql.jinja2", "")
14 | d = Definition("foo", {"minzoom": 1, "maxzoom": 3, "extent": 1024, "buffer": 8,
15 | "file": "blank.sql.jinja2"}, fs)
16 | self.assertEqual(d.id, "foo")
17 | self.assertEqual(d.minzoom, 1)
18 | self.assertEqual(d.maxzoom, 3)
19 | self.assertEqual(d.extent, 1024)
20 | self.assertEqual(d.buffer, 8)
21 |
22 | d = Definition("bar", {"minzoom": 2, "maxzoom": 4,
23 | "file": "blank.sql.jinja2"}, fs)
24 | self.assertEqual(d.id, "bar")
25 | self.assertEqual(d.minzoom, 2)
26 | self.assertEqual(d.maxzoom, 4)
27 | self.assertEqual(d.extent, 4096)
28 | self.assertEqual(d.buffer, 0)
29 |
30 | def test_attribute_exceptions(self):
31 | with MemoryFS() as fs:
32 | fs.writetext("blank.sql.jinja2", "")
33 | self.assertRaisesRegex(DefinitionError, 'maxzoom', Definition, "foo",
34 | {"minzoom": 1, "extent": 1024, "buffer": 8,
35 | "file": "blank.sql.jinja2"}, fs)
36 | self.assertRaisesRegex(DefinitionError, 'minzoom', Definition, "foo",
37 | {"maxzoom": 1, "extent": 1024, "buffer": 8,
38 | "file": "blank.sql.jinja2"}, fs)
39 | self.assertRaisesRegex(DefinitionError, 'missing.sql.jinja2', Definition, "foo",
40 | {"minzoom": 1, "maxzoom": 2, "extent": 1024, "buffer": 8,
41 | "file": "missing.sql.jinja2"}, fs)
42 |
43 | def test_render(self):
44 | with MemoryFS() as fs:
45 | fs.writetext("one.sql.jinja2", "SELECT 1")
46 | d = Definition("one", {"minzoom": 1, "maxzoom": 3, "extent": 1024, "buffer": 8,
47 | "file": "one.sql.jinja2"}, fs)
48 | expected = '''WITH mvtgeom AS -- one/2/0/0
49 | (
50 | SELECT 1
51 | )
52 | SELECT ST_AsMVT(mvtgeom.*, 'one', 1024)
53 | FROM mvtgeom;'''
54 | self.assertEqual(d.render_sql(Tile(2, 0, 0)), expected)
55 |
56 | fs.writetext("two.sql.jinja2", "SELECT {{zoom}}/{{x}}/{{y}}\n{{bbox}}\n" +
57 | "{{unbuffered_bbox}}\n{{extent}}\n{{buffer}}")
58 | d = Definition("two", {"minzoom": 1, "maxzoom": 3, "extent": 1024, "buffer": 256,
59 | "file": "two.sql.jinja2"}, fs)
60 | expected = '''WITH mvtgeom AS -- two/2/0/1
61 | (
62 | SELECT 2/0/1
63 | ST_TileEnvelope(2, 0, 1, margin=>0.25)
64 | ST_TileEnvelope(2, 0, 1, margin=>0)
65 | 1024
66 | 256
67 | )
68 | SELECT ST_AsMVT(mvtgeom.*, 'two', 1024)
69 | FROM mvtgeom;'''
70 | self.assertEqual(d.render_sql(Tile(2, 0, 1)), expected)
71 |
72 | fs.writetext("units.sql.jinja2", "{{tile_length}}\n{{tile_area}}\n" +
73 | "{{coordinate_length}}\n{{coordinate_area}}")
74 | d = Definition("units", {"minzoom": 1, "maxzoom": 3, "extent": 1024, "buffer": 256,
75 | "file": "units.sql.jinja2"}, fs)
76 | # Crudely slice up the string to turn it into numbers
77 | expected = '''WITH mvtgeom AS -- units/2/0/1
78 | (
79 | 10018754.17
80 | 100375435118892.39
81 | 9783.939619140625
82 | 95725474.4709896
83 | )
84 | SELECT ST_AsMVT(mvtgeom.*, 'units', 1024)
85 | FROM mvtgeom;'''
86 | self.assertEqual(d.render_sql(Tile(2, 0, 1)), expected)
87 |
88 | fs.writetext("whitespace.sql.jinja2", "foo\n{# comment #}\nbar")
89 | d = Definition("whitespace", {"minzoom": 1, "maxzoom": 3, "extent": 1024, "buffer": 256,
90 | "file": "whitespace.sql.jinja2"}, fs)
91 | # Crudely slice up the string to turn it into numbers
92 | expected = '''WITH mvtgeom AS -- whitespace/2/0/1
93 | (
94 | foo
95 | bar
96 | )
97 | SELECT ST_AsMVT(mvtgeom.*, 'whitespace', 1024)
98 | FROM mvtgeom;'''
99 | self.assertEqual(d.render_sql(Tile(2, 0, 1)), expected)
100 |
--------------------------------------------------------------------------------
/tests/test_storage.py:
--------------------------------------------------------------------------------
1 | import json
2 | import queue
3 | from unittest import TestCase
4 |
5 | from tilekiln.storage import Storage
6 | from tilekiln.tile import Tile
7 | from tilekiln.metric import Metric
8 | import tilekiln.errors
9 |
10 |
11 | class FakeCursor:
12 | def __init__(self, calls, rets):
13 | self.calls = calls
14 | self.rets = rets
15 |
16 | def execute(self, query, vars=None, binary=None):
17 | try:
18 | self.calls.append(query.as_string())
19 | except AttributeError:
20 | self.calls.append(query)
21 |
22 | def __iter__(self):
23 | return self
24 |
25 | def __next__(self):
26 | try:
27 | return self.rets.get_nowait()
28 | except queue.Empty:
29 | raise StopIteration
30 |
31 | def fetchone(self):
32 | return next(self)
33 |
34 |
35 | class FakeCursCM:
36 | def __init__(self, calls, rets):
37 | self.curs = FakeCursor(calls, rets)
38 |
39 | def __enter__(self):
40 | return self.curs
41 |
42 | def __exit__(*args):
43 | pass
44 |
45 |
46 | class FakeConnection:
47 | def __init__(self, calls, rets):
48 | self.curs = FakeCursCM(calls, rets)
49 |
50 | def cursor(self, row_factory=None):
51 | return self.curs
52 |
53 | def commit(self):
54 | pass
55 |
56 |
57 | class FakeConnCM:
58 | def __init__(self, calls, rets):
59 | self.conn = FakeConnection(calls, rets)
60 |
61 | def __enter__(self):
62 | return self.conn
63 |
64 | def __exit__(*args):
65 | pass
66 |
67 |
68 | class FakePool:
69 | def __init__(self, calls: list[str], rets: queue.Queue[dict[str, str]]):
70 | self.cm = FakeConnCM(calls, rets)
71 |
72 | def connection(self):
73 | return self.cm
74 |
75 |
76 | class TestStorage(TestCase):
77 | def test_schema(self):
78 | calls = []
79 | rets = queue.SimpleQueue()
80 | pool = FakePool(calls, rets)
81 |
82 | storage = Storage(pool)
83 |
84 | storage.create_schema()
85 |
86 | self.assertRegex(calls[0], r"(?ims)CREATE SCHEMA.*tilekiln")
87 | self.assertRegex(calls[1], r"(?ims)CREATE.*TABLE.*generate_stats.*id.*zoom.*")
88 | self.assertRegex(calls[2], r"(?ims)CREATE.*TABLE.*tile_stats.*id.*zoom.*")
89 | self.assertRegex(calls[3], r"(?ims)CREATE.*TABLE.*metadata.*")
90 | self.assertRegex(calls[3], r"id text")
91 | self.assertRegex(calls[3], r"active boolean")
92 | self.assertRegex(calls[3], r"layers text\[\]")
93 | self.assertRegex(calls[3], r"minzoom smallint")
94 | self.assertRegex(calls[3], r"maxzoom smallint")
95 | calls.clear()
96 |
97 | def test_tileset(self):
98 | calls = []
99 | rets = queue.SimpleQueue()
100 | pool = FakePool(calls, rets)
101 |
102 | storage = Storage(pool)
103 |
104 | storage.create_tileset("foo", ["lyr1", "lyr2"], 0, 2, "{}")
105 |
106 | self.assertRegex(calls[0], r"(?ims)INSERT INTO.*metadata.*VALUES.*ON CONFLICT")
107 | self.assertRegex(calls[1], r"(?ims)CREATE TABLE.*foo.*")
108 | self.assertRegex(calls[1], r'''(?ims)"lyr1_generated" timestamptz''')
109 | self.assertRegex(calls[1], r'''(?ims)"lyr1_data" bytea''')
110 | # Check timestamps are before tile data for storage reasons
111 | self.assertRegex(calls[1], r'''(?ims)timestamptz.*bytea''')
112 | self.assertNotRegex(calls[1], r'''(?ims)bytea.*timestamptz''')
113 |
114 | self.assertRegex(calls[2], r"(?ims)CREATE TABLE.*foo_z0")
115 | self.assertRegex(calls[2], r"(?ims)PARTITION OF.*foo")
116 | self.assertRegex(calls[2], r"(?ims)FOR VALUES IN \(0\)")
117 | self.assertRegex(calls[3], r"(?ims)CREATE TABLE.*foo_z1")
118 | self.assertRegex(calls[3], r"(?ims)PARTITION OF.*foo")
119 | self.assertRegex(calls[3], r"(?ims)FOR VALUES IN \(1\)")
120 | self.assertRegex(calls[4], r"(?ims)CREATE TABLE.*foo_z2")
121 | self.assertRegex(calls[4], r"(?ims)PARTITION OF.*foo")
122 | self.assertRegex(calls[4], r"(?ims)FOR VALUES IN \(2\)")
123 | calls.clear()
124 |
125 | storage.remove_tileset("foo")
126 |
127 | self.assertRegex(calls[0], r"(?ims)DELETE FROM.*metadata.*id")
128 | self.assertRegex(calls[1], r"(?ims)DROP TABLE.*foo")
129 | self.assertRegex(calls[2], r"(?ims)DELETE FROM.*tile_stats.*id")
130 | calls.clear()
131 |
132 | rets.put({"id": "foo"})
133 | rets.put({"id": "bar"})
134 |
135 | ids = storage.get_tileset_ids()
136 |
137 | self.assertEqual(next(ids), "foo")
138 | self.assertEqual(next(ids), "bar")
139 | self.assertRegex(calls[0], r"(?ims)SELECT id.*metadata")
140 |
141 | calls.clear()
142 | while not rets.empty():
143 | rets.get()
144 |
145 | rets.put({"id": "foo",
146 | "layers": ["lyr1", "lyr2"],
147 | "minzoom": 0,
148 | "maxzoom": 2,
149 | "tilejson": json.loads("{}")
150 | })
151 |
152 | tilesets = storage.get_tilesets()
153 | tileset = next(tilesets)
154 | self.assertRegex(calls[0], r"(?ims)SELECT id.*metadata")
155 | self.assertEqual(tileset.id, "foo")
156 | self.assertEqual(tileset.layers, ["lyr1", "lyr2"])
157 | self.assertEqual(tileset.minzoom, 0)
158 | self.assertEqual(tileset.maxzoom, 2)
159 | self.assertEqual(tileset.tilejson, '{}')
160 |
161 | def test_metadata(self):
162 | calls = []
163 | rets = queue.SimpleQueue()
164 | pool = FakePool(calls, rets)
165 |
166 | storage = Storage(pool)
167 | storage.set_metadata("foo", ["lyr1", "lyr2"], 0, 3, "{}")
168 |
169 | self.assertRegex(calls[0], r"(?ims)INSERT INTO.*metadata.*VALUES.*ON CONFLICT")
170 | calls.clear()
171 |
172 | def test_tiles(self):
173 | calls = []
174 | rets = queue.SimpleQueue()
175 | pool = FakePool(calls, rets)
176 |
177 | rets.put({"id": "foo",
178 | "layers": ["lyr1", "lyr2"],
179 | "minzoom": 0,
180 | "maxzoom": 2,
181 | "tilejson": json.loads("{}")
182 | })
183 | rets.put({"lyr1_data": b"bar", "lyr2_data": b"baz", "generated": "datetime"})
184 | storage = Storage(pool)
185 | result, generated = storage.get_tile("foo", Tile(0, 0, 0))
186 | self.assertEqual(result["lyr1"], b"bar")
187 | self.assertEqual(result["lyr2"], b"baz")
188 | self.assertEqual(generated, "datetime")
189 |
190 | # calls[0] is get_tileset call tested above. TODO: test it above
191 | self.assertRegex(calls[1],
192 | r"(?ims)SELECT.*lyr1_generated.*.*lyr1_data.*FROM.*foo.*WHERE.*zoom")
193 |
194 | calls.clear()
195 | while not rets.empty():
196 | rets.get()
197 |
198 | # Test no tile found
199 | rets.put({"id": "foo",
200 | "layers": ["lyr1", "lyr2"],
201 | "minzoom": 0,
202 | "maxzoom": 2,
203 | "tilejson": json.loads("{}")
204 | })
205 | rets.put(None)
206 | self.assertEqual(storage.get_tile("foo", Tile(0, 0, 0)),
207 | ({"lyr1": None, "lyr2": None}, None))
208 |
209 | calls.clear()
210 | while not rets.empty():
211 | rets.get()
212 |
213 | rets.put({"id": "foo",
214 | "layers": ["lyr1", "lyr2"],
215 | "minzoom": 0,
216 | "maxzoom": 2,
217 | "tilejson": json.loads("{}")
218 | })
219 |
220 | rets.put({"lyr1_data": b"bar", "lyr2_data": None, "generated": "datetime"})
221 | storage = Storage(pool)
222 |
223 | rets.put({"lyr1_data": b"bar", "lyr2_data": b"baz", "generated": "datetime"})
224 | storage = Storage(pool)
225 | result, generated = storage.get_tile("foo", Tile(0, 0, 0))
226 | self.assertEqual(result["lyr1"], b"bar")
227 | self.assertEqual(result["lyr2"], None)
228 | self.assertEqual(generated, "datetime")
229 |
230 | calls.clear()
231 | while not rets.empty():
232 | rets.get()
233 |
234 | rets.put({"id": "foo",
235 | "layers": ["lyr1", "lyr2"],
236 | "minzoom": 0,
237 | "maxzoom": 2,
238 | "tilejson": json.loads("{}")
239 | })
240 |
241 | rets.put({"lyr1_data": b"bar", "lyr2_data": b"baz",
242 | "lyr1_generated": "datetime1", "lyr2_generated": "datetime2"})
243 | self.assertEqual(storage.get_tile_details("foo", Tile(0, 0, 0)),
244 | {"lyr1": (b"bar", "datetime1"), "lyr2": (b"baz", "datetime2")})
245 |
246 | calls.clear()
247 | while not rets.empty():
248 | rets.get()
249 |
250 | rets.put({"id": "foo",
251 | "layers": ["lyr1", "lyr2"],
252 | "minzoom": 0,
253 | "maxzoom": 2,
254 | "tilejson": json.loads("{}")
255 | })
256 |
257 | rets.put({"lyr1_data": b"bar", "lyr2_data": None,
258 | "lyr1_generated": "datetime1", "lyr2_generated": None})
259 |
260 | self.assertEqual(storage.get_tile_details("foo", Tile(0, 0, 0)),
261 | {"lyr1": (b"bar", "datetime1"), "lyr2": None})
262 |
263 | calls.clear()
264 | while not rets.empty():
265 | rets.get()
266 |
267 | rets.put({"id": "foo",
268 | "layers": ["lyr1", "lyr2"],
269 | "minzoom": 0,
270 | "maxzoom": 2,
271 | "tilejson": json.loads("{}")
272 | })
273 | rets.put({"generated": "datetime"})
274 |
275 | self.assertEqual(storage.save_tile("foo", Tile(2, 1, 0),
276 | {"lyr1": b"bar", "lyr2": b"baz"}), "datetime")
277 | self.assertRegex(calls[0], r"(?ims)minzoom.*maxzoom")
278 | self.assertRegex(calls[1], r"(?ims)INSERT INTO.*foo_z2")
279 | # Test colums are right
280 | self.assertRegex(calls[1],
281 | r"(?ms)\(zoom[^\)]+x[^\)]+y[^\)]+lyr1_data[^\)]+lyr2_data[^\)]*\)")
282 | # check that the z, x, y appear in the right order
283 | self.assertRegex(calls[1], r'''(?ims)VALUES\s+\(\s*2,\s+1,\s+0,\s+''')
284 |
285 | # check there are placeholders for the data
286 | self.assertRegex(calls[1], r'''(?ims)VALUES\s+\([^\)]*%[^,]*s,\s*%[^,]*s,''')
287 | # check that the timestamps are set
288 | self.assertRegex(calls[1],
289 | r"(?s)VALUES\s+\(.*" # .* covers placeholders found above
290 | r"statement_timestamp\(\)[^\)]*statement_timestamp\(\)[^\)]*\)")
291 |
292 | self.assertRegex(calls[1], r"(?ims)ON CONFLICT\s+\(zoom,\s+x,\s+y\s*\)")
293 | # Test that the upsert sets data to something based on excluded
294 | self.assertRegex(calls[1], r"(?ims)DO UPDATE.*lyr1_data[^,]+=[^,]*EXCLUDED[^,]+lyr1_data")
295 | self.assertRegex(calls[1], r"(?ims)DO UPDATE.*lyr2_data[^,]+=[^,]*EXCLUDED[^,]+lyr2_data")
296 |
297 | # test that upserts sets generated to something based on stored and new lyr1_generated,
298 | # statement_timestamp, and that old generated is referenced
299 | self.assertRegex(calls[1],
300 | r"(?ims)DO UPDATE.*lyr1_generated[^,]*=[^,]*STORE\.[^,]*lyr1_data")
301 | self.assertRegex(calls[1],
302 | r"(?ims)DO UPDATE.*lyr1_generated[^,]*=[^,]*EXCLUDED\.[^,]*lyr1_data")
303 | self.assertRegex(calls[1],
304 | r"(?ims)DO UPDATE.*lyr1_generated[^,]+=[^,]*statement_timestamp")
305 | self.assertRegex(calls[1],
306 | r"(?ims)DO UPDATE.*lyr1_generated[^,]+=[^,]*STORE\.[^,]*lyr1_generated")
307 | self.assertRegex(calls[1],
308 | r"(?ims)DO UPDATE.*lyr2_generated[^,]*=[^,]*STORE\.[^,]*lyr2_data")
309 | self.assertRegex(calls[1],
310 | r"(?ims)DO UPDATE.*lyr2_generated[^,]*=[^,]*EXCLUDED\.[^,]*lyr2_data")
311 | self.assertRegex(calls[1],
312 | r"(?ims)DO UPDATE.*lyr2_generated[^,]+=[^,]*statement_timestamp")
313 | self.assertRegex(calls[1],
314 | r"(?ims)DO UPDATE.*lyr2_generated[^,]+=[^,]*STORE\.[^,]*lyr2_generated")
315 |
316 | self.assertRegex(calls[1],
317 | r"(?ims)RETURNING.*lyr1_generated")
318 | self.assertRegex(calls[1],
319 | r"(?ims)RETURNING.*lyr2_generated")
320 |
321 | calls.clear()
322 | while not rets.empty():
323 | rets.get()
324 |
325 | rets.put({"id": "foo",
326 | "layers": ["lyr1", "lyr2"],
327 | "minzoom": 0,
328 | "maxzoom": 2,
329 | "tilejson": json.loads("{}")
330 | })
331 | rets.put({"generated": "datetime"})
332 |
333 | # Check that an exception is raised if trying to save a tile with layers not in storage
334 | self.assertRaises(tilekiln.errors.Error, storage.save_tile, "foo", Tile(2, 1, 0),
335 | {"lyr3": b"bar"}, "datetime")
336 |
337 | calls.clear()
338 | while not rets.empty():
339 | rets.get()
340 |
341 | rets.put({"id": "foo",
342 | "layers": ["lyr1", "lyr2"],
343 | "minzoom": 0,
344 | "maxzoom": 2,
345 | "tilejson": json.loads("{}")
346 | })
347 |
348 | rets.put({"generated": "datetime"})
349 |
350 | # Saving a tile with only lyr1 should only touch the lyr1 columns
351 | storage.save_tile("foo", Tile(0, 0, 0), {"lyr1": b"bar"}, "datetime")
352 |
353 | self.assertRegex(calls[1], r"(?ims)lyr1_data")
354 | self.assertRegex(calls[1], r"(?ims)lyr1_generated")
355 | self.assertNotRegex(calls[1], r"(?ims)lyr2_data")
356 | # lyr2_generated is still present in the RETURNING clause
357 | self.assertNotRegex(calls[1], r"(?ims)lyr2_generated.*RETURNING")
358 |
359 | def test_tilelayers(self):
360 | calls = []
361 | rets = queue.SimpleQueue()
362 | pool = FakePool(calls, rets)
363 |
364 | rets.put({"id": "foo",
365 | "layers": ["lyr1", "lyr2"],
366 | "minzoom": 0,
367 | "maxzoom": 2,
368 | "tilejson": json.loads("{}")
369 | })
370 |
371 | storage = Storage(pool)
372 | storage.delete_tilelayers("foo", {Tile(0, 0, 0): {"lyr1", "lyr2"}})
373 |
374 | self.assertRegex(calls[1], r"(?ims)UPDATE.*foo_z0")
375 | self.assertRegex(calls[1], r"(?ims)SET.*lyr1_data[^,]*=[^,]*NULL")
376 | self.assertRegex(calls[1], r"(?ims)SET.*lyr2_data[^,]*=[^,]*NULL")
377 | self.assertRegex(calls[1], r"(?ims)SET.*lyr1_generated[^,]*=[^,]*NULL")
378 | self.assertRegex(calls[1], r"(?ims)SET.*lyr2_generated[^,]*=[^,]*NULL")
379 | self.assertRegex(calls[1], r"(?ims)WHERE.*x.*y")
380 |
381 | calls.clear()
382 | while not rets.empty():
383 | rets.get()
384 |
385 | # Test combining tiles
386 | rets.put({"id": "foo",
387 | "layers": ["lyr1", "lyr2"],
388 | "minzoom": 0,
389 | "maxzoom": 2,
390 | "tilejson": json.loads("{}")
391 | })
392 |
393 | storage.delete_tilelayers("foo", {Tile(0, 0, 0): {"lyr1"}, Tile(1, 0, 0): {"lyr2"}})
394 |
395 | self.assertRegex(calls[1], r"(?ims)UPDATE.*foo_z0")
396 | self.assertRegex(calls[1], r"(?ims)SET.*lyr1_data[^,]*=[^,]*NULL")
397 | self.assertRegex(calls[1], r"(?ims)SET.*lyr1_generated[^,]*=[^,]*NULL")
398 | self.assertNotRegex(calls[1], r"(?ims)SET.*lyr2_data[^,]*=[^,]*NULL")
399 | self.assertNotRegex(calls[1], r"(?ims)SET.*lyr2_generated[^,]*=[^,]*NULL")
400 | self.assertRegex(calls[2], r"(?ims)UPDATE.*foo_z1")
401 | self.assertRegex(calls[2], r"(?ims)SET.*lyr2_data[^,]*=[^,]*NULL")
402 | self.assertRegex(calls[2], r"(?ims)SET.*lyr2_generated[^,]*=[^,]*NULL")
403 | self.assertNotRegex(calls[2], r"(?ims)SET.*lyr1_data[^,]*=[^,]*NULL")
404 | self.assertNotRegex(calls[2], r"(?ims)SET.*lyr1_generated[^,]*=[^,]*NULL")
405 |
406 | calls.clear()
407 | while not rets.empty():
408 | rets.get()
409 |
410 | def test_metrics(self):
411 | calls = []
412 | rets = queue.SimpleQueue()
413 | pool = FakePool(calls, rets)
414 |
415 | storage = Storage(pool)
416 |
417 | rets.put({"id": "foo",
418 | "zoom": 0,
419 | "num_tiles": 1,
420 | "size": 1024,
421 | "percentiles": [0, 1, 2]})
422 | rets.put({"id": "foo",
423 | "zoom": 1,
424 | "num_tiles": 4,
425 | "size": 4096,
426 | "percentiles": [0, 1, 2]})
427 | metrics = storage.metrics()
428 | self.assertEqual(metrics[0], Metric(id="foo", zoom=0, num_tiles=1,
429 | size=1024, percentiles=[0, 1, 2]))
430 | self.assertEqual(metrics[1], Metric(id="foo", zoom=1, num_tiles=4,
431 | size=4096, percentiles=[0, 1, 2]))
432 |
433 | self.assertRegex(calls[0], r"(?ims)SELECT.*id.*zoom.*num_tiles.*size.*percentiles")
434 | self.assertRegex(calls[0], r"(?ims)FROM.*tile_stats")
435 | # update_metrics
436 |
437 | calls.clear()
438 | while not rets.empty():
439 | rets.get()
440 |
441 | rets.put({"id": "foo",
442 | "layers": ["lyr1", "lyr2"],
443 | "minzoom": 0,
444 | "maxzoom": 1,
445 | "tilejson": json.loads("{}")
446 | })
447 |
448 | storage.update_metrics()
449 |
450 | # calls 0 and 1 are get_tileset and JIT statements
451 | self.assertRegex(calls[2], r"(?i)INSERT INTO.*tile_stats")
452 | self.assertRegex(calls[2], r'''(?ims)SUM\(length\("?lyr1_data"?\)'''
453 | r'''\+length\("?lyr2_data"?\)\)''')
454 | self.assertRegex(calls[2], r'''(?ims)ARRAY\[.*COALESCE\(PERCENTILE_CONT\(.*\).*\).*\]''')
455 | self.assertRegex(calls[2], r"(?i)FROM.*foo_z0")
456 | # call 3 is JIT
457 | self.assertRegex(calls[4], r"(?i)FROM.*foo_z1")
458 |
--------------------------------------------------------------------------------
/tests/test_tile.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 |
3 | from tilekiln.tile import Tile, layer_frominput
4 |
5 |
6 | class TestTile(TestCase):
7 | def test_properties(self):
8 | t = Tile(3, 2, 1)
9 | self.assertEqual(t.zoom, 3)
10 | self.assertEqual(t.x, 2)
11 | self.assertEqual(t.y, 1)
12 |
13 | def test_bounds(self):
14 | t = Tile(3, 2, 1)
15 | self.assertEqual(t.bbox(0), 'ST_TileEnvelope(3, 2, 1, margin=>0)')
16 | self.assertEqual(t.bbox(8/4096), 'ST_TileEnvelope(3, 2, 1, margin=>0.001953125)')
17 |
18 | def test_eq(self):
19 | t1 = Tile(3, 2, 1)
20 | t2 = Tile(3, 2, 1)
21 | t3 = Tile(3, 1, 1)
22 |
23 | self.assertEqual(t1, t2)
24 | self.assertNotEqual(t1, t3)
25 |
26 | def test_tileid(self):
27 | self.assertEqual(Tile(0, 0, 0).tileid, 0)
28 | self.assertEqual(Tile(0, 0, 0), Tile.from_tileid(0))
29 | self.assertEqual(Tile(1, 0, 0).tileid, 1)
30 | self.assertEqual(Tile(1, 0, 0), Tile.from_tileid(1))
31 | self.assertEqual(Tile(2, 0, 0).tileid, 5)
32 | self.assertEqual(Tile(2, 0, 0), Tile.from_tileid(5))
33 | self.assertEqual(Tile(2, 1, 0).tileid, 6)
34 | self.assertEqual(Tile(2, 1, 0), Tile.from_tileid(6))
35 |
36 | def test_fromstring(self):
37 | self.assertEqual(Tile.from_string("0/0/0"), Tile(0, 0, 0))
38 | self.assertEqual(Tile.from_string("1/0/0"), Tile(1, 0, 0))
39 | self.assertEqual(Tile.from_string("1/1/0"), Tile(1, 1, 0))
40 | self.assertEqual(Tile.from_string("1/0/1"), Tile(1, 0, 1))
41 |
42 | self.assertRaises(ValueError, Tile.from_string, "0/0")
43 | self.assertRaises(ValueError, Tile.from_string, "0/0/0/0")
44 | self.assertRaises(ValueError, Tile.from_string, "a/b/c")
45 |
46 | def test_tilelayer(self):
47 | self.assertEqual(layer_frominput("0/0/0,lyr1"),
48 | {Tile(0, 0, 0): {"lyr1"}})
49 | self.assertEqual(layer_frominput("0/0/0,lyr1\n"),
50 | {Tile(0, 0, 0): {"lyr1"}})
51 |
52 | self.assertEqual(layer_frominput("0/0/0,lyr1\n1/0/0,lyr2\n0/0/0,lyr2"),
53 | {Tile(0, 0, 0): {"lyr1", "lyr2"}, Tile(1, 0, 0): {"lyr2"}})
54 |
--------------------------------------------------------------------------------
/tests/test_tilerange.py:
--------------------------------------------------------------------------------
1 | from unittest import TestCase
2 | from tilekiln.tile import Tile
3 | from tilekiln.tilerange import Tilerange
4 |
5 |
6 | class TestTilerange(TestCase):
7 | def test_length(self):
8 | self.assertEqual(len(Tilerange(0, 0)), 1)
9 | self.assertEqual(len(Tilerange(0, 1)), 5)
10 | # If this were not evaluated lazily it would be slow
11 | self.assertEqual(len(Tilerange(30, 30)), 4**30)
12 | self.assertEqual(len(Tilerange(0, 1)), 5)
13 |
14 | def test_items(self):
15 | # Only one tile
16 | for tile in Tilerange(0, 0):
17 | self.assertEqual(tile, Tile(0, 0, 0))
18 |
19 | it1 = iter(Tilerange(0, 1))
20 | self.assertEqual(next(it1), Tile(0, 0, 0))
21 | self.assertEqual(next(it1), Tile(1, 0, 0))
22 | self.assertEqual(next(it1), Tile(1, 0, 1))
23 | self.assertEqual(next(it1), Tile(1, 1, 1))
24 | self.assertEqual(next(it1), Tile(1, 1, 0))
25 | self.assertRaises(StopIteration, next, it1)
26 |
27 | self.assertEqual(len({Tile(0, 0, 0), Tile(1, 0, 0), Tile(1, 0, 0)}), 2)
28 |
29 | # If this were not evaluated lazily it would be slow
30 | it2 = iter(Tilerange(0, 30))
31 | self.assertEqual(next(it2), Tile(0, 0, 0))
32 |
--------------------------------------------------------------------------------
/tilekiln/__init__.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import fs.osfs
4 |
5 | import tilekiln.config
6 |
7 |
8 | # TODO: Put somewhere else
9 | def load_config(path) -> tilekiln.config.Config:
10 | '''Loads a config from the filesystem, given a path'''
11 |
12 | full_path = os.path.join(os.getcwd(), path)
13 | root_path = os.path.dirname(full_path)
14 | config_path = os.path.relpath(full_path, root_path)
15 | filesystem = fs.osfs.OSFS(root_path)
16 |
17 | return tilekiln.config.Config(filesystem.open(config_path).read(),
18 | filesystem)
19 |
--------------------------------------------------------------------------------
/tilekiln/config.py:
--------------------------------------------------------------------------------
1 | import json
2 | import yaml
3 |
4 | import fs
5 |
6 | from tilekiln.definition import Definition
7 | from tilekiln.errors import ConfigYAMLError, ConfigError
8 | from tilekiln.tile import Tile
9 |
10 |
11 | class Config:
12 | def __init__(self, yaml_string: str, filesystem: fs.base.FS):
13 | '''Create a config from a yaml string
14 | Creates a config from the yaml string. Any SQL files referenced must be in the
15 | filesystem.
16 | '''
17 |
18 | try:
19 | config = yaml.safe_load(yaml_string)
20 | except yaml.parser.ParserError:
21 | raise ConfigYAMLError("Unable to parse config YAML")
22 |
23 | try:
24 | metadata = config["metadata"]
25 | except Exception:
26 | raise ConfigYAMLError("No metadata found in config") from None
27 |
28 | try:
29 | self.id = metadata["id"]
30 | except Exception:
31 | raise ConfigYAMLError("id not found in config metadata") from None
32 | if not isinstance(self.id, str) or self.id is None:
33 | raise ConfigYAMLError("metadata.id is not a string") from None
34 |
35 | self.name = metadata.get("name")
36 | self.description = metadata.get("description")
37 | self.attribution = metadata.get("attribution")
38 | self.version = metadata.get("version")
39 | self.bounds = metadata.get("bounds")
40 | self.center = metadata.get("center")
41 | self.__layers = {}
42 | try:
43 | for id, l in config.get("vector_layers", {}).items():
44 | if "\"" in id:
45 | raise ConfigError(f"Illegal character \" found in layer name: f{id}")
46 | if "'" in id:
47 | raise ConfigError(f"Illegal character ' found in layer name: f{id}")
48 | if '\\' in id:
49 | raise ConfigError(f"Illegal character \\ found in layer name: f{id}")
50 | lc = LayerConfig(id, l, filesystem)
51 | self.__layers[lc.id] = lc
52 |
53 | except Exception:
54 | raise ConfigError("Unable to process vector_layers")
55 |
56 | if self.__layers:
57 | self.minzoom = min([layer.minzoom for layer in self.__layers.values()])
58 | self.maxzoom = max([layer.maxzoom for layer in self.__layers.values()])
59 | else:
60 | self.minzoom = None
61 | self.maxzoom = None
62 |
63 | def tilejson(self, url) -> str:
64 | '''Returns a TileJSON'''
65 |
66 | result = {"tilejson": "3.0.0",
67 | "tiles": [f"{url}/{self.id}" + "/{z}/{x}/{y}.mvt"],
68 | "attribution": self.attribution,
69 | "bounds": self.bounds,
70 | "center": self.center,
71 | "description": self.description,
72 | "maxzoom": self.maxzoom,
73 | "minzoom": self.minzoom,
74 | "name": self.name,
75 | "scheme": "xyz"}
76 |
77 | vector_layers = [{"id": layer.id,
78 | "fields": layer.fields,
79 | "description": layer.description,
80 | "minzoom": layer.minzoom,
81 | "maxzoom": layer.maxzoom} for layer in self.__layers.values()]
82 | result["vector_layers"] = [{k: v for k, v in layer.items() if v is not None}
83 | for layer in vector_layers]
84 |
85 | return json.dumps({k: v for k, v in result.items() if v is not None},
86 | sort_keys=True, indent=4)
87 |
88 | def layer_names(self):
89 | return [id for id in self.__layers.keys()]
90 |
91 | def layer_query(self, layer: str, tile: Tile) -> str:
92 | return self.__layers[layer].render_sql(tile)
93 |
94 | def layer_queries(self, tile: Tile) -> dict[str, str | None]:
95 | '''Returns queries for layers
96 |
97 | For layers defined in the config but not present at this zoom None is returned
98 | '''
99 | return {name: layer.render_sql(tile)
100 | for name, layer in self.__layers.items()}
101 |
102 |
103 | class LayerConfig:
104 | def __init__(self, id: str, layer_yaml: dict, filesystem: fs.base.FS):
105 | '''Create a layer config
106 | Creates a layer config from the config yaml for a layer. Any SQL files referenced must
107 | be in the filesystem.
108 | '''
109 | self.id = id
110 | self.description = layer_yaml.get("description")
111 | self.fields = layer_yaml.get("fields", {})
112 | self.definitions: list[Definition] = []
113 | self.geometry_type = set(layer_yaml.get("geometry_type", []))
114 |
115 | self.__definitions = set()
116 | for definition in layer_yaml.get("sql", []):
117 | self.__definitions.add(Definition(id, definition, filesystem))
118 |
119 | self.minzoom = min({d.minzoom for d in self.__definitions})
120 | self.maxzoom = max({d.maxzoom for d in self.__definitions})
121 |
122 | def render_sql(self, tile: Tile) -> str | None:
123 | '''Returns the SQL for a layer, given a tile, or None if it is outside the zoom range
124 | of the definitions
125 | '''
126 | if tile.zoom > self.maxzoom or tile.zoom < self.minzoom:
127 | return None
128 |
129 | # Match the first definition for the layer
130 | for d in self.__definitions:
131 | if tile.zoom <= d.maxzoom and tile.zoom >= d.minzoom:
132 | return d.render_sql(tile)
133 |
134 | return None
135 |
--------------------------------------------------------------------------------
/tilekiln/definition.py:
--------------------------------------------------------------------------------
1 | import jinja2 as j2
2 |
3 | import fs
4 |
5 | from tilekiln.tile import Tile
6 | from tilekiln.errors import DefinitionError
7 |
8 | DEFAULT_EXTENT = 4096
9 | DEFAULT_BUFFER = 0
10 |
11 | # Invariants of web mercator
12 | HALF_WORLD = 20037508.34
13 |
14 | j2Environment = j2.Environment(loader=j2.BaseLoader(), lstrip_blocks=True, trim_blocks=True)
15 |
16 |
17 | class Definition:
18 | def __init__(self, id: str, definition_yaml, filesystem: fs.base.FS):
19 | self.id = id
20 |
21 | try:
22 | self.minzoom = definition_yaml["minzoom"]
23 | except KeyError:
24 | raise DefinitionError(f"Layer {id} is missing minzoom on a definition") from None
25 | try:
26 | self.maxzoom = definition_yaml["maxzoom"]
27 | except KeyError:
28 | raise DefinitionError(f"Layer {id} is missing maxzoom on a definition") from None
29 |
30 | self.extent = definition_yaml.get("extent", DEFAULT_EXTENT)
31 | self.buffer = definition_yaml.get("buffer", DEFAULT_BUFFER)
32 |
33 | # TODO: Let is use directories so one file can include others.
34 | filename = definition_yaml["file"]
35 | try:
36 | self.__template = j2Environment.from_string(filesystem.readtext(filename))
37 | except fs.errors.ResourceNotFound:
38 | raise DefinitionError(f"Layer {id} is missing is missing file {filename}") from None
39 |
40 | def render_sql(self, tile: Tile) -> str:
41 | '''Generate the SQL for a layer
42 | '''
43 |
44 | # Tile validity constraints. x/y are checked by Tile class
45 | assert tile.zoom >= self.minzoom
46 | assert tile.zoom <= self.maxzoom
47 |
48 | # See https://postgis.net/docs/ST_AsMVT.html for SQL source
49 |
50 | inner = self.__template.render(zoom=tile.zoom, x=tile.x, y=tile.y,
51 | bbox=tile.bbox(self.buffer/self.extent),
52 | unbuffered_bbox=tile.bbox(0),
53 | extent=self.extent,
54 | buffer=self.buffer,
55 | tile_length=tile_length(tile),
56 | tile_area=tile_length(tile)**2,
57 | coordinate_length=tile_length(tile)/self.extent,
58 | coordinate_area=(tile_length(tile)/self.extent)**2)
59 |
60 | # TODO: Use proper escaping for self.id in SQL
61 | return (f'''WITH mvtgeom AS -- {self.id}/{tile.zoom}/{tile.x}/{tile.y}\n(\n''' +
62 | inner + f'''\n)\nSELECT ST_AsMVT(mvtgeom.*, '{self.id}', {self.extent})\n''' +
63 | '''FROM mvtgeom;''')
64 |
65 |
66 | def tile_length(tile) -> float:
67 | '''Returns the length of a tile, in projected units
68 | '''
69 | # -1 for half vs full world
70 | return HALF_WORLD/(2**(tile.zoom-1))
71 |
--------------------------------------------------------------------------------
/tilekiln/dev/__init__.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import psycopg_pool
4 | from fastapi import FastAPI, Response, HTTPException
5 | from fastapi.responses import RedirectResponse
6 | from fastapi.middleware.cors import CORSMiddleware
7 |
8 | import tilekiln
9 | from tilekiln.kiln import Kiln
10 | from tilekiln.config import Config
11 | from tilekiln.tile import Tile
12 |
13 |
14 | # Constants for environment variable names
15 | TILEKILN_CONFIG = "TILEKILN_CONFIG"
16 | TILEKILN_URL = "TILEKILN_URL"
17 | TILEKILN_ID = "TILEKILN_ID"
18 |
19 | STANDARD_HEADERS = {"Cache-Control": "no-cache"}
20 |
21 | kiln: Kiln
22 | config: Config
23 |
24 | dev = FastAPI()
25 | dev.add_middleware(CORSMiddleware,
26 | allow_origins=["*"],
27 | allow_methods=["*"],
28 | allow_headers=["*"])
29 |
30 |
31 | @dev.on_event("startup")
32 | def load_config():
33 | global config
34 | config = tilekiln.load_config(os.environ[TILEKILN_CONFIG])
35 | config.id = os.environ[TILEKILN_ID]
36 | # Because the DB connection variables are passed as standard PG* vars,
37 | # a plain connect() will connect to the right DB
38 |
39 | pool = psycopg_pool.ConnectionPool(min_size=1, max_size=1, num_workers=1,
40 | check=psycopg_pool.ConnectionPool.check_connection)
41 |
42 | global kiln
43 | kiln = Kiln(config, pool)
44 |
45 |
46 | @dev.head("/")
47 | @dev.get("/")
48 | def root():
49 | raise HTTPException(status_code=404)
50 |
51 |
52 | @dev.head("/favicon.ico")
53 | @dev.get("/favicon.ico")
54 | def favicon():
55 | return Response("")
56 |
57 |
58 | @dev.head("/tilejson.json")
59 | @dev.get("/tilejson.json")
60 | def redirect_tilejson():
61 | global config
62 | return RedirectResponse(f"/{config.id}/tilejson.json")
63 |
64 |
65 | @dev.head("/{prefix}/tilejson.json")
66 | @dev.get("/{prefix}/tilejson.json")
67 | def tilejson(prefix):
68 | global config
69 | if prefix != config.id:
70 | raise HTTPException(status_code=404, detail=f"Tileset {prefix} not found on server.")
71 | return Response(content=config.tilejson(os.environ[TILEKILN_URL]),
72 | media_type="application/json",
73 | headers=STANDARD_HEADERS)
74 |
75 |
76 | @dev.head("/{prefix}/{zoom}/{x}/{y}.mvt")
77 | @dev.get("/{prefix}/{zoom}/{x}/{y}.mvt")
78 | def serve_tile(prefix: str, zoom: int, x: int, y: int):
79 | global config
80 | if prefix != config.id:
81 | raise HTTPException(status_code=404, detail=f"Tileset {prefix} not found on server.")
82 | global kiln
83 | tile = b''.join(kiln.render_all(Tile(zoom, x, y)).values())
84 | return Response(tile, media_type="application/vnd.mapbox-vector-tile",
85 | headers=STANDARD_HEADERS)
86 |
--------------------------------------------------------------------------------
/tilekiln/errors.py:
--------------------------------------------------------------------------------
1 | '''
2 | Custom exceptions used by tilekiln
3 |
4 | Exception (base)
5 | |_ Error
6 | |_ ConfigError
7 | |_ RuntimeError
8 | '''
9 |
10 |
11 | class Error(Exception):
12 | pass
13 |
14 |
15 | class ConfigError(Error):
16 | pass
17 |
18 |
19 | class ConfigYAMLError(ConfigError):
20 | ''' Errors where YAML is invalid, missing, or types are wrong'''
21 | pass
22 |
23 |
24 | class ConfigLayerError(ConfigError):
25 | pass
26 |
27 |
28 | class DefinitionError(ConfigLayerError):
29 | pass
30 |
31 |
32 | class RuntimeError(Error):
33 | pass
34 |
35 |
36 | class ZoomNotDefined(RuntimeError):
37 | pass
38 |
39 |
40 | class LayerNotDefined(RuntimeError):
41 | pass
42 |
43 |
44 | class TilesetMissing(RuntimeError):
45 | pass
46 |
--------------------------------------------------------------------------------
/tilekiln/generator.py:
--------------------------------------------------------------------------------
1 | '''
2 | The code here pulls creates multiple kilns to generate the tiles in parallel
3 | '''
4 | import multiprocessing as mp
5 | from collections.abc import Collection
6 |
7 | import psycopg_pool
8 |
9 | from tilekiln.config import Config
10 | from tilekiln.kiln import Kiln
11 | from tilekiln.storage import Storage
12 | from tilekiln.tile import Tile
13 | from tilekiln.tileset import Tileset
14 |
15 |
16 | kiln: Kiln
17 | tileset: Tileset
18 |
19 |
20 | def setup(config: Config, source_kwargs, storage_kwargs) -> None: # type: ignore[no-untyped-def]
21 | '''
22 | Sets up the kiln and tileset for the worker function.
23 | '''
24 | global kiln, tileset
25 | source_pool = psycopg_pool.ConnectionPool(min_size=1, max_size=1, num_workers=1,
26 | check=psycopg_pool.ConnectionPool.check_connection,
27 | kwargs=source_kwargs)
28 | kiln = Kiln(config, source_pool)
29 |
30 | storage_pool = psycopg_pool.ConnectionPool(min_size=1, max_size=1, num_workers=1,
31 | check=psycopg_pool.ConnectionPool.check_connection,
32 | kwargs=storage_kwargs)
33 | storage = Storage(storage_pool)
34 | tileset = Tileset.from_config(storage, config)
35 |
36 |
37 | def worker(tile: Tile) -> None:
38 | global kiln, tileset
39 | try:
40 | mvt = kiln.render_all(tile)
41 | # Because everything was rendered we don't need to check for missing layers
42 | tileset.save_tile(tile, mvt)
43 | except Exception as e:
44 | print(f"Error generating {tile}")
45 | raise RuntimeError(f"Error generating {tile}") from e
46 |
47 |
48 | def layer_worker(work: tuple[Tile, set[str]]) -> None:
49 | global kiln, tileset
50 | tile, layers = work
51 | try:
52 | new_mvts = {layer: kiln.render_layer(layer, tile) for layer in layers}
53 | # Because everything was rendered we don't need to check for missing layers
54 | tileset.save_tile(tile, new_mvts)
55 | except Exception as e:
56 | print(f"Error generating {tile}")
57 | raise RuntimeError(f"Error generating {tile}") from e
58 |
59 |
60 | def generate(config: Config, source_kwargs, storage_kwargs, # type: ignore[no-untyped-def]
61 | tiles: Collection[Tile], num_processes: int) -> None:
62 |
63 | # If there are no processes and no tiles then there's nothing to do.
64 | if num_processes == 0 and len(tiles) == 0:
65 | return
66 |
67 | with mp.Pool(num_processes, setup, (config, source_kwargs, storage_kwargs)) as pool:
68 | imap_it = pool.imap_unordered(worker, tiles, 100)
69 | pool.close()
70 | pool.join()
71 |
72 | # Check for exceptions
73 | for x in imap_it:
74 | pass
75 |
76 |
77 | def generate_layers(config: Config, source_kwargs, storage_kwargs, # type: ignore[no-untyped-def]
78 | layers: Collection[tuple[Tile, set[str]]], num_processes: int) -> None:
79 |
80 | # If there are no processes and no tiles then there's nothing to do.
81 | if num_processes == 0 and len(layers) == 0:
82 | return
83 |
84 | with mp.Pool(num_processes, setup, (config, source_kwargs, storage_kwargs)) as pool:
85 | imap_it = pool.imap_unordered(layer_worker, layers, 100)
86 | pool.close()
87 | pool.join()
88 |
89 | # Check for exceptions
90 | for x in imap_it:
91 | pass
92 |
--------------------------------------------------------------------------------
/tilekiln/kiln.py:
--------------------------------------------------------------------------------
1 | import psycopg
2 | import psycopg_pool
3 |
4 | import tilekiln.errors
5 | from tilekiln.config import Config
6 | from tilekiln.tile import Tile
7 |
8 |
9 | class Kiln:
10 | '''
11 | The kiln is what actually generates the tiles, using the config to compute SQL,
12 | and a DB connection to execute it
13 | '''
14 | def __init__(self, config: Config, pool: psycopg_pool.ConnectionPool):
15 | self.__config = config
16 | self.__pool = pool
17 |
18 | def render_all(self, tile: Tile) -> dict[str, bytes]:
19 | if tile.zoom < self.__config.minzoom or tile.zoom > self.__config.maxzoom:
20 | raise tilekiln.errors.ZoomNotDefined
21 |
22 | with self.__pool.connection() as conn:
23 | with conn.cursor() as curs:
24 | return {name: self.__render_sql(curs, sql)
25 | for name, sql in self.__config.layer_queries(tile).items()}
26 |
27 | def render_layer(self, layer: str, tile: Tile) -> bytes:
28 | with self.__pool.connection() as conn:
29 | with conn.cursor() as curs:
30 | return self.__render_sql(curs, self.__config.layer_query(layer, tile))
31 |
32 | def __render_sql(self, curs: psycopg.Cursor, sql: str | None) -> bytes:
33 | if sql is None:
34 | # None is a query for a layer not present in this zoom
35 | return b''
36 |
37 | curs.execute(sql, binary=True)
38 | for record in curs:
39 | return record[0]
40 | raise RuntimeError("No rows in tile query result, should never reach here")
41 |
--------------------------------------------------------------------------------
/tilekiln/main.py:
--------------------------------------------------------------------------------
1 | import click
2 | import psycopg_pool
3 |
4 | import tilekiln
5 | import tilekiln.dev
6 | import tilekiln.server
7 | import tilekiln.scripts.config
8 | import tilekiln.scripts.generate
9 | import tilekiln.scripts.serve
10 | import tilekiln.scripts.storage
11 | from tilekiln.storage import Storage
12 |
13 |
14 | # Allocated as per https://github.com/prometheus/prometheus/wiki/Default-port-allocations
15 | PROMETHEUS_PORT = 10013
16 |
17 |
18 | # We want click to print out commands in the order they are defined.
19 | class OrderCommands(click.Group):
20 | def list_commands(self, ctx: click.Context) -> list[str]:
21 | return list(self.commands)
22 |
23 |
24 | @click.group(cls=OrderCommands)
25 | def cli() -> None:
26 | pass
27 |
28 |
29 | cli.add_command(tilekiln.scripts.config.config)
30 | cli.add_command(tilekiln.scripts.generate.generate)
31 | cli.add_command(tilekiln.scripts.storage.storage)
32 | cli.add_command(tilekiln.scripts.serve.serve)
33 |
34 |
35 | @cli.command()
36 | @click.option('--bind-host', default='0.0.0.0', show_default=True,
37 | help='Bind socket to this host. ')
38 | @click.option('--bind-port', default=PROMETHEUS_PORT, show_default=True,
39 | type=click.INT, help='Bind socket to this port.')
40 | @click.option('--storage-dbname')
41 | @click.option('--storage-host')
42 | @click.option('--storage-port', type=click.INT)
43 | @click.option('--storage-username')
44 | def prometheus(bind_host: str, bind_port: int, storage_dbname: str, storage_host: str,
45 | storage_port: int, storage_username: str) -> None:
46 | '''Run a prometheus exporter for metrics on tiles.'''
47 | # The prometheus exporter sometimes needs multiple connections
48 | with psycopg_pool.ConnectionPool(min_size=3, max_size=3, num_workers=1,
49 | check=psycopg_pool.ConnectionPool.check_connection,
50 | kwargs={"dbname": storage_dbname,
51 | "host": storage_host,
52 | "port": storage_port,
53 | "user": storage_username}) as pool:
54 | storage = Storage(pool)
55 |
56 | # tilekiln.prometheus brings in a bunch of stuff, so only do this
57 | # for this command
58 | from tilekiln.prometheus import serve_prometheus
59 | # TODO: make sleep a parameter
60 | click.echo(f'Running prometheus exporter on http://{bind_host}:{bind_port}/')
61 | serve_prometheus(storage, bind_host, bind_port, 15)
62 |
--------------------------------------------------------------------------------
/tilekiln/metric.py:
--------------------------------------------------------------------------------
1 | from dataclasses import dataclass
2 |
3 |
4 | @dataclass(kw_only=True, frozen=True)
5 | class Metric:
6 | """ Class for a metric about a tileset in storage """
7 | id: str
8 | zoom: int
9 | num_tiles: int
10 | size: int
11 | percentiles: dict[float, float]
12 |
--------------------------------------------------------------------------------
/tilekiln/prometheus.py:
--------------------------------------------------------------------------------
1 | import time
2 |
3 | import prometheus_client
4 | from prometheus_client.registry import Collector
5 | from prometheus_client.core import GaugeMetricFamily, REGISTRY
6 |
7 | from tilekiln.storage import Storage
8 |
9 | # Disable default metrics since we're not monitoring this process, we're monitoring
10 | # the DB sizes
11 | REGISTRY.unregister(prometheus_client.GC_COLLECTOR)
12 | REGISTRY.unregister(prometheus_client.PLATFORM_COLLECTOR)
13 | REGISTRY.unregister(prometheus_client.PROCESS_COLLECTOR)
14 |
15 | # Don't auto-create metrics for when the metric was created
16 | prometheus_client.disable_created_metrics()
17 |
18 |
19 | class TilekilnCollector(Collector):
20 | def __init__(self, storage: Storage):
21 | self.__storage = storage
22 | super().__init__()
23 |
24 | self.__i = 0
25 |
26 | # This one is run every 15s
27 | def collect(self):
28 | # This is manually producing the metrics described in
29 | # https://prometheus.io/docs/concepts/metric_types/#summary
30 | # Native histograms would be nice here, but are still only experimental
31 | size = GaugeMetricFamily('tilekiln_stored_bytes_sum', 'Total size of tiles',
32 | labels=['tileset', 'zoom'])
33 | quantiles = GaugeMetricFamily('tilekiln_stored_bytes', 'Tile percentiles',
34 | labels=['tileset', 'zoom', 'quantile'])
35 | total = GaugeMetricFamily('tilekiln_stored_count', 'Tiles in tilekiln storage',
36 | labels=['tileset', 'zoom'])
37 | for metric in self.__storage.metrics():
38 | size.add_metric([metric.id, str(metric.zoom)], metric.size)
39 | total.add_metric([metric.id, str(metric.zoom)], metric.num_tiles)
40 | for i in range(0, len(metric.percentiles[0])):
41 | quantiles.add_metric([metric.id, str(metric.zoom), str(metric.percentiles[0][i])],
42 | metric.percentiles[1][i])
43 | yield total
44 | yield size
45 | yield quantiles
46 |
47 | def update(self):
48 | self.__i = self.__i + 1
49 | pass
50 |
51 |
52 | METRIC_UPDATE_TIME = prometheus_client.Summary('tilekiln_metrics_storage_seconds',
53 | 'Time spent updating metrics')
54 |
55 |
56 | @METRIC_UPDATE_TIME.time()
57 | def monitored_update_metrics(storage: Storage):
58 | '''Update storage metrics while tracking call time
59 |
60 | The easiest way to monitor a function is to annotate it. Rather than require
61 | prometheus in storage.py, we wrap it and annotate the wrapper to track call time.
62 | '''
63 | storage.update_metrics()
64 |
65 |
66 | def serve_prometheus(storage: Storage, addr, port, sleep):
67 | '''Start a prometheus server for storage info.'''
68 | collector = TilekilnCollector(storage)
69 | REGISTRY.register(collector)
70 | # start http
71 | prometheus_client.start_http_server(port=port, addr=addr)
72 | while True:
73 | # TODO: Time this with prometheus
74 | monitored_update_metrics(storage)
75 | time.sleep(sleep)
76 |
--------------------------------------------------------------------------------
/tilekiln/scripts/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pnorman/tilekiln/0394c1c406dfc5e936f29f32ec4c3892b590528d/tilekiln/scripts/__init__.py
--------------------------------------------------------------------------------
/tilekiln/scripts/config.py:
--------------------------------------------------------------------------------
1 | import click
2 |
3 | import tilekiln
4 | from tilekiln.tile import Tile
5 |
6 |
7 | @click.group()
8 | def config() -> None:
9 | '''Commands to work with and check config files'''
10 | pass
11 |
12 |
13 | @config.command()
14 | @click.option('--config', required=True, type=click.Path(exists=True, dir_okay=False))
15 | def test(config: str):
16 | '''Tests a config for validity.
17 |
18 | The process will exit with exit code 0 if tilekiln can load the config.
19 |
20 | This is intended for build and CI scripts used by configs.
21 | '''
22 | tilekiln.load_config(config)
23 | return 0
24 |
25 |
26 | @config.command()
27 | @click.option('--config', required=True, type=click.Path(exists=True, dir_okay=False))
28 | @click.option('--layer', type=click.STRING)
29 | @click.option('--zoom', '-z', type=click.INT, required=True)
30 | @click.option('-x', type=click.INT, required=True)
31 | @click.option('-y', type=click.INT, required=True)
32 | def sql(config: str, layer: str, zoom: int, x: int, y: int):
33 | '''Print the SQL for a tile or layer.
34 |
35 | Prints the SQL that would be issued to generate a particular tile layer,
36 | or if no layer is given, the entire tile. This allows manual debugging of
37 | a tile query.
38 | '''
39 |
40 | c = tilekiln.load_config(config)
41 |
42 | if layer is None:
43 | for sql in c.layer_queries(Tile(zoom, x, y)).values():
44 | if sql is not None:
45 | click.echo(sql)
46 | return 0
47 | else:
48 | try:
49 | sql = c.layer_query(layer, Tile(zoom, x, y))
50 | except KeyError:
51 | click.echo(f"Layer '{layer}' not found in configuration", err=True)
52 | return 1
53 | if sql is None:
54 | click.echo((f"Zoom {zoom} not between min zoom and max zoom for layer {layer}."),
55 | err=True)
56 | return 1
57 | click.echo(sql)
58 | return 0
59 |
--------------------------------------------------------------------------------
/tilekiln/scripts/generate.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 |
4 | import click
5 | from tqdm import tqdm
6 |
7 | import tilekiln
8 |
9 | from tilekiln.tile import Tile, layer_frominput
10 | from tilekiln.tilerange import Tilerange
11 | import tilekiln.generator
12 |
13 |
14 | @click.group()
15 | def generate() -> None:
16 | '''Commands for tile generation.
17 |
18 | All tile generation commands run queries against the source database which has the
19 | geospatial data
20 | '''
21 | pass
22 |
23 |
24 | @generate.command()
25 | @click.option('--config', required=True, type=click.Path(exists=True, dir_okay=False))
26 | @click.option('-n', '--num-threads', default=len(os.sched_getaffinity(0)),
27 | show_default=True, help='Number of worker processes.')
28 | @click.option('--source-dbname')
29 | @click.option('--source-host')
30 | @click.option('--source-port')
31 | @click.option('--source-username')
32 | @click.option('--storage-dbname')
33 | @click.option('--storage-host')
34 | @click.option('--storage-port')
35 | @click.option('--storage-username')
36 | @click.option('--progress/--no-progress', help='Display progress bar')
37 | def tiles(config: int, num_threads: int,
38 | source_dbname: str, source_host: str, source_port: int, source_username: str,
39 | storage_dbname: str, storage_host: str, storage_port: int, storage_username: str,
40 | progress: bool) -> None:
41 | '''Generate specific tiles.
42 |
43 | A list of z/x/y tiles is read from stdin and those tiles are generated and saved
44 | to storage.
45 | '''
46 |
47 | c = tilekiln.load_config(config)
48 |
49 | tiles = {Tile.from_string(t) for t in sys.stdin}
50 | threads = min(num_threads, len(tiles)) # No point in more threads than tiles
51 |
52 | click.echo(f"Rendering {len(tiles)} tiles over {threads} threads")
53 |
54 | source_kwargs = {"dbname": source_dbname,
55 | "host": source_host,
56 | "port": source_port,
57 | "user": source_username}
58 | storage_kwargs = {"dbname": storage_dbname,
59 | "host": storage_host,
60 | "port": storage_port,
61 | "user": storage_username}
62 | if progress:
63 | tilekiln.generator.generate(c, source_kwargs, storage_kwargs, tqdm(tiles), threads)
64 | else:
65 | tilekiln.generator.generate(c, source_kwargs, storage_kwargs, tiles, threads)
66 |
67 |
68 | @generate.command()
69 | @click.option('--config', required=True, type=click.Path(exists=True, dir_okay=False))
70 | @click.option('-n', '--num-threads', default=len(os.sched_getaffinity(0)),
71 | show_default=True, help='Number of worker processes.')
72 | @click.option('--source-dbname')
73 | @click.option('--source-host')
74 | @click.option('--source-port')
75 | @click.option('--source-username')
76 | @click.option('--storage-dbname')
77 | @click.option('--storage-host')
78 | @click.option('--storage-port')
79 | @click.option('--storage-username')
80 | @click.option('--min-zoom', type=click.INT, required=True)
81 | @click.option('--max-zoom', type=click.INT, required=True)
82 | @click.option('--progress/--no-progress', help='Display progress bar')
83 | def zooms(config: int, num_threads: int,
84 | source_dbname: str, source_host: str, source_port: int, source_username: str,
85 | storage_dbname: str, storage_host: str, storage_port: int, storage_username: str,
86 | min_zoom: int, max_zoom: int, progress: bool) -> None:
87 |
88 | c = tilekiln.load_config(config)
89 |
90 | tiles = Tilerange(min_zoom, max_zoom)
91 | threads = min(num_threads, len(tiles)) # No point in more threads than tiles
92 | click.echo(f"Rendering {len(tiles)} tiles over {threads} threads")
93 | source_kwargs = {"dbname": source_dbname,
94 | "host": source_host,
95 | "port": source_port,
96 | "user": source_username}
97 | storage_kwargs = {"dbname": storage_dbname,
98 | "host": storage_host,
99 | "port": storage_port,
100 | "user": storage_username}
101 | if progress:
102 | tilekiln.generator.generate(c, source_kwargs, storage_kwargs, tqdm(tiles), threads)
103 | else:
104 | tilekiln.generator.generate(c, source_kwargs, storage_kwargs, tiles, threads)
105 |
106 |
107 | @generate.command()
108 | @click.option('--config', required=True, type=click.Path(exists=True, dir_okay=False))
109 | @click.option('-n', '--num-threads', default=len(os.sched_getaffinity(0)),
110 | show_default=True, help='Number of worker processes.')
111 | @click.option('--source-dbname')
112 | @click.option('--source-host')
113 | @click.option('--source-port')
114 | @click.option('--source-username')
115 | @click.option('--storage-dbname')
116 | @click.option('--storage-host')
117 | @click.option('--storage-port')
118 | @click.option('--storage-username')
119 | @click.option('--progress/--no-progress', help='Display progress bar')
120 | def layers(config: int, num_threads: int,
121 | source_dbname: str, source_host: str, source_port: int, source_username: str,
122 | storage_dbname: str, storage_host: str, storage_port: int, storage_username: str,
123 | progress: bool) -> None:
124 | '''Generate specific tile layers.
125 |
126 | A list of z/x/y,layer layers is read from stdin and those are generated and saved
127 | to storage.
128 | '''
129 |
130 | c = tilekiln.load_config(config)
131 |
132 | layers = layer_frominput(sys.stdin.read())
133 | threads = min(num_threads, len(layers)) # No point in more threads than tiles
134 |
135 | click.echo(f"Rendering {len(layers)} tiles over {threads} threads")
136 |
137 | source_kwargs = {"dbname": source_dbname,
138 | "host": source_host,
139 | "port": source_port,
140 | "user": source_username}
141 | storage_kwargs = {"dbname": storage_dbname,
142 | "host": storage_host,
143 | "port": storage_port,
144 | "user": storage_username}
145 | if progress:
146 | tilekiln.generator.generate_layers(c, source_kwargs, storage_kwargs,
147 | tqdm(layers.items()), threads)
148 | else:
149 | tilekiln.generator.generate_layers(c, source_kwargs, storage_kwargs,
150 | layers.items(), threads)
151 |
--------------------------------------------------------------------------------
/tilekiln/scripts/serve.py:
--------------------------------------------------------------------------------
1 | import os
2 |
3 | import click
4 | import uvicorn
5 |
6 | import tilekiln
7 | import tilekiln.dev
8 | import tilekiln.server
9 |
10 |
11 | @click.group()
12 | def serve() -> None:
13 | '''Commands for tile serving.
14 |
15 | All tile serving commands serve tiles and a tilejson over HTTP.
16 | '''
17 | pass
18 |
19 |
20 | @serve.command()
21 | @click.option('--config', required=True, type=click.Path(exists=True, dir_okay=False))
22 | @click.option('--bind-host', default='127.0.0.1', show_default=True,
23 | help='Bind socket to this host.')
24 | @click.option('--bind-port', default=8000, show_default=True,
25 | type=click.INT, help='Bind socket to this port.')
26 | @click.option('-n', '--num-threads', default=len(os.sched_getaffinity(0)),
27 | show_default=True, help='Number of worker processes.')
28 | @click.option('--source-dbname')
29 | @click.option('--source-host', type=click.INT)
30 | @click.option('--source-port')
31 | @click.option('--source-username')
32 | @click.option('--base-url', help='Defaults to http://127.0.0.1:8000' +
33 | ' or the bind host and port')
34 | @click.option('--id', help='Override YAML config ID')
35 | def dev(config: str, bind_host: str, bind_port: int, num_threads: int,
36 | source_dbname: str, source_host: str, source_port: int, source_username: str,
37 | base_url: str, id: str) -> None:
38 | '''Starts a server for development
39 | '''
40 | os.environ[tilekiln.dev.TILEKILN_CONFIG] = config
41 | os.environ[tilekiln.dev.TILEKILN_ID] = id or tilekiln.load_config(config).id
42 |
43 | if base_url is not None:
44 | os.environ[tilekiln.dev.TILEKILN_URL] = base_url
45 | else:
46 | os.environ[tilekiln.dev.TILEKILN_URL] = (f"http://{bind_host}:{bind_port}")
47 | if source_dbname is not None:
48 | os.environ["PGDATABASE"] = source_dbname
49 | if source_host is not None:
50 | os.environ["PGHOST"] = source_host
51 | if source_port is not None:
52 | os.environ["PGPORT"] = str(source_port)
53 | if source_username is not None:
54 | os.environ["PGUSER"] = source_username
55 |
56 | uvicorn.run("tilekiln.dev:dev", host=bind_host, port=bind_port, workers=num_threads)
57 |
58 |
59 | @serve.command()
60 | @click.option('--config', required=True, type=click.Path(exists=True, dir_okay=False))
61 | @click.option('--bind-host', default='127.0.0.1', show_default=True,
62 | help='Bind socket to this host. ')
63 | @click.option('--bind-port', default=8000, show_default=True,
64 | type=click.INT, help='Bind socket to this port.')
65 | @click.option('-n', '--num-threads', default=len(os.sched_getaffinity(0)),
66 | show_default=True, help='Number of worker processes.')
67 | @click.option('--source-dbname')
68 | @click.option('--source-host')
69 | @click.option('--source-port')
70 | @click.option('--source-username')
71 | @click.option('--storage-dbname')
72 | @click.option('--storage-host')
73 | @click.option('--storage-port')
74 | @click.option('--storage-username')
75 | @click.option('--base-url', help='Defaults to http://127.0.0.1:8000' +
76 | ' or the bind host and port')
77 | def live(config: str, bind_host: str, bind_port: int, num_threads: int,
78 | source_dbname: str, source_host: str, source_port: int, source_username: str,
79 | storage_dbname: str, storage_host: str, storage_port: int, storage_username: str,
80 | base_url: str) -> None:
81 | '''Starts a server for pre-generated tiles from DB'''
82 | os.environ[tilekiln.server.TILEKILN_CONFIG] = config
83 | os.environ[tilekiln.server.TILEKILN_THREADS] = str(num_threads)
84 |
85 | if base_url is not None:
86 | os.environ[tilekiln.dev.TILEKILN_URL] = base_url
87 | else:
88 | os.environ[tilekiln.dev.TILEKILN_URL] = (f"http://{bind_host}:{bind_port}")
89 | if source_dbname is not None:
90 | os.environ["GENERATE_PGDATABASE"] = source_dbname
91 | if source_host is not None:
92 | os.environ["GENERATE_PGHOST"] = source_host
93 | if source_port is not None:
94 | os.environ["GENERATE_PGPORT"] = str(source_port)
95 | if source_username is not None:
96 | os.environ["GENERATE_PGUSER"] = source_username
97 |
98 | if storage_dbname is not None:
99 | os.environ["STORAGE_PGDATABASE"] = storage_dbname
100 | if storage_host is not None:
101 | os.environ["STORAGE_PGHOST"] = storage_host
102 | if storage_port is not None:
103 | os.environ["STORAGE_PGPORT"] = str(storage_port)
104 | if storage_username is not None:
105 | os.environ["STORAGE_PGUSER"] = storage_username
106 |
107 | uvicorn.run("tilekiln.server:live", host=bind_host, port=bind_port, workers=num_threads)
108 |
109 |
110 | @serve.command()
111 | @click.option('--bind-host', default='127.0.0.1', show_default=True,
112 | help='Bind socket to this host. ')
113 | @click.option('--bind-port', default=8000, show_default=True,
114 | type=click.INT, help='Bind socket to this port.')
115 | @click.option('-n', '--num-threads', default=len(os.sched_getaffinity(0)),
116 | type=click.INT, show_default=True, help='Number of worker processes.')
117 | @click.option('--storage-dbname')
118 | @click.option('--storage-host')
119 | @click.option('--storage-port')
120 | @click.option('--storage-username')
121 | @click.option('--base-url', help='Defaults to http://127.0.0.1:8000' +
122 | ' or the bind host and port')
123 | def static(bind_host: str, bind_port: int, num_threads: int,
124 | storage_dbname: str, storage_host: str, storage_port: int, storage_username: str,
125 | base_url: str) -> None:
126 | '''Starts a server for pre-generated tiles from DB'''
127 |
128 | os.environ[tilekiln.server.TILEKILN_THREADS] = str(num_threads)
129 |
130 | if base_url is not None:
131 | os.environ[tilekiln.dev.TILEKILN_URL] = base_url
132 | else:
133 | os.environ[tilekiln.dev.TILEKILN_URL] = (f"http://{bind_host}:{bind_port}")
134 | if storage_dbname is not None:
135 | os.environ["PGDATABASE"] = storage_dbname
136 | if storage_host is not None:
137 | os.environ["PGHOST"] = storage_host
138 | if storage_port is not None:
139 | os.environ["PGPORT"] = str(storage_port)
140 | if storage_username is not None:
141 | os.environ["PGUSER"] = storage_username
142 |
143 | uvicorn.run("tilekiln.server:server", host=bind_host, port=bind_port, workers=num_threads)
144 |
--------------------------------------------------------------------------------
/tilekiln/scripts/storage.py:
--------------------------------------------------------------------------------
1 | import datetime
2 | import sys
3 |
4 | import click
5 | import psycopg_pool
6 |
7 | import tilekiln
8 |
9 | from tilekiln.tile import Tile, layer_frominput
10 | from tilekiln.tileset import Tileset
11 | from tilekiln.storage import Storage
12 |
13 |
14 | @click.group()
15 | def storage() -> None:
16 | '''Commands working with tile storage.
17 |
18 | These commands allow creation and manipulation of the tile storage database.
19 | '''
20 | pass
21 |
22 |
23 | @storage.command()
24 | @click.option('--config', required=True, type=click.Path(exists=True, dir_okay=False))
25 | @click.option('--storage-dbname')
26 | @click.option('--storage-host')
27 | @click.option('--storage-port', type=click.INT)
28 | @click.option('--storage-username')
29 | @click.option('--id', help='Override YAML config ID')
30 | def init(config: str,
31 | storage_dbname: str, storage_host: str, storage_port: int, storage_username: str,
32 | id: str) -> None:
33 | '''Initialize storage for tiles.
34 |
35 | Creates the storage for a tile layer and stores its metadata in the database.
36 | If the metadata tables have not yet been created they will also be setup.
37 | '''
38 |
39 | c = tilekiln.load_config(config)
40 |
41 | with psycopg_pool.ConnectionPool(min_size=1, max_size=1, num_workers=1,
42 | check=psycopg_pool.ConnectionPool.check_connection,
43 | kwargs={"dbname": storage_dbname, "host": storage_host,
44 | "port": storage_port, "user": storage_username
45 | }) as pool:
46 | storage = Storage(pool)
47 | storage.create_schema()
48 | tileset = Tileset.from_config(storage, c)
49 | tileset.prepare_storage()
50 |
51 |
52 | @storage.command()
53 | @click.option('--config', type=click.Path(exists=True, dir_okay=False))
54 | @click.option('--storage-dbname')
55 | @click.option('--storage-host')
56 | @click.option('--storage-port', type=click.INT)
57 | @click.option('--storage-username')
58 | @click.option('--id', help='Override YAML config ID')
59 | def destroy(config: str,
60 | storage_dbname: str, storage_host: str, storage_port: int, storage_username: str,
61 | id: str) -> None:
62 | ''' Destroy storage for tiles'''
63 | if config is None and id is None:
64 | raise click.UsageError('''Missing one of '--id' or '--config' options''')
65 |
66 | # No id specified, so load the config for one. We know from above config is not none.
67 | c = None
68 | if id is None:
69 | c = tilekiln.load_config(config)
70 | id = c.id
71 |
72 | with psycopg_pool.ConnectionPool(min_size=1, max_size=1, num_workers=1,
73 | check=psycopg_pool.ConnectionPool.check_connection,
74 | kwargs={"dbname": storage_dbname, "host": storage_host,
75 | "port": storage_port, "user": storage_username
76 | }) as pool:
77 | storage = Storage(pool)
78 | storage.remove_tileset(id)
79 |
80 |
81 | @storage.command()
82 | @click.option('--config', type=click.Path(exists=True, dir_okay=False))
83 | @click.option('--storage-dbname')
84 | @click.option('--storage-host')
85 | @click.option('--storage-port', type=click.INT)
86 | @click.option('--storage-username')
87 | @click.option('--id', help='Override YAML config ID')
88 | @click.option('-z', '--zoom', required=True, type=click.INT)
89 | @click.option('-x', required=True, type=click.INT)
90 | @click.option('-y', required=True, type=click.INT)
91 | def inspect(config: str,
92 | storage_dbname: str, storage_host: str, storage_port: int, storage_username: str,
93 | id: str, zoom: int, x: int, y: int) -> None:
94 | ''' Inspect a tile in storage'''
95 | if config is None and id is None:
96 | raise click.UsageError('''Missing one of '--id' or '--config' options''')
97 |
98 | # No id specified, so load the config for one. We know from above config is not none.
99 | c = None
100 | if id is None:
101 | c = tilekiln.load_config(config)
102 | id = c.id
103 |
104 | with psycopg_pool.ConnectionPool(min_size=1, max_size=1, num_workers=1,
105 | check=psycopg_pool.ConnectionPool.check_connection,
106 | kwargs={"dbname": storage_dbname, "host": storage_host,
107 | "port": storage_port, "user": storage_username
108 | }) as conn:
109 | storage = Storage(conn)
110 | tile = Tile(zoom, x, y)
111 | mvt = storage.get_tile_details(id, tile)
112 | size = 0
113 | click.echo(f"Tile {zoom}/{x}/{y} in {id}")
114 | for layer, data in mvt.items():
115 | click.echo(f" {layer}: {data_info(data)}")
116 | if data is not None:
117 | size += len(data[0])
118 | click.echo(f"Total stored: {size}b")
119 |
120 |
121 | def data_info(data: tuple[bytes, datetime.datetime] | None):
122 | if data is None:
123 | return "undefined"
124 | if data[1] is None:
125 | return f"{len(data[0])}b timestamp invalidly null"
126 | return f"{len(data[0])}b {data[1].isoformat()}"
127 |
128 |
129 | @storage.command()
130 | @click.option('--config', type=click.Path(exists=True, dir_okay=False))
131 | @click.option('--storage-dbname')
132 | @click.option('--storage-host')
133 | @click.option('--storage-port')
134 | @click.option('--storage-username')
135 | @click.option('-z', '--zoom', type=click.INT, multiple=True)
136 | @click.option('--id', help='Override YAML config ID')
137 | def delete(config: str,
138 | storage_dbname: str, storage_host: str, storage_port: int, storage_username: str,
139 | zoom: tuple[int], id: str) -> None:
140 | '''Mass-delete tiles from a tileset
141 |
142 | Deletes tiles from a tileset, by zoom, or delete all zooms.
143 | '''
144 | if config is None and id is None:
145 | raise click.UsageError('''Missing one of '--id' or '--config' options''')
146 |
147 | # No id specified, so load the config for one. We know from above config is not none.
148 | c = None
149 | if id is None:
150 | c = tilekiln.load_config(config)
151 | id = c.id
152 |
153 | with psycopg_pool.ConnectionPool(min_size=1, max_size=1, num_workers=1,
154 | check=psycopg_pool.ConnectionPool.check_connection,
155 | kwargs={"dbname": storage_dbname, "host": storage_host,
156 | "port": storage_port, "user": storage_username
157 | }) as conn:
158 | storage = Storage(conn)
159 |
160 | if (len(zoom) == 0):
161 | storage.truncate_tables(id)
162 | else:
163 | storage.truncate_tables(id, zoom)
164 |
165 |
166 | @storage.command()
167 | @click.option('--config', type=click.Path(exists=True, dir_okay=False))
168 | @click.option('--storage-dbname')
169 | @click.option('--storage-host')
170 | @click.option('--storage-port', type=click.INT)
171 | @click.option('--storage-username')
172 | @click.option('--id', help='Override YAML config ID')
173 | def tiledelete(config: str,
174 | storage_dbname: str, storage_host: str, storage_port: int, storage_username: str,
175 | id: str) -> None:
176 | '''Delete specific tiles.
177 |
178 | A list of z/x/y tiles is read from stdin and those tiles are deleted from
179 | storage. The entire list is read before deletion starts.
180 | '''
181 | if config is None and id is None:
182 | raise click.UsageError('''Missing one of '--id' or '--config' options''')
183 |
184 | # No id specified, so load the config for one. We know from above config is not none.
185 | c = None
186 | if id is None:
187 | c = tilekiln.load_config(config)
188 | id = c.id
189 |
190 | with psycopg_pool.ConnectionPool(min_size=1, max_size=1, num_workers=1,
191 | check=psycopg_pool.ConnectionPool.check_connection,
192 | kwargs={"dbname": storage_dbname, "host": storage_host,
193 | "port": storage_port, "user": storage_username
194 | }) as pool:
195 | storage = Storage(pool)
196 |
197 | # TODO: This requires reading all of stdin before starting. This lets it display
198 | # how many tiles to delete but also means it has to read them all in before starting
199 | tiles = {Tile.from_string(t) for t in sys.stdin}
200 | click.echo(f"Deleting {len(tiles)} tiles")
201 | storage.delete_tiles(id, tiles)
202 |
203 |
204 | @storage.command()
205 | @click.option('--config', type=click.Path(exists=True, dir_okay=False))
206 | @click.option('--storage-dbname')
207 | @click.option('--storage-host')
208 | @click.option('--storage-port', type=click.INT)
209 | @click.option('--storage-username')
210 | @click.option('--id', help='Override YAML config ID')
211 | def layerdelete(config: str,
212 | storage_dbname: str, storage_host: str, storage_port: int, storage_username: str,
213 | id: str) -> None:
214 | '''Delete specific tiles.
215 |
216 | A list of z/x/y tiles is read from stdin and those tiles are deleted from
217 | storage. The entire list is read before deletion starts.
218 | '''
219 | if config is None and id is None:
220 | raise click.UsageError('''Missing one of '--id' or '--config' options''')
221 |
222 | # No id specified, so load the config for one. We know from above config is not none.
223 | c = None
224 | if id is None:
225 | c = tilekiln.load_config(config)
226 | id = c.id
227 |
228 | with psycopg_pool.ConnectionPool(min_size=1, max_size=1, num_workers=1,
229 | check=psycopg_pool.ConnectionPool.check_connection,
230 | kwargs={"dbname": storage_dbname, "host": storage_host,
231 | "port": storage_port, "user": storage_username
232 | }) as pool:
233 | storage = Storage(pool)
234 |
235 | tilelayers = layer_frominput(sys.stdin.read())
236 | click.echo(f"Deleting {len(tilelayers)} tiles")
237 | storage.delete_tilelayers(id, tilelayers)
238 |
--------------------------------------------------------------------------------
/tilekiln/server/__init__.py:
--------------------------------------------------------------------------------
1 | import json
2 | import os
3 |
4 | import psycopg_pool
5 | from fastapi import FastAPI, Response, HTTPException
6 |
7 | import tilekiln
8 | from tilekiln.config import Config
9 | from tilekiln.kiln import Kiln
10 | from tilekiln.tile import Tile
11 | from tilekiln.tileset import Tileset
12 | from tilekiln.storage import Storage
13 |
14 | HTTP_TIME = "%a, %d %b %Y %H:%M:%S GMT"
15 |
16 | # Constants for MVTs
17 | MVT_MIME_TYPE = "application/vnd.mapbox-vector-tile"
18 |
19 | # Constants for environment variable names
20 | # Passing around enviornment variables really is the best way to get this to fastapi
21 | TILEKILN_CONFIG = "TILEKILN_CONFIG"
22 | TILEKILN_URL = "TILEKILN_URL"
23 | TILEKILN_THREADS = "TILEKILN_THREADS"
24 |
25 | STANDARD_HEADERS: dict[str, str] = {"Access-Control-Allow-Origin": "*",
26 | "Access-Control-Allow-Methods": "GET, HEAD"}
27 |
28 | kiln: Kiln
29 | config: Config
30 | storage: Storage
31 | tilesets: dict[str, Tileset] = {}
32 |
33 | # Two types of server are defined - one for static tiles, the other for live generated tiles.
34 | server = FastAPI()
35 | live = FastAPI()
36 |
37 | # TODO: Set up middleware for CORS
38 |
39 |
40 | # TODO: Move elsewhere
41 | def change_tilejson_url(tilejson: str, baseurl: str) -> str:
42 | modified_tilejson = json.loads(tilejson)
43 | modified_tilejson["tiles"] = [baseurl + "/{z}/{x}/{y}.mvt"]
44 | return json.dumps(modified_tilejson)
45 |
46 |
47 | @server.on_event("startup")
48 | def load_server_config():
49 | '''Load the config for the server with static pre-rendered tiles'''
50 | global storage
51 | global tilesets
52 | # Because the DB connection variables are passed as standard PG* vars,
53 | # a plain ConnectionPool() will connect to the right DB
54 | conn = psycopg_pool.ConnectionPool(min_size=1, max_size=1, num_workers=1,
55 | check=psycopg_pool.ConnectionPool.check_connection)
56 | # TODO: Make readonly?
57 |
58 | storage = Storage(conn)
59 | for tileset in storage.get_tilesets():
60 | tilesets[tileset.id] = tileset
61 |
62 |
63 | @live.on_event("startup")
64 | def load_live_config():
65 | global config
66 | global storage
67 | global tilesets
68 | config = tilekiln.load_config(os.environ[TILEKILN_CONFIG])
69 |
70 | generate_args = {}
71 | if "GENERATE_PGDATABASE" in os.environ:
72 | generate_args["dbname"] = os.environ["GENERATE_PGDATABASE"]
73 | if "GENERATE_PGHOST" in os.environ:
74 | generate_args["host"] = os.environ["GENERATE_PGHOST"]
75 | if "GENERATE_PGPORT" in os.environ:
76 | generate_args["port"] = os.environ["GENERATE_PGPORT"]
77 | if "GENERATE_PGUSER" in os.environ:
78 | generate_args["username"] = os.environ["GENERATE_PGUSER"]
79 |
80 | storage_args = {}
81 | if "STORAGE_PGDATABASE" in os.environ:
82 | storage_args["dbname"] = os.environ["STORAGE_PGDATABASE"]
83 | if "STORAGE_PGHOST" in os.environ:
84 | storage_args["host"] = os.environ["STORAGE_PGHOST"]
85 | if "STORAGE_PGPORT" in os.environ:
86 | storage_args["port"] = os.environ["STORAGE_PGPORT"]
87 | if "STORAGE_PGUSER" in os.environ:
88 | storage_args["username"] = os.environ["STORAGE_PGUSER"]
89 |
90 | storage_pool = psycopg_pool.ConnectionPool(min_size=1, max_size=1, num_workers=1,
91 | check=psycopg_pool.ConnectionPool.check_connection,
92 | kwargs=storage_args)
93 |
94 | storage = Storage(storage_pool)
95 |
96 | # Storing the tileset in the dict allows some commonalities in code later
97 | tilesets[config.id] = Tileset.from_config(storage, config)
98 | generate_pool = psycopg_pool.ConnectionPool(min_size=1, max_size=1, num_workers=1,
99 | check=psycopg_pool.ConnectionPool.check_connection,
100 | kwargs=generate_args)
101 | global kiln
102 | kiln = Kiln(config, generate_pool)
103 |
104 |
105 | @server.head("/")
106 | @server.get("/")
107 | @live.head("/")
108 | @live.get("/")
109 | def root():
110 | raise HTTPException(status_code=404)
111 |
112 |
113 | @server.head("/favicon.ico")
114 | @server.get("/favicon.ico")
115 | @live.head("/favicon.ico")
116 | @live.get("/favicon.ico")
117 | def favicon():
118 | return Response("")
119 |
120 |
121 | @server.head("/{prefix}/tilejson.json")
122 | @server.get("/{prefix}/tilejson.json")
123 | @live.head("/{prefix}/tilejson.json")
124 | @live.get("/{prefix}/tilejson.json")
125 | def tilejson(prefix: str):
126 | global tilesets
127 | if prefix not in tilesets:
128 | raise HTTPException(status_code=404, detail=f'''Tileset {prefix} not found on server.''')
129 | return Response(content=change_tilejson_url(tilesets[prefix].tilejson,
130 | os.environ[TILEKILN_URL] + f"/{prefix}"),
131 | media_type="application/json",
132 | headers=STANDARD_HEADERS)
133 |
134 |
135 | @server.head("/{prefix}/{zoom}/{x}/{y}.mvt")
136 | @server.get("/{prefix}/{zoom}/{x}/{y}.mvt")
137 | def serve_tile(prefix: str, zoom: int, x: int, y: int):
138 | global tilesets
139 | if prefix not in tilesets:
140 | raise HTTPException(status_code=404, detail=f"Tileset {prefix} not found on server.")
141 |
142 | try:
143 | tile, generated = tilesets[prefix].get_tile(Tile(zoom, x, y))
144 | except tilekiln.errors.ZoomNotDefined:
145 | raise HTTPException(status_code=410,
146 | detail=f'''Tileset {zoom} not available for tileset {prefix}.''')
147 |
148 | response = b''
149 | for data in tile.values():
150 | if data is None:
151 | raise HTTPException(status_code=404,
152 | detail=f"Tile {prefix}/{zoom}/{x}/{y} not found in storage.")
153 | response += data
154 |
155 | # We use the generated timestamp on the assumption that a specific
156 | # x/y/z will not be generated twice in the same ms.
157 | headers: dict[str, str] = {}
158 | if generated is not None:
159 | headers = {"Last-Modified": generated.strftime(HTTP_TIME),
160 | "E-tag": generated.strftime("%s.%f")}
161 | return Response(response, media_type=MVT_MIME_TYPE,
162 | headers=STANDARD_HEADERS | headers)
163 |
164 |
165 | @live.head("/{prefix}/{zoom}/{x}/{y}.mvt")
166 | @live.get("/{prefix}/{zoom}/{x}/{y}.mvt")
167 | def live_serve_tile(prefix: str, zoom: int, x: int, y: int):
168 | global tilesets
169 | if prefix not in tilesets:
170 | raise HTTPException(status_code=404, detail=f"Tileset {prefix} not found on server.")
171 |
172 | # Attempt to serve a stored tile
173 | try:
174 | existing, generated = tilesets[prefix].get_tile(Tile(zoom, x, y))
175 | except tilekiln.errors.ZoomNotDefined:
176 | raise HTTPException(status_code=410,
177 | detail=f'''Tileset {zoom} not available for tileset {prefix}.''')
178 |
179 | response = b''
180 | missing = []
181 | for layer, data in existing.items():
182 | if data is None:
183 | missing.append(layer)
184 | else:
185 | response += data
186 |
187 | # Handle storage hits
188 | if missing == []:
189 | headers: dict[str, str] = {}
190 | if generated is not None:
191 | headers = {"Last-Modified": generated.strftime(HTTP_TIME),
192 | "E-tag": generated.strftime("%s.%f")}
193 | return Response(response, media_type=MVT_MIME_TYPE,
194 | headers=STANDARD_HEADERS | headers)
195 |
196 | # Storage miss, so generate a new tile
197 | # TODO: partially generate a new tile
198 | global kiln
199 | tile = Tile(zoom, x, y)
200 | new_layers = {layer: kiln.render_layer(layer, tile) for layer in missing}
201 | # TODO: Make async so tile is saved and response returned in parallel
202 | generated = tilesets[prefix].save_tile(tile, new_layers)
203 |
204 | mvt = b''.join(new_layers.values()) + b''.join([data for data in existing.values()
205 | if data is not None])
206 | if generated is not None:
207 | headers = {"Last-Modified": generated.strftime(HTTP_TIME),
208 | "E-tag": generated.strftime("%s.%f")}
209 | else:
210 | headers = {}
211 |
212 | return Response(mvt,
213 | media_type=MVT_MIME_TYPE,
214 | headers=STANDARD_HEADERS | headers)
215 |
--------------------------------------------------------------------------------
/tilekiln/storage.py:
--------------------------------------------------------------------------------
1 | import datetime
2 | import json
3 | import sys
4 | from collections.abc import Collection, Iterator, Sequence
5 | from typing import Optional
6 |
7 | import click
8 | import psycopg.rows
9 | import psycopg_pool
10 | from psycopg import sql
11 |
12 | import tilekiln.errors
13 |
14 | from tilekiln.metric import Metric
15 | from tilekiln.tile import Tile
16 | from tilekiln.tileset import Tileset
17 |
18 | METADATA_TABLE = "metadata"
19 | GENERATE_STATS_TABLE = "generate_stats"
20 | TILE_STATS_TABLE = "tile_stats"
21 |
22 | # Lower percentiles are typically not interesting, because generally the
23 | # smallest 50% of tiles are identical water tiles or something similarly
24 | # sparse. Where the data gets interesting is p95 and above.
25 | PERCENTILES = [0.0, 0.25, 0.50, 0.75, 0.90, 0.95, 0.99, 0.999, 1.0]
26 |
27 |
28 | class Storage:
29 | '''
30 | Storage is an object representing a tile storage, backed by a PostgreSQL database
31 |
32 | A Storage contains tiles and metadata about tilesets, and has functions to update
33 | tiles and metadata based on the ID
34 | '''
35 | def __init__(self, pool: psycopg_pool.ConnectionPool, schema: str = "tilekiln"):
36 | self.__pool = pool
37 | self.__schema = schema
38 |
39 | '''
40 | Methods that manipulate schema-related stuff and don't involve any tiles
41 | '''
42 | def create_schema(self) -> None:
43 | with self.__pool.connection() as conn:
44 | with conn.cursor() as cur:
45 | # Perform one-time setup using CREATE ... IF NOT EXISTS
46 | # This is safe to rerun multiple times
47 | cur.execute(f'''CREATE SCHEMA IF NOT EXISTS "{self.__schema}"''')
48 | self.__setup_stats(cur)
49 | self.__setup_metadata(cur)
50 | conn.commit()
51 |
52 | '''
53 | Methods for tilesets
54 | '''
55 | def create_tileset(self, id: str, layers: list[str],
56 | minzoom: int, maxzoom: int, tilejson: str) -> None:
57 | with self.__pool.connection() as conn:
58 | with conn.cursor() as cur:
59 | self.__set_metadata(cur, id, layers, minzoom, maxzoom, tilejson)
60 |
61 | self.__setup_tables(cur, id, layers, minzoom, maxzoom)
62 | conn.commit()
63 |
64 | def remove_tileset(self, id: str) -> None:
65 | with self.__pool.connection() as conn:
66 | with conn.cursor() as cur:
67 | cur.execute(f'''DELETE FROM "{self.__schema}"."{METADATA_TABLE}" WHERE id = %s''',
68 | (id,))
69 | cur.execute(f'''DROP TABLE "{self.__schema}"."{id}" CASCADE''')
70 | cur.execute(f'''DELETE FROM "{self.__schema}"."{TILE_STATS_TABLE}" WHERE id = %s''',
71 | (id,))
72 | conn.commit()
73 |
74 | def get_tilesets(self) -> Iterator[Tileset]:
75 | '''
76 | Gets all tilesets in the storage
77 | '''
78 |
79 | with self.__pool.connection() as conn:
80 | with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
81 | cur.execute(f'''SELECT id, layers, minzoom, maxzoom, tilejson
82 | FROM "{self.__schema}"."{METADATA_TABLE}"''')
83 | for record in cur:
84 | yield Tileset(self, record["id"], record["layers"],
85 | record["minzoom"], record["maxzoom"],
86 | json.dumps(record["tilejson"]))
87 |
88 | def get_tileset_ids(self) -> Iterator[str]:
89 | '''
90 | Get only the tileset IDs
91 | '''
92 |
93 | with self.__pool.connection() as conn:
94 | with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
95 | cur.execute(f'''SELECT id
96 | FROM "{self.__schema}"."{METADATA_TABLE}"''')
97 | for record in cur:
98 | yield record["id"]
99 |
100 | def get_tileset(self, id: str) -> Tileset:
101 | '''
102 | Fetch a specific tileset
103 | '''
104 |
105 | with self.__pool.connection() as conn:
106 | with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
107 | cur.execute(sql.SQL('''SELECT id, layers, minzoom, maxzoom, tilejson FROM {}.{}''')
108 | .format(sql.Identifier(self.__schema), sql.Identifier(METADATA_TABLE)) +
109 | sql.SQL('''WHERE id = %s'''), (id, ))
110 | result = cur.fetchone()
111 | if result is None:
112 | raise tilekiln.errors.TilesetMissing
113 |
114 | return Tileset(self, result["id"], result["layers"],
115 | result["minzoom"], result["maxzoom"],
116 | json.dumps(result["tilejson"]))
117 |
118 | def get_layer_ids(self, id: str) -> list[str]:
119 | '''Get layers of a specific tileset
120 | '''
121 | with self.__pool.connection() as conn:
122 | with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
123 | cur.execute(sql.SQL('''SELECT layers FROM {}.{}''')
124 | .format(sql.Identifier(self.__schema), sql.Identifier(METADATA_TABLE)) +
125 | sql.SQL('''WHERE id = %s'''), (id, ))
126 | result = cur.fetchone()
127 | if result is None:
128 | raise tilekiln.errors.TilesetMissing
129 | return result["layers"]
130 |
131 | ''' Methods for metrics'''
132 | def metrics(self) -> Collection[Metric]:
133 | with self.__pool.connection() as conn:
134 | with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
135 | cur.execute(f'''SELECT id, zoom, num_tiles, size, percentiles
136 | FROM "{self.__schema}"."{TILE_STATS_TABLE}"''')
137 | return [Metric(**record) for record in cur]
138 |
139 | def update_metrics(self) -> None:
140 | tilesets = self.get_tilesets()
141 | with self.__pool.connection() as conn:
142 | with conn.cursor() as cur:
143 | for tileset in tilesets:
144 | self.__update_tileset_metrics(cur, tileset)
145 | conn.commit()
146 |
147 | '''Methods that set/get metadata'''
148 | def set_metadata(self, id: str, layers: list[str],
149 | minzoom: int, maxzoom: int, tilejson: str) -> None:
150 | '''
151 | Saves metadata into storage
152 |
153 | This just wraps __set_metadata, which requires a cursor
154 | '''
155 | with self.__pool.connection() as conn:
156 | with conn.cursor() as cur:
157 | self.__set_metadata(cur, id, layers, minzoom, maxzoom, tilejson)
158 | conn.commit()
159 |
160 | # TODO: Should the various get_* functions be separate? The query has to fetch from the
161 | # DB each time, but only tilejson needs URL. Not an urgent issue.
162 | def get_tilejson(self, id: str, url: str) -> str:
163 | '''Gets the tilejson for a layer from storage.'''
164 | with self.__pool.connection() as conn:
165 | with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
166 | cur.execute(f'''SELECT tilejson
167 | FROM "{self.__schema}"."{METADATA_TABLE}"
168 | WHERE id = %s''', (id,))
169 | result = cur.fetchone()
170 | if result is None:
171 | # TODO: raise exception and handle it at the calling level
172 | click.echo(f"Failed to retrieve tilejson for id {id}, "
173 | f"does it exist in storage DB?",
174 | err=True)
175 | sys.exit(1)
176 | tilejson = result["tilejson"]
177 | tilejson["tiles"] = [f"{url}" + "/{z}/{x}/{y}.mvt"]
178 | return json.dumps(tilejson)
179 |
180 | # TODO: Get rid of get_minzoom/maxzoom functions and use get_tileset
181 | def get_minzoom(self, id: str):
182 | '''Gets the minzoom for a layer from storage.'''
183 | with self.__pool.connection() as conn:
184 | with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
185 | cur.execute(f'''SELECT minzoom
186 | FROM "{self.__schema}"."{METADATA_TABLE}"
187 | WHERE id = %s''', (id,))
188 | result = cur.fetchone()
189 | if result is None:
190 | # TODO: raise exception and handle it at the calling level
191 | click.echo(f"Failed to retrieve minzoom for id {id}, "
192 | f"does it exist in storage DB?",
193 | err=True)
194 | sys.exit(1)
195 | return result["minzoom"]
196 |
197 | def get_maxzoom(self, id):
198 | '''Gets the minzoom for a layer from storage.'''
199 | with self.__pool.connection() as conn:
200 | with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
201 | cur.execute(f'''SELECT maxzoom
202 | FROM "{self.__schema}"."{METADATA_TABLE}"
203 | WHERE id = %s''', (id,))
204 | result = cur.fetchone()
205 | if result is None:
206 | # TODO: raise exception and handle it at the calling level
207 | click.echo(f"Failed to retrieve minzoom for id {id}, "
208 | "does it exist in storage DB?", err=True)
209 | sys.exit(1)
210 | return result["maxzoom"]
211 |
212 | '''
213 | Methods that involve saving, fetching, and deleting tiles
214 | '''
215 | def delete_tiles(self, id: str, tiles: set[Tile]):
216 | with self.__pool.connection() as conn:
217 | with conn.cursor() as cur:
218 | for tile in tiles:
219 | self.__delete_tile(cur, id, tile)
220 | conn.commit()
221 |
222 | def delete_tilelayers(self, id: str, tilelayers: dict[Tile, set[str]]):
223 | allowed_layers = self.get_layer_ids(id)
224 | with self.__pool.connection() as conn:
225 | with conn.cursor() as cur:
226 | for tile, layers in tilelayers.items():
227 | if layers.difference(allowed_layers) != set():
228 | raise tilekiln.errors.LayerNotDefined(
229 | f"Layers{layers.difference(allowed_layers)} not defined for {id}")
230 | self.__delete_tilelayer(cur, id, tile, layers)
231 | conn.commit()
232 |
233 | def truncate_tables(self, id: str, zooms: Optional[Sequence[int]] = None):
234 | if zooms is None:
235 | zooms = range(self.get_minzoom(id), self.get_maxzoom(id)+1)
236 | with self.__pool.connection() as conn:
237 | with conn.cursor() as cur:
238 | for zoom in zooms:
239 | self.__truncate_table(cur, id, zoom)
240 | conn.commit()
241 |
242 | def get_tile(self, id: str, tile: Tile) -> tuple[dict[str, bytes | None],
243 | datetime.datetime | None]:
244 | tileset = self.get_tileset(id)
245 | if tile.zoom > tileset.maxzoom or tile.zoom < tileset.minzoom:
246 | raise tilekiln.errors.ZoomNotDefined
247 | with self.__pool.connection() as conn:
248 | with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
249 | query = (sql.SQL('SELECT GREATEST(')
250 | + _generated_columns(tileset.layers)
251 | + sql.SQL(') AS generated,')
252 | + _data_columns(tileset.layers)
253 | + sql.SQL('FROM {}.{}').format(sql.Identifier(self.__schema),
254 | sql.Identifier(id))
255 | + sql.SQL('WHERE zoom = %s AND x = %s AND y = %s'))
256 | cur.execute(query, (tile.zoom, tile.x, tile.y), binary=True)
257 | result = cur.fetchone()
258 | if result is None:
259 | return {layer: None for layer in tileset.layers}, None
260 | return {layer: result[f"{layer}_data"]
261 | for layer in tileset.layers}, result["generated"]
262 |
263 | def get_tile_details(self, id: str, tile: Tile) -> dict[str,
264 | tuple[bytes, datetime.datetime] | None]:
265 |
266 | details: dict[str, tuple[bytes, datetime.datetime] | None] = {}
267 |
268 | tileset = self.get_tileset(id)
269 | if tile.zoom > tileset.maxzoom or tile.zoom < tileset.minzoom:
270 | raise tilekiln.errors.ZoomNotDefined
271 | with self.__pool.connection() as conn:
272 | with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
273 | query = (sql.SQL('SELECT ')
274 | + _generated_columns(tileset.layers)
275 | + sql.SQL(',')
276 | + _data_columns(tileset.layers)
277 | + sql.SQL('FROM {}.{}').format(sql.Identifier(self.__schema),
278 | sql.Identifier(id))
279 | + sql.SQL('WHERE zoom = %s AND x = %s AND y = %s'))
280 | cur.execute(query, (tile.zoom, tile.x, tile.y), binary=True)
281 | result = cur.fetchone()
282 | for layer in tileset.layers:
283 | if result is not None and result[f"{layer}_data"] is not None:
284 | details[layer] = (result[f"{layer}_data"], result[f"{layer}_generated"])
285 | else:
286 | details[layer] = None
287 | return details
288 |
289 | def save_tile(self, id: str, tile: Tile,
290 | layers: dict[str, bytes], render_time=0) -> datetime.datetime | None:
291 | tileset = self.get_tileset(id)
292 | if tile.zoom > tileset.maxzoom or tile.zoom < tileset.minzoom:
293 | raise tilekiln.errors.ZoomNotDefined
294 | if set(layers.keys()) - set(tileset.layers):
295 | raise tilekiln.errors.Error("Rendered tile contains layers not known to storage")
296 | tablename = f"{id}_z{tile.zoom}"
297 |
298 | with self.__pool.connection() as conn:
299 | with conn.cursor(row_factory=psycopg.rows.dict_row) as cur:
300 | # TODO: This statement unconditionally writes the row even if it's unchanged. It
301 | # shouldn't. Adding WHERE tile != EXCLUDED.tile would help, but then it would
302 | # return zero rows if the contents are the same. The method here instead results
303 | # in extra writes but does preserve the datetime.
304 |
305 | # The layers used are the incoming tile layers to allow for partial writes
306 |
307 | # Only the layers present in the new tile are
308 | data_upsert = [sql.SQL("{} = EXCLUDED.{}").format(sql.Identifier(f"{layer}_data"),
309 | sql.Identifier(f"{layer}_data"))
310 | for layer in layers]
311 | time_upsert = [sql.SQL("{generated} = CASE WHEN store.{data} IS "
312 | "DISTINCT FROM EXCLUDED.{data} THEN statement_timestamp() "
313 | # It's possible the timestamp is invalidly null,
314 | # so coalesce it with current timestamp
315 | "ELSE COALESCE(store.{generated}, statement_timestamp()) "
316 | "END")
317 | .format(generated=sql.Identifier(f"{layer}_generated"),
318 | data=sql.Identifier(f"{layer}_data"))
319 | for layer in layers]
320 |
321 | # arguments to the query
322 | data_idents = [sql.Placeholder(layer) for layer in layers]
323 |
324 | q = (sql.SQL("INSERT INTO {}.{} AS store\n").format(sql.Identifier(self.__schema),
325 | sql.Identifier(tablename))
326 | + sql.SQL("(zoom, x, y, ") + _data_columns(layers) + sql.SQL(", ")
327 | + _generated_columns(layers) + sql.SQL(")\n")
328 | + sql.SQL("VALUES ({}, {}, {}, ").format(sql.Literal(tile.zoom),
329 | sql.Literal(tile.x),
330 | sql.Literal(tile.y))
331 | + sql.SQL(", ").join(data_idents) + sql.SQL(",\n")
332 | + sql.SQL(", ").join([sql.SQL("statement_timestamp()") for _ in layers])
333 | + sql.SQL(")\n")
334 | + sql.SQL("ON CONFLICT (zoom, x, y)\n")
335 | + sql.SQL("DO UPDATE SET ")
336 | + sql.SQL(", ").join([*data_upsert, *time_upsert])
337 | # This has to operate on tileset.layers because we want the greatest date
338 | # of *any* layer, not just the layers in the incoming tile
339 | + sql.SQL("\nRETURNING GREATEST(") + _generated_columns(tileset.layers)
340 | + sql.SQL(") AS generated"))
341 |
342 | cur.execute(q, layers)
343 |
344 | result = cur.fetchone()
345 | if result is None:
346 | return None
347 | return result["generated"]
348 |
349 | def __setup_metadata(self, cur) -> None:
350 | ''' Create the metadata table in storage. This is safe to rerun
351 | '''
352 | # TODO: Updating metadata table schema??
353 | # Probably can only be done on a major version upgrade
354 |
355 | cur.execute(f'''CREATE TABLE IF NOT EXISTS "{self.__schema}"."{METADATA_TABLE}" (\n'''
356 | '''id text PRIMARY KEY,\n'''
357 | '''active boolean NOT NULL DEFAULT TRUE,\n'''
358 | '''layers text[],\n'''
359 | '''minzoom smallint NOT NULL,\n'''
360 | '''maxzoom smallint NOT NULL,\n'''
361 | '''tilejson jsonb NOT NULL)''')
362 |
363 | def __set_metadata(self, cur, id: str, layers: list[str], minzoom, maxzoom, tilejson):
364 | '''
365 | Sets metadata using a cursor
366 |
367 | This is separate from set_metadata because sometimes it needs
368 | calling within a transaction
369 | '''
370 |
371 | query = (sql.SQL("INSERT INTO {}.{}\n").format(sql.Identifier(self.__schema),
372 | sql.Identifier(METADATA_TABLE))
373 | + sql.SQL("(id, minzoom, maxzoom, layers, tilejson)\n")
374 | + sql.SQL("VALUES (%s, %s, %s, %s, %s)\n")
375 | + sql.SQL("ON CONFLICT (id)\n")
376 | + sql.SQL("DO UPDATE SET minzoom = EXCLUDED.minzoom,\n")
377 | + sql.SQL("maxzoom = EXCLUDED.maxzoom,\n")
378 | + sql.SQL("tilejson = EXCLUDED.tilejson"))
379 | cur.execute(query, (id, minzoom, maxzoom, layers, tilejson))
380 |
381 | def __setup_stats(self, cur) -> None:
382 | '''Create the stats tables.
383 |
384 | One table has tile generation stats, the other has tile storage stats.
385 | '''
386 | # Because we're just storing counters for prometheus here and unlogged table is fine.
387 | # Periodic resets are okay.
388 | # It's necessary to store this in-db since we might call tilerender more than once
389 | # in a polling interval.
390 | # TODO: Use this table
391 | cur.execute(f'''CREATE UNLOGGED TABLE IF NOT EXISTS
392 | "{self.__schema}"."{GENERATE_STATS_TABLE}" (
393 | id text,
394 | zoom smallint,
395 | num_rendered integer DEFAULT 0,
396 | time_rendered interval DEFAULT '0',
397 | PRIMARY KEY (id, zoom)
398 | )
399 | ''')
400 |
401 | # This caches information on the number of tiles. Prometheus can be called every 15 seconds
402 | # and doing a sequential scan that often is a bad idea
403 | cur.execute(f'''CREATE TABLE IF NOT EXISTS "{self.__schema}"."{TILE_STATS_TABLE}" (
404 | id text,
405 | zoom smallint,
406 | num_tiles integer NOT NULL,
407 | size bigint NOT NULL,
408 | percentiles double precision[][] NOT NULL,
409 | PRIMARY KEY (id, zoom),
410 | CHECK (array_length(percentiles, 1) = 2)
411 | )
412 | ''')
413 |
414 | def __update_tileset_metrics(self, cur, tileset: Tileset) -> None:
415 | id = tileset.id
416 | minzoom = tileset.minzoom
417 | maxzoom = tileset.maxzoom
418 | for zoom in range(minzoom, maxzoom+1):
419 | # This SQL statement needs to handle the case of an empty table.
420 | # Except for COUNT(*) the aggregate functions return NULL for
421 | # no rows, which is a problem. One option would be to save
422 | # {{}, {}} as the array but 2-d empty arrays don't really work
423 | # in PostgreSQL. Instead, we return 0 for all metrics.
424 | #
425 | # We set jit to ON as it is faster when the tables are large, but
426 | # jit is commonly disabled on tile rendering servers because it
427 | # slows down rendering queries.
428 | # TODO: Consider if it would be better to completely skip the row
429 | # and emit no metric.
430 | cur.execute('SET LOCAL jit TO ON;')
431 |
432 | length = sql.SQL("+").join([sql.SQL("length({})")
433 | .format(sql.Identifier(f"{layer}_data"))
434 | for layer in tileset.layers])
435 |
436 | query = (sql.SQL("INSERT INTO {}.{}\n").format(sql.Identifier(self.__schema),
437 | sql.Identifier(TILE_STATS_TABLE))
438 | + sql.SQL("SELECT %(id)s AS id, %(zoom)s AS zoom,")
439 | + sql.SQL("COUNT(*) AS num_tiles,\n"
440 | + "COALESCE (SUM({}), 0) AS size,\n").format(length)
441 |
442 | + sql.SQL("ARRAY[%(percentile)s, "
443 | + "COALESCE(PERCENTILE_CONT(%(percentile)s::double precision[])")
444 | + sql.SQL("WITHIN GROUP (ORDER BY {}),\n").format(length)
445 | + sql.SQL("array_fill(0, ARRAY[array_length(%(percentile)s, 1)]))] "
446 | + "AS percentiles\n").format(length, length)
447 | + sql.SQL("FROM {}.{}").format(sql.Identifier(self.__schema),
448 | sql.Identifier(f"{id}_z{zoom}"))
449 | + sql.SQL("ON CONFLICT (id, zoom)\n"
450 | + "DO UPDATE SET num_tiles = EXCLUDED.num_tiles,\n"
451 | + "size = EXCLUDED.size,\n"
452 | + "percentiles = EXCLUDED.percentiles;"))
453 |
454 | cur.execute(query, {'id': id, 'zoom': zoom, 'percentile': PERCENTILES})
455 |
456 | def __setup_tables(self, cur, id: str, layers: list[str],
457 | minzoom: int, maxzoom: int) -> None:
458 | '''Create the tile storage tables
459 |
460 | This creates the tile storage tables. It intentionally
461 | does not try to overwrite existing tables.
462 | '''
463 |
464 | columns = [sql.SQL('zoom smallint CHECK (zoom >= {} AND zoom <= {})')
465 | .format(sql.Literal(minzoom), sql.Literal(maxzoom)),
466 | sql.SQL('x int CHECK (x >= 0 AND x < 1 << zoom)'),
467 | sql.SQL('y int CHECK (y >= 0 AND y < 1 << zoom)')]
468 |
469 | columns += [sql.SQL("{} timestamptz")
470 | .format(sql.Identifier(f'{layer}_generated'))
471 | for layer in layers]
472 | columns += [sql.SQL("{} bytea").format(sql.Identifier(f'{layer}_data'))
473 | for layer in layers]
474 | columns += [sql.SQL("PRIMARY KEY (zoom, x, y)")]
475 |
476 | query = (sql.SQL('''CREATE TABLE {}.{} (\n''').format(sql.Identifier(self.__schema),
477 | sql.Identifier(id))
478 | + sql.SQL(',\n').join(columns)
479 | + sql.SQL(''') PARTITION BY LIST (zoom)'''))
480 |
481 | cur.execute(query)
482 | for zoom in range(minzoom, maxzoom+1):
483 | tablename = f"{id}_z{zoom}"
484 | query = (sql.SQL('''CREATE TABLE {}.{}\n''').format(sql.Identifier(self.__schema),
485 | sql.Identifier(tablename))
486 | + sql.SQL('''PARTITION OF {}.{}\n''').format(sql.Identifier(self.__schema),
487 | sql.Identifier(id))
488 | + sql.SQL('''FOR VALUES IN ({})''').format(sql.Literal(zoom)))
489 |
490 | cur.execute(query)
491 |
492 | def __truncate_table(self, cur, id: str, zoom: int) -> None:
493 | '''Remove every tile from a particular tileset and zoom'''
494 | tablename = f"{id}_z{zoom}"
495 | cur.execute(f'''TRUNCATE TABLE "{self.__schema}"."{tablename}"''')
496 |
497 | def __delete_tile(self, cur, id: str, tile: Tile):
498 | '''Delete an individual tile
499 |
500 | How this is implemented is not ideal for long lists of tiles
501 | to delete, but generally a long list is an entire zoom or a box.
502 |
503 | In the former case it is implemented as __truncate_table, and
504 | the latter case is not implemented but would take min/max x/y.
505 | '''
506 | cur.execute(f'''DELETE FROM "{self.__schema}"."{id}"
507 | WHERE zoom = %s AND x = %s AND y = %s''',
508 | (tile.zoom, tile.x, tile.y))
509 |
510 | def __delete_tilelayer(self, cur, id: str, tile: Tile, layers: set[str]):
511 | '''Delete specific layers from a tile
512 | '''
513 | tablename = f"{id}_z{tile.zoom}"
514 | data = sql.SQL(', ').join([sql.SQL("{} = NULL").format(sql.Identifier(f"{layer}_data"))
515 | for layer in layers])
516 | time = sql.SQL(', ').join([sql.SQL("{} = NULL").format(sql.Identifier(f"{layer}_generated"))
517 | for layer in layers])
518 | cur.execute(sql.SQL('''UPDATE {}.{}\n''').format(sql.Identifier(self.__schema),
519 | sql.Identifier(tablename))
520 | + sql.SQL('''SET ''') + data + sql.SQL(', ') + time
521 | + sql.SQL('''\nWHERE x = %s AND y = %s'''), (tile.x, tile.y))
522 |
523 |
524 | def _data_columns(layers) -> sql.Composable:
525 | return sql.SQL(', ').join([sql.Identifier(f"{layer}_data")
526 | for layer in layers])
527 |
528 |
529 | def _generated_columns(layers) -> sql.Composable:
530 | return sql.SQL(', ').join([sql.Identifier(f"{layer}_generated")
531 | for layer in layers])
532 |
--------------------------------------------------------------------------------
/tilekiln/tile.py:
--------------------------------------------------------------------------------
1 | import pmtiles.tile # type: ignore
2 |
3 |
4 | class Tile:
5 | __slots__ = ("tileid")
6 |
7 | def __init__(self, zoom: int, x: int, y: int):
8 | '''Creates a tile object, with x, y, and zoom
9 | '''
10 | self.tileid = pmtiles.tile.zxy_to_tileid(zoom, x, y)
11 |
12 | def __eq__(self, other):
13 | return isinstance(other, self.__class__) and self.tileid == other.tileid
14 |
15 | def __hash__(self):
16 | return self.tileid
17 |
18 | @property
19 | def zxy(self):
20 | return pmtiles.tile.tileid_to_zxy(self.tileid)
21 |
22 | @property
23 | def zoom(self):
24 | return self.zxy[0]
25 |
26 | @property
27 | def x(self):
28 | return self.zxy[1]
29 |
30 | @property
31 | def y(self):
32 | return self.zxy[2]
33 |
34 | def __repr__(self) -> str:
35 | return f"Tile({self.zoom},{self.x},{self.y})"
36 |
37 | @classmethod
38 | def from_string(cls, tile: str):
39 | try:
40 | fragments = tile.split("/")
41 | if len(fragments) != 3:
42 | raise ValueError(f"Unable to parse tile from: {tile}")
43 | return cls(int(fragments[0]), int(fragments[1]), int(fragments[2]))
44 | except (ValueError, IndexError):
45 | raise ValueError(f"Unable to parse tile from: {tile}")
46 |
47 | @classmethod
48 | def from_tileid(cls, tileid: int):
49 | # TODO: This converts id to xyz to id, there should be a way with less calls
50 | (zoom, x, y) = pmtiles.tile.tileid_to_zxy(tileid)
51 | return cls(zoom, x, y)
52 |
53 | def bbox(self, buffer) -> str:
54 | '''Returns the bounding box for a tile
55 | '''
56 | return f'''ST_TileEnvelope({self.zoom}, {self.x}, {self.y}, margin=>{buffer})'''
57 |
58 |
59 | def layer_frominput(input: str) -> dict[Tile, set[str]]:
60 | '''Generates a list of tile layers from string
61 | '''
62 |
63 | layers: dict[Tile, set[str]] = {}
64 | for line in input.split("\n"):
65 | if line.strip() == "":
66 | continue
67 | try:
68 | tiletext, layer = line.split(",")
69 | except ValueError:
70 | raise ValueError(f"Unable to parse layer from: {line}")
71 | tile = Tile.from_string(tiletext)
72 | if tile in layers:
73 | layers[tile].add(layer)
74 | else:
75 | layers[tile] = {layer}
76 |
77 | return layers
78 |
--------------------------------------------------------------------------------
/tilekiln/tilerange.py:
--------------------------------------------------------------------------------
1 | from tilekiln.tile import Tile
2 |
3 |
4 | class Tilerange():
5 | def __init__(self, minz, maxz):
6 | self.minid = Tile(minz, 0, 0).tileid
7 | self.maxid = Tile(maxz + 1, 0, 0).tileid
8 |
9 | def __iter__(self):
10 | for id in range(self.minid, self.maxid):
11 | yield Tile.from_tileid(id)
12 |
13 | def __len__(self):
14 | return self.maxid - self.minid
15 |
16 | def __contains__(self, value):
17 | raise NotImplementedError
18 |
--------------------------------------------------------------------------------
/tilekiln/tileset.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 | from dataclasses import dataclass
3 | import datetime
4 |
5 | import tilekiln.errors
6 | from tilekiln.config import Config
7 | from tilekiln.tile import Tile
8 |
9 | from typing import TYPE_CHECKING
10 | if TYPE_CHECKING:
11 | from tilekiln.storage import Storage
12 |
13 |
14 | @dataclass
15 | class Tileset:
16 | '''A set of tiles in storage
17 |
18 | A tileset must always have the associated DB entries with tilejson/etc
19 | TODO: How to handle populating the DB
20 | '''
21 |
22 | storage: Storage
23 | id: str
24 | layers: list[str]
25 | minzoom: int
26 | maxzoom: int
27 | tilejson: str
28 |
29 | @classmethod
30 | def from_config(cls, storage: Storage, config: Config):
31 | '''Create a tileset from a Storage and Config'''
32 | return cls(storage, config.id, config.layer_names(), config.minzoom, config.maxzoom,
33 | config.tilejson('REPLACED_BY_SERVER'))
34 |
35 | # todo: this should really be in storage
36 | @classmethod
37 | def from_id(cls, storage: Storage, id: str) -> Tileset:
38 | '''
39 | Create a tileset from a Storage and id
40 |
41 | This pulls the metadata from the storage
42 | '''
43 |
44 | layers = [layer for layer in storage.get_layer_ids(id)]
45 | minzoom = storage.get_minzoom(id)
46 | maxzoom = storage.get_maxzoom(id)
47 | tilejson = storage.get_tilejson(id, 'REPLACED_BY_SERVER')
48 | return cls(storage, id, layers, minzoom, maxzoom, tilejson)
49 |
50 | def prepare_storage(self) -> None:
51 | self.storage.create_tileset(self.id, self.layers, self.minzoom, self.maxzoom,
52 | self.tilejson)
53 |
54 | def update_storage_metadata(self) -> None:
55 | '''Sets the metadata in storage'''
56 | self.storage.set_metadata(self.id, self.layers, self.minzoom, self.maxzoom,
57 | self.tilejson)
58 |
59 | def get_tile(self, tile: Tile) -> tuple[dict[str, bytes | None], datetime.datetime | None]:
60 | if tile.zoom < self.minzoom or tile.zoom > self.maxzoom:
61 | raise tilekiln.errors.ZoomNotDefined
62 | return self.storage.get_tile(self.id, tile)
63 |
64 | def save_tile(self, tile: Tile, layers: dict[str, bytes]) -> datetime.datetime | None:
65 | if tile.zoom < self.minzoom or tile.zoom > self.maxzoom:
66 | raise tilekiln.errors.ZoomNotDefined
67 | return self.storage.save_tile(self.id, tile, layers)
68 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | [tox]
2 | envlist = py
3 |
4 | [flake8]
5 | max-line-length = 100
6 |
7 | [testenv]
8 | deps = pytest
9 | commands = pytest {posargs}
10 |
--------------------------------------------------------------------------------