@fabriktor/fx 0.0.200 → 0.0.201

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.
@@ -1,5 +1,6 @@
1
1
  import type { CallsOperator } from "@fabriktor/client";
2
2
  import { CallModeAudio, CallModeVideo } from "@fabriktor/schema";
3
+ import type { ServerClock } from "../core/server-clock.js";
3
4
  export declare const callsNotificationKey = "calls.events.received";
4
5
  export declare const callRingTimeoutMS = 60000;
5
6
  export type CallMode = typeof CallModeAudio | typeof CallModeVideo;
@@ -52,6 +53,8 @@ export type CallSessionOptions = {
52
53
  media: CallMediaAdapter;
53
54
  on_change: (state: CallSessionState) => void;
54
55
  on_error: (error: unknown) => void;
56
+ clock?: Pick<ServerClock, "now">;
57
+ elapsed_now?: () => number;
55
58
  };
56
59
  export type CallSessionDependencies = CallSessionOptions & {
57
60
  calls: CallsOperator;
@@ -63,6 +66,8 @@ export declare class CallSession {
63
66
  private connecting;
64
67
  private controller?;
65
68
  private timer?;
69
+ private ringDeadline?;
70
+ private checking?;
66
71
  private recipients;
67
72
  private closed;
68
73
  private had_remote;
@@ -72,6 +77,7 @@ export declare class CallSession {
72
77
  start(room_id: string, members: readonly string[], mode: CallMode): Promise<void>;
73
78
  receive(data: Readonly<Record<string, string>>): void;
74
79
  restore(call: CallInvitation, phase: CallPhase): Promise<void>;
80
+ refresh(): Promise<void>;
75
81
  answer(): Promise<void>;
76
82
  end(): Promise<void>;
77
83
  microphone(enabled: boolean): Promise<void>;
@@ -1,4 +1,4 @@
1
- import { CallIDKey, CallTicketKey, CallOwnerIDKey, CallExpiresAtKey, CallActionRing, CallActionAnswer, CallActionEnd, CallStateEnded, CallRingTimeoutMS, CallRoomIDKey, CallSenderIDKey, CallModeKey, CallSignalKey, CallModeAudio, CallModeVideo, CallSignalInvite, CallSignalAnswered, CallSignalCancelled, ColCallsEvents, SvcCalls, } from "@fabriktor/schema";
1
+ import { CallIDKey, CallTicketKey, CallOwnerIDKey, CallExpiresAtKey, CallActionRing, CallActionAnswer, CallActionEnd, CallActionStatus, CallStateEnded, CallRingTimeoutMS, CallRoomIDKey, CallSenderIDKey, CallModeKey, CallSignalKey, CallModeAudio, CallModeVideo, CallSignalInvite, CallSignalAnswered, CallSignalCancelled, ColCallsEvents, SvcCalls, } from "@fabriktor/schema";
2
2
  import { errValidation, errResolveFailed } from "../core/err.js";
3
3
  // Notification keys are preference-map keys, not generated Go constants.
4
4
  export const callsNotificationKey = `${SvcCalls}.${ColCallsEvents}.received`;
@@ -21,6 +21,8 @@ export class CallSession {
21
21
  connecting = "";
22
22
  controller;
23
23
  timer;
24
+ ringDeadline;
25
+ checking;
24
26
  recipients = [];
25
27
  closed = new Set();
26
28
  had_remote = false;
@@ -43,7 +45,7 @@ export class CallSession {
43
45
  caller_id: this.opts.owner_id,
44
46
  mode,
45
47
  ticket: "",
46
- expires_at: Date.now() + callRingTimeoutMS,
48
+ expires_at: 0,
47
49
  };
48
50
  this.recipients = recipients;
49
51
  this.begin(call, "connecting");
@@ -62,6 +64,7 @@ export class CallSession {
62
64
  await this.respond(call, CallActionEnd);
63
65
  return;
64
66
  }
67
+ this.armTimeout(call);
65
68
  await this.connect(call, access.token);
66
69
  if (!this.current(call))
67
70
  return;
@@ -107,7 +110,11 @@ export class CallSession {
107
110
  call?.id === id)
108
111
  return;
109
112
  const ticket = data[CallTicketKey], expires_at = Number(data[CallExpiresAtKey]);
110
- if (!ticket || !Number.isFinite(expires_at) || expires_at <= Date.now())
113
+ const now = this.opts.clock?.now();
114
+ if (!ticket ||
115
+ !Number.isFinite(expires_at) ||
116
+ expires_at <= 0 ||
117
+ (now != null && expires_at <= now))
111
118
  return;
112
119
  const incoming = {
113
120
  id,
@@ -125,6 +132,8 @@ export class CallSession {
125
132
  }
126
133
  this.begin(incoming, "incoming");
127
134
  this.armTimeout(incoming);
135
+ if (now == null)
136
+ void this.refresh().catch(this.opts.on_error);
128
137
  return;
129
138
  }
130
139
  if (signal !== CallSignalCancelled && signal !== CallSignalAnswered)
@@ -162,23 +171,70 @@ export class CallSession {
162
171
  else
163
172
  this.publish({ phase });
164
173
  const current = this.state.call;
165
- if ((phase === "connected" || phase === "ringing") &&
174
+ if (phase === "connected" || phase === "reconnecting") {
175
+ this.had_remote = true;
176
+ this.clearTimer();
177
+ }
178
+ else
179
+ this.armTimeout(current);
180
+ if ((phase === "connected" ||
181
+ phase === "reconnecting" ||
182
+ phase === "ringing") &&
166
183
  !this.connection &&
167
184
  this.connecting !== call.id)
168
185
  await this.connect(current, "");
169
186
  }
187
+ async refresh() {
188
+ const call = this.state.call;
189
+ if (!call?.ticket || this.had_remote || this.disposed)
190
+ return;
191
+ if (this.checking?.call === call)
192
+ return this.checking.promise;
193
+ const phase = this.state.phase;
194
+ const promise = (async () => {
195
+ try {
196
+ const access = await this.respond(call, CallActionStatus);
197
+ if (!this.current(call) ||
198
+ this.had_remote ||
199
+ this.state.phase !== phase)
200
+ return;
201
+ call.expires_at = access.expires_at;
202
+ this.armTimeout(call);
203
+ }
204
+ catch (error) {
205
+ if (!this.current(call) ||
206
+ this.had_remote ||
207
+ this.state.phase !== phase)
208
+ return;
209
+ this.reset(call);
210
+ throw error;
211
+ }
212
+ })();
213
+ const checking = { call, promise };
214
+ this.checking = checking;
215
+ try {
216
+ await promise;
217
+ }
218
+ finally {
219
+ if (this.checking === checking)
220
+ this.checking = undefined;
221
+ }
222
+ }
170
223
  async answer() {
171
224
  const call = this.state.call;
172
225
  if (!call || this.state.phase !== "incoming")
173
226
  return;
174
227
  this.clearTimer();
175
228
  this.publish({ phase: "connecting" });
229
+ this.armTimeout(call);
176
230
  try {
177
231
  const access = await this.respond(call, CallActionAnswer);
178
232
  if (!this.current(call)) {
179
233
  await this.respond(call, CallActionEnd);
180
234
  return;
181
235
  }
236
+ call.expires_at = access.expires_at;
237
+ this.armTimeout(call);
182
238
  await this.connect(call, access.token);
183
239
  if (!this.current(call))
184
240
  return;
@@ -232,6 +288,7 @@ export class CallSession {
232
288
  begin(call, phase) {
233
289
  this.controller = new AbortController();
234
290
  this.had_remote = false;
291
+ this.ringDeadline = undefined;
235
292
  this.state = {
236
293
  ...idleCallState(),
237
294
  call,
@@ -299,6 +356,8 @@ export class CallSession {
299
356
  !value.call_id ||
300
357
  !value.room_id ||
301
358
  value.owner_id !== this.opts.owner_id ||
359
+ !Number.isFinite(value.expires_at) ||
360
+ value.expires_at <= 0 ||
302
361
  value.state === CallStateEnded)
303
362
  throw errResolveFailed({
304
363
  resource: "call",
@@ -314,7 +373,13 @@ export class CallSession {
314
373
  });
315
374
  if (action === CallActionEnd && out.value)
316
375
  return out.value;
317
- return this.access(out.value);
376
+ const value = this.access(out.value);
377
+ if (value.call_id !== call.id || value.room_id !== call.room_id)
378
+ throw errResolveFailed({
379
+ resource: "call",
380
+ msg: "This call is no longer available.",
381
+ });
382
+ return value;
318
383
  }
319
384
  current(call) {
320
385
  return (!this.disposed &&
@@ -328,6 +393,7 @@ export class CallSession {
328
393
  reset(call) {
329
394
  this.remember(call.id);
330
395
  this.clearTimer();
396
+ this.ringDeadline = undefined;
331
397
  this.state = idleCallState();
332
398
  this.controller?.abort();
333
399
  this.controller = undefined;
@@ -344,12 +410,17 @@ export class CallSession {
344
410
  }
345
411
  armTimeout(call) {
346
412
  this.clearTimer();
347
- if (this.had_remote)
413
+ if (!this.current(call) || this.had_remote)
348
414
  return;
415
+ const elapsed = this.opts.elapsed_now?.() ?? performance.now();
416
+ const now = this.opts.clock?.now();
417
+ const remaining = now == null ? callRingTimeoutMS : Math.max(0, call.expires_at - now);
418
+ // Refreshes and permission prompts share one bounded elapsed-time deadline.
419
+ this.ringDeadline = Math.min(this.ringDeadline ?? elapsed + callRingTimeoutMS, elapsed + remaining);
349
420
  this.timer = setTimeout(() => {
350
- if (this.current(call))
421
+ if (this.current(call) && !this.had_remote)
351
422
  void this.end().catch(this.opts.on_error);
352
- }, Math.max(0, call.expires_at - Date.now()));
423
+ }, Math.max(0, this.ringDeadline - elapsed));
353
424
  }
354
425
  clearTimer() {
355
426
  if (this.timer)
@@ -9,6 +9,7 @@ export declare function newChatInput(opts: {
9
9
  export declare function newOptimisticChat(opts: {
10
10
  owner_id: string;
11
11
  in: InChat;
12
+ now: Date | null;
12
13
  }): Chat;
13
14
  export declare function isOptimisticChat(chat: Pick<Chat, "id">): boolean;
14
15
  export declare function matchesOptimisticChat(chat: Chat, optimistic: Chat): boolean;
@@ -1,5 +1,6 @@
1
1
  import { ChatSendStatus } from "./send-queue.js";
2
2
  import { ZeroID } from "@fabriktor/schema";
3
+ import { timestampDate } from "../core/date.js";
3
4
  const optimisticChatIDPrefix = "optimistic-chat:";
4
5
  export function newChatInput(opts) {
5
6
  return {
@@ -13,7 +14,9 @@ export function newChatInput(opts) {
13
14
  };
14
15
  }
15
16
  export function newOptimisticChat(opts) {
16
- const created_at = new Date().toISOString();
17
+ const created_at = opts.now && Number.isFinite(opts.now.getTime())
18
+ ? opts.now.toISOString()
19
+ : "";
17
20
  return {
18
21
  ...opts.in,
19
22
  id: `${optimisticChatIDPrefix}${crypto.randomUUID()}`,
@@ -60,6 +63,7 @@ export function projectQueuedChats(chats, snapshot, ownerID, roomID) {
60
63
  // A room event may arrive before this entry's independent confirmation
61
64
  // read. Match the server ID so identical messages remain distinct.
62
65
  if (!entry.chat && (!entry.server_id || !confirmed.has(entry.server_id))) {
66
+ const created = timestampDate(entry.optimistic.created_at);
63
67
  // Out-of-order reads must not move a later outgoing bubble ahead of an
64
68
  // earlier pending one. Canonical messages keep their server ordering.
65
69
  let after = afterPending;
@@ -78,9 +82,9 @@ export function projectQueuedChats(chats, snapshot, ownerID, roomID) {
78
82
  if (sequence !== undefined && entry.sequence !== undefined) {
79
83
  return sequence > entry.sequence;
80
84
  }
81
- // Completed entries are no longer in the durable queue after a reload.
82
- // Keep unresolved messages at their original time, not at the live tail.
83
- return (Date.parse(chat.created_at) > Date.parse(entry.optimistic.created_at));
85
+ // Without an enqueue instant, only queue sequence can place a pending
86
+ // bubble. Confirmed messages retain their backend chronology.
87
+ return (created !== null && Date.parse(chat.created_at) > created.getTime());
84
88
  });
85
89
  const index = before < 0 ? result.length : before;
86
90
  result.splice(index, 0, entry.optimistic);
@@ -2,6 +2,7 @@ import { type ChatOperator } from "@fabriktor/client";
2
2
  import type { Chat, InChat } from "@fabriktor/schema";
3
3
  import { type EventListener } from "../core/events.js";
4
4
  import { type QueueRetry, type QueueStore, type QueueLock } from "../core/queue.js";
5
+ import type { ServerClock } from "../core/server-clock.js";
5
6
  export declare const ChatSendStatus: {
6
7
  readonly Saving: "saving";
7
8
  readonly Queued: "queued";
@@ -24,6 +25,7 @@ export type QueuedChat = {
24
25
  owner_id: string;
25
26
  input: InChat;
26
27
  optimistic: Chat;
28
+ optimistic_time_source?: "server" | "unknown";
27
29
  status: ChatSendStatus;
28
30
  server_id?: string;
29
31
  chat?: Chat;
@@ -48,6 +50,7 @@ export type ChatSendQueueOptions = {
48
50
  upload: (entry: QueuedChat, signal: AbortSignal) => Promise<boolean>;
49
51
  changed?: (chat?: Chat) => void;
50
52
  online?: () => boolean;
53
+ clock?: Pick<ServerClock, "now">;
51
54
  on_error?: (error: unknown) => void;
52
55
  };
53
56
  export declare class ChatSendQueue {
@@ -3,6 +3,7 @@ import { requiredOperationID } from "../core/id.js";
3
3
  import { createEvent, EventBus, notifyObserver, } from "../core/events.js";
4
4
  import { PersistentQueue, QueueWakeup, nextQueueRetry, } from "../core/queue.js";
5
5
  import { newOptimisticChat } from "./optimistic.js";
6
+ import { timestampDate } from "../core/date.js";
6
7
  export const ChatSendStatus = {
7
8
  Saving: "saving",
8
9
  Queued: "queued",
@@ -88,12 +89,18 @@ export class ChatSendQueue {
88
89
  if (!this.enabled || !this.owner) {
89
90
  throw new Error("Chat send queue is not ready.");
90
91
  }
91
- const optimistic = newOptimisticChat({ owner_id: this.owner, in: input });
92
+ const now = this.opts.clock?.now();
93
+ const optimistic = newOptimisticChat({
94
+ owner_id: this.owner,
95
+ in: input,
96
+ now: now === undefined || now === null ? null : new Date(now),
97
+ });
92
98
  const entry = {
93
99
  id: crypto.randomUUID(),
94
100
  owner_id: this.owner,
95
101
  input: structuredClone(input),
96
102
  optimistic,
103
+ optimistic_time_source: optimistic.created_at ? "server" : "unknown",
97
104
  status: ChatSendStatus.Saving,
98
105
  attachments: { ...attachments, files: [...attachments.files] },
99
106
  attempted: false,
@@ -168,7 +175,7 @@ export class ChatSendQueue {
168
175
  }
169
176
  const owner = this.owner, signal = this.controller.signal, revision = ++this.revision;
170
177
  try {
171
- const stored = await this.opts.store.list(owner);
178
+ const stored = (await this.opts.store.list(owner)).map(normalizeOptimisticTime);
172
179
  if (!this.current(owner, signal) || revision !== this.revision) {
173
180
  return;
174
181
  }
@@ -697,11 +704,13 @@ export class ChatSendQueue {
697
704
  return this.enabled && this.owner === owner && !signal.aborted;
698
705
  }
699
706
  async save(entry) {
707
+ entry = normalizeOptimisticTime(entry);
700
708
  await this.opts.store.put(entry);
701
709
  this.replace(entry);
702
710
  this.opts.changed?.();
703
711
  }
704
712
  replace(entry) {
713
+ entry = normalizeOptimisticTime(entry);
705
714
  if (entry.owner_id !== this.owner) {
706
715
  return;
707
716
  }
@@ -727,6 +736,25 @@ export class ChatSendQueue {
727
736
  this.events.publish(this.changed, this.snapshot);
728
737
  }
729
738
  }
739
+ function normalizeOptimisticTime(entry) {
740
+ if (entry.optimistic_time_source === "server" &&
741
+ timestampDate(entry.optimistic.created_at) &&
742
+ timestampDate(entry.optimistic.updated_at)) {
743
+ return entry;
744
+ }
745
+ if (entry.optimistic_time_source === "unknown" &&
746
+ entry.optimistic.created_at === "" &&
747
+ entry.optimistic.updated_at === "") {
748
+ return entry;
749
+ }
750
+ // Legacy records used the device clock. Keep their payload, sequence and
751
+ // idempotency keys, but do not display or order by that unverified instant.
752
+ return {
753
+ ...entry,
754
+ optimistic_time_source: "unknown",
755
+ optimistic: { ...entry.optimistic, created_at: "", updated_at: "" },
756
+ };
757
+ }
730
758
  function chatSendCanConfirm(entry) {
731
759
  return (!!entry.server_id &&
732
760
  !entry.chat &&
@@ -1,5 +1,6 @@
1
1
  export type NowProvider = () => globalThis.Date | Promise<globalThis.Date>;
2
2
  export declare const serverClockMaximumAgeMS = 60000;
3
+ export declare function requireServerTime(now?: NowProvider): Promise<Date>;
3
4
  export declare class ServerClock {
4
5
  private readonly elapsedNow;
5
6
  private sample?;
@@ -1,6 +1,13 @@
1
1
  import { errValidation } from "./err.js";
2
2
  export const serverClockMaximumAgeMS = 60_000;
3
3
  const msgServerTime = "Server time is unavailable. Refresh and try again.";
4
+ export async function requireServerTime(now) {
5
+ const value = await now?.();
6
+ if (!value || !Number.isFinite(value.getTime())) {
7
+ throw errValidation({ msg: msgServerTime });
8
+ }
9
+ return value;
10
+ }
4
11
  // Wall time comes only from the API. The injected monotonic timer measures
5
12
  // elapsed duration; browser timezone and device wall-clock changes are irrelevant.
6
13
  export class ServerClock {
package/dist/src/fx.d.ts CHANGED
@@ -24,6 +24,7 @@ import type { StorageFX, StorageFXOperator } from "./storage/storage.js";
24
24
  import type { TimesheetsFX, TimesheetsFXOperator } from "./timesheets/timesheets.js";
25
25
  import type { UsersFX, UsersFXOperator } from "./users/users.js";
26
26
  export type FXOptions = {
27
+ now?: NowProvider;
27
28
  timesheets_now?: NowProvider;
28
29
  auth: AuthOperator;
29
30
  billable: BillableOperator;
@@ -54,6 +55,7 @@ export type FXOptions = {
54
55
  };
55
56
  export type DefaultFXOptions = {
56
57
  http?: HTTPDoer;
58
+ now?: NowProvider;
57
59
  timesheets_now?: NowProvider;
58
60
  base_url: string;
59
61
  auth: AuthOperator;
package/dist/src/fx.js CHANGED
@@ -68,6 +68,7 @@ export class FX {
68
68
  });
69
69
  this.jobs = newJobsFX({
70
70
  jobs: opts.jobs,
71
+ now: opts.now ?? opts.timesheets_now,
71
72
  });
72
73
  this.memos = newMemosFX({
73
74
  memos: opts.memos,
@@ -122,7 +123,7 @@ export class FX {
122
123
  timesheets: opts.timesheets,
123
124
  contacts_fx: this.contacts,
124
125
  billable: opts.billable,
125
- now: opts.timesheets_now,
126
+ now: opts.timesheets_now ?? opts.now,
126
127
  });
127
128
  this.users = newUsersFX({
128
129
  users: opts.users,
@@ -145,6 +146,7 @@ export function newDefaultFX(opts) {
145
146
  const get_token = () => opts.auth.getToken();
146
147
  return newFX({
147
148
  auth: opts.auth,
149
+ now: opts.now,
148
150
  timesheets_now: opts.timesheets_now,
149
151
  billable: newBillableClient({
150
152
  http,
@@ -1,5 +1,6 @@
1
1
  import { type Job, type JobProgram, type Location } from "@fabriktor/schema";
2
2
  import { type JobsOperator } from "@fabriktor/client";
3
+ import { type NowProvider } from "../core/server-clock.js";
3
4
  import { type OwnerSearchOptions, type SearchOptions, type SearchPage } from "../core/search.js";
4
5
  type JobInsert = Parameters<JobsOperator["insertOneJob"]>[0]["in"];
5
6
  type JobProgramInsert = Parameters<JobsOperator["insertOneJobProgram"]>[0]["in"];
@@ -40,7 +41,7 @@ export type SearchJobProgramsPage = SearchPage<JobProgram>;
40
41
  export type SearchJobsPage = SearchPage<Job>;
41
42
  export type JobsFXOptions = {
42
43
  jobs: JobsOperator;
43
- now?: () => globalThis.Date;
44
+ now?: NowProvider;
44
45
  };
45
46
  export type CreateJobOptions = {
46
47
  in: JobInsert;
@@ -115,7 +116,7 @@ export interface JobsFXOperator {
115
116
  }
116
117
  export declare class JobsFX implements JobsFXOperator {
117
118
  private jobs;
118
- private now;
119
+ private readonly now?;
119
120
  constructor(opts: JobsFXOptions);
120
121
  createLocation(opts: CreateLocationOptions): Promise<Location>;
121
122
  updateLocation(opts: UpdateLocationOptions): Promise<Location>;
@@ -3,6 +3,7 @@ import { queryParams } from "@fabriktor/client";
3
3
  import { isZeroDate, normalizeInputDate, zeroInputDate, } from "../core/date.js";
4
4
  import { errRequired, errResolveFailed, errValidation, } from "../core/err.js";
5
5
  import { normalizeIDs, requiredOperationID, resolvedID } from "../core/id.js";
6
+ import { requireServerTime } from "../core/server-clock.js";
6
7
  import { runPreActionCheck } from "../core/pre-action.js";
7
8
  import { runOwnerSearch, runSearch, withOwnerQuery, } from "../core/search.js";
8
9
  const msgJobIDRequired = "Job ID is required.";
@@ -52,7 +53,7 @@ export class JobsFX {
52
53
  now;
53
54
  constructor(opts) {
54
55
  this.jobs = opts.jobs;
55
- this.now = opts.now ?? (() => new globalThis.Date());
56
+ this.now = opts.now;
56
57
  }
57
58
  async createLocation(opts) {
58
59
  const client_id = requiredID(opts.in.client_id, "client_id", msgLocationClientRequired);
@@ -154,7 +155,7 @@ export class JobsFX {
154
155
  const current_day = validateProgramStart({
155
156
  start: input.job_start_date,
156
157
  location: opts.location,
157
- now: this.now(),
158
+ now: await requireServerTime(this.now),
158
159
  });
159
160
  if (current_day) {
160
161
  await this.jobs.immediateJobFromProgram(input);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabriktor/fx",
3
- "version": "0.0.200",
3
+ "version": "0.0.201",
4
4
  "description": "![Fabriktor Logo](./img/fabriktor-character.gif)",
5
5
  "type": "module",
6
6
  "exports": {