+
+#### MapConfig
+
+For this map, the multiple layers, order, and stylings are defined by the MapConfig.
+
+```javascript
+{
+ "version": "1.3.0",
+ "layers": [
+ {
+ "type": "http",
+ "options": {
+ "urlTemplate": "http://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}.png",
+ "subdomains": [
+ "a",
+ "b",
+ "c"
+ ]
+ }
+ },
+ {
+ "type": "mapnik",
+ "options": {
+ "sql": "select null::geometry the_geom_webmercator",
+ "cartocss": "#layer {\n\tpolygon-fill: #FF3300;\n\tpolygon-opacity: 0;\n\tline-color: #333;\n\tline-width: 0;\n\tline-opacity: 0;\n}",
+ "cartocss_version": "2.2.0"
+ }
+ },
+ {
+ "type": "cartodb",
+ "options": {
+ "sql": "select * from park",
+ "cartocss": "/** simple visualization */\n\n#park{\n polygon-fill: #229A00;\n polygon-opacity: 0.7;\n line-color: #FFF;\n line-width: 0;\n line-opacity: 1;\n}",
+ "cartocss_version": "2.1.1"
+ }
+ },
+ {
+ "type": "cartodb",
+ "options": {
+ "sql": "select * from residential_zoning_2009",
+ "cartocss": "/** simple visualization */\n\n#residential_zoning_2009{\n polygon-fill: #c7eae5;\n polygon-opacity: 1;\n line-color: #FFF;\n line-width: 0.2;\n line-opacity: 0.5;\n}",
+ "cartocss_version": "2.1.1"
+ }
+ },
+ {
+ "type": "cartodb",
+ "options": {
+ "sql": "select * from nycha_developments_july2011",
+ "cartocss": "/** simple visualization */\n\n#nycha_developments_july2011{\n polygon-fill: #ef3b2c;\n polygon-opacity: 0.7;\n line-color: #FFF;\n line-width: 0;\n line-opacity: 1;\n}",
+ "cartocss_version": "2.1.1"
+ }
+ }
+ ]
+}
+```
diff --git a/docs/guides/06-tile-aggregation.md b/docs/guides/06-tile-aggregation.md
new file mode 100644
index 00000000..ef615b2e
--- /dev/null
+++ b/docs/guides/06-tile-aggregation.md
@@ -0,0 +1,187 @@
+## Tile Aggregation
+
+To be able to represent a large amount of data (say, hundred of thousands to millions of points) in a tile. This can be useful both for raster tiles (where the aggregation reduces the number of features to be rendered) and vector tiles (the tile contais less features).
+
+Aggregation is available only for point geometries. During aggregation the points are grouped using a grid; all the points laying in the same cell of the grid are summarized in a single aggregated result point.
+ - The position of the aggregated point is controlled by the `placement` parameter.
+ - The aggregated rows always contain at least a column, named `_cdb_feature_count`, which contains the number of the original points that the aggregated point represents.
+
+#### Special default aggregation
+
+When no placement or columns are specified a special default aggregation is performed.
+
+This special mode performs only spatial aggregation (using a grid defined by the requested tile and the resolution, parameter, as all the other cases), and returns a _random_ record from each group (grid cell) with all its columns and an additional `_cdb_features_count` with the number of features in the group.
+
+Regarding the randomness of the sample: currently we use the row with the minimum `cartodb_id` value in each group.
+
+The rationale behind having this special aggregation with all the original columns is to provide a mostly transparent way to handle large datasets without having to provide special map configurations for those cases (i.e. preserving the logic used to produce the maps with smaller datasets). [Overviews have been used so far with this intent](https://carto.com/docs/tips-and-tricks/back-end-data-performance/), but they are inflexible.
+
+#### User defined aggregations
+
+When either a explicit placement or columns are requested we no longer use the special, query; we use one determined by the placement (which will default to "centroid"), and it will have as columns only the aggregated columns specified, in addition to `_cdb_features_count`, which is always present.
+
+We might decide in the future to allow sampling column values for any of the different placement modes.
+
+#### Behaviour for raster and vector tiles
+
+The vector tiles from a vector-only map will be aggregated by default.
+However, Raster tiles (or vector tiles from a map which defines CartoCSS styles) will be aggregated only upon request.
+
+Aggregation that would otherwise occur can be disabled by passing an `aggregation=false` parameter to the map instantiation HTTP call.
+
+To control how aggregation is performed, an aggregation option can be added to the layer:
+
+```json
+{
+ "layers": [
+ {
+ "options": {
+ "sql": "SELECT * FROM data",
+ "aggregation": {
+ "placement": "centroid",
+ "columns": {
+ "value": {
+ "aggregate_function": "sum",
+ "aggregated_column": "value"
+ }
+ }
+ }
+ }
+ }
+ ]
+}
+```
+
+Even if aggregation is explicitly requested it may not be activated, e.g., if the geometries are not points
+or the whole dataset is too small. The map instantiation response contains metadata that informs if any particular
+layer will be aggregated when tiles are requested, both for vector (mvt) and raster (png) tiles.
+
+```json
+{
+ "layergroupid": "7b97b6e76590fef889b63edd2efb1c79:1513608333045",
+ "metadata": {
+ "layers": [
+ {
+ "type": "mapnik",
+ "id": "layer0",
+ "meta": {
+ "stats": {
+ "estimatedFeatureCount": 6232136
+ },
+ "aggregation": {
+ "png": true,
+ "mvt": true
+ }
+ }
+ }
+ ]
+ }
+}
+```
+
+### Aggregation parameters
+
+The aggregation parameters for a layer are defined inside an `aggregation` option of the layer:
+
+```json
+{
+ "layers": [
+ {
+ "options": {
+ "sql": "SELECT * FROM data",
+ "aggregation": {"...": "..."}
+ }
+ }
+ ]
+}
+```
+
+#### `placement`
+
+Determines the kind of aggregated geometry generated:
+
+##### `point-sample`
+
+This is the default placement. It will place the aggregated point at a random sample of the grouped points,
+like the default aggregation does. No other attribute is sampled, though, the point will contain the aggregated attributes determined by the `columns` parameter.
+
+##### `point-grid`
+
+Generates points at the center of the aggregation grid cells (squares).
+
+##### `centroid`
+
+Generates points with the averaged coordinated of the grouped points (i.e. the points inside each grid cell).
+
+#### `columns`
+
+The aggregated attributes defined by `columns` are computed by a applying an _aggregate function_ to all the points in each group.
+Valid aggregate functions are `sum`, `avg` (average), `min` (minimum), `max` (maximum) and `mode` (the most frequent value in the group).
+The values to be aggregated are defined by the _aggregated column_ of the source data. The column keys define the name of the resulting column in the aggregated dataset.
+
+For example here we define three aggregate attributes named `total`, `max_price` and `price` which are all computed with the same column, `price`,
+of the original dataset applying three different aggregate functions.
+
+```json
+{
+ "columns": {
+ "total": { "aggregate_function": "sum", "aggregated_column": "price" },
+ "max_price": { "aggregate_function": "max", "aggregated_column": "price" },
+ "price": { "aggregate_function": "avg", "aggregated_column": "price" }
+ }
+}
+```
+
+> Note that you can use the original column names as names of the result, but all the result column names must be unique. In particular, the names `cartodb_id`, `the_geom`, `the_geom_webmercator` and `_cdb_feature_count` cannot be used for aggregated columns, as they correspond to columns always present in the result.
+
+#### `resolution`
+
+Defines the cell-size of the spatial aggregation grid. This is equivalent to the [CartoCSS `-torque-resolution`](https://carto.com/docs/carto-engine/cartocss/properties-for-torque/#-torque-resolution-float) property of Torque maps.
+
+The aggregation cells are `resolution`×`resolution` pixels in size, where pixels here are defined to be 1/256 of the (linear) size of a tile.
+The default value is 1, so that aggregation coincides with raster pixels. A value of 2 would make each cell to be 4 (2×2) pixels, and a value of
+0.5 would yield 4 cells per pixel. In teneral values less than 1 produce sub-pixel precision.
+
+> Note that is independent of the number of pixels for raster tile or the coordinate resolution (mvt_extent) of vector tiles.
+
+
+#### `threshold`
+
+This is the minimum number of (estimated) rows in the dataset (query results) for aggregation to be applied. If the number of rows estimate is less than the threshold aggregation will be disabled for the layer; the instantiation response will reflect that and tiles will be generated without aggregation.
+
+#### Example
+
+```json
+{
+ "version": "1.7.0",
+ "extent": [-20037508.5, -20037508.5, 20037508.5, 20037508.5],
+ "srid": 3857,
+ "maxzoom": 18,
+ "minzoom": 3,
+ "layers": [
+ {
+ "type": "mapnik",
+ "options": {
+ "sql": "select * from table",
+ "cartocss": "#table { marker-width: [total]; marker-fill: ramp(value, (red, green, blue), jenks); }",
+ "cartocss_version": "2.3.0",
+ "aggregation": {
+ "placement": "centroid",
+ "columns": {
+ "value": {
+ "aggregate_function": "avg",
+ "aggregated_column": "value"
+ },
+ "total": {
+ "aggregate_function": "sum",
+ "aggregated_column": "value"
+ }
+ },
+ "resolution": 2,
+ "threshold": 500000
+ }
+ }
+ }
+ ]
+}
+```
diff --git a/docs/guides/07-MapConfig-file-format.md b/docs/guides/07-MapConfig-file-format.md
new file mode 100644
index 00000000..2f8068a9
--- /dev/null
+++ b/docs/guides/07-MapConfig-file-format.md
@@ -0,0 +1,270 @@
+{% comment %}
+The original resource for this was:
+https://github.com/CartoDB/Windshaft/blob/master/doc/MapConfig-1.4.0.md. However this is internal documenation only. This file (07-mapconfig.md) contains select content from the Windshaft internal doc. *I instructed @rochoa to add new Doc issues if/when they make a change to this content - so that the public docs can also be updated.
+{% endcomment %}
+
+## MapConfig File Format
+
+CARTO uses Windshaft as the map tiler library to render multilayer maps with the [Maps API]({{ site.baseurl }}/carto-engine/maps-api/). The MapConfig file is where these Windshaft layers are stored and applied. You can configure tiles and use the MapConfig document to request different resources for your map.
+
+This section describes the MapConfig specifications, and required formats, when using the Maps API.
+
+### Layergroup Configurations
+
+The following MapConfig Layergroup configurations are applied using the [RFC 4627](http://www.ietf.org/rfc/rfc4627.txt) JSON format.
+
+Layergroup Configuration | Description | Optional or Required?
+--- | ---
+`version` | Spec version to use for validation.
**Note:** The default value is `"1.0.0"`. | Optional
+`extent` | The default map extent for the map projection.
**Note:** Currently, only webmercator is supported. | Optional
+`srid` | The spatial reference identifier for the map. The default is `3857`. | Optional
+`maxzoom` | The maximum zoom level for your map. A request beyond the defined maxzoom returns a 404 error.
**Note:** The default value is undefined (infinite). | Optional
+`minzoom` | The minimum zoom level for your map. A request beyond the defined minzoom returns a 404 error.
**Note:** The default value is `0`. | Optional
+`layers` | Defines the layer type, and the layers, in rendering order.
**Note:** The following layers options are available: |
+--- | ---
+ type | A string value that defines the layer type. You can define up to four values:
`mapnik`, rasterized tiles
`cartodb`, an alias for mapnik (for backward compatibility)
`torque`, render vector tiles in torque format
`http`, load tiles over HTTP
`plain`, color or background image url
`named`, use a Named Map as a layer | Required
+ options | An object value that sets different options for each layer type.
**Note:** Options that are not defined in different layers will be discarded. | Required
+
+#### Example of MapConfig
+
+{% highlight json %}
+{
+ "version": "1.7.0",
+ "extent": [-20037508.5, -20037508.5, 20037508.5, 20037508.5],
+ "srid": 3857,
+ "maxzoom": 18,
+ "minzoom": 3,
+ "layers": [
+ {
+ "type": "mapnik",
+ "options": {
+ "sql": "select * from table",
+ "cartocss": "#table { marker-placement: point; }",
+ "cartocss_version": "2.3.0"
+ }
+ }
+ ]
+}
+{% endhighlight %}
+
+---
+
+### Mapnik Layer Options
+
+If you are using Mapnik as a layer resource, the following configurations are required in your MapConfig file.
+
+Mapnik Layer Option | Description | Optional or Required?
+--- | ---
+`sql` | A string value, the SQL request to the user database that will fetch the rendered data.
**Tip:** The SQL request should include the following Mapnik layer configurations: `geom_column`, `interactivity`, and `attributes`, as described in this section.
**Note:** The SQL request may contain substitutions tokens, such as `!bbox!`, `!pixel_width!`, and `!pixel_height!`. It is suggested to define the layergroup `minzoom` and `extent` variables to prevent errors. | Required
+`cartocss` | A string value, specifying the CartoCSS style to render the tiles. If this is not present, only vector tiles can be requested for this layer. For a map to be valid either all the layers or none of them must have CartoCSS style.
**Note:** The CartoCSS specification is dependent on the layer type. For details, see [mapnik-reference.json](https://github.com/mapnik/mapnik-reference). | Optional
+`cartocss_version` | A string value, specifying the CartoCSS style version of the CartoCSS attribute.
**Note:** The CartoCSS version is specific to the layer type. | Optional
+`geom_column` | The name of the column containing the geometry. The default is `the_geom_webmercator`.
*You must specify this value as part of the Mapnik layer `SQL`configuration. | *Optional
+`geom_type` | Defines the type of column as either `geometry` (the default) or `raster`.
**Note:** `geom_type` is not compatible with the Mapnik layer `interactivity` option. | Optional
+`raster_band` | Defines the raster band (this option is only applicable when the `geom_type=raster`. The default value is `0`.
**Note:** If the default, or no value is specified, raster bands are interpreted as either: grayscale (for single bands), RGB (for 3 bands), or RGBA (for 4 bands). | Optional
+`srid` | The spatial reference identifier for the geometry column. The default is `3857`. | Optional
+`affected_tables` | A string of values containing the tables that the Mapnik layer `SQL` configuration is using. This value is used if there is a problem guessing what the affected tables are from the SQL configuration (i.e. when using PL/SQL functions). | Optional
+`interactivity` | A string of values that contains the fields rendered inside grid.json. All the parameters should be exposed as a result of executing the Mapnik layer `SQL` query.
**Note:** `interactivity` is not compatible with the Mapnik layer `geom_type` option. For example, you cannot create a layergroup instance with a raster layer by defining the `geom_type=raster`.
*You must specify this value as part of the Mapnik layer `SQL` configuration. | *Optional
+`attributes` | The id and column values returned by the Mapnik attributes service. (This option is disabled if no configuration is defined).
*You must specify this value as part of the Mapnik layer `SQL`configuration.| *Optional
+--- | ---
+ id | The key value used to fetch columns. | Required
+ columns | A string of values (columns) returned by the Mapnik attribute service. | Required
+
+#### Example of Mapnik MapConfig
+
+{% highlight json %}
+{
+ "type": "mapnik",
+ "options": {
+ "sql": "select * from table",
+ "cartocss": "#layer { marker-placement: point; }",
+ "cartocss_version": "2.3.0",
+ "geom_column": "the_geom_webmercator",
+ "geom_type": "geometry",
+ "interactivity": [ "column1", "column2", "..."],
+ "attributes": {
+ "id": "cartodb_id",
+ "columns": ["column1", "column2"]
+ }
+ }
+}
+{% endhighlight %}
+
+### Torque Layer Options
+
+If you are using Torque as a layer resource, the following configurations are required in your MapConfig file. For more details about Torque layers in general, see the [Torque API]({{ site.baseurl }}/carto-engine/torque/torqueapi/#torque-api) documentation.
+
+Torque Layer Option | Description | Optional or Required?
+--- | ---
+`sql` | A string value, the SQL request to the user database that will fetch the rendered data.
**Tip:** The SQL request should include the following Torque layer configurations: `geom_column`, `interactivity`, and `attributes`, as described in this section. | Required
+`cartocss` | A string value, specifying the CartoCSS style to render the tiles.
**Note:** The CartoCSS specification is dependent on the layer type. For details, see [Torque cartocss-reference.js](https://github.com/CartoDB/torque/blob/master/lib/torque/cartocss_reference.js).| Required
+`cartocss_version` | A string value, specifying the CartoCSS style version of the CartoCSS attribute.
**Note:** The CartoCSS version is specific to the layer type. | Required
+`step` | The number of [animation steps]({{ site.baseurl }}/carto-engine/cartocss/properties-for-torque/#torque-frame-count-number) to render when requesting a torque.png tile. The default value is `0`. | Optional
+`geom_column` | The name of the column containing the geometry. The default is `the_geom_webmercator`.
*You must specify this value as part of the Torque layer `SQL`configuration. | *Optional
+`srid` | The spatial reference identifier for the geometry column. The default is `3857`. | Optional
+`affected_tables` | A string of values containing the tables that the Mapnik layer `SQL` configuration is using. This value is used if there is a problem guessing what the affected tables are from the SQL configuration (i.e. when using PL/SQL functions). | Optional
+`attributes` | The id and column values returned by the Torque attributes service. (This option is disabled if no configuration is defined).
*You must specify this value as part of the Torque layer `SQL`configuration.| *Optional
+--- | ---
+ id | The key value used to fetch columns. | Required
+ columns | A string of values (columns) returned by the Torque attribute service. | Required
+
+#### Example of Torque MapConfig
+
+{% highlight json %}
+{
+ "type": "torque",
+ "options": {
+ "sql": "select * from table",
+ "cartocss": "#layer { ... }",
+ "cartocss_version": "1.0.0",
+ "geom_column": "the_geom_webmercator"
+ }
+}
+{% endhighlight %}
+
+### HTTP Layer Options
+
+If you are using an HTTP destination as the resource for a map layer, the following configurations are required in your MapConfig file.
+
+HTTP Layer Option | Description | Optional or Required?
+--- | ---
+`urlTemplate` | A string value, end URL, from where the tile data is retrieved. _URLs must be included in the configuration whitelist to be valid._
**Note:** The {String} value includes:
`{z}` as the zoom level
`{x} and {y}` as the tile coordinates
Optionally, the subdomain `{s}` may be included as part of the `urlTemplate` configuration. Otherwise, you can define the `subdomains` separately, as shown below. | Required
+`subdomains` | A string of values used to retrieve tiles from different subdomains. The default value is [`a`, `b`, `c`] when `{s}` is defined in the `urlTemplate` configuration. Otherwise, the default value is `[ ]`.
**Note:** The subdomains value will consistently replace the `{s}` value defined in the `urlTemplate`.| Optional
+`tms` | A boolean value that specifies whether the tile is using Tile Map Service format. The default value is `false`.
**Note:** If the value is `true`, the TMS inverses the Y axis numbering for tiles. | Optional
+
+#### Example of HTTP MapConfig
+
+{% highlight json %}
+{
+ "type": "http",
+ "options": {
+ "urlTemplate": "http://{s}.example.com/{z}/{x}/{y}.png",
+ "subdomains": ["a", "b", "c"],
+ "tms": false
+ }
+}
+{% endhighlight %}
+
+### Plain Layer Options
+
+If you are using plain layer options as your map resource, the following configurations are required in your MapConfig file.
+
+_**Note:** At least one of the plain layer options (either `color` or `imageUrl`) must be defined. If both options are defined, only `color` is used as part of the plain layer configuration._
+
+Plain Layer Option | Description | Optional or Required?
+--- | ---
+`color` | A string value of numbers that defines the valid colors to include. The default value is `null`. Valid colors include:
- A string value that includes CSS colors (i.e. `blue`) or a hex color string (i.e. `#0000ff`)
- An integer array of r,g,b values (i.e. `[255,0,0]`)
- An integer array of r,g,b,a values (i.e. `[255,0,0,128]`)
* If **only** the `color` value is used for a plain layer, this value is Required.
* If **both** `color` and `imageUrl` are defined, only the `color` value is used for the plain layer configuration.| *Both
+`imageUrl` | A string value, end URL, from where the image is retrieved. The default value is `null`.
* If **only** the `imageUrl` value is used for a plain layer, this value is Required.
* If `color` is defined, this `imageUrl` value is ignored. | *Both
+
+#### Example of Plain MapConfig
+
+{% highlight json %}
+{
+ "type": "plain",
+ "options": {
+ "color": "blue",
+ "imageUrl": "http://example.com/background.png"
+ }
+}
+{% endhighlight %}
+
+### Named Map Layer Options
+
+You can use a [Named Map]({{ site.baseurl }}/carto-engine/maps-api/named-maps/#named-maps) as a map layer. Note the following limitations before referencing the MapConfig options for a Named Map layer.
+
+_**Limitations:**_
+
+- A Named Map will not allow you to have `named` type layers inside of your template layergroup's layers definition
+- A `named` layer does not allow Named Maps from other accounts. You can only use Named Maps from the _same_ user account
+
+If you are using `named` layer options as your map resource, the following configurations are required in your MapConfig file.
+
+Named Layer Option | Description | Optional or Required?
+--- | ---
+`name` | A string value, the name for the Named Map to use. | Required
+`config` | An object, the replacement values for the Named Map's template placeholders. | Optional
+`auth_tokens` | Strings array, the authorized tokens in case the Named Map has auth method set to `token`. | Optional
+
+#### Example of Named MapConfig
+
+{% highlight json %}
+{
+ "type": "named",
+ "options": {
+ "name": "world_borders",
+ "config": {
+ "color": "#000"
+ },
+ "auth_tokens": ["token1", "token2"]
+ }
+}
+{% endhighlight %}
+
+### Aggregation Options
+
+The data used to render tiles, or contained in the tiles (for the case of vector tiles), can be spatially [aggregated](https://carto.com/docs/carto-engine/maps-api/named-maps/) under some circumstances.
+
+An `aggregation` attribute can be used in the layer `options` to control the aggregation. A value of `false` will disable aggregation for the layer. Otherwise, an object can be passed with the following aggregation parameters:
+
+Parameter|Description|Default value
+`placement`|Determines the kind of aggregated geometry generated ("point-sample", "point-grind" or "centroid").|"centroid"
+`columns`|Defines aggregated columns; each one by an "aggregate_function" ("sum", "avg", "min, "max", "mode", "count") and "aggregated_column" name.|
+`resolution`|Defines the cell-size of the spatial aggregation grid.|1 (for 256x256 cells per tile)
+`threshold`|Minimum rows in the dataset to apply aggregation.
+
+#### Example of Aggregation MapConfig
+
+{% highlight json %}
+{
+ "version": "1.7.0",
+ "extent": [-20037508.5, -20037508.5, 20037508.5, 20037508.5],
+ "srid": 3857,
+ "maxzoom": 18,
+ "minzoom": 3,
+ "layers": [
+ {
+ "type": "mapnik",
+ "options": {
+ "sql": "select * from table",
+ "cartocss": "#table { marker-width: [total]; marker-fill: ramp(value, (red, green, blue), jenks); }",
+ "cartocss_version": "2.3.0",
+ "aggregation": {
+ "placement": "centroid",s
+ "columns": {
+ "value": {
+ "aggregate_function": "avg",
+ "aggregated_column": "value"
+ },
+ "total": {
+ "aggregate_function": "sum",
+ "aggregated_column": "value"
+ }
+ },
+ "resolution": 2, // Aggregation cell is 2x2 pixels
+ "threshold": 500000
+ }
+ }
+ }
+ ]
+}
+{% endhighlight %}
+
+### MapConfig Requirements
+
+All of these are MapConfig requirements for [Anonymous Maps]({{ site.baseurl }}/carto-engine/maps-api/anonymous-maps/#retrieve-resources-from-the-layergroup).
+
+- Identified by `{z}/{x}/{y}` path
+
+- If applicable, additionally identified by `LAYER_NUMBER`
+
+- Can be of different formats:
+ - png
+ - grid.json
+ - torque.json
+
+- Static images/previews
+ - With a center or a bounding box
+
+- Attributes
+ -Identified by LAYER_NUMBER and FEATURE_ID
+
+**Tip:** The MapConfig file may be extended for specific uses. For example, [Windshaft-CartoDB](https://github.com/CartoDB/Windshaft-cartodb/blob/master/docs/MultiLayer-API.md) defines the addition of a `stat_tag` element in the config. This extension is also covered as part of the [Named Map Layer Options](#named-map-layer-options).
\ No newline at end of file
diff --git a/docs/guides/08-MapConfig-aggregation-extension.md b/docs/guides/08-MapConfig-aggregation-extension.md
new file mode 100644
index 00000000..9dfb4dfa
--- /dev/null
+++ b/docs/guides/08-MapConfig-aggregation-extension.md
@@ -0,0 +1,64 @@
+## MapConfig Aggregation Extension
+
+### 1. Purpose
+
+This specification describes an extension for
+[MapConfig 1.7.0](https://github.com/CartoDB/Windshaft/blob/master/doc/MapConfig-1.7.0.md) version.
+
+
+### 2. Changes over specification
+
+This extension introduces a new layer options for aggregated data tile generation.
+
+#### 2.1 Aggregation options
+
+The layer options attribute is extended with a new optional `aggregation` attribute.
+The value of this attribute can be `false` to explicitly disable aggregation for the layer.
+
+```javascript
+{
+ aggregation: {
+
+ // OPTIONAL
+ // string, defines the placement of aggregated geometries. Can be one of:
+ // * "point-sample", the default places geometries at a sample point (one of the aggregated geometries)
+ // * "point-grid" places geometries at the center of the aggregation grid cells
+ // * "centroid" places geometriea at the average position of the aggregated points
+ // See https://github.com/CartoDB/Windshaft-cartodb/blob/master/docs/aggregation.md#placement for more details
+ placement: "point-sample",
+
+ // OPTIONAL
+ // object, defines the columns of the aggregated datasets. Each property corresponds to a columns name and
+ // should contain an object with two properties: "aggregate_function" (one of "sum", "max", "min", "avg", "mode" or "count"),
+ // and "aggregated_column" (the name of a column of the original layer query or "*")
+ // A column defined as `"_cdb_features_count": {"aggregate_function": "count", aggregated_column: "*"}`
+ // is always generated in addition to the defined columns.
+ // The column names `cartodb_id`, `the_geom`, `the_geom_webmercator` and `_cdb_feature_count` cannot be used
+ // for aggregated columns, as they correspond to columns always present in the result.
+ // See https://github.com/CartoDB/Windshaft-cartodb/blob/master/docs/aggregation.md#columns for more details
+ columns: {
+ "aggregated_column_1": {
+ "aggregate_function": "sum",
+ "aggregated_column": "original_column_1"
+ }
+ },
+
+ // OPTIONAL
+ // Number, defines the cell-size of the spatial aggregation grid as a pixel resolution power of two (1/4, 1/2,... 2, 4, 16)
+ // to scale from 256x256 pixels; the default is 1 corresponding to 256x256 cells per tile.
+ // See https://github.com/CartoDB/Windshaft-cartodb/blob/master/docs/aggregation.md#resolution for more details
+ resolution: 1,
+
+ // OPTIONAL
+ // Number, the minimum number of (estimated) rows in the dataset (query results) for aggregation to be applied.
+ // See https://github.com/CartoDB/Windshaft-cartodb/blob/master/docs/aggregation.md#threshold for more details
+ threshold: 500000
+ }
+}
+```
+
+### History
+
+#### 1.0.0
+
+ - Initial version
diff --git a/docs/guides/09-MapConfig-analyses-extension.md b/docs/guides/09-MapConfig-analyses-extension.md
new file mode 100644
index 00000000..53500e32
--- /dev/null
+++ b/docs/guides/09-MapConfig-analyses-extension.md
@@ -0,0 +1,95 @@
+## MapConfig Analyses Extension
+
+### 1. Purpose
+
+This specification describes an extension for
+[MapConfig 1.4.0](https://github.com/CartoDB/Windshaft/blob/master/doc/MapConfig-1.4.0.md) version.
+
+
+### 2. Changes over specification
+
+This extension targets layers with `sql` option, including layer types: `cartodb`, `mapnik`, and `torque`.
+
+It extends MapConfig with a new attribute: `analyses`.
+
+#### 2.1 Analyses attribute
+
+The new analyses attribute must be an array of analyses as per [camshaft](https://github.com/CartoDB/camshaft). Each
+analysis must adhere to the [camshaft-reference](https://github.com/CartoDB/camshaft/blob/0.8.0/reference/versions/0.7.0/reference.json) specification.
+
+Each node can have an id that can be later references to consume the query from MapConfig's layers.
+
+Basic analyses example:
+
+```javascript
+[
+ {
+ // REQUIRED
+ // string, `id` free identifier that can be reference from any layer
+ "id": "HEAD",
+ // REQUIRED
+ // string, `type` camshaft's analysis type
+ "type": "source",
+ // REQUIRED
+ // object, `params` will depend on `type`, check camshaft-reference for more information
+ "params": {
+ "query": "select * from your_table"
+ }
+ }
+]
+```
+
+### 2.2. Integration with layers
+
+As pointed before an analysis node id can be referenced from layers to consume its output query.
+
+The layer consuming the output must reference it with the following option:
+
+```
+{
+ "options": {
+ // REQUIRED
+ // object, `source` as in the future we might want to have other source options
+ "source": {
+ // REQUIRED
+ // string, `id` the analysis node identifier
+ "id": "HEAD"
+ }
+ }
+}
+```
+
+#### 2.3. Complete example
+
+```
+{
+ "version": "1.4.0",
+ "layers": [
+ {
+ "type": "cartodb",
+ "options": {
+ "source": {
+ "id": "HEAD"
+ },
+ "cartocss": "...",
+ "cartocss_version": "2.3.0"
+ }
+ }
+ ],
+ "analyses": [
+ {
+ "id": "HEAD",
+ "type": "source",
+ "params": {
+ "query": "select * from your_table"
+ }
+ }
+ ]
+}
+```
+
+### History
+
+#### 1.0.0
+
+ - Initial version
diff --git a/docs/guides/10-MapConfig-dataviews-extension.md b/docs/guides/10-MapConfig-dataviews-extension.md
new file mode 100644
index 00000000..7a5ab59a
--- /dev/null
+++ b/docs/guides/10-MapConfig-dataviews-extension.md
@@ -0,0 +1,279 @@
+## MapConfig Dataviews Extension
+
+### 1. Purpose
+
+This specification describes an extension for
+[MapConfig 1.4.0](https://github.com/CartoDB/Windshaft/blob/master/doc/MapConfig-1.4.0.md) version.
+
+
+### 2. Changes over specification
+
+This extension depends on Analyses extension. It extends MapConfig with a new attribute: `dataviews`.
+
+It makes possible to get tabular data from analysis nodes: aggregated lists, aggregations, and histograms.
+
+#### 2.1. Dataview types
+
+##### Aggregation
+
+An aggregation is a list with aggregated results by a column and a given aggregation function.
+
+Definition
+```
+{
+ // REQUIRED
+ // string, `type` the aggregation type
+ “type”: “aggregation”,
+ // REQUIRED
+ // object, `options` dataview params
+ “options”: {
+ // REQUIRED
+ // string, `column` column name to aggregate by
+ “column”: “country”,
+ // REQUIRED
+ // string, `aggregation` operation to perform
+ “aggregation”: “count”
+ // OPTIONAL
+ // string, `aggregationColumn` column value to aggregate
+ // This param is required when `aggregation` is different than "count"
+ “aggregationColumn”: “population”
+ }
+}
+```
+
+Expected output
+```
+{
+ "type": "aggregation",
+ "categories": [
+ {
+ "category": "foo",
+ "value": 100
+ },
+ {
+ "category": "bar",
+ "value": 200
+ }
+ ]
+}
+```
+
+##### Histograms
+
+Histograms represent the data distribution for a column.
+
+Definition
+```
+{
+ // REQUIRED
+ // string, `type` the histogram type
+ “type”: “histogram”,
+ // REQUIRED
+ // object, `options` dataview params
+ “options”: {
+ // REQUIRED
+ // string, `column` column name to aggregate by
+ “column”: “name”,
+ // OPTIONAL
+ // number, `bins` how many buckets the histogram should use
+ “bins”: 10
+ }
+}
+```
+
+Expected output
+```
+{
+ "type": "histogram",
+ "bins": [{"bin": 0, "start": 2, "end": 2, "min": 2, "max": 2, "freq": 1}, null, null, {"bin": 3, "min": 40, "max": 44, "freq": 2}, null],
+ "width": 10
+}
+```
+
+##### Formula
+
+Formulas given a final value representing the whole dataset.
+
+Definition
+```
+{
+ // REQUIRED
+ // string, `type` the formula type
+ “type”: “formula”,
+ // REQUIRED
+ // object, `options` dataview params
+ “options”: {
+ // REQUIRED
+ // string, `column` column name to aggregate by
+ “column”: “name”,
+ // REQUIRED
+ // string, `aggregation` operation to perform
+ “operation”: “count”
+ }
+}
+```
+
+Operation must be: “min”, “max”, “count”, “avg”, or “sum”.
+
+Result
+```
+{
+ "type": "formula",
+ "operation": "count",
+ "result": 1000,
+ "nulls": 0
+}
+```
+
+
+#### 2.2 Dataviews attribute
+
+The new dataviews attribute must be a dictionary of dataviews.
+
+An analysis node id can be referenced from dataviews to consume its output query.
+
+
+The layer consuming the output must reference it with the following option:
+
+```
+{
+ // REQUIRED
+ // object, `source` as in the future we might want to have other source options
+ "source": {
+ // REQUIRED
+ // string, `id` the analysis node identifier
+ "id": "HEAD"
+ }
+}
+```
+
+#### 2.3. Complete example
+
+```
+{
+ "version": "1.4.0",
+ "layers": [
+ {
+ "type": "cartodb",
+ "options": {
+ "source": {
+ "id": "HEAD"
+ },
+ "cartocss": "...",
+ "cartocss_version": "2.3.0"
+ }
+ }
+ ],
+ "dataviews" {
+ "basic_histogram": {
+ "source": {
+ "id": "HEAD"
+ },
+ "type": "histogram",
+ "options": {
+ "column": "pop_max"
+ }
+ }
+ },
+ "analyses": [
+ {
+ "id": "HEAD",
+ "type": "source",
+ "params": {
+ "query": "select * from your_table"
+ }
+ }
+ ]
+}
+```
+
+#### 3. Filters
+
+Camshaft's analyses expose a filtering capability and `aggregation` and `histogram` dataviews get them for free with
+ this extension. Filters are available with the very dataview id, so if you have a "basic_histogram" histogram dataview
+ you can filter with a range filter with "basic_histogram" name.
+
+
+#### 3.1 Filter types
+
+##### Category
+
+Allows to remove results that are not contained within a set of elements.
+Initially this filter can be applied to a `numeric` or `text` columns.
+
+Params
+
+```
+{
+ “accept”: [“Spain”, “Germany”]
+ “reject”: [“Japan”]
+}
+```
+
+##### Range filter
+
+Allows to remove results that don’t satisfy numeric min and max values.
+Filter is applied to a numeric column.
+
+Params
+
+```
+{
+ “min”: 0,
+ “max”: 1000
+}
+```
+
+#### 3.2. How to apply filters
+
+Filters must be applied at map instantiation time.
+
+With :mapconfig as a valid MapConfig and with :filters (a valid JSON) as:
+
+##### Anonymous map
+
+`GET /api/v1/map?config=:mapconfig&filters=:filters`
+
+`POST /api/v1/map?filters=:filters`
+with `BODY=:mapconfig`
+
+If in the future we need to support a bigger filters param and it doesn’t fit in the query string,
+ we might solve it by accepting:
+
+`POST /api/v1/map`
+with `BODY={“config”: :mapconfig, “filters”: :filters}`
+
+##### Named map
+
+Assume :params (a valid JSON) as named maps params, like in: `{“color”: “red”}`
+
+`GET /api/v1/named/:name/jsonp?config=:params&filters=:filters&callback=cb`
+
+`POST /api/v1/named/:name?filters=:filters`
+with `BODY=:params`
+
+If, again, in the future we need to support a bigger filters param that doesn’t fit in the query string,
+ we might solve it by accepting:
+
+`POST /api/v1/named/:name`
+with `BODY={“config”: :params, “filters”: :filters}`
+
+
+#### 3.3 Bounding box special filter
+
+A bounding box filter allows to remove results that don’t satisfy a geospatial range.
+
+The bounding box special filter is available per dataview and there is no need to create a bounding box definition as
+it’s always possible to apply a bbox filter per dataview.
+
+A dataview can get its result filtered by bounding box by sending a bbox param in the query string,
+param must be in the form `west,south,east,north`.
+
+So applying a bbox filter to a dataview looks like:
+GET /api/v1/map/:layergroupid/dataview/:dataview_name?bbox=-90,-45,90,45
+
+### History
+
+#### 1.0.0-alpha
+
+ - WIP document
diff --git a/docs/guides/11-Mapconfig-named-maps-extension.md b/docs/guides/11-Mapconfig-named-maps-extension.md
new file mode 100644
index 00000000..001ec847
--- /dev/null
+++ b/docs/guides/11-Mapconfig-named-maps-extension.md
@@ -0,0 +1,58 @@
+## MapConfig Named Maps Extension
+
+### 1. Purpose
+
+This specification describes an extension for
+[MapConfig 1.3.0](https://github.com/CartoDB/Windshaft/blob/master/doc/MapConfig-1.3.0.md) version.
+
+
+### 2. Changes over specification
+
+This extension introduces a new layer type so it's possible to use a Named Map by its name as a layer.
+
+#### 2.1 Named layers definition
+
+```javascript
+{
+ // REQUIRED
+ // string, `named` is the only supported value
+ type: "named",
+
+ // REQUIRED
+ // object, set `named` map layers configuration
+ options: {
+
+ // REQUIRED
+ // string, the name for the Named Map to use
+ name: "world_borders",
+
+ // OPTIONAL
+ // object, the replacement values for the Named Map's template placeholders
+ // See https://github.com/CartoDB/Windshaft-cartodb/blob/master/docs/Map-API.md#instantiate-1 for more details
+ config: {
+ "color": "#000"
+ },
+
+ // OPTIONAL
+ // string array, the authorized tokens in case the Named Map has auth method set to `token`
+ // See https://github.com/CartoDB/Windshaft-cartodb/blob/master/docs/Map-API.md#named-maps-1 for more details
+ auth_tokens: [
+ "token1",
+ "token2"
+ ]
+ }
+}
+```
+
+#### 2.2 Limitations
+
+1. A Named Map will not allow to have `named` type layers inside their templates layergroup's layers definition.
+2. A `named` layer does not allow Named Maps form other accounts, it's only possible to use Named Maps from the very
+same user account.
+
+
+### History
+
+#### 1.0.0
+
+ - Initial version
diff --git a/docs/reference/01-routes.md b/docs/reference/01-routes.md
new file mode 100644
index 00000000..0ebe732b
--- /dev/null
+++ b/docs/reference/01-routes.md
@@ -0,0 +1,114 @@
+This document list all routes available in Windshaft-cartodb Maps API server.
+
+## Routes list
+
+1. `GET (?:/api/v1/map|/user/:user/api/v1/map|/tiles/layergroup)/:token/:z/:x/:y@:scale_factor?x.:format {:user(f),:token(f),:z(f),:x(f),:y(f),:scale_factor(t),:format(f)} (1)`
+ Notes: Mapnik retina tiles [0]
+
+1. `GET (?:/api/v1/map|/user/:user/api/v1/map|/tiles/layergroup)/:token/:z/:x/:y.:format {:user(f),:token(f),:z(f),:x(f),:y(f),:format(f)} (1)`
+ Notes: Mapnik tiles [0]
+
+1. `GET (?:/api/v1/map|/user/:user/api/v1/map|/tiles/layergroup)/:token/:layer/:z/:x/:y.(:format) {:user(f),:token(f),:layer(f),:z(f),:x(f),:y(f),:format(f)} (1)`
+ Notes: Per :layer rendering based on :format [0]
+
+1. `GET (?:/api/v1/map|/user/:user/api/v1/map|/tiles/layergroup)/:token/:layer/attributes/:fid {:user(f),:token(f),:layer(f),:fid(f)} (1)`
+ Notes: Endpoint for info windows data, alternative for sql api when tables are private [0]
+
+1. `GET (?:/api/v1/map|/user/:user/api/v1/map|/tiles/layergroup)/static/center/:token/:z/:lat/:lng/:width/:height.:format {:user(f),:token(f),:z(f),:lat(f),:lng(f),:width(f),:height(f),:format(f)} (1)`
+ Notes: Static Maps API [0]
+
+1. `GET (?:/api/v1/map|/user/:user/api/v1/map|/tiles/layergroup)/static/bbox/:token/:west,:south,:east,:north/:width/:height.:format {:user(f),:token(f),:west(f),:south(f),:east(f),:north(f),:width(f),:height(f),:format(f)} (1)`
+ Notes: Static Maps API [0]
+
+1. `GET (?:/api/v1/map|/user/:user/api/v1/map|/tiles/layergroup)/:token/:layer/widget/:widgetName {:user(f),:token(f),:layer(f),:widgetName(f)} (1)`
+ Notes: By :widgetName per :layer widget [0]
+
+1. `GET (?:/api/v1/map|/user/:user/api/v1/map|/tiles/layergroup)/:token/:layer/widget/:widgetName/search {:user(f),:token(f),:layer(f),:widgetName(f)} (1)`
+ Notes: By :widgetName per :layer widget search [0]
+
+1. `GET (?:/api/v1/map|/user/:user/api/v1/map|/tiles/layergroup) {:user(f)} (1)`
+ Notes: Map instantiation [0]
+
+1. `POST (?:/api/v1/map|/user/:user/api/v1/map|/tiles/layergroup) {:user(f)} (1)`
+ Notes: Map instantiation [0]
+
+1. `GET (?:/api/v1/map/named|/user/:user/api/v1/map/named|/tiles/template)/:template_id/jsonp {:user(f),:template_id(f)} (1)`
+ Notes: Named maps JSONP instantiation [1]
+
+1. `POST (?:/api/v1/map/named|/user/:user/api/v1/map/named|/tiles/template)/:template_id {:user(f),:template_id(f)} (1)`
+ Notes: Instantiate named map [1]
+
+1. `OPTIONS (?:/api/v1/map|/user/:user/api/v1/map|/tiles/layergroup) {:user(f)} (1)`
+ Notes: CORS [0]
+
+1. `GET (?:/api/v1/map/named|/user/:user/api/v1/map/named|/tiles/template)/:template_id/:layer/:z/:x/:y.(:format) {:user(f),:template_id(f),:layer(f),:z(f),:x(f),:y(f),:0(f),:format(f)} (1)`
+ Notes: Per :layer fixed URL named map tiles [1]
+
+1. `GET (?:/api/v1/map|/user/:user/api/v1/map|/tiles/layergroup)/static/named/:template_id/:width/:height.:format {:user(f),:template_id(f),:width(f),:height(f),:format(f)} (1)`
+ Notes: Static map for named maps [1]
+
+1. `POST (?:/api/v1/map/named|/user/:user/api/v1/map/named|/tiles/template) {:user(f)} (1)`
+ Notes: Create named map (w/ API KEY) [1]
+
+1. `PUT (?:/api/v1/map/named|/user/:user/api/v1/map/named|/tiles/template)/:template_id {:user(f),:template_id(f)} (1)`
+ Notes: Update a named map (w/ API KEY) [1]
+
+1. `GET (?:/api/v1/map/named|/user/:user/api/v1/map/named|/tiles/template)/:template_id {:user(f),:template_id(f)} (1)`
+ Notes: Named map retrieval (w/ API KEY) [1]
+
+1. `DELETE (?:/api/v1/map/named|/user/:user/api/v1/map/named|/tiles/template)/:template_id {:user(f),:template_id(f)} (1)`
+ Notes: Delete named map (w/ API KEY) [1]
+
+1. `GET (?:/api/v1/map/named|/user/:user/api/v1/map/named|/tiles/template) {:user(f)} (1)`
+ Notes: List named maps (w/ API KEY) [1]
+
+1. `OPTIONS (?:/api/v1/map/named|/user/:user/api/v1/map/named|/tiles/template)/:template_id {:user(f),:template_id(f)} (1)`
+ Notes: CORS [1]
+
+1. `GET /health {} (1)`
+ Notes: Health check
+
+1. `GET / {} (1)`
+ Notes: Welcome message
+
+1. `GET /version {} (1)`
+ Notes: Return relevant module versions: mapnik, grainstore, etc
+
+
+## Optional deprecated routes
+
+- [0] `/tiles/layergroup` is deprecated and `/api/v1/map` should be used but we keep it for now.
+- [1] `/tiles/template` is deprecated and `/api/v1/map/named` should be used but we keep it for now.
+
+## How to generate the list of routes
+
+Something like the following patch should do the trick
+
+```javascript
+diff --git a/lib/cartodb/server.js b/lib/cartodb/server.js
+index 5f62850..bca377d 100644
+--- a/lib/cartodb/server.js
++++ b/lib/cartodb/server.js
+@@ -215,6 +215,20 @@ module.exports = function(serverOptions) {
+ * END Routing
+ ******************************************************************************************************************/
+
++ var format = require('util').format;
++ var routesNotes = app._router.stack
++ .filter(function(handler) { return !!handler.route; })
++ .map(function(handler) {
++ return format("\n1. `%s %s {%s} (1)`\n Notes: [DEPRECATED]? ",
++ Object.keys(handler.route.methods)[0].toUpperCase(),
++ handler.route.path,
++ handler.keys.map(function(k) {
++ return format(':%s(%s)', k.name, k.optional ? 't' : 'f');
++ }).join(',')
++ );
++ });
++ console.log(routesNotes.join('\n'));
++
+ return app;
+ };
+
+
+```
diff --git a/docs/support/01-metrics.md b/docs/support/01-metrics.md
new file mode 100644
index 00000000..bf845b7a
--- /dev/null
+++ b/docs/support/01-metrics.md
@@ -0,0 +1,43 @@
+## Metrics
+
+Windshaft-cartodb metrics
+=========================
+See [Windshaft metrics documentation](https://github.com/CartoDB/Windshaft/blob/master/doc/metrics.md) to understand the full picture.
+
+The next list includes the API endpoints, each endpoint may have several inner timers, some of them are displayed within this list as subitems. Find the description for them in the Inner timers section.
+## Timers
+- **windshaft-cartodb.flush_cache**: time to flush the tile and sql cache
+- **windshaft-cartodb.get_template**: time to retrieve an specific template
+- **windshaft-cartodb.delete_template**: time to delete an specific template
+- **windshaft-cartodb.get_template_list**: time to retrieve the list of owned templates
+- **windshaft-cartodb.instance_template_post**: time to create a template via HTTP POST
+- **windshaft-cartodb.instance_template_get**: time to create a template via HTTP GET
+ + TemplateMaps_instance
+ + createLayergroup
+
+There are some endpoints that are not being tracked:
+- Adding a template
+- Updating a template
+
+### Inner timers
+Again, each inner timer may have several inner timers.
+
+- **addCacheChannel**: time to add X-Cache-Channel header based on table last modifications
+- **LZMA decompress**: time to decompress request params with LZMA
+- **TemplateMaps_instance**: time to retrieve a map template instance, see *getTemplate* and *authorizedByCert*
+- **affectedTables**: time to check what are the affected tables for adding the cache channel, see *addCacheChannel*
+- **authorize**: time to authorize a request, see *authorizedByAPIKey*, *authorizedByCert*, *authorizedBySigner*
+- **authorizedByCert**: time to authorize a template instantiation
+- **findLastUpdated**: time to retrieve the last update time for a list of tables, see *affectedTables*
+- **generateCacheChannel**: time to generate the headers for the cache channel based on the request, see *addCacheChannel*
+- **getSignerMapKey**: time to retrieve from redis the authorized user for a template map
+- **getTablePrivacy**: time to retrieve from redis the privacy of a table
+- **getTemplate**: time to retrieve from redis the template for a map
+- **getUserMapKey**: time to retrieve from redis the user key for a map
+- **incMapviewCount**: time to incremenent in redis the map views
+- **mapStore_load**: time to retrieve from redis a map configuration
+- **req2params.setup**: time to prepare the params from a request, see *req2params* in Windshaft documentation
+- **setDBAuth**: time to retrieve from redis and set db user and db password from a user
+- **setDBConn**: time to retrieve from redis and set db host and db name from a user
+- **setDBParams**: time to prepare all db params to be able to connect/query a database, see *setDBAuth* and *setDBConn*
+- **tablePrivacy_getUserDBName**: time to retrieve from redis the database for a user