@remit/backend 0.0.90 → 0.0.91

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,384 @@
1
+ import type {
2
+ CalendarResponse,
3
+ CreateCalendarInput,
4
+ UpdateCalendarInput,
5
+ } from "@remit/api-openapi-types";
6
+ import {
7
+ DEFAULT_CALENDAR_URL_SEGMENT,
8
+ isResolvableZone,
9
+ provisionDefaultCalendar,
10
+ putCalendarObject,
11
+ } from "@remit/calendar-service";
12
+ import type {
13
+ CalendarCollectionItem,
14
+ ICalendarCollectionRepository,
15
+ ICalendarEventIndexRepository,
16
+ ICalendarObjectRepository,
17
+ ICalendarUnitOfWork,
18
+ UpdateCalendarCollectionInput,
19
+ } from "@remit/data-ports";
20
+ import { normalizeCalendarUrlSegment } from "@remit/data-ports/id";
21
+ import { CalendarSource } from "@remit/domain-enums";
22
+ import type { APIGatewayProxyEvent } from "aws-lambda";
23
+ import { getAccountConfigIdFromEvent } from "../auth.js";
24
+ import type { RemitClient } from "../service/data-client.js";
25
+ import { getClient } from "../service/data-client.js";
26
+ import type {
27
+ CalendarDetailOperationIds,
28
+ CalendarOperationIds,
29
+ OperationHandler,
30
+ } from "../types.js";
31
+
32
+ /** The calendar store, as the handlers reach it. */
33
+ export interface CalendarDeps {
34
+ calendarCollection: ICalendarCollectionRepository;
35
+ calendarObject: ICalendarObjectRepository;
36
+ calendarEventIndex: ICalendarEventIndexRepository;
37
+ calendarUnitOfWork: ICalendarUnitOfWork;
38
+ }
39
+
40
+ /** Why a calendar request was refused, in a form a client can branch on. */
41
+ export interface CalendarRefusal {
42
+ code: string;
43
+ message: string;
44
+ }
45
+
46
+ /**
47
+ * A refusal is a value here, not a throw. Every one of these is something the
48
+ * caller sent — a window that runs backwards, a segment already taken, a
49
+ * RECURRENCE-ID naming no occurrence — so it is an ordinary outcome of the
50
+ * request rather than a fault of the server's.
51
+ */
52
+ export type CalendarOutcome<T> =
53
+ | { ok: true; value: T }
54
+ | { ok: false; error: CalendarRefusal };
55
+
56
+ export const refuseCalendar = <T>(
57
+ code: string,
58
+ message: string,
59
+ ): CalendarOutcome<T> => ({ ok: false, error: { code, message } });
60
+
61
+ export const badRequest = (error: CalendarRefusal) => ({
62
+ statusCode: 400,
63
+ body: error,
64
+ });
65
+
66
+ export const notFound = (message: string) => ({
67
+ statusCode: 404,
68
+ body: { code: "NotFound", message },
69
+ });
70
+
71
+ export const preconditionFailed = (message: string) => ({
72
+ statusCode: 412,
73
+ body: { code: "EtagMismatch", message },
74
+ });
75
+
76
+ /** The calendar half of the client, named so a handler takes only what it uses. */
77
+ export const calendarDepsOf = (client: RemitClient): CalendarDeps => ({
78
+ calendarCollection: client.calendarCollection,
79
+ calendarObject: client.calendarObject,
80
+ calendarEventIndex: client.calendarEventIndex,
81
+ calendarUnitOfWork: client.calendarUnitOfWork,
82
+ });
83
+
84
+ const toCalendarResponse = (
85
+ item: CalendarCollectionItem,
86
+ ): CalendarResponse => ({
87
+ calendarId: item.calendarId,
88
+ accountConfigId: item.accountConfigId,
89
+ urlSegment: item.urlSegment,
90
+ displayName: item.displayName,
91
+ color: item.color,
92
+ componentSet: item.componentSet,
93
+ source: item.source,
94
+ timezone: item.timezone,
95
+ syncSequence: item.syncSequence,
96
+ createdAt: item.createdAt,
97
+ updatedAt: item.updatedAt,
98
+ });
99
+
100
+ /**
101
+ * Every collection the account config holds, provisioning the default one when
102
+ * it holds none.
103
+ *
104
+ * Safe to race with itself: `calendarId` is derived from the account config and
105
+ * the URL segment, so two first reads arriving together write the same row
106
+ * rather than two, and the loser's write is a no-op instead of a second
107
+ * calendar nobody asked for.
108
+ */
109
+ export const listCalendarsFor = async (
110
+ deps: CalendarDeps,
111
+ accountConfigId: string,
112
+ ): Promise<CalendarCollectionItem[]> => {
113
+ const existing =
114
+ await deps.calendarCollection.listByAccountConfig(accountConfigId);
115
+ if (existing.length > 0) return existing;
116
+
117
+ await provisionDefaultCalendar(deps.calendarUnitOfWork, accountConfigId);
118
+ return deps.calendarCollection.listByAccountConfig(accountConfigId);
119
+ };
120
+
121
+ /** One of the caller's collections, or a refusal naming the one they asked for. */
122
+ export const findCalendarFor = async (
123
+ deps: CalendarDeps,
124
+ accountConfigId: string,
125
+ calendarId: string,
126
+ ): Promise<CalendarOutcome<CalendarCollectionItem>> => {
127
+ const collections =
128
+ await deps.calendarCollection.listByAccountConfig(accountConfigId);
129
+ const found = collections.find(
130
+ (collection) => collection.calendarId === calendarId,
131
+ );
132
+ if (!found) {
133
+ return refuseCalendar(
134
+ "NotFound",
135
+ `no calendar ${calendarId} on this account`,
136
+ );
137
+ }
138
+ return { ok: true, value: found };
139
+ };
140
+
141
+ /**
142
+ * A collection's timezone is what every floating time in it is read in, so a
143
+ * name this server cannot resolve is not a cosmetic setting — it silently moves
144
+ * every all-day and unzoned event in the calendar. A Windows zone name, which
145
+ * is what a client that has not normalised its input sends, is refused here
146
+ * rather than stored and quietly read as UTC.
147
+ */
148
+ export const readCollectionTimezone = (
149
+ timezone: string | undefined,
150
+ ): CalendarOutcome<string> => {
151
+ if (timezone === undefined || timezone === "") return { ok: true, value: "" };
152
+ if (!isResolvableZone(timezone)) {
153
+ return refuseCalendar(
154
+ "UnknownTimeZone",
155
+ `"${timezone}" is not a time zone this server can resolve — use an IANA name such as "Europe/Amsterdam"`,
156
+ );
157
+ }
158
+ return { ok: true, value: timezone };
159
+ };
160
+
161
+ export const createCalendarFor = async (
162
+ deps: CalendarDeps,
163
+ accountConfigId: string,
164
+ input: CreateCalendarInput,
165
+ ): Promise<CalendarOutcome<CalendarCollectionItem>> => {
166
+ const urlSegment = normalizeCalendarUrlSegment(input.urlSegment);
167
+ if (urlSegment === "") {
168
+ return refuseCalendar(
169
+ "InvalidUrlSegment",
170
+ "a calendar needs a url segment to be addressed by",
171
+ );
172
+ }
173
+
174
+ const timezone = readCollectionTimezone(input.timezone);
175
+ if (!timezone.ok) return timezone;
176
+
177
+ // The write decides, not a prior read: two creates of one segment arriving
178
+ // together would both find it free, and the loser would silently be handed
179
+ // the winner's calendar to write into.
180
+ const created = await deps.calendarUnitOfWork.transaction((repos) =>
181
+ repos.calendarCollection.createExclusive({
182
+ accountConfigId,
183
+ urlSegment,
184
+ displayName: input.displayName,
185
+ color: input.color,
186
+ timezone: timezone.value,
187
+ source: CalendarSource.UserCreated,
188
+ }),
189
+ );
190
+ if (!created) {
191
+ return refuseCalendar(
192
+ "UrlSegmentTaken",
193
+ `"${urlSegment}" already addresses a calendar on this account — pick another`,
194
+ );
195
+ }
196
+ return { ok: true, value: created };
197
+ };
198
+
199
+ /**
200
+ * Removes a collection with everything in it, in one unit.
201
+ *
202
+ * The default collection stays: it is where an accepted invitation and a first
203
+ * event land, and an account config with no calendar has nowhere to put one.
204
+ */
205
+ export const deleteCalendarFor = async (
206
+ deps: CalendarDeps,
207
+ accountConfigId: string,
208
+ calendarId: string,
209
+ ): Promise<CalendarOutcome<null>> => {
210
+ const collection = await findCalendarFor(deps, accountConfigId, calendarId);
211
+ if (!collection.ok) return collection;
212
+ if (collection.value.source === CalendarSource.Default) {
213
+ return refuseCalendar(
214
+ "DefaultCalendarUndeletable",
215
+ `"${DEFAULT_CALENDAR_URL_SEGMENT}" is the calendar this account files events into and cannot be removed`,
216
+ );
217
+ }
218
+
219
+ await deps.calendarUnitOfWork.transaction(async (repos) => {
220
+ const objects = await repos.calendarObject.listByCalendar(calendarId);
221
+ for (const object of objects) {
222
+ await repos.calendarEventIndex.deleteForObject(
223
+ calendarId,
224
+ object.calendarObjectId,
225
+ );
226
+ await repos.calendarObject.delete(calendarId, object.calendarObjectId);
227
+ }
228
+ await repos.calendarCollection.delete(accountConfigId, calendarId);
229
+ });
230
+ return { ok: true, value: null };
231
+ };
232
+
233
+ /**
234
+ * Reduce a PATCH body to the fields a collection update may set. `urlSegment`
235
+ * is deliberately absent: it is the collection's identity and the path a client
236
+ * has bookmarked, so moving it is making a different calendar.
237
+ */
238
+ export const pickCalendarUpdate = (
239
+ body: Partial<UpdateCalendarInput>,
240
+ ): UpdateCalendarCollectionInput => {
241
+ const patch: UpdateCalendarCollectionInput = {};
242
+ if (Object.hasOwn(body, "displayName")) patch.displayName = body.displayName;
243
+ if (Object.hasOwn(body, "color")) patch.color = body.color;
244
+ if (Object.hasOwn(body, "timezone")) patch.timezone = body.timezone;
245
+ return patch;
246
+ };
247
+
248
+ /**
249
+ * Applies a collection patch, rewriting what the collection's timezone decides.
250
+ *
251
+ * The timezone is not a label. Every floating and all-day time in the
252
+ * collection is read in it, so changing it moves every occurrence row those
253
+ * resources produced — and a row left at the old zone is an event drawn hours
254
+ * from where the calendar now says it is. Each resource is therefore written
255
+ * again from its own stored bytes, which re-projects and re-expands it and
256
+ * bumps the collection's sequence so a syncing client sees the change. The
257
+ * whole set is one unit: a half-converted calendar is worse than either zone.
258
+ */
259
+ export const updateCalendarFor = async (
260
+ deps: CalendarDeps,
261
+ accountConfigId: string,
262
+ calendarId: string,
263
+ body: Partial<UpdateCalendarInput>,
264
+ ): Promise<CalendarOutcome<CalendarCollectionItem>> => {
265
+ const current = await findCalendarFor(deps, accountConfigId, calendarId);
266
+ if (!current.ok) return current;
267
+
268
+ const patch = pickCalendarUpdate(body);
269
+ if (patch.timezone !== undefined) {
270
+ const timezone = readCollectionTimezone(patch.timezone);
271
+ if (!timezone.ok) return timezone;
272
+ patch.timezone = timezone.value;
273
+ }
274
+ const rezone =
275
+ patch.timezone !== undefined && patch.timezone !== current.value.timezone;
276
+
277
+ const updated = await deps.calendarUnitOfWork.transaction(async (repos) => {
278
+ const collection = await repos.calendarCollection.update(
279
+ accountConfigId,
280
+ calendarId,
281
+ patch,
282
+ );
283
+ if (!rezone) return collection;
284
+
285
+ const objects = await repos.calendarObject.listByCalendar(calendarId);
286
+ for (const object of objects) {
287
+ const rewritten = await putCalendarObject(deps.calendarUnitOfWork, {
288
+ accountConfigId,
289
+ calendarId,
290
+ resourceName: object.resourceName,
291
+ icalData: object.icalData,
292
+ });
293
+ if (!rewritten.ok) {
294
+ throw new Error(
295
+ `stored calendar object ${object.calendarObjectId} was refused on re-expansion: ${rewritten.error.code}`,
296
+ );
297
+ }
298
+ }
299
+ return repos.calendarCollection.get(accountConfigId, calendarId);
300
+ });
301
+ return { ok: true, value: updated };
302
+ };
303
+
304
+ export const CalendarOperations: Record<
305
+ CalendarOperationIds,
306
+ OperationHandler<CalendarOperationIds>
307
+ > = {
308
+ CalendarOperations_listCalendars: async (_context, ...args: unknown[]) => {
309
+ const event = args[0] as APIGatewayProxyEvent;
310
+ const accountConfigId = getAccountConfigIdFromEvent(event);
311
+ const deps = calendarDepsOf(await getClient());
312
+ const items = await listCalendarsFor(deps, accountConfigId);
313
+ return { items: items.map(toCalendarResponse) };
314
+ },
315
+
316
+ CalendarOperations_createCalendar: async (context, ...args: unknown[]) => {
317
+ const event = args[0] as APIGatewayProxyEvent;
318
+ const accountConfigId = getAccountConfigIdFromEvent(event);
319
+ const input = context.request.requestBody as CreateCalendarInput;
320
+ const deps = calendarDepsOf(await getClient());
321
+
322
+ const created = await createCalendarFor(deps, accountConfigId, input);
323
+ if (!created.ok) return badRequest(created.error);
324
+ return toCalendarResponse(created.value);
325
+ },
326
+ };
327
+
328
+ export const CalendarDetailOperations: Record<
329
+ CalendarDetailOperationIds,
330
+ OperationHandler<CalendarDetailOperationIds>
331
+ > = {
332
+ CalendarDetailOperations_getCalendar: async (context, ...args: unknown[]) => {
333
+ const event = args[0] as APIGatewayProxyEvent;
334
+ const accountConfigId = getAccountConfigIdFromEvent(event);
335
+ const { calendarId } = context.request.params as { calendarId: string };
336
+ const deps = calendarDepsOf(await getClient());
337
+
338
+ const found = await findCalendarFor(deps, accountConfigId, calendarId);
339
+ if (!found.ok) return notFound(found.error.message);
340
+ return toCalendarResponse(found.value);
341
+ },
342
+
343
+ CalendarDetailOperations_updateCalendar: async (
344
+ context,
345
+ ...args: unknown[]
346
+ ) => {
347
+ const event = args[0] as APIGatewayProxyEvent;
348
+ const accountConfigId = getAccountConfigIdFromEvent(event);
349
+ const { calendarId } = context.request.params as { calendarId: string };
350
+ const body = context.request.requestBody as Partial<UpdateCalendarInput>;
351
+ const deps = calendarDepsOf(await getClient());
352
+
353
+ const updated = await updateCalendarFor(
354
+ deps,
355
+ accountConfigId,
356
+ calendarId,
357
+ body,
358
+ );
359
+ if (!updated.ok) {
360
+ return updated.error.code === "NotFound"
361
+ ? notFound(updated.error.message)
362
+ : badRequest(updated.error);
363
+ }
364
+ return toCalendarResponse(updated.value);
365
+ },
366
+
367
+ CalendarDetailOperations_deleteCalendar: async (
368
+ context,
369
+ ...args: unknown[]
370
+ ) => {
371
+ const event = args[0] as APIGatewayProxyEvent;
372
+ const accountConfigId = getAccountConfigIdFromEvent(event);
373
+ const { calendarId } = context.request.params as { calendarId: string };
374
+ const deps = calendarDepsOf(await getClient());
375
+
376
+ const removed = await deleteCalendarFor(deps, accountConfigId, calendarId);
377
+ if (!removed.ok) {
378
+ return removed.error.code === "NotFound"
379
+ ? notFound(removed.error.message)
380
+ : badRequest(removed.error);
381
+ }
382
+ return { statusCode: 204 };
383
+ },
384
+ };
@@ -2,6 +2,12 @@ import type { OperationHandler, OperationIds } from "../types.js";
2
2
  import { AccountDetailOperations, AccountOperations } from "./account.js";
3
3
  import { MicrosoftOAuthOperations } from "./account-oauth.js";
4
4
  import { AddressDetailOperations, AddressOperations } from "./address.js";
5
+ import { CalendarDetailOperations, CalendarOperations } from "./calendar.js";
6
+ import {
7
+ CalendarEventDetailOperations,
8
+ CalendarEventOperations,
9
+ CalendarFreeBusyOperations,
10
+ } from "./calendar-event.js";
5
11
  import { ConfigOperations } from "./config.js";
6
12
  import { FilterDetailOperations, FilterOperations } from "./filter.js";
7
13
  import { FolderRoleOperations } from "./folder-role.js";
@@ -42,6 +48,11 @@ export const handlers: Record<OperationIds, OperationHandler<any>> = {
42
48
  ...LabelDetailOperations,
43
49
  ...OrganizeOperations,
44
50
  ...OrganizeJobDetailOperations,
51
+ ...CalendarOperations,
52
+ ...CalendarDetailOperations,
53
+ ...CalendarEventOperations,
54
+ ...CalendarEventDetailOperations,
55
+ ...CalendarFreeBusyOperations,
45
56
  ...TrashOperations,
46
57
  ...SyncOperations,
47
58
  ...ThreadDetailOperations,
@@ -4,8 +4,12 @@ import {
4
4
  AccountRepo,
5
5
  AccountSettingRepo,
6
6
  AddressRepo,
7
+ CalendarCollectionRepo,
8
+ CalendarEventIndexRepo,
9
+ CalendarObjectRepo,
7
10
  ConfigImportRepo,
8
11
  createSqliteDatabase,
12
+ DrizzleCalendarUnitOfWork,
9
13
  DrizzleEnvelopeRepository,
10
14
  DrizzleFilterAnchorTransaction,
11
15
  DrizzleMessageFlagRepository,
@@ -78,6 +82,10 @@ export const buildSqliteClient = async (): Promise<RemitClient> => {
78
82
  label: new LabelRepo(genericDb),
79
83
  messageLabel: new MessageLabelRepo(genericDb),
80
84
  senderSignerStanding: new SenderSignerStandingRepo(genericDb),
85
+ calendarCollection: new CalendarCollectionRepo(genericDb),
86
+ calendarObject: new CalendarObjectRepo(genericDb),
87
+ calendarEventIndex: new CalendarEventIndexRepo(genericDb),
88
+ calendarUnitOfWork: new DrizzleCalendarUnitOfWork(genericDb),
81
89
  unitOfWork: new DrizzleUnitOfWork(messageDataDb),
82
90
  writeSet: (run) => runInTransaction(genericDb, () => run()),
83
91
  };
@@ -4,6 +4,10 @@ import type {
4
4
  IAccountRepository,
5
5
  IAccountSettingRepository,
6
6
  IAddressRepository,
7
+ ICalendarCollectionRepository,
8
+ ICalendarEventIndexRepository,
9
+ ICalendarObjectRepository,
10
+ ICalendarUnitOfWork,
7
11
  IConfigImportRepository,
8
12
  IEnvelopeRepository,
9
13
  IFilterAnchorRepository,
@@ -115,6 +119,17 @@ export interface RemitClient {
115
119
  // body-sync, which is its only writer.
116
120
  senderSignerStanding: ISenderSignerStandingRepository;
117
121
 
122
+ // The calendar store (issue #15). Every write goes through
123
+ // `calendarUnitOfWork`: the object, its occurrence rows and the collection's
124
+ // sequence bump are one fact, and the three repositories beside it are the
125
+ // read side. A backend that cannot supply them cannot serve the calendar at
126
+ // all, so they are part of the client rather than something each handler
127
+ // checks for.
128
+ calendarCollection: ICalendarCollectionRepository;
129
+ calendarObject: ICalendarObjectRepository;
130
+ calendarEventIndex: ICalendarEventIndexRepository;
131
+ calendarUnitOfWork: ICalendarUnitOfWork;
132
+
118
133
  // Atomic write set for a message save. Present on the relational backend (real
119
134
  // transaction); absent on DynamoDB, where callers fall back to per-repo
120
135
  // writes with that backend's own (non-transactional) guarantees.
@@ -204,6 +219,10 @@ export interface RemitClientRepositories {
204
219
  label: ILabelRepository;
205
220
  messageLabel: IMessageLabelRepository;
206
221
  senderSignerStanding: ISenderSignerStandingRepository;
222
+ calendarCollection: ICalendarCollectionRepository;
223
+ calendarObject: ICalendarObjectRepository;
224
+ calendarEventIndex: ICalendarEventIndexRepository;
225
+ calendarUnitOfWork: ICalendarUnitOfWork;
207
226
  unitOfWork?: IUnitOfWork;
208
227
  writeSet?: <T>(run: () => Promise<T>) => Promise<T>;
209
228
  }
@@ -431,6 +450,10 @@ export const createRemitClient = (deps: RemitClientDeps): RemitClient => {
431
450
  label: repositories.label,
432
451
  messageLabel: repositories.messageLabel,
433
452
  senderSignerStanding: repositories.senderSignerStanding,
453
+ calendarCollection: repositories.calendarCollection,
454
+ calendarObject: repositories.calendarObject,
455
+ calendarEventIndex: repositories.calendarEventIndex,
456
+ calendarUnitOfWork: repositories.calendarUnitOfWork,
434
457
  unitOfWork: repositories.unitOfWork,
435
458
  writeSet: repositories.writeSet,
436
459
 
package/src/types.ts CHANGED
@@ -58,6 +58,17 @@ export type OperationIds =
58
58
  | "MessageBulkOperations_updateMessageLabels"
59
59
  | "MessageBulkOperations_reportSpam"
60
60
  | "MessageBulkOperations_notSpam"
61
+ | "CalendarOperations_listCalendars"
62
+ | "CalendarOperations_createCalendar"
63
+ | "CalendarDetailOperations_getCalendar"
64
+ | "CalendarDetailOperations_updateCalendar"
65
+ | "CalendarDetailOperations_deleteCalendar"
66
+ | "CalendarEventOperations_listCalendarEvents"
67
+ | "CalendarEventOperations_createCalendarEvent"
68
+ | "CalendarEventDetailOperations_getCalendarEvent"
69
+ | "CalendarEventDetailOperations_updateCalendarEvent"
70
+ | "CalendarEventDetailOperations_deleteCalendarEvent"
71
+ | "CalendarFreeBusyOperations_listCalendarFreeBusy"
61
72
  | "TrashOperations_emptyTrash"
62
73
  | "OutboxOperations_createOutboxMessage"
63
74
  | "OutboxOperations_listOutboxMessages"
@@ -154,6 +165,31 @@ export type MessageBulkOperationIds = MatchPrefix<
154
165
  OperationIds
155
166
  >;
156
167
 
168
+ export type CalendarOperationIds = MatchPrefix<
169
+ "CalendarOperations_",
170
+ OperationIds
171
+ >;
172
+
173
+ export type CalendarDetailOperationIds = MatchPrefix<
174
+ "CalendarDetailOperations_",
175
+ OperationIds
176
+ >;
177
+
178
+ export type CalendarEventOperationIds = MatchPrefix<
179
+ "CalendarEventOperations_",
180
+ OperationIds
181
+ >;
182
+
183
+ export type CalendarEventDetailOperationIds = MatchPrefix<
184
+ "CalendarEventDetailOperations_",
185
+ OperationIds
186
+ >;
187
+
188
+ export type CalendarFreeBusyOperationIds = MatchPrefix<
189
+ "CalendarFreeBusyOperations_",
190
+ OperationIds
191
+ >;
192
+
157
193
  export type TrashOperationIds = MatchPrefix<"TrashOperations_", OperationIds>;
158
194
 
159
195
  export type OutboxOperationIds = MatchPrefix<"OutboxOperations_", OperationIds>;