@harperfast/skills 1.6.1 → 1.8.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/dist/index.d.ts +1 -0
- package/dist/index.js +14 -12
- package/harper-best-practices/AGENTS.md +1127 -422
- package/harper-best-practices/SKILL.md +25 -20
- package/harper-best-practices/rules/automatic-apis.md +140 -19
- package/harper-best-practices/rules/caching.md +133 -22
- package/harper-best-practices/rules/checking-authentication.md +138 -149
- package/harper-best-practices/rules/creating-harper-apps.md +5 -2
- package/harper-best-practices/rules/deploying-to-harper-fabric.md +96 -78
- package/harper-best-practices/rules/load-env.md +100 -0
- package/harper-best-practices/rules/logging.md +153 -78
- package/harper-best-practices/rules/querying-rest-apis.md +189 -16
- package/harper-best-practices/rules/real-time-apps.md +79 -22
- package/harper-best-practices/rules/schema-design-tooling.md +132 -41
- package/harper-best-practices/rules/typescript-type-stripping.md +47 -17
- package/harper-best-practices/rules/vector-indexing.md +12 -12
- package/harper-best-practices/rules.manifest.yaml +135 -13
- package/package.json +1 -1
|
@@ -1,94 +1,169 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: logging
|
|
3
|
-
description:
|
|
3
|
+
description: >-
|
|
4
|
+
Best practices for logging in Harper, including console capture, the granular
|
|
5
|
+
logger interface, and programmatic log retrieval.
|
|
4
6
|
metadata:
|
|
5
|
-
mode:
|
|
7
|
+
mode: generate
|
|
8
|
+
sources:
|
|
9
|
+
- reference/v5/logging/overview.md
|
|
10
|
+
- reference/v5/logging/api.md
|
|
11
|
+
sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819
|
|
12
|
+
inputHash: 46cd384598304e3b
|
|
6
13
|
---
|
|
7
14
|
|
|
8
|
-
# Logging
|
|
15
|
+
# Harper Logging
|
|
9
16
|
|
|
10
|
-
|
|
17
|
+
Instructions for the agent to follow when implementing logging in Harper applications, including direct logger usage, tagged loggers, and console capture behavior.
|
|
11
18
|
|
|
12
|
-
##
|
|
19
|
+
## When to Use
|
|
13
20
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
21
|
+
Apply this rule when writing any JavaScript component, plugin, or resource that needs to emit structured log entries, filter logs by component, or capture existing `console.log` output into Harper's log system. Use it whenever you need to understand log levels, log entry format, or the `logger` global API.
|
|
22
|
+
|
|
23
|
+
## How It Works
|
|
24
|
+
|
|
25
|
+
1. **Use the `logger` global directly** — `logger` is available in all JavaScript components without any imports. Call the method matching the desired severity level:
|
|
26
|
+
|
|
27
|
+
```javascript
|
|
28
|
+
logger.trace('detailed trace message');
|
|
29
|
+
logger.debug('debug info', { someContext: 'value' });
|
|
30
|
+
logger.info('informational message');
|
|
31
|
+
logger.warn('potential issue');
|
|
32
|
+
logger.error('error occurred', error);
|
|
33
|
+
logger.fatal('fatal error');
|
|
34
|
+
logger.notify('server is ready');
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Only entries at or above the configured `logging.level` (or `logging.external.level`) are written to `hdb.log`.
|
|
38
|
+
|
|
39
|
+
2. **Create a tagged logger with `withTag(`** — Call `logger.withTag(tag)` once per module or class to get a `TaggedLogger` scoped to that tag. This prefixes every log entry with the tag, making log output filterable by component.
|
|
40
|
+
|
|
41
|
+
```javascript
|
|
42
|
+
const log = logger.withTag('my-resource');
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
Because `TaggedLogger` methods for disabled levels are `null`, always use optional chaining (`?.`) when calling them:
|
|
46
|
+
|
|
47
|
+
```javascript
|
|
48
|
+
log.debug?.('Fetching record', { id });
|
|
49
|
+
log.warn?.('Record not found', { id });
|
|
50
|
+
log.error?.('Failed to update record', err);
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`TaggedLogger` does not have a `withTag()` method.
|
|
54
|
+
|
|
55
|
+
3. **Understand the interface contracts** — `MainLogger` always has all methods defined:
|
|
56
|
+
|
|
57
|
+
```typescript
|
|
58
|
+
interface MainLogger {
|
|
59
|
+
trace(...messages: any[]): void;
|
|
60
|
+
debug(...messages: any[]): void;
|
|
61
|
+
info(...messages: any[]): void;
|
|
62
|
+
warn(...messages: any[]): void;
|
|
63
|
+
error(...messages: any[]): void;
|
|
64
|
+
fatal(...messages: any[]): void;
|
|
65
|
+
notify(...messages: any[]): void;
|
|
66
|
+
withTag(tag: string): TaggedLogger;
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
`TaggedLogger` methods may be `null`:
|
|
71
|
+
|
|
72
|
+
```typescript
|
|
73
|
+
interface TaggedLogger {
|
|
74
|
+
trace: ((...messages: any[]) => void) | null;
|
|
75
|
+
debug: ((...messages: any[]) => void) | null;
|
|
76
|
+
info: ((...messages: any[]) => void) | null;
|
|
77
|
+
warn: ((...messages: any[]) => void) | null;
|
|
78
|
+
error: ((...messages: any[]) => void) | null;
|
|
79
|
+
fatal: ((...messages: any[]) => void) | null;
|
|
80
|
+
notify: ((...messages: any[]) => void) | null;
|
|
81
|
+
}
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
4. **Know the log levels** — From least to most severe:
|
|
85
|
+
|
|
86
|
+
| Level | Description |
|
|
87
|
+
| -------- | -------------------------------------------------------------------- |
|
|
88
|
+
| `trace` | Highly detailed internal execution tracing. |
|
|
89
|
+
| `debug` | Diagnostic information useful during development. |
|
|
90
|
+
| `info` | General operational events. |
|
|
91
|
+
| `warn` | Potential issues that don't prevent normal operation. |
|
|
92
|
+
| `error` | Errors that affect specific operations. |
|
|
93
|
+
| `fatal` | Critical errors causing process termination. |
|
|
94
|
+
| `notify` | Important operational milestones. Always logged regardless of level. |
|
|
95
|
+
|
|
96
|
+
The default log level is `warn`. Setting a level includes that level and all more-severe levels.
|
|
97
|
+
|
|
98
|
+
5. **Enable console capture when porting existing code** — When `logging.console: true` is set, writes via `console.log`, `console.warn`, `console.error`, etc. are appended verbatim to `hdb.log`. Captured lines do **not** pass through `logger`'s level filter. Prefer `logger` directly in production code so that level filtering and tagging apply. Console capture is intended as a convenience for porting existing code and for debugging.
|
|
99
|
+
|
|
100
|
+
6. **Know where logs are written** — All standard log output goes to `<ROOTPATH>/log/hdb.log` (default: `~/hdb/log/hdb.log`). To also log to `stdout`/`stderr`, set `logging.stdStreams: true`.
|
|
101
|
+
|
|
102
|
+
## Examples
|
|
103
|
+
|
|
104
|
+
### Basic logging in a resource
|
|
105
|
+
|
|
106
|
+
```javascript
|
|
107
|
+
export class MyResource extends Resource {
|
|
108
|
+
async get(id) {
|
|
109
|
+
logger.debug('Fetching record', { id });
|
|
110
|
+
const record = await super.get(id);
|
|
111
|
+
if (!record) {
|
|
112
|
+
logger.warn('Record not found', { id });
|
|
113
|
+
}
|
|
114
|
+
return record;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async put(record) {
|
|
118
|
+
logger.info('Updating record', { id: record.id });
|
|
119
|
+
try {
|
|
120
|
+
return await super.put(record);
|
|
121
|
+
} catch (err) {
|
|
122
|
+
logger.error('Failed to update record', err);
|
|
123
|
+
throw err;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
49
127
|
```
|
|
50
128
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
129
|
+
### Tagged logging with `withTag()`
|
|
130
|
+
|
|
131
|
+
```javascript
|
|
132
|
+
const log = logger.withTag('my-resource');
|
|
133
|
+
|
|
134
|
+
export class MyResource extends Resource {
|
|
135
|
+
async get(id) {
|
|
136
|
+
log.debug?.('Fetching record', { id });
|
|
137
|
+
const record = await super.get(id);
|
|
138
|
+
if (!record) {
|
|
139
|
+
log.warn?.('Record not found', { id });
|
|
140
|
+
}
|
|
141
|
+
return record;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async put(record) {
|
|
145
|
+
log.info?.('Updating record', { id: record.id });
|
|
146
|
+
try {
|
|
147
|
+
return await super.put(record);
|
|
148
|
+
} catch (err) {
|
|
149
|
+
log.error?.('Failed to update record', err);
|
|
150
|
+
throw err;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
72
153
|
}
|
|
73
154
|
```
|
|
74
155
|
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
- `limit`: Number of log entries to return.
|
|
78
|
-
- `start`: Offset for pagination.
|
|
79
|
-
- `level`: Filter by log level (`info`, `error`, `warn`, `debug`, `trace`, `notify`, `fatal`, `stdout`, `stderr`).
|
|
80
|
-
- `from`: ISO 8601 timestamp to start reading from.
|
|
81
|
-
- `until`: ISO 8601 timestamp to stop reading at.
|
|
82
|
-
- `order`: Sort order, either `asc` or `desc`.
|
|
83
|
-
- `replicated`: (Boolean) Include logs from replicated nodes in a cluster.
|
|
156
|
+
Tagged entries appear in `hdb.log` with the tag in the header:
|
|
84
157
|
|
|
85
|
-
|
|
158
|
+
```
|
|
159
|
+
2023-03-09T14:25:05.269Z [info] [my-resource]: Updating record
|
|
160
|
+
```
|
|
86
161
|
|
|
87
|
-
|
|
162
|
+
## Notes
|
|
88
163
|
|
|
89
|
-
-
|
|
90
|
-
- `
|
|
91
|
-
- `
|
|
92
|
-
- `
|
|
93
|
-
-
|
|
94
|
-
- `
|
|
164
|
+
- All log output is written to `<ROOTPATH>/log/hdb.log`. The `logger` global writes to this file at the configured `logging.external` level.
|
|
165
|
+
- Log entry format for `logger`: `<timestamp> [<level>] [<thread>/<id>]: <message>`
|
|
166
|
+
- Log entry format for `TaggedLogger`: `<timestamp> [<level>] [<tag>]: <message>`
|
|
167
|
+
- `console.log` output is only forwarded to `hdb.log` when `logging.console: true` is explicitly set; it is not forwarded by default.
|
|
168
|
+
- When logging to standard streams, run Harper in the foreground (`harper`, not `harper start`).
|
|
169
|
+
- `TaggedLogger` is bound to the configured log level at creation time — always use `?.` on its methods.
|
|
@@ -1,29 +1,202 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: querying-rest-apis
|
|
3
|
-
description: How to use query parameters to filter, sort, and paginate Harper REST APIs.
|
|
3
|
+
description: 'How to use query parameters to filter, sort, and paginate Harper REST APIs.'
|
|
4
4
|
metadata:
|
|
5
|
-
mode:
|
|
5
|
+
mode: generate
|
|
6
|
+
sources:
|
|
7
|
+
- reference/v5/rest/querying.md
|
|
8
|
+
sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819
|
|
9
|
+
inputHash: 9f8c981a629ef606
|
|
6
10
|
---
|
|
7
11
|
|
|
8
12
|
# Querying REST APIs
|
|
9
13
|
|
|
10
|
-
Instructions for the agent to
|
|
14
|
+
Instructions for the agent to filter, sort, select, and paginate Harper REST API collections using URL query parameters.
|
|
11
15
|
|
|
12
16
|
## When to Use
|
|
13
17
|
|
|
14
|
-
|
|
18
|
+
Apply this rule when building or modifying code that queries Harper REST endpoints with filtering, sorting, field selection, or pagination. Use it whenever constructing URLs against collection paths exposed by Harper's automatic REST interface (see [automatic-apis.md](automatic-apis.md)).
|
|
15
19
|
|
|
16
20
|
## How It Works
|
|
17
21
|
|
|
18
|
-
1. **
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
22
|
+
1. **Filter by attribute**: Add query parameters matching attribute names and values. The queried attribute must be indexed.
|
|
23
|
+
|
|
24
|
+
```
|
|
25
|
+
GET /Product/?category=software
|
|
26
|
+
GET /Product/?category=software&inStock=true
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
2. **Apply comparison operators (FIQL syntax)**: Use FIQL operators directly in query parameter values.
|
|
30
|
+
|
|
31
|
+
| Operator | Meaning |
|
|
32
|
+
| ------------ | -------------------------------------- |
|
|
33
|
+
| `==` | Equal |
|
|
34
|
+
| `=lt=` | Less than |
|
|
35
|
+
| `=le=` | Less than or equal |
|
|
36
|
+
| `=gt=` | Greater than |
|
|
37
|
+
| `=ge=` | Greater than or equal |
|
|
38
|
+
| `=ne=`, `!=` | Not equal |
|
|
39
|
+
| `=ct=` | Contains (strings) |
|
|
40
|
+
| `=sw=` | Starts with (strings) |
|
|
41
|
+
| `=ew=` | Ends with (strings) |
|
|
42
|
+
| `=`, `===` | Strict equality (no type conversion) |
|
|
43
|
+
| `!==` | Strict inequality (no type conversion) |
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
GET /Product/?price=gt=100
|
|
47
|
+
GET /Product/?price=le=20
|
|
48
|
+
GET /Product/?name==Keyboard*
|
|
49
|
+
GET /Product/?category=software&price=gt=100&price=lt=200
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
For date fields, URL-encode colons as `%3A`:
|
|
53
|
+
|
|
54
|
+
```
|
|
55
|
+
GET /Product/?listDate=gt=2017-03-08T09%3A30%3A00.000Z
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
3. **Chain conditions for range queries**: Omit the attribute name on the second condition to apply it to the same attribute. Only `gt`/`ge` combined with `lt`/`le` is supported.
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
GET /Product/?price=gt=100<=200
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
4. **Combine conditions with OR logic**: Use `|` instead of `&`.
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
GET /Product/?rating=5|featured=true
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
5. **Group conditions**: Use parentheses or square brackets to control order of operations. Prefer square brackets when constructing queries from user input, since standard URI encoding safely encodes `[` and `]`.
|
|
71
|
+
|
|
72
|
+
```
|
|
73
|
+
GET /Product/?rating=5|(price=gt=100&price=lt=200)
|
|
74
|
+
GET /Product/?rating=5&[tag=fast|tag=scalable|tag=efficient]
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Construct grouped queries from JavaScript:
|
|
78
|
+
|
|
79
|
+
```javascript
|
|
80
|
+
let url = `/Product/?rating=5&[${tags.map(encodeURIComponent).join('|')}]`;
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
6. **Select specific properties with `select(`**: Use `select()` to control which fields are returned.
|
|
84
|
+
|
|
85
|
+
| Syntax | Returns |
|
|
86
|
+
| -------------------------------------- | ------------------------------------------- |
|
|
87
|
+
| `?select(property)` | Values of a single property directly |
|
|
88
|
+
| `?select(property1,property2)` | Objects with only the specified properties |
|
|
89
|
+
| `?select([property1,property2])` | Arrays of property values |
|
|
90
|
+
| `?select(property1,)` | Objects with a single specified property |
|
|
91
|
+
| `?select(property{subProp1,subProp2})` | Nested objects with specific sub-properties |
|
|
92
|
+
|
|
93
|
+
```
|
|
94
|
+
GET /Product/?category=software&select(name)
|
|
95
|
+
GET /Product/?brand.name=Microsoft&select(name,brand{name})
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
7. **Limit results with `limit(`**: Use `limit(end)` or `limit(start,end)` to paginate.
|
|
99
|
+
|
|
100
|
+
```
|
|
101
|
+
GET /Product/?rating=gt=3&inStock=true&select(rating,name)&limit(20)
|
|
102
|
+
GET /Product/?rating=gt=3&limit(10,30)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
8. **Sort results with `sort(`**: Use `sort(property)` or `sort(+property,-property,...)`. Prefix `+` or no prefix = ascending; `-` = descending.
|
|
106
|
+
|
|
107
|
+
```
|
|
108
|
+
GET /Product/?rating=gt=3&sort(+name)
|
|
109
|
+
GET /Product/?sort(+rating,-price)
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
9. **Query across relationships**: Use dot-syntax to filter by related table attributes. Relationships must be defined in the schema using `@relation`.
|
|
113
|
+
|
|
114
|
+
```
|
|
115
|
+
GET /Product/?brand.name=Microsoft
|
|
116
|
+
GET /Brand/?products.name=Keyboard
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Use `select()` to include relationship attributes in the response (they are not included by default):
|
|
120
|
+
|
|
121
|
+
```
|
|
122
|
+
GET /Product/?brand.name=Microsoft&select(name,brand{name})
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
10. **Access a specific property by URL**: Append the property name with dot syntax to the record ID. Only works for properties declared in the schema.
|
|
126
|
+
```
|
|
127
|
+
GET /MyTable/123.propertyName
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
## Examples
|
|
131
|
+
|
|
132
|
+
**Range filter with select and limit:**
|
|
133
|
+
|
|
134
|
+
```
|
|
135
|
+
GET /Product/?category=software&price=gt=100&price=lt=200&select(name,price)&limit(20)
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
**Sort descending with multiple fields:**
|
|
139
|
+
|
|
140
|
+
```
|
|
141
|
+
GET /Product/?sort(+rating,-price)
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
**OR logic with grouping:**
|
|
145
|
+
|
|
146
|
+
```
|
|
147
|
+
GET /Product/?price=lt=100|[rating=5&[tag=fast|tag=scalable|tag=efficient]&inStock=true]
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
**Relationship join with nested select:**
|
|
151
|
+
|
|
152
|
+
```
|
|
153
|
+
GET /Product/?brand.name=Microsoft&select(name,brand{name,id})
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
**Schema defining a relationship for join queries:**
|
|
157
|
+
|
|
158
|
+
```graphql
|
|
159
|
+
type Product @table @export {
|
|
160
|
+
id: Long @primaryKey
|
|
161
|
+
name: String
|
|
162
|
+
brandId: Long @indexed
|
|
163
|
+
brand: Brand @relation(from: "brandId")
|
|
164
|
+
}
|
|
165
|
+
type Brand @table @export {
|
|
166
|
+
id: Long @primaryKey
|
|
167
|
+
name: String
|
|
168
|
+
products: [Product] @relation(to: "brandId")
|
|
169
|
+
}
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
**Many-to-many relationship query:**
|
|
173
|
+
|
|
174
|
+
```graphql
|
|
175
|
+
type Product @table @export {
|
|
176
|
+
id: Long @primaryKey
|
|
177
|
+
name: String
|
|
178
|
+
resellerIds: [Long] @indexed
|
|
179
|
+
resellers: [Reseller] @relation(from: "resellerId")
|
|
180
|
+
}
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
```
|
|
184
|
+
GET /Product/?resellers.name=Cool Shop&select(id,name,resellers{name,id})
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
**Type conversion with explicit prefix:**
|
|
188
|
+
|
|
189
|
+
```
|
|
190
|
+
GET /Product/?price==number:123
|
|
191
|
+
GET /Product/?active==boolean:true
|
|
192
|
+
GET /Product/?listDate==date:2024-01-05T20%3A07%3A27.955Z
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
## Notes
|
|
196
|
+
|
|
197
|
+
- Only indexed attributes can be used as the primary filter; additional unindexed attributes can be combined with `&` once at least one indexed attribute is present.
|
|
198
|
+
- For null value queries, use `?attribute=null`. Indexes must have been created with null indexing support; existing indexes must be removed and re-added to support null queries.
|
|
199
|
+
- FIQL comparators (`==`, `!=`, `=gt=`, etc.) apply automatic type conversion based on value syntax or schema-declared type. Strict operators (`=`, `===`, `!==`) skip automatic type conversion.
|
|
200
|
+
- Filtering by a related attribute produces INNER JOIN behavior (only records with a matching related record are returned). Using `select()` on a relationship without a filter produces LEFT JOIN behavior.
|
|
201
|
+
- The array order of foreign key values in many-to-many relationships is preserved when resolving the relationship.
|
|
202
|
+
- See [automatic-apis.md](automatic-apis.md) for how Harper tables are automatically exposed as REST endpoints.
|
|
@@ -2,44 +2,101 @@
|
|
|
2
2
|
name: real-time-apps
|
|
3
3
|
description: How to build real-time features in Harper using WebSockets and Pub/Sub.
|
|
4
4
|
metadata:
|
|
5
|
-
mode:
|
|
5
|
+
mode: generate
|
|
6
|
+
sources:
|
|
7
|
+
- reference/v5/rest/websockets.md
|
|
8
|
+
sourceCommit: b7fbddadd42eb4487190b650a9abc4bcfeef5819
|
|
9
|
+
inputHash: a8afd4d3a52f77ba
|
|
6
10
|
---
|
|
7
11
|
|
|
8
|
-
# Real-
|
|
12
|
+
# Real-Time Apps with WebSockets and Pub/Sub
|
|
9
13
|
|
|
10
|
-
Instructions for the agent to follow when building real-time
|
|
14
|
+
Instructions for the agent to follow when building real-time features in Harper using WebSockets and Pub/Sub.
|
|
11
15
|
|
|
12
16
|
## When to Use
|
|
13
17
|
|
|
14
|
-
|
|
18
|
+
Apply this rule when implementing any feature that requires real-time bidirectional communication, live data streaming, or push-based updates in a Harper application. This includes chat, live dashboards, sensor feeds, and any scenario where clients must receive resource changes as they happen.
|
|
15
19
|
|
|
16
20
|
## How It Works
|
|
17
21
|
|
|
18
|
-
1. **
|
|
19
|
-
2. **Implement `connect` in a Resource**: For custom bi-directional logic, implement the `connect` method.
|
|
20
|
-
3. **Use Pub/Sub**: Use `tables.TableName.subscribe(query)` to listen for specific data changes and stream them to the client.
|
|
21
|
-
4. **Handle SSE**: Ensure your `connect` method gracefully handles cases where `incomingMessages` is null (Server-Sent Events).
|
|
22
|
-
5. **Connect from Client**: Use standard WebSockets (`new WebSocket('wss://...')`) to connect to your resource endpoint. Ensure you use the appropriate scheme (`ws://` for HTTP, `wss://` for HTTPS).
|
|
22
|
+
1. **Enable WebSocket support**: WebSocket support is enabled automatically when the `rest` plugin is enabled. To explicitly disable it, set the following in your config:
|
|
23
23
|
|
|
24
|
-
|
|
24
|
+
```yaml
|
|
25
|
+
rest:
|
|
26
|
+
webSocket: false
|
|
27
|
+
```
|
|
25
28
|
|
|
26
|
-
|
|
29
|
+
2. **Connect a client to a resource**: A WebSocket connection to a resource URL automatically subscribes to that resource. When the record changes or a message is published to it, the connection receives the update.
|
|
27
30
|
|
|
28
|
-
```
|
|
29
|
-
|
|
31
|
+
```javascript
|
|
32
|
+
let ws = new WebSocket('wss://server/my-resource/341');
|
|
33
|
+
ws.onmessage = (event) => {
|
|
34
|
+
let data = JSON.parse(event.data);
|
|
35
|
+
};
|
|
36
|
+
```
|
|
30
37
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
+
`new WebSocket('wss://server/my-resource/341')` accesses the resource defined for `my-resource` with record id `341` and subscribes to it.
|
|
39
|
+
|
|
40
|
+
3. **Implement a custom `connect()` handler**: Override the `connect(incomingMessages)` method on a resource class to control WebSocket behavior. The method must return an async iterable (or generator) that produces messages to send to the client. See [automatic-apis.md](automatic-apis.md) for more on defining resource classes.
|
|
41
|
+
|
|
42
|
+
4. **Use the default `connect()` for event-style access**: Call `super.connect()` to get a streaming iterable that provides:
|
|
43
|
+
- A `send(message)` method for pushing outgoing messages
|
|
44
|
+
- A `close` event for cleanup on disconnect
|
|
45
|
+
|
|
46
|
+
5. **Handle message ordering in distributed environments**: Harper delivers messages to local subscribers immediately without inter-node coordination delay.
|
|
47
|
+
|
|
48
|
+
| Message Type | Behavior |
|
|
49
|
+
| -------------------------------------------------------- | ----------------------------------------------------------------------- |
|
|
50
|
+
| Non-retained (no `retain` flag) | Every message delivered in order received; suitable for chat |
|
|
51
|
+
| Retained (published with `retain`, or PUT/updated in DB) | Only the latest-timestamp message is kept; suitable for sensor readings |
|
|
38
52
|
|
|
39
|
-
|
|
53
|
+
6. **Use MQTT over WebSockets** when needed by setting the sub-protocol header:
|
|
54
|
+
```
|
|
55
|
+
Sec-WebSocket-Protocol: mqtt
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
## Examples
|
|
59
|
+
|
|
60
|
+
**Simple echo server** — override `connect(incomingMessages)` to yield each incoming message back to the client:
|
|
61
|
+
|
|
62
|
+
```javascript
|
|
63
|
+
export class Echo extends Resource {
|
|
64
|
+
async *connect(incomingMessages) {
|
|
40
65
|
for await (let message of incomingMessages) {
|
|
41
|
-
yield
|
|
66
|
+
yield message; // echo each message back
|
|
42
67
|
}
|
|
43
68
|
}
|
|
44
69
|
}
|
|
45
70
|
```
|
|
71
|
+
|
|
72
|
+
**Custom connect with timer and event-style access** — use `super.connect()` to get the outgoing stream, push periodic messages, echo incoming messages, and clean up on disconnect:
|
|
73
|
+
|
|
74
|
+
```javascript
|
|
75
|
+
export class Example extends Resource {
|
|
76
|
+
connect(incomingMessages) {
|
|
77
|
+
let outgoingMessages = super.connect();
|
|
78
|
+
|
|
79
|
+
let timer = setInterval(() => {
|
|
80
|
+
outgoingMessages.send({ greeting: 'hi again!' });
|
|
81
|
+
}, 1000);
|
|
82
|
+
|
|
83
|
+
incomingMessages.on('data', (message) => {
|
|
84
|
+
outgoingMessages.send(message); // echo incoming messages
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
outgoingMessages.on('close', () => {
|
|
88
|
+
clearInterval(timer);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
return outgoingMessages;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Notes
|
|
97
|
+
|
|
98
|
+
- WebSocket connections target a resource URL path. By default, connecting to a resource subscribes to changes for that resource.
|
|
99
|
+
- The `connect(incomingMessages)` method **must** return an async iterable or generator; returning a plain value will not work.
|
|
100
|
+
- `super.connect()` returns a streaming iterable with `send(message)` and a `close` event — use this when you need to push messages outside of the incoming message loop.
|
|
101
|
+
- For one-way real-time streaming without bidirectional communication, consider Server-Sent Events instead.
|
|
102
|
+
- For full pub/sub capabilities, Harper also supports MQTT; set `Sec-WebSocket-Protocol: mqtt` to use MQTT over WebSockets.
|