@chipmobilesdk/rn-notification 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/CHANGELOG.md +42 -0
- package/README.md +306 -0
- package/package.json +73 -0
- package/src/channel/migrate.ts +211 -0
- package/src/channel/tone-map.ts +90 -0
- package/src/contract/channel.ts +89 -0
- package/src/contract/diagnostics.ts +102 -0
- package/src/contract/errors.ts +123 -0
- package/src/contract/index.ts +10 -0
- package/src/contract/interaction.ts +62 -0
- package/src/contract/notification.ts +118 -0
- package/src/contract/permission.ts +60 -0
- package/src/contract/reconcile.ts +88 -0
- package/src/contract/recurrence.ts +123 -0
- package/src/diagnostics/burst.ts +101 -0
- package/src/diagnostics/events.ts +72 -0
- package/src/diagnostics/redact.ts +72 -0
- package/src/diagnostics/snapshot.ts +64 -0
- package/src/engine/adapter.ts +79 -0
- package/src/engine/notify-kit-engine.ts +535 -0
- package/src/index.ts +173 -0
- package/src/initialize.ts +174 -0
- package/src/interaction/index.ts +146 -0
- package/src/maintenance/cycle.ts +147 -0
- package/src/maintenance/permission-refresh.ts +41 -0
- package/src/maintenance/reanchor.ts +95 -0
- package/src/maintenance/toggle.ts +60 -0
- package/src/maintenance/verify.ts +83 -0
- package/src/maintenance/window-refresh.ts +61 -0
- package/src/permission/index.ts +183 -0
- package/src/permission/state.ts +77 -0
- package/src/push/envelope.ts +165 -0
- package/src/push/fcm-provider.ts +146 -0
- package/src/push/gate.ts +190 -0
- package/src/push/index.ts +29 -0
- package/src/push/instructions.ts +109 -0
- package/src/push/provider-adapter.ts +54 -0
- package/src/push/signout.ts +65 -0
- package/src/reconcile/chunk.ts +53 -0
- package/src/reconcile/diff.ts +145 -0
- package/src/reconcile/duplicates.ts +73 -0
- package/src/reconcile/index.ts +175 -0
- package/src/reconcile/truncate.ts +56 -0
- package/src/recurrence/clock-guard.ts +71 -0
- package/src/recurrence/expand.ts +292 -0
- package/src/recurrence/index.ts +177 -0
- package/src/schedule/anchor.ts +267 -0
- package/src/schedule/index.ts +173 -0
- package/src/schedule/partition.ts +85 -0
- package/src/schedule/resolve-moment.ts +80 -0
- package/src/schedule/validate-content.ts +111 -0
- package/src/schedule/validate-identifier.ts +114 -0
- package/src/state/caps.ts +71 -0
- package/src/state/dedup-ledger.ts +39 -0
- package/src/state/interaction-buffer.ts +73 -0
- package/src/state/mmkv-store.ts +71 -0
- package/src/state/permission-history.ts +41 -0
- package/src/state/record.ts +246 -0
- package/src/state/reset.ts +41 -0
- package/src/state/series-ledger.ts +84 -0
- package/src/state/store.ts +40 -0
- package/src/testing/conformance/index.ts +194 -0
- package/src/testing/fake-engine.ts +284 -0
- package/src/testing/fake-provider.ts +129 -0
- package/src/testing/faults.ts +72 -0
- package/src/testing/index.ts +26 -0
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Time-zone anchoring and re-anchoring.
|
|
3
|
+
*
|
|
4
|
+
* Wall-clock is the default because reminders are wall-clock things: an 08:00
|
|
5
|
+
* reminder should stay 08:00 after the user crosses a time zone, and a caller
|
|
6
|
+
* who does not choose should get what their users expect rather than a silent
|
|
7
|
+
* shift.
|
|
8
|
+
*
|
|
9
|
+
* The cost is re-anchoring. When the device zone changes, every scheduled
|
|
10
|
+
* wall-clock entry must be rewritten to preserve the clock time it named, and
|
|
11
|
+
* every absolute entry must be left completely alone.
|
|
12
|
+
*
|
|
13
|
+
* The limit this cannot fix is stated rather than hidden: a wall-clock
|
|
14
|
+
* notification whose moment arrives while the app has not run since the zone
|
|
15
|
+
* changed fires at the previously anchored instant. The anchoring generation on
|
|
16
|
+
* each entry is what makes that detectable instead of invisible.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import type { AnchoringMode, PendingEntry } from '../contract/notification';
|
|
20
|
+
import { DEFAULT_ANCHORING_MODE } from '../contract/notification';
|
|
21
|
+
|
|
22
|
+
/** Reads the platform time zone. Injected so the pure logic needs no native module. */
|
|
23
|
+
export type TimeZoneReader = () => string;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Resolves the platform zone via `react-native-localize`.
|
|
27
|
+
*
|
|
28
|
+
* Pure JavaScript is not sufficient here: `Intl.DateTimeFormat().resolvedOptions().timeZone`
|
|
29
|
+
* is documented in React Native as not reliably updating when the device zone
|
|
30
|
+
* changes, so it cannot back re-anchoring. Falls back to `Intl` only when the
|
|
31
|
+
* module is absent, which is better than failing outright.
|
|
32
|
+
*/
|
|
33
|
+
export function createPlatformTimeZoneReader(): TimeZoneReader {
|
|
34
|
+
return () => {
|
|
35
|
+
try {
|
|
36
|
+
const localize = require('react-native-localize') as { getTimeZone(): string };
|
|
37
|
+
return localize.getTimeZone();
|
|
38
|
+
} catch {
|
|
39
|
+
try {
|
|
40
|
+
return Intl.DateTimeFormat().resolvedOptions().timeZone ?? 'UTC';
|
|
41
|
+
} catch {
|
|
42
|
+
return 'UTC';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The calendar fields a wall-clock moment actually names. */
|
|
49
|
+
export interface WallClockParts {
|
|
50
|
+
readonly year: number;
|
|
51
|
+
readonly month: number;
|
|
52
|
+
readonly day: number;
|
|
53
|
+
readonly hour: number;
|
|
54
|
+
readonly minute: number;
|
|
55
|
+
readonly second: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Whether a zone name is one the runtime can actually format against.
|
|
60
|
+
*
|
|
61
|
+
* Hermes throws a hard `JSRangeErrorException: Invalid timezone name!` for a
|
|
62
|
+
* bad zone, which kills the JavaScript thread rather than returning an error.
|
|
63
|
+
* A stored anchoring generation is data that can be wrong — a corrupted record,
|
|
64
|
+
* an entry written by an older build, or a defect like the one that stored a
|
|
65
|
+
* tone id here — so it must be checked before it reaches `Intl`.
|
|
66
|
+
*/
|
|
67
|
+
export function isValidTimeZone(timeZone: string): boolean {
|
|
68
|
+
if (timeZone.length === 0) return false;
|
|
69
|
+
try {
|
|
70
|
+
new Intl.DateTimeFormat('en-US', { timeZone }).format(0);
|
|
71
|
+
return true;
|
|
72
|
+
} catch {
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Decomposes an instant into the clock reading it produces in a given zone.
|
|
79
|
+
*
|
|
80
|
+
* Falls back to UTC for an unusable zone rather than throwing: a bad stored
|
|
81
|
+
* value should degrade one entry's anchoring, not crash the app.
|
|
82
|
+
*/
|
|
83
|
+
export function partsInZone(instant: number, timeZone: string): WallClockParts {
|
|
84
|
+
const zone = isValidTimeZone(timeZone) ? timeZone : 'UTC';
|
|
85
|
+
const formatter = new Intl.DateTimeFormat('en-US', {
|
|
86
|
+
timeZone: zone,
|
|
87
|
+
year: 'numeric',
|
|
88
|
+
month: '2-digit',
|
|
89
|
+
day: '2-digit',
|
|
90
|
+
hour: '2-digit',
|
|
91
|
+
minute: '2-digit',
|
|
92
|
+
second: '2-digit',
|
|
93
|
+
hour12: false,
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
const fields: Record<string, number> = {};
|
|
97
|
+
for (const part of formatter.formatToParts(new Date(instant))) {
|
|
98
|
+
if (part.type !== 'literal') {
|
|
99
|
+
fields[part.type] = Number.parseInt(part.value, 10);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
year: fields.year,
|
|
105
|
+
month: fields.month,
|
|
106
|
+
day: fields.day,
|
|
107
|
+
// Intl renders midnight as hour 24 in some environments; normalize it.
|
|
108
|
+
hour: fields.hour === 24 ? 0 : fields.hour,
|
|
109
|
+
minute: fields.minute,
|
|
110
|
+
second: fields.second,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The zone's offset from UTC, in milliseconds, at a given instant. */
|
|
115
|
+
function offsetAt(instant: number, timeZone: string): number {
|
|
116
|
+
const parts = partsInZone(instant, timeZone);
|
|
117
|
+
const asUtc = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
|
|
118
|
+
return asUtc - Math.floor(instant / 1000) * 1000;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Finds the instant at which a zone shows the given clock reading.
|
|
123
|
+
*
|
|
124
|
+
* Two passes, because the offset itself depends on the instant: the first guess
|
|
125
|
+
* uses the offset at the naive UTC interpretation, the second corrects for a
|
|
126
|
+
* daylight-saving boundary crossed by that guess.
|
|
127
|
+
*
|
|
128
|
+
* Daylight-saving resolution, per the documented rule:
|
|
129
|
+
* - a clock time that does not exist resolves **forward** to the next valid instant;
|
|
130
|
+
* - a clock time that occurs twice resolves to its **first** occurrence, so
|
|
131
|
+
* exactly one notification results rather than two.
|
|
132
|
+
*/
|
|
133
|
+
export function instantForParts(parts: WallClockParts, timeZone: string): number {
|
|
134
|
+
const naive = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
|
|
135
|
+
|
|
136
|
+
let candidate = naive - offsetAt(naive, timeZone);
|
|
137
|
+
candidate = naive - offsetAt(candidate, timeZone);
|
|
138
|
+
|
|
139
|
+
const rendered = partsInZone(candidate, timeZone);
|
|
140
|
+
|
|
141
|
+
if (rendered.hour === parts.hour && rendered.minute === parts.minute) {
|
|
142
|
+
// Ambiguous readings (the repeated hour) land here on the first, earlier
|
|
143
|
+
// offset, which is the documented choice.
|
|
144
|
+
return candidate;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// The reading does not exist in this zone — a spring-forward gap. Step
|
|
148
|
+
// forward to the next instant that does exist rather than skipping the
|
|
149
|
+
// occurrence or failing.
|
|
150
|
+
const gapStep = 60 * 60 * 1000;
|
|
151
|
+
for (let attempt = 1; attempt <= 4; attempt += 1) {
|
|
152
|
+
const shifted = candidate + gapStep * attempt;
|
|
153
|
+
const shiftedParts = partsInZone(shifted, timeZone);
|
|
154
|
+
if (shiftedParts.day === parts.day || shiftedParts.hour > parts.hour) {
|
|
155
|
+
return shifted;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
return candidate;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export interface AnchorInput {
|
|
163
|
+
readonly at: number;
|
|
164
|
+
readonly anchoring?: AnchoringMode;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
export interface AnchoredMoment {
|
|
168
|
+
readonly resolvedAt: number;
|
|
169
|
+
readonly anchoring: AnchoringMode;
|
|
170
|
+
/** The zone this was anchored against. Absent for absolute-instant moments. */
|
|
171
|
+
readonly generation?: string;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Resolves a caller-supplied moment into a firing instant.
|
|
176
|
+
*
|
|
177
|
+
* An absolute moment passes through untouched — that is the entire distinction.
|
|
178
|
+
*/
|
|
179
|
+
export function anchorMoment(input: AnchorInput, timeZone: string): AnchoredMoment {
|
|
180
|
+
const anchoring = input.anchoring ?? DEFAULT_ANCHORING_MODE;
|
|
181
|
+
|
|
182
|
+
if (anchoring === 'absolute') {
|
|
183
|
+
return { resolvedAt: input.at, anchoring };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return { resolvedAt: input.at, anchoring, generation: timeZone };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export interface ReAnchorPlan {
|
|
190
|
+
/** Entries whose firing instant must be rewritten, with their new instant. */
|
|
191
|
+
readonly rewrites: readonly { readonly entry: PendingEntry; readonly resolvedAt: number }[];
|
|
192
|
+
readonly fromZone: string | undefined;
|
|
193
|
+
readonly toZone: string;
|
|
194
|
+
readonly zoneChanged: boolean;
|
|
195
|
+
/**
|
|
196
|
+
* Entries carrying an anchoring generation the runtime cannot interpret.
|
|
197
|
+
*
|
|
198
|
+
* Left alone rather than re-anchored against a guess. Reported so a corrupted
|
|
199
|
+
* or older-build record is visible instead of quietly producing wrong firing
|
|
200
|
+
* instants.
|
|
201
|
+
*/
|
|
202
|
+
readonly unreadableGeneration: readonly string[];
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Computes what a zone change requires.
|
|
207
|
+
*
|
|
208
|
+
* Returns an empty plan when the zone has not moved, which is what makes
|
|
209
|
+
* re-anchoring idempotent: the no-change check costs one comparison per entry
|
|
210
|
+
* and issues zero platform operations.
|
|
211
|
+
*/
|
|
212
|
+
export function planReAnchor(
|
|
213
|
+
pending: readonly PendingEntry[],
|
|
214
|
+
currentZone: string,
|
|
215
|
+
): ReAnchorPlan {
|
|
216
|
+
const rewrites: { entry: PendingEntry; resolvedAt: number }[] = [];
|
|
217
|
+
const unreadableGeneration: string[] = [];
|
|
218
|
+
let fromZone: string | undefined;
|
|
219
|
+
|
|
220
|
+
for (const entry of pending) {
|
|
221
|
+
// Absolute-instant entries are never re-anchored, re-scheduled, or touched.
|
|
222
|
+
if (entry.anchoring === 'absolute') continue;
|
|
223
|
+
|
|
224
|
+
const generation = entry.anchoringGeneration;
|
|
225
|
+
if (generation === undefined || generation === currentZone) continue;
|
|
226
|
+
|
|
227
|
+
// A stored generation is data, and data can be wrong. Re-anchoring against
|
|
228
|
+
// a zone the runtime cannot read would move the entry to an arbitrary
|
|
229
|
+
// instant, which is worse than leaving it where it is and saying so.
|
|
230
|
+
if (!isValidTimeZone(generation)) {
|
|
231
|
+
unreadableGeneration.push(entry.id);
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
fromZone ??= generation;
|
|
236
|
+
|
|
237
|
+
// Preserve the clock reading the entry originally named, not the instant.
|
|
238
|
+
const originalParts = partsInZone(entry.resolvedAt, generation);
|
|
239
|
+
const resolvedAt = instantForParts(originalParts, currentZone);
|
|
240
|
+
|
|
241
|
+
if (resolvedAt !== entry.resolvedAt) {
|
|
242
|
+
rewrites.push({ entry, resolvedAt });
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
return {
|
|
247
|
+
rewrites,
|
|
248
|
+
fromZone,
|
|
249
|
+
toZone: currentZone,
|
|
250
|
+
zoneChanged: rewrites.length > 0 || fromZone !== undefined,
|
|
251
|
+
unreadableGeneration,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* True when an entry was anchored against a zone the device has since left.
|
|
257
|
+
*
|
|
258
|
+
* This is the FR-007c condition: the entry will fire at its old instant, and a
|
|
259
|
+
* consumer can detect and explain that rather than being told nothing happened.
|
|
260
|
+
*/
|
|
261
|
+
export function isStaleAnchor(entry: PendingEntry, currentZone: string): boolean {
|
|
262
|
+
return (
|
|
263
|
+
entry.anchoring === 'wallClock' &&
|
|
264
|
+
entry.anchoringGeneration !== undefined &&
|
|
265
|
+
entry.anchoringGeneration !== currentZone
|
|
266
|
+
);
|
|
267
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The scheduling operations.
|
|
3
|
+
*
|
|
4
|
+
* Validation runs in a fixed order and completes entirely before any platform
|
|
5
|
+
* call: identifier, tags, content, moment shape, tone, actions, routing size.
|
|
6
|
+
* A caller therefore never sees a native-level error surface through the
|
|
7
|
+
* package, and a rejected request leaves the device untouched.
|
|
8
|
+
*
|
|
9
|
+
* Scheduling an identifier that already has a notification **replaces** it.
|
|
10
|
+
* That is the defined semantic rather than a side effect, which is what lets a
|
|
11
|
+
* caller stop tracking whether it has already scheduled something.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import type {
|
|
15
|
+
NotificationRequest,
|
|
16
|
+
PendingEntry,
|
|
17
|
+
ScheduleResult,
|
|
18
|
+
} from '../contract/notification';
|
|
19
|
+
import type { ResolvedTone } from '../contract/channel';
|
|
20
|
+
import type { NotificationEngineAdapter } from '../engine/adapter';
|
|
21
|
+
import {
|
|
22
|
+
DIAGNOSTIC_CODES,
|
|
23
|
+
NotificationError,
|
|
24
|
+
} from '../contract/errors';
|
|
25
|
+
import { MAX_ACTIONS_PER_NOTIFICATION, MAX_ROUTING_PAYLOAD_BYTES } from '../contract/interaction';
|
|
26
|
+
import { validateIdentifier, validateOptionalTag } from './validate-identifier';
|
|
27
|
+
import { validateContent, byteLength } from './validate-content';
|
|
28
|
+
import { resolveMoment, validateMoment } from './resolve-moment';
|
|
29
|
+
import { anchorMoment, type TimeZoneReader } from './anchor';
|
|
30
|
+
import { idsForTag } from './partition';
|
|
31
|
+
|
|
32
|
+
export interface ScheduleDependencies {
|
|
33
|
+
readonly engine: NotificationEngineAdapter;
|
|
34
|
+
readonly resolveTone: (toneId: string) => ResolvedTone | undefined;
|
|
35
|
+
readonly timeZone: TimeZoneReader;
|
|
36
|
+
readonly now: () => number;
|
|
37
|
+
/** False when exact-alarm capability is unavailable, forcing approximate mode. */
|
|
38
|
+
readonly canScheduleExactly: () => boolean;
|
|
39
|
+
readonly emit?: (code: string, message: string, context?: Record<string, unknown>) => void;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Validates a request completely, before the engine is touched at all. */
|
|
43
|
+
export function validateRequest(
|
|
44
|
+
request: NotificationRequest,
|
|
45
|
+
resolveTone: (toneId: string) => ResolvedTone | undefined,
|
|
46
|
+
): ResolvedTone {
|
|
47
|
+
validateIdentifier(request.id, 'id');
|
|
48
|
+
validateOptionalTag(request.ownerTag, 'ownerTag');
|
|
49
|
+
validateOptionalTag(request.groupTag, 'groupTag');
|
|
50
|
+
validateContent(request.content);
|
|
51
|
+
validateMoment(request.moment);
|
|
52
|
+
|
|
53
|
+
const tone = resolveTone(request.tone);
|
|
54
|
+
if (tone === undefined) {
|
|
55
|
+
throw new NotificationError(
|
|
56
|
+
DIAGNOSTIC_CODES.UNDECLARED_TONE,
|
|
57
|
+
`Tone "${request.tone}" was never declared in the package configuration. Declare it before scheduling against it.`,
|
|
58
|
+
{ toneId: request.tone },
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (request.actions !== undefined) {
|
|
63
|
+
if (request.actions.length > MAX_ACTIONS_PER_NOTIFICATION) {
|
|
64
|
+
throw new NotificationError(
|
|
65
|
+
DIAGNOSTIC_CODES.TOO_MANY_ACTIONS,
|
|
66
|
+
`A notification may carry at most ${MAX_ACTIONS_PER_NOTIFICATION} actions; ${request.actions.length} were supplied.`,
|
|
67
|
+
{ count: request.actions.length, limit: MAX_ACTIONS_PER_NOTIFICATION },
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
for (const action of request.actions) {
|
|
71
|
+
validateIdentifier(action.id, 'actionId');
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (request.routing !== undefined) {
|
|
76
|
+
// Sized at schedule time rather than discovered as truncated at tap time,
|
|
77
|
+
// which is where an over-large payload would otherwise surface.
|
|
78
|
+
const size = byteLength(JSON.stringify(request.routing));
|
|
79
|
+
if (size > MAX_ROUTING_PAYLOAD_BYTES) {
|
|
80
|
+
throw new NotificationError(
|
|
81
|
+
DIAGNOSTIC_CODES.ROUTING_PAYLOAD_TOO_LARGE,
|
|
82
|
+
`Routing payload is ${size} bytes, over the ${MAX_ROUTING_PAYLOAD_BYTES}-byte limit.`,
|
|
83
|
+
{ bytes: size, limit: MAX_ROUTING_PAYLOAD_BYTES },
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
return tone;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export function createScheduler(deps: ScheduleDependencies) {
|
|
92
|
+
const emit = deps.emit ?? (() => {});
|
|
93
|
+
|
|
94
|
+
const scheduleOne = async (
|
|
95
|
+
request: NotificationRequest,
|
|
96
|
+
options: { readonly seriesId?: string; readonly pushCreated?: boolean } = {},
|
|
97
|
+
): Promise<ScheduleResult> => {
|
|
98
|
+
const tone = validateRequest(request, deps.resolveTone);
|
|
99
|
+
|
|
100
|
+
const zone = deps.timeZone();
|
|
101
|
+
const anchored = anchorMoment(request.moment, zone);
|
|
102
|
+
const resolution = resolveMoment(anchored.resolvedAt, deps.now());
|
|
103
|
+
|
|
104
|
+
const existing = await deps.engine.getPending();
|
|
105
|
+
const replaced = existing.some(entry => entry.id === request.id);
|
|
106
|
+
|
|
107
|
+
// Approximate mode is a degradation, not a refusal: the notification is
|
|
108
|
+
// still scheduled and the caller is told it may arrive late.
|
|
109
|
+
const approximate = !deps.canScheduleExactly();
|
|
110
|
+
if (approximate) {
|
|
111
|
+
emit(
|
|
112
|
+
DIAGNOSTIC_CODES.EXACT_ALARM_UNAVAILABLE,
|
|
113
|
+
'Scheduled in approximate mode; delivery may be late.',
|
|
114
|
+
{ id: request.id },
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
await deps.engine.schedule({
|
|
119
|
+
request,
|
|
120
|
+
resolvedAt: resolution.at,
|
|
121
|
+
tone,
|
|
122
|
+
// The zone this was anchored against, so `getPending` can report it and a
|
|
123
|
+
// consumer can detect a stale anchor (FR-007c). Absent for absolute
|
|
124
|
+
// moments, which are never anchored to a zone.
|
|
125
|
+
anchoringGeneration: anchored.generation,
|
|
126
|
+
approximate,
|
|
127
|
+
seriesId: options.seriesId,
|
|
128
|
+
pushCreated: options.pushCreated,
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
id: request.id,
|
|
133
|
+
resolvedAt: resolution.at,
|
|
134
|
+
anchoring: anchored.anchoring,
|
|
135
|
+
replaced,
|
|
136
|
+
deliveredImmediately: resolution.kind === 'immediate',
|
|
137
|
+
mayBeDelayed: approximate,
|
|
138
|
+
};
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
return {
|
|
142
|
+
schedule: scheduleOne,
|
|
143
|
+
|
|
144
|
+
async cancel(id: string): Promise<void> {
|
|
145
|
+
validateIdentifier(id, 'id');
|
|
146
|
+
await deps.engine.cancel(id);
|
|
147
|
+
},
|
|
148
|
+
|
|
149
|
+
async cancelByGroup(groupTag: string): Promise<readonly string[]> {
|
|
150
|
+
validateIdentifier(groupTag, 'groupTag');
|
|
151
|
+
const ids = idsForTag(await deps.engine.getPending(), 'group', groupTag);
|
|
152
|
+
await deps.engine.cancelMany(ids);
|
|
153
|
+
return ids;
|
|
154
|
+
},
|
|
155
|
+
|
|
156
|
+
async cancelByOwner(ownerTag: string): Promise<readonly string[]> {
|
|
157
|
+
validateIdentifier(ownerTag, 'ownerTag');
|
|
158
|
+
const ids = idsForTag(await deps.engine.getPending(), 'owner', ownerTag);
|
|
159
|
+
await deps.engine.cancelMany(ids);
|
|
160
|
+
return ids;
|
|
161
|
+
},
|
|
162
|
+
|
|
163
|
+
async cancelAll(): Promise<void> {
|
|
164
|
+
await deps.engine.cancelAll();
|
|
165
|
+
},
|
|
166
|
+
|
|
167
|
+
async getPending(): Promise<readonly PendingEntry[]> {
|
|
168
|
+
return deps.engine.getPending();
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export type Scheduler = ReturnType<typeof createScheduler>;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Owner-tag and group-tag partitioning.
|
|
3
|
+
*
|
|
4
|
+
* A tag is an opaque label the caller supplies and the package never
|
|
5
|
+
* interprets. That is deliberate: modelling identity would mean acquiring an
|
|
6
|
+
* opinion about it, and this package is forbidden from knowing anything about
|
|
7
|
+
* accounts, tenants, or users.
|
|
8
|
+
*
|
|
9
|
+
* What the tag buys is one call — "clear this account's notifications" — on a
|
|
10
|
+
* shared device, without the package ever learning what an account is.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { PendingEntry } from '../contract/notification';
|
|
14
|
+
|
|
15
|
+
export type PartitionKind = 'owner' | 'group';
|
|
16
|
+
|
|
17
|
+
/** Selects entries carrying a tag. Comparison is exact; nothing is normalized. */
|
|
18
|
+
export function selectByTag(
|
|
19
|
+
entries: readonly PendingEntry[],
|
|
20
|
+
kind: PartitionKind,
|
|
21
|
+
tag: string,
|
|
22
|
+
): readonly PendingEntry[] {
|
|
23
|
+
return entries.filter(entry =>
|
|
24
|
+
kind === 'owner' ? entry.ownerTag === tag : entry.groupTag === tag,
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Identifiers to cancel for a tag. */
|
|
29
|
+
export function idsForTag(
|
|
30
|
+
entries: readonly PendingEntry[],
|
|
31
|
+
kind: PartitionKind,
|
|
32
|
+
tag: string,
|
|
33
|
+
): readonly string[] {
|
|
34
|
+
return selectByTag(entries, kind, tag).map(entry => entry.id);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Groups entries by a tag, keeping untagged entries under a distinct bucket.
|
|
39
|
+
*
|
|
40
|
+
* Untagged is not the same as any tag: an entry with no owner belongs to no
|
|
41
|
+
* account, and folding it into one would make a sign-out delete notifications
|
|
42
|
+
* that were never that account's.
|
|
43
|
+
*/
|
|
44
|
+
export function partition(
|
|
45
|
+
entries: readonly PendingEntry[],
|
|
46
|
+
kind: PartitionKind,
|
|
47
|
+
): { readonly tagged: ReadonlyMap<string, readonly PendingEntry[]>; readonly untagged: readonly PendingEntry[] } {
|
|
48
|
+
const tagged = new Map<string, PendingEntry[]>();
|
|
49
|
+
const untagged: PendingEntry[] = [];
|
|
50
|
+
|
|
51
|
+
for (const entry of entries) {
|
|
52
|
+
const tag = kind === 'owner' ? entry.ownerTag : entry.groupTag;
|
|
53
|
+
if (tag === undefined) {
|
|
54
|
+
untagged.push(entry);
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
const bucket = tagged.get(tag);
|
|
58
|
+
if (bucket === undefined) {
|
|
59
|
+
tagged.set(tag, [entry]);
|
|
60
|
+
} else {
|
|
61
|
+
bucket.push(entry);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
return { tagged, untagged };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* True when cancelling `tag` would affect any entry outside it.
|
|
70
|
+
*
|
|
71
|
+
* Exists so isolation can be asserted directly rather than inferred from a
|
|
72
|
+
* count — the property that matters is that one account's sign-out changes
|
|
73
|
+
* exactly zero of another account's notifications.
|
|
74
|
+
*/
|
|
75
|
+
export function wouldAffectOtherTags(
|
|
76
|
+
entries: readonly PendingEntry[],
|
|
77
|
+
kind: PartitionKind,
|
|
78
|
+
tag: string,
|
|
79
|
+
): boolean {
|
|
80
|
+
const selected = new Set(idsForTag(entries, kind, tag));
|
|
81
|
+
return entries.some(entry => {
|
|
82
|
+
const entryTag = kind === 'owner' ? entry.ownerTag : entry.groupTag;
|
|
83
|
+
return selected.has(entry.id) && entryTag !== tag;
|
|
84
|
+
});
|
|
85
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Delivery moment resolution.
|
|
3
|
+
*
|
|
4
|
+
* Two rules, and they are two sides of one decision rather than a threshold:
|
|
5
|
+
* a moment more than the tolerance in the past is a caller error and is
|
|
6
|
+
* refused; a moment a few seconds in the past is a processing delay and is
|
|
7
|
+
* delivered promptly. Both outcomes are reported, so a caller never has to
|
|
8
|
+
* guess which happened.
|
|
9
|
+
*
|
|
10
|
+
* Sixty seconds is long enough to absorb reconciling a large desired set, cold
|
|
11
|
+
* start work, and clock skew, and short enough that a genuinely stale schedule
|
|
12
|
+
* is still caught rather than fired at the user minutes late with no
|
|
13
|
+
* explanation.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { DIAGNOSTIC_CODES, NotificationError } from '../contract/errors';
|
|
17
|
+
import type { DeliveryMoment } from '../contract/notification';
|
|
18
|
+
|
|
19
|
+
export const PAST_TOLERANCE_MS = 60_000;
|
|
20
|
+
|
|
21
|
+
export type MomentResolution =
|
|
22
|
+
| { readonly kind: 'future'; readonly at: number }
|
|
23
|
+
| { readonly kind: 'immediate'; readonly at: number; readonly lateBy: number };
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Classifies a resolved instant against now.
|
|
27
|
+
*
|
|
28
|
+
* Takes an already-anchored instant: anchoring decides *which* instant a moment
|
|
29
|
+
* means, and this decides whether that instant is usable. Keeping them separate
|
|
30
|
+
* is what lets each be tested without the other.
|
|
31
|
+
*/
|
|
32
|
+
export function resolveMoment(resolvedAt: number, now: number): MomentResolution {
|
|
33
|
+
if (!Number.isFinite(resolvedAt)) {
|
|
34
|
+
throw new NotificationError(
|
|
35
|
+
DIAGNOSTIC_CODES.MOMENT_IN_PAST,
|
|
36
|
+
'A delivery moment must be a finite epoch-millisecond timestamp.',
|
|
37
|
+
{ received: String(resolvedAt) },
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (resolvedAt >= now) {
|
|
42
|
+
return { kind: 'future', at: resolvedAt };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const lateBy = now - resolvedAt;
|
|
46
|
+
|
|
47
|
+
if (lateBy <= PAST_TOLERANCE_MS) {
|
|
48
|
+
return { kind: 'immediate', at: now, lateBy };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
throw new NotificationError(
|
|
52
|
+
DIAGNOSTIC_CODES.MOMENT_IN_PAST,
|
|
53
|
+
`Delivery moment is ${Math.round(lateBy / 1000)}s in the past, beyond the ${PAST_TOLERANCE_MS / 1000}s tolerance. ` +
|
|
54
|
+
'It was not scheduled, because handing it to the platform would fire it immediately without explanation.',
|
|
55
|
+
{ lateByMs: lateBy, toleranceMs: PAST_TOLERANCE_MS },
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Validates the shape of a caller-supplied moment before anchoring resolves it. */
|
|
60
|
+
export function validateMoment(moment: DeliveryMoment): void {
|
|
61
|
+
if (typeof moment.at !== 'number' || !Number.isFinite(moment.at)) {
|
|
62
|
+
throw new NotificationError(
|
|
63
|
+
DIAGNOSTIC_CODES.MOMENT_IN_PAST,
|
|
64
|
+
'A delivery moment must carry a finite epoch-millisecond `at` value.',
|
|
65
|
+
{ received: typeof moment.at },
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
if (
|
|
70
|
+
moment.anchoring !== undefined &&
|
|
71
|
+
moment.anchoring !== 'wallClock' &&
|
|
72
|
+
moment.anchoring !== 'absolute'
|
|
73
|
+
) {
|
|
74
|
+
throw new NotificationError(
|
|
75
|
+
DIAGNOSTIC_CODES.MOMENT_IN_PAST,
|
|
76
|
+
'Anchoring must be either "wallClock" or "absolute".',
|
|
77
|
+
{ received: String(moment.anchoring) },
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
}
|