@duoquote/geotini 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/redis.js ADDED
@@ -0,0 +1,217 @@
1
+ // Geometries in Redis as geotini strings: one key or one hash field per
2
+ // geometry, with its centroid in a GEO set so GEOSEARCH finds it, and a
3
+ // cache keyed by the canonical string. Redis GEO holds points only, so the
4
+ // string keeps the geometry and the point makes it searchable. No Redis
5
+ // code is imported: you pass a client of node-redis (4 and newer) or
6
+ // ioredis (5 and newer), and the functions send it raw commands.
7
+ //
8
+ // import { createStore, cached } from '@duoquote/geotini/redis';
9
+ // const parcels = createStore(client, { prefix: 'parcel:', geoKey: 'parcels:geo', precision: 6 });
10
+ // await parcels.set('p1', geometry);
11
+ // const near = await parcels.search({ lng: 14.42, lat: 50.08, radius: 500, withGeometry: true });
12
+ // const area = await cached(client, str, (g) => String(turf.area(g)), { to: { precision: 6 }, ttl: 3600 });
13
+ //
14
+ // With `binary: true` a store keeps each geometry's binary value (SPEC.md
15
+ // section 23) instead of its string, about three quarters of the bytes, and
16
+ // reads it back with buffer replies.
17
+ /* @ts-self-types="../types/redis.d.ts" */
18
+ import { encode, decode, canonical, encodeValue, decodeValue, canonicalValue, toValue, fromValue } from './geotini.js';
19
+ import { centroid, onGlobe } from './geoindex.js';
20
+
21
+ // Redis keeps GEO points as 52-bit geohashes in Web Mercator's latitude range.
22
+ const MAX_LAT = 85.05112878;
23
+ const OWN = { maxLength: Infinity, maxPositions: Infinity };
24
+ const reading = (o) => (o == null ? undefined : { checksum: o.checksum, maxLength: o.maxLength, maxPositions: o.maxPositions });
25
+
26
+ // Bytes as the clients send them: a Buffer, which both take as a binary
27
+ // argument. A plain Uint8Array would be turned into text.
28
+ const arg = (b) => (globalThis.Buffer ? globalThis.Buffer.from(b.buffer, b.byteOffset, b.byteLength) : b);
29
+
30
+ // send(args), sendBuffer(args) for a reply of bytes, and transaction(list
31
+ // of args) for the two clients, from what they have: ioredis has call()
32
+ // and callBuffer(), node-redis has sendCommand(args, options). node-redis 4
33
+ // takes returnBuffers there, and 5 and newer a typeMapping of blob strings
34
+ // (RESP type 36, '$') to Buffer; each ignores the other's option.
35
+ function driver(client) {
36
+ if (client && typeof client.call === 'function' && typeof client.multi === 'function') {
37
+ return {
38
+ send: (args) => client.call(...args),
39
+ sendBuffer: (args) => client.callBuffer(...args),
40
+ async transaction(cmds) {
41
+ const out = await client.multi(cmds.map((c) => [c[0].toLowerCase(), ...c.slice(1)])).exec();
42
+ for (const [err] of out ?? []) if (err) throw err;
43
+ return out.map((r) => r[1]);
44
+ },
45
+ };
46
+ }
47
+ if (client && typeof client.sendCommand === 'function' && typeof client.multi === 'function') {
48
+ return {
49
+ send: (args) => client.sendCommand(args),
50
+ sendBuffer: (args) => client.sendCommand(args, { returnBuffers: true, typeMapping: { 36: globalThis.Buffer } }),
51
+ transaction(cmds) {
52
+ const m = client.multi();
53
+ for (const c of cmds) (typeof m.addCommand === 'function' ? m.addCommand(c) : m.sendCommand(c));
54
+ return m.exec();
55
+ },
56
+ };
57
+ }
58
+ throw new TypeError('Expected a node-redis or ioredis client');
59
+ }
60
+
61
+ const text = (v) => (v == null ? null : typeof v === 'string' ? v : String(v));
62
+
63
+ const target = (o) => {
64
+ if (o?.favor !== undefined) throw new RangeError("the strings are always written with favor 'size', the canonical encoder");
65
+ return { precision: o?.precision, zPrecision: o?.zPrecision, mPrecision: o?.mPrecision, checksum: o?.checksum };
66
+ };
67
+
68
+ // The canonical string at the store's or the cache's settings, or with
69
+ // binary its value. The input is a geometry, a geotini string or a value.
70
+ const write = (input, to, read, binary) => {
71
+ if (typeof input === 'string') return binary ? toValue(canonical(input, { ...read, to }), OWN) : canonical(input, { ...read, to });
72
+ if (input instanceof Uint8Array) return binary ? canonicalValue(input, { ...read, to }) : canonical(fromValue(input, read), { ...OWN, to });
73
+ return binary ? encodeValue(input, { ...to, favor: 'size' }) : encode(input, { ...to, favor: 'size' });
74
+ };
75
+
76
+ /**
77
+ * The point a geometry goes into a GEO set at: its centroid (planar, by
78
+ * area, length or count, unwrapped across the antimeridian), with the
79
+ * latitude kept within the ±85.05112878 degrees Redis takes. null for a
80
+ * geometry without positions.
81
+ */
82
+ export function geoPoint(geometry) {
83
+ if (geometry?.type === 'Feature') geometry = geometry.geometry;
84
+ onGlobe(geometry, 'a Redis GEO set');
85
+ const c = centroid(geometry);
86
+ if (!c) return null;
87
+ return [c[0], Math.max(-MAX_LAT, Math.min(MAX_LAT, c[1]))];
88
+ }
89
+
90
+ /**
91
+ * A store of geometries under ids. Each is the canonical string at the
92
+ * store's settings, or with `binary: true` its binary value, in its own key
93
+ * (prefix + id) or, with `hash`, a field of one hash; and its point is in
94
+ * the GEO set geoKey (prefix + 'geo' unless given, false for none). Writes
95
+ * go in one MULTI, so the geometry and the point change together.
96
+ */
97
+ export function createStore(client, options = {}) {
98
+ const r = driver(client);
99
+ const prefix = options.prefix ?? 'geotini:', hash = options.hash, read = reading(options.decode), binary = options.binary ?? false;
100
+ if (typeof binary !== 'boolean') throw new TypeError('binary must be true or false');
101
+ const geoKey = options.geoKey === undefined ? prefix + 'geo' : options.geoKey;
102
+ const to = target(options);
103
+ if (hash !== undefined && (typeof hash !== 'string' || !hash)) throw new TypeError('hash must be a non-empty string');
104
+ if (geoKey !== false && (typeof geoKey !== 'string' || !geoKey || geoKey === hash)) throw new TypeError('geoKey must be a non-empty string other than hash, or false');
105
+ const id = (v) => {
106
+ if (typeof v !== 'string' && typeof v !== 'number') throw new TypeError('An id is a string or a number');
107
+ v = String(v);
108
+ if (!hash && prefix + v === geoKey) throw new RangeError(`The id ${v} would be the key of the GEO set`);
109
+ return v;
110
+ };
111
+ const getCmd = (k) => (hash ? ['HGET', hash, k] : ['GET', prefix + k]);
112
+ // A store's own form: a value comes back as a Buffer, a string as text.
113
+ const fetch = (args) => (binary ? r.sendBuffer(args) : r.send(args));
114
+ const decodeOr = (s) => (s == null ? null : binary ? decodeValue(s, read) : decode(text(s), read));
115
+ const store = {
116
+ /**
117
+ * Writes a geometry, a Feature, a geotini string or a binary value under
118
+ * id, and returns what it wrote: the string, or the value in a binary
119
+ * store. `point` overrides the centroid.
120
+ */
121
+ async set(k, input, o) {
122
+ k = id(k);
123
+ const s = write(input, to, read, binary);
124
+ const v = binary ? arg(s) : s;
125
+ const cmds = [hash ? ['HSET', hash, k, v] : ['SET', prefix + k, v]];
126
+ if (geoKey !== false) {
127
+ const p = o?.point ?? geoPoint(binary ? decodeValue(s, OWN) : decode(s, OWN));
128
+ if (p) {
129
+ if (!(p[0] >= -180 && p[0] <= 180 && p[1] >= -MAX_LAT && p[1] <= MAX_LAT)) throw new RangeError('A GEO point needs a longitude and a latitude within ±85.05112878');
130
+ cmds.push(['GEOADD', geoKey, String(p[0]), String(p[1]), k]);
131
+ } else cmds.push(['ZREM', geoKey, k]);
132
+ }
133
+ await r.transaction(cmds);
134
+ return s;
135
+ },
136
+ /** The geometry under id, or null. */
137
+ async get(k) {
138
+ return decodeOr(await fetch(getCmd(id(k))));
139
+ },
140
+ /** The string under id, or null. A binary store converts its value. */
141
+ async getString(k) {
142
+ if (!binary) return text(await r.send(getCmd(id(k))));
143
+ const b = await fetch(getCmd(id(k)));
144
+ return b == null ? null : fromValue(b, read);
145
+ },
146
+ /** The geometries under several ids, in order, null where there's none. */
147
+ async getMany(ids) {
148
+ if (!ids.length) return [];
149
+ const ks = ids.map(id);
150
+ const out = await fetch(hash ? ['HMGET', hash, ...ks] : ['MGET', ...ks.map((k) => prefix + k)]);
151
+ return out.map(decodeOr);
152
+ },
153
+ /** Removes the geometry under id and its point. */
154
+ async delete(k) {
155
+ k = id(k);
156
+ const cmds = [hash ? ['HDEL', hash, k] : ['DEL', prefix + k]];
157
+ if (geoKey !== false) cmds.push(['ZREM', geoKey, k]);
158
+ await r.transaction(cmds);
159
+ },
160
+ /**
161
+ * GEOSEARCH on the GEO set: from { lng, lat } or { member }, within
162
+ * `radius` or a `width` by `height` box, in `unit` (m, km, mi or ft;
163
+ * m by default), nearest first unless `order: 'DESC'`, at most `count`.
164
+ * Gives [{ id, distance }], and each geometry too with `withGeometry`.
165
+ * Redis 6.2 and newer.
166
+ */
167
+ async search(q) {
168
+ if (geoKey === false) throw new TypeError('This store has no GEO set');
169
+ const unit = q.unit ?? 'm';
170
+ const args = ['GEOSEARCH', geoKey];
171
+ if (q.member != null) args.push('FROMMEMBER', String(q.member));
172
+ else args.push('FROMLONLAT', String(q.lng), String(q.lat));
173
+ if (q.radius != null) args.push('BYRADIUS', String(q.radius), unit);
174
+ else args.push('BYBOX', String(q.width), String(q.height), unit);
175
+ args.push(q.order === 'DESC' ? 'DESC' : 'ASC');
176
+ if (q.count != null) args.push('COUNT', String(q.count), ...(q.any ? ['ANY'] : []));
177
+ args.push('WITHDIST');
178
+ const rows = (await r.send(args)).map((x) => ({ id: text(x[0]), distance: Number(text(x[1])) }));
179
+ if (q.withGeometry && rows.length) {
180
+ const gs = await store.getMany(rows.map((x) => x.id));
181
+ rows.forEach((x, i) => (x.geometry = gs[i]));
182
+ }
183
+ return rows;
184
+ },
185
+ };
186
+ return store;
187
+ }
188
+
189
+ /**
190
+ * The cache key for a geometry, a Feature or a geotini string: prefix
191
+ * ('geotini:cache:') and the canonical string at options.to, the settings
192
+ * your application fixes (a precision or encode's options). `to` is
193
+ * required: a key at the string's own settings would give one geometry
194
+ * several keys. A string is read with checksum, maxLength and maxPositions.
195
+ */
196
+ export function cacheKey(input, options) {
197
+ const to = options?.to;
198
+ if (to == null) throw new TypeError('cacheKey needs options.to, the settings every key is written at');
199
+ const prefix = options.prefix ?? 'geotini:cache:';
200
+ const t = typeof to === 'number' ? { precision: to } : to;
201
+ return prefix + write(input, t, reading(options));
202
+ }
203
+
204
+ /**
205
+ * The cached value for a geometry, or compute(geometry) stored under its
206
+ * cacheKey, with an expiry of `ttl` seconds when given. Values are strings:
207
+ * serialize anything else yourself.
208
+ */
209
+ export async function cached(client, input, compute, options) {
210
+ const r = driver(client), k = cacheKey(input, options);
211
+ const hit = await r.send(['GET', k]);
212
+ if (hit != null) return text(hit);
213
+ const v = await compute(decode(k.slice((options.prefix ?? 'geotini:cache:').length), OWN));
214
+ if (typeof v !== 'string') throw new TypeError('compute must return a string');
215
+ await r.send(options.ttl != null ? ['SET', k, v, 'EX', String(options.ttl)] : ['SET', k, v]);
216
+ return v;
217
+ }