mapcomplete/Logic/FeatureSource/Sources/OverpassFeatureSource.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

219 lines
7.5 KiB
TypeScript
Raw Normal View History

import { Feature } from "geojson"
import { FeatureSource } from "../FeatureSource"
2023-03-28 05:13:48 +02:00
import { ImmutableStore, Store, UIEventSource } from "../../UIEventSource"
import LayerConfig from "../../../Models/ThemeConfig/LayerConfig"
import { Or } from "../../Tags/Or"
import { Overpass } from "../../Osm/Overpass"
import { Utils } from "../../../Utils"
import { TagsFilter } from "../../Tags/TagsFilter"
import { BBox } from "../../BBox"
2020-06-24 00:35:19 +02:00
/**
* A wrapper around the 'Overpass'-object.
* It has more logic and will automatically fetch the data for the right bbox and the active layers
*/
export default class OverpassFeatureSource implements FeatureSource {
2021-01-03 00:19:42 +01:00
/**
* The last loaded features, as geojson
2021-01-03 00:19:42 +01:00
*/
public readonly features: UIEventSource<Feature[]> = new UIEventSource(undefined)
2020-06-24 00:35:19 +02:00
public readonly runningQuery: UIEventSource<boolean> = new UIEventSource<boolean>(false)
public readonly timeout: UIEventSource<number> = new UIEventSource<number>(0)
private readonly retries: UIEventSource<number> = new UIEventSource<number>(0)
private readonly state: {
readonly zoom: Store<number>
readonly layers: LayerConfig[]
readonly widenFactor: number
readonly overpassUrl: Store<string[]>
readonly overpassTimeout: Store<number>
readonly bounds: Store<BBox>
}
private readonly _isActive: Store<boolean>
private readonly padToZoomLevel?: Store<number>
private _lastQueryBBox: BBox
2021-01-03 00:19:42 +01:00
constructor(
state: {
readonly layers: LayerConfig[]
readonly widenFactor: number
readonly zoom: Store<number>
readonly overpassUrl: Store<string[]>
readonly overpassTimeout: Store<number>
readonly overpassMaxZoom: Store<number>
readonly bounds: Store<BBox>
2021-09-29 16:55:05 +02:00
},
options?: {
padToTiles?: Store<number>
isActive?: Store<boolean>
2021-09-29 16:55:05 +02:00
}
) {
this.state = state
this._isActive = options?.isActive ?? new ImmutableStore(true)
this.padToZoomLevel = options?.padToTiles
2020-06-24 00:35:19 +02:00
const self = this
state.bounds.addCallbackD((_) => {
self.updateAsyncIfNeeded()
})
}
2020-06-24 00:35:19 +02:00
/**
* Creates the 'Overpass'-object for the given layers
* @param interpreterUrl
* @param layersToDownload
* @constructor
* @private
*/
private GetFilter(interpreterUrl: string, layersToDownload: LayerConfig[]): Overpass {
let filters: TagsFilter[] = layersToDownload.map((layer) => layer.source.osmTags)
filters = Utils.NoNull(filters)
if (filters.length === 0) {
2020-07-31 16:17:16 +02:00
return undefined
}
return new Overpass(new Or(filters), [], interpreterUrl, this.state.overpassTimeout)
2020-06-24 00:35:19 +02:00
}
/**
*
* @private
*/
private async updateAsyncIfNeeded(): Promise<void> {
if (!this._isActive?.data) {
console.log("OverpassFeatureSource: not triggering as not active")
return
}
2020-06-24 00:35:19 +02:00
if (this.runningQuery.data) {
console.log("Still running a query, not updating")
return undefined
}
if (this.timeout.data > 0) {
console.log("Still in timeout - not updating")
return undefined
2020-06-24 00:35:19 +02:00
}
const requestedBounds = this.state.bounds.data
if (
this._lastQueryBBox !== undefined &&
requestedBounds.isContainedIn(this._lastQueryBBox)
) {
return undefined
}
2023-03-28 05:13:48 +02:00
const result = await this.updateAsync()
if (!result) {
return
}
const [bounds, date, updatedLayers] = result
this._lastQueryBBox = bounds
}
2020-07-30 00:59:08 +02:00
/**
* Download the relevant data from overpass. Attempt to use a different server; only downloads the relevant layers
* @private
*/
private async updateAsync(): Promise<[BBox, Date, LayerConfig[]]> {
let data: any = undefined
let date: Date = undefined
let lastUsed = 0
const layersToDownload = []
for (const layer of this.state.layers) {
if (typeof layer === "string") {
throw "A layer was not expanded!"
}
2023-03-25 02:48:24 +01:00
if (layer.source === undefined) {
continue
}
if (this.state.zoom.data < layer.minzoom) {
continue
}
if (layer.doNotDownload) {
continue
}
if (layer.source === null) {
// This is a special layer. Should not have been here
console.warn(
"OverpassFeatureSource received a layer for which the source is null:",
layer.id
)
continue
}
if (layer.source.geojsonSource !== undefined) {
// Not our responsibility to download this layer!
continue
}
layersToDownload.push(layer)
}
if (layersToDownload.length == 0) {
return
}
const self = this
2021-09-29 16:55:05 +02:00
const overpassUrls = self.state.overpassUrl.data
2022-10-27 01:50:41 +02:00
if (overpassUrls === undefined || overpassUrls.length === 0) {
2022-09-18 12:45:02 +02:00
throw "Panic: overpassFeatureSource didn't receive any overpassUrls"
}
// Note: the bounds are updated between attempts, in case that the user zoomed around
2021-11-07 16:34:51 +01:00
let bounds: BBox
do {
try {
bounds = this.state.bounds.data
?.pad(this.state.widenFactor)
?.expandToTileBounds(this.padToZoomLevel?.data)
if (bounds === undefined) {
return undefined
}
const overpass = this.GetFilter(overpassUrls[lastUsed], layersToDownload)
2021-09-29 16:55:05 +02:00
if (overpass === undefined) {
return undefined
}
2022-12-16 13:45:07 +01:00
this.runningQuery.setData(true)
;[data, date] = await overpass.queryGeoJson(bounds)
} catch (e) {
2021-01-03 00:19:42 +01:00
self.retries.data++
self.retries.ping()
2021-09-29 16:55:05 +02:00
console.error(`QUERY FAILED due to`, e)
await Utils.waitFor(1000)
if (lastUsed + 1 < overpassUrls.length) {
lastUsed++
console.log("Trying next time with", overpassUrls[lastUsed])
} else {
lastUsed = 0
self.timeout.setData(self.retries.data * 5)
while (self.timeout.data > 0) {
await Utils.waitFor(1000)
self.timeout.data--
self.timeout.ping()
}
}
}
} while (data === undefined && this._isActive.data)
2021-11-07 16:34:51 +01:00
try {
2021-11-07 16:34:51 +01:00
if (data === undefined) {
2021-10-20 19:12:28 +02:00
return undefined
}
2023-03-28 05:13:48 +02:00
// Some metatags are delivered by overpass _without_ underscore-prefix; we fix them below
// TODO FIXME re-enable this data.features.forEach((f) => SimpleMetaTaggers.objectMetaInfo.applyMetaTagsOnFeature(f))
console.log("Overpass returned", data.features.length, "features")
self.features.setData(data.features)
return [bounds, date, layersToDownload]
} catch (e) {
console.error("Got the overpass response, but could not process it: ", e, e.stack)
2021-10-20 19:12:28 +02:00
return undefined
2021-09-29 16:55:05 +02:00
} finally {
2021-10-20 19:12:28 +02:00
self.retries.setData(0)
self.runningQuery.setData(false)
}
2020-06-24 00:35:19 +02:00
}
}