@appweaver/skill 0.0.0-stage → 3.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.
@@ -0,0 +1,143 @@
1
+ # SMS
2
+
3
+ The SMS module sends text messages: the SMS 2FA codes, the phone verification codes, and any message of the
4
+ application. Its driver `TwilioSms` (provider `twilio`) of `@appweaver/twilio` calls the REST API of Twilio and is
5
+ selected when the package is installed. The `JsonSms` of core (provider `json`, selected by name only) writes the
6
+ messages into the log at `debug` (the `sms` logger) instead of sending them, for development and tests. Without a
7
+ driver, or with `SMS_PROVIDER=none`, no `SmsSender` and no `SmsService` are defined, the SMS 2FA method is unavailable,
8
+ and the phone verification routes are not registered.
9
+
10
+ ## SmsService
11
+
12
+ `SmsService` of `@appweaver/core` sends every message through the `sms` queue, so a message failing for a transient
13
+ reason is retried with the `queue.retryAttempts` and `queue.retryBackoff` of the queue. It is defined with an
14
+ `SmsSender` and a `Queue` (the in-memory one when no queue driver is installed), so inject it optionally:
15
+
16
+ ```ts
17
+ import { inject, SmsService } from '@appweaver/core';
18
+
19
+ const smsService = inject(SmsService, false); // undefined without an SMS sender
20
+ ```
21
+
22
+ | Method | Returns | Description |
23
+ | ------------------------------ | -------------------------------- | ------------------------------------------------------------------------------------------ |
24
+ | `sendSms(sms)` | `Promise<void>` | Queues the message and resolves once it is queued. |
25
+ | `sendSmsBulk(messages)` | `Promise<void>` | Queues the messages at once. A template message failing to render is logged and left out. |
26
+ | `sendSmsAndWait(sms)` | `Promise<boolean>` | Queues the message and resolves once it is sent, rejects with the error of its last retry. |
27
+ | `sendSmsBulkAndWait(messages)` | `Promise<{ success, error? }[]>` | Sends the messages and reports the result of each one, in their order. |
28
+ | `renderTemplateSms(sms)` | `Promise<SmsMessage>` | Renders a template message into the message to send, which the send methods do themselves. |
29
+
30
+ Every method takes an `SmsMessage` or a `TemplateSms`:
31
+
32
+ | Field | Type | Required | Description |
33
+ | ----------------- | ------------------------- | -------- | -------------------------------------------------------------------------------- |
34
+ | `to` | `string` | Yes | Recipient phone number in the E.164 format, i.e. `+385911234567` |
35
+ | `text` | `string` | Yes | The text, of an `SmsMessage` |
36
+ | `template` | `string` | Yes | The template without the format, of a `TemplateSms`, i.e. `sms/order-shipped` |
37
+ | `data` | `Record<string, any>` | No | The data to render the template with |
38
+ | `locale` | `string` | No | The locale to render the template in, `LOCALE_DEFAULT` by default |
39
+ | `from` | `string` | No | Sender, a phone number or an alphanumeric sender ID, `SMS_SENDER` by default |
40
+ | `providerOptions` | `Record<string, unknown>` | No | Options of the driver, i.e. the extra parameters of the Twilio Messages resource |
41
+
42
+ ```ts
43
+ await smsService.sendSms({
44
+ to: '+385911234567',
45
+ text: 'Your order has shipped.'
46
+ });
47
+
48
+ // Waits for the provider, i.e. to answer a request with a rejected number
49
+ await smsService.sendSmsAndWait({
50
+ to: user.phone,
51
+ template: 'sms/order-shipped',
52
+ data: { orderId: order.id },
53
+ locale: 'de'
54
+ });
55
+
56
+ const results = await smsService.sendSmsBulkAndWait(
57
+ customers.map((customer) => ({
58
+ to: customer.phone,
59
+ text: 'We are open on Sunday.'
60
+ }))
61
+ );
62
+ ```
63
+
64
+ The worker sends the queued message with the `SmsSender`, so an error of the driver fails the job with
65
+ `SMS_SEND_FAILED`: an `SmsError` of the driver is kept, and any other error is wrapped in one naming the selected
66
+ provider (`details.provider`, i.e. `twilio`). `sendSmsAndWait` sends the job with an ID of its own and receives its
67
+ result through the `PubSub` (`queue:sms:results`), so it resolves on whichever instance the worker sending the message
68
+ runs, once the message is sent or its last retry failed, rejecting with the `SmsError` of the job.
69
+
70
+ ### Templates
71
+
72
+ A `TemplateSms` is rendered from its `<template>.txt` template with the template engine of `@appweaver/handlebars`,
73
+ so it needs the package, and the text is trimmed with its whitespace collapsed into single spaces. A message without
74
+ the template fails with `TEMPLATE_NOT_FOUND`, and without a template engine with `CONFIGURATION_INVALID`. The templates
75
+ live in `TEMPLATE_PATH` like the email ones, and translate with `{{t "key"}}`:
76
+
77
+ ```hbs
78
+ {{! templates/sms/order-shipped.txt.hbs }}
79
+ {{t 'sms.orderShipped' orderId=orderId}}
80
+ ```
81
+
82
+ ### Account messages
83
+
84
+ The 2FA codes and the phone verification codes are sent with `sendSmsAndWait`, so a number the provider rejects fails
85
+ the request with `SMS_SEND_FAILED`. Each one renders the template of the application when it exists, otherwise the
86
+ `sms.*` translation, which the framework defines in English and `locales/<locale>.json` overrides:
87
+
88
+ | Template | Translation | Data |
89
+ | --------------------- | ------------------- | ------------------------------------- |
90
+ | `sms/two-factor-code` | `sms.twoFactorCode` | `code`, `appName`, `expiresInMinutes` |
91
+ | `sms/verify-phone` | `sms.verifyPhone` | `code`, `appName`, `expiresInMinutes` |
92
+
93
+ The translations take the minutes as `count`, i.e. `{count, plural, one {# minute} other {# minutes}}`. A project
94
+ created with the `sms` and `templates` modules of `@appweaver/create` gets both templates, and their English texts in
95
+ `locales/en.json` with the `locales` module.
96
+
97
+ ## Injecting SmsSender
98
+
99
+ The driver sends a message right away, outside of the queue:
100
+
101
+ ```ts
102
+ import { inject } from '@appweaver/core';
103
+ import { SmsSender } from '@appweaver/common';
104
+
105
+ const sender = inject(SmsSender, false);
106
+ await sender?.sendSms({ to: '+385911234567', text: 'Hello' });
107
+ ```
108
+
109
+ The health check of `TwilioSms` reads the status page of Twilio (`SMS_TWILIO_STATUS_URL`), reporting the sender down
110
+ during a major or critical outage.
111
+
112
+ ### A driver of another provider
113
+
114
+ A driver of another service (Infobip, Vonage, ...) extends `SmsSender` (`sendSms`, `checkHealth`), sends a message
115
+ without `from` from the default sender of the service, and throws an `SmsError` (`SMS_SEND_FAILED` with its
116
+ `provider` name, and the `status` and `providerCode` of the service) when the service rejects a message.
117
+ `npm create @appweaver module <package> -- --contract sms` scaffolds it as a module package with its `sms.<name>`
118
+ config section, tested with `testSmsContract`:
119
+
120
+ ```sh
121
+ npm create @appweaver module @acme/appweaver-vonage "Vonage SMS sender" -- --contract sms
122
+ ```
123
+
124
+ An application installs it with `weaver module add @acme/appweaver-vonage`, which selects it with `sms.provider`
125
+ `auto` (or `"sms": { "provider": "vonage" }` beside another SMS driver), see [modules](./modules.md#package-modules).
126
+
127
+ ## Configuration
128
+
129
+ See the [SMS section](./configuration.md#sms-sms_) of the configuration: `SMS_PROVIDER`, `SMS_SENDER` and the
130
+ `SMS_TWILIO_*` keys. A test environment selects the `json` provider, which a project created with the `sms` module also
131
+ does in the `dev` environment:
132
+
133
+ ```json
134
+ {
135
+ "environments": {
136
+ "test": {
137
+ "sms": {
138
+ "provider": "json"
139
+ }
140
+ }
141
+ }
142
+ }
143
+ ```
@@ -0,0 +1,197 @@
1
+ # Spatial fields and spatial queries
2
+
3
+ The `spatial` section of a resource model declares fields holding geometries: the location of a store, the delivery area
4
+ of a restaurant, the route of a delivery. A spatial field is read and written like a scalar, as a GeoJSON geometry (RFC
5
+ 7946, WGS 84 longitude and latitude), and filtered with the operators `_near`, `_within`, `_withinBox` and
6
+ `_intersects`, in every route and `ResourceService` method taking a filter.
7
+
8
+ ## Declaring spatial fields
9
+
10
+ ```ts
11
+ import { createModel } from '@appweaver/data';
12
+
13
+ export default createModel({
14
+ name: 'Store',
15
+ scalars: {
16
+ name: { type: 'string', maxLength: 255 }
17
+ },
18
+ spatial: {
19
+ location: { type: 'point', description: 'Where the store is' },
20
+ deliveryArea: { type: 'polygon', required: false },
21
+ route: { type: 'lineString', required: false, index: false }
22
+ }
23
+ });
24
+ ```
25
+
26
+ | Spatial field option | Description |
27
+ |----------------------|--------------------------------------------------------------------------------------------------------|
28
+ | `type` | `point`, `multiPoint`, `lineString`, `multiLineString`, `polygon`, `multiPolygon`, or `geometry` (any) |
29
+ | `required` | Required on creation, `false` makes it nullable (default: `true`, like a scalar) |
30
+ | `hidden` | Left out of the API input and output, the filters and the sorts |
31
+ | `index` | Index the field for the spatial queries (default: `true`) |
32
+ | `description` | The description of the field in the OpenAPI specification |
33
+ | `example` | The example of the field in the OpenAPI specification |
34
+
35
+ A spatial field takes no name of another field of the model, nor of the names derived from its own: its columns
36
+ (`<field>MinLng`, `<field>MinLat`, `<field>MaxLng`, `<field>MaxLat`, `<field>Geom`) and its `<field>Distance`. Its name
37
+ can be used in the `omit` and `pick` of the `read`, `create` and `update` options. After adding or changing a spatial
38
+ field, run `weaver generate` and `weaver migration new <name>`.
39
+
40
+ ## Values
41
+
42
+ A value is a GeoJSON geometry of the type of the field, its positions `[lng, lat]` in degrees:
43
+
44
+ ```json
45
+ { "type": "Point", "coordinates": [15.9819, 45.815] }
46
+ { "type": "Polygon", "coordinates": [[[15.9, 45.75], [16.1, 45.75], [16.1, 45.9], [15.9, 45.9], [15.9, 45.75]]] }
47
+ ```
48
+
49
+ - A `point` (or `geometry`) field also takes `{ "lat": 45.815, "lng": 15.9819 }`, stored and returned as a GeoJSON
50
+ point.
51
+ - A polygon ring has at least 4 positions and ends with its first one, a line string has at least 2.
52
+ - A geometry with an altitude, or of more positions than `spatial.maxVertices` (`10000`), is rejected.
53
+ - An invalid value fails with `SPATIAL_INVALID_GEOMETRY` (400), also when written through the Prisma client directly,
54
+ i.e. in a seeder.
55
+ - The generated types use the geometry types of `@appweaver/common`: `location: GeoPoint` in the model,
56
+ `location: GeoPoint | GeoLatLng` in its create and update types (`GeoMultiPoint`, `GeoLineString`,
57
+ `GeoMultiLineString`, `GeoPolygon`, `GeoMultiPolygon` and `GeoGeometry` for the other field types).
58
+
59
+ ## Spatial filters
60
+
61
+ The operators of a spatial field combine with every other filter ([resources.md](./resources.md#query-filters)), in the
62
+ logical operators (`_and`, `_or`, `_not`, `_nor`) and in the filters of the relations. Distances are in meters, measured
63
+ on a sphere of the mean radius of the Earth.
64
+
65
+ | Operator | Value | Matches the geometries |
66
+ |---------------|----------------------------------------|------------------------------------------------------------|
67
+ | `_near` | `{ point, maxDistance, minDistance? }` | Within `maxDistance` of the point (and from `minDistance`) |
68
+ | `_within` | A GeoJSON `Polygon` or `MultiPolygon` | Covered by it, its boundary included |
69
+ | `_withinBox` | `[minLng, minLat, maxLng, maxLat]` | Covered by the box |
70
+ | `_intersects` | Any GeoJSON geometry | Sharing at least a point with it |
71
+ | `_exists` | `true` / `false` | With a value / without one (also `field: null`) |
72
+
73
+ The `point` of `_near` is a position `[lng, lat]`, a `{ lat, lng }` object or a GeoJSON point. The distance of a
74
+ geometry other than a point is the one to its nearest point, `0` inside a polygon. A `_withinBox` whose `minLng` is
75
+ above its `maxLng` crosses the antimeridian, i.e. `[170, -20, -170, -10]`, as the viewport of a map does.
76
+
77
+ ```ts
78
+ // The stores within 5 km, nearest first
79
+ const { items } = await storeService.query({
80
+ filter: {
81
+ location: { _near: { point: { lat: 45.8, lng: 15.97 }, maxDistance: 5000 } }
82
+ },
83
+ sort: 'location'
84
+ });
85
+ items[0].locationDistance; // 412.7
86
+
87
+ // The stores of a map viewport, delivering to an address
88
+ await storeService.query({
89
+ filter: {
90
+ location: { _withinBox: [15.9, 45.7, 16.1, 45.9] },
91
+ deliveryArea: { _intersects: { type: 'Point', coordinates: [16.0, 45.8] } }
92
+ }
93
+ });
94
+
95
+ // The nearest store
96
+ const nearest = await storeService.single(
97
+ { location: { _near: { point: [15.97, 45.8], maxDistance: 50_000 } } },
98
+ 'location'
99
+ );
100
+ ```
101
+
102
+ ```http
103
+ POST /api/stores/query
104
+ { "filter": { "location": { "_near": { "point": [15.97, 45.8], "maxDistance": 5000 } } }, "sort": "location" }
105
+ ```
106
+
107
+ ### Distance
108
+
109
+ A record matched by a `_near` operator on the top level of the filter carries its distance in meters as
110
+ `<field>Distance` (`locationDistance`), an optional number of the response and of the generated types. It is left out
111
+ with its field by the `read` options and for a hidden field.
112
+
113
+ Sorting by a spatial field (`sort: 'location'`, `'-location'` or `{ location: 'desc' }`) orders the records by that
114
+ distance, nearest first, the ties by id. It takes no other sort field, and without a `_near` filter on the field it
115
+ fails with `RESOURCE_INVALID_SORT`. The pages, the cursors and the total count work as on any other sort.
116
+
117
+ ### How the operators run, and their limits
118
+
119
+ - `_withinBox` and `_exists` are conditions of the bounding box columns of the field, run by the database with the
120
+ rest of the query, whatever the number of records they match.
121
+ - `_near`, `_within` and `_intersects` are first resolved into the ids of the records they match, by the provider. An
122
+ operator matching more records than `spatial.maxCandidates` (`10000`, at most `2000` on SQL Server) fails with
123
+ `SPATIAL_TOO_MANY_CANDIDATES` (400). The limit counts the records matching the operator alone, before the other
124
+ conditions and the read restrictions, so narrow it down with a smaller radius or polygon.
125
+ - An invalid operator fails with `SPATIAL_INVALID_FILTER` (400).
126
+ - `_within` and `_intersects` take the longitude and latitude as planar coordinates, like the `geometry` type of
127
+ PostGIS: an edge of a polygon is a straight line in degrees, not a great circle. A stored geometry or a polygon
128
+ crossing the antimeridian (±180°) is not supported, while `_near` and `_withinBox` work across it.
129
+
130
+ ## Storage and providers
131
+
132
+ Every spatial field is stored in three or four columns, on every database:
133
+
134
+ | Column | Holds |
135
+ |----------------------------|------------------------------------------------------------------------------------|
136
+ | `<field>` | The GeoJSON (`Json`, a `NVARCHAR(MAX)` serialized by the data layer on SQL Server) |
137
+ | `<field>MinLng` … `MaxLat` | Its bounding box, four nullable floats with an index on the minimums |
138
+ | `<field>Geom` | With the `postgis` provider, a `geometry(<Type>, 4326)` with a GiST index |
139
+
140
+ The data layer writes the bounding box on every write through the Prisma client and leaves it out of the results, so
141
+ a record written with plain SQL needs it written too.
142
+
143
+ The `spatial.provider` config selects how `_near`, `_within` and `_intersects` are matched. It changes the generated
144
+ schema, so run `weaver generate` and create a migration after changing it.
145
+
146
+ | Provider | Databases | Matches with |
147
+ |------------|------------|-------------------------------------------------------------------------------------------------|
148
+ | `postgis` | PostgreSQL | The functions of PostGIS on the geometry column (`ST_DWithin`, `ST_CoveredBy`, `ST_Intersects`) |
149
+ | `database` | All | The bounding box narrows the records in the database, the application matches each geometry |
150
+
151
+ `auto` (the default) selects `postgis` on PostgreSQL and `database` on SQLite, MySQL and SQL Server. Set it to
152
+ `database` on a PostgreSQL server without PostGIS.
153
+
154
+ **PostGIS**: the generated schema declares the extension (`extensions = [postgis]`, with the `postgresqlExtensions`
155
+ preview feature of Prisma), so the first migration runs `CREATE EXTENSION IF NOT EXISTS "postgis"`, which needs a
156
+ server with PostGIS installed, i.e. the `postgis/postgis` Docker image (or `timescale/timescaledb-ha`, which has both
157
+ TimescaleDB and PostGIS). The geometry column is written by the trigger `<table>_geo_sync` of its table, on an insert
158
+ and on an update changing the GeoJSON, so a write with plain SQL keeps it in line too. `SpatialService` creates the
159
+ trigger at startup when it is missing or the spatial fields of the model changed, and then writes the geometries missing,
160
+ within `spatial.setupTimeout`. A start with the triggers in place changes nothing in the database. `weaver migrate`
161
+ sets the triggers up too, after the migrations, as the user of `database.migrationUrl`.
162
+
163
+ - The trigger is not part of the Prisma schema, so it causes no migration drift, and a migration can drop a spatial field
164
+ before the next start replaces it.
165
+ - Setting a trigger up needs the right to create functions and to own the table. With an application user that can
166
+ only read and write the data (see [database](./database.md#separate-migration-and-application-users)), `weaver
167
+ migrate` sets them up, and a start finding a trigger out of date fails with `CONFIGURATION_INVALID`, asking to run
168
+ `weaver migrate`.
169
+ - A model that lost its spatial fields, or a switch to the `database` provider, leaves a trigger doing nothing: drop it
170
+ with `DROP FUNCTION "<table>_geo_sync" CASCADE`.
171
+
172
+ ## Configuration
173
+
174
+ | Key | Env | Default | Description |
175
+ |-------------------------|--------------------------|---------|----------------------------------------------------------------|
176
+ | `spatial.provider` | `SPATIAL_PROVIDER` | `auto` | `auto`, `postgis` or `database` |
177
+ | `spatial.maxCandidates` | `SPATIAL_MAX_CANDIDATES` | `10000` | Maximum records a `_near`, `_within` or `_intersects` matches |
178
+ | `spatial.maxVertices` | `SPATIAL_MAX_VERTICES` | `10000` | Maximum positions of a geometry, written or in a filter |
179
+ | `spatial.setupTimeout` | `SPATIAL_SETUP_TIMEOUT` | `60000` | Milliseconds the `postgis` provider takes to set up at startup |
180
+
181
+ ## Programmatic use
182
+
183
+ `SpatialService` of `@appweaver/data` finds the records of a model matching a condition, nearest first for a `near`
184
+ one (`match`). The helpers of `@appweaver/common` work on GeoJSON values: `normalizeGeometry`, `geometryBox`,
185
+ `spatialDistance` (haversine, meters), `geometryDistance`, `geometryCoveredBy` and `geometryIntersects`.
186
+
187
+ ```ts
188
+ import { inject } from '@appweaver/core';
189
+ import { SpatialService } from '@appweaver/data';
190
+
191
+ const matches = await inject(SpatialService).match('Store', 'location', {
192
+ operator: 'near',
193
+ point: [15.97, 45.8],
194
+ maxDistance: 2000
195
+ });
196
+ // [{ id: 3, distance: 412.7 }, { id: 1, distance: 1890.2 }]
197
+ ```