@fabriktor/fx 0.0.156 → 0.0.158

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.
@@ -7,6 +7,10 @@ export type QueueRetry = {
7
7
  attempts: number;
8
8
  after: number;
9
9
  };
10
+ export declare class MutationQueue {
11
+ private pending;
12
+ run<T>(signal: AbortSignal, fn: (signal: AbortSignal) => Promise<T>): Promise<T>;
13
+ }
10
14
  export declare function nextQueueRetry(previous?: QueueRetry): QueueRetry;
11
15
  export declare class QueueWakeup {
12
16
  private pending?;
@@ -5,6 +5,20 @@
5
5
  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
6
  const queueRetryInitialMilliseconds = 1_000;
7
7
  const queueRetryMaximumMilliseconds = 30_000;
8
+ // In-memory mutations stay sequential while unrelated UI remains interactive.
9
+ export class MutationQueue {
10
+ pending = Promise.resolve();
11
+ run(signal, fn) {
12
+ const result = this.pending.then(async () => {
13
+ signal.throwIfAborted();
14
+ const value = await fn(signal);
15
+ signal.throwIfAborted();
16
+ return value;
17
+ });
18
+ this.pending = result.catch(() => undefined);
19
+ return result;
20
+ }
21
+ }
8
22
  // Durable deadlines prevent refreshes and other tabs from bypassing backoff.
9
23
  export function nextQueueRetry(previous) {
10
24
  const attempts = (previous?.attempts ?? 0) + 1;
@@ -160,7 +160,7 @@ export type CreateFeedPostWithMediaResult = {
160
160
  status: typeof FeedMediaPostStatus.PatchFailed;
161
161
  post_id: string;
162
162
  upload: StoragePersonalBoxUploadResult;
163
- objects: FeedObject[];
163
+ objects: FeedPostInsert["objects"];
164
164
  error: unknown;
165
165
  };
166
166
  export interface FeedFXOperator {
@@ -200,7 +200,7 @@ export interface FeedFXOperator {
200
200
  export declare class FeedFX implements FeedFXOperator {
201
201
  private readonly sessions;
202
202
  private readonly events;
203
- private mutating;
203
+ private readonly mutations;
204
204
  private feed;
205
205
  private storage_fx;
206
206
  private keep_alive_interval_ms;
@@ -7,6 +7,7 @@ import { All, PullTypeBatch, PullTypeSingle, PullTypeResearch, PullTypeReplies,
7
7
  import { isClientErr, queryParams, } from "@fabriktor/client";
8
8
  import { errResolveFailed, errValidation, errUnconfirmedMutation, } from "../core/err.js";
9
9
  import { requiredOperationID, resolvedID } from "../core/id.js";
10
+ import { MutationQueue } from "../core/queue.js";
10
11
  import { startPullSession, PullSessionScope, } from "../core/pull.js";
11
12
  import { runOwnerSearch, } from "../core/search.js";
12
13
  import { validateStorageUploadFiles, } from "../storage/storage.js";
@@ -32,7 +33,6 @@ const msgCreatedFeedReactionIDMissing = "Created feed reaction response did not
32
33
  const msgFeedReactionResolveMissing = "Feed reaction could not be resolved after the mutation.";
33
34
  const msgCreatedFeedFavoriteIDMissing = "Created feed favorite response did not contain an ID.";
34
35
  const msgFeedFavoriteResolveMissing = "Feed favorite could not be resolved after the mutation.";
35
- const msgFeedActionInProgress = "This feed action is already in progress for the post.";
36
36
  const msgFeedReactionAlreadyExists = "A reaction already exists for this post.";
37
37
  const msgFeedReactionMissing = "No reaction exists for this post.";
38
38
  const msgFeedFavoriteAlreadyExists = "A favorite already exists for this post.";
@@ -59,7 +59,7 @@ export const FeedMediaPostStatus = {
59
59
  export class FeedFX {
60
60
  sessions = new PullSessionScope();
61
61
  events;
62
- mutating = false;
62
+ mutations = new MutationQueue();
63
63
  feed;
64
64
  storage_fx;
65
65
  keep_alive_interval_ms;
@@ -280,19 +280,9 @@ export class FeedFX {
280
280
  this.events.publish(FeedEvents.Changed, { post_id });
281
281
  }
282
282
  async mutate(fn, parent) {
283
- if (this.mutating)
284
- throw errValidation({ msg: msgFeedActionInProgress });
285
283
  const signal = this.sessions.signal(parent);
286
284
  signal.throwIfAborted();
287
- this.mutating = true;
288
- try {
289
- const result = await fn(signal);
290
- signal.throwIfAborted();
291
- return result;
292
- }
293
- finally {
294
- this.mutating = false;
295
- }
285
+ return this.mutations.run(signal, fn);
296
286
  }
297
287
  async createFeedReaction(opts) {
298
288
  const out = await this.feed.insertOneFeedReaction(opts);
@@ -1,5 +1,5 @@
1
1
  import { type FeedOperator, type StorageUploadFile } from "@fabriktor/client";
2
- import { type FeedPost, type InFeedPost, type FeedObject, type Object as StorageObject } from "@fabriktor/schema";
2
+ import { type FeedPost, type InFeedPost, type Object as StorageObject } from "@fabriktor/schema";
3
3
  import type { MultiCreateAttempt } from "../core/multi-create.js";
4
4
  import { type StorageFXOperator, type StoragePersonalBoxUploadResult, type StorageUploadResult } from "../storage/storage.js";
5
5
  export type FeedPostDraft = {
@@ -22,9 +22,7 @@ export type FeedPostSaveState = {
22
22
  baseline?: StorageObject[];
23
23
  primary?: StorageUploadResult;
24
24
  upload?: StoragePersonalBoxUploadResult;
25
- input?: InFeedPost & {
26
- objects: FeedObject[];
27
- };
25
+ input?: InFeedPost;
28
26
  patch_attempted?: boolean;
29
27
  patched?: boolean;
30
28
  rejected?: boolean;
@@ -49,5 +47,5 @@ type SaveDependencies = {
49
47
  changed: (id: string) => void;
50
48
  };
51
49
  export declare function saveFeedPost(deps: SaveDependencies, opts: SaveFeedPostOptions): Promise<FeedPostSaveResult>;
52
- export declare function feedObjects(objects: StorageObject[]): FeedObject[];
50
+ export declare function feedObjects(objects: StorageObject[]): InFeedPost["objects"];
53
51
  export {};
@@ -9,7 +9,7 @@ import { errResolveFailed, errValidation, errUnconfirmedMutation, } from "../cor
9
9
  import { notifyObserver } from "../core/events.js";
10
10
  import { requiredOperationID, resolvedID } from "../core/id.js";
11
11
  import { validateStorageUploadFiles, } from "../storage/storage.js";
12
- import { feedPostInput, validateFeedVisibility, checkFeedPostVersion, } from "./validation.js";
12
+ import { feedPostInput, feedObjectInput, validateFeedVisibility, checkFeedPostVersion, } from "./validation.js";
13
13
  export function newFeedPostSaveState() {
14
14
  return {
15
15
  create_key: newIdempotencyKey(),
@@ -157,7 +157,7 @@ export async function saveFeedPost(deps, opts) {
157
157
  const current = await own(id);
158
158
  checkFeedPostVersion(current, original);
159
159
  const base = feedPostInput(original);
160
- const retained = original.objects.filter((object) => draft.retained_urls.includes(object.public_url));
160
+ const retained = base.objects.filter((object) => draft.retained_urls.includes(object.public_url));
161
161
  let attachments = retained;
162
162
  if (draft.retained_urls.some((url) => !original.objects.some((object) => object.public_url === url)))
163
163
  throw errValidation({
@@ -325,22 +325,21 @@ export function feedObjects(objects) {
325
325
  });
326
326
  return objects.map((object) => {
327
327
  const embedding = object.caption;
328
- if (!object.public_url?.trim() ||
329
- !object.mime_prefix ||
330
- !embedding?.plot_embedding?.length ||
331
- embedding.dim !== embedding.plot_embedding.length ||
332
- !embedding.plot_embedding.every(Number.isFinite))
328
+ if (!object.public_url?.trim() || !object.mime_prefix?.trim())
333
329
  throw errResolveFailed({
334
330
  resource: "feed_object",
335
- msg: "Storage did not return a public URL and complete caption embedding.",
331
+ msg: "Storage did not return a public URL and media type.",
336
332
  });
337
- return {
333
+ if (!embedding?.text?.trim())
334
+ throw errResolveFailed({
335
+ resource: "feed_object",
336
+ msg: "Storage did not return caption text for this media.",
337
+ });
338
+ // Generated Feed inputs contain caption content; Feed computes its vector.
339
+ return feedObjectInput({
338
340
  public_url: object.public_url,
339
341
  mime_prefix: object.mime_prefix,
340
- embedding: {
341
- ...embedding,
342
- plot_embedding: [...embedding.plot_embedding],
343
- },
344
- };
342
+ embedding,
343
+ });
345
344
  });
346
345
  }
@@ -2,4 +2,5 @@ import { type FeedPost, type InFeedPost } from "@fabriktor/schema";
2
2
  export declare function checkFeedPostVersion(current: FeedPost, expected?: Pick<FeedPost, "owner_id" | "updated_at">): void;
3
3
  export declare function validateFeedVisibility(value: number): void;
4
4
  export declare function feedPostInput(post: FeedPost): InFeedPost;
5
+ export declare function feedObjectInput(object: InFeedPost["objects"][number]): InFeedPost["objects"][number];
5
6
  export declare function prepareFeedTextPost(input: InFeedPost): InFeedPost;
@@ -32,14 +32,7 @@ export function validateFeedVisibility(value) {
32
32
  export function feedPostInput(post) {
33
33
  return {
34
34
  text: { text: post.text.text, file: "", file_url: "", mime: "" },
35
- objects: post.objects.map((object) => ({
36
- public_url: object.public_url,
37
- mime_prefix: object.mime_prefix,
38
- embedding: {
39
- ...object.embedding,
40
- plot_embedding: [...object.embedding.plot_embedding],
41
- },
42
- })),
35
+ objects: post.objects.map(feedObjectInput),
43
36
  is_uploading: post.is_uploading,
44
37
  has_media: post.has_media,
45
38
  visibility: post.visibility,
@@ -47,6 +40,18 @@ export function feedPostInput(post) {
47
40
  reply_to_post_id: post.reply_to_post_id,
48
41
  };
49
42
  }
43
+ export function feedObjectInput(object) {
44
+ return {
45
+ public_url: object.public_url,
46
+ mime_prefix: object.mime_prefix,
47
+ embedding: {
48
+ text: object.embedding.text ?? "",
49
+ file: object.embedding.file ?? "",
50
+ file_url: object.embedding.file_url ?? "",
51
+ mime: object.embedding.mime ?? "",
52
+ },
53
+ };
54
+ }
50
55
  // Text publishing uses generated inputs; media creation has its own storage workflow.
51
56
  export function prepareFeedTextPost(input) {
52
57
  validateFeedVisibility(input.visibility);
@@ -38,6 +38,7 @@ export type MarketplaceFavoriteOptions = {
38
38
  export type SetMarketplaceFavoriteOptions = MarketplaceFavoriteOptions & {
39
39
  post_id: string;
40
40
  saved: boolean;
41
+ on_confirmed?: () => void;
41
42
  };
42
43
  export type SearchMarketplacePostsPage = SearchPage<MarketplacePost>;
43
44
  export type MarketplacePullContext = Pick<MarketplacePullOptions, "pull_type" | "entity_id" | "research" | "research_user_type">;
@@ -86,7 +87,7 @@ export interface MarketplaceFXOperator {
86
87
  export declare class MarketplaceFX implements MarketplaceFXOperator {
87
88
  private readonly sessions;
88
89
  private readonly events;
89
- private mutating;
90
+ private readonly mutations;
90
91
  private marketplace;
91
92
  private keep_alive_interval_ms;
92
93
  constructor(opts: MarketplaceFXOptions);
@@ -7,6 +7,7 @@ import { isClientErr, queryParams, } from "@fabriktor/client";
7
7
  import { PullTypeBatch, PullTypeKeepAlive, PullTypeResearch, PullTypeSingle, OwnerIDKey, } from "@fabriktor/schema";
8
8
  import { errRequired, errResolveFailed, errValidation, errUnconfirmedMutation, } from "../core/err.js";
9
9
  import { requiredOperationID, resolvedID } from "../core/id.js";
10
+ import { MutationQueue } from "../core/queue.js";
10
11
  import { startPullSession, PullSessionScope, } from "../core/pull.js";
11
12
  import { runOwnerSearch, } from "../core/search.js";
12
13
  import { createEvent, EventBus, notifyObserver } from "../core/events.js";
@@ -34,7 +35,7 @@ const msgMarketplaceCountryRequired = "Country is required for marketplace welco
34
35
  export class MarketplaceFX {
35
36
  sessions = new PullSessionScope();
36
37
  events;
37
- mutating = false;
38
+ mutations = new MutationQueue();
38
39
  marketplace;
39
40
  keep_alive_interval_ms;
40
41
  constructor(opts) {
@@ -269,8 +270,10 @@ export class MarketplaceFX {
269
270
  return await this.mutate(async (signal) => {
270
271
  const existing = await this.listMarketplaceFavorites({ ...opts, signal });
271
272
  if (opts.saved) {
272
- if (existing.length)
273
+ if (existing.length) {
274
+ notifyObserver(() => opts.on_confirmed?.());
273
275
  return existing[0];
276
+ }
274
277
  if (!(await this.readMarketplacePost({ id: opts.post_id, signal }))) {
275
278
  throw errResolveFailed({
276
279
  resource: resourceMarketplacePost,
@@ -282,6 +285,8 @@ export class MarketplaceFX {
282
285
  signal,
283
286
  });
284
287
  signal.throwIfAborted();
288
+ // The write is acknowledged even if resolving its document later fails.
289
+ notifyObserver(() => opts.on_confirmed?.());
285
290
  const id = requiredOperationID(out, msgCreatedMarketplaceFavoriteIDMissing);
286
291
  const found = await this.marketplace.findOneMarketplaceFavorite({
287
292
  id,
@@ -304,6 +309,7 @@ export class MarketplaceFX {
304
309
  });
305
310
  }
306
311
  signal.throwIfAborted();
312
+ notifyObserver(() => opts.on_confirmed?.());
307
313
  this.changed(opts.owner_id, "favorites", opts.post_id);
308
314
  return null;
309
315
  }, opts.signal);
@@ -329,21 +335,9 @@ export class MarketplaceFX {
329
335
  });
330
336
  }
331
337
  async mutate(fn, parent) {
332
- if (this.mutating)
333
- throw errValidation({
334
- msg: "A Marketplace action is already in progress.",
335
- });
336
338
  const signal = this.sessions.signal(parent);
337
339
  signal.throwIfAborted();
338
- this.mutating = true;
339
- try {
340
- const result = await fn(signal);
341
- signal.throwIfAborted();
342
- return result;
343
- }
344
- finally {
345
- this.mutating = false;
346
- }
340
+ return this.mutations.run(signal, fn);
347
341
  }
348
342
  requireID(value) {
349
343
  const id = resolvedID(value);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabriktor/fx",
3
- "version": "0.0.156",
3
+ "version": "0.0.158",
4
4
  "description": "![Fabriktor Logo](./img/fabriktor-character.gif)",
5
5
  "type": "module",
6
6
  "exports": {