@fabriktor/fx 0.0.201 → 0.0.203

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.
@@ -73,6 +73,7 @@ export declare class ChatSendQueue {
73
73
  private enabled;
74
74
  private revision;
75
75
  private readonly wakeup;
76
+ private readonly retryClock;
76
77
  private storageRetry?;
77
78
  private pendingCreates;
78
79
  constructor(opts: ChatSendQueueOptions);
@@ -1,7 +1,7 @@
1
1
  import { ClientErrKind, isClientErr, } from "@fabriktor/client";
2
2
  import { requiredOperationID } from "../core/id.js";
3
3
  import { createEvent, EventBus, notifyObserver, } from "../core/events.js";
4
- import { PersistentQueue, QueueWakeup, nextQueueRetry, } from "../core/queue.js";
4
+ import { PersistentQueue, QueueWakeup, QueueRetryClock, nextQueueRetry, } from "../core/queue.js";
5
5
  import { newOptimisticChat } from "./optimistic.js";
6
6
  import { timestampDate } from "../core/date.js";
7
7
  export const ChatSendStatus = {
@@ -38,6 +38,7 @@ export class ChatSendQueue {
38
38
  enabled = false;
39
39
  revision = 0;
40
40
  wakeup = new QueueWakeup();
41
+ retryClock = new QueueRetryClock();
41
42
  storageRetry;
42
43
  pendingCreates = new Map();
43
44
  constructor(opts) {
@@ -525,7 +526,7 @@ export class ChatSendQueue {
525
526
  : ChatSendStatus.Failed,
526
527
  });
527
528
  if (retry && this.current(owner, signal))
528
- this.scheduleRecovery(retry.after);
529
+ this.scheduleRecovery(this.retryClock.deadline(current.id, retry));
529
530
  }
530
531
  })
531
532
  .catch((err) => {
@@ -673,14 +674,17 @@ export class ChatSendQueue {
673
674
  notifyObserver(() => this.opts.on_error?.(error));
674
675
  }
675
676
  waitForRetry(entry) {
676
- if (!entry.retry || entry.retry.after <= Date.now())
677
+ if (!entry.retry)
677
678
  return false;
678
- this.scheduleRecovery(entry.retry.after);
679
+ const deadline = this.retryClock.deadline(entry.id, entry.retry);
680
+ if (deadline <= performance.now())
681
+ return false;
682
+ this.scheduleRecovery(deadline);
679
683
  return true;
680
684
  }
681
685
  recoverStorage() {
682
686
  this.storageRetry = nextQueueRetry(this.storageRetry);
683
- this.scheduleRecovery(this.storageRetry.after);
687
+ this.scheduleRecovery(this.retryClock.deadline("storage", this.storageRetry));
684
688
  }
685
689
  scheduleRecovery(after) {
686
690
  if (!this.enabled)
@@ -732,6 +736,11 @@ export class ChatSendQueue {
732
736
  }
733
737
  }
734
738
  publish() {
739
+ this.retryClock.retain([
740
+ ...this.entries.filter((entry) => entry.retry).map((entry) => entry.id),
741
+ ...this.pendingSaves.keys(),
742
+ ...(this.storageRetry ? ["storage"] : []),
743
+ ]);
735
744
  this.revision++;
736
745
  this.events.publish(this.changed, this.snapshot);
737
746
  }
@@ -0,0 +1,2 @@
1
+ export declare function elapsedTimestamp(): number;
2
+ export declare function elapsedAge(at: number, now?: number): number | null;
@@ -0,0 +1,9 @@
1
+ // Comparable across live windows/workers. This is a duration coordinate,
2
+ // never an authoritative Unix timestamp or a value to display as a date.
3
+ export function elapsedTimestamp() {
4
+ return performance.timeOrigin + performance.now();
5
+ }
6
+ export function elapsedAge(at, now = elapsedTimestamp()) {
7
+ const age = now - at;
8
+ return Number.isFinite(at) && Number.isFinite(age) && age >= 0 ? age : null;
9
+ }
@@ -49,7 +49,7 @@ export declare function errValidation<T extends object = Record<string, unknown>
49
49
  export declare function errResolveFailed<T extends object = Record<string, unknown>>(opts: ResolveFailedFXErrOptions<T>): FXErr;
50
50
  export declare function errUnknown(cause: unknown): FXErr;
51
51
  export declare function isFXErr(err: unknown): err is FXErr;
52
- export declare function errUnconfirmedMutation(): FXErr;
52
+ export declare function errUnconfirmedMutation(cause?: unknown): FXErr;
53
53
  export declare function isUnconfirmedMutation(err: unknown): boolean;
54
54
  export declare function fxErrMessage(err: unknown): string;
55
55
  export {};
@@ -74,10 +74,11 @@ export function errUnknown(cause) {
74
74
  export function isFXErr(err) {
75
75
  return err instanceof FXErr;
76
76
  }
77
- export function errUnconfirmedMutation() {
77
+ export function errUnconfirmedMutation(cause) {
78
78
  return errResolveFailed({
79
79
  resource: resourceUnconfirmedMutation,
80
80
  msg: "The previous mutation was not acknowledged. Repeating it could duplicate the operation.",
81
+ cause,
81
82
  });
82
83
  }
83
84
  export function isUnconfirmedMutation(err) {
@@ -1,3 +1,4 @@
1
+ import { elapsedTimestamp } from "./elapsed-time.js";
1
2
  export type QueueRecord = {
2
3
  id: string;
3
4
  owner_id: string;
@@ -6,12 +7,21 @@ export type QueueRecord = {
6
7
  export type QueueRetry = {
7
8
  attempts: number;
8
9
  after: number;
10
+ clock?: "elapsed";
9
11
  };
10
12
  export declare class MutationQueue {
11
13
  private pending;
12
14
  run<T>(signal: AbortSignal, fn: (signal: AbortSignal) => Promise<T>): Promise<T>;
13
15
  }
14
16
  export declare function nextQueueRetry(previous?: QueueRetry): QueueRetry;
17
+ export declare class QueueRetryClock {
18
+ private readonly sharedNow;
19
+ private readonly localNow;
20
+ private pending;
21
+ constructor(sharedNow?: typeof elapsedTimestamp, localNow?: () => number);
22
+ deadline(key: string, retry: QueueRetry): number;
23
+ retain(keys: Iterable<string>): void;
24
+ }
15
25
  export declare class QueueWakeup {
16
26
  private pending?;
17
27
  schedule(after: number, signal: AbortSignal, run: () => void): void;
@@ -1,3 +1,4 @@
1
+ import { elapsedTimestamp } from "./elapsed-time.js";
1
2
  const queueRetryInitialMilliseconds = 1_000;
2
3
  const queueRetryMaximumMilliseconds = 30_000;
3
4
  // In-memory mutations stay sequential while unrelated UI remains interactive.
@@ -14,11 +15,46 @@ export class MutationQueue {
14
15
  return result;
15
16
  }
16
17
  }
17
- // Durable deadlines prevent refreshes and other tabs from bypassing backoff.
18
+ function queueRetryDelay(attempts) {
19
+ return Math.min(queueRetryMaximumMilliseconds, queueRetryInitialMilliseconds * 2 ** Math.max(0, attempts - 1));
20
+ }
18
21
  export function nextQueueRetry(previous) {
19
22
  const attempts = (previous?.attempts ?? 0) + 1;
20
- const delay = Math.min(queueRetryMaximumMilliseconds, queueRetryInitialMilliseconds * 2 ** (attempts - 1));
21
- return { attempts, after: Date.now() + delay };
23
+ return {
24
+ attempts,
25
+ after: elapsedTimestamp() + queueRetryDelay(attempts),
26
+ clock: "elapsed",
27
+ };
28
+ }
29
+ // Persisted coordinates survive tab handoffs, but cannot be trusted indefinitely
30
+ // across browser restarts. Adopt each retry once, capped by its normal backoff.
31
+ export class QueueRetryClock {
32
+ sharedNow;
33
+ localNow;
34
+ pending = new Map();
35
+ constructor(sharedNow = elapsedTimestamp, localNow = () => performance.now()) {
36
+ this.sharedNow = sharedNow;
37
+ this.localNow = localNow;
38
+ }
39
+ deadline(key, retry) {
40
+ const token = `${retry.clock}:${retry.attempts}:${retry.after}`;
41
+ const pending = this.pending.get(key);
42
+ if (pending?.token === token)
43
+ return pending.deadline;
44
+ const delay = queueRetryDelay(retry.attempts);
45
+ const remaining = retry.clock === "elapsed" && Number.isFinite(retry.after)
46
+ ? Math.max(0, Math.min(delay, retry.after - this.sharedNow()))
47
+ : delay;
48
+ const deadline = this.localNow() + remaining;
49
+ this.pending.set(key, { token, deadline });
50
+ return deadline;
51
+ }
52
+ retain(keys) {
53
+ const active = new Set(keys);
54
+ for (const key of this.pending.keys())
55
+ if (!active.has(key))
56
+ this.pending.delete(key);
57
+ }
22
58
  }
23
59
  // One wakeup for the earliest pending recovery. A paused account must never
24
60
  // be restarted by an old timer. The caller re-reads durable state on wakeup.
@@ -37,7 +73,7 @@ export class QueueWakeup {
37
73
  cancel();
38
74
  if (!signal.aborted)
39
75
  run();
40
- }, Math.max(0, after - Date.now()));
76
+ }, Math.max(0, after - performance.now()));
41
77
  this.pending = { after, cancel };
42
78
  signal.addEventListener("abort", cancel, { once: true });
43
79
  }
@@ -4,7 +4,13 @@ export declare function requireServerTime(now?: NowProvider): Promise<Date>;
4
4
  export declare class ServerClock {
5
5
  private readonly elapsedNow;
6
6
  private sample?;
7
+ private active;
8
+ private generation;
7
9
  constructor(elapsedNow: () => number);
10
+ get isActive(): boolean;
11
+ get revision(): number;
12
+ invalidate(): void;
13
+ setActive(active: boolean): void;
8
14
  observeHTTPDate(value: string | null): void;
9
15
  now(): number | null;
10
16
  requireNow(): number;
@@ -13,11 +13,28 @@ export async function requireServerTime(now) {
13
13
  export class ServerClock {
14
14
  elapsedNow;
15
15
  sample;
16
+ active = true;
17
+ generation = 0;
16
18
  constructor(elapsedNow) {
17
19
  this.elapsedNow = elapsedNow;
18
20
  }
21
+ get isActive() {
22
+ return this.active;
23
+ }
24
+ get revision() {
25
+ return this.generation;
26
+ }
27
+ invalidate() {
28
+ this.generation++;
29
+ this.sample = undefined;
30
+ }
31
+ setActive(active) {
32
+ if (this.active !== active)
33
+ this.invalidate();
34
+ this.active = active;
35
+ }
19
36
  observeHTTPDate(value) {
20
- if (!value || !value.endsWith(" GMT"))
37
+ if (!this.active || !value || !value.endsWith(" GMT"))
21
38
  return;
22
39
  const epoch = globalThis.Date.parse(value);
23
40
  if (!Number.isFinite(epoch))
@@ -1,10 +1,20 @@
1
- import type { FulfillmentsOperator } from "@fabriktor/client";
2
- import type { FulfillOrder } from "@fabriktor/schema";
1
+ import { type FulfillmentsOperator } from "@fabriktor/client";
2
+ import { type FulfillOrder, type User } from "@fabriktor/schema";
3
3
  import { type OwnerSearchOptions, type SearchPage } from "../core/search.js";
4
4
  type FulfillOrderInsertOptions = Parameters<FulfillmentsOperator["insertOneFulfillOrder"]>[0];
5
- type FulfillOrderReplaceOptions = Parameters<FulfillmentsOperator["replaceOneFulfillOrder"]>[0];
6
- export type CreateFulfillOrderOptions = FulfillOrderInsertOptions;
7
- export type ReplaceFulfillOrderOptions = FulfillOrderReplaceOptions;
5
+ export type CreateFulfillOrderOptions = FulfillOrderInsertOptions & {
6
+ user: Pick<User, "id" | "account_identity">;
7
+ };
8
+ export type FulfillOrderAllowanceOptions = {
9
+ owner_id: string;
10
+ signal?: AbortSignal;
11
+ };
12
+ export type FulfillOrderAllowance = {
13
+ used: number;
14
+ remaining: number;
15
+ };
16
+ export declare function canOrderFreeMagnets(user: Pick<User, "account_identity"> | null | undefined): boolean;
17
+ export declare function isFulfillOrderAllowanceExceeded(error: unknown): boolean;
8
18
  export type SearchFulfillOrdersOptions = OwnerSearchOptions;
9
19
  export type SearchFulfillOrdersPage = SearchPage<FulfillOrder>;
10
20
  export type FulfillmentsFXOptions = {
@@ -12,14 +22,14 @@ export type FulfillmentsFXOptions = {
12
22
  };
13
23
  export interface FulfillmentsFXOperator {
14
24
  createFulfillOrder(opts: CreateFulfillOrderOptions): Promise<FulfillOrder>;
15
- replaceFulfillOrder(opts: ReplaceFulfillOrderOptions): Promise<FulfillOrder>;
25
+ getFulfillOrderAllowance(opts: FulfillOrderAllowanceOptions): Promise<FulfillOrderAllowance>;
16
26
  searchFulfillOrders(opts: SearchFulfillOrdersOptions): Promise<SearchFulfillOrdersPage>;
17
27
  }
18
28
  export declare class FulfillmentsFX implements FulfillmentsFXOperator {
19
29
  private fulfillments;
20
30
  constructor(opts: FulfillmentsFXOptions);
21
31
  createFulfillOrder(opts: CreateFulfillOrderOptions): Promise<FulfillOrder>;
22
- replaceFulfillOrder(opts: ReplaceFulfillOrderOptions): Promise<FulfillOrder>;
32
+ getFulfillOrderAllowance(opts: FulfillOrderAllowanceOptions): Promise<FulfillOrderAllowance>;
23
33
  searchFulfillOrders(opts: SearchFulfillOrdersOptions): Promise<SearchFulfillOrdersPage>;
24
34
  private findFulfillOrder;
25
35
  }
@@ -1,22 +1,97 @@
1
- import { errResolveFailed } from "../core/err.js";
1
+ import { ClientErrKind, isClientErr, isHTTPClientErr, } from "@fabriktor/client";
2
+ import { ErrCodeFulfillOrderAllowanceExceeded, FulfillOrderQuantityLimit, FulfillOrderQuantityMin, FulfillOrderStatusFailed, FulfillProductNameCarMagnet5x5, UserTypeEmployer, } from "@fabriktor/schema";
3
+ import { errResolveFailed, errValidation, errUnconfirmedMutation, isFXErr, } from "../core/err.js";
2
4
  import { requiredOperationID } from "../core/id.js";
5
+ import { withOwnerQuery } from "../core/query.js";
6
+ import { userSupportsMode } from "../users/users.js";
3
7
  import { runOwnerSearch, } from "../core/search.js";
4
8
  const resourceFulfillOrder = "fulfill_order";
5
9
  const msgCreatedFulfillOrderIDMissing = "Created fulfill order response did not contain an ID.";
6
10
  const msgFulfillOrderMissing = "Fulfill order could not be resolved after the mutation.";
11
+ export function canOrderFreeMagnets(user) {
12
+ return userSupportsMode(user, UserTypeEmployer);
13
+ }
14
+ export function isFulfillOrderAllowanceExceeded(error) {
15
+ return (((isHTTPClientErr(error) && error.status === 409) || isFXErr(error)) &&
16
+ error.message === ErrCodeFulfillOrderAllowanceExceeded);
17
+ }
7
18
  export class FulfillmentsFX {
8
19
  fulfillments;
9
20
  constructor(opts) {
10
21
  this.fulfillments = opts.fulfillments;
11
22
  }
12
23
  async createFulfillOrder(opts) {
13
- const out = await this.fulfillments.insertOneFulfillOrder(opts);
14
- const id = requiredOperationID(out, msgCreatedFulfillOrderIDMissing);
15
- return await this.findFulfillOrder(id);
24
+ const { user, ...insertOpts } = opts;
25
+ if (!canOrderFreeMagnets(user)) {
26
+ throw errValidation({
27
+ field: "account_identity",
28
+ msg: "Free magnets require an employer identity.",
29
+ });
30
+ }
31
+ if (!Number.isInteger(opts.in.quantity) ||
32
+ opts.in.quantity < FulfillOrderQuantityMin ||
33
+ opts.in.quantity > FulfillOrderQuantityLimit) {
34
+ throw errValidation({
35
+ field: "quantity",
36
+ msg: "Invalid magnet quantity.",
37
+ });
38
+ }
39
+ const allowance = await this.getFulfillOrderAllowance({
40
+ owner_id: user.id,
41
+ signal: opts.signal,
42
+ });
43
+ if (opts.in.quantity > allowance.remaining) {
44
+ throw errValidation({
45
+ field: "quantity",
46
+ msg: ErrCodeFulfillOrderAllowanceExceeded,
47
+ });
48
+ }
49
+ let out;
50
+ try {
51
+ out = await this.fulfillments.insertOneFulfillOrder(insertOpts);
52
+ }
53
+ catch (error) {
54
+ if (isClientErr(error) &&
55
+ (error.kind === ClientErrKind.HTTPRequestFailed ||
56
+ error.kind === ClientErrKind.HTTPResponseInvalid ||
57
+ (error.status !== undefined && error.status >= 500)))
58
+ throw errUnconfirmedMutation(error);
59
+ throw error;
60
+ }
61
+ try {
62
+ const id = requiredOperationID(out, msgCreatedFulfillOrderIDMissing);
63
+ return await this.findFulfillOrder(id, opts.signal);
64
+ }
65
+ catch (error) {
66
+ throw errUnconfirmedMutation(error);
67
+ }
16
68
  }
17
- async replaceFulfillOrder(opts) {
18
- await this.fulfillments.replaceOneFulfillOrder(opts);
19
- return await this.findFulfillOrder(opts.id);
69
+ async getFulfillOrderAllowance(opts) {
70
+ if (!opts.owner_id.trim()) {
71
+ throw errValidation({
72
+ field: "owner_id",
73
+ msg: "An owner is required to check the magnet allowance.",
74
+ });
75
+ }
76
+ // Query returns the complete retained history; search pages cannot determine the allowance.
77
+ const out = await this.fulfillments.queryFulfillOrders({
78
+ query: withOwnerQuery(opts.owner_id),
79
+ signal: opts.signal,
80
+ });
81
+ if (!Array.isArray(out.value)) {
82
+ throw errResolveFailed({
83
+ resource: resourceFulfillOrder,
84
+ msg: "Magnet allowance could not be resolved.",
85
+ });
86
+ }
87
+ const used = out.value.reduce((total, order) => {
88
+ if (order.owner_id !== opts.owner_id ||
89
+ order.product_name !== FulfillProductNameCarMagnet5x5 ||
90
+ order.status === FulfillOrderStatusFailed)
91
+ return total;
92
+ return total + order.quantity;
93
+ }, 0);
94
+ return { used, remaining: Math.max(0, FulfillOrderQuantityLimit - used) };
20
95
  }
21
96
  async searchFulfillOrders(opts) {
22
97
  return await runOwnerSearch({
@@ -24,9 +99,10 @@ export class FulfillmentsFX {
24
99
  search: (searchOpts) => this.fulfillments.searchManyFulfillOrders(searchOpts),
25
100
  });
26
101
  }
27
- async findFulfillOrder(id) {
102
+ async findFulfillOrder(id, signal) {
28
103
  const out = await this.fulfillments.findOneFulfillOrder({
29
104
  id,
105
+ signal,
30
106
  });
31
107
  const fulfill_order = out.value;
32
108
  if (fulfill_order === undefined) {
@@ -13,6 +13,7 @@ export * from "./contacts/contacts.js";
13
13
  export * from "./contacts/scope.js";
14
14
  export * from "./core/address.js";
15
15
  export * from "./core/date.js";
16
+ export * from "./core/elapsed-time.js";
16
17
  export * from "./core/err.js";
17
18
  export * from "./core/events.js";
18
19
  export * from "./core/id.js";
package/dist/src/index.js CHANGED
@@ -13,6 +13,7 @@ export * from "./contacts/contacts.js";
13
13
  export * from "./contacts/scope.js";
14
14
  export * from "./core/address.js";
15
15
  export * from "./core/date.js";
16
+ export * from "./core/elapsed-time.js";
16
17
  export * from "./core/err.js";
17
18
  export * from "./core/events.js";
18
19
  export * from "./core/id.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabriktor/fx",
3
- "version": "0.0.201",
3
+ "version": "0.0.203",
4
4
  "description": "![Fabriktor Logo](./img/fabriktor-character.gif)",
5
5
  "type": "module",
6
6
  "exports": {
@@ -17,9 +17,9 @@
17
17
  "typescript": "^6.0.3"
18
18
  },
19
19
  "dependencies": {
20
- "@fabriktor/client": "0.0.121",
20
+ "@fabriktor/client": "0.0.122",
21
21
  "@fabriktor/fx": "0.0.94",
22
- "@fabriktor/schema": "0.0.91",
22
+ "@fabriktor/schema": "0.0.92",
23
23
  "convert": "8.0.2"
24
24
  }
25
25
  }