@pikku/mongodb 0.12.9 → 0.12.11

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 CHANGED
@@ -1,5 +1,79 @@
1
1
  # @pikku/mongodb
2
2
 
3
+ ## 0.12.11
4
+
5
+ ### Patch Changes
6
+
7
+ - e3d4454: Add job groups, so one shared queue can stay fair without splitting into one
8
+ queue per producer.
9
+
10
+ A job may now carry `group: { id, tier }`, and a worker may cap how many jobs
11
+ of any one group run at once via `groupConcurrency`. On pg-boss this maps to
12
+ `localGroupConcurrency`, which excludes at-capacity groups from the fetch query
13
+ itself, so a capped group costs nothing rather than being fetched and restored.
14
+ BullMQ declares it unsupported (groups are a BullMQ Pro feature) — being
15
+ push-based, it can simply use a queue per group at no polling cost.
16
+
17
+ Workflow services accept a `queueStrategy`. The default `'per-workflow'` is
18
+ unchanged: every workflow gets its own `wf-orchestrator-*` / `wf-step-*` queue,
19
+ which is also what lets serverless providers deploy one unit per workflow. The
20
+ new `'shared-groups'` routes every workflow through the shared
21
+ orchestrator/step-worker queues and isolates them by group instead, so a
22
+ monolith runs one set of pollers rather than one per workflow — on a
23
+ pull-based backend with dozens of workflows that is the difference between
24
+ hundreds of poll loops and twenty. It is for single-process runtimes only; a
25
+ per-unit serverless deploy still needs the per-workflow queues to route to its
26
+ units.
27
+
28
+ - Updated dependencies [24252b8]
29
+ - Updated dependencies [e3d4454]
30
+ - @pikku/core@0.12.69
31
+
32
+ ## 0.12.10
33
+
34
+ ### Patch Changes
35
+
36
+ - 4324652: Scope AI agent thread reads to the calling session.
37
+
38
+ The generated thread-management functions (`getAgentThreads`,
39
+ `getAgentThreadMessages`, `getAgentThreadRuns`, `deleteAgentThread`) keyed purely
40
+ off a caller-supplied `threadId` and treated `resourceId` as an optional filter,
41
+ so omitting it enumerated every tenant's threads.
42
+ - `listThreads` gains an `owners` **authorization constraint** (distinct from the
43
+ `resourceId` filter): an empty array matches nothing, and it is always derived
44
+ from the session, never from input. Implemented across the Kysely, Redis and
45
+ MongoDB agent run services, with LIKE/regex metacharacter escaping so an owner
46
+ id containing `_` or `%` cannot match a foreign owner.
47
+ - The three `threadId`-keyed functions are now guarded by an `isThreadOwner`
48
+ `pikkuPermission` rather than an in-body check. A thread that does not exist is
49
+ denied rather than 404'd, so it is indistinguishable from one owned by someone
50
+ else.
51
+ - New `@pikku/core/ai-agent` helpers: `canAccessThread`, `threadOwnerConstraint`,
52
+ `sessionPrincipals`, `isOwnedByPrincipal`.
53
+
54
+ Services destructured by a wired function are now non-optional inside it.
55
+
56
+ The inspector already aggregated the services used by every wired `func`,
57
+ `permissions` and `middleware` into `RequiredSingletonServices`, but the
58
+ generated function types defaulted their service parameter to the raw `Services`
59
+ — so a service declared `foo?: Foo` still arrived as possibly-undefined, forcing
60
+ `if (!foo) throw new MissingServiceError(...)` guards that could never fire.
61
+ Generated types now expose `WiredSingletonServices` / `WiredServices`
62
+ (`RequiredSingletonServices & Services`) and default the `RequiredServices`
63
+ generic of functions, permissions, middleware, auth and approval-description
64
+ helpers to them. Optionality now means only what it should: "this service may
65
+ not be created, because nothing uses it".
66
+
67
+ - Updated dependencies [5f19016]
68
+ - Updated dependencies [78e4778]
69
+ - Updated dependencies [4324652]
70
+ - Updated dependencies [de044f8]
71
+ - Updated dependencies [cd1a811]
72
+ - Updated dependencies [19fa6f0]
73
+ - Updated dependencies [b501612]
74
+ - Updated dependencies [eb37b1e]
75
+ - @pikku/core@0.12.66
76
+
3
77
  ## 0.12.9
4
78
 
5
79
  ### Patch Changes
@@ -9,6 +9,7 @@ export declare class MongoDBAgentRunService implements AgentRunService {
9
9
  listThreads(options?: {
10
10
  agentName?: string;
11
11
  resourceId?: string;
12
+ owners?: string[];
12
13
  limit?: number;
13
14
  offset?: number;
14
15
  }): Promise<AIThread[]>;
@@ -1,3 +1,6 @@
1
+ // Owner ids are untrusted input to the regex, so metacharacters must not be
2
+ // able to widen the prefix match.
3
+ const escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1
4
  export class MongoDBAgentRunService {
2
5
  threads;
3
6
  messages;
@@ -10,11 +13,21 @@ export class MongoDBAgentRunService {
10
13
  this.runs = db.collection('ai_run');
11
14
  }
12
15
  async listThreads(options) {
13
- const { agentName, resourceId, limit = 50, offset = 0 } = options ?? {};
16
+ const { agentName, resourceId, owners, limit = 50, offset = 0, } = options ?? {};
17
+ // An owners constraint is an authorization boundary, so an empty list must
18
+ // match nothing rather than degrade to "no filter".
19
+ if (owners && owners.length === 0)
20
+ return [];
14
21
  let filter = {};
15
22
  if (resourceId) {
16
23
  filter.resourceId = resourceId;
17
24
  }
25
+ if (owners) {
26
+ filter.$or = owners.flatMap((owner) => [
27
+ { resourceId: owner },
28
+ { resourceId: { $regex: `^${escapeRegExp(owner)}:` } },
29
+ ]);
30
+ }
18
31
  if (agentName) {
19
32
  const threadIds = await this.runs.distinct('threadId', {
20
33
  agentName,
@@ -1,5 +1,5 @@
1
1
  import type { SerializedError } from '@pikku/core';
2
- import { PikkuWorkflowService, type WorkflowPlannedStep, type WorkflowRun, type WorkflowRunWire, type StepState, type StepStatus, type WorkflowStatus, type WorkflowVersionStatus } from '@pikku/core/workflow';
2
+ import { PikkuWorkflowService, type WorkflowPlannedStep, type WorkflowQueueOptions, type WorkflowRun, type WorkflowRunWire, type StepState, type StepStatus, type WorkflowStatus, type WorkflowVersionStatus } from '@pikku/core/workflow';
3
3
  import type { Db } from 'mongodb';
4
4
  export declare class MongoDBWorkflowService extends PikkuWorkflowService {
5
5
  private initialized;
@@ -8,7 +8,7 @@ export declare class MongoDBWorkflowService extends PikkuWorkflowService {
8
8
  private steps;
9
9
  private stepHistory;
10
10
  private versions;
11
- constructor(db: Db);
11
+ constructor(db: Db, options?: WorkflowQueueOptions);
12
12
  init(): Promise<void>;
13
13
  protected createRunImpl(workflowName: string, input: any, inline: boolean, graphHash: string, wire: WorkflowRunWire, options?: {
14
14
  deterministic?: boolean;
@@ -7,8 +7,8 @@ export class MongoDBWorkflowService extends PikkuWorkflowService {
7
7
  steps;
8
8
  stepHistory;
9
9
  versions;
10
- constructor(db) {
11
- super();
10
+ constructor(db, options = {}) {
11
+ super(options);
12
12
  this.runService = new MongoDBWorkflowRunService(db);
13
13
  this.runs = db.collection('workflow_runs');
14
14
  this.steps = db.collection('workflow_step');
@@ -216,13 +216,7 @@ export class MongoDBWorkflowService extends PikkuWorkflowService {
216
216
  .limit(1)
217
217
  .toArray();
218
218
  if (latestHistory.length > 0) {
219
- await this.stepHistory.updateOne({ _id: latestHistory[0]._id }, {
220
- $set: {
221
- status: 'failed',
222
- error: serializedError,
223
- failedAt: new Date(),
224
- },
225
- });
219
+ await this.stepHistory.updateOne({ _id: latestHistory[0]._id }, { $set: { status: 'failed', error: serializedError, failedAt: new Date() } });
226
220
  }
227
221
  }
228
222
  async createRetryAttemptImpl(stepId, status) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pikku/mongodb",
3
- "version": "0.12.9",
3
+ "version": "0.12.11",
4
4
  "author": "yasser.fadl@gmail.com",
5
5
  "license": "MIT",
6
6
  "module": "dist/src/index.js",
@@ -17,7 +17,7 @@
17
17
  "prepublishOnly": "yarn build"
18
18
  },
19
19
  "peerDependencies": {
20
- "@pikku/core": "^0.12.44"
20
+ "@pikku/core": "^0.12.69"
21
21
  },
22
22
  "dependencies": {
23
23
  "mongodb": "^6.12.0"
package/run-tests.sh CHANGED
@@ -38,16 +38,16 @@ if [ ${#files[@]} -eq 0 ]; then
38
38
  fi
39
39
 
40
40
  # Construct the node command
41
- node_cmd="node --import tsx --test"
41
+ node_cmd=(node --import tsx --test)
42
42
 
43
43
  # Append options based on flags
44
44
  if [ "$watch_mode" = true ]; then
45
- node_cmd="$node_cmd --watch"
45
+ node_cmd+=(--watch)
46
46
  fi
47
47
 
48
48
  if [ "$coverage_mode" = true ]; then
49
- node_cmd="$node_cmd --test-coverage-include=\"src/**/*.{ts,js}\" --test-coverage-exclude=\"**/dist/**\" --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info"
49
+ node_cmd+=(--test-coverage-include="src/**/*.{ts,js}" --test-coverage-exclude="**/dist/**" --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=lcov.info)
50
50
  fi
51
51
 
52
52
  # Execute the node command with the expanded list of files
53
- $node_cmd "${files[@]}"
53
+ "${node_cmd[@]}" "${files[@]}"
@@ -6,6 +6,11 @@ import type {
6
6
  } from '@pikku/core/ai-agent'
7
7
  import type { Db, Collection } from 'mongodb'
8
8
 
9
+ // Owner ids are untrusted input to the regex, so metacharacters must not be
10
+ // able to widen the prefix match.
11
+ const escapeRegExp = (value: string) =>
12
+ value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
13
+
9
14
  interface AIThreadDoc {
10
15
  _id: string
11
16
  resourceId: string
@@ -71,10 +76,21 @@ export class MongoDBAgentRunService implements AgentRunService {
71
76
  async listThreads(options?: {
72
77
  agentName?: string
73
78
  resourceId?: string
79
+ owners?: string[]
74
80
  limit?: number
75
81
  offset?: number
76
82
  }): Promise<AIThread[]> {
77
- const { agentName, resourceId, limit = 50, offset = 0 } = options ?? {}
83
+ const {
84
+ agentName,
85
+ resourceId,
86
+ owners,
87
+ limit = 50,
88
+ offset = 0,
89
+ } = options ?? {}
90
+
91
+ // An owners constraint is an authorization boundary, so an empty list must
92
+ // match nothing rather than degrade to "no filter".
93
+ if (owners && owners.length === 0) return []
78
94
 
79
95
  let filter: Record<string, any> = {}
80
96
 
@@ -82,6 +98,13 @@ export class MongoDBAgentRunService implements AgentRunService {
82
98
  filter.resourceId = resourceId
83
99
  }
84
100
 
101
+ if (owners) {
102
+ filter.$or = owners.flatMap((owner) => [
103
+ { resourceId: owner },
104
+ { resourceId: { $regex: `^${escapeRegExp(owner)}:` } },
105
+ ])
106
+ }
107
+
85
108
  if (agentName) {
86
109
  const threadIds = await this.runs.distinct('threadId', {
87
110
  agentName,
@@ -2,6 +2,7 @@ import type { SerializedError } from '@pikku/core'
2
2
  import {
3
3
  PikkuWorkflowService,
4
4
  type WorkflowPlannedStep,
5
+ type WorkflowQueueOptions,
5
6
  type WorkflowRun,
6
7
  type WorkflowRunWire,
7
8
  type StepState,
@@ -77,8 +78,8 @@ export class MongoDBWorkflowService extends PikkuWorkflowService {
77
78
  private stepHistory: Collection<WorkflowStepHistoryDoc>
78
79
  private versions: Collection<WorkflowVersionDoc>
79
80
 
80
- constructor(db: Db) {
81
- super()
81
+ constructor(db: Db, options: WorkflowQueueOptions = {}) {
82
+ super(options)
82
83
  this.runService = new MongoDBWorkflowRunService(db)
83
84
  this.runs = db.collection<WorkflowRunDoc>('workflow_runs')
84
85
  this.steps = db.collection<WorkflowStepDoc>('workflow_step')