| 1 | package assist |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "strings" |
| 8 | "sync" |
| 9 | "time" |
| 10 | ) |
| 11 | |
| 12 | const ( |
| 13 | listTTL = 60 * time.Second |
| 14 | maxLookLines = 200 |
| 15 | maxDescription = 160 |
| 16 | unknownOperation = "unknown_operation" |
| 17 | ) |
| 18 | |
| 19 | type listing struct { |
| 20 | ops []Operation |
| 21 | at time.Time |
| 22 | } |
| 23 | |
| 24 | // Registry joins providers behind look, describe and invoke. |
| 25 | type Registry struct { |
| 26 | providers []Provider |
| 27 | now func() time.Time |
| 28 | |
| 29 | mu sync.Mutex |
| 30 | cache map[string]map[int]listing // person -> provider index -> list |
| 31 | gen map[string]uint64 // person -> times Forget has run |
| 32 | // unconnected is told when look showed a provider's hint |
| 33 | // (OnUnconnected). |
| 34 | unconnected func(ctx context.Context, person, provider string) bool |
| 35 | } |
| 36 | |
| 37 | // The end of a hint's line in look: the person has a card to connect |
| 38 | // the provider (the hook said so), or not. With one, Base draws its |
| 39 | // button at the end of the reply, so the model is told only what to say: |
| 40 | // in its own words, what connecting lets it do for them. It is told of |
| 41 | // no card or machinery, so it names none to the person. |
| 42 | const ( |
| 43 | hintCard = " The way to connect now shows right after your reply. Say in your own words, in a sentence, that once they connect their Oficina apps you can do what they asked, such as \"Connect your Oficina apps and I'll show you this week.\" Don't describe what they will see or how connecting works." |
| 44 | hintNoCard = " Tell them it needs connecting first." |
| 45 | ) |
| 46 | |
| 47 | // OnUnconnected sets what look tells when it shows a provider's hint: the |
| 48 | // person asked for something it does and has not connected it. f says |
| 49 | // whether the person now has a card to connect it; look tells the model |
| 50 | // only what f reports. |
| 51 | func (r *Registry) OnUnconnected(f func(ctx context.Context, person, provider string) bool) { |
| 52 | r.mu.Lock() |
| 53 | r.unconnected = f |
| 54 | r.mu.Unlock() |
| 55 | } |
| 56 | |
| 57 | // NewRegistry returns a registry over providers, listed in the order given. |
| 58 | func NewRegistry(providers ...Provider) *Registry { |
| 59 | return &Registry{providers: providers, now: time.Now, cache: map[string]map[int]listing{}, gen: map[string]uint64{}} |
| 60 | } |
| 61 | |
| 62 | // Forget drops the person's cached lists. |
| 63 | func (r *Registry) Forget(person string) { |
| 64 | r.mu.Lock() |
| 65 | delete(r.cache, person) |
| 66 | r.gen[person]++ |
| 67 | r.mu.Unlock() |
| 68 | } |
| 69 | |
| 70 | // list returns each provider's operations for the person, in provider order. |
| 71 | // A provider that fails is left out and its failure is not cached. |
| 72 | func (r *Registry) list(ctx context.Context, person string) [][]Operation { |
| 73 | out, _ := r.listing(ctx, person) |
| 74 | return out |
| 75 | } |
| 76 | |
| 77 | // listing is list with each provider's failure, by index. |
| 78 | func (r *Registry) listing(ctx context.Context, person string) ([][]Operation, []error) { |
| 79 | out, errs := make([][]Operation, len(r.providers)), make([]error, len(r.providers)) |
| 80 | filter := filterFrom(ctx) |
| 81 | for i, p := range r.providers { |
| 82 | if filter != nil && !filter.Provider(p.Name()) { |
| 83 | continue |
| 84 | } |
| 85 | r.mu.Lock() |
| 86 | l, ok := r.cache[person][i] |
| 87 | gen := r.gen[person] |
| 88 | r.mu.Unlock() |
| 89 | if ok && r.now().Sub(l.at) < listTTL { |
| 90 | out[i] = filtered(filter, l.ops) |
| 91 | continue |
| 92 | } |
| 93 | ops, err := p.List(ctx, person) |
| 94 | if err != nil { |
| 95 | errs[i] = err |
| 96 | continue |
| 97 | } |
| 98 | for j := range ops { |
| 99 | ops[j].Provider = p.Name() |
| 100 | } |
| 101 | r.mu.Lock() |
| 102 | // A Forget since the call started means this answer may be stale: |
| 103 | // its caller gets it, the cache does not. |
| 104 | if r.gen[person] == gen { |
| 105 | if r.cache[person] == nil { |
| 106 | r.cache[person] = map[int]listing{} |
| 107 | } |
| 108 | r.cache[person][i] = listing{ops: ops, at: r.now()} |
| 109 | } |
| 110 | r.mu.Unlock() |
| 111 | out[i] = filtered(filter, ops) |
| 112 | } |
| 113 | return out, errs |
| 114 | } |
| 115 | |
| 116 | // filtered is ops less those filter leaves out (all of them, with none). |
| 117 | func filtered(filter Filter, ops []Operation) []Operation { |
| 118 | if filter == nil { |
| 119 | return ops |
| 120 | } |
| 121 | var out []Operation |
| 122 | for _, op := range ops { |
| 123 | if filter.Operation(op) { |
| 124 | out = append(out, op) |
| 125 | } |
| 126 | } |
| 127 | return out |
| 128 | } |
| 129 | |
| 130 | // Look returns model-facing text: one header per app and one line per |
| 131 | // operation, filtered by query when there is one. A provider the person |
| 132 | // has not connected that has a hint for query (Hinter) shows it under |
| 133 | // its name, and OnUnconnected's hook hears of it. |
| 134 | func (r *Registry) Look(ctx context.Context, person, query string) (string, error) { |
| 135 | q := strings.ToLower(strings.TrimSpace(query)) |
| 136 | var b strings.Builder |
| 137 | n := 0 |
| 138 | lists, errs := r.listing(ctx, person) |
| 139 | for i, ops := range lists { |
| 140 | if text, ok := r.hint(i, errs[i], query); ok { |
| 141 | if b.Len() > 0 { |
| 142 | b.WriteByte('\n') |
| 143 | } |
| 144 | r.mu.Lock() |
| 145 | hook := r.unconnected |
| 146 | r.mu.Unlock() |
| 147 | end := hintNoCard |
| 148 | if hook != nil && hook(ctx, person, r.providers[i].Name()) { |
| 149 | end = hintCard |
| 150 | } |
| 151 | b.WriteString(r.providers[i].Name() + " (" + r.providers[i].Name() + ")\n" + text + end) |
| 152 | continue |
| 153 | } |
| 154 | var apps []string |
| 155 | byApp := map[string][]Operation{} |
| 156 | for _, op := range ops { |
| 157 | app := op.App |
| 158 | if app == "" { |
| 159 | app = r.providers[i].Name() |
| 160 | } |
| 161 | if q != "" && !strings.Contains(strings.ToLower(op.Name+"\n"+op.Description+"\n"+app), q) { |
| 162 | continue |
| 163 | } |
| 164 | if _, seen := byApp[app]; !seen { |
| 165 | apps = append(apps, app) |
| 166 | } |
| 167 | byApp[app] = append(byApp[app], op) |
| 168 | } |
| 169 | for _, app := range apps { |
| 170 | if n >= maxLookLines { |
| 171 | break |
| 172 | } |
| 173 | if b.Len() > 0 { |
| 174 | b.WriteByte('\n') |
| 175 | } |
| 176 | b.WriteString(app + " (" + r.providers[i].Name() + ")") |
| 177 | for _, op := range byApp[app] { |
| 178 | if n >= maxLookLines { |
| 179 | break |
| 180 | } |
| 181 | n++ |
| 182 | b.WriteString("\n- " + op.Name + ": " + firstLine(op.Description)) |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | if b.Len() == 0 { |
| 187 | return "No operations found.", nil |
| 188 | } |
| 189 | return b.String(), nil |
| 190 | } |
| 191 | |
| 192 | // hint is provider i's hint for query, when its list failed because the |
| 193 | // person has not connected it. |
| 194 | func (r *Registry) hint(i int, err error, query string) (string, bool) { |
| 195 | var f Failure |
| 196 | h, ok := r.providers[i].(Hinter) |
| 197 | if !ok || !errors.As(err, &f) || f.Code != "not_connected" { |
| 198 | return "", false |
| 199 | } |
| 200 | return h.Hint(query) |
| 201 | } |
| 202 | |
| 203 | func firstLine(s string) string { |
| 204 | s = strings.TrimSpace(s) |
| 205 | if i := strings.IndexByte(s, '\n'); i >= 0 { |
| 206 | s = strings.TrimSpace(s[:i]) |
| 207 | } |
| 208 | if r := []rune(s); len(r) > maxDescription { |
| 209 | s = string(r[:maxDescription]) |
| 210 | } |
| 211 | return s |
| 212 | } |
| 213 | |
| 214 | func (r *Registry) find(ctx context.Context, person, name string) (Operation, Provider, error) { |
| 215 | for i, ops := range r.list(ctx, person) { |
| 216 | for _, op := range ops { |
| 217 | if op.Name == name { |
| 218 | return op, r.providers[i], nil |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | return Operation{}, nil, Failure{Code: unknownOperation, Message: "No operation is called " + name + "."} |
| 223 | } |
| 224 | |
| 225 | // Describe returns the full operation, schemas included. |
| 226 | func (r *Registry) Describe(ctx context.Context, person, operation string) (Operation, error) { |
| 227 | op, _, err := r.find(ctx, person, operation) |
| 228 | return op, err |
| 229 | } |
| 230 | |
| 231 | // Invoke runs an operation if Decide allows it. For a write, key is the |
| 232 | // ledger key and must not be empty: the provider receives its UUIDv5, also placed in the input at |
| 233 | // the operation's KeyField. Reads are sent no key. |
| 234 | func (r *Registry) Invoke(ctx context.Context, person, operation string, input json.RawMessage, key string) (json.RawMessage, error) { |
| 235 | op, p, err := r.find(ctx, person, operation) |
| 236 | if err != nil { |
| 237 | return nil, err |
| 238 | } |
| 239 | if run, code := Decide(op); !run { |
| 240 | return nil, Failure{Code: code, Message: "This operation can't be run from here."} |
| 241 | } |
| 242 | sent := "" |
| 243 | if !op.ReadOnly { |
| 244 | if key == "" { |
| 245 | return nil, Failure{Code: "missing_key", Message: "A write needs a ledger key."} |
| 246 | } |
| 247 | sent = Key(key) |
| 248 | if op.KeyField != "" { |
| 249 | fields := map[string]json.RawMessage{} |
| 250 | if t := strings.TrimSpace(string(input)); t != "" && t != "null" { |
| 251 | if err := json.Unmarshal(input, &fields); err != nil { |
| 252 | return nil, Failure{Code: "invalid_input", Message: "The input must be a JSON object."} |
| 253 | } |
| 254 | } |
| 255 | kv, _ := json.Marshal(sent) |
| 256 | fields[op.KeyField] = kv |
| 257 | if input, err = json.Marshal(fields); err != nil { |
| 258 | return nil, err |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | // The gate checks the operation as resolved now, then the provider |
| 263 | // checks again right before its request. |
| 264 | ctx = withResolved(ctx, op) |
| 265 | if err := Gate(ctx, op); err != nil { |
| 266 | return nil, err |
| 267 | } |
| 268 | out, err := p.Invoke(ctx, person, operation, input, sent) |
| 269 | if err != nil { |
| 270 | return nil, err |
| 271 | } |
| 272 | if len(out) > MaxResult { |
| 273 | return nil, Failure{Code: "too_large", Message: "The result is too large to return."} |
| 274 | } |
| 275 | return out, nil |
| 276 | } |
| 277 | |